Skip to content

Instantly share code, notes, and snippets.

@gmolveau
Created June 23, 2022 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmolveau/73e541f572da1d033c810e78214df8ca to your computer and use it in GitHub Desktop.
Save gmolveau/73e541f572da1d033c810e78214df8ca to your computer and use it in GitHub Desktop.
“Don’t Mock What You Don’t Own” in 5 Minutes #python

source : https://hynek.me/articles/what-to-mock-in-5-mins/

  • first iteration, naive implementation
# client.py
def get_repos_w_tags(client):
    rv = {}
    repos = client.get(
        "https://docker.example.com/v2/_catalog"
    ).json()["repositories"]

    for repo in repos:
        rv[repo] = client.get(
            f"https://docker.example.com/v2/{repo}/tags/list"
        ).json()["tags"]

    return rv

###

# test_client.py

from unittest.mock import Mock
import httpx

def test_empty():
    client = Mock(
        spec_set=httpx.Client,
        get=Mock(
            return_value=Mock(
                spec_set=httpx.Response,
                json=lambda: {
                    "repositories": []
                },
            )
        ),
    )

    assert {} == get_repos_w_tags(client)
  • second iteration, facade pattern, our abstraction
# client.py
class DockerRegistryClient:
    def __init__(self, client):
        self._client = client

    def get_repos(self):
        return self._client.get(
            "https://docker.example.com/v2/_catalog"
        ).json()["repositories"]

    def get_repo_tags(self, repo):
        return self._client.get(
             f"https://docker.example.com/v2/{repo}/tags/list"
        ).json()["tags"]

def get_repos_w_tags_drc(drc):
    rv = {}
    for repo in drc.get_repos():
        rv[repo] = drc.get_repo_tags(repo)
    return rv

###

# test_client.py

def test_empty_drc():
    drc = Mock(
        spec_set=DockerRegistryClient,
        get_repos=lambda: []
    )

    assert {} == get_repos_w_tags_drc(drc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment