簡體   English   中英

當使用Python的unittest模塊作為testrunner時,如何在測試之前運行初始化代碼?

[英]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.orghttp://pytest.org/latest/unittest.html

HTH,holger

您可以在調用unittest.main之前完成設置工作。

或者您可以繼承測試套件並運行類級別的安裝方法

或者您可以讓測試設置包含對用戶定義的設置方法的回調。

類似問題的回答在這里更有幫助:

如何在python中的每個單元測試之前和之后運行特定代碼

我用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM