Skip to content

Instantly share code, notes, and snippets.

@benhowes
Created November 15, 2018 16:23
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 benhowes/fc30573413eb1c5ab5598d16171820d7 to your computer and use it in GitHub Desktop.
Save benhowes/fc30573413eb1c5ab5598d16171820d7 to your computer and use it in GitHub Desktop.

Example unit

def _parse_id(uid)
    if not instanceof(uid, UUID):
        uid = UUID(uid)
    return uid

def get_consent_document(uid):
    uid = _parse_id(uid)
    repo = registry.get(IConsentRepository)
    document = repo.get_document(uid)

    return document

Too loose

def test_get_consent_document():

    with dummy_data(Consent) as consent: # Pretend this puts a consent document in the database
        consent_uid = consent.uid
        doc = get_consent_document(consent_uid)
        assert doc.uid = consent_uid
  1. Doesn't assert correct use of registry interface
  2. Doesn't assert correct use of repository interface

Over fitted

def get_consent_document_bad_id():
    """ Mocks _parse_id to raise an error """
    with patch("module._parse_id", side_effect=ValueError) as mock:
        get_consent_document("123")
    assert mock.called_with("123")
  1. Mocks internal methods

Just right

    def test_get_consent_document():
        mock_repository = MagicMock()
        expected_document = ConsentFactory()
        mock_repository.get_document.return_value = expected_document
        with patch("module.registry.get", return_value=mock_repository) as mock_registry_get:
            document = get_consent_document("some_value")

        assert mock_registry_get.called_once_with(IConsentRepository)
        assert mock_repository.get_document.called_once_with("some_value")
        assert document is expected_document
  1. Tests that extenal units are correctly called acccording to their interfaces.
  2. asserts the correct result is returned
  3. Doesn't make assumptions about the unit, other than it's external calls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment