I’ve been writing a lot of golang recently and there is one big thing that golang gets right over python: it colocates source and test code.
Colocating source and test code means putting them next to each other. So instead of having a separate
test directory, you have
main_test.go. If try this in python this is what it would look like:
Colocating has many benefits and drawbacks, but I think there is one big pro that outweighs all the other cons.
Colocating your source and test code elevates your test code to the same importance as your source code.
Too often I’ve seen projects where testing is an afterthought, but it shouldn’t be! I believe that your tests are as important as your source code because they are the only verifiable source of truth for the behavior of your program. (See also the Github repo for more information)
You probably agree with me quite quickly that this is nice for unit tests, but what about integration tests I hear you think? Good question. I haven’t figured this out myself completely but someone on Reddit said this:
Rust does both. The rust book suggests unit tests within the source files (in separate modules) and integration tests in the test directory. I’ve found it makes simple unit and property tests very convenient (I usually use hspec with Haskell). However, it means cargo can’t differentiate between imports for the library vs the test suite.
Anyway, I made a small proof of concept (POC) to explore this idea further and I wanted to share it. I wonder if this leads to higher quality projects and if this approach scales to bigger projects.
Find the code on Github here: https://github.com/Rainymood/colocated-tests