py导入包异常跳出_Python运行Unittest作为包导入错误
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內.但是還有另一種方法可以解決這個問題嗎?
為了完整起見,在運行應用程序時,__ main__的打印語句為:
models : models.transactions
resources: resources.transactions
app : __main__
這是預期的,并且不會嘗試導入高于/ sandbox / app或橫向的導入.
IV.附錄
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)resources.transactions:
from models.transactions import TransactionsModel
print ' resources: ', __name__
class Transactions:
pass
(4)tests.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()
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的py导入包异常跳出_Python运行Unittest作为包导入错误的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: row间距 table 某一行_UITa
- 下一篇: 进行DLL注入的三种方法