Create and delete users before and after each API integration test

  • There are endpoints in a simplified form on the server:

    GET / users
    POST / users - create a user
    GET / users / {id}
    DELETE / users / {id}

    Server and client are on the same server. They have a common database for testing sqlite. Let's say I have a test for each endpoint. In each test, an http request is sent to the endpoint using the http client, as if it were a consumer (consumer), and the response is checked for correctness. Before the very beginning of the tests, an empty database is created and the migration is rolled. After finishing the tests, the database is deleted.

    My problem is that before each test I need to create 7 users with fake data. And after the test, so that they are "deleted".

    First, I did the database through transactions, the test starts and a transaction is started on the client, 7 users are created, in the test there is an http request for GET / users, but there is no transaction on the server and an empty database. Therefore, this option is eliminated.

    If you do without a transaction, then shared database data is the same on the client and the server due to the fact, but I need only 7 users before each test so that previous manipulations with the database do not distort the data. Therefore, this option is also eliminated.

    I tried the option where the database is deleted and migrated before each test. It works but for a very long time (it takes a minute to check 4 endpoints). Database in memory would speed up a lot here, but here is the same problem as with a transaction.

    I just can't find a solution. What can you advise? I want to test all endpoints not through functional tests inside the code, but as if from the outside (as an interface is tested using selenium).

  • I had a similar situation in one of the projects. A separate test database is created before starting the tests and the structure of the prod database is copied into it and filled with fake data. Then it is removed.

    Tests use a mock object to work with a database, where a test database is substituted instead of a prod.

    Sometimes you need to run non-destructive tests on existing records in a prod or stage database; or if it is not convenient to update the test data - you can switch the used database.

Suggested Topics