How do I solve a ModuleNotFound error: No module named 'stuff' in VSCode Python 3.10.0

How do I solve a ModuleNotFound error: No module named 'stuff' in VSCode Python 3.10.0

我创建了一个名为 stuff 的模块,在 stuff 文件夹中,我创建了这些文件,visual studio code preview

init.py,以及accum.py

in accum.py I have

class 累加器:

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

in test_accum.py file I have

导入 pytest

从 stuff.accum 导入累加器

when I run the Python file it returns:

ModuleNotFoundError: 没有名为 'stuff'

的模块

如果您尝试 运行 测试模块,它会失败,因为它不在@tromgy 解释的路径中。但是,对于 运行 测试,您不需要初始化文件或弄乱 sys.path.

使用 pytest,你不应该 运行 测试模块本身 运行 测试,而是 运行 从命令行使用 `python -m 的 pytest pytest 测试”。只要确保你是 运行ning 从你的项目文件夹,即“tau-intro-to-pytest”。如果你想 运行 一个特定的测试函数,你可以 specify that from the command line as well, but there are good VS Code extensions to do that without writing lengthy command line calls. The python extension has a tests explorer included in it, but I like the UI of Python Test Explorer for VS Code 更好.