![](/img/trans.png)
[英]Using Python's `unittest` module to compose tests of functions in a separate file
[英]How to run initialization code before tests when using Python's unittest module as a testrunner?
在運行庫提供的測試之前,庫的用戶如何運行自己的初始化代碼(例如設置記錄器的調試級別)? Python的unittest
模塊用作測試人員。
您可以嘗試使用pytest來運行單元測試。 如果可行(許多基於單元測試的測試套件工作),那么你可以創建一個小模塊,例如“mymod.py”,定義一個pytest配置鈎子:
# content of mymod.py
def pytest_configure():
import logging
logging.getLogger().setLevel(logging.WARN)
如果您現在執行py.test,如下所示:
$ py.test -p mymmod --pyargs mylib
然后將搜索“mylib”包以進行測試,並在運行它們之前修改日志記錄級別。 “-p”選項指定要加載的插件,“ - pygs”告訴pytest首先嘗試導入參數,而不是將它們視為目錄或文件名(默認值)。
有關詳細信息,請訪問: http : //pytest.org和http://pytest.org/latest/unittest.html
HTH,holger
類似問題的回答在這里更有幫助:
我用python setUpClass方法https://docs.python.org/2/library/unittest.html#unittest.TestCase.setUpClass
setUpClass()
A class method called before tests in an individual class are run. setUpClass is called with the class as the only argument and must be decorated as a classmethod():
@classmethod
def setUpClass(cls):
...
我像這樣運行我的測試:
python -m unittest discover -v
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.