Source

dynamodb-mapper / dynamodb_mapper / tests / test_model.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
import unittest

import json

import mock

from dynamodb_mapper.model import (ConnectionBorg, DynamoDBModel,
    autoincrement_int, MaxRetriesExceededError, MAX_RETRIES,
    ExpectedValueError, _python_to_dynamodb, _dynamodb_to_python, utc_tz)
from boto.exception import DynamoDBResponseError
import datetime


# Hash-only primary key
class DoomEpisode(DynamoDBModel):
    __table__ = "doom_episode"
    __hash_key__ = "id"
    __schema__ = {
        "id": int,
        "name": unicode,
    }


# Composite primary key
class DoomMap(DynamoDBModel):
    __table__ = "doom_map"
    __hash_key__ = "episode_id"
    __range_key__ = "name"
    __schema__ = {
        "episode_id": int,
        "name": unicode,
    }


# autoincrement_int primary key
class LogEntry(DynamoDBModel):
    __table__ = "log_entry"
    __hash_key__ = "id"
    __schema__ = {
        "id": autoincrement_int,
        "text": unicode,
    }


# set attribute
class DoomCampaign(DynamoDBModel):
    __table__ = "doom_campaign"
    __hash_key__ = "id"
    __schema__ = {
        "id": int,
        "name": unicode,
        "cheats": set,
    }


# list attribute
class DoomMonster(DynamoDBModel):
    __table__ = "doom_monster"
    __hash_key__ = "id"
    __schema__ = {
        "id": int,
        "attacks": list,
    }


# dict attribute
class DoomMonsterMap(DynamoDBModel):
    __table__ = "doom_monster_map"
    __hash_key__ = "map_id"
    __schema__ = {
        "map_id": int,
        "monsters": dict,
    }


# datetime.datetime hash key
class Patch(DynamoDBModel):
    __table__ = "patch"
    __hash_key__ = "datetime"
    __schema__ = {
        "datetime": datetime.datetime,
        "description": unicode,
    }


# Composite key with list hash_key, datetime.datetime range_key
class GameReport(DynamoDBModel):
    __table__ = "game_report"
    __hash_key__ = "player_ids"
    __range_key__ = "datetime"
    __schema__ = {
        "player_ids": list,
        "datetime": datetime.datetime,
    }


class TestConnectionBorg(unittest.TestCase):
    def setUp(self):
        ConnectionBorg()._connections.clear()

    def tearDown(self):
        ConnectionBorg()._connections.clear()

    def test_borgness(self):
        aws_access_key_id = "foo"
        aws_secret_access_key = "bar"

        borg1 = ConnectionBorg()
        borg2 = ConnectionBorg()

        borg1.set_credentials(aws_access_key_id, aws_secret_access_key)

        self.assertEquals(borg1._aws_access_key_id, aws_access_key_id)
        self.assertEquals(borg1._aws_secret_access_key, aws_secret_access_key)

        self.assertEquals(borg2._aws_access_key_id, aws_access_key_id)
        self.assertEquals(borg2._aws_secret_access_key, aws_secret_access_key)

    @mock.patch("dynamodb_mapper.model.boto")
    def test_get_table_nominal(self, m_boto):
        m_get_table = m_boto.connect_dynamodb.return_value.get_table

        aws_access_key_id = "foo"
        aws_secret_access_key = "bar"
        table_name = "foo"
        table_name2 = "bar"

        ConnectionBorg().set_credentials(aws_access_key_id, aws_secret_access_key)

        ConnectionBorg().get_table(table_name)
        m_get_table.assert_called_with(table_name)

        ConnectionBorg().get_table(table_name2)
        m_get_table.assert_called_with(table_name2)

        # Should be called only once per thread even when getting multiple tables.
        m_boto.connect_dynamodb.assert_called_once_with(
            aws_access_key_id=aws_access_key_id,
            aws_secret_access_key=aws_secret_access_key
        )

    @mock.patch("dynamodb_mapper.model.boto")
    def test_new_batch_list_nominal(self, m_boto):
        m_new_batch_list = m_boto.connect_dynamodb.return_value.new_batch_list
        ConnectionBorg().new_batch_list()

        m_new_batch_list.assert_called_once()

    @mock.patch("dynamodb_mapper.model.boto")
    def test_create_table_hash_key(self, m_boto):
        m_connection = m_boto.connect_dynamodb.return_value
        m_create_schema = m_connection.create_schema
        m_create_table = m_connection.create_table

        table = ConnectionBorg().create_table(DoomEpisode, 10, 5, False)

        m_create_schema.assert_called_once_with(
            hash_key_name=DoomEpisode.__hash_key__,
            hash_key_proto_value=0,
            range_key_name=None,
            range_key_proto_value=None
        )

        m_create_table.assert_called_once_with(
            DoomEpisode.__table__, m_create_schema.return_value, 10, 5)

        table.refresh.assert_called_once_with(wait_for_active=False)

    @mock.patch("dynamodb_mapper.model.boto")
    def test_create_table_composite_key(self, m_boto):
        m_connection = m_boto.connect_dynamodb.return_value
        m_create_schema = m_connection.create_schema
        m_create_table = m_connection.create_table

        table = ConnectionBorg().create_table(DoomMap, 10, 5, True)

        m_create_schema.assert_called_once_with(
            hash_key_name=DoomMap.__hash_key__,
            hash_key_proto_value=0,
            range_key_name=DoomMap.__range_key__,
            range_key_proto_value=""
        )

        m_create_table.assert_called_once_with(
            DoomMap.__table__, m_create_schema.return_value, 10, 5)

        table.refresh.assert_called_once_with(wait_for_active=True)


class TestTypeConversions(unittest.TestCase):
    def test_python_to_dynamodb_number(self):
        self.assertEquals(0, _python_to_dynamodb(0))
        self.assertEquals(0.0, _python_to_dynamodb(0.0))
        self.assertEquals(10, _python_to_dynamodb(10))
        self.assertEquals(10.0, _python_to_dynamodb(10.0))

    def test_dynamodb_to_python_number(self):
        self.assertEquals(0, _dynamodb_to_python(int, 0))
        self.assertEquals(0.0, _dynamodb_to_python(float, 0.0))
        self.assertEquals(10, _dynamodb_to_python(int, 10))
        self.assertEquals(10.0, _dynamodb_to_python(float, 10.0))

    def test_python_to_dynamodb_unicode(self):
        self.assertEquals(u"hello", _python_to_dynamodb(u"hello"))
        # Empty strings become missing attributes
        self.assertIsNone(_python_to_dynamodb(u""))

    def test_dynamodb_to_python_unicode(self):
        self.assertEquals(u"hello", _dynamodb_to_python(unicode, u"hello"))
        # Missing attributes become empty strings
        self.assertEquals(u"", _dynamodb_to_python(unicode, None))

    def test_python_to_dynamodb_set(self):
        self.assertEquals(set([1, 2, 3]), _python_to_dynamodb(set([1, 2, 3])))
        self.assertEquals(
            set(["foo", "bar", "baz"]),
            _python_to_dynamodb(set(["foo", "bar", "baz"])))
        # Empty sets become missing attributes
        self.assertIsNone(_python_to_dynamodb(set()))

    def test_dynamodb_to_python_set(self):
        self.assertEquals(set([1, 2, 3]), _dynamodb_to_python(set, set([1, 2, 3])))
        self.assertEquals(
            set(["foo", "bar", "baz"]),
            _dynamodb_to_python(set, set(["foo", "bar", "baz"])))
        # Empty sets become missing attributes
        self.assertEquals(set(), _dynamodb_to_python(set, None))

    def test_python_to_dynamodb_list(self):
        attacks = [
            {'name': 'fireball', 'damage': 10},
            {'name': 'punch', 'damage': 5}
        ]

        self.assertEquals(
            json.dumps(attacks, sort_keys=True),
            _python_to_dynamodb(attacks))
        self.assertEquals("[]", _python_to_dynamodb([]))

    def test_dynamodb_to_python_list(self):
        attacks = [
            {'name': 'fireball', 'damage': 10},
            {'name': 'punch', 'damage': 5}
        ]

        self.assertEquals(
            attacks,
            _dynamodb_to_python(list, json.dumps(attacks, sort_keys=True)))
        self.assertEquals([], _dynamodb_to_python(list, "[]"))

    def test_python_to_dynamodb_dict(self):
        monsters = {
            "cacodemon": [
                {"x": 10, "y": 20},
                {"x": 10, "y": 30}
            ],
            "imp": [],
            "cyberdemon": []
        }

        self.assertEquals(
            json.dumps(monsters, sort_keys=True),
            _python_to_dynamodb(monsters))
        self.assertEquals("{}", _python_to_dynamodb({}))

    def test_dynamodb_to_python_dict(self):
        monsters = {
            "cacodemon": [
                {"x": 10, "y": 20},
                {"x": 10, "y": 30}
            ],
            "imp": [],
            "cyberdemon": []
        }

        self.assertEquals(
            monsters,
            _dynamodb_to_python(dict, json.dumps(monsters, sort_keys=True)))
        self.assertEquals({}, _dynamodb_to_python(dict, "{}"))

    def test_dynamodb_to_python_datetime(self):
        self.assertEquals(
            datetime.datetime(2012, 05, 31, 12, 0, 0, tzinfo=utc_tz),
            _dynamodb_to_python(datetime.datetime,
                                "2012-05-31T12:00:00.000000+00:00"))
        self.assertEquals(
            datetime.datetime(2010, 11, 1, 4, 0, 0, tzinfo=utc_tz),
            _dynamodb_to_python(datetime.datetime,
                                "2010-11-01T04:00:00.000000Z"))

    @mock.patch("dynamodb_mapper.model.datetime")
    def test_dynamodb_to_python_default(self, m_datetime):
        # There's some fairly ugly mock/datetime juggling in that test, because
        # datetime is written in C, so I can't simply overwrite its attributes
        # or those of its members:
        # the entire module must be mocked, and precise bits un-mocked as
        # required. Joy.
        m_datetime.timedelta = datetime.timedelta
        m_now = datetime.datetime.now(tz=utc_tz)
        m_datetime.datetime.now.return_value = m_now
        self.assertEquals(
            m_now,
            _dynamodb_to_python(m_datetime.datetime, None))

    def test_dynamodb_to_python_datetime_notz(self):
        # Timezone info is mandatory
        self.assertRaises(
            ValueError,
            _dynamodb_to_python, datetime.datetime, "2012-05-31T12:00:00.000000")

    def test_python_to_dynamodb_datetime(self):
        self.assertEquals(
            "2012-05-31T12:00:00.000000+00:00",
            _python_to_dynamodb(datetime.datetime(2012, 05, 31, 12, 0, 0, tzinfo=utc_tz)))

    def test_python_to_dynamodb_datetime_notz(self):
        self.assertRaises(
            ValueError,
            _python_to_dynamodb, datetime.datetime(2012, 05, 31, 12, 0, 0))


class TestDynamoDBModel(unittest.TestCase):
    def test_build_default_values(self):
        d = DoomEpisode()
        self.assertEquals(d.id, 0)
        self.assertEquals(d.name, u"")

        # Using to_json_dict because to_db_dict omits empty values
        d_dict = d.to_json_dict()
        self.assertEquals(d_dict["id"], d.id)
        self.assertEquals(d_dict["name"], d.name)

    def test_build_from_dict(self):
        d_dict = {"id": 1, "name": "Knee-deep in the Dead"}
        d = DoomEpisode.from_dict(d_dict)
        self.assertEquals(d_dict["id"], d.id)
        self.assertEquals(d_dict["name"], d.name)

    def test_build_from_dict_missing_attrs(self):
        d = DoomCampaign.from_dict({})
        self.assertEquals(d.id, 0)
        self.assertEquals(d.name, u"")
        self.assertEquals(d.cheats, set())

    def test_build_from_dict_json_list(self):
        attacks = [
            {'name': 'fireball', 'damage': 10},
            {'name': 'punch', 'damage': 5}
        ]

        m = DoomMonster.from_dict({
            "id": 1,
            "attacks": json.dumps(attacks, sort_keys=True)
        })

        self.assertEquals(m.attacks, attacks)

        # Test default values
        m2 = DoomMonster.from_dict({"id": 1})
        self.assertEquals(m2.attacks, [])

    def test_build_from_dict_json_dict(self):
        monsters = {
            "cacodemon": [
                {"x": 10, "y": 20},
                {"x": 10, "y": 30}
            ],
            "imp": [],
            "cyberdemon": []
        }

        e = DoomMonsterMap.from_dict({
            "map_id": 1,
            "monsters": json.dumps(monsters, sort_keys=True)
        })
        self.assertEquals(e.monsters, monsters)

        e2 = DoomMonsterMap.from_dict({"map_id": 1})
        self.assertEquals(e2.monsters, {})

    def test_to_db_dict_json_list(self):
        attacks = [
            {'name': 'fireball', 'damage': 10},
            {'name': 'punch', 'damage': 5}
        ]

        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, sort_keys=True))

    def test_to_db_dict_json_dict(self):
        monsters = {
            "cacodemon": [
                {"x": 10, "y": 20},
                {"x": 10, "y": 30}
            ],
            "imp": [],
            "cyberdemon": []
        }

        e = DoomMonsterMap()
        e.map_id = 1
        e.monsters = monsters

        d = e.to_db_dict()

        self.assertEquals(d["map_id"], 1)
        self.assertEquals(d["monsters"], json.dumps(monsters, sort_keys=True))

    @mock.patch("dynamodb_mapper.model.Item")
    @mock.patch("dynamodb_mapper.model.boto")
    def test_save_simple_types(self, m_boto, m_item):
        DoomEpisode().save()

        m_item.return_value.put.assert_called_once()

    @mock.patch("dynamodb_mapper.model.Item")
    @mock.patch("dynamodb_mapper.model.boto")
    def test_save_sets(self, m_boto, m_item):
        l = DoomCampaign()
        l.id = 1
        l.name = "Knee-deep in the Dead"
        l.cheats = set(["iddqd", "idkfa", "idclip"])
        l.save()

        m_item.assert_called_once_with(
            mock.ANY, attrs={"id": l.id, "name": l.name, "cheats": l.cheats})

    @mock.patch("dynamodb_mapper.model.Item")
    @mock.patch("dynamodb_mapper.model.boto")
    def test_save_empty_sets(self, m_boto, m_item):
        l = DoomCampaign()
        l.id = 1
        l.cheats = set()
        l.save()

        m_item.assert_called_once_with(mock.ANY, attrs={"id": 1})

    @mock.patch("dynamodb_mapper.model.Item")
    @mock.patch("dynamodb_mapper.model.boto")
    def test_save_empty_strings(self, m_boto, m_item):
        e = DoomEpisode()
        e.id = 0
        e.save()

        m_item.assert_called_once_with(mock.ANY, attrs={"id": 0})

    @mock.patch("dynamodb_mapper.model.ConnectionBorg.get_table")
    def test_get_by_hash_key(self, m_get_table):
        m_table = m_get_table.return_value

        DoomEpisode.get(1)
        m_table.get_item.assert_called_once_with(hash_key=1, range_key=None, consistent_read=False)

    @mock.patch("dynamodb_mapper.model.ConnectionBorg.get_table")
    def test_get_by_composite_key(self, m_get_table):
        m_table = m_get_table.return_value

        DoomMap.get(1, "Knee-deep in the dead")
        m_table.get_item.assert_called_once_with(
            hash_key=1, range_key="Knee-deep in the dead", consistent_read=False)

    @mock.patch("dynamodb_mapper.model.ConnectionBorg.get_table")
    def test_get_by_hash_key_magic_types(self, m_get_table):
        m_table = m_get_table.return_value
        d = datetime.datetime(2012, 5, 31, 12, 0, 0, tzinfo=utc_tz)
        d_text = "2012-05-31T12:00:00.000000+00:00"
        m_table.get_item.return_value = {"datetime": d_text}

        Patch.get(d)
        m_table.get_item.assert_called_once_with(
            hash_key=d_text, range_key=None, consistent_read=False)

    @mock.patch("dynamodb_mapper.model.ConnectionBorg.get_table")
    def test_get_by_composite_key_magic_types(self, m_get_table):
        m_table = m_get_table.return_value
        d = datetime.datetime(2012, 5, 31, 12, 0, 0, tzinfo=utc_tz)
        d_text = "2012-05-31T12:00:00.000000+00:00"
        players = ["duke", "doomguy", "blackowicz"]
        players_text = json.dumps(players)
        m_table.get_item.return_value = {
            "player_ids": players_text,
            "datetime": d_text
        }

        GameReport.get(players, d)
        m_table.get_item.assert_called_once_with(
            hash_key=players_text, range_key=d_text, consistent_read=False)

    @mock.patch("dynamodb_mapper.model.Item")
    @mock.patch("dynamodb_mapper.model.boto")
    def test_save_autoincrement_int(self, m_boto, m_item):
        m_item_instance = m_item.return_value
        m_item_instance.hash_key_name = "id"
        max_item = m_item_instance.table.get_item.return_value
        max_item.__getitem__.return_value = 2

        l = LogEntry()
        l.text = "Everybody's dead, Dave."
        l.save()

        m_item.assert_called_with(mock.ANY, attrs={"id": 0, "text": l.text})
        m_item.return_value.__setitem__.assert_called_with("id", 3)
        m_item_instance.save.assert_called()

    @mock.patch("dynamodb_mapper.model.Item")
    @mock.patch("dynamodb_mapper.model.boto")
    def test_save_autoincrement_int_conflict(self, m_boto, m_item):
        m_item_instance = m_item.return_value
        m_item_instance.hash_key_name = "id"
        max_item = m_item_instance.table.get_item.return_value
        max_item.__getitem__.return_value = 2

        # The first call (id=3) will be rejected.
        error = DynamoDBResponseError(
            None, None, {"__type": "ConditionalCheckFailedException"})

        def err(*args, **kw):
            # Clear the error then fail
            m_item_instance.put.side_effect = None
            raise error

        m_item_instance.put.side_effect = err

        l = LogEntry()
        l.text = "Everybody's dead, Dave."
        l.save()

        m_item.return_value.__setitem__.assert_called_with("id", 3)
        self.assertEquals(m_item.return_value.__setitem__.call_count, 2)

    @mock.patch("dynamodb_mapper.model.Item")
    @mock.patch("dynamodb_mapper.model.boto")
    def test_save_autoincrement_int_max_retries(self, m_boto, m_item):
        m_item_instance = m_item.return_value
        m_item_instance.hash_key_name = "id"
        max_item = m_item_instance.table.get_item.return_value
        max_item.__getitem__.return_value = 2
        error = DynamoDBResponseError(
            None, None, {"__type": "ConditionalCheckFailedException"})
        # the put call will never succeed
        m_item_instance.put.side_effect = error

        l = LogEntry()
        l.text = "Everybody's dead, Dave."
        self.assertRaises(MaxRetriesExceededError, l.save)

        self.assertEquals(m_item_instance.put.call_count, MAX_RETRIES)

    @mock.patch("dynamodb_mapper.model.Item")
    @mock.patch("dynamodb_mapper.model.boto")
    def test_save_expected_values(self, m_boto, m_item):
        m_item_instance = m_item.return_value

        name = "Knee-deep in the Dead"
        cheats = set(["iddqd", "idkfa"])

        c = DoomCampaign()
        c.id = 0
        c.name = name
        c.cheats = cheats

        c.save(expected_values={"id": 1, "name": name, "cheats": cheats})
        m_item_instance.put.assert_called_with({"id": 1, "name": name, "cheats": cheats})

    @mock.patch("dynamodb_mapper.model.Item")
    @mock.patch("dynamodb_mapper.model.boto")
    def test_save_expected_values_false_values(self, m_boto, m_item):
        m_item_instance = m_item.return_value
        error = DynamoDBResponseError(
            None, None, {"__type": "ConditionalCheckFailedException"})
        m_item_instance.put.side_effect = error

        name = "Knee-deep in the Dead"
        cheats = set(["iddqd", "idkfa"])

        c = DoomCampaign()
        c.id = 0
        c.name = name
        c.cheats = cheats

        self.assertRaises(
            ExpectedValueError,
            c.save, expected_values={"id": 0, "name": "", "cheats": set()}
        )

    @mock.patch("dynamodb_mapper.model.Item")
    @mock.patch("dynamodb_mapper.model.boto")
    def test_save_expected_values_conditional_check_failed(self, m_boto, m_item):
        m_item_instance = m_item.return_value
        m_item_instance.put.side_effect

        name = "Knee-deep in the Dead"
        cheats = set(["iddqd", "idkfa"])

        c = DoomCampaign()
        c.id = 0
        c.name = name
        c.cheats = cheats

        c.save(expected_values={"id": 1, "name": name, "cheats": cheats})

    def test_query(self):
        pass

    def test_scan(self):
        pass