簡體   English   中英

使用py.test以編程方式收集或創建測試

[英]Programmatically collecting or creating tests with py.test

我正在編寫一個pytest插件來運行它們之前訂購測試。 我想要一個更好的方法來為我的插件編寫測試。

我正在使用pytest的pytest_collection_modifyitems 鈎子 ,然后根據某些標記就地修改items 測試這個的最簡單方法是獲得pytest測試的輸入列表,將它們傳遞給我的函數,並聲明輸出的順序正確。

我無法收集或創建輸入測試列表。 輸入測試應該與pytest作為items傳遞給pytest_collection_modifyitems鈎子的格式相同,即它們應該是_pytest.python.Function實例,並定義了適當的標記。

我將接受以下任何一種方法的答案:1)在給定現有Python模塊的情況下收集測試,或2)以編程方式創建_pytest.python.Function實例, _pytest.python.Function實例看起來像傳遞給pytest_collection_modifyitems鈎子的pytest_collection_modifyitems 任何可以輕松生成測試數據的東西。

我建議你使用testdir fixture進行更高級別的測試,這對pytest插件很常見,可以通過pytester插件獲得:

pytest_plugins = "pytester"


def test_something(testdir):
    """Test some thing."""
    testdir.makepyfile("""
        import pytest

        @pytest.mark.some
        def test_some():
            assert True

        @pytest.mark.some_thing_else
        def test_some_thing_else():
            assert True
    """)
    result = testdir.runpytest('-vv')
    assert result.stdout.lines[-4:-2] == [
        u'test_something.py::test_some PASSED',
        u'test_something.py::test_some_thing_else PASSED'
    ]

因此,您可以輕松地在源中進行多個測試及其標記的排列,並通過斷言輸出行來確定實際排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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