base_test.rb 77.0 KB
Newer Older
1
require "cases/helper"
2
require 'models/post'
3
require 'models/author'
J
Jeremy Kemper 已提交
4 5
require 'models/topic'
require 'models/reply'
6
require 'models/category'
J
Jeremy Kemper 已提交
7 8 9 10 11 12 13 14 15
require 'models/company'
require 'models/customer'
require 'models/developer'
require 'models/project'
require 'models/default'
require 'models/auto_id'
require 'models/column_name'
require 'models/subscriber'
require 'models/keyboard'
16
require 'models/comment'
J
Jeremy Kemper 已提交
17 18
require 'models/minimalistic'
require 'models/warehouse_thing'
19
require 'models/parrot'
20
require 'rexml/document'
J
Jeremy Kemper 已提交
21
require 'active_support/core_ext/exception'
D
Initial  
David Heinemeier Hansson 已提交
22 23

class Category < ActiveRecord::Base; end
24
class Categorization < ActiveRecord::Base; end
D
Initial  
David Heinemeier Hansson 已提交
25
class Smarts < ActiveRecord::Base; end
26
class CreditCard < ActiveRecord::Base
27 28 29 30 31 32
  class PinNumber < ActiveRecord::Base
    class CvvCode < ActiveRecord::Base; end
    class SubCvvCode < CvvCode; end
  end
  class SubPinNumber < PinNumber; end
  class Brand < Category; end
33
end
D
Initial  
David Heinemeier Hansson 已提交
34
class MasterCreditCard < ActiveRecord::Base; end
35
class Post < ActiveRecord::Base; end
36
class Computer < ActiveRecord::Base; end
37
class NonExistentTable < ActiveRecord::Base; end
38
class TestOracleDefault < ActiveRecord::Base; end
D
Initial  
David Heinemeier Hansson 已提交
39 40

class LoosePerson < ActiveRecord::Base
41
  self.table_name = 'people'
42
  self.abstract_class = true
43
  attr_protected :credit_rating, :administrator
D
Initial  
David Heinemeier Hansson 已提交
44 45
end

46 47 48 49
class LooseDescendant < LoosePerson
  attr_protected :phone_number
end

50 51 52 53 54
class LooseDescendantSecond< LoosePerson
  attr_protected :phone_number
  attr_protected :name
end

D
Initial  
David Heinemeier Hansson 已提交
55
class TightPerson < ActiveRecord::Base
56
  self.table_name = 'people'
D
Initial  
David Heinemeier Hansson 已提交
57 58 59
  attr_accessible :name, :address
end

60
class TightDescendant < TightPerson
D
Initial  
David Heinemeier Hansson 已提交
61 62 63
  attr_accessible :phone_number
end

64 65 66 67
class ReadonlyTitlePost < Post
  attr_readonly :title
end

D
Initial  
David Heinemeier Hansson 已提交
68 69
class Booleantest < ActiveRecord::Base; end

70 71 72 73
class Task < ActiveRecord::Base
  attr_protected :starting
end

J
Jeremy Kemper 已提交
74 75
class TopicWithProtectedContentAndAccessibleAuthorName < ActiveRecord::Base
  self.table_name = 'topics'
76 77 78 79
  attr_accessible :author_name
  attr_protected  :content
end

80
class BasicsTest < ActiveRecord::TestCase
81
  fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts
D
Initial  
David Heinemeier Hansson 已提交
82

83 84 85 86
  def test_table_exists
    assert !NonExistentTable.table_exists?
    assert Topic.table_exists?
  end
J
Jeremy Kemper 已提交
87

D
Initial  
David Heinemeier Hansson 已提交
88 89 90 91 92 93
  def test_set_attributes
    topic = Topic.find(1)
    topic.attributes = { "title" => "Budget", "author_name" => "Jason" }
    topic.save
    assert_equal("Budget", topic.title)
    assert_equal("Jason", topic.author_name)
94
    assert_equal(topics(:first).author_email_address, Topic.find(1).author_email_address)
D
Initial  
David Heinemeier Hansson 已提交
95
  end
96

D
Initial  
David Heinemeier Hansson 已提交
97
  def test_integers_as_nil
J
Jeremy Kemper 已提交
98 99
    test = AutoId.create('value' => '')
    assert_nil AutoId.find(test.id).value
D
Initial  
David Heinemeier Hansson 已提交
100
  end
J
Jeremy Kemper 已提交
101

D
Initial  
David Heinemeier Hansson 已提交
102 103 104 105 106 107 108 109 110
  def test_set_attributes_with_block
    topic = Topic.new do |t|
      t.title       = "Budget"
      t.author_name = "Jason"
    end

    assert_equal("Budget", topic.title)
    assert_equal("Jason", topic.author_name)
  end
J
Jeremy Kemper 已提交
111

D
Initial  
David Heinemeier Hansson 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124
  def test_respond_to?
    topic = Topic.find(1)
    assert topic.respond_to?("title")
    assert topic.respond_to?("title?")
    assert topic.respond_to?("title=")
    assert topic.respond_to?(:title)
    assert topic.respond_to?(:title?)
    assert topic.respond_to?(:title=)
    assert topic.respond_to?("author_name")
    assert topic.respond_to?("attribute_names")
    assert !topic.respond_to?("nothingness")
    assert !topic.respond_to?(:nothingness)
  end
J
Jeremy Kemper 已提交
125

D
Initial  
David Heinemeier Hansson 已提交
126 127 128 129 130 131 132 133
  def test_array_content
    topic = Topic.new
    topic.content = %w( one two three )
    topic.save

    assert_equal(%w( one two three ), Topic.find(topic.id).content)
  end

134 135
  def test_read_attributes_before_type_cast
    category = Category.new({:name=>"Test categoty", :type => nil})
136
    category_attrs = {"name"=>"Test categoty", "type" => nil, "categorizations_count" => nil}
137 138
    assert_equal category_attrs , category.attributes_before_type_cast
  end
139

140 141 142
  if current_adapter?(:MysqlAdapter)
    def test_read_attributes_before_type_cast_on_boolean
      bool = Booleantest.create({ "value" => false })
143
      assert_equal "0", bool.reload.attributes_before_type_cast["value"]
144
    end
145
  end
146

147 148
  def test_read_attributes_before_type_cast_on_datetime
    developer = Developer.find(:first)
149 150 151 152 153 154
    # Oracle adapter returns Time before type cast
    unless current_adapter?(:OracleAdapter)
      assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"]
    else
      assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"].to_s(:db)
    end
155
  end
156

D
Initial  
David Heinemeier Hansson 已提交
157 158 159 160 161 162
  def test_hash_content
    topic = Topic.new
    topic.content = { "one" => 1, "two" => 2 }
    topic.save

    assert_equal 2, Topic.find(topic.id).content["two"]
J
Jeremy Kemper 已提交
163

164
    topic.content_will_change!
D
Initial  
David Heinemeier Hansson 已提交
165 166 167 168 169
    topic.content["three"] = 3
    topic.save

    assert_equal 3, Topic.find(topic.id).content["three"]
  end
J
Jeremy Kemper 已提交
170

D
Initial  
David Heinemeier Hansson 已提交
171 172 173 174 175 176 177 178
  def test_update_array_content
    topic = Topic.new
    topic.content = %w( one two three )

    topic.content.push "four"
    assert_equal(%w( one two three four ), topic.content)

    topic.save
J
Jeremy Kemper 已提交
179

D
Initial  
David Heinemeier Hansson 已提交
180 181 182 183
    topic = Topic.find(topic.id)
    topic.content << "five"
    assert_equal(%w( one two three four five ), topic.content)
  end
J
Jeremy Kemper 已提交
184

185 186 187 188
  def test_case_sensitive_attributes_hash
    # DB2 is not case-sensitive
    return true if current_adapter?(:DB2Adapter)

189
    assert_equal @loaded_fixtures['computers']['workstation'].to_hash, Computer.find(:first).attributes
190
  end
191

D
Initial  
David Heinemeier Hansson 已提交
192 193 194 195
  def test_create
    topic = Topic.new
    topic.title = "New Topic"
    topic.save
196 197 198
    topic_reloaded = Topic.find(topic.id)
    assert_equal("New Topic", topic_reloaded.title)
  end
J
Jeremy Kemper 已提交
199

200 201 202
  def test_save!
    topic = Topic.new(:title => "New Topic")
    assert topic.save!
J
Jeremy Kemper 已提交
203

204 205 206
    reply = Reply.new
    assert_raise(ActiveRecord::RecordInvalid) { reply.save! }
  end
207 208 209 210 211 212 213 214

  def test_save_null_string_attributes
    topic = Topic.find(1)
    topic.attributes = { "title" => "null", "author_name" => "null" }
    topic.save!
    topic.reload
    assert_equal("null", topic.title)
    assert_equal("null", topic.author_name)
215 216 217 218 219 220 221 222 223 224
  end

  def test_save_nil_string_attributes
    topic = Topic.find(1)
    topic.title = nil
    topic.save!
    topic.reload
    assert_nil topic.title
  end

225 226 227 228 229 230 231 232 233
  def test_save_for_record_with_only_primary_key
    minimalistic = Minimalistic.new
    assert_nothing_raised { minimalistic.save }
  end

  def test_save_for_record_with_only_primary_key_that_is_provided
    assert_nothing_raised { Minimalistic.create!(:id => 2) }
  end

234 235 236 237 238 239 240 241
  def test_hashes_not_mangled
    new_topic = { :title => "New Topic" }
    new_topic_values = { :title => "AnotherTopic" }

    topic = Topic.new(new_topic)
    assert_equal new_topic[:title], topic.title

    topic.attributes= new_topic_values
242
    assert_equal new_topic_values[:title], topic.title
D
Initial  
David Heinemeier Hansson 已提交
243
  end
J
Jeremy Kemper 已提交
244

245 246 247 248 249
  def test_create_many
    topics = Topic.create([ { "title" => "first" }, { "title" => "second" }])
    assert_equal 2, topics.size
    assert_equal "first", topics.first.title
  end
250 251 252 253 254 255 256 257

  def test_create_columns_not_equal_attributes
    topic = Topic.new
    topic.title = 'Another New Topic'
    topic.send :write_attribute, 'does_not_exist', 'test'
    assert_nothing_raised { topic.save }
  end

D
Initial  
David Heinemeier Hansson 已提交
258 259 260 261
  def test_create_through_factory
    topic = Topic.create("title" => "New Topic")
    topicReloaded = Topic.find(topic.id)
    assert_equal(topic, topicReloaded)
262
  end
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282

  def test_create_through_factory_with_block
    topic = Topic.create("title" => "New Topic") do |t|
      t.author_name = "David"
    end
    topicReloaded = Topic.find(topic.id)
    assert_equal("New Topic", topic.title)
    assert_equal("David", topic.author_name)
  end

  def test_create_many_through_factory_with_block
    topics = Topic.create([ { "title" => "first" }, { "title" => "second" }]) do |t|
      t.author_name = "David"
    end
    assert_equal 2, topics.size
    topic1, topic2 = Topic.find(topics[0].id), Topic.find(topics[1].id)
    assert_equal "first", topic1.title
    assert_equal "David", topic1.author_name
    assert_equal "second", topic2.title
    assert_equal "David", topic2.author_name
D
Initial  
David Heinemeier Hansson 已提交
283 284 285 286 287
  end

  def test_update
    topic = Topic.new
    topic.title = "Another New Topic"
288
    topic.written_on = "2003-12-12 23:23:00"
D
Initial  
David Heinemeier Hansson 已提交
289
    topic.save
290
    topicReloaded = Topic.find(topic.id)
D
Initial  
David Heinemeier Hansson 已提交
291 292 293 294
    assert_equal("Another New Topic", topicReloaded.title)

    topicReloaded.title = "Updated topic"
    topicReloaded.save
J
Jeremy Kemper 已提交
295

296
    topicReloadedAgain = Topic.find(topic.id)
J
Jeremy Kemper 已提交
297

D
Initial  
David Heinemeier Hansson 已提交
298 299 300
    assert_equal("Updated topic", topicReloadedAgain.title)
  end

301 302 303 304
  def test_update_columns_not_equal_attributes
    topic = Topic.new
    topic.title = "Still another topic"
    topic.save
J
Jeremy Kemper 已提交
305

306
    topicReloaded = Topic.find(topic.id)
307 308 309 310
    topicReloaded.title = "A New Topic"
    topicReloaded.send :write_attribute, 'does_not_exist', 'test'
    assert_nothing_raised { topicReloaded.save }
  end
311 312 313 314 315

  def test_update_for_record_with_only_primary_key
    minimalistic = minimalistics(:first)
    assert_nothing_raised { minimalistic.save }
  end
J
Jeremy Kemper 已提交
316

317 318 319 320 321 322 323 324
  def test_write_attribute
    topic = Topic.new
    topic.send(:write_attribute, :title, "Still another topic")
    assert_equal "Still another topic", topic.title

    topic.send(:write_attribute, "title", "Still another topic: part 2")
    assert_equal "Still another topic: part 2", topic.title
  end
325

326 327 328 329 330 331 332 333 334 335
  def test_read_attribute
    topic = Topic.new
    topic.title = "Don't change the topic"
    assert_equal "Don't change the topic", topic.send(:read_attribute, "title")
    assert_equal "Don't change the topic", topic["title"]

    assert_equal "Don't change the topic", topic.send(:read_attribute, :title)
    assert_equal "Don't change the topic", topic[:title]
  end

336 337 338
  def test_read_attribute_when_false
    topic = topics(:first)
    topic.approved = false
J
Jeremy Kemper 已提交
339
    assert !topic.approved?, "approved should be false"
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
    topic.approved = "false"
    assert !topic.approved?, "approved should be false"
  end

  def test_read_attribute_when_true
    topic = topics(:first)
    topic.approved = true
    assert topic.approved?, "approved should be true"
    topic.approved = "true"
    assert topic.approved?, "approved should be true"
  end

  def test_read_write_boolean_attribute
    topic = Topic.new
    # puts ""
    # puts "New Topic"
    # puts topic.inspect
    topic.approved = "false"
    # puts "Expecting false"
    # puts topic.inspect
360
    assert !topic.approved?, "approved should be false"
361 362 363
    topic.approved = "false"
    # puts "Expecting false"
    # puts topic.inspect
364
    assert !topic.approved?, "approved should be false"
365 366 367
    topic.approved = "true"
    # puts "Expecting true"
    # puts topic.inspect
368
    assert topic.approved?, "approved should be true"
369 370 371
    topic.approved = "true"
    # puts "Expecting true"
    # puts topic.inspect
372
    assert topic.approved?, "approved should be true"
373
    # puts ""
374
  end
J
Jeremy Kemper 已提交
375

376 377 378 379
  def test_query_attribute_string
    [nil, "", " "].each do |value|
      assert_equal false, Topic.new(:author_name => value).author_name?
    end
J
Jeremy Kemper 已提交
380

381 382
    assert_equal true, Topic.new(:author_name => "Name").author_name?
  end
J
Jeremy Kemper 已提交
383

384 385 386 387
  def test_query_attribute_number
    [nil, 0, "0"].each do |value|
      assert_equal false, Developer.new(:salary => value).salary?
    end
J
Jeremy Kemper 已提交
388

389 390 391
    assert_equal true, Developer.new(:salary => 1).salary?
    assert_equal true, Developer.new(:salary => "1").salary?
  end
J
Jeremy Kemper 已提交
392

393 394 395 396
  def test_query_attribute_boolean
    [nil, "", false, "false", "f", 0].each do |value|
      assert_equal false, Topic.new(:approved => value).approved?
    end
J
Jeremy Kemper 已提交
397

398 399 400 401
    [true, "true", "1", 1].each do |value|
      assert_equal true, Topic.new(:approved => value).approved?
    end
  end
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416

  def test_query_attribute_with_custom_fields
    object = Company.find_by_sql(<<-SQL).first
      SELECT c1.*, c2.ruby_type as string_value, c2.rating as int_value
        FROM companies c1, companies c2
       WHERE c1.firm_id = c2.id
         AND c1.id = 2
    SQL

    assert_equal "Firm", object.string_value
    assert object.string_value?

    object.string_value = "  "
    assert !object.string_value?

J
Jamis Buck 已提交
417
    assert_equal 1, object.int_value.to_i
418 419 420 421 422 423
    assert object.int_value?

    object.int_value = "0"
    assert !object.int_value?
  end

424

425 426 427
  def test_non_attribute_access_and_assignment
    topic = Topic.new
    assert !topic.respond_to?("mumbo")
428 429
    assert_raise(NoMethodError) { topic.mumbo }
    assert_raise(NoMethodError) { topic.mumbo = 5 }
430 431
  end

D
Initial  
David Heinemeier Hansson 已提交
432
  def test_preserving_date_objects
433
    if current_adapter?(:SybaseAdapter, :OracleAdapter)
434
      # Sybase ctlib does not (yet?) support the date type; use datetime instead.
435
      # Oracle treats all dates/times as Time.
436
      assert_kind_of(
J
Jeremy Kemper 已提交
437
        Time, Topic.find(1).last_read,
438 439 440 441
        "The last_read attribute should be of the Time class"
      )
    else
      assert_kind_of(
J
Jeremy Kemper 已提交
442
        Date, Topic.find(1).last_read,
443 444 445
        "The last_read attribute should be of the Date class"
      )
    end
446
  end
447

448
  def test_preserving_time_objects
449 450 451 452
    assert_kind_of(
      Time, Topic.find(1).bonus_time,
      "The bonus_time attribute should be of the Time class"
    )
D
Initial  
David Heinemeier Hansson 已提交
453 454 455 456 457

    assert_kind_of(
      Time, Topic.find(1).written_on,
      "The written_on attribute should be of the Time class"
    )
458 459

    # For adapters which support microsecond resolution.
460
    if current_adapter?(:PostgreSQLAdapter) || current_adapter?(:SQLiteAdapter)
461 462
      assert_equal 11, Topic.find(1).written_on.sec
      assert_equal 223300, Topic.find(1).written_on.usec
463
      assert_equal 9900, Topic.find(2).written_on.usec
464
    end
D
Initial  
David Heinemeier Hansson 已提交
465
  end
J
Jeremy Kemper 已提交
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
  def test_preserving_time_objects_with_local_time_conversion_to_default_timezone_utc
    with_env_tz 'America/New_York' do
      with_active_record_default_timezone :utc do
        time = Time.local(2000)
        topic = Topic.create('written_on' => time)
        saved_time = Topic.find(topic.id).written_on
        assert_equal time, saved_time
        assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "EST"], time.to_a
        assert_equal [0, 0, 5, 1, 1, 2000, 6, 1, false, "UTC"], saved_time.to_a
      end
    end
  end

  def test_preserving_time_objects_with_time_with_zone_conversion_to_default_timezone_utc
    with_env_tz 'America/New_York' do
      with_active_record_default_timezone :utc do
        Time.use_zone 'Central Time (US & Canada)' do
          time = Time.zone.local(2000)
          topic = Topic.create('written_on' => time)
          saved_time = Topic.find(topic.id).written_on
          assert_equal time, saved_time
          assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "CST"], time.to_a
          assert_equal [0, 0, 6, 1, 1, 2000, 6, 1, false, "UTC"], saved_time.to_a
        end
      end
    end
  end

  def test_preserving_time_objects_with_utc_time_conversion_to_default_timezone_local
    with_env_tz 'America/New_York' do
      time = Time.utc(2000)
      topic = Topic.create('written_on' => time)
      saved_time = Topic.find(topic.id).written_on
      assert_equal time, saved_time
      assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "UTC"], time.to_a
      assert_equal [0, 0, 19, 31, 12, 1999, 5, 365, false, "EST"], saved_time.to_a
    end
  end

  def test_preserving_time_objects_with_time_with_zone_conversion_to_default_timezone_local
    with_env_tz 'America/New_York' do
      with_active_record_default_timezone :local do
        Time.use_zone 'Central Time (US & Canada)' do
          time = Time.zone.local(2000)
          topic = Topic.create('written_on' => time)
          saved_time = Topic.find(topic.id).written_on
          assert_equal time, saved_time
          assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "CST"], time.to_a
          assert_equal [0, 0, 1, 1, 1, 2000, 6, 1, false, "EST"], saved_time.to_a
        end
      end
    end
  end

521 522 523 524 525 526
  def test_custom_mutator
    topic = Topic.find(1)
    # This mutator is protected in the class definition
    topic.send(:approved=, true)
    assert topic.instance_variable_get("@custom_approved")
  end
J
Jeremy Kemper 已提交
527

528 529 530 531 532 533 534 535 536 537 538 539
  def test_delete
    topic = Topic.find(1)
    assert_equal topic, topic.delete, 'topic.delete did not return self'
    assert topic.frozen?, 'topic not frozen after delete'
    assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) }
  end

  def test_delete_doesnt_run_callbacks
    Topic.find(1).delete
    assert_not_nil Topic.find(2)
  end

D
Initial  
David Heinemeier Hansson 已提交
540
  def test_destroy
J
Jeremy Kemper 已提交
541 542 543
    topic = Topic.find(1)
    assert_equal topic, topic.destroy, 'topic.destroy did not return self'
    assert topic.frozen?, 'topic not frozen after destroy'
544
    assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) }
D
Initial  
David Heinemeier Hansson 已提交
545
  end
J
Jeremy Kemper 已提交
546

D
Initial  
David Heinemeier Hansson 已提交
547
  def test_record_not_found_exception
548
    assert_raise(ActiveRecord::RecordNotFound) { topicReloaded = Topic.find(99999) }
D
Initial  
David Heinemeier Hansson 已提交
549
  end
J
Jeremy Kemper 已提交
550

D
Initial  
David Heinemeier Hansson 已提交
551
  def test_initialize_with_attributes
J
Jeremy Kemper 已提交
552
    topic = Topic.new({
D
Initial  
David Heinemeier Hansson 已提交
553 554
      "title" => "initialized from attributes", "written_on" => "2003-12-12 23:23"
    })
J
Jeremy Kemper 已提交
555

D
Initial  
David Heinemeier Hansson 已提交
556 557
    assert_equal("initialized from attributes", topic.title)
  end
J
Jeremy Kemper 已提交
558

559 560
  def test_initialize_with_invalid_attribute
    begin
J
Jeremy Kemper 已提交
561
      topic = Topic.new({ "title" => "test",
562 563 564 565 566 567
        "last_read(1i)" => "2005", "last_read(2i)" => "2", "last_read(3i)" => "31"})
    rescue ActiveRecord::MultiparameterAssignmentErrors => ex
      assert_equal(1, ex.errors.size)
      assert_equal("last_read", ex.errors[0].attribute)
    end
  end
J
Jeremy Kemper 已提交
568

D
Initial  
David Heinemeier Hansson 已提交
569
  def test_load
J
Jeremy Kemper 已提交
570
    topics = Topic.find(:all, :order => 'id')
571
    assert_equal(4, topics.size)
572
    assert_equal(topics(:first).title, topics.first.title)
D
Initial  
David Heinemeier Hansson 已提交
573
  end
J
Jeremy Kemper 已提交
574

D
Initial  
David Heinemeier Hansson 已提交
575
  def test_load_with_condition
576
    topics = Topic.find(:all, :conditions => "author_name = 'Mary'")
J
Jeremy Kemper 已提交
577

D
Initial  
David Heinemeier Hansson 已提交
578
    assert_equal(1, topics.size)
579
    assert_equal(topics(:second).title, topics.first.title)
D
Initial  
David Heinemeier Hansson 已提交
580 581 582
  end

  def test_table_name_guesses
583 584
    classes = [Category, Smarts, CreditCard, CreditCard::PinNumber, CreditCard::PinNumber::CvvCode, CreditCard::SubPinNumber, CreditCard::Brand, MasterCreditCard]

D
Initial  
David Heinemeier Hansson 已提交
585
    assert_equal "topics", Topic.table_name
586

D
Initial  
David Heinemeier Hansson 已提交
587 588 589
    assert_equal "categories", Category.table_name
    assert_equal "smarts", Smarts.table_name
    assert_equal "credit_cards", CreditCard.table_name
590
    assert_equal "credit_card_pin_numbers", CreditCard::PinNumber.table_name
591 592 593
    assert_equal "credit_card_pin_number_cvv_codes", CreditCard::PinNumber::CvvCode.table_name
    assert_equal "credit_card_pin_numbers", CreditCard::SubPinNumber.table_name
    assert_equal "categories", CreditCard::Brand.table_name
D
Initial  
David Heinemeier Hansson 已提交
594 595 596
    assert_equal "master_credit_cards", MasterCreditCard.table_name

    ActiveRecord::Base.pluralize_table_names = false
597 598
    classes.each(&:reset_table_name)

D
Initial  
David Heinemeier Hansson 已提交
599 600 601
    assert_equal "category", Category.table_name
    assert_equal "smarts", Smarts.table_name
    assert_equal "credit_card", CreditCard.table_name
602
    assert_equal "credit_card_pin_number", CreditCard::PinNumber.table_name
603 604 605
    assert_equal "credit_card_pin_number_cvv_code", CreditCard::PinNumber::CvvCode.table_name
    assert_equal "credit_card_pin_number", CreditCard::SubPinNumber.table_name
    assert_equal "category", CreditCard::Brand.table_name
D
Initial  
David Heinemeier Hansson 已提交
606
    assert_equal "master_credit_card", MasterCreditCard.table_name
607

D
Initial  
David Heinemeier Hansson 已提交
608
    ActiveRecord::Base.pluralize_table_names = true
609
    classes.each(&:reset_table_name)
D
Initial  
David Heinemeier Hansson 已提交
610 611

    ActiveRecord::Base.table_name_prefix = "test_"
612
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
613 614
    assert_equal "test_categories", Category.table_name
    ActiveRecord::Base.table_name_suffix = "_test"
615
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
616 617
    assert_equal "test_categories_test", Category.table_name
    ActiveRecord::Base.table_name_prefix = ""
618
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
619 620
    assert_equal "categories_test", Category.table_name
    ActiveRecord::Base.table_name_suffix = ""
621
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
622 623 624 625
    assert_equal "categories", Category.table_name

    ActiveRecord::Base.pluralize_table_names = false
    ActiveRecord::Base.table_name_prefix = "test_"
626
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
627 628
    assert_equal "test_category", Category.table_name
    ActiveRecord::Base.table_name_suffix = "_test"
629
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
630 631
    assert_equal "test_category_test", Category.table_name
    ActiveRecord::Base.table_name_prefix = ""
632
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
633 634
    assert_equal "category_test", Category.table_name
    ActiveRecord::Base.table_name_suffix = ""
635
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
636
    assert_equal "category", Category.table_name
637

D
Initial  
David Heinemeier Hansson 已提交
638
    ActiveRecord::Base.pluralize_table_names = true
639
    classes.each(&:reset_table_name)
D
Initial  
David Heinemeier Hansson 已提交
640
  end
J
Jeremy Kemper 已提交
641

D
Initial  
David Heinemeier Hansson 已提交
642
  def test_destroy_all
643 644
    original_count = Topic.count
    topics_by_mary = Topic.count(:conditions => mary = "author_name = 'Mary'")
645

646 647
    Topic.destroy_all mary
    assert_equal original_count - topics_by_mary, Topic.count
D
Initial  
David Heinemeier Hansson 已提交
648
  end
649 650

  def test_destroy_many
651 652 653
    assert_difference('Client.count', -2) do
      Client.destroy([2, 3])
    end
654 655 656
  end

  def test_delete_many
657 658 659
    original_count = Topic.count
    Topic.delete(deleting = [1, 2])
    assert_equal original_count - deleting.size, Topic.count
660 661
  end

D
Initial  
David Heinemeier Hansson 已提交
662 663 664 665
  def test_boolean_attributes
    assert ! Topic.find(1).approved?
    assert Topic.find(2).approved?
  end
J
Jeremy Kemper 已提交
666

D
Initial  
David Heinemeier Hansson 已提交
667 668
  def test_increment_counter
    Topic.increment_counter("replies_count", 1)
669
    assert_equal 2, Topic.find(1).replies_count
D
Initial  
David Heinemeier Hansson 已提交
670 671

    Topic.increment_counter("replies_count", 1)
672
    assert_equal 3, Topic.find(1).replies_count
D
Initial  
David Heinemeier Hansson 已提交
673
  end
J
Jeremy Kemper 已提交
674

D
Initial  
David Heinemeier Hansson 已提交
675 676
  def test_decrement_counter
    Topic.decrement_counter("replies_count", 2)
677
    assert_equal -1, Topic.find(2).replies_count
D
Initial  
David Heinemeier Hansson 已提交
678 679

    Topic.decrement_counter("replies_count", 2)
680
    assert_equal -2, Topic.find(2).replies_count
D
Initial  
David Heinemeier Hansson 已提交
681
  end
682

683
  def test_update_counter
J
Jeremy Kemper 已提交
684
    category = categories(:general)
685 686 687 688 689 690 691 692 693 694 695 696
    assert_nil category.categorizations_count
    assert_equal 2, category.categorizations.count

    Category.update_counters(category.id, "categorizations_count" => category.categorizations.count)
    category.reload
    assert_not_nil category.categorizations_count
    assert_equal 2, category.categorizations_count

    Category.update_counters(category.id, "categorizations_count" => category.categorizations.count)
    category.reload
    assert_not_nil category.categorizations_count
    assert_equal 4, category.categorizations_count
697 698 699 700 701 702 703

    category_2 = categories(:technology)
    count_1, count_2 = (category.categorizations_count || 0), (category_2.categorizations_count || 0)
    Category.update_counters([category.id, category_2.id], "categorizations_count" => 2)
    category.reload; category_2.reload
    assert_equal count_1 + 2, category.categorizations_count
    assert_equal count_2 + 2, category_2.categorizations_count
704 705
  end

706
  def test_update_all
707
    assert_equal Topic.count, Topic.update_all("content = 'bulk updated!'")
708 709
    assert_equal "bulk updated!", Topic.find(1).content
    assert_equal "bulk updated!", Topic.find(2).content
710

711
    assert_equal Topic.count, Topic.update_all(['content = ?', 'bulk updated again!'])
712 713 714
    assert_equal "bulk updated again!", Topic.find(1).content
    assert_equal "bulk updated again!", Topic.find(2).content

715
    assert_equal Topic.count, Topic.update_all(['content = ?', nil])
716 717 718 719 720
    assert_nil Topic.find(1).content
  end

  def test_update_all_with_hash
    assert_not_nil Topic.find(1).last_read
721
    assert_equal Topic.count, Topic.update_all(:content => 'bulk updated with hash!', :last_read => nil)
722 723 724 725
    assert_equal "bulk updated with hash!", Topic.find(1).content
    assert_equal "bulk updated with hash!", Topic.find(2).content
    assert_nil Topic.find(1).last_read
    assert_nil Topic.find(2).last_read
D
Initial  
David Heinemeier Hansson 已提交
726
  end
727

728 729 730 731 732
  def test_update_all_with_non_standard_table_name
    assert_equal 1, WarehouseThing.update_all(['value = ?', 0], ['id = ?', 1])
    assert_equal 0, WarehouseThing.find(1).value
  end

733 734 735 736 737 738
  if current_adapter?(:MysqlAdapter)
    def test_update_all_with_order_and_limit
      assert_equal 1, Topic.update_all("content = 'bulk updated!'", nil, :limit => 1, :order => 'id DESC')
    end
  end

739 740 741 742 743 744 745
  # Oracle UPDATE does not support ORDER BY
  unless current_adapter?(:OracleAdapter)
    def test_update_all_ignores_order_without_limit_from_association
      author = authors(:david)
      assert_nothing_raised do
        assert_equal author.posts_with_comments_and_categories.length, author.posts_with_comments_and_categories.update_all([ "body = ?", "bulk update!" ])
      end
746 747
    end

748 749 750 751 752 753 754 755 756
    def test_update_all_with_order_and_limit_updates_subset_only
      author = authors(:david)
      assert_nothing_raised do
        assert_equal 1, author.posts_sorted_by_id_limited.size
        assert_equal 2, author.posts_sorted_by_id_limited.find(:all, :limit => 2).size
        assert_equal 1, author.posts_sorted_by_id_limited.update_all([ "body = ?", "bulk update!" ])
        assert_equal "bulk update!", posts(:welcome).body
        assert_not_equal "bulk update!", posts(:thinking).body
      end
757 758 759
    end
  end

760
  def test_update_many
761
    topic_data = { 1 => { "content" => "1 updated" }, 2 => { "content" => "2 updated" } }
762
    updated = Topic.update(topic_data.keys, topic_data.values)
763 764 765 766 767 768

    assert_equal 2, updated.size
    assert_equal "1 updated", Topic.find(1).content
    assert_equal "2 updated", Topic.find(2).content
  end

769
  def test_delete_all
770
    assert Topic.count > 0
771

772
    assert_equal Topic.count, Topic.delete_all
773 774
  end

D
Initial  
David Heinemeier Hansson 已提交
775
  def test_update_by_condition
776
    Topic.update_all "content = 'bulk updated!'", ["approved = ?", true]
D
Initial  
David Heinemeier Hansson 已提交
777 778 779
    assert_equal "Have a nice day", Topic.find(1).content
    assert_equal "bulk updated!", Topic.find(2).content
  end
J
Jeremy Kemper 已提交
780

D
Initial  
David Heinemeier Hansson 已提交
781 782 783 784 785 786 787 788
  def test_attribute_present
    t = Topic.new
    t.title = "hello there!"
    t.written_on = Time.now
    assert t.attribute_present?("title")
    assert t.attribute_present?("written_on")
    assert !t.attribute_present?("content")
  end
J
Jeremy Kemper 已提交
789

D
Initial  
David Heinemeier Hansson 已提交
790 791 792
  def test_attribute_keys_on_new_instance
    t = Topic.new
    assert_equal nil, t.title, "The topics table has a title column, so it should be nil"
793
    assert_raise(NoMethodError) { t.title2 }
D
Initial  
David Heinemeier Hansson 已提交
794
  end
J
Jeremy Kemper 已提交
795

D
Initial  
David Heinemeier Hansson 已提交
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
  def test_class_name
    assert_equal "Firm", ActiveRecord::Base.class_name("firms")
    assert_equal "Category", ActiveRecord::Base.class_name("categories")
    assert_equal "AccountHolder", ActiveRecord::Base.class_name("account_holder")

    ActiveRecord::Base.pluralize_table_names = false
    assert_equal "Firms", ActiveRecord::Base.class_name( "firms" )
    ActiveRecord::Base.pluralize_table_names = true

    ActiveRecord::Base.table_name_prefix = "test_"
    assert_equal "Firm", ActiveRecord::Base.class_name( "test_firms" )
    ActiveRecord::Base.table_name_suffix = "_tests"
    assert_equal "Firm", ActiveRecord::Base.class_name( "test_firms_tests" )
    ActiveRecord::Base.table_name_prefix = ""
    assert_equal "Firm", ActiveRecord::Base.class_name( "firms_tests" )
    ActiveRecord::Base.table_name_suffix = ""
    assert_equal "Firm", ActiveRecord::Base.class_name( "firms" )
  end
J
Jeremy Kemper 已提交
814

D
Initial  
David Heinemeier Hansson 已提交
815 816 817 818
  def test_null_fields
    assert_nil Topic.find(1).parent_id
    assert_nil Topic.create("title" => "Hey you").parent_id
  end
J
Jeremy Kemper 已提交
819

D
Initial  
David Heinemeier Hansson 已提交
820 821
  def test_default_values
    topic = Topic.new
J
Jeremy Kemper 已提交
822
    assert topic.approved?
D
Initial  
David Heinemeier Hansson 已提交
823
    assert_nil topic.written_on
824
    assert_nil topic.bonus_time
D
Initial  
David Heinemeier Hansson 已提交
825
    assert_nil topic.last_read
J
Jeremy Kemper 已提交
826

D
Initial  
David Heinemeier Hansson 已提交
827 828 829
    topic.save

    topic = Topic.find(topic.id)
J
Jeremy Kemper 已提交
830
    assert topic.approved?
D
Initial  
David Heinemeier Hansson 已提交
831
    assert_nil topic.last_read
832

J
Jeremy Kemper 已提交
833
    # Oracle has some funky default handling, so it requires a bit of
834
    # extra testing. See ticket #2788.
835 836
    if current_adapter?(:OracleAdapter)
      test = TestOracleDefault.new
837 838 839 840
      assert_equal "X", test.test_char
      assert_equal "hello", test.test_string
      assert_equal 3, test.test_int
    end
D
Initial  
David Heinemeier Hansson 已提交
841
  end
842

843 844
  # Oracle, and Sybase do not have a TIME datatype.
  unless current_adapter?(:OracleAdapter, :SybaseAdapter)
845 846 847 848 849 850 851 852
    def test_utc_as_time_zone
      Topic.default_timezone = :utc
      attributes = { "bonus_time" => "5:42:00AM" }
      topic = Topic.find(1)
      topic.attributes = attributes
      assert_equal Time.utc(2000, 1, 1, 5, 42, 0), topic.bonus_time
      Topic.default_timezone = :local
    end
853

854 855 856 857 858 859 860 861 862 863 864 865
    def test_utc_as_time_zone_and_new
      Topic.default_timezone = :utc
      attributes = { "bonus_time(1i)"=>"2000",
                     "bonus_time(2i)"=>"1",
                     "bonus_time(3i)"=>"1",
                     "bonus_time(4i)"=>"10",
                     "bonus_time(5i)"=>"35",
                     "bonus_time(6i)"=>"50" }
      topic = Topic.new(attributes)
      assert_equal Time.utc(2000, 1, 1, 10, 35, 50), topic.bonus_time
      Topic.default_timezone = :local
    end
866 867
  end

D
Initial  
David Heinemeier Hansson 已提交
868 869 870 871 872 873 874 875 876
  def test_default_values_on_empty_strings
    topic = Topic.new
    topic.approved  = nil
    topic.last_read = nil

    topic.save

    topic = Topic.find(topic.id)
    assert_nil topic.last_read
877 878 879 880 881 882 883

    # Sybase adapter does not allow nulls in boolean columns
    if current_adapter?(:SybaseAdapter)
      assert topic.approved == false
    else
      assert_nil topic.approved
    end
D
Initial  
David Heinemeier Hansson 已提交
884
  end
885

D
Initial  
David Heinemeier Hansson 已提交
886
  def test_equality
887
    assert_equal Topic.find(1), Topic.find(2).topic
D
Initial  
David Heinemeier Hansson 已提交
888
  end
J
Jeremy Kemper 已提交
889

890 891 892
  def test_equality_of_new_records
    assert_not_equal Topic.new, Topic.new
  end
J
Jeremy Kemper 已提交
893

D
Initial  
David Heinemeier Hansson 已提交
894
  def test_hashing
895
    assert_equal [ Topic.find(1) ], [ Topic.find(2).topic ] & [ Topic.find(1) ]
D
Initial  
David Heinemeier Hansson 已提交
896
  end
J
Jeremy Kemper 已提交
897

898 899 900 901 902 903 904 905 906 907 908
  def test_delete_new_record
    client = Client.new
    client.delete
    assert client.frozen?
  end

  def test_delete_record_with_associations
    client = Client.find(3)
    client.delete
    assert client.frozen?
    assert_kind_of Firm, client.firm
909
    assert_raise(ActiveSupport::FrozenObjectError) { client.name = "something else" }
910 911
  end

D
Initial  
David Heinemeier Hansson 已提交
912 913 914 915 916
  def test_destroy_new_record
    client = Client.new
    client.destroy
    assert client.frozen?
  end
J
Jeremy Kemper 已提交
917

918 919 920 921 922
  def test_destroy_record_with_associations
    client = Client.find(3)
    client.destroy
    assert client.frozen?
    assert_kind_of Firm, client.firm
923
    assert_raise(ActiveSupport::FrozenObjectError) { client.name = "something else" }
924
  end
J
Jeremy Kemper 已提交
925

D
Initial  
David Heinemeier Hansson 已提交
926 927 928 929
  def test_update_attribute
    assert !Topic.find(1).approved?
    Topic.find(1).update_attribute("approved", true)
    assert Topic.find(1).approved?
930 931 932

    Topic.find(1).update_attribute(:approved, false)
    assert !Topic.find(1).approved?
D
Initial  
David Heinemeier Hansson 已提交
933
  end
J
Jeremy Kemper 已提交
934

935 936 937 938
  def test_update_attributes
    topic = Topic.find(1)
    assert !topic.approved?
    assert_equal "The First Topic", topic.title
J
Jeremy Kemper 已提交
939

940 941 942 943 944 945 946 947 948 949
    topic.update_attributes("approved" => true, "title" => "The First Topic Updated")
    topic.reload
    assert topic.approved?
    assert_equal "The First Topic Updated", topic.title

    topic.update_attributes(:approved => false, :title => "The First Topic")
    topic.reload
    assert !topic.approved?
    assert_equal "The First Topic", topic.title
  end
J
Jeremy Kemper 已提交
950

951 952
  def test_update_attributes!
    reply = Reply.find(2)
953
    assert_equal "The Second Topic of the day", reply.title
954
    assert_equal "Have a nice day", reply.content
J
Jeremy Kemper 已提交
955

956
    reply.update_attributes!("title" => "The Second Topic of the day updated", "content" => "Have a nice evening")
957
    reply.reload
958
    assert_equal "The Second Topic of the day updated", reply.title
959
    assert_equal "Have a nice evening", reply.content
J
Jeremy Kemper 已提交
960

961
    reply.update_attributes!(:title => "The Second Topic of the day", :content => "Have a nice day")
962
    reply.reload
963
    assert_equal "The Second Topic of the day", reply.title
964
    assert_equal "Have a nice day", reply.content
J
Jeremy Kemper 已提交
965

966 967
    assert_raise(ActiveRecord::RecordInvalid) { reply.update_attributes!(:title => nil, :content => "Have a nice evening") }
  end
J
Jeremy Kemper 已提交
968

969 970
  def test_mass_assignment_should_raise_exception_if_accessible_and_protected_attribute_writers_are_both_used
    topic = TopicWithProtectedContentAndAccessibleAuthorName.new
971 972
    assert_raise(RuntimeError) { topic.attributes = { "author_name" => "me" } }
    assert_raise(RuntimeError) { topic.attributes = { "content" => "stuff" } }
973
  end
J
Jeremy Kemper 已提交
974

D
Initial  
David Heinemeier Hansson 已提交
975 976 977 978 979
  def test_mass_assignment_protection
    firm = Firm.new
    firm.attributes = { "name" => "Next Angle", "rating" => 5 }
    assert_equal 1, firm.rating
  end
J
Jeremy Kemper 已提交
980

981 982
  def test_mass_assignment_protection_against_class_attribute_writers
    [:logger, :configurations, :primary_key_prefix_type, :table_name_prefix, :table_name_suffix, :pluralize_table_names, :colorize_logging,
983
      :default_timezone, :schema_format, :lock_optimistically, :record_timestamps].each do |method|
984 985 986 987 988 989
      assert  Task.respond_to?(method)
      assert  Task.respond_to?("#{method}=")
      assert  Task.new.respond_to?(method)
      assert !Task.new.respond_to?("#{method}=")
    end
  end
990 991 992 993 994 995 996 997 998

  def test_customized_primary_key_remains_protected
    subscriber = Subscriber.new(:nick => 'webster123', :name => 'nice try')
    assert_nil subscriber.id

    keyboard = Keyboard.new(:key_number => 9, :name => 'nice try')
    assert_nil keyboard.id
  end

999
  def test_customized_primary_key_remains_protected_when_referred_to_as_id
1000 1001 1002 1003 1004 1005
    subscriber = Subscriber.new(:id => 'webster123', :name => 'nice try')
    assert_nil subscriber.id

    keyboard = Keyboard.new(:id => 9, :name => 'nice try')
    assert_nil keyboard.id
  end
J
Jeremy Kemper 已提交
1006

1007 1008 1009
  def test_mass_assigning_invalid_attribute
    firm = Firm.new

1010
    assert_raise(ActiveRecord::UnknownAttributeError) do
1011 1012 1013 1014
      firm.attributes = { "id" => 5, "type" => "Client", "i_dont_even_exist" => 20 }
    end
  end

1015 1016 1017 1018 1019 1020
  def test_mass_assignment_protection_on_defaults
    firm = Firm.new
    firm.attributes = { "id" => 5, "type" => "Client" }
    assert_nil firm.id
    assert_equal "Firm", firm[:type]
  end
J
Jeremy Kemper 已提交
1021

D
Initial  
David Heinemeier Hansson 已提交
1022
  def test_mass_assignment_accessible
1023
    reply = Reply.new("title" => "hello", "content" => "world", "approved" => true)
D
Initial  
David Heinemeier Hansson 已提交
1024
    reply.save
J
Jeremy Kemper 已提交
1025 1026

    assert reply.approved?
J
Jeremy Kemper 已提交
1027

J
Jeremy Kemper 已提交
1028
    reply.approved = false
D
Initial  
David Heinemeier Hansson 已提交
1029 1030
    reply.save

J
Jeremy Kemper 已提交
1031
    assert !reply.approved?
D
Initial  
David Heinemeier Hansson 已提交
1032
  end
J
Jeremy Kemper 已提交
1033

D
Initial  
David Heinemeier Hansson 已提交
1034
  def test_mass_assignment_protection_inheritance
1035
    assert_nil LoosePerson.accessible_attributes
1036
    assert_equal Set.new([ 'credit_rating', 'administrator' ]), LoosePerson.protected_attributes
1037 1038

    assert_nil LooseDescendant.accessible_attributes
1039 1040 1041 1042
    assert_equal Set.new([ 'credit_rating', 'administrator', 'phone_number' ]), LooseDescendant.protected_attributes

    assert_nil LooseDescendantSecond.accessible_attributes
    assert_equal Set.new([ 'credit_rating', 'administrator', 'phone_number', 'name' ]), LooseDescendantSecond.protected_attributes, 'Running attr_protected twice in one class should merge the protections'
1043

D
Initial  
David Heinemeier Hansson 已提交
1044
    assert_nil TightPerson.protected_attributes
1045
    assert_equal Set.new([ 'name', 'address' ]), TightPerson.accessible_attributes
1046 1047

    assert_nil TightDescendant.protected_attributes
1048
    assert_equal Set.new([ 'name', 'address', 'phone_number' ]), TightDescendant.accessible_attributes
D
Initial  
David Heinemeier Hansson 已提交
1049
  end
J
Jeremy Kemper 已提交
1050

1051
  def test_readonly_attributes
1052
    assert_equal Set.new([ 'title' , 'comments_count' ]), ReadonlyTitlePost.readonly_attributes
J
Jeremy Kemper 已提交
1053

1054 1055 1056
    post = ReadonlyTitlePost.create(:title => "cannot change this", :body => "changeable")
    post.reload
    assert_equal "cannot change this", post.title
J
Jeremy Kemper 已提交
1057

1058 1059 1060 1061 1062
    post.update_attributes(:title => "try to change", :body => "changed")
    post.reload
    assert_equal "cannot change this", post.title
    assert_equal "changed", post.body
  end
D
Initial  
David Heinemeier Hansson 已提交
1063 1064 1065 1066 1067

  def test_multiparameter_attributes_on_date
    attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "6", "last_read(3i)" => "24" }
    topic = Topic.find(1)
    topic.attributes = attributes
J
Jeremy Kemper 已提交
1068
    # note that extra #to_date call allows test to pass for Oracle, which
1069
    # treats dates/times the same
1070
    assert_date_from_db Date.new(2004, 6, 24), topic.last_read.to_date
D
Initial  
David Heinemeier Hansson 已提交
1071 1072
  end

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
  def test_multiparameter_attributes_on_date_with_empty_year
    attributes = { "last_read(1i)" => "", "last_read(2i)" => "6", "last_read(3i)" => "24" }
    topic = Topic.find(1)
    topic.attributes = attributes
    # note that extra #to_date call allows test to pass for Oracle, which
    # treats dates/times the same
    assert_date_from_db Date.new(1, 6, 24), topic.last_read.to_date
  end

  def test_multiparameter_attributes_on_date_with_empty_month
    attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "", "last_read(3i)" => "24" }
    topic = Topic.find(1)
    topic.attributes = attributes
    # note that extra #to_date call allows test to pass for Oracle, which
    # treats dates/times the same
    assert_date_from_db Date.new(2004, 1, 24), topic.last_read.to_date
  end

  def test_multiparameter_attributes_on_date_with_empty_day
D
Initial  
David Heinemeier Hansson 已提交
1092 1093 1094
    attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "6", "last_read(3i)" => "" }
    topic = Topic.find(1)
    topic.attributes = attributes
J
Jeremy Kemper 已提交
1095
    # note that extra #to_date call allows test to pass for Oracle, which
1096
    # treats dates/times the same
1097
    assert_date_from_db Date.new(2004, 6, 1), topic.last_read.to_date
D
Initial  
David Heinemeier Hansson 已提交
1098 1099
  end

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
  def test_multiparameter_attributes_on_date_with_empty_day_and_year
    attributes = { "last_read(1i)" => "", "last_read(2i)" => "6", "last_read(3i)" => "" }
    topic = Topic.find(1)
    topic.attributes = attributes
    # note that extra #to_date call allows test to pass for Oracle, which
    # treats dates/times the same
    assert_date_from_db Date.new(1, 6, 1), topic.last_read.to_date
  end

  def test_multiparameter_attributes_on_date_with_empty_day_and_month
    attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "", "last_read(3i)" => "" }
    topic = Topic.find(1)
    topic.attributes = attributes
    # note that extra #to_date call allows test to pass for Oracle, which
    # treats dates/times the same
    assert_date_from_db Date.new(2004, 1, 1), topic.last_read.to_date
  end

  def test_multiparameter_attributes_on_date_with_empty_year_and_month
    attributes = { "last_read(1i)" => "", "last_read(2i)" => "", "last_read(3i)" => "24" }
    topic = Topic.find(1)
    topic.attributes = attributes
    # note that extra #to_date call allows test to pass for Oracle, which
    # treats dates/times the same
    assert_date_from_db Date.new(1, 1, 24), topic.last_read.to_date
  end

D
Initial  
David Heinemeier Hansson 已提交
1127 1128 1129 1130 1131 1132 1133 1134
  def test_multiparameter_attributes_on_date_with_all_empty
    attributes = { "last_read(1i)" => "", "last_read(2i)" => "", "last_read(3i)" => "" }
    topic = Topic.find(1)
    topic.attributes = attributes
    assert_nil topic.last_read
  end

  def test_multiparameter_attributes_on_time
J
Jeremy Kemper 已提交
1135 1136
    attributes = {
      "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
D
Initial  
David Heinemeier Hansson 已提交
1137 1138 1139 1140 1141 1142
      "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
    }
    topic = Topic.find(1)
    topic.attributes = attributes
    assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
  end
1143

1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
  def test_multiparameter_attributes_on_time_with_old_date
    attributes = {
      "written_on(1i)" => "1850", "written_on(2i)" => "6", "written_on(3i)" => "24",
      "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
    }
    topic = Topic.find(1)
    topic.attributes = attributes
    # testing against to_s(:db) representation because either a Time or a DateTime might be returned, depending on platform
    assert_equal "1850-06-24 16:24:00", topic.written_on.to_s(:db)
  end
D
Initial  
David Heinemeier Hansson 已提交
1154

1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
  def test_multiparameter_attributes_on_time_with_utc
    ActiveRecord::Base.default_timezone = :utc
    attributes = {
      "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
      "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
    }
    topic = Topic.find(1)
    topic.attributes = attributes
    assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on
  ensure
    ActiveRecord::Base.default_timezone = :local
  end

1168 1169 1170
  def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes
    ActiveRecord::Base.time_zone_aware_attributes = true
    ActiveRecord::Base.default_timezone = :utc
1171
    Time.zone = ActiveSupport::TimeZone[-28800]
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
    attributes = {
      "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
      "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
    }
    topic = Topic.find(1)
    topic.attributes = attributes
    assert_equal Time.utc(2004, 6, 24, 23, 24, 0), topic.written_on
    assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on.time
    assert_equal Time.zone, topic.written_on.time_zone
  ensure
    ActiveRecord::Base.time_zone_aware_attributes = false
    ActiveRecord::Base.default_timezone = :local
    Time.zone = nil
1185
  end
1186

1187 1188
  def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes_false
    ActiveRecord::Base.time_zone_aware_attributes = false
1189
    Time.zone = ActiveSupport::TimeZone[-28800]
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
    attributes = {
      "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
      "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
    }
    topic = Topic.find(1)
    topic.attributes = attributes
    assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
    assert_equal false, topic.written_on.respond_to?(:time_zone)
  ensure
    Time.zone = nil
  end

1202 1203 1204
  def test_multiparameter_attributes_on_time_with_skip_time_zone_conversion_for_attributes
    ActiveRecord::Base.time_zone_aware_attributes = true
    ActiveRecord::Base.default_timezone = :utc
1205
    Time.zone = ActiveSupport::TimeZone[-28800]
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
    Topic.skip_time_zone_conversion_for_attributes = [:written_on]
    attributes = {
      "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
      "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
    }
    topic = Topic.find(1)
    topic.attributes = attributes
    assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on
    assert_equal false, topic.written_on.respond_to?(:time_zone)
  ensure
    ActiveRecord::Base.time_zone_aware_attributes = false
    ActiveRecord::Base.default_timezone = :local
    Time.zone = nil
    Topic.skip_time_zone_conversion_for_attributes = []
  end
1221

1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
  # Oracle, and Sybase do not have a TIME datatype.
  unless current_adapter?(:OracleAdapter, :SybaseAdapter)
    def test_multiparameter_attributes_on_time_only_column_with_time_zone_aware_attributes_does_not_do_time_zone_conversion
      ActiveRecord::Base.time_zone_aware_attributes = true
      ActiveRecord::Base.default_timezone = :utc
      Time.zone = ActiveSupport::TimeZone[-28800]
      attributes = {
        "bonus_time(1i)" => "2000", "bonus_time(2i)" => "1", "bonus_time(3i)" => "1",
        "bonus_time(4i)" => "16", "bonus_time(5i)" => "24"
      }
      topic = Topic.find(1)
      topic.attributes = attributes
      assert_equal Time.utc(2000, 1, 1, 16, 24, 0), topic.bonus_time
      assert topic.bonus_time.utc?
    ensure
      ActiveRecord::Base.time_zone_aware_attributes = false
      ActiveRecord::Base.default_timezone = :local
      Time.zone = nil
    end
1241
  end
1242

D
Initial  
David Heinemeier Hansson 已提交
1243
  def test_multiparameter_attributes_on_time_with_empty_seconds
J
Jeremy Kemper 已提交
1244 1245
    attributes = {
      "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
D
Initial  
David Heinemeier Hansson 已提交
1246 1247 1248 1249 1250 1251 1252
      "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => ""
    }
    topic = Topic.find(1)
    topic.attributes = attributes
    assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
  end

1253 1254
  def test_multiparameter_mass_assignment_protector
    task = Task.new
1255
    time = Time.mktime(2000, 1, 1, 1)
J
Jeremy Kemper 已提交
1256
    task.starting = time
1257 1258 1259 1260
    attributes = { "starting(1i)" => "2004", "starting(2i)" => "6", "starting(3i)" => "24" }
    task.attributes = attributes
    assert_equal time, task.starting
  end
J
Jeremy Kemper 已提交
1261

1262 1263 1264 1265 1266 1267 1268
  def test_multiparameter_assignment_of_aggregation
    customer = Customer.new
    address = Address.new("The Street", "The City", "The Country")
    attributes = { "address(1)" => address.street, "address(2)" => address.city, "address(3)" => address.country }
    customer.attributes = attributes
    assert_equal address, customer.address
  end
1269

1270
  def test_attributes_on_dummy_time
1271 1272
    # Oracle, and Sybase do not have a TIME datatype.
    return true if current_adapter?(:OracleAdapter, :SybaseAdapter)
1273

1274 1275 1276 1277 1278 1279 1280 1281
    attributes = {
      "bonus_time" => "5:42:00AM"
    }
    topic = Topic.find(1)
    topic.attributes = attributes
    assert_equal Time.local(2000, 1, 1, 5, 42, 0), topic.bonus_time
  end

D
Initial  
David Heinemeier Hansson 已提交
1282
  def test_boolean
1283 1284
    b_nil = Booleantest.create({ "value" => nil })
    nil_id = b_nil.id
D
Initial  
David Heinemeier Hansson 已提交
1285 1286 1287 1288 1289
    b_false = Booleantest.create({ "value" => false })
    false_id = b_false.id
    b_true = Booleantest.create({ "value" => true })
    true_id = b_true.id

1290 1291
    b_nil = Booleantest.find(nil_id)
    assert_nil b_nil.value
D
Initial  
David Heinemeier Hansson 已提交
1292 1293 1294 1295 1296
    b_false = Booleantest.find(false_id)
    assert !b_false.value?
    b_true = Booleantest.find(true_id)
    assert b_true.value?
  end
1297 1298

  def test_boolean_cast_from_string
1299 1300
    b_blank = Booleantest.create({ "value" => "" })
    blank_id = b_blank.id
D
David Heinemeier Hansson 已提交
1301
    b_false = Booleantest.create({ "value" => "0" })
1302
    false_id = b_false.id
D
David Heinemeier Hansson 已提交
1303
    b_true = Booleantest.create({ "value" => "1" })
1304 1305
    true_id = b_true.id

1306 1307
    b_blank = Booleantest.find(blank_id)
    assert_nil b_blank.value
1308 1309 1310
    b_false = Booleantest.find(false_id)
    assert !b_false.value?
    b_true = Booleantest.find(true_id)
J
Jeremy Kemper 已提交
1311
    assert b_true.value?
1312
  end
J
Jeremy Kemper 已提交
1313

1314 1315 1316 1317 1318
  def test_new_record_returns_boolean
    assert_equal Topic.new.new_record?, true
    assert_equal Topic.find(1).new_record?, false
  end

1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
  def test_destroyed_returns_boolean
    developer = Developer.new
    assert_equal developer.destroyed?, false
    developer.destroy
    assert_equal developer.destroyed?, true

    developer = Developer.first
    assert_equal developer.destroyed?, false
    developer.destroy
    assert_equal developer.destroyed?, true

    developer = Developer.last
    assert_equal developer.destroyed?, false
    developer.delete
    assert_equal developer.destroyed?, true
  end

D
Initial  
David Heinemeier Hansson 已提交
1336 1337
  def test_clone
    topic = Topic.find(1)
1338 1339
    cloned_topic = nil
    assert_nothing_raised { cloned_topic = topic.clone }
D
Initial  
David Heinemeier Hansson 已提交
1340
    assert_equal topic.title, cloned_topic.title
1341
    assert cloned_topic.new_record?
D
Initial  
David Heinemeier Hansson 已提交
1342 1343

    # test if the attributes have been cloned
J
Jeremy Kemper 已提交
1344 1345
    topic.title = "a"
    cloned_topic.title = "b"
D
Initial  
David Heinemeier Hansson 已提交
1346 1347 1348 1349 1350 1351
    assert_equal "a", topic.title
    assert_equal "b", cloned_topic.title

    # test if the attribute values have been cloned
    topic.title = {"a" => "b"}
    cloned_topic = topic.clone
J
Jeremy Kemper 已提交
1352
    cloned_topic.title["a"] = "c"
D
Initial  
David Heinemeier Hansson 已提交
1353
    assert_equal "b", topic.title["a"]
1354

1355
    # test if attributes set as part of after_initialize are cloned correctly
1356 1357 1358
    assert_equal topic.author_email_address, cloned_topic.author_email_address

    # test if saved clone object differs from original
1359
    cloned_topic.save
1360
    assert !cloned_topic.new_record?
1361
    assert cloned_topic.id != topic.id
D
Initial  
David Heinemeier Hansson 已提交
1362
  end
1363 1364 1365 1366 1367 1368 1369 1370 1371

  def test_clone_with_aggregate_of_same_name_as_attribute
    dev = DeveloperWithAggregate.find(1)
    assert_kind_of DeveloperSalary, dev.salary

    clone = nil
    assert_nothing_raised { clone = dev.clone }
    assert_kind_of DeveloperSalary, clone.salary
    assert_equal dev.salary.amount, clone.salary.amount
1372
    assert clone.new_record?
1373 1374 1375 1376 1377 1378 1379

    # test if the attributes have been cloned
    original_amount = clone.salary.amount
    dev.salary.amount = 1
    assert_equal original_amount, clone.salary.amount

    assert clone.save
1380
    assert !clone.new_record?
1381 1382 1383 1384 1385 1386 1387 1388 1389
    assert clone.id != dev.id
  end

  def test_clone_preserves_subtype
    clone = nil
    assert_nothing_raised { clone = Company.find(3).clone }
    assert_kind_of Client, clone
  end

D
Initial  
David Heinemeier Hansson 已提交
1390 1391 1392 1393 1394 1395 1396 1397
  def test_bignum
    company = Company.find(1)
    company.rating = 2147483647
    company.save
    company = Company.find(1)
    assert_equal 2147483647, company.rating
  end

1398
  # TODO: extend defaults tests to other databases!
1399
  if current_adapter?(:PostgreSQLAdapter)
1400
    def test_default
D
Initial  
David Heinemeier Hansson 已提交
1401
      default = Default.new
J
Jeremy Kemper 已提交
1402

D
Initial  
David Heinemeier Hansson 已提交
1403 1404 1405
      # fixed dates / times
      assert_equal Date.new(2004, 1, 1), default.fixed_date
      assert_equal Time.local(2004, 1,1,0,0,0,0), default.fixed_time
J
Jeremy Kemper 已提交
1406

D
Initial  
David Heinemeier Hansson 已提交
1407 1408 1409 1410 1411
      # char types
      assert_equal 'Y', default.char1
      assert_equal 'a varchar field', default.char2
      assert_equal 'a text field', default.char3
    end
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428

    class Geometric < ActiveRecord::Base; end
    def test_geometric_content

      # accepted format notes:
      # ()'s aren't required
      # values can be a mix of float or integer

      g = Geometric.new(
        :a_point        => '(5.0, 6.1)',
        #:a_line         => '((2.0, 3), (5.5, 7.0))' # line type is currently unsupported in postgresql
        :a_line_segment => '(2.0, 3), (5.5, 7.0)',
        :a_box          => '2.0, 3, 5.5, 7.0',
        :a_path         => '[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]',  # [ ] is an open path
        :a_polygon      => '((2.0, 3), (5.5, 7.0), (8.5, 11.0))',
        :a_circle       => '<(5.3, 10.4), 2>'
      )
J
Jeremy Kemper 已提交
1429

1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
      assert g.save

      # Reload and check that we have all the geometric attributes.
      h = Geometric.find(g.id)

      assert_equal '(5,6.1)', h.a_point
      assert_equal '[(2,3),(5.5,7)]', h.a_line_segment
      assert_equal '(5.5,7),(2,3)', h.a_box   # reordered to store upper right corner then bottom left corner
      assert_equal '[(2,3),(5.5,7),(8.5,11)]', h.a_path
      assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon
      assert_equal '<(5.3,10.4),2>', h.a_circle

      # use a geometric function to test for an open path
      objs = Geometric.find_by_sql ["select isopen(a_path) from geometrics where id = ?", g.id]
      assert_equal objs[0].isopen, 't'

      # test alternate formats when defining the geometric types
J
Jeremy Kemper 已提交
1447

1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
      g = Geometric.new(
        :a_point        => '5.0, 6.1',
        #:a_line         => '((2.0, 3), (5.5, 7.0))' # line type is currently unsupported in postgresql
        :a_line_segment => '((2.0, 3), (5.5, 7.0))',
        :a_box          => '(2.0, 3), (5.5, 7.0)',
        :a_path         => '((2.0, 3), (5.5, 7.0), (8.5, 11.0))',  # ( ) is a closed path
        :a_polygon      => '2.0, 3, 5.5, 7.0, 8.5, 11.0',
        :a_circle       => '((5.3, 10.4), 2)'
      )

      assert g.save

      # Reload and check that we have all the geometric attributes.
      h = Geometric.find(g.id)
J
Jeremy Kemper 已提交
1462

1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
      assert_equal '(5,6.1)', h.a_point
      assert_equal '[(2,3),(5.5,7)]', h.a_line_segment
      assert_equal '(5.5,7),(2,3)', h.a_box   # reordered to store upper right corner then bottom left corner
      assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_path
      assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon
      assert_equal '<(5.3,10.4),2>', h.a_circle

      # use a geometric function to test for an closed path
      objs = Geometric.find_by_sql ["select isclosed(a_path) from geometrics where id = ?", g.id]
      assert_equal objs[0].isclosed, 't'
    end
D
Initial  
David Heinemeier Hansson 已提交
1474 1475
  end

1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
  class NumericData < ActiveRecord::Base
    self.table_name = 'numeric_data'
  end

  def test_numeric_fields
    m = NumericData.new(
      :bank_balance => 1586.43,
      :big_bank_balance => BigDecimal("1000234000567.95"),
      :world_population => 6000000000,
      :my_house_population => 3
    )
    assert m.save

    m1 = NumericData.find(m.id)
    assert_not_nil m1

    # As with migration_test.rb, we should make world_population >= 2**62
    # to cover 64-bit platforms and test it is a Bignum, but the main thing
    # is that it's an Integer.
    assert_kind_of Integer, m1.world_population
    assert_equal 6000000000, m1.world_population

    assert_kind_of Fixnum, m1.my_house_population
    assert_equal 3, m1.my_house_population

    assert_kind_of BigDecimal, m1.bank_balance
    assert_equal BigDecimal("1586.43"), m1.bank_balance

    assert_kind_of BigDecimal, m1.big_bank_balance
    assert_equal BigDecimal("1000234000567.95"), m1.big_bank_balance
  end

D
Initial  
David Heinemeier Hansson 已提交
1508 1509 1510 1511 1512
  def test_auto_id
    auto = AutoId.new
    auto.save
    assert (auto.id > 0)
  end
1513

D
Initial  
David Heinemeier Hansson 已提交
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
  def quote_column_name(name)
    "<#{name}>"
  end

  def test_quote_keys
    ar = AutoId.new
    source = {"foo" => "bar", "baz" => "quux"}
    actual = ar.send(:quote_columns, self, source)
    inverted = actual.invert
    assert_equal("<foo>", inverted["bar"])
    assert_equal("<baz>", inverted["quux"])
  end

1527
  def test_sql_injection_via_find
1528
    assert_raise(ActiveRecord::RecordNotFound, ActiveRecord::StatementInvalid) do
1529 1530 1531 1532
      Topic.find("123456 OR id > 0")
    end
  end

D
Initial  
David Heinemeier Hansson 已提交
1533 1534 1535
  def test_column_name_properly_quoted
    col_record = ColumnName.new
    col_record.references = 40
1536
    assert col_record.save
D
Initial  
David Heinemeier Hansson 已提交
1537
    col_record.references = 41
1538 1539
    assert col_record.save
    assert_not_nil c2 = ColumnName.find(col_record.id)
D
Initial  
David Heinemeier Hansson 已提交
1540 1541 1542
    assert_equal(41, c2.references)
  end

1543
  def test_quoting_arrays
1544
    replies = Reply.find(:all, :conditions => [ "id IN (?)", topics(:first).replies.collect(&:id) ])
1545 1546
    assert_equal topics(:first).replies.size, replies.size

1547
    replies = Reply.find(:all, :conditions => [ "id IN (?)", [] ])
1548 1549 1550
    assert_equal 0, replies.size
  end

D
Initial  
David Heinemeier Hansson 已提交
1551
  MyObject = Struct.new :attribute1, :attribute2
J
Jeremy Kemper 已提交
1552

D
Initial  
David Heinemeier Hansson 已提交
1553 1554
  def test_serialized_attribute
    myobj = MyObject.new('value1', 'value2')
J
Jeremy Kemper 已提交
1555
    topic = Topic.create("content" => myobj)
D
Initial  
David Heinemeier Hansson 已提交
1556 1557 1558 1559
    Topic.serialize("content", MyObject)
    assert_equal(myobj, topic.content)
  end

1560 1561 1562 1563 1564
  def test_serialized_time_attribute
    myobj = Time.local(2008,1,1,1,0)
    topic = Topic.create("content" => myobj).reload
    assert_equal(myobj, topic.content)
  end
1565

1566 1567 1568 1569 1570
  def test_serialized_string_attribute
    myobj = "Yes"
    topic = Topic.create("content" => myobj).reload
    assert_equal(myobj, topic.content)
  end
1571

1572
  def test_nil_serialized_attribute_with_class_constraint
D
Initial  
David Heinemeier Hansson 已提交
1573
    myobj = MyObject.new('value1', 'value2')
1574 1575 1576
    topic = Topic.new
    assert_nil topic.content
  end
D
Initial  
David Heinemeier Hansson 已提交
1577

1578 1579 1580 1581 1582
  def test_should_raise_exception_on_serialized_attribute_with_type_mismatch
    myobj = MyObject.new('value1', 'value2')
    topic = Topic.new(:content => myobj)
    assert topic.save
    Topic.serialize(:content, Hash)
1583
    assert_raise(ActiveRecord::SerializationTypeMismatch) { Topic.find(topic.id).content }
1584 1585 1586
  ensure
    Topic.serialize(:content)
  end
D
Initial  
David Heinemeier Hansson 已提交
1587

1588
  def test_serialized_attribute_with_class_constraint
D
Initial  
David Heinemeier Hansson 已提交
1589
    settings = { "color" => "blue" }
1590 1591 1592
    Topic.serialize(:content, Hash)
    topic = Topic.new(:content => settings)
    assert topic.save
D
Initial  
David Heinemeier Hansson 已提交
1593
    assert_equal(settings, Topic.find(topic.id).content)
1594
  ensure
D
Initial  
David Heinemeier Hansson 已提交
1595 1596 1597 1598
    Topic.serialize(:content)
  end

  def test_quote
1599 1600 1601
    author_name = "\\ \001 ' \n \\n \""
    topic = Topic.create('author_name' => author_name)
    assert_equal author_name, Topic.find(topic.id).author_name
D
Initial  
David Heinemeier Hansson 已提交
1602
  end
1603 1604 1605

  if RUBY_VERSION < '1.9'
    def test_quote_chars
1606 1607 1608 1609
      with_kcode('UTF8') do
        str = 'The Narrator'
        topic = Topic.create(:author_name => str)
        assert_equal str, topic.author_name
1610

1611 1612
        assert_kind_of ActiveSupport::Multibyte.proxy_class, str.mb_chars
        topic = Topic.find_by_author_name(str.mb_chars)
1613

1614 1615 1616
        assert_kind_of Topic, topic
        assert_equal str, topic.author_name, "The right topic should have been found by name even with name passed as Chars"
      end
1617
    end
1618
  end
1619

1620 1621
  def test_class_level_destroy
    should_be_destroyed_reply = Reply.create("title" => "hello", "content" => "world")
1622
    Topic.find(1).replies << should_be_destroyed_reply
1623 1624

    Topic.destroy(1)
1625 1626
    assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1) }
    assert_raise(ActiveRecord::RecordNotFound) { Reply.find(should_be_destroyed_reply.id) }
1627 1628 1629 1630
  end

  def test_class_level_delete
    should_be_destroyed_reply = Reply.create("title" => "hello", "content" => "world")
1631
    Topic.find(1).replies << should_be_destroyed_reply
1632 1633

    Topic.delete(1)
1634
    assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1) }
1635 1636
    assert_nothing_raised { Reply.find(should_be_destroyed_reply.id) }
  end
1637 1638

  def test_increment_attribute
1639 1640
    assert_equal 50, accounts(:signals37).credit_limit
    accounts(:signals37).increment! :credit_limit
J
Jeremy Kemper 已提交
1641
    assert_equal 51, accounts(:signals37, :reload).credit_limit
1642 1643 1644

    accounts(:signals37).increment(:credit_limit).increment!(:credit_limit)
    assert_equal 53, accounts(:signals37, :reload).credit_limit
1645
  end
J
Jeremy Kemper 已提交
1646

1647
  def test_increment_nil_attribute
1648 1649 1650
    assert_nil topics(:first).parent_id
    topics(:first).increment! :parent_id
    assert_equal 1, topics(:first).parent_id
1651
  end
J
Jeremy Kemper 已提交
1652

1653 1654 1655
  def test_increment_attribute_by
    assert_equal 50, accounts(:signals37).credit_limit
    accounts(:signals37).increment! :credit_limit, 5
J
Jeremy Kemper 已提交
1656
    assert_equal 55, accounts(:signals37, :reload).credit_limit
1657 1658 1659 1660

    accounts(:signals37).increment(:credit_limit, 1).increment!(:credit_limit, 3)
    assert_equal 59, accounts(:signals37, :reload).credit_limit
  end
J
Jeremy Kemper 已提交
1661

1662
  def test_decrement_attribute
1663
    assert_equal 50, accounts(:signals37).credit_limit
1664

1665 1666
    accounts(:signals37).decrement!(:credit_limit)
    assert_equal 49, accounts(:signals37, :reload).credit_limit
J
Jeremy Kemper 已提交
1667

1668 1669
    accounts(:signals37).decrement(:credit_limit).decrement!(:credit_limit)
    assert_equal 47, accounts(:signals37, :reload).credit_limit
1670
  end
J
Jeremy Kemper 已提交
1671

1672 1673 1674
  def test_decrement_attribute_by
    assert_equal 50, accounts(:signals37).credit_limit
    accounts(:signals37).decrement! :credit_limit, 5
J
Jeremy Kemper 已提交
1675
    assert_equal 45, accounts(:signals37, :reload).credit_limit
1676 1677 1678 1679

    accounts(:signals37).decrement(:credit_limit, 1).decrement!(:credit_limit, 3)
    assert_equal 41, accounts(:signals37, :reload).credit_limit
  end
J
Jeremy Kemper 已提交
1680

1681
  def test_toggle_attribute
1682 1683 1684
    assert !topics(:first).approved?
    topics(:first).toggle!(:approved)
    assert topics(:first).approved?
1685 1686 1687 1688 1689
    topic = topics(:first)
    topic.toggle(:approved)
    assert !topic.approved?
    topic.reload
    assert topic.approved?
1690
  end
1691 1692 1693 1694 1695 1696 1697 1698 1699

  def test_reload
    t1 = Topic.find(1)
    t2 = Topic.find(1)
    t1.title = "something else"
    t1.save
    t2.reload
    assert_equal t1.title, t2.title
  end
1700 1701 1702

  def test_define_attr_method_with_value
    k = Class.new( ActiveRecord::Base )
1703
    k.send(:define_attr_method, :table_name, "foo")
1704 1705 1706 1707 1708
    assert_equal "foo", k.table_name
  end

  def test_define_attr_method_with_block
    k = Class.new( ActiveRecord::Base )
1709
    k.send(:define_attr_method, :primary_key) { "sys_" + original_primary_key }
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
    assert_equal "sys_id", k.primary_key
  end

  def test_set_table_name_with_value
    k = Class.new( ActiveRecord::Base )
    k.table_name = "foo"
    assert_equal "foo", k.table_name
    k.set_table_name "bar"
    assert_equal "bar", k.table_name
  end

  def test_set_table_name_with_block
    k = Class.new( ActiveRecord::Base )
    k.set_table_name { "ks" }
    assert_equal "ks", k.table_name
  end

  def test_set_primary_key_with_value
    k = Class.new( ActiveRecord::Base )
    k.primary_key = "foo"
    assert_equal "foo", k.primary_key
    k.set_primary_key "bar"
    assert_equal "bar", k.primary_key
  end

  def test_set_primary_key_with_block
    k = Class.new( ActiveRecord::Base )
    k.set_primary_key { "sys_" + original_primary_key }
    assert_equal "sys_id", k.primary_key
  end

  def test_set_inheritance_column_with_value
    k = Class.new( ActiveRecord::Base )
    k.inheritance_column = "foo"
    assert_equal "foo", k.inheritance_column
    k.set_inheritance_column "bar"
    assert_equal "bar", k.inheritance_column
  end

  def test_set_inheritance_column_with_block
    k = Class.new( ActiveRecord::Base )
    k.set_inheritance_column { original_inheritance_column + "_id" }
    assert_equal "type_id", k.inheritance_column
  end
1754 1755

  def test_count_with_join
1756
    res = Post.count_by_sql "SELECT COUNT(*) FROM posts LEFT JOIN comments ON posts.id=comments.post_id WHERE posts.#{QUOTED_TYPE} = 'Post'"
J
Jeremy Kemper 已提交
1757

1758
    res2 = Post.count(:conditions => "posts.#{QUOTED_TYPE} = 'Post'", :joins => "LEFT JOIN comments ON posts.id=comments.post_id")
1759
    assert_equal res, res2
J
Jeremy Kemper 已提交
1760

1761
    res3 = nil
1762 1763 1764 1765 1766
    assert_nothing_raised do
      res3 = Post.count(:conditions => "posts.#{QUOTED_TYPE} = 'Post'",
                        :joins => "LEFT JOIN comments ON posts.id=comments.post_id")
    end
    assert_equal res, res3
J
Jeremy Kemper 已提交
1767

1768
    res4 = Post.count_by_sql "SELECT COUNT(p.id) FROM posts p, comments co WHERE p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id"
1769 1770
    res5 = nil
    assert_nothing_raised do
1771 1772
      res5 = Post.count(:conditions => "p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id",
                        :joins => "p, comments co",
1773 1774 1775
                        :select => "p.id")
    end

J
Jeremy Kemper 已提交
1776
    assert_equal res4, res5
1777

P
Pratik Naik 已提交
1778 1779 1780 1781 1782 1783 1784
    res6 = Post.count_by_sql "SELECT COUNT(DISTINCT p.id) FROM posts p, comments co WHERE p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id"
    res7 = nil
    assert_nothing_raised do
      res7 = Post.count(:conditions => "p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id",
                        :joins => "p, comments co",
                        :select => "p.id",
                        :distinct => true)
1785
    end
P
Pratik Naik 已提交
1786
    assert_equal res6, res7
1787
  end
J
Jeremy Kemper 已提交
1788 1789

  def test_clear_association_cache_stored
1790 1791 1792 1793 1794 1795
    firm = Firm.find(1)
    assert_kind_of Firm, firm

    firm.clear_association_cache
    assert_equal Firm.find(1).clients.collect{ |x| x.name }.sort, firm.clients.collect{ |x| x.name }.sort
  end
J
Jeremy Kemper 已提交
1796

1797 1798 1799 1800 1801 1802
  def test_clear_association_cache_new_record
     firm            = Firm.new
     client_stored   = Client.find(3)
     client_new      = Client.new
     client_new.name = "The Joneses"
     clients         = [ client_stored, client_new ]
1803

1804
     firm.clients    << clients
1805
     assert_equal clients.map(&:name).to_set, firm.clients.map(&:name).to_set
1806 1807

     firm.clear_association_cache
1808
     assert_equal clients.map(&:name).to_set, firm.clients.map(&:name).to_set
1809
  end
1810

1811 1812 1813 1814 1815 1816
  def test_interpolate_sql
    assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo@bar') }
    assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo bar) baz') }
    assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo bar} baz') }
  end

1817
  def test_scoped_find_conditions
M
Marcel Molina 已提交
1818
    scoped_developers = Developer.with_scope(:find => { :conditions => 'salary > 90000' }) do
1819 1820
      Developer.find(:all, :conditions => 'id < 5')
    end
M
Marcel Molina 已提交
1821 1822
    assert !scoped_developers.include?(developers(:david)) # David's salary is less than 90,000
    assert_equal 3, scoped_developers.size
1823
  end
J
Jeremy Kemper 已提交
1824

1825
  def test_scoped_find_limit_offset
M
Marcel Molina 已提交
1826
    scoped_developers = Developer.with_scope(:find => { :limit => 3, :offset => 2 }) do
1827
      Developer.find(:all, :order => 'id')
J
Jeremy Kemper 已提交
1828
    end
M
Marcel Molina 已提交
1829 1830 1831
    assert !scoped_developers.include?(developers(:david))
    assert !scoped_developers.include?(developers(:jamis))
    assert_equal 3, scoped_developers.size
J
Jeremy Kemper 已提交
1832

1833
    # Test without scoped find conditions to ensure we get the whole thing
1834
    developers = Developer.find(:all, :order => 'id')
M
Marcel Molina 已提交
1835
    assert_equal Developer.count, developers.size
1836
  end
1837

J
Jeremy Kemper 已提交
1838 1839
  def test_scoped_find_order
    # Test order in scope
1840 1841
    scoped_developers = Developer.with_scope(:find => { :limit => 1, :order => 'salary DESC' }) do
      Developer.find(:all)
J
Jeremy Kemper 已提交
1842
    end
1843 1844 1845 1846 1847
    assert_equal 'Jamis', scoped_developers.first.name
    assert scoped_developers.include?(developers(:jamis))
    # Test scope without order and order in find
    scoped_developers = Developer.with_scope(:find => { :limit => 1 }) do
      Developer.find(:all, :order => 'salary DESC')
J
Jeremy Kemper 已提交
1848
    end
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
    # Test scope order + find order, find has priority
    scoped_developers = Developer.with_scope(:find => { :limit => 3, :order => 'id DESC' }) do
      Developer.find(:all, :order => 'salary ASC')
    end
    assert scoped_developers.include?(developers(:poor_jamis))
    assert scoped_developers.include?(developers(:david))
    assert scoped_developers.include?(developers(:dev_10))
    # Test without scoped find conditions to ensure we get the right thing
    developers = Developer.find(:all, :order => 'id', :limit => 1)
    assert scoped_developers.include?(developers(:david))
  end

1861 1862 1863 1864 1865 1866 1867 1868
  def test_scoped_find_limit_offset_including_has_many_association
    topics = Topic.with_scope(:find => {:limit => 1, :offset => 1, :include => :replies}) do
      Topic.find(:all, :order => "topics.id")
    end
    assert_equal 1, topics.size
    assert_equal 2, topics.first.id
  end

1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
  def test_scoped_find_order_including_has_many_association
    developers = Developer.with_scope(:find => { :order => 'developers.salary DESC', :include => :projects }) do
      Developer.find(:all)
    end
    assert developers.size >= 2
    for i in 1...developers.size
      assert developers[i-1].salary >= developers[i].salary
    end
  end

1879
  def test_scoped_find_with_group_and_having
1880
    developers = Developer.with_scope(:find => { :group => 'developers.salary', :having => "SUM(salary) > 10000", :select => "SUM(salary) as salary" }) do
1881 1882 1883 1884 1885
      Developer.find(:all)
    end
    assert_equal 3, developers.size
  end

1886 1887 1888 1889
  def test_find_last
    last  = Developer.find :last
    assert_equal last, Developer.find(:first, :order => 'id desc')
  end
1890

1891 1892 1893
  def test_last
    assert_equal Developer.find(:first, :order => 'id desc'), Developer.last
  end
1894 1895

  def test_all_with_conditions
1896
    assert_equal Developer.find(:all, :order => 'id desc'), Developer.all.order('id desc').to_a
1897
  end
1898

1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
  def test_find_ordered_last
    last  = Developer.find :last, :order => 'developers.salary ASC'
    assert_equal last, Developer.find(:all, :order => 'developers.salary ASC').last
  end

  def test_find_reverse_ordered_last
    last  = Developer.find :last, :order => 'developers.salary DESC'
    assert_equal last, Developer.find(:all, :order => 'developers.salary DESC').last
  end

  def test_find_multiple_ordered_last
    last  = Developer.find :last, :order => 'developers.name, developers.salary DESC'
    assert_equal last, Developer.find(:all, :order => 'developers.name, developers.salary DESC').last
  end
1913

1914 1915 1916 1917 1918
  def test_find_symbol_ordered_last
    last  = Developer.find :last, :order => :salary
    assert_equal last, Developer.find(:all, :order => :salary).last
  end

1919 1920 1921 1922 1923 1924
  def test_find_scoped_ordered_last
    last_developer = Developer.with_scope(:find => { :order => 'developers.salary ASC' }) do
      Developer.find(:last)
    end
    assert_equal last_developer, Developer.find(:all, :order => 'developers.salary ASC').last
  end
1925

1926
  def test_abstract_class
1927
    assert !ActiveRecord::Base.abstract_class?
1928 1929
    assert LoosePerson.abstract_class?
    assert !LooseDescendant.abstract_class?
1930 1931 1932
  end

  def test_base_class
1933 1934 1935 1936
    assert_equal LoosePerson,     LoosePerson.base_class
    assert_equal LooseDescendant, LooseDescendant.base_class
    assert_equal TightPerson,     TightPerson.base_class
    assert_equal TightPerson,     TightDescendant.base_class
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969

    assert_equal Post, Post.base_class
    assert_equal Post, SpecialPost.base_class
    assert_equal Post, StiPost.base_class
    assert_equal SubStiPost, SubStiPost.base_class
  end

  def test_descends_from_active_record
    # Tries to call Object.abstract_class?
    assert_raise(NoMethodError) do
      ActiveRecord::Base.descends_from_active_record?
    end

    # Abstract subclass of AR::Base.
    assert LoosePerson.descends_from_active_record?

    # Concrete subclass of an abstract class.
    assert LooseDescendant.descends_from_active_record?

    # Concrete subclass of AR::Base.
    assert TightPerson.descends_from_active_record?

    # Concrete subclass of a concrete class but has no type column.
    assert TightDescendant.descends_from_active_record?

    # Concrete subclass of AR::Base.
    assert Post.descends_from_active_record?

    # Abstract subclass of a concrete class which has a type column.
    # This is pathological, as you'll never have Sub < Abstract < Concrete.
    assert !StiPost.descends_from_active_record?

    # Concrete subclasses an abstract class which has a type column.
1970
    assert !SubStiPost.descends_from_active_record?
1971 1972 1973 1974 1975 1976
  end

  def test_find_on_abstract_base_class_doesnt_use_type_condition
    old_class = LooseDescendant
    Object.send :remove_const, :LooseDescendant

1977
    descendant = old_class.create! :first_name => 'bob'
1978 1979 1980 1981 1982
    assert_not_nil LoosePerson.find(descendant.id), "Should have found instance of LooseDescendant when finding abstract LoosePerson: #{descendant.inspect}"
  ensure
    unless Object.const_defined?(:LooseDescendant)
      Object.const_set :LooseDescendant, old_class
    end
1983 1984
  end

1985 1986 1987 1988 1989 1990 1991
  def test_assert_queries
    query = lambda { ActiveRecord::Base.connection.execute 'select count(*) from developers' }
    assert_queries(2) { 2.times { query.call } }
    assert_queries 1, &query
    assert_no_queries { assert true }
  end

1992
  def test_to_xml
1993
    xml = REXML::Document.new(topics(:first).to_xml(:indent => 0))
1994 1995
    bonus_time_in_current_timezone = topics(:first).bonus_time.xmlschema
    written_on_in_current_timezone = topics(:first).written_on.xmlschema
1996
    last_read_in_current_timezone = topics(:first).last_read.xmlschema
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019

    assert_equal "topic", xml.root.name
    assert_equal "The First Topic" , xml.elements["//title"].text
    assert_equal "David" , xml.elements["//author-name"].text

    assert_equal "1", xml.elements["//id"].text
    assert_equal "integer" , xml.elements["//id"].attributes['type']

    assert_equal "1", xml.elements["//replies-count"].text
    assert_equal "integer" , xml.elements["//replies-count"].attributes['type']

    assert_equal written_on_in_current_timezone, xml.elements["//written-on"].text
    assert_equal "datetime" , xml.elements["//written-on"].attributes['type']

    assert_equal "--- Have a nice day\n" , xml.elements["//content"].text
    assert_equal "yaml" , xml.elements["//content"].attributes['type']

    assert_equal "david@loudthinking.com", xml.elements["//author-email-address"].text

    assert_equal nil, xml.elements["//parent-id"].text
    assert_equal "integer", xml.elements["//parent-id"].attributes['type']
    assert_equal "true", xml.elements["//parent-id"].attributes['nil']

2020
    if current_adapter?(:SybaseAdapter, :OracleAdapter)
2021 2022
      assert_equal last_read_in_current_timezone, xml.elements["//last-read"].text
      assert_equal "datetime" , xml.elements["//last-read"].attributes['type']
2023
    else
2024 2025
      assert_equal "2004-04-15", xml.elements["//last-read"].text
      assert_equal "date" , xml.elements["//last-read"].attributes['type']
2026
    end
2027

2028
    # Oracle and DB2 don't have true boolean or time-only fields
2029
    unless current_adapter?(:OracleAdapter, :DB2Adapter)
2030 2031 2032 2033 2034
      assert_equal "false", xml.elements["//approved"].text
      assert_equal "boolean" , xml.elements["//approved"].attributes['type']

      assert_equal bonus_time_in_current_timezone, xml.elements["//bonus-time"].text
      assert_equal "datetime" , xml.elements["//bonus-time"].attributes['type']
2035
    end
2036
  end
2037

2038
  def test_to_xml_skipping_attributes
2039
    xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :except => [:title, :replies_count])
2040
    assert_equal "<topic>", xml.first(7)
2041
    assert !xml.include?(%(<title>The First Topic</title>))
J
Jeremy Kemper 已提交
2042
    assert xml.include?(%(<author-name>David</author-name>))
2043

2044
    xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :except => [:title, :author_name, :replies_count])
2045
    assert !xml.include?(%(<title>The First Topic</title>))
J
Jeremy Kemper 已提交
2046
    assert !xml.include?(%(<author-name>David</author-name>))
2047
  end
2048

2049
  def test_to_xml_including_has_many_association
2050
    xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :include => :replies, :except => :replies_count)
2051
    assert_equal "<topic>", xml.first(7)
2052
    assert xml.include?(%(<replies type="array"><reply>))
2053
    assert xml.include?(%(<title>The Second Topic of the day</title>))
2054
  end
2055 2056 2057

  def test_array_to_xml_including_has_many_association
    xml = [ topics(:first), topics(:second) ].to_xml(:indent => 0, :skip_instruct => true, :include => :replies)
2058
    assert xml.include?(%(<replies type="array"><reply>))
2059
  end
2060 2061 2062

  def test_array_to_xml_including_methods
    xml = [ topics(:first), topics(:second) ].to_xml(:indent => 0, :skip_instruct => true, :methods => [ :topic_id ])
2063 2064
    assert xml.include?(%(<topic-id type="integer">#{topics(:first).topic_id}</topic-id>)), xml
    assert xml.include?(%(<topic-id type="integer">#{topics(:second).topic_id}</topic-id>)), xml
2065
  end
J
Jeremy Kemper 已提交
2066

2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
  def test_array_to_xml_including_has_one_association
    xml = [ companies(:first_firm), companies(:rails_core) ].to_xml(:indent => 0, :skip_instruct => true, :include => :account)
    assert xml.include?(companies(:first_firm).account.to_xml(:indent => 0, :skip_instruct => true))
    assert xml.include?(companies(:rails_core).account.to_xml(:indent => 0, :skip_instruct => true))
  end

  def test_array_to_xml_including_belongs_to_association
    xml = [ companies(:first_client), companies(:second_client), companies(:another_client) ].to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
    assert xml.include?(companies(:first_client).to_xml(:indent => 0, :skip_instruct => true))
    assert xml.include?(companies(:second_client).firm.to_xml(:indent => 0, :skip_instruct => true))
    assert xml.include?(companies(:another_client).firm.to_xml(:indent => 0, :skip_instruct => true))
  end
2079 2080 2081 2082 2083 2084 2085 2086

  def test_to_xml_including_belongs_to_association
    xml = companies(:first_client).to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
    assert !xml.include?("<firm>")

    xml = companies(:second_client).to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
    assert xml.include?("<firm>")
  end
J
Jeremy Kemper 已提交
2087

2088 2089 2090 2091
  def test_to_xml_including_multiple_associations
    xml = companies(:first_firm).to_xml(:indent => 0, :skip_instruct => true, :include => [ :clients, :account ])
    assert_equal "<firm>", xml.first(6)
    assert xml.include?(%(<account>))
2092
    assert xml.include?(%(<clients type="array"><client>))
2093
  end
2094 2095 2096

  def test_to_xml_including_multiple_associations_with_options
    xml = companies(:first_firm).to_xml(
J
Jeremy Kemper 已提交
2097
      :indent  => 0, :skip_instruct => true,
2098 2099
      :include => { :clients => { :only => :name } }
    )
J
Jeremy Kemper 已提交
2100

2101
    assert_equal "<firm>", xml.first(6)
2102
    assert xml.include?(%(<client><name>Summit</name></client>))
2103
    assert xml.include?(%(<clients type="array"><client>))
2104
  end
J
Jeremy Kemper 已提交
2105

2106 2107 2108 2109 2110
  def test_to_xml_including_methods
    xml = Company.new.to_xml(:methods => :arbitrary_method, :skip_instruct => true)
    assert_equal "<company>", xml.first(9)
    assert xml.include?(%(<arbitrary-method>I am Jack's profound disappointment</arbitrary-method>))
  end
J
Jeremy Kemper 已提交
2111

2112 2113 2114 2115 2116 2117 2118 2119
  def test_to_xml_with_block
    value = "Rockin' the block"
    xml = Company.new.to_xml(:skip_instruct => true) do |xml|
      xml.tag! "arbitrary-element", value
    end
    assert_equal "<company>", xml.first(9)
    assert xml.include?(%(<arbitrary-element>#{value}</arbitrary-element>))
  end
J
Jeremy Kemper 已提交
2120

2121 2122 2123 2124
  def test_type_name_with_module_should_handle_beginning
    assert_equal 'ActiveRecord::Person', ActiveRecord::Base.send(:type_name_with_module, 'Person')
    assert_equal '::Person', ActiveRecord::Base.send(:type_name_with_module, '::Person')
  end
J
Jeremy Kemper 已提交
2125

2126 2127 2128
  def test_to_param_should_return_string
    assert_kind_of String, Client.find(:first).to_param
  end
J
Jeremy Kemper 已提交
2129

2130 2131 2132 2133 2134 2135 2136
  def test_inspect_class
    assert_equal 'ActiveRecord::Base', ActiveRecord::Base.inspect
    assert_equal 'LoosePerson(abstract)', LoosePerson.inspect
    assert_match(/^Topic\(id: integer, title: string/, Topic.inspect)
  end

  def test_inspect_instance
2137
    topic = topics(:first)
2138
    assert_equal %(#<Topic id: 1, title: "The First Topic", author_name: "David", author_email_address: "david@loudthinking.com", written_on: "#{topic.written_on.to_s(:db)}", bonus_time: "#{topic.bonus_time.to_s(:db)}", last_read: "#{topic.last_read.to_s(:db)}", content: "Have a nice day", approved: false, replies_count: 1, parent_id: nil, parent_title: nil, type: nil>), topic.inspect
2139
  end
2140

2141
  def test_inspect_new_instance
2142 2143 2144
    assert_match /Topic id: nil/, Topic.new.inspect
  end

2145 2146 2147 2148
  def test_inspect_limited_select_instance
    assert_equal %(#<Topic id: 1>), Topic.find(:first, :select => 'id', :conditions => 'id = 1').inspect
    assert_equal %(#<Topic id: 1, title: "The First Topic">), Topic.find(:first, :select => 'id, title', :conditions => 'id = 1').inspect
  end
J
Jeremy Kemper 已提交
2149

2150 2151 2152
  def test_inspect_class_without_table
    assert_equal "NonExistentTable(Table doesn't exist)", NonExistentTable.inspect
  end
2153

2154 2155
  def test_attribute_for_inspect
    t = topics(:first)
2156
    t.title = "The First Topic Now Has A Title With\nNewlines And More Than 50 Characters"
2157 2158

    assert_equal %("#{t.written_on.to_s(:db)}"), t.attribute_for_inspect(:written_on)
2159
    assert_equal '"The First Topic Now Has A Title With\nNewlines And M..."', t.attribute_for_inspect(:title)
2160
  end
J
Jeremy Kemper 已提交
2161

2162 2163 2164 2165
  def test_becomes
    assert_kind_of Reply, topics(:first).becomes(Reply)
    assert_equal "The First Topic", topics(:first).becomes(Reply).title
  end
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197

  def test_silence_sets_log_level_to_error_in_block
    original_logger = ActiveRecord::Base.logger
    log = StringIO.new
    ActiveRecord::Base.logger = Logger.new(log)
    ActiveRecord::Base.logger.level = Logger::DEBUG
    ActiveRecord::Base.silence do
      ActiveRecord::Base.logger.warn "warn"
      ActiveRecord::Base.logger.error "error"
    end
    assert_equal "error\n", log.string
  ensure
    ActiveRecord::Base.logger = original_logger
  end

  def test_silence_sets_log_level_back_to_level_before_yield
    original_logger = ActiveRecord::Base.logger
    log = StringIO.new
    ActiveRecord::Base.logger = Logger.new(log)
    ActiveRecord::Base.logger.level = Logger::WARN
    ActiveRecord::Base.silence do
    end
    assert_equal Logger::WARN, ActiveRecord::Base.logger.level
  ensure
    ActiveRecord::Base.logger = original_logger
  end

  def test_benchmark_with_log_level
    original_logger = ActiveRecord::Base.logger
    log = StringIO.new
    ActiveRecord::Base.logger = Logger.new(log)
    ActiveRecord::Base.logger.level = Logger::WARN
J
José Valim 已提交
2198 2199 2200
    ActiveRecord::Base.benchmark("Debug Topic Count", :level => :debug) { Topic.count }
    ActiveRecord::Base.benchmark("Warn Topic Count",  :level => :warn)  { Topic.count }
    ActiveRecord::Base.benchmark("Error Topic Count", :level => :error) { Topic.count }
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
    assert_no_match /Debug Topic Count/, log.string
    assert_match /Warn Topic Count/, log.string
    assert_match /Error Topic Count/, log.string
  ensure
    ActiveRecord::Base.logger = original_logger
  end

  def test_benchmark_with_use_silence
    original_logger = ActiveRecord::Base.logger
    log = StringIO.new
    ActiveRecord::Base.logger = Logger.new(log)
J
José Valim 已提交
2212 2213
    ActiveRecord::Base.benchmark("Logging", :level => :debug, :silence => true) { ActiveRecord::Base.logger.debug "Loud" }
    ActiveRecord::Base.benchmark("Logging", :level => :debug, :silence => false)  { ActiveRecord::Base.logger.debug "Quiet" }
2214 2215 2216 2217 2218
    assert_no_match /Loud/, log.string
    assert_match /Quiet/, log.string
  ensure
    ActiveRecord::Base.logger = original_logger
  end
2219

2220 2221 2222 2223 2224 2225 2226 2227
  def test_create_with_custom_timestamps
    custom_datetime = 1.hour.ago.beginning_of_day

    %w(created_at created_on updated_at updated_on).each do |attribute|
      parrot = LiveParrot.create(:name => "colombian", attribute => custom_datetime)
      assert_equal custom_datetime, parrot[attribute]
    end
  end
2228 2229 2230 2231

  def test_dup
    assert !Minimalistic.new.freeze.dup.frozen?
  end
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246

  protected
    def with_env_tz(new_tz = 'US/Eastern')
      old_tz, ENV['TZ'] = ENV['TZ'], new_tz
      yield
    ensure
      old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
    end

    def with_active_record_default_timezone(zone)
      old_zone, ActiveRecord::Base.default_timezone = ActiveRecord::Base.default_timezone, zone
      yield
    ensure
      ActiveRecord::Base.default_timezone = old_zone
    end
2247
end