简体   繁体   中英

Running pytest with separate test files

I have a directory structure as recommended by the pytest good integration practices guide , which looks like this:

.
src/
    mypkg/
          __init__.py
          mypkg.py
tests/
      __init__.py
      test_mypkg.py

The __init__.py files are both empty, and the other files are as follows:

mypkg.py

def foo(x):
    """
    Show x.
    >>> foo(5)
    x is 5
    >>> foo("hello")
    x is hello
    """
    return "x is {0}".format(x)

test.py

from mypkg import *
def test_foo():
    assert foo(5) == "x is 5"

When I run pytest from the root directory I get:

tests\test_foo.py:1: in <module>
    from mypkg import *
E   ModuleNotFoundError: No module named 'mypkg'

What is the recommended way of setting this up?

I am no pytest specialist but this looks like a mission for conftest.py, conftest allow one to load tests from module / package / shared fixtures and more...

See this page for more info.

py doesn't know the path of mypkg.py . So you need to inform that using below two lines

import sys
sys.path.append("/path/to/src/mypkg")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM