Skip to content

Commit

Permalink
Tests must use test settings (#11)
Browse files Browse the repository at this point in the history
* chore: remove pytest-env

* fix: tests must use test settings instead of environment variables

* docs: add release changes
  • Loading branch information
rrrrs09 authored Jul 23, 2021
1 parent d671ba1 commit 769575e
Show file tree
Hide file tree
Showing 14 changed files with 68 additions and 45 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
## 0.15.4 (Jul 23, 2021)

### Fixed

* Now tests use `TestAppSettings` instead of environment variables.


## 0.15.3 (Jul 22, 2021)

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion scripts/test
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ python -m venv .venv
source .venv/bin/activate
pip install poetry
poetry install
APP_ENV=test TEST_DB_CONNECTION=$TEST_DB_CONNECTION REDIS_DSN=$REDIS_DSN pytest --cov-config=setup.cfg
APP_ENV=test pytest --cov-config=setup.cfg
EXIT_CODE=$?
cd "${PRJDIR}" || exit 1
rm -rf "${TMPDIR}"
Expand Down
3 changes: 2 additions & 1 deletion {{cookiecutter.bot_name}}/.gitlab-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,11 @@ test:
- postgres:11.4-alpine
- redis:6.0.1-alpine
script:
- poetry run ./scripts/test
- poetry run pytest --cov-config=setup.cfg
variables:
TEST_DB_CONNECTION: postgres://postgres:postgres@postgres/postgres
REDIS_DSN: redis://redis/0
APP_ENV: test
coverage: '/Total coverage: \d\d\d.\d\d%/'

build:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class AppEnvTypes(str, Enum): # noqa:WPS600, WPS115
class BaseAppSettings(BaseSettings):
"""Allows to determine the current application environment."""

APP_ENV: AppEnvTypes = AppEnvTypes.DEV
APP_ENV: AppEnvTypes

class Config: # noqa: WPS431
env_file = ".env"
Expand Down
19 changes: 16 additions & 3 deletions {{cookiecutter.bot_name}}/app/settings/environments/test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""App settings for test stage."""
from typing import Any
from typing import Any, List

from pydantic import Field
from botx import BotXCredentials
from pydantic import Field, validator

from app.settings.environments.base import AppSettings

Expand All @@ -16,7 +17,7 @@ class TestAppSettings(AppSettings):

# storages
DATABASE_URL: str = Field(
"postgresql+asyncpg://postgres:postgres@localhost/postgres",
"postgresql://postgres:postgres@localhost/{{ cookiecutter.bot_name_underscored }}_test",
env="TEST_DB_CONNECTION",
)
REDIS_DSN: str = "redis://localhost/0"
Expand All @@ -28,3 +29,15 @@ class TestAppSettings(AppSettings):

class Config(AppSettings.Config): # noqa: WPS431
env_file = ".env"

@validator("BOT_CREDENTIALS", pre=True)
@classmethod
def parse_bot_credentials(cls, raw_credentials: Any) -> List[BotXCredentials]:
"""Parse bot credentials separated by comma.
If passed empty string return empty list for test env.
"""
try:
return super().parse_bot_credentials(raw_credentials)
except ValueError:
return []
35 changes: 17 additions & 18 deletions {{cookiecutter.bot_name}}/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion {{cookiecutter.bot_name}}/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ pytest-cov = "~2.12.1"
pytest-asyncio = "~0.15.1"
pytest-localserver = "~0.5.0"
python-dotenv = "~0.18.0"
pytest-env = "~0.6.2"
pytest-clarity = "~1.0.1"
pytest-timeout = "~1.4.2"

Expand Down
2 changes: 1 addition & 1 deletion {{cookiecutter.bot_name}}/scripts/test
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
set -e
set -x

pytest --cov-config=setup.cfg -m "not db" ${@}
APP_ENV=test pytest --cov-config=setup.cfg -m "not db" ${@}
2 changes: 1 addition & 1 deletion {{cookiecutter.bot_name}}/scripts/test_db
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
set -e
set -x

pytest -m "db" ${@}
APP_ENV=test pytest -m "db" ${@}
4 changes: 2 additions & 2 deletions {{cookiecutter.bot_name}}/setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ timeout = 20
filterwarnings =
error

env =
APP_ENV=test
# test classes must be subclasses of unittest.TestCase
python_classes =

[coverage:report]
precision = 2
Expand Down
8 changes: 6 additions & 2 deletions {{cookiecutter.bot_name}}/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@
from asgi_lifespan import LifespanManager
from botx import Bot, BotXCredentials, ChatCreatedEvent
from botx.testing import MessageBuilder, TestClient
from dotenv import load_dotenv
from fastapi import FastAPI
from pytest_cov.plugin import StoreReport

load_dotenv(".env")
from app.settings.environments.test import TestAppSettings


pytest_plugins = ["tests.fixtures.printer", "tests.fixtures.database"]
Expand All @@ -34,6 +33,11 @@ def fake_validate_report(_): # pragma: no cover
)


@pytest.fixture
def settings() -> TestAppSettings:
return TestAppSettings()


@pytest.fixture
def app(migrations) -> FastAPI:
from app.main import get_application
Expand Down
20 changes: 9 additions & 11 deletions {{cookiecutter.bot_name}}/tests/fixtures/database.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
import warnings
from os import environ

import pytest
from sqlalchemy import create_engine

from app.db.sqlalchemy import Base, make_url_sync
from app.settings.environments.test import TestAppSettings


@pytest.fixture
def migrations(printer):
def migrations(printer, settings: TestAppSettings):
import app.db.models # isort: skip

warnings.filterwarnings("ignore", category=ResourceWarning)
dsn = environ.get("TEST_DB_CONNECTION")
if dsn:
printer(f"Using database {dsn}")
engine = create_engine(make_url_sync(dsn))
Base.metadata.create_all(engine)
yield
Base.metadata.drop_all(engine)
else:
yield
dsn = settings.DATABASE_URL
printer(f"Using database {dsn}")

engine = create_engine(make_url_sync(dsn))
Base.metadata.create_all(engine)
yield
Base.metadata.drop_all(engine)
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from botx import ChatCreatedEvent, SystemEvents
from botx.testing import MessageBuilder, TestClient as BotXClient


@pytest.mark.db
@pytest.mark.asyncio
async def test_default_handler(builder: MessageBuilder, botx_client: BotXClient):
Expand Down
7 changes: 4 additions & 3 deletions {{cookiecutter.bot_name}}/tests/test_db/test_migrations.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import alembic.config
import pytest
from sqlalchemy import create_engine
from os import environ

from app.db.sqlalchemy import Base, make_url_sync
from app.settings.environments.test import TestAppSettings


@pytest.mark.db
def test_migrations():
dsn = environ.get("TEST_DB_CONNECTION")
def test_migrations(settings: TestAppSettings):
dsn = settings.DATABASE_URL
engine = create_engine(make_url_sync(dsn))
Base.metadata.drop_all(engine)
alembic.config.main(argv=["upgrade", "head"])
Expand Down

0 comments on commit 769575e

Please sign in to comment.