'Parameterized test using fixture with yield. Fixture doesn't run cleanup code after yield
I have a fixture that inserts the data in DB and removes it after yield
@pytest.fixture
def add_marketplace_ts(session: Session):
marketplace = Marketplace(
name="themeselection",
support_duration=148,
purchase_verification_url="https://google.com",
)
session.add(marketplace)
session.commit()
session.refresh(marketplace)
yield marketplace
session.delete(marketplace)
session.commit()
I have a test which uses this function but that test is parameterized:
@pytest.mark.parametrize(
"endpoint",
[
"/github/access-form",
"/github/issue-form",
],
)
def test_marketplace_return(
client: TestClient, session: Session, endpoint: str, add_marketplace_ts: Marketplace
):
r = client.get(endpoint)
assert r.status_code == 200
data = r.json()
assert data["marketplaces"] == IsList(
IsPartialDict(
id=1,
name="themeselection",
purchase_verification_url="https://google.com",
)
)
assert data["brands"] == []
assert data["product_w_technology_name"] == []
When I run the above test it calls the fixture twice but it doesn't run code written after yield once the first execution is complete. This results in the same record being inserted twice and raises error (DB unique error).
How can I let pytest run the code after yield in fixture on each execution regardless of the number of parameters provided by the test function?
Solution 1:[1]
Sorry, this was my mistake.
This is because when you insert the data in DB its id is autoincremented and the second time when data is inserted its id is 2 which makes test fail even if the first row is deleted.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JD Solanki |
