Paul Manta
Paul Manta

Reputation: 31597

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?

Upvotes: 10

Views: 2545

Answers (4)

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29727

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.

Upvotes: 6

David Heffernan
David Heffernan

Reputation: 613192

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.

Upvotes: 3

manojlds
manojlds

Reputation: 301297

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.

Upvotes: 6

LeleDumbo
LeleDumbo

Reputation: 9340

I guess not, in fact, I saw a lot of python scripts (mostly plugins of another application) written that way.

Upvotes: 0

Related Questions