testing.odin 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. package testing
  2. /*
  3. (c) Copyright 2024 Feoramund <[email protected]>.
  4. Made available under Odin's BSD-3 license.
  5. List of contributors:
  6. Ginger Bill: Initial implementation.
  7. Feoramund: Total rewrite.
  8. */
  9. import "base:intrinsics"
  10. import "base:runtime"
  11. import "core:log"
  12. import "core:reflect"
  13. import "core:sync"
  14. import "core:sync/chan"
  15. import "core:time"
  16. import "core:mem"
  17. _ :: reflect // alias reflect to nothing to force visibility for -vet
  18. _ :: mem // in case TRACKING_MEMORY is not enabled
  19. MAX_EXPECTED_ASSERTIONS_PER_TEST :: 5
  20. // IMPORTANT NOTE: Compiler requires this layout
  21. Test_Signature :: proc(^T)
  22. // IMPORTANT NOTE: Compiler requires this layout
  23. Internal_Test :: struct {
  24. pkg: string,
  25. name: string,
  26. p: Test_Signature,
  27. }
  28. Internal_Cleanup :: struct {
  29. procedure: proc(rawptr),
  30. user_data: rawptr,
  31. ctx: runtime.Context,
  32. }
  33. T :: struct {
  34. error_count: int,
  35. // If your test needs to perform random operations, it's advised to use
  36. // this value to seed a local random number generator rather than relying
  37. // on the non-thread-safe global one.
  38. //
  39. // This way, your results will be deterministic.
  40. //
  41. // This value is chosen at startup of the test runner, logged, and may be
  42. // specified by the user. It is the same for all tests of a single run.
  43. seed: u64,
  44. channel: Update_Channel_Sender,
  45. cleanups: [dynamic]Internal_Cleanup,
  46. // This allocator is shared between the test runner and its threads for
  47. // cloning log strings, so they can outlive the lifetime of individual
  48. // tests during channel transmission.
  49. _log_allocator: runtime.Allocator,
  50. _fail_now_called: bool,
  51. }
  52. fail :: proc(t: ^T, loc := #caller_location) {
  53. log.error("FAIL", location=loc)
  54. }
  55. // fail_now will cause a test to immediately fail and abort, much in the same
  56. // way a failed assertion or panic call will stop a thread.
  57. //
  58. // It is for when you absolutely need a test to fail without calling any of its
  59. // deferred statements. It will be cleaner than a regular assert or panic,
  60. // as the test runner will know to expect the signal this procedure will raise.
  61. fail_now :: proc(t: ^T, msg := "", loc := #caller_location) -> ! {
  62. t._fail_now_called = true
  63. if msg != "" {
  64. log.error("FAIL:", msg, location=loc)
  65. } else {
  66. log.error("FAIL", location=loc)
  67. }
  68. runtime.trap()
  69. }
  70. failed :: proc(t: ^T) -> bool {
  71. return t.error_count != 0
  72. }
  73. // cleanup registers a procedure and user_data, which will be called when the test, and all its subtests, complete.
  74. // Cleanup procedures will be called in LIFO (last added, first called) order.
  75. //
  76. // Each procedure will use a copy of the context at the time of registering,
  77. // and if the test failed due to a timeout, failed assertion, panic, bounds-checking error,
  78. // memory access violation, or any other signal-based fault, this procedure will
  79. // run with greater privilege in the test runner's main thread.
  80. //
  81. // That means that any cleanup procedure absolutely must not fail in the same way,
  82. // or it will take down the entire test runner with it. This is for when you
  83. // need something to run no matter what, if a test failed.
  84. //
  85. // For almost every usual case, `defer` should be preferable and sufficient.
  86. cleanup :: proc(t: ^T, procedure: proc(rawptr), user_data: rawptr) {
  87. append(&t.cleanups, Internal_Cleanup{procedure, user_data, context})
  88. }
  89. expect :: proc(t: ^T, ok: bool, msg := "", expr := #caller_expression(ok), loc := #caller_location) -> bool {
  90. if !ok {
  91. if msg == "" {
  92. log.errorf("expected %v to be true", expr, location=loc)
  93. } else {
  94. log.error(msg, location=loc)
  95. }
  96. }
  97. return ok
  98. }
  99. expectf :: proc(t: ^T, ok: bool, format: string, args: ..any, loc := #caller_location) -> bool {
  100. if !ok {
  101. log.errorf(format, ..args, location=loc)
  102. }
  103. return ok
  104. }
  105. expect_value :: proc(t: ^T, value, expected: $T, loc := #caller_location, value_expr := #caller_expression(value)) -> bool where intrinsics.type_is_comparable(T) {
  106. ok := value == expected || reflect.is_nil(value) && reflect.is_nil(expected)
  107. if !ok {
  108. log.errorf("expected %v to be %v, got %v", value_expr, expected, value, location=loc)
  109. }
  110. return ok
  111. }
  112. Memory_Verifier_Proc :: #type proc(t: ^T, ta: ^mem.Tracking_Allocator)
  113. expect_leaks :: proc(t: ^T, client_test: proc(t: ^T), verifier: Memory_Verifier_Proc) {
  114. when TRACKING_MEMORY {
  115. client_test(t)
  116. ta := (^mem.Tracking_Allocator)(context.allocator.data)
  117. sync.mutex_lock(&ta.mutex)
  118. // The verifier can inspect this local tracking allocator.
  119. // And then call `testing.expect_*` as makes sense for the client test.
  120. verifier(t, ta)
  121. sync.mutex_unlock(&ta.mutex)
  122. clear(&ta.bad_free_array)
  123. free_all(context.allocator)
  124. }
  125. }
  126. set_fail_timeout :: proc(t: ^T, duration: time.Duration, loc := #caller_location) {
  127. chan.send(t.channel, Event_Set_Fail_Timeout {
  128. at_time = time.time_add(time.now(), duration),
  129. location = loc,
  130. })
  131. }
  132. /*
  133. Let the test runner know that it should expect an assertion failure from a
  134. specific location in the source code for this test.
  135. In the event that an assertion fails, a debug message will be logged with its
  136. exact message and location in a copyable format to make it convenient to write
  137. tests which use this API.
  138. This procedure may be called up to 5 times with different locations.
  139. This is a limitation for the sake of simplicity in the implementation, and you
  140. should consider breaking up your tests into smaller procedures if you need to
  141. check for asserts in more than 2 places.
  142. */
  143. expect_assert_from :: proc(t: ^T, expected_place: runtime.Source_Code_Location, caller_loc := #caller_location) {
  144. count := local_test_expected_failures.location_count
  145. if count == MAX_EXPECTED_ASSERTIONS_PER_TEST {
  146. panic("This test cannot handle that many expected assertions based on matching the location.", caller_loc)
  147. }
  148. local_test_expected_failures.locations[count] = expected_place
  149. local_test_expected_failures.location_count += 1
  150. }
  151. /*
  152. Let the test runner know that it should expect an assertion failure with a
  153. specific message for this test.
  154. In the event that an assertion fails, a debug message will be logged with its
  155. exact message and location in a copyable format to make it convenient to write
  156. tests which use this API.
  157. This procedure may be called up to 5 times with different messages.
  158. This is a limitation for the sake of simplicity in the implementation, and you
  159. should consider breaking up your tests into smaller procedures if you need to
  160. check for more than a couple different assertion messages.
  161. */
  162. expect_assert_message :: proc(t: ^T, expected_message: string, caller_loc := #caller_location) {
  163. count := local_test_expected_failures.message_count
  164. if count == MAX_EXPECTED_ASSERTIONS_PER_TEST {
  165. panic("This test cannot handle that many expected assertions based on matching the message.", caller_loc)
  166. }
  167. local_test_expected_failures.messages[count] = expected_message
  168. local_test_expected_failures.message_count += 1
  169. }
  170. expect_assert :: proc {
  171. expect_assert_from,
  172. expect_assert_message,
  173. }
  174. /*
  175. Let the test runner know that it should expect a signal to be raised within
  176. this test.
  177. This API is for advanced users, as arbitrary signals will not be caught; only
  178. the ones already handled by the test runner, such as
  179. - SIGINT, (interrupt)
  180. - SIGTERM, (polite termination)
  181. - SIGILL, (illegal instruction)
  182. - SIGFPE, (arithmetic error)
  183. - SIGSEGV, and (segmentation fault)
  184. - SIGTRAP (only on POSIX systems). (trap / debug trap)
  185. Note that only one signal can be expected per test.
  186. */
  187. expect_signal :: proc(t: ^T, #any_int sig: i32) {
  188. local_test_expected_failures.signal = sig
  189. }