6

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?

1 Answer 1

7

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'])
Sign up to request clarification or add additional context in comments.

3 Comments

I'm already in a python script, I don't wanna run another shell or anything.
How can I do what u do with Nose but with plain unittest? at the moment I get module 'unittest' has no attribute 'run'
@MoteZart nose will discover plain unittest-style tests. My first example shows how to use unittest via unittest.main(), though it offers far fewer options than discovering/running tests with nose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.