Search code examples
pythonunit-testingtestingcommandpytest

pytest will not run the test files in subdirectories


I am new to pytest and trying to run a simple test to check if pytest works. I'm using windows 10, python 3.8.5 and pytest 6.0.1.

Here is my project directory:

projects
 └-tests    
    |-__init__.py   
    └-test_sample.py

Here is what I put in test_sample.py:

def func(x):
    return x + 1

def test_answer():
    assert func(3) == 5

If I do the following:

> pytest 
the test run fine (1 failed in 0.004s)
> pytest tests/test_sample.py 
the test run fine (1 failed in 0.006s) 

However, if I do this:

> pytest test_sample.py

It will return a message like this:

no test ran in 0.000s
ERROR: file not found: test_sample.py

I tried deleting __init__.py file but the result was still the same. Also, I have tried this on 2 different computers but nothing changed. In case the problem can't be solved, can I just ignore it and move on with the solutions I'm having?


Solution

  • The "best practices" approach to configuring a project with pytest is using a config file. The simplest solution is a pytest.ini that looks like this:

    # pytest.ini
    [pytest]
    
    testpaths = tests
    

    This configures the testpaths relative to your rootdir (pytest will tell you what both paths are whenever you run it). This answers the specific problem you raised in your question.

    C:\YourProject  <<-- Run pytest on this path and it will be considered your rootdir.
    │
    │ pytest.ini
    │ your_module.py
    │
    ├───tests       <<-- This is the directory you configured as testpaths in pytest.ini
    │     __init__.py
    │     test_sample.py
    

    Your example was about running specific tests from the command line. The complete set of rules for finding the rootdir from args is somewhat contrived.

    You should notice that pytest currently supports two possible layouts for your tests and modules. It's currently strongly suggested by pytest documentation to use a src layout. Answering about the importance of using __init__.py depends on the former to an extent, however choosing a configuration file and layout still takes precedence over how you choose to use __init__.py to define your packages.