Skip to main content
In this article, we extend our testing suite by verifying the retrieval of individual posts. We start by ensuring that unauthorized users are prevented from accessing posts and then validate both valid and invalid post retrieval scenarios using an authorized client. –––––––

Unauthorized Access Tests

First, we verify that an unauthorized user cannot retrieve all posts. The following code snippet demonstrates this test:
Next, we ensure that an unauthorized user cannot access a single post. We use the ID of the first post in our test data. Depending on your data structure, the ID may be accessed as a dictionary key or as an object attribute. Here, we assume it is provided by the SQLAlchemy model as an attribute:
–––––––

Handling Non-Existent Posts

It is essential to confirm that the service returns a 404 error when a request is made for a post which does not exist. In the example below, we simulate a request for a post with an ID that is very unlikely to exist (e.g., 88888):
When running these tests, you might encounter warnings similar to the following. These warnings do not affect the test outcomes.
–––––––

Retrieving a Valid Post

Finally, we test the retrieval of a valid post with an authorized client. The test includes printing the returned JSON response (useful for debugging) and then validating the response against our Pydantic schema. Note that the JSON response contains a “Post” property nested within the returned data; thus, the details are accessed from this nested object.
For your reference, the Pydantic schema for a post is defined as follows:
This configuration ensures that the data returned by SQLAlchemy is compatible with our schema, which is why we access the nested “Post” property in our validation assertions. –––––––

Test Run Summary

When you run the tests with pytest, you will see an output similar to this:
This output confirms that the tests for unauthorized access, handling non-existent posts, and retrieving a valid post are functioning as expected. ––––––– In the next article, we will explore testing the creation of a post.

Watch Video