Search code examples
pythonunit-testingcontinuous-integrationnose

How to run all tests in a python file from a python script?


How do I run all tests (unittest.TestCase) from a python file in a script?

I've tried using nose but it always seems to run the test discovery. All I want is to import a module, give some function a path and get the test results back, any suggestions?


Solution

  • At the bottom of your test script put

    if __name__ == '__main__':
        unittest.main()
    

    Then just call your file as normal

    $ python my_test_script.py
    

    Optionally, if you want to use nose or pytest, you can just give it the name of the script you want to run, it will still do discovery, but only on that one file.

    $ nosetests my_test_script.py
    
    $ py.test my_test_script.py
    

    If you're running nose from inside python, you can use nose.run()

    my_script.py

    import nose
    nose.run()
    

    By default, it will use the arguments you pass to the script, so if you only want to run a single test_script

    $ python my_script.py /path/to/test_script.py
    

    Or, you can pass the arguments directly inside your script

    nose.run(argv=[__file__, '/path/to/test_script'])