1 /* $NetBSD: async_test.c,v 1.2 2025/01/26 16:25:49 christos Exp $ */ 2 3 /* 4 * Copyright (C) Internet Systems Consortium, Inc. ("ISC") 5 * 6 * SPDX-License-Identifier: MPL-2.0 7 * 8 * This Source Code Form is subject to the terms of the Mozilla Public 9 * License, v. 2.0. If a copy of the MPL was not distributed with this 10 * file, you can obtain one at https://mozilla.org/MPL/2.0/. 11 * 12 * See the COPYRIGHT file distributed with this work for additional 13 * information regarding copyright ownership. 14 */ 15 16 #include <inttypes.h> 17 #include <sched.h> /* IWYU pragma: keep */ 18 #include <setjmp.h> 19 #include <stdarg.h> 20 #include <stddef.h> 21 #include <stdlib.h> 22 #include <string.h> 23 #include <sys/types.h> 24 #include <unistd.h> 25 26 #define UNIT_TESTING 27 #include <cmocka.h> 28 29 #include <isc/async.h> 30 #include <isc/atomic.h> 31 #include <isc/loop.h> 32 #include <isc/os.h> 33 #include <isc/result.h> 34 #include <isc/tid.h> 35 #include <isc/util.h> 36 37 #include "async.c" 38 39 #include <tests/isc.h> 40 41 static atomic_uint scheduled = 0; 42 43 static void 44 async_cb(void *arg) { 45 uint32_t tid = isc_tid(); 46 47 UNUSED(arg); 48 49 atomic_fetch_add(&scheduled, 1); 50 51 if (tid > 0) { 52 isc_loop_t *loop = isc_loop_get(loopmgr, tid - 1); 53 isc_async_run(loop, async_cb, loopmgr); 54 } else { 55 isc_loopmgr_shutdown(loopmgr); 56 } 57 } 58 59 static void 60 async_setup_cb(void *arg) { 61 uint32_t tid = isc_loopmgr_nloops(loopmgr) - 1; 62 isc_loop_t *loop = isc_loop_get(loopmgr, tid); 63 64 UNUSED(arg); 65 66 isc_async_run(loop, async_cb, loopmgr); 67 } 68 69 ISC_RUN_TEST_IMPL(isc_async_run) { 70 isc_loop_setup(isc_loop_main(loopmgr), async_setup_cb, loopmgr); 71 isc_loopmgr_run(loopmgr); 72 assert_int_equal(atomic_load(&scheduled), loopmgr->nloops); 73 } 74 75 static char string[32] = ""; 76 int n1 = 1, n2 = 2, n3 = 3, n4 = 4, n5 = 5; 77 78 static void 79 append(void *arg) { 80 char value[32]; 81 sprintf(value, "%d", *(int *)arg); 82 strlcat(string, value, 10); 83 } 84 85 static void 86 async_multiple(void *arg) { 87 isc_loop_t *loop = isc_loop(); 88 89 UNUSED(arg); 90 91 isc_async_run(loop, append, &n1); 92 isc_async_run(loop, append, &n2); 93 isc_async_run(loop, append, &n3); 94 isc_async_run(loop, append, &n4); 95 isc_async_run(loop, append, &n5); 96 isc_loopmgr_shutdown(loopmgr); 97 } 98 99 ISC_RUN_TEST_IMPL(isc_async_multiple) { 100 string[0] = '\0'; 101 isc_loop_setup(isc_loop_main(loopmgr), async_multiple, loopmgr); 102 isc_loopmgr_run(loopmgr); 103 assert_string_equal(string, "12345"); 104 } 105 106 ISC_TEST_LIST_START 107 ISC_TEST_ENTRY_CUSTOM(isc_async_run, setup_loopmgr, teardown_loopmgr) 108 ISC_TEST_ENTRY_CUSTOM(isc_async_multiple, setup_loopmgr, teardown_loopmgr) 109 ISC_TEST_LIST_END 110 111 ISC_TEST_MAIN 112