def test_attribute_call(self): self.assertEqual(call.foo(1), ('foo', (1,), {})) self.assertEqual(call.bar.baz(fish='eggs'), ('bar.baz', (), {'fish': 'eggs'})) mock = Mock() mock.foo(1, 2 ,3) mock.bar.baz(a=3, b=6) self.assertEqual(mock.method_calls, [call.foo(1, 2, 3), call.bar.baz(a=3, b=6)])
def test_attaching__unnamed_attr_assignment__propogated(): parent = Mock() child = Mock() # unnamed assert mock_name(parent) is None assert mock_name(child) is None parent.child = child # attach assert mock_name(child) == 'mock.child' # renamed child.foo() assert parent.mock_calls == [call.child.foo()] # propogated
def test_attaching__named_attr_assignment__not_propogated(): parent = Mock() child = Mock(name='named') assert mock_name(parent) is None assert mock_name(child) == 'named' parent.child = child # attach (assignment) assert mock_name(child) == 'named' # not renamed child.foo() assert parent.mock_calls == [] # NOT propogated
def test_attaching__attach_named__propogated(): parent = Mock() child = Mock(name='named') assert mock_name(parent) is None assert mock_name(child) == 'named' parent.attach_mock(child, 'child') # attach (API) assert mock_name(child) == 'mock.child' # renamed child.foo() assert parent.mock_calls == [call.child.foo()] # propogated
def test_call_list_str(self): mock = Mock() mock(1, 2) mock.foo(a=3) mock.foo.bar().baz('fish', cat='dog') expected = ("[call(1, 2),\n" " call.foo(a=3),\n" " call.foo.bar(),\n" " call.foo.bar().baz('fish', cat='dog')]") self.assertEqual(str(mock.mock_calls), expected)
def test_call_list_str(self): mock = Mock() mock(1, 2) mock.foo(a=3) mock.foo.bar().baz('fish', cat='dog') expected = ( "[call(1, 2),\n" " call.foo(a=3),\n" " call.foo.bar(),\n" " call.foo.bar().baz('fish', cat='dog')]" ) self.assertEqual(str(mock.mock_calls), expected)
def test_should_test_mock(): m = Mock() m.configure_mock(bar='baz') m.configure_mock(baz=lambda: 'baz') assert isinstance(m.foo, Mock) assert isinstance(m.foo(), Mock) assert isinstance(m(), Mock) assert m.foo is not m.foo() is not m() assert 'baz' == m.bar assert 'baz' == m.baz()
def test_follows_permissions(self): allow = True allow_obj = True class MockPermission(object): def has_permission(self, *args): return allow def has_object_permission(self, *args): return allow_obj serializer = Mock() obj = Mock() obj.foo = 'bar' field = api.PermissionMod(fields.WritableField, [MockPermission])() field.initialize(serializer, 'foo') # If either has_permission or has_object_permission returns False, # then the field should act as a write_only field. Otherwise it shld # act as a read/write field . cases = [ (True, True, 'bar', False), (True, False, None, True), (False, True, None, True), (False, False, None, True), ] for case in cases: allow, allow_obj, expected_val, expected_write = case eq_(field.field_to_native(obj, 'foo'), expected_val) eq_(field.write_only, expected_write)
def test_incoming_read_only(self): class Resource(ModelResource): model_class = Mock(spec=[]) fields = [ AttributeField(attribute='bar', type=int), ] field = SubModelResourceField( attribute='foo', resource_class=Resource, read_only=True, ) source_dict = { 'foo': { 'bar': 20 }, } target_object = Mock() target_object.foo = Mock(['save']) field.handle_incoming(mock_context(), source_dict, target_object) self.assertFalse(hasattr(target_object.foo, 'bar')) self.assertFalse(target_object.foo.save.called)
def test_follows_permissions(self): allow = True allow_obj = True class MockPermission(object): def has_permission(self, *args): return allow def has_object_permission(self, *args): return allow_obj class MockSerializer(serializers.Serializer): foo = api_utils.PermissionMod(fields.ReadOnlyField, [MockPermission])() obj = Mock() obj.foo = 'bar' # If either has_permission or has_object_permission returns False, # then the field should act as a write_only field. Otherwise it should # act as a read/write field . cases = [ # allow, allow_obj, expected_val, expected_write_only (True, True, 'bar', False), (True, False, None, True), (False, True, None, True), (False, False, None, True), ] for case in cases: allow, allow_obj, expected_val, expected_write_only = case serializer = MockSerializer(instance=obj) eq_(serializer.data.get('foo'), expected_val)
def test_incoming_read_only(self): class Resource(ModelResource): model_class = Mock(spec=[]) fields = [ AttributeField(attribute='bar', type=int), ] field = SubModelResourceField( attribute='foo', resource_class=Resource, read_only=True, ) source_dict = { 'foo': {'bar': 20}, } target_object = Mock() target_object.foo = Mock(['save']) field.handle_incoming(mock_context(), source_dict, target_object) self.assertFalse(hasattr(target_object.foo, 'bar')) self.assertFalse(target_object.foo.save.called)
def test_should_reset_severity_according_to_rule( self, nested_severity_ruleset_source): rules = SeverityRules.load(nested_severity_ruleset_source) alert = Mock() alert.foo = "0xc0ffee" alert.bar = "0xbadc0de" assert rules.evaluate(alert) == 5
def test_follows_permissions(self): allow = True allow_obj = True class MockPermission(object): def has_permission(self, *args): return allow def has_object_permission(self, *args): return allow_obj serializer = Mock() obj = Mock() obj.foo = 'bar' field = api_utils.PermissionMod(fields.WritableField, [MockPermission])() field.initialize(serializer, 'foo') # If either has_permission or has_object_permission returns False, # then the field should act as a write_only field. Otherwise it shld # act as a read/write field . cases = [ (True, True, 'bar', False), (True, False, None, True), (False, True, None, True), (False, False, None, True), ] for case in cases: allow, allow_obj, expected_val, expected_write = case eq_(field.field_to_native(obj, 'foo'), expected_val) eq_(field.write_only, expected_write)
def test_simple_none_outgoing(self): source_object = Mock() source_object.foo = None target_dict = dict() field = AttributeField(attribute='foo', type=int) field.handle_outgoing(mock_context(), source_object, target_dict) self.assertEqual(target_dict['foo'], None)
def test_attaching__attr_method_access_and_return_value(): mock = Mock() # both attribute and return value get attached automatically rvalue1 = mock.foo.bar() rvalue2 = mock.foo().bar() assert mock_name(rvalue1) == 'mock.foo.bar()' assert mock_name(rvalue2) == 'mock.foo().bar()' assert mock.mock_calls == [call.foo.bar(), call.foo(), call.foo().bar()]
class TestConnectionHandler(object): def setup(self): self.api = Mock() self.cxn = Mock() self.edge = APIEdge(MockApp(self.api), None) self.handler = ConnectionHandler(self.edge.execute) self.handler.client = ("mock_peer", 1234) self.handler.cxn = self.cxn def set_next_message(self, type, data): self.cxn.recv_message.return_value = (type, data) def test_call_normal(self): self.set_next_message("call", ("foo", [], {})) self.handler._handle_one_message() assert_equal(self.cxn.send_message.call_args, ((("return", self.api.foo()), ), {})) def test_call_normal_no_response(self): self.set_next_message("call_ignore", ("foo", [], {})) self.handler._handle_one_message() assert_equal(self.cxn.send_message.call_count, 0) test_iterables = [ ([1, 2], [("return", [1, 2])]), ("foo", [("return", "foo")]), ({ "a": 1 }, [("return", { "a": 1 })]), (iter([]), [("stop", )]), (iter([1]), [("yield", 1), ("stop", )]), ] @parameterized(test_iterables) def test_call_returns_iterable(self, iterable, expected): self.api.foo.return_value = iterable self.set_next_message("call", ("foo", [], {})) self.handler._handle_one_message() actual = [ args[0] for (args, kwargs) in self.cxn.send_message.call_args_list ] assert_equal(actual, expected) def _run_exception_test(self, call): self.api.foo.side_effect = Exception("ohai") self.set_next_message(call, ("foo", [], {})) try: self.handler._handle_one_message() raise AssertionError("Exception not raised") except Exception, e: if str(e) != "ohai": raise
def test_getattr_string_name(): # Special attention since this is important m = Mock() m.foo = "bar" v = Value(m) foo_v = getattr(v, "foo") assert isinstance(foo_v, Value) assert foo_v.value == "bar" log = [] foo_v.on_value_changed(log.append) m2 = Mock() m2.foo = "baz" v.value = m2 assert foo_v.value == "baz" assert log == ["baz"]
def test_attaching__attr_method_access_and_return_value(): mock = Mock() # both attribute and return value get attached automatically rvalue1 = mock.foo.bar() rvalue2 = mock.foo().bar() assert mock_name(rvalue1) == 'mock.foo.bar()' assert mock_name(rvalue2) == 'mock.foo().bar()' assert mock.mock_calls == [ call.foo.bar(), call.foo(), call.foo().bar() ]
def test_outgoing(self): class Resource(ModelResource): model_class = Mock() parent_resource_path = 'resources' field = URIResourceField(attribute='foo', resource_class=Resource) source_object = Mock() source_object.foo = mock_orm.Model(pk=2) target_dict = dict() field.handle_outgoing(mock_context(), source_object, target_dict) self.assertEqual(target_dict['foo'], 'uri://resources/2')
class TestConnectionHandler(object): def setup(self): self.api = Mock() self.cxn = Mock() self.edge = APIEdge(MockApp(self.api), None) self.handler = ConnectionHandler(self.edge.execute) self.handler.client = ("mock_peer", 1234) self.handler.cxn = self.cxn def set_next_message(self, type, data): self.cxn.recv_message.return_value = (type, data) def test_call_normal(self): self.set_next_message("call", ("foo", [], {})) self.handler._handle_one_message() assert_equal(self.cxn.send_message.call_args, ((("return", self.api.foo()),), {})) def test_call_normal_no_response(self): self.set_next_message("call_ignore", ("foo", [], {})) self.handler._handle_one_message() assert_equal(self.cxn.send_message.call_count, 0) test_iterables = [ ([1, 2], [("return", [1, 2])]), ("foo", [("return", "foo")]), ({"a": 1}, [("return", {"a": 1})]), (iter([]), [("stop", )]), (iter([1]), [("yield", 1), ("stop", )]), ] @parameterized(test_iterables) def test_call_returns_iterable(self, iterable, expected): self.api.foo.return_value = iterable self.set_next_message("call", ("foo", [], {})) self.handler._handle_one_message() actual = [args[0] for (args, kwargs) in self.cxn.send_message.call_args_list] assert_equal(actual, expected) def _run_exception_test(self, call): self.api.foo.side_effect = Exception("ohai") self.set_next_message(call, ("foo", [], {})) try: self.handler._handle_one_message() raise AssertionError("Exception not raised") except Exception, e: if str(e) != "ohai": raise
def test_incoming_with_none_source_with_not_none_existing(self): class Resource(ModelResource): model_class = Mock() fields = [ AttributeField(attribute='bar', type=int), ] field = SubModelResourceField(attribute='foo', resource_class=Resource) source_dict = {'foo': None} target_object = Mock() target_object.foo = UserDict({'bar': 4}) target_object.foo.pk = 1 field.handle_incoming(mock_context(), source_dict, target_object) self.assertEqual(target_object.foo, None)
def test_getattr_value_name(): # Special attention since this is important m = Mock() m.foo = "FOO!" m.bar = "BAR!" v = Value(m) name_v = Value("foo") attr_v = getattr(v, name_v) assert attr_v.value == "FOO!" log = [] attr_v.on_value_changed(log.append) name_v.value = "bar" assert attr_v.value == "BAR!" assert log == ["BAR!"]
def test_incoming_with_none_source_with_not_none_existing(self): class Resource(ModelResource): model_class = Mock() fields = [ AttributeField(attribute='bar', type=int), ] field = SubModelResourceField(attribute='foo', resource_class=Resource) source_dict = { 'foo': None } target_object = Mock() target_object.foo = UserDict({'bar': 4}) target_object.foo.pk = 1 field.handle_incoming(mock_context(), source_dict, target_object) self.assertEqual(target_object.foo, None)
def test_mock(self): """A Mock object is callable, and you can configure this callable's return value. By default it returns another Mock instance, created on first access. Any arbitrary attribute access also creates & returns another mock instance. This 'spreads' to form a tree of Mock objects""" m = Mock() self.assertIsInstance(m, Mock) # a mock is always callable, and returns its return_value (by default, another Mock instance) self.assertIsInstance(m(), Mock) # any arbitrary attribute access or invocation will return another mock self.assertIsInstance(m.xyz, Mock) self.assertIsInstance(m.foo(), Mock) self.assertIsInstance(m.just.keep.on().trucking, Mock) # different attributes will all have different mock objects returned self.assertNotEqual(m.abcd, m.efgh) # but once referenced, the same mock is always returned self.assertEqual(m.abcd, m.abcd)
def test_outgoing_with_submodel_none(self): class OtherResource(ModelResource): model_class = Mock() field = [ AttributeField(attribute='bar', type=int), ] class Resource(ModelResource): model_class = Mock() fields = [ SubModelResourceField(attribute='bar', resource_class=OtherResource), ] field = SubModelResourceField(attribute='foo', resource_class=Resource) source_object = Mock() source_object.foo = None target_dict = dict() field.handle_outgoing(mock_context(), source_object, target_dict) self.assertEqual(target_dict['foo'], None)
def test_should_add_to_severity_for_simple_rule( self, simple_severity_ruleset_source): rules = SeverityRules.load(simple_severity_ruleset_source) alert = Mock() alert.foo = "perfectly-cromulent" assert rules.evaluate(alert) == 3
class AssertMockTestCase(unittest.TestCase): def setUp(self): self.mock = Mock() def test_basic(self): with assert_not_raises(): with assert_mock(self.mock): pass def test_no_call(self): with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: m.foo() assert cm.exception.args == ("Expected a foo() call but instead there was no call", ) def test_one_call(self): self.mock.foo() with assert_not_raises(): with assert_mock(self.mock): pass with assert_not_raises(): with assert_mock(self.mock) as m: m.foo() with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: m.foo() m.foo() assert cm.exception.args == ("Expected a foo() call but instead there was no call", ) def test_with_wrong_name(self): self.mock.foo() with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: m.bar() assert cm.exception.args == ("Expected a bar() call but found foo() instead", ) def test_with_wrong_args(self): self.mock.foo('bar') with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: m.foo() assert cm.exception.args == ("Expected a foo() call but found foo('bar') instead", ) self.mock.reset_mock() self.mock.foo() with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: m.foo('bar') assert cm.exception.args == ("Expected a foo('bar') call but found foo() instead", ) def test_with_wrong_kwargs(self): self.mock.foo(arg='bar') with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: m.foo() assert cm.exception.args == ("Expected a foo() call but found foo(arg='bar') instead", ) self.mock.reset_mock() self.mock.foo() with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: m.foo(arg='bar') assert cm.exception.args == ("Expected a foo(arg='bar') call but found foo() instead", ) def test_with_wrong_args_and_kwargs(self): self.mock.foo('bar', arg='baz') with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: m.foo() assert cm.exception.args == ("Expected a foo() call but found foo('bar', arg='baz') instead", ) with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: m.foo('bar') assert cm.exception.args == ("Expected a foo('bar') call but found foo('bar', arg='baz') instead", ) with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: m.foo(arg='baz') assert cm.exception.args == ("Expected a foo(arg='baz') call but found foo('bar', arg='baz') instead", ) with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: m.foo(1, arg=2) assert cm.exception.args == ("Expected a foo(1, arg=2) call but found foo('bar', arg='baz') instead", ) def test_with_correct_args(self): self.mock.foo() self.mock.bar() self.mock.foo(1) self.mock.foo(1, 2) self.mock.bar(1, 2, 3) self.mock.foo(1, 2, a=3, b=4) self.mock.foo(1, 2, a=3, b=4) with assert_not_raises(): with assert_mock(self.mock) as m: m.foo() m.bar() m.foo(1) m.foo(1, 2) m.bar(1, 2, 3) m.foo(1, 2, a=3, b=4) m.foo(1, 2, a=3, b=4) def test_no_more_calls(self): with assert_not_raises(): with assert_mock(self.mock) as m: no_more_calls(m) self.mock.foo() with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: no_more_calls(m) assert cm.exception.args == ("There should be no more method calls but there are: foo()", ) def test_skip(self): self.mock.foo() self.mock.foo() self.mock.foo() with assert_not_raises(): with assert_mock(self.mock) as m: skip(m, 3) with assert_not_raises(): with assert_mock(self.mock) as m: m.foo() skip(m, 2) with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: skip(m, 4) assert cm.exception.args == ("There should be at least 4 more method calls but there are only 3", ) with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: m.foo() skip(m, 4) assert cm.exception.args == ("There should be at least 4 more method calls but there are only 2", ) def test_current_call(self): self.mock.foo('one two three') self.mock.foo(foo='bar') with assert_not_raises(): with assert_mock(self.mock) as m: assert current_call(m).name == 'foo' assert 'two' in current_call(m).args[0] skip(m, 1) assert current_call(m).kwargs['foo'] == 'bar' def test_current_call_as_contextmanager(self): self.mock.foo('one two three') self.mock.foo(foo='bar') with assert_not_raises(): with assert_mock(self.mock) as m: with current_call(m) as c: c.name == 'foo' assert 'two' in c.args[0] # No need to `skip(m, 1)` as above. with current_call(m) as c: assert c.kwargs['foo'] == 'bar' no_more_calls(m) def test_current_call_with_single_arg(self): self.mock.foo('bar') with assert_not_raises(): with assert_mock(self.mock) as m: with current_call(m) as c: c.arg == 'bar' self.mock.reset_mock() self.mock.foo('bar', 'baz') with assert_raises(AssertionError) as cm: with assert_mock(self.mock) as m: with current_call(m) as c: c.arg assert cm.exception.args == ("Call should only have a single argument", )
def test_raw_field(self): obj = Mock() obj.foo = 3 field = fields.Raw() self.assertEquals(field.output("foo", obj), 3)