### Connect to PostgreSQL with Custom Parameters Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Example of connecting to a PostgreSQL database using custom connection parameters. ```python password="secret_password", ): with psycopg.connect( dbname="my_custom_db", user=postgresql_proc.user, host=postgresql_proc.host, port=postgresql_proc.port, password="secret_password", ) as conn: # use connection pass ``` -------------------------------- ### Install pytest-postgresql Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Install the plugin using pip. Ensure you also install psycopg version 3. ```sh pip install pytest-postgresql ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/CONTRIBUTING.rst Use pipenv to install development dependencies for the project. ```bash pipenv install --dev ``` -------------------------------- ### Define a load function for initial database state Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Example of defining a load function to set up the initial state of a database, including table creation and data insertion. ```python import psycopg from pytest_postgresql import factories def load_database(**kwargs): with psycopg.connect(**kwargs) as conn: with conn.cursor() as cur: cur.execute("CREATE TABLE stories (id serial PRIMARY KEY, name varchar);") cur.execute("INSERT INTO stories (name) VALUES ('Silmarillion'), ('The Expanse');") postgresql_proc = factories.postgresql_proc(load=[load_database]) postgresql = factories.postgresql("postgresql_proc") def test_stories(postgresql): with postgresql.cursor() as cur: cur.execute("SELECT count(*) FROM stories") assert cur.fetchone()[0] == 2 ``` -------------------------------- ### Connect to PostgreSQL in Docker with pytest-postgresql Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Example of using the postgresql_noproc fixture to connect to a PostgreSQL instance running in Docker. ```python from pytest_postgresql import factories postgresql_in_docker = factories.postgresql_noproc() postgresql = factories.postgresql("postgresql_in_docker", dbname="test") def test_docker(postgresql): with postgresql.cursor() as cur: cur.execute("SELECT 1") ``` -------------------------------- ### Basic Test with postgresql Fixture Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Use the `postgresql` fixture in your tests to get a connected `psycopg.Connection` object. It manages connections and drops the test database after each test. ```python def test_example(postgresql): """Check main postgresql fixture.""" with postgresql.cursor() as cur: cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);") postgresql.commit() ``` -------------------------------- ### Pre-populate Database with SQL Files and Functions Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Configure the process fixture to load schema and data from SQL files or callable functions for pre-populating databases. This speeds up tests by cloning a template database. ```python from pathlib import Path postgresql_my_proc = factories.postgresql_proc( load=[ Path("schemafile.sql"), "import.path.to.function", load_this_callable ]) ``` -------------------------------- ### Create Custom Process and Client Fixtures Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Define custom fixtures using factories for independent configuration of PostgreSQL process and client connections. ```python from pytest_postgresql import factories # Create a custom process fixture postgresql_my_proc = factories.postgresql_proc( port=None, unixsocketdir='/var/run') # Create a client fixture that uses the custom process postgresql_my = factories.postgresql('postgresql_my_proc') ``` -------------------------------- ### Define Pre-population via Command Line Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Specify SQL files or functions for pre-populating the template database directly from the pytest command line. ```sh pytest --postgresql-populate-template=path/to/file.sql --postgresql-populate-template=path.to.function ``` -------------------------------- ### Create PostgreSQL Superuser Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/CONTRIBUTING.rst Command to create a PostgreSQL superuser named 'postgres'. This is a prerequisite for running tests. ```bash createuser --superuser postgres ``` -------------------------------- ### Run PostgreSQL in Docker Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Command to run a PostgreSQL instance in a Docker container. ```sh docker run --name some-postgres -e POSTGRES_PASSWORD=mysecret -d postgres ``` -------------------------------- ### Run pytest with Docker PostgreSQL connection details Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Command to run pytest, specifying connection details for a PostgreSQL instance in Docker. ```sh pytest --postgresql-host=172.17.0.2 --postgresql-password=mysecret ``` -------------------------------- ### Connect to External PostgreSQL Instance Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Use the `postgresql_noproc` fixture factory to connect to an existing PostgreSQL server, such as one running in Docker or a CI environment. Defaults to 127.0.0.1:5432. ```python postgresql_external = factories.postgresql('postgresql_noproc') ``` -------------------------------- ### Bump version using tbump Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Command to bump the project version using tbump. ```sh pipenv run tbump [NEW_VERSION] ``` -------------------------------- ### Chain PostgreSQL Fixtures Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Layer data pre-population by chaining multiple postgresql_noproc fixtures. Each fixture creates its own template database based on the previous one. ```python from pytest_postgresql import factories # 1. Start with a process or a no-process base base_proc = factories.postgresql_proc(load=[load_schema]) # 2. Add a layer with some data seeded_noproc = factories.postgresql_noproc(depends_on="base_proc", load=[load_data]) # 3. Add another layer with more data more_seeded_noproc = factories.postgresql_noproc(depends_on="seeded_noproc", load=[load_more_data]) # 4. Use the final layer in your test client = factories.postgresql("more_seeded_noproc") ``` -------------------------------- ### Set PostgreSQL Version Environment Variable Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/CONTRIBUTING.rst Set the POSTGRES environment variable to the desired PostgreSQL version number before running tests. ```bash export POSTGRES= ``` -------------------------------- ### Run Tests with Pytest Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/CONTRIBUTING.rst Execute the test suite using pipenv and pytest. ```bash pipenv run pytest ``` -------------------------------- ### Enable Locale Generation Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/CONTRIBUTING.rst Commands to enable specific UTF-8 locales in /etc/locale.gen and then generate them. This is useful for resolving locale-related test failures. ```bash sudo locale-gen en_US.UTF-8 sudo locale-gen de_DE.UTF-8 ``` -------------------------------- ### SQLAlchemy Session Fixture Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Create an SQLAlchemy session fixture using a psycopg connection. Ensure to define your Base model and handle session closing and metadata dropping. ```python from typing import Iterator import pytest from psycopg import Connection from sqlalchemy import create_engine from sqlalchemy.orm import Session, sessionmaker, scoped_session from sqlalchemy.pool import NullPool @pytest.fixture def db_session(postgresql: Connection) -> Iterator[Session]: """Session for SQLAlchemy.""" user = postgresql.info.user host = postgresql.info.host port = postgresql.info.port dbname = postgresql.info.dbname connection_str = f'postgresql+psycopg://{user}:@{host}:{port}/{dbname}' engine = create_engine(connection_str, echo=False, poolclass=NullPool) # Assuming you use a Base model from my_app.models import Base Base.metadata.create_all(engine) SessionLocal = scoped_session(sessionmaker(bind=engine)) yield SessionLocal() SessionLocal.close() Base.metadata.drop_all(engine) ``` -------------------------------- ### Manual DatabaseJanitor Usage Source: https://github.com/dbfixtures/pytest-postgresql/blob/main/README.rst Manage database state outside standard fixtures using DatabaseJanitor. This is useful for custom database management scenarios. ```python import psycopg from pytest_postgresql.janitor import DatabaseJanitor def test_manual_janitor(postgresql_proc): with DatabaseJanitor( user=postgresql_proc.user, host=postgresql_proc.host, port=postgresql_proc.port, dbname="my_custom_db", version=postgresql_proc.version, ): pass ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.