Example #1
0
    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)
Example #2
0
    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)])
Example #3
0
    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)])
Example #4
0
    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)
Example #5
0
    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)
Example #6
0
    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)
Example #7
0
    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")
Example #8
0
    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)
Example #9
0
    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)
Example #10
0
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
Example #11
0
    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)
Example #12
0
 def test_raw_field(self):
     obj = Mock()
     obj.foo = 3
     field = fields.Raw()
     self.assertEquals(field.output("foo", obj), 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",)