Skip to content Skip to sidebar Skip to footer

Testing Postgres Db Python

I don't understand how to test my repositories. I want to be sure that I really saved object with all of it parameters into database, and when I execute my SQL statement I really

Solution 1:

The best solution for this is to use the testing.postgresql module. This fires up a db in user-space, then deletes it again at the end of the run. You can put the following in a unittest suite - either in setUp, setUpClass or setUpModule - depending on what persistence you want:

import testing.postgresql

defsetUp(self):
    self.postgresql = testing.postgresql.Postgresql(port=7654)
    # Get the url to connect to with psycopg2 or equivalentprint(self.postgresql.url())

deftearDown(self):
    self.postgresql.stop()

If you want the database to persist between/after tests, you can run it with the base_dir option to set a directory - which will prevent it's removal after shutdown:

name = "testdb"
port = "5678"
path = "/tmp/my_test_db"
testing.postgresql.Postgresql(name=name, port=port, base_dir=path)

Outside of testing it can also be used as a context manager, where it will automatically clean up and shut down when the with block is exited:

with testing.postgresql.Postgresql(port=7654) as psql:
    # do something here

Post a Comment for "Testing Postgres Db Python"