runner.odin 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  1. //+private
  2. package testing
  3. /*
  4. (c) Copyright 2024 Feoramund <[email protected]>.
  5. Made available under Odin's BSD-3 license.
  6. List of contributors:
  7. Ginger Bill: Initial implementation.
  8. Feoramund: Total rewrite.
  9. */
  10. import "base:intrinsics"
  11. import "base:runtime"
  12. import "core:bytes"
  13. import "core:encoding/ansi"
  14. @require import "core:encoding/base64"
  15. @require import "core:encoding/json"
  16. import "core:fmt"
  17. import "core:io"
  18. @require import "core:log"
  19. import "core:math/rand"
  20. import "core:mem"
  21. import "core:os"
  22. import "core:slice"
  23. @require import "core:strings"
  24. import "core:sync/chan"
  25. import "core:thread"
  26. import "core:time"
  27. // Specify how many threads to use when running tests.
  28. TEST_THREADS : int : #config(ODIN_TEST_THREADS, 0)
  29. // Track the memory used by each test.
  30. TRACKING_MEMORY : bool : #config(ODIN_TEST_TRACK_MEMORY, true)
  31. // Always report how much memory is used, even when there are no leaks or bad frees.
  32. ALWAYS_REPORT_MEMORY : bool : #config(ODIN_TEST_ALWAYS_REPORT_MEMORY, false)
  33. // Treat memory leaks and bad frees as errors.
  34. FAIL_ON_BAD_MEMORY : bool : #config(ODIN_TEST_FAIL_ON_BAD_MEMORY, false)
  35. // Specify how much memory each thread allocator starts with.
  36. PER_THREAD_MEMORY : int : #config(ODIN_TEST_THREAD_MEMORY, mem.ROLLBACK_STACK_DEFAULT_BLOCK_SIZE)
  37. // Select a specific set of tests to run by name.
  38. // Each test is separated by a comma and may optionally include the package name.
  39. // This may be useful when running tests on multiple packages with `-all-packages`.
  40. // The format is: `package.test_name,test_name_only,...`
  41. TEST_NAMES : string : #config(ODIN_TEST_NAMES, "")
  42. // Show the fancy animated progress report.
  43. FANCY_OUTPUT : bool : #config(ODIN_TEST_FANCY, true)
  44. // Copy failed tests to the clipboard when done.
  45. USE_CLIPBOARD : bool : #config(ODIN_TEST_CLIPBOARD, false)
  46. // How many test results to show at a time per package.
  47. PROGRESS_WIDTH : int : #config(ODIN_TEST_PROGRESS_WIDTH, 24)
  48. // This is the random seed that will be sent to each test.
  49. // If it is unspecified, it will be set to the system cycle counter at startup.
  50. SHARED_RANDOM_SEED : u64 : #config(ODIN_TEST_RANDOM_SEED, 0)
  51. // Set the lowest log level for this test run.
  52. LOG_LEVEL_DEFAULT : string : "debug" when ODIN_DEBUG else "info"
  53. LOG_LEVEL : string : #config(ODIN_TEST_LOG_LEVEL, LOG_LEVEL_DEFAULT)
  54. // Show only the most necessary logging information.
  55. USING_SHORT_LOGS : bool : #config(ODIN_TEST_SHORT_LOGS, false)
  56. // Output a report of the tests to the given path.
  57. JSON_REPORT : string : #config(ODIN_TEST_JSON_REPORT, "")
  58. get_log_level :: #force_inline proc() -> runtime.Logger_Level {
  59. when LOG_LEVEL == "debug" { return .Debug } else
  60. when LOG_LEVEL == "info" { return .Info } else
  61. when LOG_LEVEL == "warning" { return .Warning } else
  62. when LOG_LEVEL == "error" { return .Error } else
  63. when LOG_LEVEL == "fatal" { return .Fatal } else {
  64. #panic("Unknown `ODIN_TEST_LOG_LEVEL`: \"" + LOG_LEVEL + "\", possible levels are: \"debug\", \"info\", \"warning\", \"error\", or \"fatal\".")
  65. }
  66. }
  67. JSON :: struct {
  68. total: int,
  69. success: int,
  70. duration: time.Duration,
  71. packages: map[string][dynamic]JSON_Test,
  72. }
  73. JSON_Test :: struct {
  74. success: bool,
  75. name: string,
  76. }
  77. end_t :: proc(t: ^T) {
  78. for i := len(t.cleanups)-1; i >= 0; i -= 1 {
  79. #no_bounds_check c := t.cleanups[i]
  80. context = c.ctx
  81. c.procedure(c.user_data)
  82. }
  83. delete(t.cleanups)
  84. t.cleanups = {}
  85. }
  86. when TRACKING_MEMORY && FAIL_ON_BAD_MEMORY {
  87. Task_Data :: struct {
  88. it: Internal_Test,
  89. t: T,
  90. allocator_index: int,
  91. tracking_allocator: ^mem.Tracking_Allocator,
  92. }
  93. } else {
  94. Task_Data :: struct {
  95. it: Internal_Test,
  96. t: T,
  97. allocator_index: int,
  98. }
  99. }
  100. Task_Timeout :: struct {
  101. test_index: int,
  102. at_time: time.Time,
  103. location: runtime.Source_Code_Location,
  104. }
  105. run_test_task :: proc(task: thread.Task) {
  106. data := cast(^Task_Data)(task.data)
  107. setup_task_signal_handler(task.user_index)
  108. chan.send(data.t.channel, Event_New_Test {
  109. test_index = task.user_index,
  110. })
  111. chan.send(data.t.channel, Event_State_Change {
  112. new_state = .Running,
  113. })
  114. context.assertion_failure_proc = test_assertion_failure_proc
  115. context.logger = {
  116. procedure = test_logger_proc,
  117. data = &data.t,
  118. lowest_level = get_log_level(),
  119. options = Default_Test_Logger_Opts,
  120. }
  121. random_generator_state: runtime.Default_Random_State
  122. context.random_generator = {
  123. procedure = runtime.default_random_generator_proc,
  124. data = &random_generator_state,
  125. }
  126. rand.reset(data.t.seed)
  127. free_all(context.temp_allocator)
  128. data.it.p(&data.t)
  129. end_t(&data.t)
  130. when TRACKING_MEMORY && FAIL_ON_BAD_MEMORY {
  131. // NOTE(Feoramund): The simplest way to handle treating memory failures
  132. // as errors is to allow the test task runner to access the tracking
  133. // allocator itself.
  134. //
  135. // This way, it's still able to send up a log message, which will be
  136. // used in the end summary, and it can set the test state to `Failed`
  137. // under the usual conditions.
  138. //
  139. // No outside intervention needed.
  140. memory_leaks := len(data.tracking_allocator.allocation_map)
  141. bad_frees := len(data.tracking_allocator.bad_free_array)
  142. memory_is_in_bad_state := memory_leaks + bad_frees > 0
  143. data.t.error_count += memory_leaks + bad_frees
  144. if memory_is_in_bad_state {
  145. log.errorf("Memory failure in `%s.%s` with %i leak%s and %i bad free%s.",
  146. data.it.pkg, data.it.name,
  147. memory_leaks, "" if memory_leaks == 1 else "s",
  148. bad_frees, "" if bad_frees == 1 else "s")
  149. }
  150. }
  151. new_state : Test_State = .Failed if failed(&data.t) else .Successful
  152. chan.send(data.t.channel, Event_State_Change {
  153. new_state = new_state,
  154. })
  155. }
  156. runner :: proc(internal_tests: []Internal_Test) -> bool {
  157. BATCH_BUFFER_SIZE :: 32 * mem.Kilobyte
  158. POOL_BLOCK_SIZE :: 16 * mem.Kilobyte
  159. CLIPBOARD_BUFFER_SIZE :: 16 * mem.Kilobyte
  160. BUFFERED_EVENTS_PER_CHANNEL :: 16
  161. RESERVED_LOG_MESSAGES :: 64
  162. RESERVED_TEST_FAILURES :: 64
  163. ERROR_STRING_TIMEOUT : string : "Test timed out."
  164. ERROR_STRING_UNKNOWN : string : "Test failed for unknown reasons."
  165. OSC_WINDOW_TITLE : string : ansi.OSC + ansi.WINDOW_TITLE + ";Odin test runner (%i/%i)" + ansi.ST
  166. safe_delete_string :: proc(s: string, allocator := context.allocator) {
  167. // Guard against bad frees on static strings.
  168. switch raw_data(s) {
  169. case raw_data(ERROR_STRING_TIMEOUT), raw_data(ERROR_STRING_UNKNOWN):
  170. return
  171. case:
  172. delete(s, allocator)
  173. }
  174. }
  175. stdout := io.to_writer(os.stream_from_handle(os.stdout))
  176. stderr := io.to_writer(os.stream_from_handle(os.stderr))
  177. // -- Prepare test data.
  178. alloc_error: mem.Allocator_Error
  179. when TEST_NAMES != "" {
  180. select_internal_tests: [dynamic]Internal_Test
  181. defer delete(select_internal_tests)
  182. {
  183. index_list := TEST_NAMES
  184. for selector in strings.split_iterator(&index_list, ",") {
  185. // Temp allocator is fine since we just need to identify which test it's referring to.
  186. split_selector := strings.split(selector, ".", context.temp_allocator)
  187. found := false
  188. switch len(split_selector) {
  189. case 1:
  190. // Only the test name?
  191. #no_bounds_check name := split_selector[0]
  192. find_test_by_name: for it in internal_tests {
  193. if it.name == name {
  194. found = true
  195. _, alloc_error = append(&select_internal_tests, it)
  196. fmt.assertf(alloc_error == nil, "Error appending to select internal tests: %v", alloc_error)
  197. break find_test_by_name
  198. }
  199. }
  200. case 2:
  201. #no_bounds_check pkg := split_selector[0]
  202. #no_bounds_check name := split_selector[1]
  203. find_test_by_pkg_and_name: for it in internal_tests {
  204. if it.pkg == pkg && it.name == name {
  205. found = true
  206. _, alloc_error = append(&select_internal_tests, it)
  207. fmt.assertf(alloc_error == nil, "Error appending to select internal tests: %v", alloc_error)
  208. break find_test_by_pkg_and_name
  209. }
  210. }
  211. }
  212. if !found {
  213. fmt.wprintfln(stderr, "No test found for the name: %q", selector)
  214. }
  215. }
  216. }
  217. // `-vet` needs parameters to be shadowed by themselves first as an
  218. // explicit declaration, to allow the next line to work.
  219. internal_tests := internal_tests
  220. // Intentional shadow with user-specified tests.
  221. internal_tests = select_internal_tests[:]
  222. }
  223. total_failure_count := 0
  224. total_success_count := 0
  225. total_done_count := 0
  226. total_test_count := len(internal_tests)
  227. when !FANCY_OUTPUT {
  228. // This is strictly for updating the window title when the progress
  229. // report is disabled. We're otherwise able to depend on the call to
  230. // `needs_to_redraw`.
  231. last_done_count := -1
  232. }
  233. if total_test_count == 0 {
  234. // Exit early.
  235. fmt.wprintln(stdout, "No tests to run.")
  236. return true
  237. }
  238. for it in internal_tests {
  239. // NOTE(Feoramund): The old test runner skipped over tests with nil
  240. // procedures, but I couldn't find any case where they occurred.
  241. // This assert stands to prevent any oversight on my part.
  242. fmt.assertf(it.p != nil, "Test %s.%s has <nil> procedure.", it.pkg, it.name)
  243. }
  244. slice.sort_by(internal_tests, proc(a, b: Internal_Test) -> bool {
  245. if a.pkg == b.pkg {
  246. return a.name < b.name
  247. } else {
  248. return a.pkg < b.pkg
  249. }
  250. })
  251. // -- Set thread count.
  252. when TEST_THREADS == 0 {
  253. thread_count := os.processor_core_count()
  254. } else {
  255. thread_count := max(1, TEST_THREADS)
  256. }
  257. thread_count = min(thread_count, total_test_count)
  258. // -- Allocate.
  259. pool_stack: mem.Rollback_Stack
  260. alloc_error = mem.rollback_stack_init(&pool_stack, POOL_BLOCK_SIZE)
  261. fmt.assertf(alloc_error == nil, "Error allocating memory for thread pool: %v", alloc_error)
  262. defer mem.rollback_stack_destroy(&pool_stack)
  263. pool: thread.Pool
  264. thread.pool_init(&pool, mem.rollback_stack_allocator(&pool_stack), thread_count)
  265. defer thread.pool_destroy(&pool)
  266. task_channels: []Task_Channel = ---
  267. task_channels, alloc_error = make([]Task_Channel, thread_count)
  268. fmt.assertf(alloc_error == nil, "Error allocating memory for update channels: %v", alloc_error)
  269. defer delete(task_channels)
  270. for &task_channel, index in task_channels {
  271. task_channel.channel, alloc_error = chan.create_buffered(Update_Channel, BUFFERED_EVENTS_PER_CHANNEL, context.allocator)
  272. fmt.assertf(alloc_error == nil, "Error allocating memory for update channel #%i: %v", index, alloc_error)
  273. }
  274. defer for &task_channel in task_channels {
  275. chan.destroy(&task_channel.channel)
  276. }
  277. // This buffer is used to batch writes to STDOUT or STDERR, to help reduce
  278. // screen flickering.
  279. batch_buffer: bytes.Buffer
  280. bytes.buffer_init_allocator(&batch_buffer, 0, BATCH_BUFFER_SIZE)
  281. batch_writer := io.to_writer(bytes.buffer_to_stream(&batch_buffer))
  282. defer bytes.buffer_destroy(&batch_buffer)
  283. report: Report = ---
  284. report, alloc_error = make_report(internal_tests)
  285. fmt.assertf(alloc_error == nil, "Error allocating memory for test report: %v", alloc_error)
  286. defer destroy_report(&report)
  287. when FANCY_OUTPUT {
  288. // We cannot make use of the ANSI save/restore cursor codes, because they
  289. // work by absolute screen coordinates. This will cause unnecessary
  290. // scrollback if we print at the bottom of someone's terminal.
  291. ansi_redraw_string := fmt.aprintf(
  292. // ANSI for "go up N lines then erase the screen from the cursor forward."
  293. ansi.CSI + "%i" + ansi.CPL + ansi.CSI + ansi.ED +
  294. // We'll combine this with the window title format string, since it
  295. // can be printed at the same time.
  296. "%s",
  297. // 1 extra line for the status bar.
  298. 1 + len(report.packages), OSC_WINDOW_TITLE)
  299. assert(len(ansi_redraw_string) > 0, "Error allocating ANSI redraw string.")
  300. defer delete(ansi_redraw_string)
  301. thread_count_status_string: string = ---
  302. {
  303. PADDING :: PROGRESS_COLUMN_SPACING + PROGRESS_WIDTH
  304. unpadded := fmt.tprintf("%i thread%s", thread_count, "" if thread_count == 1 else "s")
  305. thread_count_status_string = fmt.aprintf("%- *[1]s", unpadded, report.pkg_column_len + PADDING)
  306. assert(len(thread_count_status_string) > 0, "Error allocating thread count status string.")
  307. }
  308. defer delete(thread_count_status_string)
  309. }
  310. task_data_slots: []Task_Data = ---
  311. task_data_slots, alloc_error = make([]Task_Data, thread_count)
  312. fmt.assertf(alloc_error == nil, "Error allocating memory for task data slots: %v", alloc_error)
  313. defer delete(task_data_slots)
  314. // Tests rotate through these allocators as they finish.
  315. task_allocators: []mem.Rollback_Stack = ---
  316. task_allocators, alloc_error = make([]mem.Rollback_Stack, thread_count)
  317. fmt.assertf(alloc_error == nil, "Error allocating memory for task allocators: %v", alloc_error)
  318. defer delete(task_allocators)
  319. when TRACKING_MEMORY {
  320. task_memory_trackers: []mem.Tracking_Allocator = ---
  321. task_memory_trackers, alloc_error = make([]mem.Tracking_Allocator, thread_count)
  322. fmt.assertf(alloc_error == nil, "Error allocating memory for memory trackers: %v", alloc_error)
  323. defer delete(task_memory_trackers)
  324. }
  325. #no_bounds_check for i in 0 ..< thread_count {
  326. alloc_error = mem.rollback_stack_init(&task_allocators[i], PER_THREAD_MEMORY)
  327. fmt.assertf(alloc_error == nil, "Error allocating memory for task allocator #%i: %v", i, alloc_error)
  328. when TRACKING_MEMORY {
  329. mem.tracking_allocator_init(&task_memory_trackers[i], mem.rollback_stack_allocator(&task_allocators[i]))
  330. }
  331. }
  332. defer #no_bounds_check for i in 0 ..< thread_count {
  333. when TRACKING_MEMORY {
  334. mem.tracking_allocator_destroy(&task_memory_trackers[i])
  335. }
  336. mem.rollback_stack_destroy(&task_allocators[i])
  337. }
  338. task_timeouts: [dynamic]Task_Timeout = ---
  339. task_timeouts, alloc_error = make([dynamic]Task_Timeout, 0, thread_count)
  340. fmt.assertf(alloc_error == nil, "Error allocating memory for task timeouts: %v", alloc_error)
  341. defer delete(task_timeouts)
  342. failed_test_reason_map: map[int]string = ---
  343. failed_test_reason_map, alloc_error = make(map[int]string, RESERVED_TEST_FAILURES)
  344. fmt.assertf(alloc_error == nil, "Error allocating memory for failed test reasons: %v", alloc_error)
  345. defer delete(failed_test_reason_map)
  346. log_messages: [dynamic]Log_Message = ---
  347. log_messages, alloc_error = make([dynamic]Log_Message, 0, RESERVED_LOG_MESSAGES)
  348. fmt.assertf(alloc_error == nil, "Error allocating memory for log message queue: %v", alloc_error)
  349. defer delete(log_messages)
  350. sorted_failed_test_reasons: [dynamic]int = ---
  351. sorted_failed_test_reasons, alloc_error = make([dynamic]int, 0, RESERVED_TEST_FAILURES)
  352. fmt.assertf(alloc_error == nil, "Error allocating memory for sorted failed test reasons: %v", alloc_error)
  353. defer delete(sorted_failed_test_reasons)
  354. when USE_CLIPBOARD {
  355. clipboard_buffer: bytes.Buffer
  356. bytes.buffer_init_allocator(&clipboard_buffer, 0, CLIPBOARD_BUFFER_SIZE)
  357. defer bytes.buffer_destroy(&clipboard_buffer)
  358. }
  359. when SHARED_RANDOM_SEED == 0 {
  360. shared_random_seed := cast(u64)intrinsics.read_cycle_counter()
  361. } else {
  362. shared_random_seed := SHARED_RANDOM_SEED
  363. }
  364. // -- Setup initial tasks.
  365. // NOTE(Feoramund): This is the allocator that will be used by threads to
  366. // persist log messages past their lifetimes. It has its own variable name
  367. // in the event it needs to be changed from `context.allocator` without
  368. // digging through the source to divine everywhere it is used for that.
  369. shared_log_allocator := context.allocator
  370. context.logger = {
  371. procedure = runner_logger_proc,
  372. data = &log_messages,
  373. lowest_level = get_log_level(),
  374. options = Default_Test_Logger_Opts - {.Short_File_Path, .Line, .Procedure},
  375. }
  376. run_index: int
  377. setup_tasks: for &data, task_index in task_data_slots {
  378. setup_next_test: for run_index < total_test_count {
  379. #no_bounds_check it := internal_tests[run_index]
  380. defer run_index += 1
  381. data.it = it
  382. data.t.seed = shared_random_seed
  383. #no_bounds_check data.t.channel = chan.as_send(task_channels[task_index].channel)
  384. data.t._log_allocator = shared_log_allocator
  385. data.allocator_index = task_index
  386. #no_bounds_check when TRACKING_MEMORY {
  387. task_allocator := mem.tracking_allocator(&task_memory_trackers[task_index])
  388. when FAIL_ON_BAD_MEMORY {
  389. data.tracking_allocator = &task_memory_trackers[task_index]
  390. }
  391. } else {
  392. task_allocator := mem.rollback_stack_allocator(&task_allocators[task_index])
  393. }
  394. thread.pool_add_task(&pool, task_allocator, run_test_task, &data, run_index)
  395. continue setup_tasks
  396. }
  397. }
  398. // -- Run tests.
  399. setup_signal_handler()
  400. fmt.wprint(stdout, ansi.CSI + ansi.DECTCEM_HIDE)
  401. when FANCY_OUTPUT {
  402. signals_were_raised := false
  403. redraw_report(stdout, report)
  404. draw_status_bar(stdout, thread_count_status_string, total_done_count, total_test_count)
  405. }
  406. when TEST_THREADS == 0 {
  407. log.infof("Starting test runner with %i thread%s. Set with -define:ODIN_TEST_THREADS=n.",
  408. thread_count,
  409. "" if thread_count == 1 else "s")
  410. } else {
  411. log.infof("Starting test runner with %i thread%s.",
  412. thread_count,
  413. "" if thread_count == 1 else "s")
  414. }
  415. when SHARED_RANDOM_SEED == 0 {
  416. log.infof("The random seed sent to every test is: %v. Set with -define:ODIN_TEST_RANDOM_SEED=n.", shared_random_seed)
  417. } else {
  418. log.infof("The random seed sent to every test is: %v.", shared_random_seed)
  419. }
  420. when TRACKING_MEMORY {
  421. when ALWAYS_REPORT_MEMORY {
  422. log.info("Memory tracking is enabled. Tests will log their memory usage when complete.")
  423. } else {
  424. log.info("Memory tracking is enabled. Tests will log their memory usage if there's an issue.")
  425. }
  426. log.info("< Final Mem/ Total Mem> < Peak Mem> (#Free/Alloc) :: [package.test_name]")
  427. } else {
  428. when ALWAYS_REPORT_MEMORY {
  429. log.warn("ODIN_TEST_ALWAYS_REPORT_MEMORY is true, but ODIN_TEST_TRACK_MEMORY is false.")
  430. }
  431. when FAIL_ON_BAD_MEMORY {
  432. log.warn("ODIN_TEST_FAIL_ON_BAD_MEMORY is true, but ODIN_TEST_TRACK_MEMORY is false.")
  433. }
  434. }
  435. start_time := time.now()
  436. thread.pool_start(&pool)
  437. main_loop: for !thread.pool_is_empty(&pool) {
  438. {
  439. events_pending := thread.pool_num_done(&pool) > 0
  440. if !events_pending {
  441. poll_tasks: for &task_channel in task_channels {
  442. if chan.len(task_channel.channel) > 0 {
  443. events_pending = true
  444. break poll_tasks
  445. }
  446. }
  447. }
  448. if !events_pending {
  449. // Keep the main thread from pegging a core at 100% usage.
  450. time.sleep(1 * time.Microsecond)
  451. }
  452. }
  453. cycle_pool: for task in thread.pool_pop_done(&pool) {
  454. data := cast(^Task_Data)(task.data)
  455. when TRACKING_MEMORY {
  456. #no_bounds_check tracker := &task_memory_trackers[data.allocator_index]
  457. memory_is_in_bad_state := len(tracker.allocation_map) + len(tracker.bad_free_array) > 0
  458. when ALWAYS_REPORT_MEMORY {
  459. should_report := true
  460. } else {
  461. should_report := memory_is_in_bad_state
  462. }
  463. if should_report {
  464. write_memory_report(batch_writer, tracker, data.it.pkg, data.it.name)
  465. when FAIL_ON_BAD_MEMORY {
  466. log.log(.Error if memory_is_in_bad_state else .Info, bytes.buffer_to_string(&batch_buffer))
  467. } else {
  468. log.log(.Warning if memory_is_in_bad_state else .Info, bytes.buffer_to_string(&batch_buffer))
  469. }
  470. bytes.buffer_reset(&batch_buffer)
  471. }
  472. mem.tracking_allocator_reset(tracker)
  473. }
  474. free_all(task.allocator)
  475. if run_index < total_test_count {
  476. #no_bounds_check it := internal_tests[run_index]
  477. defer run_index += 1
  478. data.it = it
  479. data.t.seed = shared_random_seed
  480. data.t.error_count = 0
  481. data.t._fail_now_called = false
  482. thread.pool_add_task(&pool, task.allocator, run_test_task, data, run_index)
  483. }
  484. }
  485. handle_events: for &task_channel in task_channels {
  486. for ev in chan.try_recv(task_channel.channel) {
  487. switch event in ev {
  488. case Event_New_Test:
  489. task_channel.test_index = event.test_index
  490. case Event_State_Change:
  491. #no_bounds_check report.all_test_states[task_channel.test_index] = event.new_state
  492. #no_bounds_check it := internal_tests[task_channel.test_index]
  493. #no_bounds_check pkg := report.packages_by_name[it.pkg]
  494. #partial switch event.new_state {
  495. case .Failed:
  496. if task_channel.test_index not_in failed_test_reason_map {
  497. failed_test_reason_map[task_channel.test_index] = ERROR_STRING_UNKNOWN
  498. }
  499. total_failure_count += 1
  500. total_done_count += 1
  501. case .Successful:
  502. total_success_count += 1
  503. total_done_count += 1
  504. }
  505. when ODIN_DEBUG {
  506. log.debugf("Test #%i %s.%s changed state to %v.", task_channel.test_index, it.pkg, it.name, event.new_state)
  507. }
  508. pkg.last_change_state = event.new_state
  509. pkg.last_change_name = it.name
  510. pkg.frame_ready = false
  511. case Event_Set_Fail_Timeout:
  512. _, alloc_error = append(&task_timeouts, Task_Timeout {
  513. test_index = task_channel.test_index,
  514. at_time = event.at_time,
  515. location = event.location,
  516. })
  517. fmt.assertf(alloc_error == nil, "Error appending to task timeouts: %v", alloc_error)
  518. case Event_Log_Message:
  519. _, alloc_error = append(&log_messages, Log_Message {
  520. level = event.level,
  521. text = event.formatted_text,
  522. time = event.time,
  523. allocator = shared_log_allocator,
  524. })
  525. fmt.assertf(alloc_error == nil, "Error appending to log messages: %v", alloc_error)
  526. if event.level >= .Error {
  527. // Save the message for the final summary.
  528. if old_error, ok := failed_test_reason_map[task_channel.test_index]; ok {
  529. safe_delete_string(old_error, shared_log_allocator)
  530. }
  531. failed_test_reason_map[task_channel.test_index] = event.text
  532. } else {
  533. delete(event.text, shared_log_allocator)
  534. }
  535. }
  536. }
  537. }
  538. check_timeouts: for i := len(task_timeouts) - 1; i >= 0; i -= 1 {
  539. #no_bounds_check timeout := &task_timeouts[i]
  540. if time.since(timeout.at_time) < 0 {
  541. continue check_timeouts
  542. }
  543. defer unordered_remove(&task_timeouts, i)
  544. #no_bounds_check if report.all_test_states[timeout.test_index] > .Running {
  545. continue check_timeouts
  546. }
  547. if !thread.pool_stop_task(&pool, timeout.test_index) {
  548. // The task may have stopped a split second after we started
  549. // checking, but we haven't handled the new state yet.
  550. continue check_timeouts
  551. }
  552. #no_bounds_check report.all_test_states[timeout.test_index] = .Failed
  553. #no_bounds_check it := internal_tests[timeout.test_index]
  554. #no_bounds_check pkg := report.packages_by_name[it.pkg]
  555. pkg.frame_ready = false
  556. if old_error, ok := failed_test_reason_map[timeout.test_index]; ok {
  557. safe_delete_string(old_error, shared_log_allocator)
  558. }
  559. failed_test_reason_map[timeout.test_index] = ERROR_STRING_TIMEOUT
  560. total_failure_count += 1
  561. total_done_count += 1
  562. now := time.now()
  563. _, alloc_error = append(&log_messages, Log_Message {
  564. level = .Error,
  565. text = format_log_text(.Error, ERROR_STRING_TIMEOUT, Default_Test_Logger_Opts, timeout.location, now),
  566. time = now,
  567. allocator = context.allocator,
  568. })
  569. fmt.assertf(alloc_error == nil, "Error appending to log messages: %v", alloc_error)
  570. find_task_data_for_timeout: for &data in task_data_slots {
  571. if data.it.pkg == it.pkg && data.it.name == it.name {
  572. end_t(&data.t)
  573. break find_task_data_for_timeout
  574. }
  575. }
  576. }
  577. if should_stop_runner() {
  578. fmt.wprintln(stderr, "\nCaught interrupt signal. Stopping all tests.")
  579. thread.pool_shutdown(&pool)
  580. break main_loop
  581. }
  582. when FANCY_OUTPUT {
  583. // Because the bounds checking procs send directly to STDERR with
  584. // no way to redirect or handle them, we need to at least try to
  585. // let the user see those messages when using the animated progress
  586. // report. This flag may be set by the block of code below if a
  587. // signal is raised.
  588. //
  589. // It'll be purely by luck if the output is interleaved properly,
  590. // given the nature of non-thread-safe printing.
  591. //
  592. // At worst, if Odin did not print any error for this signal, we'll
  593. // just re-display the progress report. The fatal log error message
  594. // should be enough to clue the user in that something dire has
  595. // occurred.
  596. bypass_progress_overwrite := false
  597. }
  598. if test_index, reason, ok := should_stop_test(); ok {
  599. #no_bounds_check report.all_test_states[test_index] = .Failed
  600. #no_bounds_check it := internal_tests[test_index]
  601. #no_bounds_check pkg := report.packages_by_name[it.pkg]
  602. pkg.frame_ready = false
  603. found := thread.pool_stop_task(&pool, test_index)
  604. fmt.assertf(found, "A signal (%v) was raised to stop test #%i %s.%s, but it was unable to be found.",
  605. reason, test_index, it.pkg, it.name)
  606. // The order this is handled in is a little particular.
  607. task_data: ^Task_Data
  608. find_task_data_for_stop_signal: for &data in task_data_slots {
  609. if data.it.pkg == it.pkg && data.it.name == it.name {
  610. task_data = &data
  611. break find_task_data_for_stop_signal
  612. }
  613. }
  614. fmt.assertf(task_data != nil, "A signal (%v) was raised to stop test #%i %s.%s, but its task data is missing.",
  615. reason, test_index, it.pkg, it.name)
  616. if !task_data.t._fail_now_called {
  617. if test_index not_in failed_test_reason_map {
  618. // We only write a new error message here if there wasn't one
  619. // already, because the message we can provide based only on
  620. // the signal won't be very useful, whereas asserts and panics
  621. // will provide a user-written error message.
  622. failed_test_reason_map[test_index] = fmt.aprintf("Signal caught: %v", reason, allocator = shared_log_allocator)
  623. log.fatalf("Caught signal to stop test #%i %s.%s for: %v.", test_index, it.pkg, it.name, reason)
  624. }
  625. when FANCY_OUTPUT {
  626. bypass_progress_overwrite = true
  627. signals_were_raised = true
  628. }
  629. }
  630. end_t(&task_data.t)
  631. total_failure_count += 1
  632. total_done_count += 1
  633. }
  634. // -- Redraw.
  635. when FANCY_OUTPUT {
  636. if len(log_messages) == 0 && !needs_to_redraw(report) {
  637. continue main_loop
  638. }
  639. if !bypass_progress_overwrite {
  640. fmt.wprintf(stdout, ansi_redraw_string, total_done_count, total_test_count)
  641. }
  642. } else {
  643. if total_done_count != last_done_count {
  644. fmt.wprintf(stdout, OSC_WINDOW_TITLE, total_done_count, total_test_count)
  645. last_done_count = total_done_count
  646. }
  647. if len(log_messages) == 0 {
  648. continue main_loop
  649. }
  650. }
  651. // Because each thread has its own messenger channel, log messages
  652. // arrive in chunks that are in-order, but when they're merged with the
  653. // logs from other threads, they become out-of-order.
  654. slice.stable_sort_by(log_messages[:], proc(a, b: Log_Message) -> bool {
  655. return time.diff(a.time, b.time) > 0
  656. })
  657. for message in log_messages {
  658. fmt.wprintln(batch_writer, message.text)
  659. delete(message.text, message.allocator)
  660. }
  661. fmt.wprint(stderr, bytes.buffer_to_string(&batch_buffer))
  662. clear(&log_messages)
  663. bytes.buffer_reset(&batch_buffer)
  664. when FANCY_OUTPUT {
  665. redraw_report(batch_writer, report)
  666. draw_status_bar(batch_writer, thread_count_status_string, total_done_count, total_test_count)
  667. fmt.wprint(stdout, bytes.buffer_to_string(&batch_buffer))
  668. bytes.buffer_reset(&batch_buffer)
  669. }
  670. }
  671. // -- All tests are complete, or the runner has been interrupted.
  672. // NOTE(Feoramund): If you've arrived here after receiving signal 11 or
  673. // SIGSEGV on the main runner thread, while using a UNIX-like platform,
  674. // there is the possibility that you may have encountered a rare edge case
  675. // involving the joining of threads.
  676. //
  677. // At the time of writing, the thread library is undergoing a rewrite that
  678. // should solve this problem; it is not an issue with the test runner itself.
  679. thread.pool_join(&pool)
  680. finished_in := time.since(start_time)
  681. when !FANCY_OUTPUT {
  682. // One line to space out the results, since we don't have the status
  683. // bar in plain mode.
  684. fmt.wprintln(batch_writer)
  685. }
  686. fmt.wprintf(batch_writer,
  687. "Finished %i test%s in %v.",
  688. total_done_count,
  689. "" if total_done_count == 1 else "s",
  690. finished_in)
  691. if total_done_count != total_test_count {
  692. not_run_count := total_test_count - total_done_count
  693. fmt.wprintf(batch_writer,
  694. " " + SGR_READY + "%i" + SGR_RESET + " %s left undone.",
  695. not_run_count,
  696. "test was" if not_run_count == 1 else "tests were")
  697. }
  698. if total_success_count == total_test_count {
  699. fmt.wprintfln(batch_writer,
  700. " %s " + SGR_SUCCESS + "successful." + SGR_RESET,
  701. "The test was" if total_test_count == 1 else "All tests were")
  702. } else if total_failure_count > 0 {
  703. if total_failure_count == total_test_count {
  704. fmt.wprintfln(batch_writer,
  705. " %s " + SGR_FAILED + "failed." + SGR_RESET,
  706. "The test" if total_test_count == 1 else "All tests")
  707. } else {
  708. fmt.wprintfln(batch_writer,
  709. " " + SGR_FAILED + "%i" + SGR_RESET + " test%s failed.",
  710. total_failure_count,
  711. "" if total_failure_count == 1 else "s")
  712. }
  713. for test_index in failed_test_reason_map {
  714. _, alloc_error = append(&sorted_failed_test_reasons, test_index)
  715. fmt.assertf(alloc_error == nil, "Error appending to sorted failed test reasons: %v", alloc_error)
  716. }
  717. slice.sort(sorted_failed_test_reasons[:])
  718. for test_index in sorted_failed_test_reasons {
  719. #no_bounds_check last_error := failed_test_reason_map[test_index]
  720. #no_bounds_check it := internal_tests[test_index]
  721. pkg_and_name := fmt.tprintf("%s.%s", it.pkg, it.name)
  722. fmt.wprintfln(batch_writer, " - %- *[1]s\t%s",
  723. pkg_and_name,
  724. report.pkg_column_len + report.test_column_len,
  725. last_error)
  726. safe_delete_string(last_error, shared_log_allocator)
  727. }
  728. if total_success_count > 0 {
  729. when USE_CLIPBOARD {
  730. clipboard_writer := io.to_writer(bytes.buffer_to_stream(&clipboard_buffer))
  731. fmt.wprint(clipboard_writer, "-define:ODIN_TEST_NAMES=")
  732. for test_index in sorted_failed_test_reasons {
  733. #no_bounds_check it := internal_tests[test_index]
  734. fmt.wprintf(clipboard_writer, "%s.%s,", it.pkg, it.name)
  735. }
  736. encoded_names := base64.encode(bytes.buffer_to_bytes(&clipboard_buffer), allocator = context.temp_allocator)
  737. fmt.wprintf(batch_writer,
  738. ansi.OSC + ansi.CLIPBOARD + ";c;%s" + ansi.ST +
  739. "\nThe name%s of the failed test%s been copied to your clipboard.",
  740. encoded_names,
  741. "" if total_failure_count == 1 else "s",
  742. " has" if total_failure_count == 1 else "s have")
  743. } else {
  744. fmt.wprintf(batch_writer, "\nTo run only the failed test%s, use:\n\t-define:ODIN_TEST_NAMES=",
  745. "" if total_failure_count == 1 else "s")
  746. for test_index in sorted_failed_test_reasons {
  747. #no_bounds_check it := internal_tests[test_index]
  748. fmt.wprintf(batch_writer, "%s.%s,", it.pkg, it.name)
  749. }
  750. fmt.wprint(batch_writer, "\n\nIf your terminal supports OSC 52, you may use -define:ODIN_TEST_CLIPBOARD to have this copied directly to your clipboard.")
  751. }
  752. fmt.wprintln(batch_writer)
  753. }
  754. }
  755. fmt.wprint(stdout, ansi.CSI + ansi.DECTCEM_SHOW)
  756. when FANCY_OUTPUT {
  757. if signals_were_raised {
  758. fmt.wprintln(batch_writer, `
  759. Signals were raised during this test run. Log messages are likely to have collided with each other.
  760. To partly mitigate this, redirect STDERR to a file or use the -define:ODIN_TEST_FANCY=false option.`)
  761. }
  762. }
  763. fmt.wprintln(stderr, bytes.buffer_to_string(&batch_buffer))
  764. when JSON_REPORT != "" {
  765. json_report: JSON
  766. mode: int
  767. when ODIN_OS != .Windows {
  768. mode = os.S_IRUSR|os.S_IWUSR|os.S_IRGRP|os.S_IROTH
  769. }
  770. json_fd, err := os.open(JSON_REPORT, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode)
  771. fmt.assertf(err == nil, "unable to open file %q for writing of JSON report, error: %v", JSON_REPORT, err)
  772. defer os.close(json_fd)
  773. for test, i in report.all_tests {
  774. #no_bounds_check state := report.all_test_states[i]
  775. if test.pkg not_in json_report.packages {
  776. json_report.packages[test.pkg] = {}
  777. }
  778. tests := &json_report.packages[test.pkg]
  779. append(tests, JSON_Test{name = test.name, success = state == .Successful})
  780. }
  781. json_report.total = len(internal_tests)
  782. json_report.success = total_success_count
  783. json_report.duration = finished_in
  784. err := json.marshal_to_writer(os.stream_from_handle(json_fd), json_report, &{ pretty = true })
  785. fmt.assertf(err == nil, "Error writing JSON report: %v", err)
  786. }
  787. return total_success_count == total_test_count
  788. }