Showing posts with label mocking. Show all posts
Showing posts with label mocking. Show all posts

Apr 16, 2012

Imposing no-DB discipline

from django.utils.unittest import TestCase

import mock

cursor_wrapper = mock.Mock()
cursor_wrapper.side_effect = RuntimeError("No touching the database!")


@mock.patch("django.db.backends.util.CursorWrapper", cursor_wrapper)
class NoDBTestCase(TestCase):
    """Will blow up if you database."""
https://github.com/carljm/django-testing-slides/blob/master/models/30_no_database.md

Feb 17, 2012

Test Django transaction using mocking and TransactionTestCase

It's pretty simple using mock side_effect:
class MyTransactionTestCase(TransactionTestCase):
    fixtures = ['some_fixture.json',]

    @patch.object(SomeObjectInsideTransaction, 'some_method')
    def test_disable_transaction(self, some_method):
        some_method.side_effect = IOError("Unexpected exception")

        try:
            self.client.get('/your/view/url/')
        except IOError:
            pass

        # assertions here
You have to use TransactionTestCase:
Django TestCase classes make use of database transaction facilities, if available, to speed up the process of resetting the database to a known state at the beginning of each test. A consequence of this, however, is that the effects of transaction commit and rollback cannot be tested by a Django TestCase class. If your test requires testing of such transactional behavior, you should use a Django TransactionTestCase.

Feb 2, 2012

Chaos Python

Add this into your functional tests and smoke it.
import sys, random

def chaos_trace(frame, event, arg): 
   if event == 'line' and random.random() < 0.000001: 
       raise MemoryError()
   return chaos_trace

sys.settrace(chaos_trace)
You will get some lovely random failures injected into your code. A great way to find bugs, and make sure your reasoning is sound in the face of CHAOS!

Jan 20, 2012

Mocking

Mock basics

mock = Mock(name='bar', return_value='fish')
mock(1, 2, spam = 99)
# 'fish'
mock.assert_called_once_with(1, 2, spam = 99)
mock.called
# True
mock.call_count
# 1
mock.call_args
# ((1, 2), {'spam': 99})
From: http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2011-testing-with-mock-4899484

Magic Mock basics

mock = MagicMock()
mock[5]
# <mock.Mock object at 0x2f90690>
mock.__str__.return_value = 'bzzzz'
str(mock)
# 'bzzzz'

Mock exceptions handling test

mock = Mock(side_effect=KeyError('boom'))
mock()
# Traceback (most recent call last)
# ....
# KeyError: 'boom'

Mock file write

>>> open_name = '%s.open' % __name__
>>> with patch(open_name, create=True) as mock_open:
...     mock_open.return_value = MagicMock(spec=file)
...
...     with open('/some/path', 'w') as f:
...         f.write('something')
...

>>> file_handle = mock_open.return_value.__enter__.return_value
>>> file_handle.write.assert_called_with('something')
http://stackoverflow.com/questions/1289894/how-do-i-mock-an-open-used-in-a-with-statement-using-the-mock-framework-in-pyth
http://www.voidspace.org.uk/python/mock/magicmock.html

Mock file and raw_post_data

from mock import Mock, MagicMock

class SomeTestCase(TestCase):

    def testRawPostData(self):
        ...

        request = Mock(spec=request)
        request.raw_post_data = 'myrawdata'
        print request.raw_post_data  # prints 'myrawdata'

        file_mock = MagicMock(spec=file)
        file_mock.read.return_value = 'myfiledata'
        request.FILES = {'myfile': file_mock}    
        print request.FILES['myfile'].read()  # prints 'myfiledata'

Mocking stdout

outstream = StringIO()
with patch('sys.stdout', new=outstream) as out:
    ...
    actual_out = out.getvalue()

Video: 
A Gentle Introduction to Mock for Python
Why Use Mock?
Mock and Django