Skip to content

Commit 8843fe6

Browse files
euri10cofin
authored andcommitted
tests exactly like code-blocks
1 parent 6044ff6 commit 8843fe6

File tree

9 files changed

+307
-78
lines changed

9 files changed

+307
-78
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# start-example
2+
from sqlspec.adapters.asyncpg import AsyncpgConfig
3+
4+
__all__ = ("test_async_methods",)
5+
6+
7+
config = AsyncpgConfig(
8+
pool_config={"dsn": "postgresql://user:pass@localhost/mydb"},
9+
migration_config={"enabled": True, "script_location": "migrations"},
10+
)
11+
# end-example
12+
13+
14+
def test_async_methods() -> None:
15+
# These are just smoke tests for method presence, not actual DB calls
16+
assert hasattr(config, "migrate_up")
17+
assert hasattr(config, "upgrade")
18+
assert hasattr(config, "migrate_down")
19+
assert hasattr(config, "downgrade")
20+
assert hasattr(config, "get_current_migration")
21+
assert hasattr(config, "create_migration")
22+
assert hasattr(config, "init_migrations")
23+
assert hasattr(config, "stamp_migration")
24+
assert hasattr(config, "fix_migrations")
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# start-example
2+
from sqlspec.adapters.sqlite import SqliteConfig
3+
4+
__all__ = ("test_sync_methods",)
5+
6+
7+
config = SqliteConfig(
8+
pool_config={"database": "myapp.db"}, migration_config={"enabled": True, "script_location": "migrations"}
9+
)
10+
11+
# Apply migrations (no await needed)
12+
config.migrate_up("head")
13+
# Or use the alias
14+
config.upgrade("head")
15+
16+
# Rollback one revision
17+
config.migrate_down("-1")
18+
# Or use the alias
19+
config.downgrade("-1")
20+
21+
# Check current version
22+
current = config.get_current_migration(verbose=True)
23+
print(current)
24+
25+
# Create new migration
26+
config.create_migration("add users table", file_type="sql")
27+
28+
# Initialize migrations directory
29+
config.init_migrations()
30+
31+
# Stamp database to specific revision
32+
config.stamp_migration("0003")
33+
34+
# Convert timestamp to sequential migrations
35+
config.fix_migrations(dry_run=False, update_database=True, yes=True)
36+
# end-example
37+
38+
39+
def test_sync_methods() -> None:
40+
# Smoke tests for method presence, not actual DB calls
41+
assert hasattr(config, "migrate_up")
42+
assert hasattr(config, "upgrade")
43+
assert hasattr(config, "migrate_down")
44+
assert hasattr(config, "downgrade")
45+
assert hasattr(config, "get_current_migration")
46+
assert hasattr(config, "create_migration")
47+
assert hasattr(config, "init_migrations")
48+
assert hasattr(config, "stamp_migration")
49+
assert hasattr(config, "fix_migrations")
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# start-example
2+
__all__ = ("test_template_config",)
3+
4+
5+
migration_config = {
6+
"default_format": "py", # CLI default when --format omitted
7+
"title": "Acme Migration", # Shared title for all templates
8+
"author": "env:SQLSPEC_AUTHOR", # Read from environment variable
9+
"templates": {
10+
"sql": {
11+
"header": "-- {title} - {message}",
12+
"metadata": ["-- Version: {version}", "-- Owner: {author}"],
13+
"body": "-- custom SQL body",
14+
},
15+
"py": {
16+
"docstring": """{title}\nDescription: {description}""",
17+
"imports": ["from typing import Iterable"],
18+
"body": """def up(context: object | None = None) -> str | Iterable[str]:\n return \"SELECT 1\"\n\ndef down(context: object | None = None) -> str | Iterable[str]:\n return \"DROP TABLE example;\"\n""",
19+
},
20+
},
21+
}
22+
# end-example
23+
24+
25+
def test_template_config() -> None:
26+
# Check structure of migration_config
27+
assert migration_config["default_format"] == "py"
28+
assert "py" in migration_config["templates"]
29+
assert "sql" in migration_config["templates"]
30+
assert isinstance(migration_config["templates"]["py"], dict)
31+
assert isinstance(migration_config["templates"]["sql"], dict)
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
__all__ = ("test_async_command_class_methods",)
2+
3+
4+
async def test_async_command_class_methods() -> None:
5+
6+
# start-example
7+
from sqlspec.adapters.asyncpg import AsyncpgConfig
8+
from sqlspec.migrations.commands import AsyncMigrationCommands
9+
10+
config = AsyncpgConfig(pool_config={"dsn": "postgresql://..."}, migration_config={"script_location": "migrations"})
11+
12+
# Create commands instance
13+
commands = AsyncMigrationCommands(config)
14+
15+
# Use commands directly
16+
await commands.upgrade("head")
17+
# end-example
18+
19+
# Smoke test for AsyncMigrationCommands method presence
20+
commands = AsyncMigrationCommands(config)
21+
assert hasattr(commands, "upgrade")
22+
assert hasattr(commands, "downgrade")
23+
assert hasattr(commands, "get_current_migration")
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# start-example
2+
from sqlspec.adapters.asyncpg import AsyncpgConfig
3+
4+
__all__ = ("test_config_structure",)
5+
6+
7+
config = AsyncpgConfig(
8+
pool_config={"dsn": "postgresql://user:pass@localhost/mydb"},
9+
migration_config={
10+
"enabled": True,
11+
"script_location": "migrations",
12+
"version_table_name": "ddl_migrations",
13+
"auto_sync": True, # Enable automatic version reconciliation
14+
},
15+
)
16+
# end-example
17+
18+
19+
def test_config_structure() -> None:
20+
# Check config attributes
21+
assert hasattr(config, "pool_config")
22+
assert hasattr(config, "migration_config")
23+
assert config.migration_config["enabled"] is True
24+
assert config.migration_config["script_location"] == "migrations"
25+
assert config.migration_config["version_table_name"] == "ddl_migrations"
26+
assert config.migration_config["auto_sync"] is True
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# start-example
2+
# migrations/0002_add_user_roles.py
3+
"""Add user roles table
4+
5+
Revision ID: 0002_add_user_roles
6+
Created at: 2025-10-18 12:00:00
7+
"""
8+
9+
__all__ = ("downgrade", "test_upgrade_and_downgrade_strings", "upgrade")
10+
11+
12+
def upgrade() -> str:
13+
"""Apply migration."""
14+
return """
15+
CREATE TABLE user_roles (
16+
id SERIAL PRIMARY KEY,
17+
user_id INTEGER REFERENCES users(id),
18+
role VARCHAR(50) NOT NULL
19+
);
20+
"""
21+
22+
23+
def downgrade() -> str:
24+
"""Revert migration."""
25+
return """
26+
DROP TABLE user_roles;
27+
"""
28+
29+
30+
# end-example
31+
32+
33+
def test_upgrade_and_downgrade_strings() -> None:
34+
up_sql = upgrade()
35+
down_sql = downgrade()
36+
assert "CREATE TABLE user_roles" in up_sql
37+
assert "DROP TABLE user_roles" in down_sql
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# start-example
2+
__all__ = ("test_upgrade_returns_list", "upgrade")
3+
4+
5+
def upgrade() -> list[str]:
6+
"""Apply migration in multiple steps."""
7+
return [
8+
"CREATE TABLE products (id SERIAL PRIMARY KEY);",
9+
"CREATE TABLE orders (id SERIAL PRIMARY KEY, product_id INTEGER);",
10+
"CREATE INDEX idx_orders_product ON orders(product_id);",
11+
]
12+
13+
14+
# end-example
15+
16+
17+
def test_upgrade_returns_list() -> None:
18+
stmts = upgrade()
19+
assert isinstance(stmts, list)
20+
assert any("products" in s for s in stmts)
21+
assert any("orders" in s for s in stmts)
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
__all__ = ("test_tracker_instance",)
2+
3+
4+
from pytest_databases.docker.postgres import PostgresService
5+
6+
7+
async def test_tracker_instance(postgres_service: PostgresService) -> None:
8+
9+
# start-example
10+
from sqlspec.adapters.asyncpg import AsyncpgConfig
11+
from sqlspec.migrations.tracker import AsyncMigrationTracker
12+
13+
tracker = AsyncMigrationTracker()
14+
15+
config = AsyncpgConfig(
16+
pool_config={
17+
"dsn": f"postgres://{postgres_service.user}:{postgres_service.password}@{postgres_service.host}:{postgres_service.port}/{postgres_service.database}"
18+
},
19+
migration_config={
20+
"enabled": True,
21+
"script_location": "migrations",
22+
"version_table_name": "ddl_migrations",
23+
"auto_sync": True, # Enable automatic version reconciliation
24+
},
25+
)
26+
async with config.provide_session() as session:
27+
driver = session._driver
28+
29+
# Update version record
30+
await tracker.update_version_record(driver, old_version="20251018120000", new_version="0003")
31+
# end-example
32+
# Just check that tracker is an instance of AsyncMigrationTracker
33+
assert isinstance(tracker, AsyncMigrationTracker)

0 commit comments

Comments
 (0)