0

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.

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

Meaning pytest test_script.py for my example? It's not different (except for verbose) from pytest -v as pytest uses discovery rules to do the same thing.
So.. you want to test some script behaviour, without executing it? How do you test it then? :) I guess you should show us test_script.py and scripts.py if possible.
I am not sure if it's possible or not. Added an example now. Thanks!
0

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

2 Comments

You can run pytest on a directory
Still executes the main script. Not sure if pytest -v is any different from pytest -v test/ since we have only one test directory here. Just to be clear, main script gets executed when it is imported as module in the test script.

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.