DEV Community

whchi
whchi

Posted on

1

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?

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay