Trung BìnhPython iconPython

pytest fixtures — `scope` hoạt động thế nào?

Fixture scope xác định fixture được tạo và destroy khi nào: function (default) — mỗi test; class — mỗi test class; module — mỗi module; session — toàn bộ test session.

python
@pytest.fixture(scope="session")
def db_engine():   # Tạo 1 lần cho toàn bộ session
    engine = create_engine(TEST_URL)
    Base.metadata.create_all(engine)
    yield engine
    Base.metadata.drop_all(engine)

@pytest.fixture      # scope="function" — mỗi test
def db(db_engine):
    connection = db_engine.connect()
    transaction = connection.begin()
    session = Session(bind=connection)
    yield session
    session.close()
    transaction.rollback()  # Rollback sau mỗi test — isolation

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python