본문 바로가기
소프트웨어 마에스트로/BackEnd(Django)

[Django] ManyToMany pytest 작성하기

by alpakaka 2024. 11. 21.
@pytest.fixture
def create_profile(create_user, username, age, job, sleep_time, delay_reason):
    profile = Profile.objects.create(
        user_id=create_user,
        username=username,
        age=age,
        job=job,
        sleep_time=sleep_time,
        delay_reason=delay_reason,
    )
    return profile

여기에서 계속 에러가 발생한다.

PytestDeprecationWarning: The configuration option "asyncio_default_fixture_loop_scope" is unset.
The event loop scope for asynchronous fixtures will default to the fixture caching scope. Future versions of pytest-asyncio will default the loop scope for asynchronous fixtures to function scope. Set the default fixture loop scope explicitly in order to avoid unexpected behavior in the future. Valid fixture loop scopes are: "function", "class", "module", "package", "session"
해당 에러는 Django의 ManyToManyField에서 발생하는 일반적인 문제입니다. ManyToManyField는 객체 생성 시에 직접 데이터를 할당할 수 없으며, 대신 .set() 메서드를 사용해야 합니다. Profile.objects.create() 메서드는 ManyToManyField 필드에 직접 값을 설정할 수 없으므로, 이 필드는 객체를 생성한 후에 값을 설정해야 합니다.

이유는 다음과 같았는데 대략.. 해석해보면 아래와 같은 에러라고 한다.

ManyToMany의 경우 이렇게 직접적으로 create 를 하면 안되는 듯 싶다.

@pytest.fixture
def create_profile(create_user, username, age, job, sleep_time, delay_reason):
    profile = Profile.objects.create(
        user_id=create_user,
        username=username,
        age=age,
        job=job,
        sleep_time=sleep_time,
    )
    profile.delay_reason.set(delay_reason)
    return profile

그리고테스트코드를 작성했다.

리스트는 다음과 같다.

post : success, 해당 아이디에 이미 존재하는 경우, 잘못된 값을 입력하려는 경우

get : success ,없는 친구를 불러오려는 경우

patch : success, 없는 친구를 수정하려는 경우, user_id 를 업데이트하려는 경우, data 가 invalid 한 경우

 

이 경우들을 테스트할 수 있도록 코드를 작성했다.