aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/cases/dirty_test.rb
blob: df4183c06540bdadb6a2b8554f463a6c04cb1af3 (plain) (blame)
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
require 'cases/helper'
require 'models/topic'    # For booleans
require 'models/pirate'   # For timestamps
require 'models/parrot'
require 'models/person'   # For optimistic locking
require 'models/aircraft'

class Pirate # Just reopening it, not defining it
  attr_accessor :detected_changes_in_after_update # Boolean for if changes are detected
  attr_accessor :changes_detected_in_after_update # Actual changes

  after_update :check_changes

private
  # after_save/update and the model itself
  # can end up checking dirty status and acting on the results
  def check_changes
    if self.changed?
      self.detected_changes_in_after_update = true
      self.changes_detected_in_after_update = self.changes
    end
  end
end

class NumericData < ActiveRecord::Base
  self.table_name = 'numeric_data'
end

class DirtyTest < ActiveRecord::TestCase
  include InTimeZone

  # Dummy to force column loads so query counts are clean.
  def setup
    Person.create :first_name => 'foo'
  end

  def test_attribute_changes
    # New record - no changes.
    pirate = Pirate.new
    assert !pirate.catchphrase_changed?
    assert_nil pirate.catchphrase_change

    # Change catchphrase.
    pirate.catchphrase = 'arrr'
    assert pirate.catchphrase_changed?
    assert_nil pirate.catchphrase_was
    assert_equal [nil, 'arrr'], pirate.catchphrase_change

    # Saved - no changes.
    pirate.save!
    assert !pirate.catchphrase_changed?
    assert_nil pirate.catchphrase_change

    # Same value - no changes.
    pirate.catchphrase = 'arrr'
    assert !pirate.catchphrase_changed?
    assert_nil pirate.catchphrase_change
  end

  def test_time_attributes_changes_with_time_zone
    in_time_zone 'Paris' do
      target = Class.new(ActiveRecord::Base)
      target.table_name = 'pirates'

      # New record - no changes.
      pirate = target.new
      assert !pirate.created_on_changed?
      assert_nil pirate.created_on_change

      # Saved - no changes.
      pirate.catchphrase = 'arrrr, time zone!!'
      pirate.save!
      assert !pirate.created_on_changed?
      assert_nil pirate.created_on_change

      # Change created_on.
      old_created_on = pirate.created_on
      pirate.created_on = Time.now - 1.day
      assert pirate.created_on_changed?
      assert_kind_of ActiveSupport::TimeWithZone, pirate.created_on_was
      assert_equal old_created_on, pirate.created_on_was
      pirate.created_on = old_created_on
      assert !pirate.created_on_changed?
    end
  end

  def test_setting_time_attributes_with_time_zone_field_to_itself_should_not_be_marked_as_a_change
    in_time_zone 'Paris' do
      target = Class.new(ActiveRecord::Base)
      target.table_name = 'pirates'

      pirate = target.create
      pirate.created_on = pirate.created_on
      assert !pirate.created_on_changed?
    end
  end

  def test_time_attributes_changes_without_time_zone_by_skip
    in_time_zone 'Paris' do
      target = Class.new(ActiveRecord::Base)
      target.table_name = 'pirates'

      target.skip_time_zone_conversion_for_attributes = [:created_on]

      # New record - no changes.
      pirate = target.new
      assert !pirate.created_on_changed?
      assert_nil pirate.created_on_change

      # Saved - no changes.
      pirate.catchphrase = 'arrrr, time zone!!'
      pirate.save!
      assert !pirate.created_on_changed?
      assert_nil pirate.created_on_change

      # Change created_on.
      old_created_on = pirate.created_on
      pirate.created_on = Time.now + 1.day
      assert pirate.created_on_changed?
      # kind_of does not work because
      # ActiveSupport::TimeWithZone.name == 'Time'
      assert_instance_of Time, pirate.created_on_was
      assert_equal old_created_on, pirate.created_on_was
    end
  end

  def test_time_attributes_changes_without_time_zone
    with_timezone_config aware_attributes: false do
      target = Class.new(ActiveRecord::Base)
      target.table_name = 'pirates'

      # New record - no changes.
      pirate = target.new
      assert !pirate.created_on_changed?
      assert_nil pirate.created_on_change

      # Saved - no changes.
      pirate.catchphrase = 'arrrr, time zone!!'
      pirate.save!
      assert !pirate.created_on_changed?
      assert_nil pirate.created_on_change

      # Change created_on.
      old_created_on = pirate.created_on
      pirate.created_on = Time.now + 1.day
      assert pirate.created_on_changed?
      # kind_of does not work because
      # ActiveSupport::TimeWithZone.name == 'Time'
      assert_instance_of Time, pirate.created_on_was
      assert_equal old_created_on, pirate.created_on_was
    end
  end


  def test_aliased_attribute_changes
    # the actual attribute here is name, title is an
    # alias setup via alias_attribute
    parrot = Parrot.new
    assert !parrot.title_changed?
    assert_nil parrot.title_change

    parrot.name = 'Sam'
    assert parrot.title_changed?
    assert_nil parrot.title_was
    assert_equal parrot.name_change, parrot.title_change
  end

  def test_reset_attribute!
    pirate = Pirate.create!(:catchphrase => 'Yar!')
    pirate.catchphrase = 'Ahoy!'

    pirate.reset_catchphrase!
    assert_equal "Yar!", pirate.catchphrase
    assert_equal Hash.new, pirate.changes
    assert !pirate.catchphrase_changed?
  end

  def test_nullable_number_not_marked_as_changed_if_new_value_is_blank
    pirate = Pirate.new

    ["", nil].each do |value|
      pirate.parrot_id = value
      assert !pirate.parrot_id_changed?
      assert_nil pirate.parrot_id_change
    end
  end

  def test_nullable_decimal_not_marked_as_changed_if_new_value_is_blank
    numeric_data = NumericData.new

    ["", nil].each do |value|
      numeric_data.bank_balance = value
      assert !numeric_data.bank_balance_changed?
      assert_nil numeric_data.bank_balance_change
    end
  end

  def test_nullable_float_not_marked_as_changed_if_new_value_is_blank
    numeric_data = NumericData.new

    ["", nil].each do |value|
      numeric_data.temperature = value
      assert !numeric_data.temperature_changed?
      assert_nil numeric_data.temperature_change
    end
  end

  def test_nullable_datetime_not_marked_as_changed_if_new_value_is_blank
    in_time_zone 'Edinburgh' do
      target = Class.new(ActiveRecord::Base)
      target.table_name = 'topics'

      topic = target.create
      assert_nil topic.written_on

      ["", nil].each do |value|
        topic.written_on = value
        assert_nil topic.written_on
        assert !topic.written_on_changed?
      end
    end
  end

  def test_integer_zero_to_string_zero_not_marked_as_changed
    pirate = Pirate.new
    pirate.parrot_id = 0
    pirate.catchphrase = 'arrr'
    assert pirate.save!

    assert !pirate.changed?

    pirate.parrot_id = '0'
    assert !pirate.changed?
  end

  def test_integer_zero_to_integer_zero_not_marked_as_changed
    pirate = Pirate.new
    pirate.parrot_id = 0
    pirate.catchphrase = 'arrr'
    assert pirate.save!

    assert !pirate.changed?

    pirate.parrot_id = 0
    assert !pirate.changed?
  end

  def test_float_zero_to_string_zero_not_marked_as_changed
    data = NumericData.new :temperature => 0.0
    data.save!

    assert_not data.changed?

    data.temperature = '0'
    assert_empty data.changes

    data.temperature = '0.0'
    assert_empty data.changes

    data.temperature = '0.00'
    assert_empty data.changes
  end

  def test_zero_to_blank_marked_as_changed
    pirate = Pirate.new
    pirate.catchphrase = "Yarrrr, me hearties"
    pirate.parrot_id = 1
    pirate.save

    # check the change from 1 to ''
    pirate = Pirate.find_by_catchphrase("Yarrrr, me hearties")
    pirate.parrot_id = ''
    assert pirate.parrot_id_changed?
    assert_equal([1, nil], pirate.parrot_id_change)
    pirate.save

    # check the change from nil to 0
    pirate = Pirate.find_by_catchphrase("Yarrrr, me hearties")
    pirate.parrot_id = 0
    assert pirate.parrot_id_changed?
    assert_equal([nil, 0], pirate.parrot_id_change)
    pirate.save

    # check the change from 0 to ''
    pirate = Pirate.find_by_catchphrase("Yarrrr, me hearties")
    pirate.parrot_id = ''
    assert pirate.parrot_id_changed?
    assert_equal([0, nil], pirate.parrot_id_change)
  end

  def test_object_should_be_changed_if_any_attribute_is_changed
    pirate = Pirate.new
    assert !pirate.changed?
    assert_equal [], pirate.changed
    assert_equal Hash.new, pirate.changes

    pirate.catchphrase = 'arrr'
    assert pirate.changed?
    assert_nil pirate.catchphrase_was
    assert_equal %w(catchphrase), pirate.changed
    assert_equal({'catchphrase' => [nil, 'arrr']}, pirate.changes)

    pirate.save
    assert !pirate.changed?
    assert_equal [], pirate.changed
    assert_equal Hash.new, pirate.changes
  end

  def test_attribute_will_change!
    pirate = Pirate.create!(:catchphrase => 'arr')

    pirate.catchphrase << ' matey'
    assert !pirate.catchphrase_changed?

    assert pirate.catchphrase_will_change!
    assert pirate.catchphrase_changed?
    assert_equal ['arr matey', 'arr matey'], pirate.catchphrase_change

    pirate.catchphrase << '!'
    assert pirate.catchphrase_changed?
    assert_equal ['arr matey', 'arr matey!'], pirate.catchphrase_change
  end

  def test_association_assignment_changes_foreign_key
    pirate = Pirate.create!(:catchphrase => 'jarl')
    pirate.parrot = Parrot.create!(:name => 'Lorre')
    assert pirate.changed?
    assert_equal %w(parrot_id), pirate.changed
  end

  def test_attribute_should_be_compared_with_type_cast
    topic = Topic.new
    assert topic.approved?
    assert !topic.approved_changed?

    # Coming from web form.
    params = {:topic => {:approved => 1}}
    # In the controller.
    topic.attributes = params[:topic]
    assert topic.approved?
    assert !topic.approved_changed?
  end

  def test_partial_update
    pirate = Pirate.new(:catchphrase => 'foo')
    old_updated_on = 1.hour.ago.beginning_of_day

    with_partial_writes Pirate, false do
      assert_queries(2) { 2.times { pirate.save! } }
      Pirate.where(id: pirate.id).update_all(:updated_on => old_updated_on)
    end

    with_partial_writes Pirate, true do
      assert_queries(0) { 2.times { pirate.save! } }
      assert_equal old_updated_on, pirate.reload.updated_on

      assert_queries(1) { pirate.catchphrase = 'bar'; pirate.save! }
      assert_not_equal old_updated_on, pirate.reload.updated_on
    end
  end

  def test_partial_update_with_optimistic_locking
    person = Person.new(:first_name => 'foo')
    old_lock_version = 1

    with_partial_writes Person, false do
      assert_queries(2) { 2.times { person.save! } }
      Person.where(id: person.id).update_all(:first_name => 'baz')
    end

    with_partial_writes Person, true do
      assert_queries(0) { 2.times { person.save! } }
      assert_equal old_lock_version, person.reload.lock_version

      assert_queries(1) { person.first_name = 'bar'; person.save! }
      assert_not_equal old_lock_version, person.reload.lock_version
    end
  end

  def test_changed_attributes_should_be_preserved_if_save_failure
    pirate = Pirate.new
    pirate.parrot_id = 1
    assert !pirate.save
    check_pirate_after_save_failure(pirate)

    pirate = Pirate.new
    pirate.parrot_id = 1
    assert_raise(ActiveRecord::RecordInvalid) { pirate.save! }
    check_pirate_after_save_failure(pirate)
  end

  def test_reload_should_clear_changed_attributes
    pirate = Pirate.create!(:catchphrase => "shiver me timbers")
    pirate.catchphrase = "*hic*"
    assert pirate.changed?
    pirate.reload
    assert !pirate.changed?
  end

  def test_dup_objects_should_not_copy_dirty_flag_from_creator
    pirate = Pirate.create!(:catchphrase => "shiver me timbers")
    pirate_dup = pirate.dup
    pirate_dup.reset_catchphrase!
    pirate.catchphrase = "I love Rum"
    assert pirate.catchphrase_changed?
    assert !pirate_dup.catchphrase_changed?
  end

  def test_reverted_changes_are_not_dirty
    phrase = "shiver me timbers"
    pirate = Pirate.create!(:catchphrase => phrase)
    pirate.catchphrase = "*hic*"
    assert pirate.changed?
    pirate.catchphrase = phrase
    assert !pirate.changed?
  end

  def test_reverted_changes_are_not_dirty_after_multiple_changes
    phrase = "shiver me timbers"
    pirate = Pirate.create!(:catchphrase => phrase)
    10.times do |i|
      pirate.catchphrase = "*hic*" * i
      assert pirate.changed?
    end
    assert pirate.changed?
    pirate.catchphrase = phrase
    assert !pirate.changed?
  end


  def test_reverted_changes_are_not_dirty_going_from_nil_to_value_and_back
    pirate = Pirate.create!(:catchphrase => "Yar!")

    pirate.parrot_id = 1
    assert pirate.changed?
    assert pirate.parrot_id_changed?
    assert !pirate.catchphrase_changed?

    pirate.parrot_id = nil
    assert !pirate.changed?
    assert !pirate.parrot_id_changed?
    assert !pirate.catchphrase_changed?
  end

  def test_save_should_store_serialized_attributes_even_with_partial_writes
    with_partial_writes(Topic) do
      topic = Topic.create!(:content => {:a => "a"})
      topic.content[:b] = "b"
      #assert topic.changed? # Known bug, will fail
      topic.save!
      assert_equal "b", topic.content[:b]
      topic.reload
      assert_equal "b", topic.content[:b]
    end
  end

  def test_save_always_should_update_timestamps_when_serialized_attributes_are_present
    with_partial_writes(Topic) do
      topic = Topic.create!(:content => {:a => "a"})
      topic.save!

      updated_at = topic.updated_at
      topic.content[:hello] = 'world'
      topic.save!

      assert_not_equal updated_at, topic.updated_at
      assert_equal 'world', topic.content[:hello]
    end
  end

  def test_save_should_not_save_serialized_attribute_with_partial_writes_if_not_present
    with_partial_writes(Topic) do
      Topic.create!(:author_name => 'Bill', :content => {:a => "a"})
      topic = Topic.select('id, author_name').first
      topic.update_columns author_name: 'John'
      topic = Topic.first
      assert_not_nil topic.content
    end
  end

  def test_previous_changes
    # original values should be in previous_changes
    pirate = Pirate.new

    assert_equal Hash.new, pirate.previous_changes
    pirate.catchphrase = "arrr"
    pirate.save!

    assert_equal 4, pirate.previous_changes.size
    assert_equal [nil, "arrr"], pirate.previous_changes['catchphrase']
    assert_equal [nil, pirate.id], pirate.previous_changes['id']
    assert_nil pirate.previous_changes['updated_on'][0]
    assert_not_nil pirate.previous_changes['updated_on'][1]
    assert_nil pirate.previous_changes['created_on'][0]
    assert_not_nil pirate.previous_changes['created_on'][1]
    assert !pirate.previous_changes.key?('parrot_id')

    # original values should be in previous_changes
    pirate = Pirate.new

    assert_equal Hash.new, pirate.previous_changes
    pirate.catchphrase = "arrr"
    pirate.save

    assert_equal 4, pirate.previous_changes.size
    assert_equal [nil, "arrr"], pirate.previous_changes['catchphrase']
    assert_equal [nil, pirate.id], pirate.previous_changes['id']
    assert pirate.previous_changes.include?('updated_on')
    assert pirate.previous_changes.include?('created_on')
    assert !pirate.previous_changes.key?('parrot_id')

    pirate.catchphrase = "Yar!!"
    pirate.reload
    assert_equal Hash.new, pirate.previous_changes

    pirate = Pirate.find_by_catchphrase("arrr")
    pirate.catchphrase = "Me Maties!"
    pirate.save!

    assert_equal 2, pirate.previous_changes.size
    assert_equal ["arrr", "Me Maties!"], pirate.previous_changes['catchphrase']
    assert_not_nil pirate.previous_changes['updated_on'][0]
    assert_not_nil pirate.previous_changes['updated_on'][1]
    assert !pirate.previous_changes.key?('parrot_id')
    assert !pirate.previous_changes.key?('created_on')

    pirate = Pirate.find_by_catchphrase("Me Maties!")
    pirate.catchphrase = "Thar She Blows!"
    pirate.save

    assert_equal 2, pirate.previous_changes.size
    assert_equal ["Me Maties!", "Thar She Blows!"], pirate.previous_changes['catchphrase']
    assert_not_nil pirate.previous_changes['updated_on'][0]
    assert_not_nil pirate.previous_changes['updated_on'][1]
    assert !pirate.previous_changes.key?('parrot_id')
    assert !pirate.previous_changes.key?('created_on')

    pirate = Pirate.find_by_catchphrase("Thar She Blows!")
    pirate.update(catchphrase: "Ahoy!")

    assert_equal 2, pirate.previous_changes.size
    assert_equal ["Thar She Blows!", "Ahoy!"], pirate.previous_changes['catchphrase']
    assert_not_nil pirate.previous_changes['updated_on'][0]
    assert_not_nil pirate.previous_changes['updated_on'][1]
    assert !pirate.previous_changes.key?('parrot_id')
    assert !pirate.previous_changes.key?('created_on')

    pirate = Pirate.find_by_catchphrase("Ahoy!")
    pirate.update_attribute(:catchphrase, "Ninjas suck!")

    assert_equal 2, pirate.previous_changes.size
    assert_equal ["Ahoy!", "Ninjas suck!"], pirate.previous_changes['catchphrase']
    assert_not_nil pirate.previous_changes['updated_on'][0]
    assert_not_nil pirate.previous_changes['updated_on'][1]
    assert !pirate.previous_changes.key?('parrot_id')
    assert !pirate.previous_changes.key?('created_on')
  end

  if ActiveRecord::Base.connection.supports_migrations?
    class Testings < ActiveRecord::Base; end
    def test_field_named_field
      ActiveRecord::Base.connection.create_table :testings do |t|
        t.string :field
      end
      assert_nothing_raised do
        Testings.new.attributes
      end
    ensure
      ActiveRecord::Base.connection.drop_table :testings rescue nil
    end
  end

  def test_datetime_attribute_can_be_updated_with_fractional_seconds
    in_time_zone 'Paris' do
      target = Class.new(ActiveRecord::Base)
      target.table_name = 'topics'

      written_on = Time.utc(2012, 12, 1, 12, 0, 0).in_time_zone('Paris')

      topic = target.create(:written_on => written_on)
      topic.written_on += 0.3

      assert topic.written_on_changed?, 'Fractional second update not detected'
    end
  end

  def test_datetime_attribute_doesnt_change_if_zone_is_modified_in_string
    time_in_paris = Time.utc(2014, 1, 1, 12, 0, 0).in_time_zone('Paris')
    pirate = Pirate.create!(:catchphrase => 'rrrr', :created_on => time_in_paris)

    pirate.created_on = pirate.created_on.in_time_zone('Tokyo').to_s
    assert !pirate.created_on_changed?
  end

  test "partial insert" do
    with_partial_writes Person do
      jon = nil
      assert_sql(/first_name/i) do
        jon = Person.create! first_name: 'Jon'
      end

      assert ActiveRecord::SQLCounter.log_all.none? { |sql| sql =~ /followers_count/ }

      jon.reload
      assert_equal 'Jon', jon.first_name
      assert_equal 0, jon.followers_count
      assert_not_nil jon.id
    end
  end

  test "partial insert with empty values" do
    with_partial_writes Aircraft do
      a = Aircraft.create!
      a.reload
      assert_not_nil a.id
    end
  end

  private
    def with_partial_writes(klass, on = true)
      old = klass.partial_writes?
      klass.partial_writes = on
      yield
    ensure
      klass.partial_writes = old
    end

    def check_pirate_after_save_failure(pirate)
      assert pirate.changed?
      assert pirate.parrot_id_changed?
      assert_equal %w(parrot_id), pirate.changed
      assert_nil pirate.parrot_id_was
    end
end