Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use if __name__ == '__main__': for tests

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?

like image 696
Paul Manta Avatar asked Sep 04 '11 06:09

Paul Manta


3 Answers

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.

like image 32
manojlds Avatar answered Oct 18 '22 03:10

manojlds


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.

like image 68
Roman Bodnarchuk Avatar answered Oct 18 '22 03:10

Roman Bodnarchuk


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.

like image 25
David Heffernan Avatar answered Oct 18 '22 03:10

David Heffernan