Skip to content

Commit

Permalink
Continue adding tests
Browse files Browse the repository at this point in the history
  • Loading branch information
raphodn committed Nov 15, 2023
1 parent aa41163 commit 83e4e63
Showing 1 changed file with 79 additions and 0 deletions.
79 changes: 79 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,90 @@
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool

from app import crud
from app.api import app
from app.api import get_db
from app.db import Base


# DB & client setup
# ------------------------------------------------------------------------------
SQLALCHEMY_DATABASE_URL = "sqlite://"

engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base.metadata.create_all(bind=engine)


def override_get_db():
try:
db = TestingSessionLocal()
yield db
finally:
db.close()


app.dependency_overrides[get_db] = override_get_db

client = TestClient(app)


@pytest.fixture
def user(db=override_get_db()):
db_user = crud.get_user(next(db), user_id="user1")
if not db_user:
db_user = crud.create_user(next(db), {"user_id": "user1", "token": "user1__Utoken"})
return db_user


# Tests
# ------------------------------------------------------------------------------
def test_hello():
response = client.get("/")
assert response.status_code == 200


PRICE_JSON = {
"product_code": "1111111111111",
"price": 3.5,
"currency": "EUR",
"location_osm_id": 123,
"location_osm_type": "NODE",
"date": "2023-10-31",
}


def test_create_price_must_be_authenticated(user):
# without authentication
response = client.post(
"/prices",
json=PRICE_JSON,
)
assert response.status_code == 401
# with authentication
response = client.post(
"/prices",
json=PRICE_JSON,
headers={"Authorization": f"Bearer {user.token}"},
)
assert response.status_code == 200


def test_create_price_validation(user):
# product_code missing
PRICE_JSON_WITHOUT_PRODUCT_CODE = PRICE_JSON.copy()
del PRICE_JSON_WITHOUT_PRODUCT_CODE["product_code"]
response = client.post(
"/prices",
json=PRICE_JSON_WITHOUT_PRODUCT_CODE,
headers={"Authorization": f"Bearer {user.token}"},
)
assert response.status_code == 422

0 comments on commit 83e4e63

Please sign in to comment.