mocklikeaboss



mocklikeaboss

0 0


mocklikeaboss

Mock Like a Boss (presentation)

On Github oxtopus / mocklikeaboss

Mock Like a Boss

A Python Mocking and Patching Library for Testing

Hello, mock!

    >>> from mock import Mock
    >>> func = Mock(return_value="Hello, mock!")
    >>> func()
    'Hello, mock!'

Mock objects...

...Create all attributes and methods (dynamically) as you access them

    >>> from mock import Mock
    >>> func = Mock()
    >>> hasattr(func, 'foo')
    True

Mock objects...

...Keep track of how they are used

    func = Mock()
    assert func.called
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AssertionError

    func()
    func.assert_called_with()

    func(1, 2, 3)
    func.assert_called_with(1, 2, 3)

    func('foo', bar='baz')
    args, kwargs = func.call_args_list[2]

Mock objects...

...can act like other functions

    sumMock = Mock(side_effect=sum)
    total = sumMock([1,2,4])
    assert total == 7
    sumMock.assert_called_once_with([1, 2, 4])

patch

Use patch for context.

def foo():
  print 'Hello, mock!'

with patch('sys.stdout', new_callable=StringIO) as stdout:
  foo()
  assert stdout.getvalue() == 'Hello, mock!'

patch

patch decorators help, too.

def foo():
  print 'Hello, mock!'

@patch('sys.stdout', new_callable=StringIO)
def test(stdout):
  foo()
  assert stdout.getvalue() == 'Hello, mock!\n'

Be sneaky

delorean.py:

import datetime

def travel(mph=None):
  return datetime.date.today()

testBackToTheFuture.py:

@patch.object(delorean, 'datetime', spec=datetime)
def testDelorean(datetimeMock):
  datetimeMock.date.today.return_value = \
    datetime.date(1955, 11, 5)
  date = delorean.travel(mph=88)
  assert date.strftime('%b %d %Y').upper() == 'NOV 05 1955'

  • Arrange
  • Act
  • Aassert
    @patch.object(Foo, 'baz')
    def foo(my_mocked_func):
      my_mocked_func.return_value = "Hello, mock!"

      fooInstance = Foo()
      result = fooInstance.bar()

      assert isinstance(fooInstance, Foo)
      assert result == "Hello, mock!"
      my_mocked_func.assert_called_once_with()

Arrange

    @patch.object(Foo, 'baz')
    def foo(my_mocked_func):
      my_mocked_func.return_value = "Hello, mock!"

Act

      fooInstance = Foo()
      result = fooInstance.bar()

Assert

      assert isinstance(fooInstance, Foo)
      assert result == "Hello, mock!"
      my_mocked_func.assert_called_once_with()

Questions?

See me.