1# Unit tests 2 3Unit tests are for Starlark code that isn't specific to analysis-phase or 4loading phase cases; usually utility code of some sort. Such tests typically 5don't require a rule `ctx` or instantiating other targets to verify the code 6under test. 7 8To write such a test, simply write a function accepting `env` and pass it to 9`test_suite`. The test suite will pass your verification function to 10`unit_test()` for you. 11 12```starlark 13# BUILD 14 15load(":my_tests.bzl", "my_test_suite") 16load("@rules_testing//lib:test_suite.bzl", "test_suite") 17 18my_test_suite(name = "my_tests") 19 20# my_tests.bzl 21 22def _foo_test(env): 23 env.expect.that_str(...).equals(...) 24 25def my_test_suite(name): 26 test_suite( 27 name = name, 28 basic_tests = [ 29 _foo_test, 30 ] 31 ) 32``` 33 34Note that it isn't _required_ to write a custom test suite function, but doing 35so is preferred because it's uncommon for BUILD files to pass around function 36objects, and tools won't be confused by it. 37 38## Customizing setup 39 40If you want to customize the setup (loading phase) of a unit test, e.g. to add 41custom attributes, then you need to write in the same style as an analysis test: 42one function is a verification function, and another function performs setup and 43calls `unit_test()`, passing in the verification function. 44 45Custom tests are like basic tests, except you can hook into the loading phase 46before the actual unit test is defined. Because you control the invocation of 47`unit_test`, you can e.g. define custom attributes specific to the test. 48 49```starlark 50# my_tests.bzl 51def _foo_test(name): 52 unit_test( 53 name = name, 54 impl = _foo_test_impl, 55 attrs = {"myattr": attr.string(default="default")} 56 ) 57 58def _foo_test_impl(env): 59 env.expect.that_str(...).equals(...) 60 61def my_test_suite(name): 62 test_suite( 63 name = name, 64 custom_tests = [ 65 _foo_test, 66 ] 67 ) 68``` 69 70Note that a custom test is not required to define custom attributes; the above 71is just an example. If you want to define custom attributes for every test in a 72suite, the `test_kwargs` argument of `test_suite` can be used to pass additional 73arguments to all tests in the suite. 74