File size: 3,168 Bytes
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
"""Test harness: a real Postgres database (migrated with Alembic), an in-process S3 server (moto) and an HTTP client.

Each parallel test run must use its own database: set TEST_DATABASE_NAME (default app_test).
Postgres comes from TEST_DATABASE_SERVER (default the local docker container on port 55440).
"""

import os
import socket
import subprocess
import sys
from pathlib import Path

import pytest

ROOT = Path(__file__).resolve().parents[1]
SERVER = os.environ.get("TEST_DATABASE_SERVER", "postgresql://app:app@localhost:55440")
DB_NAME = os.environ.get("TEST_DATABASE_NAME", "app_test")


def _free_port() -> int:
    with socket.socket() as s:
        s.bind(("127.0.0.1", 0))
        return s.getsockname()[1]


S3_PORT = _free_port()
os.environ.update({
    "ENV": "test",
    "DATABASE_URL": f"{SERVER.replace('postgresql://', 'postgresql+asyncpg://')}/{DB_NAME}",
    "JWT_SECRET": "test-secret-test-secret-test-secret",
    "STORAGE_ENDPOINT": f"http://127.0.0.1:{S3_PORT}",
    "STORAGE_REGION": "us-east-1",
    "STORAGE_BUCKET": "test-media",
    "STORAGE_KEY": "test",
    "STORAGE_SECRET": "test",
    "GOOGLE_API_KEY": "",          # the AI coach uses its rule-based text in tests
    "COACH_CACHE_ENABLED": "false",
})

import boto3  # noqa: E402
import httpx  # noqa: E402
from moto.server import ThreadedMotoServer  # noqa: E402
from sqlalchemy import text  # noqa: E402

from app.core.database import get_engine  # noqa: E402
from app.core.rate_limit import reset_all as reset_rate_limits  # noqa: E402
from app.main import create_app  # noqa: E402
from app.models import Base  # noqa: E402


def _create_database() -> None:
    import asyncio

    import asyncpg

    async def run() -> None:
        conn = await asyncpg.connect(f"{SERVER}/postgres")
        try:
            await conn.execute(f'DROP DATABASE IF EXISTS "{DB_NAME}" WITH (FORCE)')
            await conn.execute(f'CREATE DATABASE "{DB_NAME}"')
        finally:
            await conn.close()

    asyncio.run(run())


@pytest.fixture(scope="session", autouse=True)
def database() -> None:
    _create_database()
    subprocess.run([sys.executable, "-m", "alembic", "upgrade", "head"], cwd=ROOT, check=True,
                   env=os.environ.copy(), capture_output=True)


@pytest.fixture(scope="session", autouse=True)
def s3_server():
    server = ThreadedMotoServer(ip_address="127.0.0.1", port=S3_PORT)
    server.start()
    boto3.client("s3", endpoint_url=os.environ["STORAGE_ENDPOINT"], region_name="us-east-1",
                 aws_access_key_id="test", aws_secret_access_key="test").create_bucket(Bucket="test-media")
    yield server
    server.stop()


@pytest.fixture(autouse=True)
async def clean_tables():
    reset_rate_limits()
    yield
    tables = ", ".join(t.name for t in Base.metadata.sorted_tables)
    async with get_engine().begin() as conn:
        await conn.execute(text(f"TRUNCATE {tables} RESTART IDENTITY CASCADE"))


@pytest.fixture(scope="session")
def app():
    return create_app()


@pytest.fixture
async def client(app):
    async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as c:
        yield c