How do I mock part of a python constructor just for testing?

There is no need to provide a separate constructor. Mocking patches your code to replace objects with mocks. Just use the mock.patch() decorator on your test methods; it’ll pass in references to the generated mock objects. Both producer.Producer() and consumer.Consumer() are then mocked out before you create the instance: import mock class MyTest(unittest.TestCase): @mock.patch(‘producer.Producer’, autospec=True) … Read more

Mocking default=timezone.now for unit tests

Here’s a method you can use that doesn’t require altering your non-test code. Just patch the default attributes of the fields you want to affect. For example– field = User._meta.get_field(‘timestamp’) mock_now = lambda: datetime(2010, 1, 1) with patch.object(field, ‘default’, new=mock_now): # Your code here You can write helper functions to make this less verbose. For … Read more

How to mock os.walk in python with a temporary filesystem?

No. os.walk() is constructed entirely around os.listdir(), with assistance of os.path.islink() and os.path.isdir(). These are essentially system calls, so you’d have to mock your filesystem at the system level. Unless you want to write a FUSE plugin this is not going to be easy to mock. All os.walk() needs to return is a list of … Read more

How do you mock patch a python class and get a new Mock object for each instantiation?

Here’s a quick’n’dirty example to get you going: import mock import unittest class ClassToPatch(): def __init__(self, *args): pass def some_func(self): return id(self) class UUT(): def __init__(self, *args): resource_1 = ClassToPatch() resource_2 = ClassToPatch() self.test_property = (resource_1.some_func(), resource_2.some_func()) class TestCase1(unittest.TestCase): @mock.patch(‘__main__.ClassToPatch’, autospec = True) def test_1(self, mock1): ctpMocks = [mock.Mock(), mock.Mock()] ctpMocks[0].some_func.return_value = “funky” ctpMocks[1].some_func.return_value = … Read more

Can’t catch mocked exception because it doesn’t inherit BaseException

I could reproduce the error with a minimal example: foo.py: class MyError(Exception): pass class A: def inner(self): err = MyError(“FOO”) print(type(err)) raise err def outer(self): try: self.inner() except MyError as err: print (“catched “, err) return “OK” Test without mocking : class FooTest(unittest.TestCase): def test_inner(self): a = foo.A() self.assertRaises(foo.MyError, a.inner) def test_outer(self): a = foo.A() … Read more

Checking call order across multiple mocks

Define a Mock manager and attach mocks to it via attach_mock(). Then check for the mock_calls: @patch(‘module.a’) @patch(‘module.b’) @patch(‘module.c’) def test_main_routine(c, b, a): manager = Mock() manager.attach_mock(a, ‘a’) manager.attach_mock(b, ‘b’) manager.attach_mock(c, ‘c’) module.main_routine() expected_calls = [call.a(‘a’), call.b(‘b’), call.c(‘c’)] assert manager.mock_calls == expected_calls Just to test that it works, change the order of function calls in … Read more

Mock patching from/import statement in Python

If you’re patching something in the same module, you can use __main__: from mock import patch from collections import defaultdict with patch(‘__main__.defaultdict’): d = defaultdict() print ‘d:’, d If you’re mocking something for an imported module, however, you’ll want to use that module’s name so the correct reference (or name) is patched: # foo.py from … Read more

Mocking only a single method on an object

I think what you are looking for is mock.patch.object with mock.patch.object(MyClassUnderTest, “submethod”) as submethod_mocked: submethod_mocked.return_value = 13 MyClassUnderTest().main_method() submethod_mocked.assert_called_once_with(user_id, 100, self.context, self.account_type) Here is small description patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) patch the named member (attribute) on an object (target) with a mock object.

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)