Skip to content

Instantly share code, notes, and snippets.

@Luttik
Last active September 21, 2020 14:59
Show Gist options
  • Select an option

  • Save Luttik/2ae284069aa88dde5f3e7340f03dd021 to your computer and use it in GitHub Desktop.

Select an option

Save Luttik/2ae284069aa88dde5f3e7340f03dd021 to your computer and use it in GitHub Desktop.
Shows how to use pytest-locker with
from unittest.mock import MagicMock, patch
import json
from json import JSONEncoder
from typing import List, Type
import requests
from pytest import fixture
from pytest_locker import Locker
from _pytest.fixtures import FixtureRequest
# It is usually more scalable to inherit than to implement serialization
# You can use the json_encoder element to handle object that are not json-serializable by default
class CallArgsListLocker(Locker):
"""Implements locking of Mocker.call_args_list"""
def __init__(
self, request: FixtureRequest, json_encoder: Type[JSONEncoder] = JSONEncoder
) -> None:
super(CallArgsListLocker, self).__init__(request)
self.json_encoder = json_encoder
def lock(self, data: List, name: str = None, extension: str = "json") -> None:
super().lock(
json.dumps(
[dict(args=call[0], kwargs=call[1]) for call in data],
indent=2,
sort_keys=True,
cls=self.json_encoder,
),
name,
extension,
)
# the fixture for your child class of the pytest Locker class
@fixture
def call_args_list_locker(request: FixtureRequest) -> CallArgsListLocker:
return CallArgsListLocker(request)
# Tip: If you want to ensure that you do not make actual webcalls from your application you can always patch requests / urllib methods to prevent unexpected calls.
# Patch the api call that you want to "lock" (can be a request call but also a call to your api wrapper / sdk)
@patch.object(requests, "get")
def test_call_args_list_locker(
mocker: MagicMock, call_args_list_locker: CallArgsListLocker
) -> None:
# Make the call that you want to lock. (usually there obviously is a lot more logic surrounding the call that you want to test)
requests.get("https://google.com/", params=dict(bla=1, test="c"))
# Lock the attributes obtained by your mocker.
call_args_list_locker.lock(mocker.call_args_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment