Take the 2-minute tour ×

Say I have a module with the following:

def main():

if __name__ == "__main__":

I want to write a unit test for the bottom half (I'd like to achieve 100% coverage). I discovered the runpy builtin module that performs the import/__name__-setting mechanism, but I can't figure out how to mock or otherwise check that the main() function is called.

This is what I've tried so far:

import runpy
import mock

def test_main(self, main):
    runpy.run_module('foobar', run_name='__main__')
share|improve this question
add comment

3 Answers

up vote 10 down vote accepted

I will choose another alternative which is to exclude the if __name__ == '__main__' from the coverage report , of course you can do that only if you already have a test case for your main() function in your tests.

As for why i choose to exclude rather than writing a new test case for the whole script is because if as i stated you already have a test case for your main() function the fact that you add an other test case for the script (just for having a 100 % coverage) will be just a duplicated one.

For how to exclude the if __name__ == '__main__' you can write a coverage configuration file and add in the section report:


exclude_lines =
    if __name__ == .__main__.:

More info about the coverage configuration file can be found here.

Hope this can help.

share|improve this answer
add comment

You can do this using the imp module rather than the import statement. The problem with the import statement is that the test for '__main__' runs as part of the import statement before you get a chance to assign to runpy.__name__.

For example, you could use imp.load_source() like so:

import imp
runpy = imp.load_source('__main__', '/path/to/runpy.py')

The first parameter is assigned to __name__ of the imported module.

share|improve this answer
The imp module seems to work much like the runpy module I used in the question. The problem is that the mock cannot (apparently) be inserted after the module was loaded and before the code was run. Do you have any suggestions for this? –  Nikolaj May 1 '11 at 19:54
add comment

One approach is to run the modules as scripts (e.g. os.system(...)) and compare their stdout and stderr output to expected values.

share|improve this answer
Running the script in a sub process and expecting coverage.py to track the line executed is not at easy as it sound , more info to make this solution work can be found here: nedbatchelder.com/code/coverage/subprocess.html –  mouad May 1 '11 at 18:37
add comment

Your Answer


