def test_add_relationship_classes(self):
     """Test that adding relationship classes works."""
     with mock.patch.object(DiffDatabaseMapping, "object_class_list"
                            ) as mock_object_class_list, mock.patch.object(
                                DiffDatabaseMapping,
                                "wide_relationship_class_list"):
         mock_object_class_list.return_value = [
             KeyedTuple([1, "fish"], labels=["id", "name"]),
             KeyedTuple([2, "dog"], labels=["id", "name"]),
         ]
         self.db_map.add_wide_relationship_classes(
             {
                 "name": "fish__dog",
                 "object_class_id_list": [1, 2]
             },
             {
                 "name": "fishy_doggy",
                 "object_class_id_list": [1, 2]
             },
         )
     relationship_classes = self.db_map.session.query(
         self.db_map.DiffRelationshipClass).all()
     self.assertEqual(len(relationship_classes), 4)
     self.assertEqual(relationship_classes[0].name, "fish__dog")
     self.assertEqual(relationship_classes[0].object_class_id, 1)
     self.assertEqual(relationship_classes[1].name, "fish__dog")
     self.assertEqual(relationship_classes[1].object_class_id, 2)
     self.assertEqual(relationship_classes[2].name, "fishy_doggy")
     self.assertEqual(relationship_classes[2].object_class_id, 1)
     self.assertEqual(relationship_classes[3].name, "fishy_doggy")
     self.assertEqual(relationship_classes[3].object_class_id, 2)
 def test_add_relationship_identical_to_existing_one(self):
     """Test that adding a relationship with the same class and same objects as an existing one
     raises an integrity error.
     """
     with mock.patch.object(
             DiffDatabaseMapping,
             "object_list") as mock_object_list, mock.patch.object(
                 DiffDatabaseMapping, "wide_relationship_class_list"
             ) as mock_wide_rel_cls_list, mock.patch.object(
                 DiffDatabaseMapping,
                 "wide_relationship_list") as mock_wide_rel_list:
         mock_object_list.return_value = [
             KeyedTuple([1, 10, "nemo"], labels=["id", "class_id", "name"]),
             KeyedTuple([2, 20, "pluto"], labels=["id", "class_id",
                                                  "name"]),
         ]
         mock_wide_rel_cls_list.return_value = [
             KeyedTuple([1, "10,20", "fish__dog"],
                        labels=["id", "object_class_id_list", "name"])
         ]
         mock_wide_rel_list.return_value = [
             KeyedTuple([1, 1, "1,2", "nemo__pluto"],
                        labels=["id", "class_id", "object_id_list", "name"])
         ]
         with self.assertRaises(SpineIntegrityError):
             self.db_map.add_wide_relationships(
                 {
                     "name": "nemoy__plutoy",
                     "class_id": 1,
                     "object_id_list": [1, 2]
                 },
                 strict=True)
 def test_add_parameter_with_same_name_as_existing_one(self):
     """Test that adding parameter_definitions with an already taken name raises and integrity error."""
     with mock.patch.object(
             DiffDatabaseMapping, "object_class_list"
     ) as mock_object_class_list, mock.patch.object(
             DiffDatabaseMapping,
             "wide_relationship_class_list"), mock.patch.object(
                 DiffDatabaseMapping, "parameter_definition_list"
             ) as mock_parameter_definition_list:
         mock_object_class_list.return_value = [
             KeyedTuple([1, "fish"], labels=["id", "name"])
         ]
         mock_parameter_definition_list.return_value = [
             KeyedTuple([1, 1, "color", None],
                        labels=[
                            "id", "object_class_id", "name",
                            "parameter_value_list_id"
                        ])
         ]
         with self.assertRaises(SpineIntegrityError):
             self.db_map.add_parameter_definitions(
                 {
                     "name": "color",
                     "object_class_id": 2
                 }, strict=True)
 def test_add_parameter_definitions_with_same_name(self):
     """Test that adding two parameter_definitions with the same name adds both of them."""
     with mock.patch.object(
             DiffDatabaseMapping, "object_class_list"
     ) as mock_object_class_list, mock.patch.object(
             DiffDatabaseMapping,
             "wide_relationship_class_list") as mock_wide_rel_cls_list:
         mock_object_class_list.return_value = [
             KeyedTuple([1, "fish"], labels=["id", "name"])
         ]
         mock_wide_rel_cls_list.return_value = [
             KeyedTuple([10, "1,2", "fish__dog"],
                        labels=["id", "object_class_id_list", "name"])
         ]
         self.db_map.add_parameter_definitions(
             {
                 "name": "color",
                 "object_class_id": 1
             }, {
                 "name": "color",
                 "relationship_class_id": 10
             })
     parameter_definitions = self.db_map.session.query(
         self.db_map.DiffParameterDefinition).all()
     self.assertEqual(len(parameter_definitions), 2)
     self.assertEqual(parameter_definitions[0].name, "color")
     self.assertEqual(parameter_definitions[0].object_class_id, 1)
     self.assertIsNone(parameter_definitions[0].relationship_class_id)
 def test_add_relationship_with_invalid_object(self):
     """Test that adding a relationship with an invalid object raises an integrity error.
     """
     with mock.patch.object(
             DiffDatabaseMapping,
             "object_list") as mock_object_list, mock.patch.object(
                 DiffDatabaseMapping, "wide_relationship_class_list"
             ) as mock_wide_rel_cls_list, mock.patch.object(
                 DiffDatabaseMapping, "wide_relationship_list"):
         mock_object_list.return_value = [
             KeyedTuple([1, 10, "nemo"], labels=["id", "class_id", "name"]),
             KeyedTuple([2, 20, "pluto"], labels=["id", "class_id",
                                                  "name"]),
         ]
         mock_wide_rel_cls_list.return_value = [
             KeyedTuple([1, "10,20", "fish__dog"],
                        labels=["id", "object_class_id_list", "name"])
         ]
         with self.assertRaises(SpineIntegrityError):
             self.db_map.add_wide_relationships(
                 {
                     "name": "nemo__pluto",
                     "class_id": 1,
                     "object_id_list": [1, 3]
                 },
                 strict=True)
 def test_add_parameter_with_invalid_class(self):
     """Test that adding parameter_definitions with an invalid (object or relationship) class raises and integrity error."""
     with mock.patch.object(
             DiffDatabaseMapping, "object_class_list"
     ) as mock_object_class_list, mock.patch.object(
             DiffDatabaseMapping,
             "wide_relationship_class_list") as mock_wide_rel_cls_list:
         mock_object_class_list.return_value = [
             KeyedTuple([1, "fish"], labels=["id", "name"])
         ]
         mock_wide_rel_cls_list.return_value = [
             KeyedTuple([10, "1,2", "fish__dog"],
                        labels=["id", "object_class_id_list", "name"])
         ]
         with self.assertRaises(SpineIntegrityError):
             self.db_map.add_parameter_definitions(
                 {
                     "name": "color",
                     "object_class_id": 2
                 }, strict=True)
         with self.assertRaises(SpineIntegrityError):
             self.db_map.add_parameter_definitions(
                 {
                     "name": "color",
                     "relationship_class_id": 9
                 }, strict=True)
 def test_add_relationship_classes_with_same_name(self):
     """Test that adding two relationship classes with the same name only adds one of them."""
     with mock.patch.object(DiffDatabaseMapping, "object_class_list"
                            ) as mock_object_class_list, mock.patch.object(
                                DiffDatabaseMapping,
                                "wide_relationship_class_list"):
         mock_object_class_list.return_value = [
             KeyedTuple([1, "fish"], labels=["id", "name"]),
             KeyedTuple([2, "dog"], labels=["id", "name"]),
         ]
         self.db_map.add_wide_relationship_classes(
             {
                 "name": "dog__fish",
                 "object_class_id_list": [1, 2]
             },
             {
                 "name": "dog__fish",
                 "object_class_id_list": [1, 2]
             },
         )
     relationship_classes = self.db_map.session.query(
         self.db_map.DiffRelationshipClass).all()
     self.assertEqual(len(relationship_classes), 2)
     self.assertEqual(relationship_classes[0].name, "dog__fish")
     self.assertEqual(relationship_classes[0].object_class_id, 1)
     self.assertEqual(relationship_classes[1].name, "dog__fish")
     self.assertEqual(relationship_classes[1].object_class_id, 2)
 def test_add_parameter_values(self):
     """Test that adding parameter values works."""
     with mock.patch.object(
             DiffDatabaseMapping,
             "object_list") as mock_object_list, mock.patch.object(
                 DiffDatabaseMapping, "wide_relationship_list"
             ) as mock_wide_rel_list, mock.patch.object(
                 DiffDatabaseMapping, "parameter_definition_list"
             ) as mock_parameter_definition_list:
         mock_object_list.return_value = [
             KeyedTuple([1, 10, "nemo"], labels=["id", "class_id", "name"]),
             KeyedTuple([2, 20, "pluto"], labels=["id", "class_id",
                                                  "name"]),
         ]
         mock_wide_rel_list.return_value = [
             KeyedTuple([1, 100, "1,2", "nemo__pluto"],
                        labels=["id", "class_id", "object_id_list", "name"])
         ]
         mock_parameter_definition_list.return_value = [
             KeyedTuple(
                 [1, 10, None, "color", None],
                 labels=[
                     "id", "object_class_id", "relationship_class_id",
                     "name", "parameter_value_list_id"
                 ],
             ),
             KeyedTuple(
                 [2, None, 100, "rel_speed", None],
                 labels=[
                     "id", "object_class_id", "relationship_class_id",
                     "name", "parameter_value_list_id"
                 ],
             ),
         ]
         self.db_map.add_parameter_values(
             {
                 "parameter_definition_id": 1,
                 "object_id": 1,
                 "value": '"orange"'
             },
             {
                 "parameter_definition_id": 2,
                 "relationship_id": 1,
                 "value": "125"
             },
         )
     parameter_values = self.db_map.session.query(
         self.db_map.DiffParameterValue).all()
     self.assertEqual(len(parameter_values), 2)
     self.assertEqual(parameter_values[0].parameter_definition_id, 1)
     self.assertEqual(parameter_values[0].object_id, 1)
     self.assertIsNone(parameter_values[0].relationship_id)
     self.assertEqual(parameter_values[0].value, '"orange"')
     self.assertEqual(parameter_values[1].parameter_definition_id, 2)
     self.assertIsNone(parameter_values[1].object_id)
     self.assertEqual(parameter_values[1].relationship_id, 1)
     self.assertEqual(parameter_values[1].value, "125")
 def test_add_parameter_value_with_invalid_object_or_relationship(self):
     """Test that adding a parameter value with an invalid object or relationship raises an
     integrity error."""
     with mock.patch.object(
             DiffDatabaseMapping,
             "object_list") as mock_object_list, mock.patch.object(
                 DiffDatabaseMapping, "wide_relationship_list"
             ) as mock_wide_rel_list, mock.patch.object(
                 DiffDatabaseMapping, "parameter_definition_list"
             ) as mock_parameter_definition_list:
         mock_object_list.return_value = [
             KeyedTuple([1, 10, "nemo"], labels=["id", "class_id", "name"]),
             KeyedTuple([2, 20, "pluto"], labels=["id", "class_id",
                                                  "name"]),
         ]
         mock_wide_rel_list.return_value = [
             KeyedTuple([1, 100, "1,2", "nemo__pluto"],
                        labels=["id", "class_id", "object_id_list", "name"])
         ]
         mock_parameter_definition_list.return_value = [
             KeyedTuple(
                 [1, 10, None, "color", None],
                 labels=[
                     "id", "object_class_id", "relationship_class_id",
                     "name", "parameter_value_list_id"
                 ],
             ),
             KeyedTuple(
                 [2, None, 100, "rel_speed", None],
                 labels=[
                     "id", "object_class_id", "relationship_class_id",
                     "name", "parameter_value_list_id"
                 ],
             ),
         ]
         with self.assertRaises(SpineIntegrityError):
             self.db_map.add_parameter_values(
                 {
                     "parameter_definition_id": 1,
                     "object_id": 3,
                     "value": "orange"
                 },
                 strict=True)
         with self.assertRaises(SpineIntegrityError):
             self.db_map.add_parameter_values(
                 {
                     "parameter_definition_id": 2,
                     "relationship_id": 2,
                     "value": "125"
                 },
                 strict=True)
Beispiel #10
0
    def test_from_json(self):
        """Tests the jsonable.from_json function"""

        self.assertEqual(None, jsonable.from_json(None))
        self.assertEqual({}, jsonable.from_json({}))
        self.assertEqual([], jsonable.from_json([]))

        self.assertEqual({'a': 1}, jsonable.from_json({'a': 1}))
        self.assertEqual([1], jsonable.from_json([1]))
        self.assertEqual([1], jsonable.from_json((1, )))

        from decimal import Decimal
        self.assertEqual(1, jsonable.from_json(Decimal(1)))
        self.assertEqual(1.1, jsonable.from_json(Decimal(1.1)))

        import datetime
        obj = datetime.datetime(2014, 5, 5)
        self.assertEqual(
            obj,
            jsonable.from_json({
                '__cls__': 'datetime.datetime',
                'value': obj.isoformat()
            }))
        self.assertEqual(
            obj,
            jsonable.from_json({
                '__cls__': 'datetime.datetime',
                'value': '2014-05-05T00:00:00.000'
            }))
        self.assertEqual(
            obj.date(),
            jsonable.from_json({
                '__cls__': 'datetime.date',
                'value': '2014-05-05'
            }))

        self.assertEqual(
            'a',
            jsonable.from_json({
                '__cls__': 'a.Exception',
                'message': 'a'
            }).message)

        from sqlalchemy.util import KeyedTuple
        self.assertEqual(
            KeyedTuple([1], labels=['a']),
            jsonable.from_json({
                '__cls__': 'sqlalchemy.util.KeyedTuple',
                '_labels': ['a'],
                'a': 1
            }))

        from dbmanagr.dto.node import NameNode
        self.assertEqual(
            NameNode('a'),
            jsonable.from_json({
                '__cls__': 'dbmanagr.dto.node.NameNode',
                'name': 'a',
                'indent': 0
            }))
Beispiel #11
0
def from_json(d):
    if type(d) is dict:
        if '__cls__' in d:
            classname = d['__cls__']
            if (classname.endswith('Exception') or classname.endswith('Error')
                    or classname.endswith('Exit')):
                return BusinessException(d['message'])
            if classname == 'sqlalchemy.util.KeyedTuple':
                from sqlalchemy.util import KeyedTuple
                return KeyedTuple(map(lambda k: from_json(d[k]), d['_labels']),
                                  labels=d['_labels'])
            if classname == 'datetime.datetime':
                from datetime import datetime
                try:
                    return datetime.strptime(d['value'], "%Y-%m-%dT%H:%M:%S")
                except ValueError:
                    return datetime.strptime(d['value'],
                                             "%Y-%m-%dT%H:%M:%S.%f")
            if classname == 'datetime.date':
                from datetime import datetime
                return datetime.strptime(d['value'], "%Y-%m-%d").date()
            cls = import_class(classname)
            if hasattr(cls, 'from_json'):
                return cls.from_json(d)
        return dict(map(lambda (k, v): (k, from_json(v)), d.iteritems()))
    if type(d) is list or type(d) is tuple:
        return map(from_json, d)
    if type(d) is Decimal:
        if d % 1 == 0:
            return int(d)
        else:
            return float(d)
    return d
Beispiel #12
0
    def test_row_item(self):
        """Tests the RowItem class"""

        row = Row(
            None,
            KeyedTuple(['', -1, '', '', None, None, '', '', '', '', -1, -1],
                       labels=[
                           'database_name', 'pid', 'username', 'client',
                           'transaction_start', 'query_start', 'state',
                           'query', 'blocked', 'blocked_by',
                           'transaction_duration', 'query_duration'
                       ]))

        item = exporter.RowItem(row, None, None, None)

        self.assertEqual(item, item)

        self.assertEqual(
            item,
            exporter.RowItem.from_json({
                'row': row,
                'include': None,
                'exclude': None,
                'substitutes': None
            }))
Beispiel #13
0
 def member2KeyedTuple(self, member):
     keys = list(member.__dict__.keys())
     values = list(member.__dict__.values())
     if '_sa_instance_state' in keys:
         i = keys.index('_sa_instance_state')
         del keys[i]
         del values[i]
     return KeyedTuple(values, labels=keys)
 def test_add_object_with_same_name_as_existing_one(self):
     """Test that adding an object with an already taken name raises an integrity error."""
     with mock.patch.object(DiffDatabaseMapping, "object_class_list"
                            ) as mock_object_class_list, mock.patch.object(
                                DiffDatabaseMapping,
                                "object_list") as mock_object_list:
         mock_object_class_list.return_value = [
             KeyedTuple([1, "fish"], labels=["id", "name"])
         ]
         mock_object_list.return_value = [
             KeyedTuple([1, 1, "nemo"], labels=["id", "class_id", "name"])
         ]
         with self.assertRaises(SpineIntegrityError):
             self.db_map.add_objects({
                 "name": "nemo",
                 "class_id": 1
             },
                                     strict=True)
Beispiel #15
0
    def test_none_entity(self):
        s, (u1, u2, u3, u4) = self._fixture()
        User = self.classes.User

        ua = aliased(User)
        q = s.query(User, ua)
        kt = lambda *x: KeyedTuple(x, ['User', 'useralias'])
        collection = [kt(u1, u2), kt(u1, None), kt(u2, u3)]
        it = loading.merge_result(q, collection)
        eq_([(x and x.id or None, y and y.id or None) for x, y in it],
            [(u1.id, u2.id), (u1.id, None), (u2.id, u3.id)])
Beispiel #16
0
    def test_entity_col_mix_keyed_tuple(self):
        s, (u1, u2, u3, u4) = self._fixture()
        User = self.classes.User

        q = s.query(User, User.id)
        kt = lambda *x: KeyedTuple(x, ['User', 'id'])
        collection = [kt(u1, 1), kt(u2, 2), kt(u3, 7), kt(u4, 8)]
        it = loading.merge_result(q, collection)
        it = list(it)
        eq_([(x.id, y) for x, y in it], [(1, 1), (2, 2), (7, 7), (8, 8)])
        eq_(list(it[0].keys()), ['User', 'id'])
 def test_add_identical_relationships(self):
     """Test that adding two relationships with the same class and same objects only adds the first one.
     """
     with mock.patch.object(
             DiffDatabaseMapping,
             "object_list") as mock_object_list, mock.patch.object(
                 DiffDatabaseMapping, "wide_relationship_class_list"
             ) as mock_wide_rel_cls_list, mock.patch.object(
                 DiffDatabaseMapping, "wide_relationship_list"):
         mock_object_list.return_value = [
             KeyedTuple([1, 10, "nemo"], labels=["id", "class_id", "name"]),
             KeyedTuple([2, 20, "pluto"], labels=["id", "class_id",
                                                  "name"]),
         ]
         mock_wide_rel_cls_list.return_value = [
             KeyedTuple([1, "10,20", "fish__dog"],
                        labels=["id", "object_class_id_list", "name"])
         ]
         self.db_map.add_wide_relationships(
             {
                 "name": "nemo__pluto",
                 "class_id": 1,
                 "object_id_list": [1, 2]
             },
             {
                 "name": "nemoy__plutoy",
                 "class_id": 1,
                 "object_id_list": [1, 2]
             },
         )
     relationships = self.db_map.session.query(
         self.db_map.DiffRelationship).all()
     self.assertEqual(len(relationships), 2)
     self.assertEqual(relationships[0].name, "nemo__pluto")
     self.assertEqual(relationships[0].class_id, 1)
     self.assertEqual(relationships[0].object_id, 1)
     self.assertEqual(relationships[1].name, "nemo__pluto")
     self.assertEqual(relationships[1].class_id, 1)
     self.assertEqual(relationships[1].object_id, 2)
    def test_orgs_condition(self):
        """Test SCMActivityPersons object with an organizations condition"""

        correct = ActivityList(
            (KeyedTuple([
                774, u'John Dickinson',
                datetime.strptime("2013-11-15 15:10:39", datefmt),
                datetime.strptime("2014-01-24 14:53:17", datefmt)
            ],
                        labels=rowlabels),
             KeyedTuple([
                 1094, u'Samuel Merritt',
                 datetime.strptime("2013-11-13 12:52:21", datefmt),
                 datetime.strptime("2014-01-31 13:17:00", datefmt)
             ],
                        labels=rowlabels),
             KeyedTuple([
                 2071, u'Darrell Bishop',
                 datetime.strptime("2013-11-27 00:37:02", datefmt),
                 datetime.strptime("2013-11-27 12:07:42", datefmt)
             ],
                        labels=rowlabels),
             KeyedTuple([
                 2110, u'Jon Snitow',
                 datetime.strptime("2014-01-29 13:02:54", datefmt),
                 datetime.strptime("2014-01-29 13:02:54", datefmt)
             ],
                        labels=rowlabels)))

        period = SCMPeriodCondition(start=self.start, end=self.end)
        nomerges = SCMNomergesCondition()
        orgs = SCMOrgsCondition(orgs=("SwiftStack", "Inktank"),
                                actors="authors")
        data = SCMActivityPersons(datasource=self.session,
                                  name="list_authors",
                                  conditions=(period, nomerges, orgs))
        activity = data.activity()
        print activity
        self.assertEqual(data.activity(), correct)
 def test_add_relationship_class_with_same_name_as_existing_one(self):
     """Test that adding a relationship class with an already taken name raises an integrity error."""
     with mock.patch.object(
             DiffDatabaseMapping, "object_class_list"
     ) as mock_object_class_list, mock.patch.object(
             DiffDatabaseMapping,
             "wide_relationship_class_list") as mock_wide_rel_cls_list:
         mock_object_class_list.return_value = [
             KeyedTuple([1, "fish"], labels=["id", "name"]),
             KeyedTuple([2, "dog"], labels=["id", "name"]),
         ]
         mock_wide_rel_cls_list.return_value = [
             KeyedTuple([1, "1,2", "fish__dog"],
                        labels=["id", "object_class_id_list", "name"])
         ]
         with self.assertRaises(SpineIntegrityError):
             self.db_map.add_wide_relationship_classes(
                 {
                     "name": "fish__dog",
                     "object_class_id_list": [1, 2]
                 },
                 strict=True)
 def test_add_object_with_invalid_class(self):
     """Test that adding an object with a non existing class raises an integrity error."""
     with mock.patch.object(DiffDatabaseMapping,
                            "object_class_list") as mock_object_class_list:
         mock_object_class_list.return_value = [
             KeyedTuple([1, "fish"], labels=["id", "name"])
         ]
         with self.assertRaises(SpineIntegrityError):
             self.db_map.add_objects({
                 "name": "pluto",
                 "class_id": 2
             },
                                     strict=True)
    def test_activity_json(self):
        """Test Period producing JSON"""

        correct_json = """
[
    {
        "id": 12,
        "name": "Fulano Larguiño",
        "period": {
            "end": "2012-11-01T00:00:00",
            "start": "2011-12-01T00:00:00"
        }
    },
    {
        "id": 3,
        "name": "Mengana Corta",
        "period": {
            "end": "2013-02-03T00:00:00",
            "start": "2010-02-03T00:00:00"
        }
    }
]
"""

        rowlabels = ["person_id", "name", "firstdate", "lastdate"]
        list = ActivityList((KeyedTuple([
            12, "Fulano Larguiño",
            datetime(2011, 12, 1),
            datetime(2012, 11, 1)
        ],
                                        labels=rowlabels),
                             KeyedTuple([
                                 3, "Mengana Corta",
                                 datetime(2010, 2, 3),
                                 datetime(2013, 2, 3)
                             ],
                                        labels=rowlabels)))
        activity_json = encode(list, unpicklable=False)
        self.assertTrue(equal_JSON(activity_json, correct_json))
Beispiel #22
0
def unkeyed_tuples(d):
    class KeyedTuple(object):
        # I need a class to have self.__dict__ (object() hasn't got it)
        def __repr__(self):
            # For debugging purposes
            z = u"KeyedTuple: "
            for k, v in self.__dict__.items():
                z += u"{}='{}' ".format(k, v)
            return z

    # FIXME not really a keyed tuple (it lacks '[]' operator)
    obj = KeyedTuple()
    obj.__dict__.update(d)
    return obj
Beispiel #23
0
def jsonable_to_keyed_tuple_sequence(metadata: SQLAMetaData, recursive_set,
                                     kts: KeyedTuplesSequence, kt_sequence):

    keyed_tuples = []
    for kt in kt_sequence:

        typed = []
        for i in range(len(kts)):
            typed.append(
                jsonable_to_typed_values(metadata, kts._types[i], kt[i],
                                         recursive_set))

        keyed_tuples.append(KeyedTuple(typed, kts.keys()))

    return keyed_tuples
 def test_add_relationship_class_with_invalid_object_class(self):
     """Test that adding a relationship class with a non existing object class raises an integrity error."""
     with mock.patch.object(DiffDatabaseMapping, "object_class_list"
                            ) as mock_object_class_list, mock.patch.object(
                                DiffDatabaseMapping,
                                "wide_relationship_class_list"):
         mock_object_class_list.return_value = [
             KeyedTuple([1, "fish"], labels=["id", "name"])
         ]
         with self.assertRaises(SpineIntegrityError):
             self.db_map.add_wide_relationship_classes(
                 {
                     "name": "fish__dog",
                     "object_class_id_list": [1, 2]
                 },
                 strict=True)
Beispiel #25
0
def list_subscription_rule_states(name=None, account=None):
    """Returns a list of with the number of rules per state for a subscription.

    :param name: Name of the subscription
    :param account: Account identifier
    :param session: The database session in use.
    :returns: List with tuple (account, name, state, count)
    """
    if account is not None:
        account = InternalAccount(account)
    subs = subscription.list_subscription_rule_states(name, account)
    for sub in subs:
        # sub is an immutable KeyedTuple so return new KeyedTuple with edited entries
        labels = sub._fields
        d = sub._asdict()
        d['account'] = d['account'].external
        yield KeyedTuple([d[l] for l in labels], labels=labels)
 def test_add_objects_with_same_name(self):
     """Test that adding two objects with the same name only adds one of them."""
     with mock.patch.object(DiffDatabaseMapping,
                            "object_class_list") as mock_object_class_list:
         mock_object_class_list.return_value = [
             KeyedTuple([1, "fish"], labels=["id", "name"])
         ]
         self.db_map.add_objects({
             "name": "nemo",
             "class_id": 1
         }, {
             "name": "nemo",
             "class_id": 1
         })
     objects = self.db_map.session.query(self.db_map.DiffObject).all()
     self.assertEqual(len(objects), 1)
     self.assertEqual(objects[0].name, "nemo")
     self.assertEqual(objects[0].class_id, 1)
 def test_add_relationships(self):
     """Test that adding relationships works."""
     with mock.patch.object(
             DiffDatabaseMapping,
             "object_list") as mock_object_list, mock.patch.object(
                 DiffDatabaseMapping, "wide_relationship_class_list"
             ) as mock_wide_rel_cls_list, mock.patch.object(
                 DiffDatabaseMapping, "wide_relationship_list"):
         mock_object_list.return_value = [
             KeyedTuple([1, 10, "nemo"], labels=["id", "class_id", "name"]),
             KeyedTuple([2, 10, "dory"], labels=["id", "class_id", "name"]),
             KeyedTuple([3, 20, "pluto"], labels=["id", "class_id",
                                                  "name"]),
             KeyedTuple([4, 20, "scooby"],
                        labels=["id", "class_id", "name"]),
         ]
         mock_wide_rel_cls_list.return_value = [
             KeyedTuple([1, "10,20", "fish__dog"],
                        labels=["id", "object_class_id_list", "name"]),
             KeyedTuple([2, "20,10", "dog__fish"],
                        labels=["id", "object_class_id_list", "name"]),
         ]
         self.db_map.add_wide_relationships(
             {
                 "name": "nemo__pluto",
                 "class_id": 1,
                 "object_id_list": [1, 3]
             },
             {
                 "name": "scooby_dory",
                 "class_id": 2,
                 "object_id_list": [4, 2]
             },
         )
     relationships = self.db_map.session.query(
         self.db_map.DiffRelationship).all()
     self.assertEqual(len(relationships), 4)
     self.assertEqual(relationships[0].name, "nemo__pluto")
     self.assertEqual(relationships[0].class_id, 1)
     self.assertEqual(relationships[0].object_id, 1)
     self.assertEqual(relationships[1].name, "nemo__pluto")
     self.assertEqual(relationships[1].class_id, 1)
     self.assertEqual(relationships[1].object_id, 3)
     self.assertEqual(relationships[2].name, "scooby_dory")
     self.assertEqual(relationships[2].class_id, 2)
     self.assertEqual(relationships[2].object_id, 4)
     self.assertEqual(relationships[3].name, "scooby_dory")
     self.assertEqual(relationships[3].class_id, 2)
     self.assertEqual(relationships[3].object_id, 2)
Beispiel #28
0
    def test_as_json(self):
        """Tests the jsonable.as_json function"""

        self.assertEqual(None, jsonable.as_json(None))
        self.assertEqual({}, jsonable.as_json({}))

        import datetime
        obj = datetime.datetime(2014, 5, 5)
        self.assertEqual(
            {
                '__cls__': 'datetime.datetime',
                'value': obj.isoformat()
            }, jsonable.as_json(obj))

        from sqlalchemy.util import KeyedTuple
        self.assertEqual(
            {
                '__cls__': 'sqlalchemy.util.KeyedTuple',
                '_labels': ['a'],
                'a': 1
            }, jsonable.as_json(KeyedTuple([1], labels=['a'])))

        from sqlalchemy.sql.sqltypes import NullType
        self.assertEqual(None, jsonable.as_json(NullType()))

        self.assertEqual([1], jsonable.as_json([1]))
        self.assertEqual(u'a', jsonable.as_json('a'))

        class TestJsonable(jsonable.Jsonable):
            def __init__(self):
                self.a = 1
                self.b = jsonable.Jsonable()

        self.assertEqual(
            {
                '__cls__': "<class 'tests.test_jsonable.TestJsonable'>",
                'a': 1,
                'b': {
                    '__cls__': "<class 'dbmanagr.jsonable.Jsonable'>"
                }
            }, jsonable.as_json(TestJsonable()))
Beispiel #29
0
    def test_row_item(self):
        """Tests the RowItem class"""

        row = Row(
            None,
            KeyedTuple(['', -1, '', '', None, None, '', '', '', '', -1, -1],
                       labels=[
                           'database_name', 'pid', 'username', 'client',
                           'transaction_start', 'query_start', 'state',
                           'query', 'blocked', 'blocked_by',
                           'transaction_duration', 'query_duration'
                       ]))

        item = activity.RowItem(row)

        self.assertEqual(item, item)

        self.assertEqual(item, activity.RowItem.from_json({'row': row}))
        self.assertIsNotNone(
            activity.writer.StatementActivityWriter(
                Options()).itemtostring(item))
Beispiel #30
0
def poster_developmental_issues():
    session = get_session()

    bid = request_arg('bid', int, default=None)
    uid = request_arg('uid', int, default=None)
    if uid is None:
        username = request_arg('user', str)
        user = session.query(User).filter(func.lower(User.name) == func.lower(username)).order_by(desc(User.uid)).first()
        if not user:
            raise APIError('User not found: %s' % username)
    else:
        user = session.query(User).get(uid)
        if not user:
            raise APIError('User ID not found: %s' % uid)

    columns = ['year', 'post_count', 'edit_count', 'threads_created', 'quoted_count', 'quotes_count', 'avg_post_length']
    rows = dal.poster_developmental_issues(session, user.uid, bid).all()
    years = {r.year: r for r in rows}
    for year in range(min(years), max(years)):
        if year not in years:
            years[year] = KeyedTuple([year, 0, 0, 0, 0, 0, 0],labels=columns)
    rows = sorted(years.values(), key=lambda r: r.year)

    if 'csv' in request.args:
        fd = io.StringIO()
        writer = csv.writer(fd)
        writer.writerow(columns)
        for row in rows:
            writer.writerow(row)

        response = Response(fd.getvalue(), mimetype='text/csv')
        response.headers["Content-Disposition"] = "attachment; filename=user-development-%d.csv" % user.uid
        return response
    else:
        return json_response({
            'user': user,
            'years': {r.year: r._asdict() for r in rows},
        })