[Beanie + PyTest] CollectionWasNotInitialized 오류

Joonas' Note

[Beanie + PyTest] CollectionWasNotInitialized 오류 본문

개발/python

[Beanie + PyTest] CollectionWasNotInitialized 오류

2022. 9. 24. 14:13 joonas 읽는데 2분
  • 오류
  • 해결법
  • 참고

오류

Beanie Document를 사용하는 Pydantic 모델을 pytest에서 사용하려고 할 때, collection이 초기화 되지 않았다는 오류가 나오면서 테스트 실행 자체를 실패한다.

MongoDB와 관련해서 초기화를 하지 못했다는 내용 같은데, fixture 같은 걸로 테스트 실행 전에 아래처럼 추가해줘도 마찬가지로 발생한다.

@pytest.fixture(autouse=True)
async def test_client():
    client = AsyncMongoMockClient()
    await init_beanie(document_models=[TestModel], database=client.get_database(name="db"))

계속 발생하는 beanie.exceptions.CollectionWasNotInitialized 예외..

tests\objects\models\section.py:24:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
tests\objects\models\section.py:19: in create_dummy_section
    return Section(content=Faker().text())
.venv\lib\site-packages\beanie\odm\documents.py:140: in __init__
    self.get_motor_collection()
.venv\lib\site-packages\beanie\odm\interfaces\getters.py:13: in get_motor_collection
    return cls.get_settings().motor_collection
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

cls = <class 'app.object.models.section.Section'>

    @classmethod
    def get_settings(cls) -> DocumentSettings:
        """
        Get document settings, which was created on
        the initialization step

        :return: DocumentSettings class
        """
        if cls._document_settings is None:
>           raise CollectionWasNotInitialized
E           beanie.exceptions.CollectionWasNotInitialized

.venv\lib\site-packages\beanie\odm\documents.py:878: CollectionWasNotInitialized

해결법

pytest.ini 파일에 아래와 같이 옵션을 추가한다.

[pytest]
asyncio_mode=auto

이제 테스트를 실행하면, asyncio_mode를 strict 가 아니라 auto 모드로 실행하면서 오류가 사라진다.

asyncio: mode=auto

참고

https://githublab.com/repository/issues/roman-right/beanie/307