官术网_书友最值得收藏!

Defining the pytest fixtures

Fixtures are used in pytest to prepare the context in which a test should be executed, preparing it and cleaning it at the end. The application fixture is expected by pytest-flask, as seen in the documentation. The plugin generates a client fixture that we can use to send requests in test mode. We see this fixture in action in the thoughts_fixture fixture, which generates three thoughts through the API and deletes everything after our test has run. 

The structure, simplified, is as follows:

  1. Generate three thoughts. Store its thought_id:
@pytest.fixture
def thought_fixture(client):

thought_ids = []
for _ in range(3):
thought = {
'text': fake.text(240),
}
header = token_validation.generate_token_header(fake.name(),
PRIVATE_KEY)
headers = {
'Authorization': header,
}
response = client.post('/api/me/thoughts/', data=thought,
headers=headers)
assert http.client.CREATED == response.status_code
result = response.json
thought_ids.append(result['id'])
  1. Then, add yield thought_ids to the test:
yield thought_ids
  1. Retrieve all thoughts and delete them one by one:
# Clean up all thoughts
response = client.get('/api/thoughts/')
thoughts = response.json
for thought in thoughts:
thought_id = thought['id']
url = f'/admin/thoughts/{thought_id}/'
response = client.delete(url)
assert http.client.NO_CONTENT == response.status_code

Note that we use the faker module to generate fake names and text. You can check its full documentation at https://faker.readthedocs.io/en/stable/. It is a great way of generating random values for your tests that avoid reusing test_user and test_text over and over. It also helps to shape your tests, by checking the input independently and not blindly copying a placeholder.

Fixtures can also exercise your API. You can choose a lower-level approach such as writing raw information in your database, but using your own defined API is a great way of ensuring that you have a complete and useful interface. In our example, we added an admin interface that's used to delete thoughts. This is exercised throughout the fixture as well as the creation of thoughts for a whole and complete interface.

This way, we also use tests to validate that we can use our microservice as a complete service, without tricking ourselves into hacking our way to perform common operations.

Also note the usage of the client fixture, which is provided by pytest-flask.

主站蜘蛛池模板: 深泽县| 上高县| 安塞县| 高雄县| 麻江县| 博爱县| 尼勒克县| 金沙县| 张家港市| 徐汇区| 孟村| 泊头市| 余江县| 攀枝花市| 新昌县| 保山市| 密山市| 天等县| 怀来县| 察雅县| 东丰县| 大洼县| 婺源县| 津市市| 个旧市| 若尔盖县| 清镇市| 榆中县| 安新县| 西吉县| 商都县| 明水县| 金川县| 洛宁县| 海盐县| 大同县| 栾川县| 安新县| 铜川市| 荣昌县| 舞钢市|