首页 文章

pytest - 如何使用全局/会话范围的灯具?

提问于
浏览
2

我希望有一个“全局固定”(在pytest中它们也可以称为“会话范围固定装置”),它执行一些昂贵的环境设置,例如通常准备资源,然后在测试模块之间重复使用 . 设置是这样的,

shared_env.py

会有一个夹具做一些昂贵的东西,比如启动Docker容器,MySQL服务器等 .

@pytest.yield_fixture(scope="session")
def test_server():
    start_docker_container(port=TEST_PORT)
    yield TEST_PORT
    stop_docker_container()

test_a.py

会使用服务器,

def test_foo(test_server): ...

test_b.py

会使用相同的服务器

def test_foo(test_server): ...

似乎pytest通过 scope="session" 支持这个,但我无法弄清楚如何使实际的导入工作 . 当前设置将给出错误消息,如,

fixture 'test_server' not found
available fixtures: pytestconfig, ...
use 'py.test --fixtures [testpath] ' for help on them

2 回答

  • 5

    pytest中有一个约定,使用名为 conftest.py 的特殊文件并将会话装置放入其中 .

    我已经提取了2个非常简单的例子来快速启动 . 他们不使用课程 .

    一切都取自http://pythontesting.net/framework/pytest/pytest-session-scoped-fixtures/

    Example 1:

    除非使用夹具,否则不执行夹具 . 如果未使用,则不会执行 . 如果使用固定装置,则在结束时执行终结器 .

    conftest.py:

    import pytest
    @pytest.fixture(scope="session")
    
    def some_resource(request):
      print('\nSome recource')
    
      def some_resource_fin():
        print('\nSome resource fin')
    
      request.addfinalizer(some_resource_fin)
    

    test_a.py:

    def test_1():
      print('\n Test 1')
    
    def test_2(some_resource):
      print('\n Test 2')
    
    def test_3():
      print('\n Test 3')
    

    结果:

    $ pytest -s
    ======================================================= test session starts ========================================================
    platform linux -- Python 3.4.3 -- py-1.4.26 -- pytest-2.7.0
    rootdir: /tmp/d2, inifile: 
    collected 3 items 
    
    test_a.py 
     Test 1
    .
    Some recource
    
     Test 2
    .
     Test 3
    .
    Some resource fin
    

    Example 2:

    夹具配置为autouse = True,因此它在会话开始时执行一次,并且不必调用它 . 它的终结器在会话结束时执行 .

    conftest.py:

    import pytest
    @pytest.fixture(scope="session", autouse=True)
    
    def some_resource(request):
      print('\nSome recource')
    
      def some_resource_fin():
        print('\nSome resource fin')
    
      request.addfinalizer(some_resource_fin)
    

    test_a.py:

    def test_1():
      print('\n Test 1')
    
    def test_2():
      print('\n Test 2')
    
    def test_3():
      print('\n Test 3')
    

    结果:

    $ pytest -s
    ======================================================= test session starts ========================================================
    platform linux -- Python 3.4.3 -- py-1.4.26 -- pytest-2.7.0
    rootdir: /tmp/d2, inifile: 
    collected 3 items 
    
    test_a.py 
    Some recource
    
     Test 1
    .
     Test 2
    .
     Test 3
    .
    Some resource fin
    
  • 3

    好吧,我想我明白了...解决方案就是命名 shared_env.py conftest.py

    有关详细信息,请参阅此博客文章[http://pythontesting.net/framework/pytest/pytest-session-scoped-fixtures/] . 它有一个工作的例子,所以如果有必要,希望不要太难从那里倒退 .

相关问题