PyTest -Tests scheitern bei Github -Aktionen mit asynchrischer SqlalchemiePython

Python-Programme
Anonymous
 PyTest -Tests scheitern bei Github -Aktionen mit asynchrischer Sqlalchemie

Post by Anonymous »

Ich habe ein Fastapi -Projekt, das SQLalchemy Orm im asynchronen Modus (+SQLite) verwendet, und ich führe meine Tests mit PyTest durch. Alles funktioniert lokal gut, aber in meinen Github-Aktionen CI-Pipeline fehlen meine Tests mit dem folgenden Fehler in meinem Ausgabeprotokoll: < /p>

Code: Select all

=================================== FAILURES ===================================
______________________________ test_create_person ______________________________
/opt/hostedtoolcache/Python/3.10.16/x64/lib/python3.10/site-packages/sqlalchemy/engine/base.py:1964: in _exec_single_context
self.dialect.do_execute(
/opt/hostedtoolcache/Python/3.10.16/x64/lib/python3.10/site-packages/sqlalchemy/engine/default.py:942: in do_execute
cursor.execute(statement, parameters)
E   sqlite3.OperationalError: no such table: persons
Es gibt meine conftest.

Code: Select all

"""conftest.py
"""
import os
import pytest

from httpx import AsyncClient
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker

from api.database import BASE, get_db
from api.main import app
from api.config import BASE_DIR, settings

# Set up ENV var for testing
# os.environ["ENV"] = "test"

# WHOOSH_INDEX_DIR = os.path.join(BASE_DIR, settings.WHOOSH_INDEX_DIR)
SQLALCHEMY_DATABASE_TEST_URL = "sqlite+aiosqlite:///./test.db"

engine = create_async_engine(
SQLALCHEMY_DATABASE_TEST_URL,
echo=False,
connect_args={"check_same_thread": False},
)

TestingSessionLocal = async_sessionmaker(bind=engine, expire_on_commit=False)

@pytest.fixture(scope="function")
async def db_session() -> AsyncSession:
"""Create a new database session and clean up after the test."""
async with engine.begin() as conn:
await conn.run_sync(BASE.metadata.drop_all)
await conn.run_sync(BASE.metadata.create_all)

async with TestingSessionLocal() as session:
yield session
await session.rollback()

@pytest.fixture(scope="function")
async def session_test(db_session: AsyncSession):
"""Create a test client that overrides the database session."""

async def override_get_db():
async with db_session as session:
yield session

app.dependency_overrides[get_db] = override_get_db

async with AsyncClient(app=app) as ac:
yield ac

< /code>
Und hier gibt es meinen einfachen Test, der fehlschlägt: < /p>
import pytest
import datetime
from sqlalchemy import select
from api.models.models import Person

@pytest.mark.asyncio
async def test_create_person(db_session):
"""Test: Create a new person"""

# Create a new person
person = Person(
lastname="Dupont",
firstnames="Jean",
birth_date="1970-1-1",
personal_information="Information personnelle",
)

db_session.add(person)
await db_session.commit()
result = await db_session.execute(select(Person).where(Person.lastname == "Dupont"))
retrieved_person = result.scalars().first()
assert retrieved_person is not None
assert retrieved_person.lastname == "Dupont"
assert retrieved_person.firstnames == "Jean"
< /code>
In meinem CI -Workflow (.github/workflows/CI.yml
), ich verwende Ubuntu-latest mit Python 3.10:

Code: Select all

name: DIL API CI

on:
push:
branches: [ master ]
pull_request:
branches: [ master ]

jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.10']

steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python3 -m pip install --upgrade pip
if [ -f requirements.txt ]; then pip install -r requirements.txt;  fi
- name: Test with pytest
run: |
cd ./tests/
pytest --tb=short -v
shell: bash

Das Problem legt nahe, dass die Tabellen nicht vor dem Test erstellt wurden, aber auf conn.run_sync (base.metadata.create_all ()) wird zu Beginn eines jeden Tests ausgeführt. Und global, warum die Tests nicht Github -Aktionen übergeben?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post