Skip to content

Commit

Permalink
Merge pull request #81 from schireson/dc/overeager-default
Browse files Browse the repository at this point in the history
  • Loading branch information
DanCardin authored Apr 18, 2023
2 parents 911afb0 + 367fa50 commit d308a19
Show file tree
Hide file tree
Showing 16 changed files with 181 additions and 18 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ format:
black src tests

publish: build
poetry publish -u __token__ -p '${PYPI_PASSWORD}' --no-interaction
poetry publish -u __token__ -p '${PYPI_TOKEN}' --no-interaction

changelog:
# https://convco.github.io/
Expand Down
36 changes: 36 additions & 0 deletions examples/test_pytest_alembic_tests_path/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
[alembic]
script_location = alembic

[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
25 changes: 25 additions & 0 deletions examples/test_pytest_alembic_tests_path/alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from logging.config import fileConfig

from alembic import context
from sqlalchemy import engine_from_config, pool

from models import Base

fileConfig(context.config.config_file_name)
target_metadata = Base.metadata


connectable = context.config.attributes.get("connection", None)

if connectable is None:
connectable = engine_from_config(
context.config.get_section(context.config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)

with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)

with context.begin_transaction():
context.run_migrations()
24 changes: 24 additions & 0 deletions examples/test_pytest_alembic_tests_path/alembic/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}


def upgrade():
${upgrades if upgrades else "pass"}


def downgrade():
${downgrades if downgrades else "pass"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from alembic import op
import sqlalchemy as sa

revision = "aaaaaaaaaaaa"
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
op.create_table(
"foo",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("(CURRENT_TIMESTAMP)"),
nullable=False,
),
sa.PrimaryKeyConstraint("id"),
)


def downgrade():
op.drop_table("foo")
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from alembic import op

revision = "bbbbbbbbbbbb"
down_revision = "aaaaaaaaaaaa"
branch_labels = None
depends_on = None


def upgrade():
conn = op.get_bind()
result = conn.execute("SELECT * FROM foo").fetchall()
assert len(result) == 0


def downgrade():
pass
17 changes: 17 additions & 0 deletions examples/test_pytest_alembic_tests_path/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import sqlalchemy
from sqlalchemy import Column, types
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class CreatedAt(Base):
__tablename__ = "foo"

id = Column(types.Integer(), autoincrement=True, primary_key=True)

created_at = sqlalchemy.Column(
sqlalchemy.types.DateTime(timezone=True),
server_default=sqlalchemy.text("CURRENT_TIMESTAMP"),
nullable=False,
)
2 changes: 2 additions & 0 deletions examples/test_pytest_alembic_tests_path/pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[pytest]
pytest_alembic_tests_path = tests_/test/conftest.py
Empty file.
6 changes: 6 additions & 0 deletions examples/test_pytest_alembic_tests_path/tests_/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import pytest


@pytest.fixture
def alembic_engine():
raise
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from pytest_mock_resources import create_postgres_fixture

alembic_engine = create_postgres_fixture()
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "pytest-alembic"
version = "0.10.2"
version = "0.10.4"
description = "A pytest plugin for verifying alembic migrations."
authors = [
"Dan Cardin <ddcardin@gmail.com>",
Expand Down
7 changes: 4 additions & 3 deletions src/pytest_alembic/plugin/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ def pytest_addoption(parser):
"Typically, you would want this to coincide with the path at which your `alembic_engine` is being "
"defined/registered. Note that this path must be the full path, relative to the root location "
"at which pytest is being invoked.",
default="tests/conftest.py",
)

group = parser.getgroup("collect")
Expand All @@ -55,8 +54,10 @@ def pytest_addoption(parser):
)
group.addoption(
"--alembic-tests-path",
default="tests/conftest.py",
help="The location at which the built-in tests will be bound.",
help=(
"The location at which the built-in tests will be bound. Has higher precedence than the "
"corresponding `pytest_alembic_tests_path` ini option."
),
dest="pytest_alembic_tests_path",
)

Expand Down
6 changes: 3 additions & 3 deletions src/pytest_alembic/plugin/plugin.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import re
from dataclasses import dataclass
from pathlib import Path, PurePath
from typing import Callable, Dict, List, Optional
from typing import Callable, cast, Dict, List, Optional

import pytest
from _pytest import config
Expand Down Expand Up @@ -30,8 +30,8 @@ def pytest_collect_file(self, path, parent): # type: ignore

def should_register(self, path):
tests_path = PurePath(
self.config.option.pytest_alembic_tests_path
or self.config.getini("pytest_alembic_tests_path")
cast(Optional[str], self.config.option.pytest_alembic_tests_path)
or cast(Optional[str], self.config.getini("pytest_alembic_tests_path"))
or "tests/conftest.py"
)
relative_path = path.relative_to(self.config.rootpath)
Expand Down
28 changes: 18 additions & 10 deletions tests/test_runner.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import pytest


def run_pytest(pytester, *, success=True, passed=4, skipped=0, failed=0, test_alembic=True):
args = [
"--test-alembic",
"--alembic-tests-path",
"conftest.py",
"-vv",
"-s",
]
if not test_alembic:
args = ["-vv", "conftest.py"]
def run_pytest(
pytester, *, success=True, passed=4, skipped=0, failed=0, test_alembic=True, args=None
):
if not args:
args = [
"--test-alembic",
"--alembic-tests-path",
"conftest.py",
"-vv",
"-s",
]
if not test_alembic:
args = ["-vv", "conftest.py"]

pytester.copy_example()
result = pytester.inline_run(*args)
Expand Down Expand Up @@ -262,3 +265,8 @@ def test_generate_revision(pytester):
def test_skip_revision(pytester):
"""Assert a revision can be skipped through configuring the "skip_revisions" config."""
run_pytest(pytester, passed=4)


def test_pytest_alembic_tests_path(pytester):
"""Assert the pytest_alembic_tests_path can be overridden."""
run_pytest(pytester, passed=4, args=["-vv", "--test-alembic", "tests_"])

0 comments on commit d308a19

Please sign in to comment.