blaix / tdubs

A python test double library
MIT License
8 stars 1 forks source link

Show how tdubs enables distinct stubbing vs mocking #4

Closed blaix closed 8 years ago

blaix commented 8 years ago

Use stubs to set up responses for queries. Use mocks to verify commands. A Double can be used for either. The difference is in how you use them.

Use this woma-style action as an example (depends on #1 and #2):

class CreateArticle(object):
    def __init__(self, repo, validator):
        self.repo = repo
        self.validator = validator

    def __call__(self, data):
        # ------------------------
        # query:
        # ------------------------
        if self.validator.is_valid(data):

            # ------------------------
            # command:
            # ------------------------
            repo.insert(data)

class CreateArticleTest(TestCase):
    def setUp():
        self.repo, validator = Double(), StrictDouble()
        self.action = CreateArticle(self.repo, self.validator)

        # ------------------------
        # queries are stubbed:
        # ------------------------
        calling(validator.is_valid).passing('good data').returns(True)
        calling(validator.is_valid).passing('bad data').returns(False)

    # ------------------------
    # commands are verified:
    # ------------------------

    def test_inserts_valid_article_data(self):
        self.action('good data')
        verify(self.repo.insert).called_with('good data')

    def test_does_not_insert_invalid_article_data(self):
        self.action('bad data')
        verify(self.repo.insert).not_called()
blaix commented 8 years ago

...but in reality, I'd prefer to do something like that with a pipeline:

def validate(data):
    # raises if invalid
    return data

def persist(data):
    # saves data to db
    return saved_article

create_article = pipeline(validate, persist)
create_article({'some': 'data'})

To show the same stubbing/mocking separation using a pipeline action, I'd have to change it to show an example woma controller. Where the request is stubbed and the action and response are mocked.