Here’s a look at how PyTest’s fixtures are used in real life.

Fixture the most I’ve used for fixtures is to write setup and teardown, so now there’s a use case for testing a list interface that parameterizes different state values to pass arguments for testing.

So for the setup and teardown of this use case, I’m going to insert the test data in different states into setup, and when the test is done, I’m going to erase the inserted data in the Teardown.

A, the setup

But when I’m inserting data, I don’t want to insert all the states at once. For example, if 1,2,3,4, and 5 have five states, I want to perform 1 to insert the data in state 1, and when the test is complete, delete the data that was inserted, and so on.

So, here we still need to use an effect of parameter passing, which is also described in the previous article, if you are interested in it, I will not repeat it here.

@pytest.fixture(params=[1, 2, 3, 4, 5]) def init_allot_task_status(request): status = request.param db = DB() insert_allot_task_sql = """ INSERT INTO purchase_allot (`id`, `allot_sn`... ) Format (10000086, status) db. Exec_sql (insert_allot_task_sql) yield status Use delete_SQL = "DELETE from SM_purchase_allot WHERE ID = {}" for test cases. Format (10000086) print(" Execute delete-sql: ", delete_sql) db.exec_sql(delete_sql) db.close()Copy the code

Before yield, all you really do is insert data, and yield the parameters that Request. param takes out for use by the test case.

Second, the teardown

After yield, delete the data that was previously inserted. For convenience, I used a separate id for the inserted test data, so I can delete the data with that ID.

Take a look at the test cases

def test_allot_list_query_by_status(init_allot_task_status): List queries that test different states are parameterized in fixtures 1- pending, 2- processing, 3- shipped, 4- completed, and 5 canceled. """ Payload = {"status": Init_allot_task_status} # Since the yield in the fixture returns the argument, R = requests. Post (QA_URL + API_URL, json=payload, headers=HEADER) result = r.json() assert result["result"] == "ok" assert result["errmsg"] == "success" assert Result ["row"]["taskListOfPage"]["resultData"][0]["status"] == init_allot_task_status #Copy the code

Pass the fixture init_allot_task_status into the test case so that the fixture method is executed at case execution, and the fixture method is parameterized and returned to the test case each time it is used. Used by test cases to initiate requests, assertions, and so on.

Three, test

By executing the test case, you can see the final run:



Parameters are executed separately, and test data is inserted and deleted at the beginning and end of the corresponding test case.