我创建了一个名为 stuff 的模块,并在 stuff 文件夹中创建了这些文件,
__init__.py
和accum.py
在
accum.py
我有
class Accumulator:
def __init__(self):
self._count = 0
@property
def count(self):
return self._count
def add(self, more=1):
self._count += more
我创建了一个新文件夹
test
,并在test
文件夹中创建了一个文件test_accum.py
在我有的
test_accum.py
文件中
import pytest
from stuff.accum import Accumulator
当我运行 Python 文件时,它返回:
ModuleNotFoundError: No module named 'stuff'
如果您尝试运行测试模块,它会失败,因为它不在 @tromgy 解释的路径中。但是,要运行测试,您不需要初始化文件或弄乱
sys.path
。
使用 pytest,您不应该运行测试模块本身来运行测试,而是使用
python -m pytest tests
从命令行运行 pytest。只需确保您正在从项目文件夹运行,即“tau-intro-to-pytest”。如果您想运行特定的测试函数,您也可以从命令行指定,但是有很好的 VS Code 扩展可以做到这一点,而无需编写冗长的命令行调用。 python 扩展包含一个测试资源管理器,但我更喜欢 Python Test Explorer for VS Code 的 UI。