mirror of
https://github.com/xorcare/testing-go-code-with-postgres.git
synced 2024-12-24 16:28:34 +02:00
b98187650e
Sometimes tests terminate fatally and databases are not deleted and you want to understand which test left garbage behind. It is also in the future it will be possible to add the ability not to delete databases for tests that ended with an error, and it will be necessary to understand from which test the database. Therefore, the generation of the database name from the name of the test with the addition of a unique identifier so that the names do not overlap. Reports the maximum identifier length. It is determined as one less than the value of NAMEDATALEN when building the server. The default value of NAMEDATALEN is 64; therefore the default max_identifier_length is 63 bytes, which can be less than 63 characters when using multibyte encodings. See https://www.postgresql.org/docs/15/runtime-config-preset.html PostgreSQL allows you to create any number of databases at a given site. Database names must have an alphabetic first character and are limited to 63 bytes in length. A convenient choice is to create a database with the same name as your current user name. Many tools assume that database name as the default, so it can save you some typing. To create that database, simply type: See https://www.postgresql.org/docs/15/tutorial-createdb.html
2.9 KiB
2.9 KiB
Example of testing Go code with Postgres
The example suggests a solution to the problem of cleaning the database after running tests and the problem of running tests in parallel. It also shows how to organize integration testing of Go code with Postgres.
What's interesting here?
- Example of docker-compose.yml with multiple databases and automated migrations.
- Example of test database connection management in testingpg package.
- Example of integration tests.
- And example of GitHub Actions and Gitlab CI.
Generating human-readable database names from t.Name()
to simplifying problem investigation.
The last 8 characters are a short unique identifier needed to prevent name collision, its necessary
because the maximum length of the name is 63 bytes, and the name must be unique.
TestNewPostgres-Changes-are-not-visible-in-different-inWirPQD7J
TestNewPostgres-Changes-are-not-visible-in-different-ineYp0ljjI
TestNewPostgres-Successfully-connect-by-URL-and-get-verzGq4pGza
TestNewPostgres-Successfully-obtained-a-version-using-a20YgZaMf
TestNewPostgres-URL-is-different-at-different-instancesIMDkJgoP
TestNewPostgres-URL-is-different-at-different-instancesjtSsjPR5
TestUserRepository-CreateUser-Cannot-create-a-user-withmgmHFdZe
TestUserRepository-CreateUser-Successfully-created-a-UspTBGNltW
TestUserRepository-ReadUser-Get-an-error-if-the-user-doRqS1GvYh
How to use
Run make test-env-up test
and then everything will happen by itself.
Disclaimer
This example is not an example of software architecture!