简体   繁体   English

使用py.test以编程方式收集或创建测试

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

I am writing a pytest plugin to order your tests before running them. 我正在编写一个pytest插件来运行它们之前订购测试。 I want a better way to write tests for my plugin. 我想要一个更好的方法来为我的插件编写测试。

I am using pytest's pytest_collection_modifyitems hook , and then modifying items in-place based on certain markers. 我正在使用pytest的pytest_collection_modifyitems 钩子 ,然后根据某些标记就地修改items The easiest way to test this would be to have an input list of pytest tests, pass them to my function, and assert that the output is in the correct order. 测试这个的最简单方法是获得pytest测试的输入列表,将它们传递给我的函数,并声明输出的顺序正确。

I am having trouble collecting or creating the input test lists. 我无法收集或创建输入测试列表。 The input tests should be in the same format that pytest will pass in as items to the pytest_collection_modifyitems hook, ie they should be instances of _pytest.python.Function with appropriate markers defined. 输入测试应该与pytest作为items传递给pytest_collection_modifyitems钩子的格式相同,即它们应该是_pytest.python.Function实例,并定义了适当的标记。

I will accept answers for either 1) collecting the tests given an existing Python module, or 2) programmatically creating _pytest.python.Function instances that look like what would be passed to the pytest_collection_modifyitems hook. 我将接受以下任何一种方法的答案:1)在给定现有Python模块的情况下收集测试,或2)以编程方式创建_pytest.python.Function实例, _pytest.python.Function实例看起来像传递给pytest_collection_modifyitems钩子的pytest_collection_modifyitems Anything that makes it easy to generate test data. 任何可以轻松生成测试数据的东西。

I'd suggest you to go with higher level testing approach using testdir fixture, which is common for pytest plugins and available via pytester plugin: 我建议你使用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'
    ]

so you can easily have multiple permutations of tests and their markers in the source and by asserting the output lines you assert the actual ordering. 因此,您可以轻松地在源中进行多个测试及其标记的排列,并通过断言输出行来确定实际排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM