我有一个Flask应用程序,正在尝试为其编写单元测试。如果有人想要更多上下文,可以在here中找到源代码。我的项目位于名为be
的文件夹中,其结构如下:
├── __init__.py
├── app.py
├── api
│ ├── __init__.py
│ ├── auth
│ │ ├── __init__.py
│ │ ├── views.py
│ │ ├── tests
│ │ │ ├── __init__.py
│ │ │ ├── test_views.py
views.py
包含我的/login
和/register
端点。使用flask run
运行服务器可以正常工作,并且我可以成功达到这些端点。但是,运行python -m unittest discover
会导致以下控制台输出:
(env) ➜ be git:(master) ./scripts test
python -m unittest
E
======================================================================
ERROR: api.auth.test.test_views (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: api.auth.test.test_views
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 434, in _find_test_path
module = self._get_module_from_name(name)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 375, in _get_module_from_name
__import__(name)
File "/Users/samscheding/projects/vue_tutorials/be/api/auth/test/test_views.py", line 4, in <module>
from be.app import app
ModuleNotFoundError: No module named 'be'
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
我只写了一个测试,基本上是以下内容:
import unittest
from be.app import app
app.testing = True
class TestLogin(unittest.TestCase):
with app.test_client() as client:
... # Do some stuff with the test client
我当前的工作目录位于be/
文件夹中,我在运行flask run
的同一虚拟环境中运行Python3.7.2。我发现this StackOverflow答案有很多信息,但是它建议的主要目的是在每个目录中添加一个__init__.py
,这是我已经完成的。另一个答案说是将目录添加到我的PYTHON_PATH
中,但我不愿意这样做,因为克隆到项目时需要额外的配置。
我知道在尝试进行import be
时会抛出异常,但是我不明白为什么flask run
具有我的be
包的上下文,但是{ {1}}否。我缺少什么信息,有什么解决方案?