Skip to content

Commit

Permalink
test(postgres): add example of initdb.d usage for postgres (#572)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderankin authored May 14, 2024
1 parent 49b261e commit 6f9376c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
create table example
(
id serial not null primary key,
name varchar(255) not null unique,
description text null
);
20 changes: 20 additions & 0 deletions modules/postgres/tests/test_postgres.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from pathlib import Path

import pytest

from testcontainers.postgres import PostgresContainer
Expand Down Expand Up @@ -77,3 +79,21 @@ def test_quoted_password():
# it raises ValueError, but auth (OperationalError) = more interesting
with sqlalchemy.create_engine(raw_pass_url).begin() as connection:
connection.execute(sqlalchemy.text("select 1=1"))


def test_show_how_to_initialize_db_via_initdb_dir():
postgres_container = PostgresContainer("postgres:16-alpine")
script = Path(__file__).parent / "fixtures" / "postgres_create_example_table.sql"
postgres_container.with_volume_mapping(host=str(script), container=f"/docker-entrypoint-initdb.d/{script.name}")

insert_query = "insert into example(name, description) VALUES ('sally', 'sells seashells');"
select_query = "select id, name, description from example;"

with postgres_container as postgres:
engine = sqlalchemy.create_engine(postgres.get_connection_url())
with engine.begin() as connection:
connection.execute(sqlalchemy.text(insert_query))
result = connection.execute(sqlalchemy.text(select_query))
result = result.fetchall()
assert len(result) == 1
assert result[0] == (1, "sally", "sells seashells")

0 comments on commit 6f9376c

Please sign in to comment.