def test_magic_method_wrapping(self):
        mock = Mock()

        def f(self, name):
            return self, "fish"

        mock.__getitem__ = f
        self.assertIsNot(mock.__getitem__, f)
        self.assertEqual(mock["foo"], (mock, "fish"))
        self.assertEqual(mock.__getitem__("foo"), (mock, "fish"))

        mock.__getitem__ = mock
        self.assertIs(mock.__getitem__, mock)
    def test_dict_methods(self):
        mock = Mock()

        self.assertRaises(TypeError, lambda: mock["foo"])

        def _del():
            del mock["foo"]

        def _set():
            mock["foo"] = 3

        self.assertRaises(TypeError, _del)
        self.assertRaises(TypeError, _set)

        _dict = {}

        def getitem(s, name):
            return _dict[name]

        def setitem(s, name, value):
            _dict[name] = value

        def delitem(s, name):
            del _dict[name]

        mock.__setitem__ = setitem
        mock.__getitem__ = getitem
        mock.__delitem__ = delitem

        self.assertRaises(KeyError, lambda: mock["foo"])
        mock["foo"] = "bar"
        self.assertEqual(_dict, {"foo": "bar"})
        self.assertEqual(mock["foo"], "bar")
        del mock["foo"]
        self.assertEqual(_dict, {})
Example #3
0
 def qs(self, count):
     """Returns mock queryset with given count."""
     qs = Mock()
     qs.count.return_value = count
     qs.empty.return_value = []
     qs.__getitem__ = Mock()
     return qs
Example #4
0
 def _dict_mock(self, **kwargs):
     """
     Get a mock that allows __getitem__
     """
     item = Mock()
     item.data = kwargs
     item.__getitem__ = lambda s, k: s.data[k]
     return item
Example #5
0
def test_input_sample_init_getitem_noexpand_param():
    mock_obj = Mock()
    mock_obj.__getitem__ = Mock(return_value=[0, 1, 2])
    mock_obj.__setitem__ = Mock()
    s = InputSample(4, 3, mock_obj, expand=False)
    assert hasattr(s, "__getitem__")
    assert s[1] == [0, 1, 2]
    mock_obj.__getitem__.assert_called_once_with(1)
    def setUp(self):
        # NOTE this context will not push and pop so we can inspect it
        self.context = {}
        mock_cxt = Mock()
        mock_cxt.__getitem__ = lambda _, x: self.context[x]
        mock_cxt.__setitem__ = lambda _, x, y: self.context.__setitem__(x, y)

        self.mock_cxt = mock_cxt
    def test_deleting_magic_methods(self):
        mock = Mock()
        self.assertFalse(hasattr(mock, "__getitem__"))

        mock.__getitem__ = Mock()
        self.assertTrue(hasattr(mock, "__getitem__"))

        del mock.__getitem__
        self.assertFalse(hasattr(mock, "__getitem__"))
Example #8
0
    def test_del_variabledefattr_backwards(self):

        migration = self._pick_migration("0013_del_variabledefattr")
        orm = Mock(autospec=migration.prev_orm())
        available_models = {"platform.variabledef": Mock()}
        orm.__getitem__ = lambda self, model: available_models[model.lower()]
        with patch("wirecloud.platform.south_migrations.0013_del_variabledefattr.db", autospec=True):
            migration_instance = migration.migration_instance()
            with patch.object(migration_instance, "gf", autospec=True):
                migration_instance.backwards(orm)
Example #9
0
    def testMagicMethodWrapping(self):
        mock = Mock()

        def f(self, name):
            return self, "fish"

        mock.__getitem__ = f
        self.assertFalse(mock.__getitem__ is f)
        self.assertEqual(mock["foo"], (mock, "fish"))

        # When you pull the function back of the *instance*
        # the first argument (self) is removed
        def instance_f(name):
            pass

        self.assertEqual(inspect.getargspec(mock.__getitem__), inspect.getargspec(instance_f))

        mock.__getitem__ = mock
        self.assertTrue(mock.__getitem__ is mock)
    def test__list(self):
        self.instances.api.client.get = Mock(return_value=("resp", None))
        self.assertRaises(Exception, self.instances._list, "url", None)

        body = Mock()
        body.get = Mock(return_value=[{"href": "http://test.net/test_file", "rel": "next"}])
        body.__getitem__ = Mock(return_value="instance1")
        # self.instances.resource_class = Mock(return_value="instance-1")
        self.instances.api.client.get = Mock(return_value=("resp", body))
        _expected = [{"href": "http://test.net/test_file", "rel": "next"}]
        self.assertEqual(_expected, self.instances._list("url", None).links)
Example #11
0
def test_input_sample_init_getitem_expand_param():
    mock_obj = Mock()
    mock_obj.__getitem__ = Mock(return_value=[0, 1, 2])
    mock_obj.__setitem__ = Mock()
    s = InputSample(4, 3, mock_obj, expand=True)
    assert s._array == [[0, 1, 2]] * 4
    expected = [((0,), {})] * 3 + [((1,), {})] * 3 + [((2,), {})] * 3 + [((3,), {})] * 3
    assert mock_obj.__getitem__.call_args_list == expected
    s[3] = ["s"]
    assert s._setitem == s._assign_to_array
    assert not mock_obj.__setitem__.called  # expand=T copied the contents
    def test(get_database):
        database_mock = Mock()
        database_mock.__getitem__ = Mock(return_value="$20.33")
        database_mock.close = Mock(return_value=None)

        get_database.return_value = database_mock

        assert get_transaction("mocked_transaction_id") == "$20.33"

        get_database.assert_called_with()
        database_mock.__getitem__.assert_called_with("mocked_transaction_id")
Example #13
0
    def test_add_gcode_file(self):
        fake = Mock()
        fake.filename = "test_stl.gcode"
        self.filenames.append(fake.filename)
        fake.__getitem__ = "SOMETHING"

        result, done = self.manager.addFile(fake, FileDestinations.LOCAL)

        logging.info("RESULT:%s" % str(result))

        self.assertTrue(fake.filename == result)
        self.assertTrue(done)
Example #14
0
    def test_remove_userprefoption_model_and_metadata_fields_backwards(self):

        migration = self._pick_migration("0012_remove_userprefoption_model_and_metadata_fields")
        orm = Mock(autospec=migration.prev_orm())
        available_models = {"platform.variabledef": Mock()}
        orm.__getitem__ = lambda self, model: available_models[model.lower()]
        with patch(
            "wirecloud.platform.south_migrations.0012_remove_userprefoption_model_and_metadata_fields.db", autospec=True
        ):
            migration_instance = migration.migration_instance()
            with patch.object(migration_instance, "gf", autospec=True):
                migration_instance.backwards(orm)
Example #15
0
    def test_subscribe_target_is_allowed(self):
        mock_receiver = Mock(Receiver)
        mock_config = Mock(ReceiverConfig)
        mock_config.configuration = {"allowed_targets": ["foo"]}
        mock_config.__getitem__ = lambda _self, key: mock_config.configuration[key]
        mock_receiver.broadcaster = Mock()
        mock_receiver.broadcaster.client = Mock()
        mock_receiver.configuration = mock_config

        Receiver.subscribeTarget(mock_receiver, "foo")

        mock_receiver.configuration.reload_targets.assert_called_with()
        mock_receiver.broadcaster.client.subscribe.assert_called_with(mock_receiver.onEvent, "foo")
Example #16
0
    def test_add_stl_file_curaDisabled(self, process, getterMock):

        getterMock.return_value = False

        fake = Mock()
        fake.filename = "test_stl.stl"
        self.filenames.append(fake.filename)
        fake.__getitem__ = "SOMETHING"

        result, done = self.manager.addFile(fake, FileDestinations.LOCAL)

        logging.info("RESULT:%s" % str(result))

        self.assertFalse(process.called)
        self.assertIsNone(result)
        self.assertTrue(done)
    def test__list(self):
        def side_effect_func(self, val):
            return val

        key = "key"
        body = Mock()
        body.get = Mock(return_value=[{"href": "http://test.net/test_file", "rel": "next"}])
        body.__getitem__ = Mock(return_value=["test-value"])

        resp = Mock()
        resp.status = 200
        self.users.resource_class = Mock(side_effect=side_effect_func)
        self.users.api.client.get = Mock(return_value=(resp, body))
        self.assertEqual(["test-value"], self.users._list("url", key).items)

        self.users.api.client.get = Mock(return_value=(resp, None))
        self.assertRaises(Exception, self.users._list, "url", None)
Example #18
0
    def test_add_stl_file_curaEnabled(self, process, getterMock):

        getterMock.return_value = True

        fake = Mock()
        fake.filename = "test_stl.stl"
        self.filenames.append(fake.filename)
        fake.__getitem__ = "SOMETHING"

        result, done = self.manager.addFile(fake, FileDestinations.LOCAL)

        logging.info("RESULT:%s" % str(result))

        getterMock.assert_called_once_with(["cura", "enabled"])
        self.assertTrue(process.called)
        self.assertTrue("test_stl.gcode" == result)
        self.assertFalse(done)
Example #19
0
    def test_anchor(self):
        target = Mock()
        target.type = "node"

        source = Mock()
        source.type = "node"

        relation = Mock()
        relation.type = "edge"

        # given two node objects connected by an edge object

        target.name = "target"
        source.name = "source"

        properties = {"source-object": "source", "target-object": "target"}

        def getitem(name):
            return properties[name]

        relation.__getitem__ = Mock(side_effect=getitem)
        relation.name = "relation"

        # added to diagram

        self.diagram.add(relation)
        self.diagram.add(target)
        self.diagram.add(source)

        # when anchors are set

        self.diagram.set_anchors()

        # each DrawableNode object should be referenced by proper DrawableEdge object's anchors
        drawable_relation = self.diagram.edges["relation"]
        drawable_source = self.diagram.nodes["source"]
        drawable_target = self.diagram.nodes["target"]

        self.assertEquals(drawable_source, drawable_relation.source_anchor.slot)
        self.assertEquals(drawable_target, drawable_relation.target_anchor.slot)

        # and each DrawableNode object's anchor should reference the
        # DrawableEdge object
        self.assertEquals(drawable_relation, drawable_source.anchors.pop().connector)
        self.assertEquals(drawable_relation, drawable_target.anchors.pop().connector)
Example #20
0
        def side_effect(*args_, **kwargs_):
            d = dict(*args_, **kwargs_)

            def getitem(name):
                return d[name]

            def setitem(name, value):
                d[name] = value

            def contains(name):
                return name in d

            m = Mock()
            m.__getitem__ = Mock(side_effect=getitem)
            m.__setitem__ = Mock(side_effect=setitem)
            m.__contains__ = Mock(side_effect=contains)
            m.get = Mock(side_effect=d.get)
            m.pop = Mock(side_effect=d.pop)
            m.update = Mock(side_effect=d.update)
            self.instances.append(m)
            return m
Example #21
0
    def test__authenticate(self):
        authObj = auth.Authenticator(Mock(), auth.KeyStoneV2Authenticator, Mock(), Mock(), Mock(), Mock())
        # test response code 200
        resp = Mock()
        resp.status = 200
        body = "test_body"

        auth.ServiceCatalog._load = Mock(return_value=1)
        authObj.client._time_request = Mock(return_value=(resp, body))

        sc = authObj._authenticate(Mock(), Mock())
        self.assertEqual(body, sc.catalog)

        # test AmbiguousEndpoints exception
        auth.ServiceCatalog.__init__ = Mock(side_effect=exceptions.AmbiguousEndpoints)
        self.assertRaises(exceptions.AmbiguousEndpoints, authObj._authenticate, Mock(), Mock())

        # test handling KeyError and raising AuthorizationFailure exception
        auth.ServiceCatalog.__init__ = Mock(side_effect=KeyError)
        self.assertRaises(exceptions.AuthorizationFailure, authObj._authenticate, Mock(), Mock())

        # test EndpointNotFound exception
        mock = Mock(side_effect=exceptions.EndpointNotFound)
        auth.ServiceCatalog.__init__ = mock
        self.assertRaises(exceptions.EndpointNotFound, authObj._authenticate, Mock(), Mock())
        mock.side_effect = None

        # test response code 305
        resp.__getitem__ = Mock(return_value="loc")
        resp.status = 305
        body = "test_body"
        authObj.client._time_request = Mock(return_value=(resp, body))

        l = authObj._authenticate(Mock(), Mock())
        self.assertEqual("loc", l)

        # test any response code other than 200 and 305
        resp.status = 404
        exceptions.from_response = Mock(side_effect=ValueError)
        self.assertRaises(ValueError, authObj._authenticate, Mock(), Mock())
Example #22
0
    def case_ambiguous_endpoint(self, scObj):
        scObj.service_type = "reddwarf"
        scObj.service_name = "test_service_name"

        def side_effect_func_service(key):
            if key == "type":
                return "reddwarf"
            elif key == "name":
                return "test_service_name"
            return None

        mock1 = Mock()
        mock1.side_effect = side_effect_func_service
        service1 = Mock()
        service1.get = mock1

        endpoint2 = {"test_attr": "test_attr_value"}
        service1.__getitem__ = Mock(return_value=[endpoint2])
        scObj.catalog[scObj.root_key]["serviceCatalog"] = [service1]
        self.assertRaises(
            exceptions.AmbiguousEndpoints, scObj._url_for, attr="test_attr", filter_value="test_attr_value"
        )
Example #23
0
    def case_no_endpoint_match(self, scObj):
        # empty endpoint list
        scObj.catalog = dict()
        scObj.catalog["endpoints"] = list()
        self.assertRaises(exceptions.EndpointNotFound, scObj._url_for)

        def side_effect_func_ep(attr):
            return "test_attr_value"

        # simulating dict
        endpoint = Mock()
        mock = Mock()
        mock.side_effect = side_effect_func_ep
        endpoint.__getitem__ = mock
        scObj.catalog["endpoints"].append(endpoint)

        # not-empty list but not matching endpoint
        filter_value = "not_matching_value"
        self.assertRaises(exceptions.EndpointNotFound, scObj._url_for, attr="test_attr", filter_value=filter_value)

        filter_value = "test_attr_value"  # so that we have an endpoint match
        scObj.root_key = "access"
        scObj.catalog[scObj.root_key] = dict()
        self.assertRaises(exceptions.EndpointNotFound, scObj._url_for, attr="test_attr", filter_value=filter_value)
 def prepare_orm(self, spec):
     orm = Mock(autospec=spec)
     items = {"social_auth.UserSocialAuth": Mock()}
     orm.__getitem__ = lambda self, name: items[name]
     return orm
Example #25
0
def test_input_sample_init_getitem_noexpand_param_setitem_raises_typerr():
    mock_obj = Mock()
    mock_obj.__getitem__ = Mock(return_value=[0, 1, 2])
    s = InputSample(4, 3, mock_obj, expand=False)
    s[3] = ["s"]
    def it_can_save_nested_collections_on_the_django_backend(self):
        # Prepare an environment where you have a collection nesting another
        # collection
        Doc1Model = Mock(name="DjangoModel1")

        class Doc1(Document):
            id = fields.NumberField()

            class Meta:
                backend_type = "django"
                model = Doc1Model

        class Doc1Collection(Collection):
            document = Doc1

        Doc2Model = Mock(name="DjangoModel2")

        class Doc2(Document):
            id = fields.NumberField()
            name = fields.StringField()
            doc1 = fields.CollectionField(Doc1Collection)

            class Meta:
                backend_type = "django"
                model = Doc2Model

            def map_doc1_field(self):
                return "doc1_map"

        class Doc2Collection(Collection):
            document = Doc2

        Doc3Model = Mock(name="DjangoModel3")

        class Doc3(Document):
            id = fields.NumberField()
            doc2 = fields.CollectionField(Doc2Collection)

            class Meta:
                backend_type = "django"
                model = Doc3Model

        post_data = {"id": 1, "doc2": [{"id": 2, "name": "miss kitty", "doc1": [{"id": 3}]}]}

        # create the document structure
        doc3 = Doc3(post_data)

        # and verify some expectations
        ok_(isinstance(doc3.doc2, Doc2Collection))
        eq_(1, len(doc3.doc2.collection_set))
        ok_(isinstance(doc3.doc2.collection_set[0], Doc2))
        temp_doc = doc3.doc2.collection_set[0]
        eq_("miss kitty", temp_doc.name)
        ok_(isinstance(temp_doc.doc1, Doc1Collection))

        # Now mock the django backend properly
        Doc1Model.DoesNotExist = Exception
        Doc2Model.DoesNotExist = Exception
        Doc3Model.DoesNotExist = Exception

        Doc3Model.objects.get.side_effect = Doc3Model.DoesNotExist
        mock_doc3 = Mock(name="Doc3")
        mock_doc3.id = 1
        mock_doc3.doc2 = Mock()
        mock_doc3.doc2.__dict__["model"] = Doc2Model
        Doc3Model.return_value = mock_doc3
        mock_doc2 = Mock()
        mock_doc2.__dict__["model"] = Doc2Model
        mock_doc2.id = 2
        mock_doc2.doc1_map = Mock(name="doc1_map")
        mock_doc2.doc1_map.__dict__["model"] = Doc1Model

        # I have to mock a queryset for each collection, cause I run an exclude
        # on it everytime I iterate through an item of the collection
        qs_doc2 = Mock(name="queryset2")
        qs_doc2.__len__ = Mock(return_value=1)
        qs_doc2.__getitem__ = Mock()
        qs_doc2.__iter__ = Mock(return_value=iter([mock_doc2]))
        qs_doc2a = Mock(name="queryset-exclude_doc2")
        qs_doc2a.__iter__ = Mock(return_value=iter([]))
        qs_doc2.exclude.return_value = qs_doc2a

        mock_doc3.doc2.all.return_value = qs_doc2
        mock_doc3.doc2.create.return_value = mock_doc2
        mock_doc3.doc2.get.return_value = mock_doc2
        mock_doc1 = Mock()
        mock_doc1.__dict__["model"] = Doc1Model
        mock_doc1.id = 3

        qs_doc1 = Mock(name="queryset1")
        qs_doc1.__len__ = Mock(return_value=1)
        qs_doc1.__getitem__ = Mock()
        qs_doc1.__iter__ = Mock(return_value=iter([mock_doc1]))

        qs_doc1a = Mock(name="queryset-exclude_doc1")
        qs_doc1a.__len__ = Mock(return_value=0)
        qs_doc1a.__getitem__ = Mock()
        qs_doc1a.__iter__ = Mock(return_value=iter([]))
        qs_doc1.exclude.return_value = qs_doc1a

        mock_doc2.doc1_map.all.return_value = qs_doc1
        mock_doc2.doc1_map.get.return_value = mock_doc1
        mock_doc2.doc1_map.create.return_value = mock_doc1

        # saving the model should create all nested relations too
        doc3.save()

        # make sure the right methods have been called.
        ok_(mock_doc2.doc1_map.get.called)
        ok_(mock_doc3.doc2.get.called)
        ok_(Doc3Model.called)
    def it_can_delete_items_from_a_m2m_relation(self):
        Model1 = Mock()
        Model2 = Mock()

        class Doc1(Document):
            id = fields.NumberField()

            class Meta:
                backend_type = "django"
                model = Model1

        class Col1(Collection):
            document = Doc1

        class Doc2(Document):
            id = fields.NumberField()
            col1 = fields.CollectionField(Col1)

            class Meta:
                backend_type = "django"
                model = Model2

        # First return an existing model instance
        mock_doc1a = Mock()
        mock_doc1a.id = 1
        mock_doc1a.__dict__["model"] = Model1

        mock_doc1b = Mock()
        mock_doc1b.id = 2
        mock_doc1b.__dict__["model"] = Model1

        m2m_relation = Mock(name="m2m_relation")
        mock_doc2 = Mock()
        mock_doc2.col1 = m2m_relation
        mock_doc2.id = 3
        mock_doc2.col1.__dict__["model"] = Model1

        # The fetch for the foreign document will raise a BackendDoesNotExist
        # and therefore creates a new model instance
        Model2.objects.get.return_value = mock_doc2

        Queryset = Mock(name="queryset")
        Queryset.__len__ = Mock(return_value=2)
        Queryset.__getitem__ = Mock()
        Queryset.__iter__ = Mock(return_value=iter([mock_doc1a, mock_doc1b]))
        m2m_relation.all.return_value = Queryset

        doc = Doc2({"id": 1, "col1": []})
        doc.save()

        # If the collection is empty we make sure that the backend instances
        # are delete too
        eq_(True, mock_doc1a.delete.called)
        eq_(True, mock_doc1b.delete.called)

        mock_doc1a.reset_mock()
        mock_doc1b.reset_mock()
        m2m_relation.all.reset_mock()

        Queryset1 = Mock(name="queryset1")
        Queryset1.__len__ = Mock(return_value=2)
        Queryset1.__getitem__ = Mock()
        Queryset1.__iter__ = Mock(return_value=iter([mock_doc1a, mock_doc1b]))
        Queryset2 = Mock(name="queryset2")
        Queryset2.__len__ = Mock(return_value=1)
        Queryset2.__getitem__ = Mock()
        Queryset2.__iter__ = Mock(return_value=iter([mock_doc1b]))

        m2m_relation.all.return_value = Queryset1
        Queryset1.exclude.return_value = Queryset2

        doc = Doc2({"id": 1, "col1": [{"id": 1}]})
        doc.save()

        m2m_relation.get.assert_called_once_with(id=1)
        eq_(True, mock_doc1b.delete.called)
    def it_saves_collections_as_m2m_relations(self):
        # prepare the app structure
        Doc1Model = Mock(name="doc1_model")

        class Doc1(Document):
            id = fields.NumberField()

            class Meta:
                backend_type = "django"
                model = Doc1Model

        class Doc1Col(Collection):
            document = Doc1

        Doc2Model = Mock(name="doc2_model")

        class Doc2(Document):
            id = fields.NumberField()
            # The bool field tests an edge case where boolean fields with a
            # default value of False are ignored unfortunately
            bool = fields.BooleanField(default=False)
            col = fields.CollectionField(Doc1Col)

            class Meta:
                backend_type = "django"
                model = Doc2Model

        request = {"id": 1, "col": [{"id": 1}, {"id": 2}]}

        # now mock the underlying model store
        mock_doc2 = Mock(name="mock_doc2_model")
        mock_doc1_1 = Mock(name="mock_doc1_1")
        mock_doc1_2 = Mock(name="mock_doc1_2")

        Doc2Model.objects.get.return_value = mock_doc2

        collection_model = [mock_doc1_2, mock_doc1_1]

        def se(*args, **kwargs):
            return collection_model.pop()

        # I have to mock a queryset for each collection, cause I run an exclude
        # on it everytime I iterate through an item of the collection
        qs_col = Mock(name="queryset")
        qs_col.__len__ = Mock(return_value=2)
        qs_col.__getitem__ = Mock()
        qs_col.__iter__ = Mock(return_value=iter([mock_doc1_1, mock_doc1_2]))

        qs_cola = Mock(name="queryset-exclude_cola")
        qs_cola.__len__ = Mock(return_value=1)
        qs_cola.__getitem__ = Mock()
        qs_cola.__iter__ = Mock(return_value=iter([mock_doc1_2]))

        qs_col.exclude.return_value = qs_cola
        qs_colb = Mock(name="queryset-exclude_colb")
        qs_colb.__len__ = Mock(return_value=1)
        qs_colb.__getitem__ = Mock()
        qs_colb.__iter__ = Mock(return_value=iter([]))
        qs_cola.exclude.return_value = qs_colb

        mock_doc2.col = Mock()
        mock_doc2.col.__dict__["model"] = Doc1Model
        mock_doc2.col.get.side_effect = se
        mock_doc2.col.get.return_value = True
        mock_doc2.col.all.return_value = qs_col

        doc = Doc2(request)

        eq_(2, len(doc.col.collection_set))

        doc.save()

        eq_(True, mock_doc2.col.get.called)
        eq_(True, Doc2Model.objects.get.called)
        Doc2Model.objects.get.assert_called_once_with(id=1)