common.odin 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Boilerplate for tests
  2. package common
  3. import "core:testing"
  4. import "core:fmt"
  5. import "core:os"
  6. import "core:strings"
  7. TEST_count := 0
  8. TEST_fail := 0
  9. when ODIN_TEST {
  10. expect :: testing.expect
  11. log :: testing.log
  12. errorf :: testing.errorf
  13. } else {
  14. expect :: proc(t: ^testing.T, condition: bool, message: string, loc := #caller_location) {
  15. TEST_count += 1
  16. if !condition {
  17. TEST_fail += 1
  18. fmt.printf("[%v:%s] FAIL %v\n", loc, loc.procedure, message)
  19. return
  20. }
  21. }
  22. errorf :: proc(t: ^testing.T, message: string, args: ..any, loc := #caller_location) {
  23. TEST_fail += 1
  24. fmt.printf("[%v:%s] Error %v\n", loc, loc.procedure, fmt.tprintf(message, ..args))
  25. return
  26. }
  27. log :: proc(t: ^testing.T, v: any, loc := #caller_location) {
  28. fmt.printf("[%v] ", loc)
  29. fmt.printf("log: %v\n", v)
  30. }
  31. }
  32. report :: proc(t: ^testing.T) {
  33. if TEST_fail > 0 {
  34. if TEST_fail > 1 {
  35. fmt.printf("%v/%v tests successful, %v tests failed.\n", TEST_count - TEST_fail, TEST_count, TEST_fail)
  36. } else {
  37. fmt.printf("%v/%v tests successful, 1 test failed.\n", TEST_count - TEST_fail, TEST_count)
  38. }
  39. os.exit(1)
  40. } else {
  41. fmt.printf("%v/%v tests successful.\n", TEST_count, TEST_count)
  42. }
  43. }
  44. // Returns absolute path to `sub_path` where `sub_path` is within the "tests/" sub-directory of the Odin project root
  45. // and we're being run from the Odin project root or from a sub-directory of "tests/"
  46. // e.g. get_data_path("assets/blah") will return "/Odin_root/tests/assets/blah" if run within "/Odin_root",
  47. // "/Odin_root/tests" or "/Odin_root/tests/subdir" etc
  48. get_data_path :: proc(t: ^testing.T, sub_path: string) -> (data_path: string) {
  49. cwd := os.get_current_directory()
  50. defer delete(cwd)
  51. when ODIN_OS == .Windows {
  52. norm, was_allocation := strings.replace_all(cwd, "\\", "/")
  53. if !was_allocation {
  54. norm = strings.clone(norm)
  55. }
  56. defer delete(norm)
  57. } else {
  58. norm := cwd
  59. }
  60. last_index := strings.last_index(norm, "/tests/")
  61. if last_index == -1 {
  62. len := len(norm)
  63. if len >= 6 && norm[len-6:] == "/tests" {
  64. data_path = fmt.tprintf("%s/%s", norm, sub_path)
  65. } else {
  66. data_path = fmt.tprintf("%s/tests/%s", norm, sub_path)
  67. }
  68. } else {
  69. data_path = fmt.tprintf("%s/tests/%s", norm[:last_index], sub_path)
  70. }
  71. return data_path
  72. }