FatSnake
FatSnake

Reputation: 93

What are the best practices for testing a FastAPI project with JWT authentication?

I have FastAPI project which does the following:

  1. Register users(unauthenticated)
  2. CRUD operations on user resources(authenticated)

What I want to do:

  1. Develop an automated testing framework to unit test all the APIs
  2. Run that on a devops platform like jenkins regularly
  3. Run it locally before deployment

Some specific doubts I have:

  1. For testing, should I use the OpenAPI generated client sdk or the FastAPI client or use the python requests module?
  2. Authentication should happen only once and reuse the JWT token or fresh authentication for each API test ?
  3. Should I use the same pydantic modules for dev and testing or re-write them to ensure that no issues were introduced in case of updated models ?
  4. How to do proper unit testing when one API requires result from multiple other APIs?

Upvotes: 2

Views: 5406

Answers (1)

MatsLindh
MatsLindh

Reputation: 52852

  1. Use the built-in TestClient

  2. Use a fixture and let pytest sort it out for you; if it's too slow to reauthenticate each time, change the scope of the fixture to a larger scope (i.e. class, module, session, etc.). You can also use FastAPI's dependency_overrides to let your tests run with static authentication configured (so that you can skip actually authenticating in most of your tests).

  3. You should test what you use in your application. Nothing specific written for your tests, except if necessary to make your application testable in a better way.

  4. The only "proper" thing is that your API has been tested to work as you expect it to work. Do multiple API calls if necessary, but move them into fixtures to get composable sets of dependencies for tests (i.e. the result of the fixture can be cached and re-used for all tests in a test class if necessary). If you have tests that depend on a customer being created, create a fixture that creates a customer and use that fixture in the tests where a created customer is necessary.

Upvotes: 5

Related Questions