简体   繁体   中英

How does pytest find files to test?

I know how py.test discovers tests to run, but I don't know how to make the tests refer to the files that contains the code to test.

My project looks like this:

arith.py
tests/
    test_airth.py

In my project root directory, I have the file arith.py with

def plus(x, y):
    return x + y

In the file tests/test_arith.py I have

import arith
def test_plus():
    assert arith.plus(3, 5) == 8

When I run, in the project root directory,

pytest

It discovers my test file, because I followed the test discovery rules. But pytest replies with

ImportError while importing test module tests/test_arith.py'

I ran pytest from the project root, so why does it not like my import? It wants to find the files that I am testing in the tests directory!

How can I set up the imports properly, so that my test files in the tests/ directory, can see the files under test which are in the project root directory? (The examples in pytest's documentation seem to not do anything special...perhaps the tests are in the same directory as the files under test? They describe test discovery in great detail, but I must have missed how to set up the tests so they can see the code they are testing.)

Assuming you have a layout like this (which is what I do):

.
├── myprogram
│   ├── __init__.py
│   ├── core.py
│   └── db.py
├── setup.py
└── tests
    ├── test_core.py
    └── test_db.py

You should be invoking pytest like so:

py.test tests

I'm fairly sure that's an absolute/relative path to the tests directory. This also assumes that you have done something like python -m pip install -e . in your root directory. And you have a .git or .hg folder there, too :)

It's a little strange so much is needed. Surely there is a better way?

Actually that is the best way. I don't think it's controversial to declare that the best way to distribute your Python application is as a Python package, preferably a wheel . To do that, you're probably going to need a setup.py .

By installing your package (preferably in a venv/virtualenv sandbox) you're ensuring that you know what packages are required to install/run yours . If your package is installed that means that any script that does import myprogram (using my example layout) will be able to import your package. Which is what you'll be doing in your test suite.

Then your test discovery is as simple as telling pytest where to find it.

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