When you write some scripts that are self sufficient, is it a bad idea to use the if __name__ == '__main__'
as a place to write tests?
Test logic and tests should never be part of "production" (production can mean in use by you, released to client, etc.) code. So, it is a bad idea to have them anywhere within your script.
Ideally, have them in separate files.
It really depends on your code and purposes of your script. For big and complex projects you for sure have to put all your tests into a separate place.
But while working on something small it might be a good solution to have tests along with code - it is the main idea of doctest
(it is a great Python module that allows you to write tests in the docstrings). In this case your if __name__ == '__main__'
will look like:
if __name__ == "__main__":
import doctest
doctest.testmod()
I find it nice and clean.
Best practice is to put the tests in separate units that use the unittest module. This separation allows you to keep the main code clean (no need for lots of testing helper functions) and encourages you to write good comprehensive tests since you are not inhibited by cluttering the main code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With