首页 > 解决方案 > Pytest 无法导入源文件。我究竟做错了什么?

问题描述

这是我的文件夹结构:

 tree -L 2
.
├── Pipfile
├── Pipfile.lock
├── Procfile
├── README.md
├── __init__.py
├── __pycache__
│   └── __init__.cpython-37.pyc
├── alembic
│   ├── README
│   ├── env.py
│   ├── script.py.mako
│   └── versions
├── clients
│   ├── __init__.py
│   ├── __pycache__
│   ├── binance_client.py
│   └── slack_client.py
├── helpers
│   ├── __init__.py
│   ├── __pycache__
│   └── math_helpers.py
├── models
│   ├── __init__.py
│   ├── __pycache__
│   ├── pair.py
├── requirements.txt
├── tests
│   ├── __init__.py
│   ├── __pycache__
│   └── test_pair.py

当我在文件夹中运行此测试时tests

from models.pair import Pair


def test_name():
    coin = "some_coin"
    underlying_asset = "BTC"
    pair = Pair(coin, underlying_asset)
    print(pair)

我得到一个错误。

ImportError while importing test module '/Users/stride-admin/kittycapital/tests/test_pair.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_pair.py:1: in <module>
    from models.pair import Pair
E   ModuleNotFoundError: No module named 'models'
=========================================================================================================================== short test summary info ============================================================================================================================
ERROR tests/test_pair.py
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

clients在根目录(与, tests,相同的级别models)中,当我运行 pytest 时出现上述错误。我究竟做错了什么?

当我在我的测试文件中这样做时:

from ..models.pair import Pair


def test_name():
    coin = "some_coin"
    underlying_asset = "BTC"
    pair = Pair(coin, underlying_asset)
    print(pair)

我收到此错误:

ImportError while importing test module '/Users/stride-admin/kittycapital/tests/test_pair.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_pair.py:1: in <module>
    from ..models.pair import Pair
models/pair.py:1: in <module>
    from clients.binance_client import BinanceClient, BinanceAPIError
E   ModuleNotFoundError: No module named 'clients'

所以感觉不对。

标签: pytest

解决方案


推荐阅读