DEV Community

whchi
whchi

Posted on

Mock your service as fixture in pytest

Summary

Mock all your service's method with patch

code

assume you have a jwt service

# jwt_service.py

class JWTService:

    @classmethod
    def create_access_token(cls, email: str) -> str:
        ...

    @classmethod
    def verify_access_token(cls, access_token: str) -> Dict[str, Any]:
        ...

    @classmethod
    def decode_access_token(cls, access_token: str) -> Dict[str, Any]:
        ...

    @classmethod
    def revoke_access_token(cls, access_token: str) -> None:
        ...

    @classmethod
    def get_subject(cls, access_token: str) -> str:
        ...
Enter fullscreen mode Exit fullscreen mode

you can mock it as fixture like this

# conftest.py

@pytest.fixture
def mock_jwt_service():
    with patch.object(JWTService, 'decode_access_token', return_value='123456778'), \
            patch.object(JWTService, 'verify_access_token', return_value=True), \
            patch.object(JWTService, 'create_access_token', return_value='999999999'), \
            patch.object(JWTService, 'get_subject', return_value='example@cc.cc'), \
            patch.object(JWTService, 'revoke_access_token', return_value=None) as m:
        yield m
Enter fullscreen mode Exit fullscreen mode

then you can simply use it in all your tests

def test_add_article(mock_jwt_service):
    ...
Enter fullscreen mode Exit fullscreen mode

so simple, isn't it?

Top comments (0)