pytest的ModuleNotFoundError [英] ModuleNotFoundError with pytest

查看:328
本文介绍了pytest的ModuleNotFoundError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的测试文件夹分开我的应用程序代码。我的项目结构是这样的

I want my tests folder separate to my application code. My project structure is like so

myproject/
  myproject/
    myproject.py
    moduleone.py
  tests/
    myproject_test.py

myproject.py

myproject.py

from moduleone import ModuleOne

class MyProject(object)
....

myproject_test.py

myproject_test.py

from myproject.myproject import MyProject
import pytest

...

我使用 myproject.myproject ,因为我使用了命令

I use myproject.myproject since I use the command

python -m pytest

从项目根目录 ./ myproject /

但是,这些模块中的导入会失败,

However, then the imports within those modules fail with


E ModuleNotFoundError:没有名为'moduleone'的模块

E ModuleNotFoundError: No module named 'moduleone'

我正在运行Python 3.7,并且从3.3开始就读过,空的 __ init __ fil不再需要es,这意味着我的项目成为了隐式命名空间包

I am running Python 3.7 and have read that since 3.3, empty __init__ files are no longer needed which means my project becomes an implicit namespace package

但是,我尝试在 myproject / myproject / 中添加 __ init __。py 文件,并尝试添加 myproject / 中的 conftest.py 文件,但都不起作用

However, I have tried adding an __init__.py file in myproject/myproject/ and also tried adding a conftest.py file in myproject/ but neither works

我有阅读答案,它对弄乱路径,然后在其他问题中对评论说 不接受

I have read answers that say to mess with the paths and then upvoted comments in other questions saying not to.

正确的方法是什么?我想念什么?

What is the correct way and what am I missing?

编辑;

可能相关,我使用了 requirements.txt 通过pip安装pytest。这可能有关吗?如果是这样,在这种情况下安装pytest的正确方法是什么?

Possibly related, I used a requirements.txt to install pytest using pip. Could this be related? And if so, what is the correct way to install pytest in this case?

编辑2:

sys.path 中的路径之一是 / usr / src / app / 排成 / my / local / path / myproject / 的docker卷。

One of the paths in sys.path is /usr/src/app/ which is a docker volume lined to /my/local/path/myproject/.

该卷应为<$ c是$ c> / my / local / path / myproject / myproject / ?

推荐答案

$ PYTHONPATH env变量中包含点。

Be sure to include . dot in the $PYTHONPATH env var.

您可以使用此代码段调试此类问题:

You can use this code fragment to debug such issues:

import pprint
import sys
pprint.pprint(sys.path)

您的问题设法使用了 myproject 处于三个不同级别。至少在调试过程中,您可能需要使用三个不同的名称,以减少可能的混淆。

Your question managed to use myproject at three different levels. At least during debugging you might want to use three distinct names, to reduce possible confusion.

这篇关于pytest的ModuleNotFoundError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆