Skip to content

[05.24.2024] Pytest 실패 #1

@philosucker

Description

@philosucker

현재 이슈 05.24.2024

  • pytest 실패, 원 #인분석 중
  • 테스트 내용
    • 가상 클라이언트 9개로 각각 유저 등록, 로그인, 이벤트 생성 및 변경 요청 처리를 하는 pytest 실행시 에러 발생

에러 메시지

 RuntimeError: Task attached to a different loop

에러 해결 방법

pytest는 기본적으로 각 테스트 함수에 대해 새로운 이벤트 루프를 생성하기 때문에,
비동기 함수들이 서로 다른 이벤트 루프에서 실행될 수 있다.

따라서
a : 별도의 이벤트루프 함수를 짤 필요 없이 테스트 함수 하나에 테스트할 함수들을 모아 넣고,
테스트 함수들이 실행될 DB 및 클라이언트 초기화 함수의 fixture의 범위를 function으로 한정하든가

@pytest.fixture(scope="function")
async def initialize_test_db():
...

@pytest.fixture(scope="function")
async def async_client(initialize_test_db):
...
yield client

async def 테스트 함수들(client):
...

b : 별도의 이벤트루프 함수를 만들어 fixture의 범위를 session으로 두고
이 이벤트 루프 함수를 DB와 클라이언트 초기화 함수에 넣은 뒤,
테스트 함수들을 전부 기능별로 분리하든가

@pytest.fixture(scope="session")
def event_loop():
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()

@pytest.fixture(scope="session")
async def initialize_test_db(event_loop):
...

@pytest.fixture(scope="session")
async def async_client(initialize_test_db, event_loop):
...
yield client

async def 테스트 함수들(client):

a, b 둘 중 하나의 방법을 쓰면 된다.

에러 원인

  1. 이벤트 루프 함수를 DB 초기화 함수에는 넣어주고, 이 DB 함수를 클라이언트 초기화 함수에 넣었다.
  2. fixture의 scope 인자가 의미하는 바를 제대로 이해하지 못했다.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions