Reputation: 4089
How do I just run the tests without executing the parent script in py.test? Currently I run command pytest -v
from directory Project_dir, and this runs script.py and tests finally in the end. Ideally only tests need to be run. Here is my current directory setup:
Project_dir
script.py
test
test_script.py
script.py
def add(a,b):
added = a + b
return added
x = add(1,3)
print x, 'yup'
test_script.py
import script
def test_add():
assert script.add(3,4) == 7
Working directory: Project_dir
Command: pytest -vs
========================================== test session starts ==========================================
platform darwin -- Python 2.7.10, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 -- /usr/bin/python
cachedir: .cache
rootdir: **, inifile:
plugins: cov-2.4.0
collecting 0 items
Sum is 4
collected 1 items
test/test_script.py::test_add PASSED
======================================= 1 passed in 0.00 seconds ========================================
Sum is 4
shows the script.py executed fully instead of just the tests. It happens as the script.py is imported as module. But I keep thinking there must be a way to avoid this and just execute the tests directly.
Upvotes: 0
Views: 2434
Reputation: 11929
Importing a module in Python executes all top-level code in it.
You should have your code in a if __name__ == '__main__':
so it only executes when you run your script (but not when you import it) - see e.g. this answer for details.
Upvotes: 3
Reputation: 22942
Try to Ignore paths during test collection
pytest -v --ignore=script.py
Or run pytest on a directory:
pytest -v test/
See Specifying tests / selecting tests
Upvotes: 0
Reputation: 359
How about running pytest test/
?
Just to make it clear:
https://docs.pytest.org/en/latest/usage.html#specifying-tests-selecting-tests
pytest somepath # run all tests below somepath
Upvotes: 0