fixture特性
夾具是在測試中用于提供共享資源、設置測試環境或模擬行為的工具。
1. 可以重復使用,多個用例可以使用同一個fixture
2. 一個測試用例可以使用多個裝置
import pytest
# Arrange
@pytest.fixture
def first_entry():return "a"# Arrange
@pytest.fixture
def second_entry():return 2# Arrange
@pytest.fixture
def order(first_entry, second_entry):return [first_entry, second_entry]
2.1 如果多個裝置存在yield,則是先進后出
import pytest@pytest.fixture
def a():print("hello")yieldprint("this is a")@pytest.fixture
def b():print("world")yieldprint("this is b")def test_demo(a, b):print("this is test_demo")if __name__ == '__main__':pytest.main(["-sv", "test1.py"])
3. fixture的返回值不需要接收
- 如果一個fixture存在返回值,那么可以通過
函數名
直接使用其返回值
,如下所示:
import pytest
@pytest.fixture
def first_entry():return "a"def test_a(first_entry):print(first_entry)if __name__ == '__main__':pytest.main(["-sv","test1.py"])
4. fixfure多重嵌套
- 如下
append_first
、test_string_only
并且此fixture緩存即order,根據gpt即我的測試
如果一個 fixture 被請求了多次,但它的作用范圍是函數級別(默認),那么這個 fixture 在每次請求時都會重新執行一次,而不會緩存。這會導致每次請求獲得的數據都是獨立的,不受前一次請求的影響。
所以一般不要使用緩存,保證起獨立性
import pytest# Arrange
@pytest.fixture
def first_entry():return "a"# Arrange
@pytest.fixture
def order():return []# Act
@pytest.fixture
def append_first(order, first_entry):order.append(first_entry)return orderdef test_string_only(append_first, order, first_entry):# Assertprint(append_first) # ['a']print(order) ['a']assert order == [first_entry]pytest.main(["-sv", "test1.py"])
5自動使用fixture,不需要請求
- 設置和清理環境、全局配置,例如數據庫連接、日志設置等可以使用,筆者用的不多
import pytest@pytest.fixture
def first_entry():return "a"@pytest.fixture(autouse=True)
def order():return "hello world"def test_a(order):print(order)pytest.main(["-sv", "test1.py"])