-
-
Notifications
You must be signed in to change notification settings - Fork 196
/
persistence_spec.rb
1108 lines (889 loc) · 31.8 KB
/
persistence_spec.rb
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe Dynamoid::Persistence do
let(:address) { Address.new }
context 'without AWS keys' do
unless ENV['ACCESS_KEY'] && ENV['SECRET_KEY']
before do
Dynamoid.adapter.delete_table(Address.table_name) if Dynamoid.adapter.list_tables.include?(Address.table_name)
end
it 'creates a table' do
Address.create_table(table_name: Address.table_name)
expect(Dynamoid.adapter.list_tables).to include 'dynamoid_tests_addresses'
end
it 'checks if a table already exists' do
Address.create_table(table_name: Address.table_name)
expect(Address.table_exists?(Address.table_name)).to be_truthy
expect(Address.table_exists?('crazytable')).to be_falsey
end
end
end
describe 'delete_table' do
it 'deletes the table' do
Address.create_table
Address.delete_table
tables = Dynamoid.adapter.list_tables
expect(tables.include?(Address.table_name)).to be_falsey
end
end
describe 'record deletion' do
let(:klass) do
Class.new do
include Dynamoid::Document
table name: :addresses
field :city
before_destroy {|i|
# Halting the callback chain in active record changed with Rails >= 5.0.0.beta1
# We now have to throw :abort to halt the callback chain
# See: https://github.com/rails/rails/commit/bb78af73ab7e86fd9662e8810e346b082a1ae193
if ActiveModel::VERSION::MAJOR < 5
false
else
throw :abort
end
}
end
end
describe 'destroy' do
it 'deletes an item completely' do
@user = User.create(name: 'Josh')
@user.destroy
expect(Dynamoid.adapter.read('dynamoid_tests_users', @user.id)).to be_nil
end
it 'returns false when destroy fails (due to callback)' do
a = klass.create!
expect(a.destroy).to eql false
expect(klass.first.id).to eql a.id
end
end
describe 'destroy!' do
it 'deletes the item' do
address.save!
address.destroy!
expect(Address.count).to eql 0
end
it 'raises exception when destroy fails (due to callback)' do
a = klass.create!
expect { a.destroy! }.to raise_error(Dynamoid::Errors::RecordNotDestroyed)
end
end
end
it 'assigns itself an id on save' do
address.save
expect(Dynamoid.adapter.read('dynamoid_tests_addresses', address.id)[:id]).to eq address.id
end
it 'prevents concurrent writes to tables with a lock_version' do
address.save!
a1 = address
a2 = Address.find(address.id)
a1.city = 'Seattle'
a2.city = 'San Francisco'
a1.save!
expect { a2.save! }.to raise_exception(Dynamoid::Errors::StaleObjectError)
end
it 'assigns itself an id on save only if it does not have one' do
address.id = 'test123'
address.save
expect(Dynamoid.adapter.read('dynamoid_tests_addresses', 'test123')).to_not be_empty
end
it 'has a table name' do
expect(Address.table_name).to eq 'dynamoid_tests_addresses'
end
context 'with namespace is empty' do
def reload_address
Object.send(:remove_const, 'Address')
load 'app/models/address.rb'
end
namespace = Dynamoid::Config.namespace
before do
reload_address
Dynamoid.configure do |config|
config.namespace = ''
end
end
after do
reload_address
Dynamoid.configure do |config|
config.namespace = namespace
end
end
it 'does not add a namespace prefix to table names' do
table_name = Address.table_name
expect(Dynamoid::Config.namespace).to be_empty
expect(table_name).to eq 'addresses'
end
end
context 'with timestamps set to false' do
def reload_address
Object.send(:remove_const, 'Address')
load 'app/models/address.rb'
end
timestamps = Dynamoid::Config.timestamps
before do
reload_address
Dynamoid.configure do |config|
config.timestamps = false
end
end
after do
reload_address
Dynamoid.configure do |config|
config.timestamps = timestamps
end
end
it 'sets nil to created_at and updated_at' do
address = Address.create
expect(address.created_at).to be_nil
expect(address.updated_at).to be_nil
end
end
it 'deletes an item completely' do
@user = User.create(name: 'Josh')
@user.destroy
expect(Dynamoid.adapter.read('dynamoid_tests_users', @user.id)).to be_nil
end
it 'keeps string attributes as strings' do
@user = User.new(name: 'Josh')
expect(@user.send(:dump)[:name]).to eq 'Josh'
end
it 'keeps raw Hash attributes as a Hash' do
config = {acres: 5, trees: {cyprus: 30, poplar: 10, joshua: 1}, horses: ['Lucky', 'Dummy'], lake: 1, tennis_court: 1}
@addr = Address.new(config: config)
expect(@addr.send(:dump)[:config]).to eq config
end
it 'keeps raw Array attributes as an Array' do
config = ['windows', 'roof', 'doors']
@addr = Address.new(config: config)
expect(@addr.send(:dump)[:config]).to eq config
end
it 'keeps raw String attributes as a String' do
config = 'Configy'
@addr = Address.new(config: config)
expect(@addr.send(:dump)[:config]).to eq config
end
it 'keeps raw Number attributes as a Number' do
config = 100
@addr = Address.new(config: config)
expect(@addr.send(:dump)[:config]).to eq config
end
context 'transforms booleans' do
it 'handles true' do
deliverable = true
@addr = Address.new(deliverable: deliverable)
expect(@addr.send(:dump)[:deliverable]).to eq 't'
end
it 'handles false' do
deliverable = false
@addr = Address.new(deliverable: deliverable)
expect(@addr.send(:dump)[:deliverable]).to eq 'f'
end
it 'handles t' do
deliverable = 't'
@addr = Address.new(deliverable: deliverable)
expect(@addr.send(:dump)[:deliverable]).to eq 't'
end
it 'handles f' do
deliverable = 'f'
@addr = Address.new(deliverable: deliverable)
expect(@addr.send(:dump)[:deliverable]).to eq 'f'
end
end
context 'when dumps datetime attribute' do
it 'loads time in local time zone if config.application_timezone == :local', application_timezone: :local do
time = Time.now
user = User.create(last_logged_in_at: time)
user = User.find(user.id)
expect(user.last_logged_in_at).to be_a(DateTime)
# we can't compare objects directly because lose precision of milliseconds in conversions
expect(user.last_logged_in_at.to_s).to eq time.to_datetime.to_s
end
it 'loads time in specified time zone if config.application_timezone == time zone name', application_timezone: 'Hawaii' do
time = '2017-06-20 08:00:00 +0300'.to_time
user = User.create(last_logged_in_at: time)
user = User.find(user.id)
expect(user.last_logged_in_at).to eq '2017-06-19 19:00:00 -1000'.to_datetime # Hawaii UTC-10
end
it 'loads time in UTC if config.application_timezone = :utc', application_timezone: :utc do
time = '2017-06-20 08:00:00 +0300'.to_time
user = User.create(last_logged_in_at: time)
user = User.find(user.id)
expect(user.last_logged_in_at).to eq '2017-06-20 05:00:00 +0000'.to_datetime
end
end
it 'dumps date attributes' do
address = Address.create(registered_on: '2017-06-18'.to_date)
expect(Address.find(address.id).registered_on).to eq '2017-06-18'.to_date
# check internal format - days since 1970-01-01
expect(Address.find(address.id).send(:dump)[:registered_on])
.to eq ('2017-06-18'.to_date - Date.new(1970, 1, 1)).to_i
end
it 'dumps integer attributes' do
@subscription = Subscription.create(length: 10)
expect(@subscription.send(:dump)[:length]).to eq 10
end
it 'dumps set attributes' do
@subscription = Subscription.create(length: 10)
@magazine = @subscription.magazine.create
expect(@subscription.send(:dump)[:magazine_ids]).to eq Set[@magazine.hash_key]
end
it 'handles nil attributes properly' do
expect(Address.undump(nil)).to be_a(Hash)
end
it 'dumps and undump a serialized field' do
address.options = (hash = {:x => [1, 2], 'foobar' => 3.14})
expect(Address.undump(address.send(:dump))[:options]).to eq hash
end
it 'dumps and undumps an integer in number field' do
expect(Address.undump(Address.new(latitude: 123).send(:dump))[:latitude]).to eq 123
end
it 'dumps and undumps a float in number field' do
expect(Address.undump(Address.new(latitude: 123.45).send(:dump))[:latitude]).to eq 123.45
end
it 'dumps and undumps a BigDecimal in number field' do
expect(Address.undump(Address.new(latitude: BigDecimal.new(123.45, 3)).send(:dump))[:latitude]).to eq 123
end
it 'dumps and undumps a date' do
date = '2017-06-18'.to_date
expect(
Address.undump(Address.new(registered_on: date).send(:dump))[:registered_on]
).to eq date
end
it 'supports empty containers in `serialized` fields' do
u = User.create(name: 'Philip')
u.favorite_colors = Set.new
u.save!
u = User.find(u.id)
expect(u.favorite_colors).to eq Set.new
end
it 'supports array being empty' do
user = User.create(todo_list: [])
expect(User.find(user.id).todo_list).to eq []
end
it 'saves empty set as nil' do
tweet = Tweet.create(group: 'one', tags: [])
expect(Tweet.find_by_tweet_id(tweet.tweet_id).tags).to eq nil
end
it 'saves empty string as nil' do
user = User.create(name: '')
expect(User.find(user.id).name).to eq nil
end
it 'saves attributes with nil value' do
user = User.create(name: nil)
expect(User.find(user.id).name).to eq nil
end
it 'supports container types being nil' do
u = User.create(name: 'Philip')
u.todo_list = nil
u.save!
u = User.find(u.id)
expect(u.todo_list).to be_nil
end
[true, false].each do |bool|
it "dumps a #{bool} boolean field" do
address.deliverable = bool
expect(Address.undump(address.send(:dump))[:deliverable]).to eq bool
end
end
describe "Boolean field" do
context "stored in string format" do
let(:klass) do
new_class do
field :active, :boolean
end
end
it "saves false as 'f'" do
obj = klass.create(active: false)
attributes = Dynamoid.adapter.get_item(klass.table_name, obj.hash_key)
expect(attributes[:active]).to eq "f"
end
it "saves 'f' as 'f'" do
obj = klass.create(active: "f")
attributes = Dynamoid.adapter.get_item(klass.table_name, obj.hash_key)
expect(attributes[:active]).to eq "f"
end
it "saves true as 't'" do
obj = klass.create(active: true)
attributes = Dynamoid.adapter.get_item(klass.table_name, obj.hash_key)
expect(attributes[:active]).to eq "t"
end
it "saves 't' as 't'" do
obj = klass.create(active: 't')
attributes = Dynamoid.adapter.get_item(klass.table_name, obj.hash_key)
expect(attributes[:active]).to eq "t"
end
end
context "stored in boolean format" do
let(:klass) do
new_class do
field :active, :boolean, store_as_native_boolean: true
end
end
it "saves false as false" do
obj = klass.create(active: false)
attributes = Dynamoid.adapter.get_item(klass.table_name, obj.hash_key)
expect(attributes[:active]).to eq false
end
it "saves true as true" do
obj = klass.create(active: true)
attributes = Dynamoid.adapter.get_item(klass.table_name, obj.hash_key)
expect(attributes[:active]).to eq true
end
it "saves and loads boolean field correctly" do
obj = klass.create(active: true)
expect(klass.find(obj.hash_key).active).to eq true
obj = klass.create(active: false)
expect(klass.find(obj.hash_key).active).to eq false
end
end
end
describe "Datetime field" do
context "Stored in :number format" do
let(:klass) do
new_class do
field :sent_at, :datetime
end
end
it "saves time as :number" do
time = Time.now
obj = klass.create(sent_at: time)
attributes = Dynamoid.adapter.get_item(klass.table_name, obj.hash_key)
expect(attributes[:sent_at]).to eq BigDecimal.new(time.to_f.to_s)
end
it "saves date as :number" do
date = Date.today
obj = klass.create(sent_at: date)
attributes = Dynamoid.adapter.get_item(klass.table_name, obj.hash_key)
expect(attributes[:sent_at]).to eq BigDecimal.new(date.to_time.to_f.to_s)
end
end
context "Stored in :string format" do
let(:klass) do
new_class do
field :sent_at, :datetime, { store_as_string: true }
end
end
it "saves time as a :string" do
time = Time.now
obj = klass.create(sent_at: time)
attributes = Dynamoid.adapter.get_item(klass.table_name, obj.hash_key)
expect(attributes[:sent_at]).to eq time.iso8601
end
it "saves date as :string" do
date = Date.today
obj = klass.create(sent_at: date)
attributes = Dynamoid.adapter.get_item(klass.table_name, obj.hash_key)
expect(attributes[:sent_at]).to eq date.to_time.iso8601
end
it 'saves as :string if global option :store_date_time_as_string is true' do
klass2 = new_class do
field :sent_at, :datetime
end
store_datetime_as_string = Dynamoid.config.store_datetime_as_string
Dynamoid.config.store_datetime_as_string = true
time = Time.now
obj = klass2.create(sent_at: time)
attributes = Dynamoid.adapter.get_item(klass2.table_name, obj.hash_key)
expect(attributes[:sent_at]).to eq time.iso8601
Dynamoid.config.store_datetime_as_string = store_datetime_as_string
end
it 'prioritize field option over global one' do
store_datetime_as_string = Dynamoid.config.store_datetime_as_string
Dynamoid.config.store_datetime_as_string = false
time = Time.now
obj = klass.create(sent_at: time)
attributes = Dynamoid.adapter.get_item(klass.table_name, obj.hash_key)
expect(attributes[:sent_at]).to eq time.iso8601
Dynamoid.config.store_datetime_as_string = store_datetime_as_string
end
end
end
describe 'Date field' do
context 'stored in :string format' do
it 'stores in ISO 8601 format' do
klass = new_class do
field :signed_up_on, :date, store_as_string: true
end
model = klass.create(signed_up_on: '25-09-2017'.to_date)
expect(klass.find(model.id).signed_up_on).to eq('25-09-2017'.to_date)
attributes = Dynamoid.adapter.get_item(klass.table_name, model.id)
expect(attributes[:signed_up_on]).to eq '2017-09-25'
end
it 'stores in string format when global option :store_date_as_string is true' do
klass = new_class do
field :signed_up_on, :date
end
store_date_as_string = Dynamoid.config.store_date_as_string
Dynamoid.config.store_date_as_string = true
model = klass.create(signed_up_on: '25-09-2017'.to_date)
attributes = Dynamoid.adapter.get_item(klass.table_name, model.id)
expect(attributes[:signed_up_on]).to eq '2017-09-25'
Dynamoid.config.store_date_as_string = store_date_as_string
end
it 'prioritize field option over global one' do
klass = new_class do
field :signed_up_on, :date, store_as_string: true
end
store_date_as_string = Dynamoid.config.store_date_as_string
Dynamoid.config.store_date_as_string = false
model = klass.create(signed_up_on: '25-09-2017'.to_date)
attributes = Dynamoid.adapter.get_item(klass.table_name, model.id)
expect(attributes[:signed_up_on]).to eq '2017-09-25'
Dynamoid.config.store_date_as_string = store_date_as_string
end
end
end
describe "Set field" do
let(:klass) do
new_class do
field :string_set, :set
field :integer_set, :set, { of: :integer }
field :number_set, :set, { of: :number }
end
end
it "stored a string set" do
obj = klass.create(string_set: Set.new(['a','b']))
expect(obj.reload[:string_set]).to eq(Set.new(['a','b']))
end
it "stored an integer set" do
obj = klass.create(integer_set: Set.new([1,2]))
expect(obj.reload[:integer_set]).to eq(Set.new([1,2]))
end
it "stored a number set" do
obj = klass.create(number_set: Set.new([1,2]))
expect(obj.reload[:number_set]).to eq(Set.new([BigDecimal(1),BigDecimal(2)]))
end
end
it 'raises on an invalid boolean value' do
expect do
address.deliverable = true
data = address.send(:dump)
data[:deliverable] = 'foo'
Address.undump(data)
end.to raise_error(ArgumentError)
end
it 'loads a hash into a serialized field' do
hash = {foo: :bar}
expect(Address.new(options: hash).options).to eq hash
end
it 'loads attributes from a hash' do
@time = DateTime.now
@hash = {name: 'Josh', created_at: @time.to_f}
expect(User.undump(@hash)[:name]).to eq 'Josh'
User.undump(@hash)[:created_at].to_f == @time.to_f
end
it 'runs the before_create callback only once' do
expect_any_instance_of(CamelCase).to receive(:doing_before_create).once.and_return(true)
CamelCase.create
end
it 'runs after save callbacks when doing #create' do
expect_any_instance_of(CamelCase).to receive(:doing_after_create).once.and_return(true)
CamelCase.create
end
it 'runs after save callbacks when doing #save' do
expect_any_instance_of(CamelCase).to receive(:doing_after_create).once.and_return(true)
CamelCase.new.save
end
it 'works with a HashWithIndifferentAccess' do
hash = ActiveSupport::HashWithIndifferentAccess.new('city' => 'Atlanta')
expect{Address.create(hash)}.to_not raise_error
end
context 'create' do
{
Tweet => ['with range', { tweet_id: 1, group: 'abc' }],
Message => ['without range', { message_id: 1, text: 'foo', time: DateTime.now }]
}.each_pair do |clazz, fields|
it "checks for existence of an existing object #{fields[0]}" do
t1 = clazz.new(fields[1])
t2 = clazz.new(fields[1])
t1.save
expect do
t2.save!
end.to raise_exception Dynamoid::Errors::RecordNotUnique
end
end
end
context 'unknown fields' do
let(:clazz) do
Class.new do
include Dynamoid::Document
table name: :addresses
field :city
field :options, :serialized
field :deliverable, :bad_type_specifier
end
end
it 'raises when undumping a column with an unknown field type' do
expect do
clazz.new(deliverable: true) # undump is called here
end.to raise_error(ArgumentError)
end
it 'raises when dumping a column with an unknown field type' do
doc = clazz.new
doc.deliverable = true
expect do
doc.dump
end.to raise_error(ArgumentError)
end
end
describe 'save' do
it 'creates table if it does not exist' do
klass = Class.new do
include Dynamoid::Document
table name: :foo_bars
end
expect { klass.create }.not_to raise_error(Aws::DynamoDB::Errors::ResourceNotFoundException)
expect(klass.create.id).to be_present
end
end
context 'update' do
before :each do
@tweet = Tweet.create(tweet_id: 1, group: 'abc', count: 5, tags: Set.new(['db', 'sql']), user_name: 'john')
end
it 'runs before_update callbacks when doing #update' do
expect_any_instance_of(CamelCase).to receive(:doing_before_update).once.and_return(true)
CamelCase.create(color: 'blue').update do |t|
t.set(color: 'red')
end
end
it 'runs after_update callbacks when doing #update' do
expect_any_instance_of(CamelCase).to receive(:doing_after_update).once.and_return(true)
CamelCase.create(color: 'blue').update do |t|
t.set(color: 'red')
end
end
it 'support add/delete operation on a field' do
@tweet.update do |t|
t.add(count: 3)
t.delete(tags: Set.new(['db']))
end
expect(@tweet.count).to eq(8)
expect(@tweet.tags.to_a).to eq(['sql'])
end
it 'checks the conditions on update' do
result = @tweet.update(if: { count: 5 }) do |t|
t.add(count: 3)
end
expect(result).to be_truthy
expect(@tweet.count).to eq(8)
result = @tweet.update(if: { count: 5 }) do |t|
t.add(count: 3)
end
expect(result).to be_falsey
expect(@tweet.count).to eq(8)
expect do
@tweet.update!(if: { count: 5 }) do |t|
t.add(count: 3)
end
end.to raise_error(Dynamoid::Errors::StaleObjectError)
end
it 'prevents concurrent saves to tables with a lock_version' do
address.save!
a2 = Address.find(address.id)
a2.update! { |a| a.set(city: 'Chicago') }
expect do
address.city = 'Seattle'
address.save!
end.to raise_error(Dynamoid::Errors::StaleObjectError)
end
end
context 'delete' do
it 'deletes model with datetime range key' do
expect do
msg = Message.create!(message_id: 1, time: DateTime.now, text: 'Hell yeah')
msg.destroy
end.to_not raise_error
end
context 'with lock version' do
it 'deletes a record if lock version matches' do
address.save!
expect { address.destroy }.to_not raise_error
end
it 'does not delete a record if lock version does not match' do
address.save!
a1 = address
a2 = Address.find(address.id)
a1.city = 'Seattle'
a1.save!
expect { a2.destroy }.to raise_exception(Dynamoid::Errors::StaleObjectError)
end
it 'uses the correct lock_version even if it is modified' do
address.save!
a1 = address
a1.lock_version = 100
expect { a1.destroy }.to_not raise_error
end
end
end
context 'single table inheritance' do
let(:vehicle) { Vehicle.create }
let(:car) { Car.create(power_locks: false) }
let(:sub) { NuclearSubmarine.create(torpedoes: 5) }
it 'saves subclass objects in the parent table' do
c = car
expect(Vehicle.find(c.id)).to eq c
end
it 'loads subclass item when querying the parent table' do
c = car
s = sub
Vehicle.all.to_a.tap { |v|
expect(v).to include(c)
expect(v).to include(s)
}
end
it 'does not load parent item when quering the child table' do
vehicle && car
expect(Car.all).to contain_exactly(car)
expect(Car.all).not_to include(vehicle)
end
it 'does not load items of sibling class' do
car && sub
expect(Car.all).to contain_exactly(car)
expect(Car.all).not_to include(sub)
end
end
describe ':raw datatype persistence' do
subject { Address.new() }
it 'it persists raw Hash and reads the same back' do
config = {acres: 5, trees: {cyprus: 30, poplar: 10, joshua: 1}, horses: ['Lucky', 'Dummy'], lake: 1, tennis_court: 1}
subject.config = config
subject.save!
subject.reload
expect(subject.config).to eq config
end
it 'it persists raw Array and reads the same back' do
config = ['windows', 'doors', 'roof']
subject.config = config
subject.save!
subject.reload
expect(subject.config).to eq config
end
it 'it persists raw Number and reads the same back' do
config = 100
subject.config = config
subject.save!
subject.reload
expect(subject.config).to eq config
end
it 'it persists raw String and reads the same back' do
config = 'Configy'
subject.config = config
subject.save!
subject.reload
expect(subject.config).to eq config
end
it 'it persists raw value, then reads back, then deletes the value by setting to nil, persists and reads the nil back' do
config = 'To become nil'
subject.config = config
subject.save!
subject.reload
expect(subject.config).to eq config
subject.config = nil
subject.save!
subject.reload
expect(subject.config).to be_nil
end
end
describe 'class-type fields' do
subject { doc_class.new }
context 'when Money can load itself and Money instances can dump themselves with Dynamoid-specific methods' do
let(:doc_class) do
Class.new do
def self.name; 'Doc'; end
include Dynamoid::Document
field :price, MoneyInstanceDump
end
end
before(:each) do
subject.price = MoneyInstanceDump.new(BigDecimal.new('5'))
subject.save!
end
it 'round-trips using Dynamoid-specific methods' do
expect(doc_class.all.first).to eq subject
end
it 'is findable as a string' do
pending 'casting to declared type is not supported yet'
expect(doc_class.where(price: '5.0').first).to eq subject
end
end
context 'when MoneyAdapter dumps/loads a class that does not directly support Dynamoid\'s interface' do
let(:doc_class) do
Class.new do
def self.name; 'Doc'; end
include Dynamoid::Document
field :price, MoneyAdapter
end
end
before(:each) do
subject.price = Money.new(BigDecimal.new('5'))
subject.save!
subject.reload
end
it 'round-trips using Dynamoid-specific methods' do
expect(doc_class.all.first.price).to eq subject.price
end
it 'is findable as a string' do
pending 'casting to declared type is not supported yet'
expect(doc_class.where(price: '5.0').first).to eq subject
end
it 'is a Money object' do
expect(subject.price).to be_a Money
end
end
context 'when Money has Dynamoid-specific serialization methods and is a range' do
let(:doc_class) do
Class.new do
def self.name; 'Doc'; end
include Dynamoid::Document
range :price, MoneyAsNumber
end
end
before(:each) do
subject.price = MoneyAsNumber.new(BigDecimal.new('5'))
subject.save!
end
it 'round-trips using Dynamoid-specific methods' do
expect(doc_class.all.first.price).to eq subject.price
end
it 'is findable with number semantics' do
pending 'casting to declared type is not supported yet'
# With the primary key, we're forcing a Query rather than a Scan because of https://github.com/Dynamoid/Dynamoid/issues/6
primary_key = subject.id
expect(doc_class.where(id: primary_key).where('price.gt' => 4).first).to_not be_nil
end
end
end
describe '.import' do
before do
Address.create_table
User.create_table
Tweet.create_table
end
it 'creates multiple documents' do
expect {
Address.import([{city: 'Chicago'}, {city: 'New York'}])
}.to change { Address.count }.by(2)
end
it 'returns created documents' do
addresses = Address.import([{city: 'Chicago'}, {city: 'New York'}])
expect(addresses[0].city).to eq('Chicago')
expect(addresses[1].city).to eq('New York')
end
it 'does not validate documents' do
klass = Class.new do
include Dynamoid::Document
field :city
validates :city, presence: true
def self.name; 'Address'; end
end
addresses = klass.import([{city: nil}, {city: 'Chicago'}])
expect(addresses[0].persisted?).to be true
expect(addresses[1].persisted?).to be true
end
it 'does not run callbacks' do
klass = Class.new do
include Dynamoid::Document
field :city
validates :city, presence: true
def self.name; 'Address'; end
before_save { raise 'before save callback called' }
end
expect { klass.import([{city: 'Chicago'}]) }.not_to raise_error
end
it 'makes batch operation' do
expect(Dynamoid.adapter).to receive(:batch_write_item).and_call_original
Address.import([{city: 'Chicago'}, {city: 'New York'}])
end
it 'supports empty containers in `serialized` fields' do
users = User.import([name: 'Philip', favorite_colors: Set.new])
user = User.find(users[0].id)
expect(user.favorite_colors).to eq Set.new
end
it 'supports array being empty' do
users = User.import([{todo_list: []}])
user = User.find(users[0].id)