【发布时间】:2018-06-04 18:21:54
【问题描述】:
我。前言:应用目录结构和模块在文末列出。
二。问题陈述:如果未设置 PYTHONPATH 应用程序运行,但单元测试失败并出现 ImportError: No module named models.transactions。尝试导入时会发生这种情况
app.py 中的事务。如果 PYTHONPATH 设置为 /sandbox/app 应用程序和
unittest 运行没有错误。解决方案的限制是不必设置 PYTHONPATH,并且
sys.path 不必以编程方式修改。
三。详细信息:考虑设置 PYTHONPATH 并且 test_app.py 作为包 /sandbox$ python -m unittest tests.test_app 运行的情况。查看__main__ 的打印语句
贯穿整个代码:
models : app.models.transactions
models : models.transactions
resources: app.resources.transactions
app : app.app
test : tests.test_app
单元测试首先导入应用程序,因此有app.models.transactions。该应用程序的下一个导入
尝试是resources.transactions。当它被导入时,它会自己导入models.transactions,并且
然后我们看到__name__ 对应app.resources.transactions。紧随其后的是app.app
导入,最后是单元测试模块tests.test.app。设置 PYTHONPATH 允许应用程序解析 models.transactions!
一种解决方案是将models.transactions 放在resources.transaction 中。但是还有另一种方法来处理这个问题吗?
为了完整起见,当应用程序运行时,__main__ 的打印语句为:
models : models.transactions
resources: resources.transactions
app : __main__
这是意料之中的,并且不会尝试高于/sandbox/app 或横向的导入。
四。附录
A.1 目录结构:
|-- sandbox
|-- app
|-- models
|-- __init__.py
|-- transactions.py
|-- resources
|-- __init__.py
|-- transactions.py
|-- __init__.py
|-- app.py
|-- tests
|-- __init__.py
|-- test_app.py
A.2 模块:
(1) 应用程序:
from flask import Flask
from models.transactions import TransactionsModel
from resources.transactions import Transactions
print ' app : ', __name__
def create_app():
app = Flask(__name__)
return app
app = create_app()
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000, debug=True)
(2) 模型.事务
print ' model : ', __name__
class TransactionsModel:
pass
(3) 资源.事务:
from models.transactions import TransactionsModel
print ' resources: ', __name__
class Transactions:
pass
(4) 测试.test_app
import unittest
from app.app import create_app
from app.resources.transactions import Transactions
print ' test : ', __name__
class DonationTestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_transactions_get_with_none_ids(self):
self.assertEqual(0, 0)
if __name__ == '__main__':
unittest.main()
【问题讨论】:
标签: python python-import importerror python-unittest pythonpath