Created
August 26, 2017 14:58
-
-
Save GuyHoozdis/986cb386762510d9cddd9def4166a197 to your computer and use it in GitHub Desktop.
If you can't or don't want to use the start/stop pattern of mock.patch, this might work for you too
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mock | |
from couchbase.bucket import Bucket | |
from couchbase.n1ql import N1QLQuery | |
class DoInterestingStuff(object): | |
def __init__(self, bucket, other_thing): | |
self._bucket = bucket | |
self._other_thing = other_thing | |
def _get_blah_blah_doc_ids(self, some_value): | |
"""Demonstrate the mocked object. | |
Imagine you had some logic that constructed a query | |
and called `Bucket.n1ql_query`. | |
""" | |
if some_value in VALID_VALUES: | |
raise YouAreAnIdiot("I'm not doing that because you are an idiot") | |
query = N1QLQuery('... a query that uses "some_value" ...') | |
for row in bucket.n1ql_query(query): | |
# ... imagine that interesting stuff happens... | |
return useful_information | |
def do_interesting_stuff(some_value): | |
# ... imagine that interesting stuff happens... | |
pass | |
def test_get_blah_blah_doc_ids(): | |
"""Not realistic, just demonstrative. | |
This is a dumb example becuase it is made up to demonstrate the one thing I want to remember; that is, | |
how I constructed the mock object that could get called, like object instantiation, and return the | |
interface I needed after being called - without using `mock.patch`. | |
The key was to specify the `return_value` of the first mock as a new mock with the spec that I was | |
expecting. This is minimally, very minimally, imitating what mock.patch.object does. | |
""" | |
MockCbBucket = mock.MagicMock( | |
Bucket, | |
name='Bucket', | |
return_value=mock.NonCallableMagicMock( | |
name='Bucket()', | |
spec=Bucket, | |
) | |
) | |
mock_bucket = MockCbBucket('couchbase://couch.example.com/default') | |
mock_bucket.n1ql_query.return_value = [...] | |
sut = DoInterestingStuff(mock_bucket) | |
_ = sut._get_blah_blah_doc_ids(420) | |
assert mock_bucket.called, "Something has gone terribly wrong" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment