簡體   English   中英

pytest — 如何使用全局/會話范圍的裝置?

[英]pytest — how do I use global / session-wide fixtures?

我想要一個“全局裝置”(在 pytest 中,它們也可以稱為“會話范圍的裝置”),它可以進行一些昂貴的環境設置,例如通常准備一個資源,然后在測試模塊中重復使用。 設置是這樣的,

共享環境.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

pytest 中有一個約定,它使用名為conftest.py的特殊文件並包含會話裝置。

我提取了兩個非常簡單的例子來快速入門。 他們不使用類。

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

示例 1:

除非作為test_*函數的參數提供,否則不會執行夾具。 夾具some_resource在調用引用函數之前執行,在本例中為test_2 另一方面,終結器在最后執行。

conftest.py:

import pytest
@pytest.fixture(scope="session")

def some_resource(request):
  print('\nSome resource')
 
  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

示例 2:

這里的 fixture 配置了autouse=True ,所以它在會話開始時執行一次,並且不必引用它。 它的終結器在會話結束時執行。

conftest.py:

import pytest
@pytest.fixture(scope="session", autouse=True)

def auto_resource(request):
  print('\nSome resource')
 
  def auto_resource_fin():
    print('\nSome resource fin')

  request.addfinalizer(auto_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

好的,我想我明白了……解決方案是將shared_env.py命名shared_env.py conftest.py

有關詳細信息,請參閱這篇優秀的博客文章 [ http://pythontesting.net/framework/pytest/pytest-session-scoped-fixtures/ ]。 它有一個有效的例子,所以希望如果有必要的話,從那里向后工作不會太難。

暫無
暫無

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

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