Last active
April 26, 2021 21:36
-
-
Save hectorcanto/a57d5ff2c0a043a3626afae245793461 to your computer and use it in GitHub Desktop.
[Conftest example with fixtures] A Pytest conftest example with a function scoped fixture, with autouse. The code will be executed after every function, since it only has logic after the yield. #python #pytest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment