Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Tests] Init tests. #21

Merged
merged 3 commits into from
Dec 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ gunicorn = "==20.1.0"
black = "~=23.1.0"
gevent = "*"
werkzeug = "==2.2.2"

pytest = "*"
pytest-cov = "*"
pytest-mock = "*"
pytest-socket = "*"
pytest-sugar = "*"
factory-boy = "*"

[dev-packages]

Expand Down
866 changes: 507 additions & 359 deletions Pipfile.lock

Large diffs are not rendered by default.

25 changes: 25 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,28 @@ class ProductionConfig(Config):
"pool_size": 10,
"max_overflow": 20,
}


class TestingConfig(Config):
DEBUG = True
TESTING = True
SECRET_KEY = "test"
JWT_SECRET_KEY = "test"
ENABLE_SEMANTIC_SEARCH = False
SQLALCHEMY_DATABASE_URI = os.environ.get(
"DATABASE_URI_TESTING",
"mysql+mysqlconnector://root:@/onisep_testing?charset=utf8mb4&collation=utf8mb4_general_ci",
)


def load_config(env: str) -> Config:
config_switch = {
"production": ProductionConfig,
"testing": TestingConfig,
"development": DevelopmentConfig,
}

config = config_switch.get(env, DevelopmentConfig)
config.ENV = env

return config
1 change: 1 addition & 0 deletions conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pytest_plugins = ["src.tests.fixtures.service"]
38 changes: 24 additions & 14 deletions src/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
import sys

from flasgger import Swagger
Expand All @@ -8,24 +9,22 @@
from flask_sqlalchemy import SQLAlchemy
from loguru import logger

from config import DevelopmentConfig, ProductionConfig
from config import load_config
from src.config.swagger import swagger_config, template
from src.constants.env import is_dev

from .errors import register_error_handlers
from .middlewares import after_request

db = SQLAlchemy()


def create_app(config_class=DevelopmentConfig):
def create_app(environment=None):
_setup_logging()
env = environment or os.environ.get("ENV")
config = load_config(env)
app = Flask(__name__, instance_relative_config=True)

if not is_dev():
config_class = ProductionConfig

app.config.from_object(config_class)
app.config.from_object(config)
CORS(app)
db.init_app(app)
Migrate().init_app(app, db)
Expand Down Expand Up @@ -53,13 +52,18 @@ def register_blueprints(app: Flask):
app.register_blueprint(formations)


def _setup_logging():
logger.remove()
logger.level("INFO", color="<green>")
logger.level("DEBUG", color="<blue>")
logger.level("WARNING", color="<yellow>")
logger.level("ERROR", color="<red>")
logger.level("CRITICAL", color="<red>")
def _set_log_levels():
log_levels = {
"INFO": "<green>",
"DEBUG": "<blue>",
"WARNING": "<yellow>",
"ERROR": "<red>",
"CRITICAL": "<red>",
}
[logger.level(level, color=color) for level, color in log_levels.items()]


def _add_stderr_logger():
logger.add(
sys.stderr,
colorize=True,
Expand All @@ -70,3 +74,9 @@ def _setup_logging():
"{extra}"
),
)


def _setup_logging():
logger.remove()
_set_log_levels()
_add_stderr_logger()
Empty file added src/tests/__init__.py
Empty file.
31 changes: 31 additions & 0 deletions src/tests/factories/factories.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import factory
from src import models


class UserFactory(factory.Factory):
class Meta:
model = models.User

username = factory.Faker("uuidv4")
email = factory.Faker("uuidv4")


class UserFavorisFactory(factory.Factory):
class Meta:
model = models.UserFavori


class FormationFactory(factory.Factory):
class Meta:
model = models.Formation

code_nsf = 334
type = "baccalauréat technologique"
libelle = (
"bac techno STHR Sciences et technologies de l'hôtellerie et de la restauration"
)
tutelle = "Ministère chargé de l'Éducation nationale et de la Jeunesse"
url = "http://www.onisep.fr/http/redirection/formation/slug/FOR.494"
domain = "hôtellerie-restauration, tourisme/hôtellerie | hôtellerie-restauration, tourisme/restauration"
niveau_de_sortie = "Bac ou équivalent"
duree = "1 an"
20 changes: 20 additions & 0 deletions src/tests/factories/test_factories.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import uuid
from sqlalchemy import func
from src.models.formation import Formation
from src.tests.factories.factories import FormationFactory


def test_check_if_formation_table_is_empty_should_return_0(db_session):
formation_count = db_session.query(func.count(Formation.id)).scalar()
assert formation_count == 0


def test_create_one_formation_should_return_1(db_session):
formation: Formation = FormationFactory()
db_session.add(formation)
db_session.commit()

assert formation.id is not None
assert isinstance(formation.id, uuid.UUID)
formation_count = db_session.query(func.count(Formation.id)).scalar()
assert formation_count == 1
36 changes: 36 additions & 0 deletions src/tests/fixtures/service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from typing import Generator
import pytest
from flask import Flask
from sqlalchemy.orm import Session
from flask.testing import FlaskClient
from flask_sqlalchemy import SQLAlchemy

from src import create_app
from src import db as _db


@pytest.fixture(autouse=True, scope="session")
def app() -> Flask:
app = create_app("testing")
return app


@pytest.fixture(scope="module")
def db(app: Flask) -> SQLAlchemy:
with app.app_context():
_db.create_all()
yield _db
_db.drop_all()


@pytest.fixture(scope="module")
def db_session(db: SQLAlchemy) -> Session:
yield db.session
db.session.rollback()
db.session.close()


@pytest.fixture()
def client(app: Flask, db: SQLAlchemy) -> Generator[FlaskClient, None, None]:
with app.test_client() as client:
yield client
11 changes: 11 additions & 0 deletions src/tests/test_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from config import TestingConfig


def test_testing_config(db_session):
from flask import current_app as app

assert app.config["DEBUG"]
assert app.config["TESTING"]
assert (
app.config["SQLALCHEMY_DATABASE_URI"] == TestingConfig.SQLALCHEMY_DATABASE_URI
)