Commits

Max Noel  committed 38d5257

* Fixed a bug (and added a test that reproduces it) where to_db_dict wouldn't, in fact, json.dumps the json_* datatypes.

  • Participants
  • Parent commits 959a468

Comments (0)

Files changed (2)

File dynamodb_mapper/model.py

         out = {}
         for (name, type_) in type(self).__schema__.iteritems():
             value = getattr(self, name)
-            # Yes, that part is horrible. DynamoDB can't store empty
-            # sets/strings, so we're representing them as missing
-            # attributes on the DB side.
-            if value or value == 0:
-                out[name] = value
-            elif type_ in [json_list, json_dict]:
+            if type_ in [json_list, json_dict]:
                 # json serialization hooks for json_* data types.
                 out[name] = json.dumps(value)
+            elif value or value == 0:
+                # Yes, that part is horrible. DynamoDB can't store empty
+                # sets/strings, so we're representing them as missing
+                # attributes on the DB side.
+                out[name] = value
         return out
 
     def to_json_dict(self):

File dynamodb_mapper/tests/test_model.py

         e2 = DoomEpisode.from_dict({"id": 1})
         self.assertEquals(e2.monsters, {})
 
+    def test_to_db_dict_json_list(self):
+        table_name = "doom_monster"
+        hash_key = "id"
+        schema = {
+            "id": int,
+            "attacks": json_list,
+        }
+
+        attacks = [
+            {'name': 'fireball', 'damage': 10},
+            {'name': 'punch', 'damage': 5}
+        ]
+
+        class DoomMonster(DynamoDBModel):
+            __table__ = table_name
+            __hash_key__ = hash_key
+            __schema__ = schema
+
+        m = DoomMonster()
+        m.id = 1
+        m.attacks = attacks
+
+        d = m.to_db_dict()
+
+        self.assertEquals(d["id"], 1)
+        self.assertEquals(d["attacks"], json.dumps(attacks))
+
+    def test_to_db_dict_json_dict(self):
+        table_name = "doom_episode"
+        hash_key = "id"
+        schema = {
+            "id": int,
+            "monsters": json_dict,
+        }
+
+        monsters = {
+            "cacodemon": [
+                {"x": 10, "y": 20},
+                {"x": 10, "y": 30}
+            ],
+            "imp": [],
+            "cyberdemon": []
+        }
+
+        class DoomEpisode(DynamoDBModel):
+            __table__ = table_name
+            __hash_key__ = hash_key
+            __schema__ = schema
+
+        e = DoomEpisode()
+        e.id = 1
+        e.monsters = monsters
+
+        d = e.to_db_dict()
+
+        self.assertEquals(d["id"], 1)
+        self.assertEquals(d["monsters"], json.dumps(monsters))
+
     @mock.patch("dynamodb_mapper.model.Item")
     @mock.patch("dynamodb_mapper.model.boto")
     def test_save_simple_types(self, m_boto, m_item):