Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- This example has not been tested. Use it as a reference only.
- """
- import psycopg2
- import pytest
- USER = "postgres"
- PASS = None
- HOST = "localhost"
- PORT = 5432
- DATABASE = "my_schema"
- TABLE = "my_table"
- CREATE_DB = "CREATE DATABASE %s;"
- TRUNCATE = "TRUNCATE TABLE %s CASCADE"
- DROP_DB = "DROP DATABASE %s;"
- # A simple fixture
- def db_conf():
- return dict(user=USER, password=PASS, host=HOST, port=PORT)
- # __create_db and _drop_db should come from another package or from a library
- def _create_db(configuration):
- connection = psycopg2.connect(**configuration)
- connection.autocommit = True
- try:
- connection.cursor().execute(CREATE_DB, [psycopg2.extensions.AsIs(DATABASE)])
- except Exception as error:
- if not hasattr(error, "pgerror") or "already exists" not in error.pgerror:
- raise error
- print("Database '%s' already exists.", DATABASE)
- connection.close()
- def _drop_db(configuration):
- connection = psycopg2.connect(**configuration)
- connection.autocommit = True
- try:
- connection.cursor().execute(DROP_DB, [psycopg2.extensions.AsIs(DATABASE)])
- except Exception as error:
- if not hasattr(error, "pgerror") or "already exists" not in error.pgerror:
- raise error
- print("Database '%s' already exists.", DATABASE)
- connection.close()
- @pytest.fixture(scope="session", autouse=True)
- def test_db(db_conf):
- """
- This fixture will be executed once in the entire suite, independently of the filters you use
- running pytest. It will create the test_db at the beginning and droping the table at the end
- of all tests.
- """
- _create_db(**db_conf)
- yield
- _drop_db(**db_conf)
- # A function scoped fixture
- @pytest.fixture(scope="function", autouse=True)
- def clear_tables(db_conf):
- """
- This fixture will be executed after every test, clearing the
- given table.
- You can remove the autouse, and specify when it executed whenever you want.
- """
- yield
- connection = psycopg2.connect(**db_conf)
- connection.autocommit = True
- connection.cursor().execute(TRUNCATE, [psycopg2.extensions.AsIs(TABLE)])
- connection.close()
Add Comment
Please, Sign In to add comment