I.前言:应用程序的目录结构和模块在文章末尾列出.
二.问题陈述:如果未设置PYTHONPATH,则应用程序运行,但是单元测试失败,并出现ImportError:没有名为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.导入时,它会自己导入model.transactions和
然后我们看到__name__代表app.resources.transactions.其次是app.app
导入,最后是unittest模块tests.test.app.设置PYTHONPATH允许应用程序解析模型.
一种解决方案是将model.transactions放入resources.transaction内.但是还有另一种方法可以解决这个问题吗?<