Sử Dụng Bộ Nhớ Đệm Trong Pytest Để Quản Lý Trạng Thái Xuyên Qua Các Lần Chạy

Cách Sử Dụng

Pytest cung cấp hai tùy chọn dòng lệnh để chạy lại các test thất bại:

  • --lf, --last-failed: Chỉ chạy lại các test thất bại
  • --ff, --failed-first: Chạy test thất bại trước, sau đó đến các test còn lại

Để xóa bộ nhớ đệm, sử dụng --cache-clear. Các plugin khác có thể truy cập đối tượng config.cache để lưu trữ dữ liệu JSON giữa các lần chạy.

Chạy Lại Test Thất Bại

# test_data.py
import pytest

@pytest.mark.parametrize("index", range(50))
def test_value(index):
    if index in (7, 15):
        pytest.fail("unexpected error")

Sau lần chạy đầu tiên, sử dụng --lf để chỉ chạy lại test thất bại:

$ pytest --lf
collected 50 items / 48 deselected / 2 selected
run-last-failure: rerun previous 2 failures

Với --ff, test thất bại sẽ chạy trước:

$ pytest --ff
run-last-failure: rerun previous 2 failures first

Hành Vi Khi Không Có Test Thất Bại

pytest --last-failed --last-failed-no-failures all   # Chạy tất cả test
pytest --last-failed --last-failed-no-failures none  # Không chạy test

Đối Tượng config.cache

# test_cache.py
import pytest

def heavy_calculation():
    print("Performing complex operation...")

@pytest.fixture
def app_data(request):
    data = request.config.cache.get("app/data", None)
    if data is None:
        heavy_calculation()
        data = 100
        request.config.cache.set("app/data", data)
    return data

def test_validation(app_data):
    assert app_data == 50

Kiểm Tra Và Xóa Bộ Nhớ Đệm

Xem nội dung bộ nhớ đệm:

$ pytest --cache-show

Xóa toàn bộ bộ nhớ đệm:

$ pytest --cache-clear

Sửa Lỗi Từng Bước

pytest --stepwise      # Dừng sau lỗi đầu tiên
pytest --sw --sw-skip  # Bỏ qua lỗi hiện tại

Hỗ Trợ unittest.TestCase

Chạy test unittest:

pytest test_module.py

Tính năng hỗ trợ:

  • Các decorator @unittest.skip
  • setUp/tearDown
  • setUpClass/tearDownClass

Tích Hợp Pytest Fixture Vào unittest

# conftest.py
import pytest

@pytest.fixture(scope="class")
def resource_setup(request):
    class TestResource: pass
    request.cls.res = TestResource()

# test_integration.py
import unittest
import pytest

@pytest.mark.usefixtures("resource_setup")
class IntegrationTest(unittest.TestCase):
    def test_feature(self):
        assert hasattr(self, "res")

Sử Dụng autouse Fixture

class SystemTest(unittest.TestCase):
    @pytest.fixture(autouse=True)
    def setup_env(self, tmpdir):
        tmpdir.chdir()
        tmpdir.join("config.cfg").write("# settings")
    
    def test_config(self):
        with open("config.cfg") as f:
            assert "settings" in f.read()

Thẻ: pytest Caching unittest test-run fixture

Đăng vào ngày 31 tháng 5 lúc 03:50