base_test.rb 49.0 KB
Newer Older
A
Aaron Patterson 已提交
1 2
# encoding: utf-8

3
require "cases/helper"
4
require 'active_support/concurrency/latch'
5
require 'models/post'
6
require 'models/author'
J
Jeremy Kemper 已提交
7 8
require 'models/topic'
require 'models/reply'
9
require 'models/category'
J
Jeremy Kemper 已提交
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'
16
require 'models/boolean'
J
Jeremy Kemper 已提交
17 18 19
require 'models/column_name'
require 'models/subscriber'
require 'models/keyboard'
20
require 'models/comment'
J
Jeremy Kemper 已提交
21 22
require 'models/minimalistic'
require 'models/warehouse_thing'
23
require 'models/parrot'
24
require 'models/person'
25
require 'models/edge'
26
require 'models/joke'
27
require 'models/bird'
28 29
require 'models/car'
require 'models/bulb'
30
require 'rexml/document'
D
Initial  
David Heinemeier Hansson 已提交
31

32 33 34 35 36 37 38
class FirstAbstractClass < ActiveRecord::Base
  self.abstract_class = true
end
class SecondAbstractClass < FirstAbstractClass
  self.abstract_class = true
end
class Photo < SecondAbstractClass; end
D
Initial  
David Heinemeier Hansson 已提交
39
class Category < ActiveRecord::Base; end
40
class Categorization < ActiveRecord::Base; end
D
Initial  
David Heinemeier Hansson 已提交
41
class Smarts < ActiveRecord::Base; end
42
class CreditCard < ActiveRecord::Base
43 44 45 46 47 48
  class PinNumber < ActiveRecord::Base
    class CvvCode < ActiveRecord::Base; end
    class SubCvvCode < CvvCode; end
  end
  class SubPinNumber < PinNumber; end
  class Brand < Category; end
49
end
D
Initial  
David Heinemeier Hansson 已提交
50
class MasterCreditCard < ActiveRecord::Base; end
51
class Post < ActiveRecord::Base; end
52
class Computer < ActiveRecord::Base; end
53
class NonExistentTable < ActiveRecord::Base; end
54
class TestOracleDefault < ActiveRecord::Base; end
D
Initial  
David Heinemeier Hansson 已提交
55

56 57 58 59
class ReadonlyTitlePost < Post
  attr_readonly :title
end

60 61
class Weird < ActiveRecord::Base; end

62 63 64 65 66
class Boolean < ActiveRecord::Base
  def has_fun
    super
  end
end
D
Initial  
David Heinemeier Hansson 已提交
67

68 69 70 71 72 73 74 75 76 77
class LintTest < ActiveRecord::TestCase
  include ActiveModel::Lint::Tests

  class LintModel < ActiveRecord::Base; end

  def setup
    @model = LintModel.new
  end
end

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

81 82 83 84 85 86 87
  def test_generated_methods_modules
    modules = Computer.ancestors
    assert modules.include?(Computer::GeneratedFeatureMethods)
    assert_equal(Computer::GeneratedFeatureMethods, Computer.generated_feature_methods)
    assert(modules.index(Computer.generated_attribute_methods) > modules.index(Computer.generated_feature_methods),
           "generated_attribute_methods must be higher in inheritance hierarchy than generated_feature_methods")
    assert_not_equal Computer.generated_feature_methods, Post.generated_feature_methods
88
    assert(modules.index(Computer.generated_attribute_methods) < modules.index(ActiveRecord::Base.ancestors[1]))
89 90
  end

91 92 93 94 95 96 97 98 99 100 101 102 103 104
  def test_column_names_are_escaped
    conn      = ActiveRecord::Base.connection
    classname = conn.class.name[/[^:]*$/]
    badchar   = {
      'SQLite3Adapter'    => '"',
      'MysqlAdapter'      => '`',
      'Mysql2Adapter'     => '`',
      'PostgreSQLAdapter' => '"',
      'OracleAdapter'     => '"',
    }.fetch(classname) {
      raise "need a bad char for #{classname}"
    }

    quoted = conn.quote_column_name "foo#{badchar}bar"
105 106 107 108 109 110 111
    if current_adapter?(:OracleAdapter)
      # Oracle does not allow double quotes in table and column names at all
      # therefore quoting removes them
      assert_equal("#{badchar}foobar#{badchar}", quoted)
    else
      assert_equal("#{badchar}foo#{badchar * 2}bar#{badchar}", quoted)
    end
112 113
  end

114 115 116 117 118
  def test_columns_should_obey_set_primary_key
    pk = Subscriber.columns.find { |x| x.name == 'nick' }
    assert pk.primary, 'nick should be primary key'
  end

119 120 121 122
  def test_primary_key_with_no_id
    assert_nil Edge.primary_key
  end

123
  unless current_adapter?(:PostgreSQLAdapter, :OracleAdapter, :SQLServerAdapter)
124
    def test_limit_with_comma
125
      assert Topic.limit("1,2").to_a
126 127 128 129
    end
  end

  def test_limit_without_comma
130 131
    assert_equal 1, Topic.limit("1").to_a.length
    assert_equal 1, Topic.limit(1).to_a.length
132 133 134 135
  end

  def test_invalid_limit
    assert_raises(ArgumentError) do
136
      Topic.limit("asdfadf").to_a
137 138 139
    end
  end

J
Josh Adams 已提交
140
  def test_limit_should_sanitize_sql_injection_for_limit_without_commas
141
    assert_raises(ArgumentError) do
142
      Topic.limit("1 select * from schema").to_a
143 144 145
    end
  end

J
Josh Adams 已提交
146
  def test_limit_should_sanitize_sql_injection_for_limit_with_commas
147
    assert_raises(ArgumentError) do
148
      Topic.limit("1, 7 procedure help()").to_a
149 150
    end
  end
151

152
  unless current_adapter?(:MysqlAdapter, :Mysql2Adapter)
153
    def test_limit_should_allow_sql_literal
154
      assert_equal 1, Topic.limit(Arel.sql('2-1')).to_a.length
155
    end
156
  end
157

158 159
  def test_select_symbol
    topic_ids = Topic.select(:id).map(&:id).sort
S
Sandeep 已提交
160
    assert_equal Topic.pluck(:id).sort, topic_ids
161 162
  end

163 164 165 166
  def test_table_exists
    assert !NonExistentTable.table_exists?
    assert Topic.table_exists?
  end
J
Jeremy Kemper 已提交
167

D
Initial  
David Heinemeier Hansson 已提交
168
  def test_preserving_date_objects
169
    if current_adapter?(:SybaseAdapter)
170 171
      # Sybase ctlib does not (yet?) support the date type; use datetime instead.
      assert_kind_of(
J
Jeremy Kemper 已提交
172
        Time, Topic.find(1).last_read,
173 174 175
        "The last_read attribute should be of the Time class"
      )
    else
176
      # Oracle enhanced adapter allows to define Date attributes in model class (see topic.rb)
177
      assert_kind_of(
J
Jeremy Kemper 已提交
178
        Date, Topic.find(1).last_read,
179 180 181
        "The last_read attribute should be of the Date class"
      )
    end
182
  end
183

184
  def test_previously_changed
185
    topic = Topic.first
186 187 188 189 190 191 192 193 194
    topic.title = '<3<3<3'
    assert_equal({}, topic.previous_changes)

    topic.save!
    expected = ["The First Topic", "<3<3<3"]
    assert_equal(expected, topic.previous_changes['title'])
  end

  def test_previously_changed_dup
195
    topic = Topic.first
196 197 198 199 200 201 202 203 204 205 206 207 208
    topic.title = '<3<3<3'
    topic.save!

    t2 = topic.dup

    assert_equal(topic.previous_changes, t2.previous_changes)

    topic.title = "lolwut"
    topic.save!

    assert_not_equal(topic.previous_changes, t2.previous_changes)
  end

209
  def test_preserving_time_objects
210 211 212 213
    assert_kind_of(
      Time, Topic.find(1).bonus_time,
      "The bonus_time attribute should be of the Time class"
    )
D
Initial  
David Heinemeier Hansson 已提交
214 215 216 217 218

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

    # For adapters which support microsecond resolution.
221
    if current_adapter?(:PostgreSQLAdapter, :SQLite3Adapter)
222 223
      assert_equal 11, Topic.find(1).written_on.sec
      assert_equal 223300, Topic.find(1).written_on.usec
224
      assert_equal 9900, Topic.find(2).written_on.usec
225
      assert_equal 129346, Topic.find(3).written_on.usec
226
    end
D
Initial  
David Heinemeier Hansson 已提交
227
  end
J
Jeremy Kemper 已提交
228

229 230
  def test_preserving_time_objects_with_local_time_conversion_to_default_timezone_utc
    with_env_tz 'America/New_York' do
231
      with_timezone_config default: :utc do
232 233
        time = Time.local(2000)
        topic = Topic.create('written_on' => time)
234
        saved_time = Topic.find(topic.id).reload.written_on
235 236 237 238 239 240 241 242 243
        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
244
      with_timezone_config default: :utc do
245 246 247
        Time.use_zone 'Central Time (US & Canada)' do
          time = Time.zone.local(2000)
          topic = Topic.create('written_on' => time)
248
          saved_time = Topic.find(topic.id).reload.written_on
249 250 251 252 253 254 255 256 257 258
          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
259 260 261 262 263 264 265 266
      with_timezone_config default: :local do
        time = Time.utc(2000)
        topic = Topic.create('written_on' => time)
        saved_time = Topic.find(topic.id).reload.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
267 268 269 270 271
    end
  end

  def test_preserving_time_objects_with_time_with_zone_conversion_to_default_timezone_local
    with_env_tz 'America/New_York' do
272
      with_timezone_config default: :local do
273 274 275
        Time.use_zone 'Central Time (US & Canada)' do
          time = Time.zone.local(2000)
          topic = Topic.create('written_on' => time)
276
          saved_time = Topic.find(topic.id).reload.written_on
277 278 279 280 281 282 283 284
          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

285 286 287 288 289 290
  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 已提交
291

D
Initial  
David Heinemeier Hansson 已提交
292
  def test_initialize_with_attributes
J
Jeremy Kemper 已提交
293
    topic = Topic.new({
D
Initial  
David Heinemeier Hansson 已提交
294 295
      "title" => "initialized from attributes", "written_on" => "2003-12-12 23:23"
    })
J
Jeremy Kemper 已提交
296

D
Initial  
David Heinemeier Hansson 已提交
297 298
    assert_equal("initialized from attributes", topic.title)
  end
J
Jeremy Kemper 已提交
299

300
  def test_initialize_with_invalid_attribute
301 302 303 304 305
    Topic.new({ "title" => "test",
      "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)
306
  end
J
Jeremy Kemper 已提交
307

308
  def test_create_after_initialize_without_block
309 310 311
    cb = CustomBulb.create(:name => 'Dude')
    assert_equal('Dude', cb.name)
    assert_equal(true, cb.frickinawesome)
312
  end
313

314
  def test_create_after_initialize_with_block
315 316 317
    cb = CustomBulb.create {|c| c.name = 'Dude' }
    assert_equal('Dude', cb.name)
    assert_equal(true, cb.frickinawesome)
318 319
  end

320 321 322 323 324 325 326 327
  def test_create_after_initialize_with_array_param
    cbs = CustomBulb.create([{ name: 'Dude' }, { name: 'Bob' }])
    assert_equal 'Dude', cbs[0].name
    assert_equal 'Bob', cbs[1].name
    assert cbs[0].frickinawesome
    assert !cbs[1].frickinawesome
  end

D
Initial  
David Heinemeier Hansson 已提交
328
  def test_load
329
    topics = Topic.all.merge!(:order => 'id').to_a
330
    assert_equal(4, topics.size)
331
    assert_equal(topics(:first).title, topics.first.title)
D
Initial  
David Heinemeier Hansson 已提交
332
  end
J
Jeremy Kemper 已提交
333

D
Initial  
David Heinemeier Hansson 已提交
334
  def test_load_with_condition
335
    topics = Topic.all.merge!(:where => "author_name = 'Mary'").to_a
J
Jeremy Kemper 已提交
336

D
Initial  
David Heinemeier Hansson 已提交
337
    assert_equal(1, topics.size)
338
    assert_equal(topics(:second).title, topics.first.title)
D
Initial  
David Heinemeier Hansson 已提交
339 340
  end

341
  GUESSED_CLASSES = [Category, Smarts, CreditCard, CreditCard::PinNumber, CreditCard::PinNumber::CvvCode, CreditCard::SubPinNumber, CreditCard::Brand, MasterCreditCard]
342

343
  def test_table_name_guesses
D
Initial  
David Heinemeier Hansson 已提交
344
    assert_equal "topics", Topic.table_name
345

D
Initial  
David Heinemeier Hansson 已提交
346 347 348
    assert_equal "categories", Category.table_name
    assert_equal "smarts", Smarts.table_name
    assert_equal "credit_cards", CreditCard.table_name
349
    assert_equal "credit_card_pin_numbers", CreditCard::PinNumber.table_name
350 351 352
    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 已提交
353
    assert_equal "master_credit_cards", MasterCreditCard.table_name
354 355 356
  ensure
    GUESSED_CLASSES.each(&:reset_table_name)
  end
D
Initial  
David Heinemeier Hansson 已提交
357

358
  def test_singular_table_name_guesses
D
Initial  
David Heinemeier Hansson 已提交
359
    ActiveRecord::Base.pluralize_table_names = false
360
    GUESSED_CLASSES.each(&:reset_table_name)
361

D
Initial  
David Heinemeier Hansson 已提交
362 363 364
    assert_equal "category", Category.table_name
    assert_equal "smarts", Smarts.table_name
    assert_equal "credit_card", CreditCard.table_name
365
    assert_equal "credit_card_pin_number", CreditCard::PinNumber.table_name
366 367 368
    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 已提交
369
    assert_equal "master_credit_card", MasterCreditCard.table_name
370
  ensure
D
Initial  
David Heinemeier Hansson 已提交
371
    ActiveRecord::Base.pluralize_table_names = true
372 373
    GUESSED_CLASSES.each(&:reset_table_name)
  end
D
Initial  
David Heinemeier Hansson 已提交
374

375
  def test_table_name_guesses_with_prefixes_and_suffixes
D
Initial  
David Heinemeier Hansson 已提交
376
    ActiveRecord::Base.table_name_prefix = "test_"
377
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
378 379
    assert_equal "test_categories", Category.table_name
    ActiveRecord::Base.table_name_suffix = "_test"
380
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
381 382
    assert_equal "test_categories_test", Category.table_name
    ActiveRecord::Base.table_name_prefix = ""
383
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
384 385
    assert_equal "categories_test", Category.table_name
    ActiveRecord::Base.table_name_suffix = ""
386
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
387
    assert_equal "categories", Category.table_name
388 389 390 391 392
  ensure
    ActiveRecord::Base.table_name_prefix = ""
    ActiveRecord::Base.table_name_suffix = ""
    GUESSED_CLASSES.each(&:reset_table_name)
  end
D
Initial  
David Heinemeier Hansson 已提交
393

394
  def test_singular_table_name_guesses_with_prefixes_and_suffixes
D
Initial  
David Heinemeier Hansson 已提交
395
    ActiveRecord::Base.pluralize_table_names = false
396

D
Initial  
David Heinemeier Hansson 已提交
397
    ActiveRecord::Base.table_name_prefix = "test_"
398
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
399 400
    assert_equal "test_category", Category.table_name
    ActiveRecord::Base.table_name_suffix = "_test"
401
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
402 403
    assert_equal "test_category_test", Category.table_name
    ActiveRecord::Base.table_name_prefix = ""
404
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
405 406
    assert_equal "category_test", Category.table_name
    ActiveRecord::Base.table_name_suffix = ""
407
    Category.reset_table_name
D
Initial  
David Heinemeier Hansson 已提交
408
    assert_equal "category", Category.table_name
409
  ensure
D
Initial  
David Heinemeier Hansson 已提交
410
    ActiveRecord::Base.pluralize_table_names = true
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
    ActiveRecord::Base.table_name_prefix = ""
    ActiveRecord::Base.table_name_suffix = ""
    GUESSED_CLASSES.each(&:reset_table_name)
  end

  def test_table_name_guesses_with_inherited_prefixes_and_suffixes
    GUESSED_CLASSES.each(&:reset_table_name)

    CreditCard.table_name_prefix = "test_"
    CreditCard.reset_table_name
    Category.reset_table_name
    assert_equal "test_credit_cards", CreditCard.table_name
    assert_equal "categories", Category.table_name
    CreditCard.table_name_suffix = "_test"
    CreditCard.reset_table_name
    Category.reset_table_name
    assert_equal "test_credit_cards_test", CreditCard.table_name
    assert_equal "categories", Category.table_name
    CreditCard.table_name_prefix = ""
    CreditCard.reset_table_name
    Category.reset_table_name
    assert_equal "credit_cards_test", CreditCard.table_name
    assert_equal "categories", Category.table_name
    CreditCard.table_name_suffix = ""
    CreditCard.reset_table_name
    Category.reset_table_name
    assert_equal "credit_cards", CreditCard.table_name
    assert_equal "categories", Category.table_name
  ensure
    CreditCard.table_name_prefix = ""
    CreditCard.table_name_suffix = ""
    GUESSED_CLASSES.each(&:reset_table_name)
D
Initial  
David Heinemeier Hansson 已提交
443
  end
J
Jeremy Kemper 已提交
444

445
  def test_singular_table_name_guesses_for_individual_table
446 447 448
    Post.pluralize_table_names = false
    Post.reset_table_name
    assert_equal "post", Post.table_name
449 450
    assert_equal "categories", Category.table_name
  ensure
451 452
    Post.pluralize_table_names = true
    Post.reset_table_name
453
  end
J
Jeremy Kemper 已提交
454

455
  if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
456
    def test_update_all_with_order_and_limit
A
Andrey Deryabin 已提交
457
      assert_equal 1, Topic.limit(1).order('id DESC').update_all(:content => 'bulk updated!')
458 459 460
    end
  end

D
Initial  
David Heinemeier Hansson 已提交
461 462 463 464
  def test_null_fields
    assert_nil Topic.find(1).parent_id
    assert_nil Topic.create("title" => "Hey you").parent_id
  end
J
Jeremy Kemper 已提交
465

D
Initial  
David Heinemeier Hansson 已提交
466 467
  def test_default_values
    topic = Topic.new
J
Jeremy Kemper 已提交
468
    assert topic.approved?
D
Initial  
David Heinemeier Hansson 已提交
469
    assert_nil topic.written_on
470
    assert_nil topic.bonus_time
D
Initial  
David Heinemeier Hansson 已提交
471
    assert_nil topic.last_read
J
Jeremy Kemper 已提交
472

D
Initial  
David Heinemeier Hansson 已提交
473 474 475
    topic.save

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

J
Jeremy Kemper 已提交
479
    # Oracle has some funky default handling, so it requires a bit of
480
    # extra testing. See ticket #2788.
481 482
    if current_adapter?(:OracleAdapter)
      test = TestOracleDefault.new
483 484 485 486
      assert_equal "X", test.test_char
      assert_equal "hello", test.test_string
      assert_equal 3, test.test_int
    end
D
Initial  
David Heinemeier Hansson 已提交
487
  end
488

489
  # Oracle, and Sybase do not have a TIME datatype.
490
  unless current_adapter?(:OracleAdapter, :SybaseAdapter)
491
    def test_utc_as_time_zone
492 493 494 495 496 497
      with_timezone_config default: :utc do
        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
      end
498
    end
499

500
    def test_utc_as_time_zone_and_new
501 502 503 504 505 506 507 508 509 510
      with_timezone_config default: :utc do
        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
      end
511
    end
512 513
  end

D
Initial  
David Heinemeier Hansson 已提交
514 515 516 517 518 519 520 521 522
  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
523 524 525 526 527 528 529

    # 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 已提交
530
  end
531

D
Initial  
David Heinemeier Hansson 已提交
532
  def test_equality
533
    assert_equal Topic.find(1), Topic.find(2).topic
D
Initial  
David Heinemeier Hansson 已提交
534
  end
J
Jeremy Kemper 已提交
535

536 537 538 539
  def test_find_by_slug
    assert_equal Topic.find('1-meowmeow'), Topic.find(1)
  end

540 541 542
  def test_equality_of_new_records
    assert_not_equal Topic.new, Topic.new
  end
J
Jeremy Kemper 已提交
543

544 545 546 547 548 549 550 551 552
  def test_equality_of_destroyed_records
    topic_1 = Topic.new(:title => 'test_1')
    topic_1.save
    topic_2 = Topic.find(topic_1.id)
    topic_1.destroy
    assert_equal topic_1, topic_2
    assert_equal topic_2, topic_1
  end

D
Initial  
David Heinemeier Hansson 已提交
553
  def test_hashing
554
    assert_equal [ Topic.find(1) ], [ Topic.find(2).topic ] & [ Topic.find(1) ]
D
Initial  
David Heinemeier Hansson 已提交
555
  end
556

557 558 559 560 561 562 563
  def test_comparison
    topic_1 = Topic.create!
    topic_2 = Topic.create!

    assert_equal [topic_2, topic_1].sort, [topic_1, topic_2]
  end

564 565 566 567 568 569 570 571
  def test_create_without_prepared_statement
    topic = Topic.connection.unprepared_statement do
      Topic.create(:title => 'foo')
    end

    assert_equal topic, Topic.find(topic.id)
  end

M
Marc Lennox 已提交
572 573 574 575 576 577 578 579 580
  def test_destroy_without_prepared_statement
    topic = Topic.create(title: 'foo')
    Topic.connection.unprepared_statement do
      Topic.find(topic.id).destroy
    end

    assert_equal nil, Topic.find_by_id(topic.id)
  end

581 582 583 584 585 586
  def test_blank_ids
    one = Subscriber.new(:id => '')
    two = Subscriber.new(:id => '')
    assert_equal one, two
  end

587 588 589 590 591 592
  def test_comparison_with_different_objects
    topic = Topic.create
    category = Category.create(:name => "comparison")
    assert_nil topic <=> category
  end

593 594 595 596 597 598 599
  def test_comparison_with_different_objects_in_array
    topic = Topic.create
    assert_raises(ArgumentError) do
      [1, topic].sort
    end
  end

600
  def test_readonly_attributes
601
    assert_equal Set.new([ 'title' , 'comments_count' ]), ReadonlyTitlePost.readonly_attributes
J
Jeremy Kemper 已提交
602

603 604 605
    post = ReadonlyTitlePost.create(:title => "cannot change this", :body => "changeable")
    post.reload
    assert_equal "cannot change this", post.title
J
Jeremy Kemper 已提交
606

607
    post.update(title: "try to change", body: "changed")
608 609 610 611
    post.reload
    assert_equal "cannot change this", post.title
    assert_equal "changed", post.body
  end
D
Initial  
David Heinemeier Hansson 已提交
612

613
  def test_unicode_column_name
614
    Weird.reset_column_information
615 616
    weird = Weird.create(:なまえ => 'たこ焼き仮面')
    assert_equal 'たこ焼き仮面', weird.なまえ
A
Aaron Patterson 已提交
617 618
  end

619 620 621 622 623 624 625 626 627 628 629 630 631 632
  def test_respect_internal_encoding
    if current_adapter?(:PostgreSQLAdapter)
      skip 'pg does not respect internal encoding and always returns utf8'
    end
    old_default_internal = Encoding.default_internal
    silence_warnings { Encoding.default_internal = "EUC-JP" }

    Weird.reset_column_information

    assert_equal ["EUC-JP"], Weird.columns.map {|c| c.name.encoding.name }.uniq
  ensure
    silence_warnings { Encoding.default_internal = old_default_internal }
  end

633 634 635 636
  def test_non_valid_identifier_column_name
    weird = Weird.create('a$b' => 'value')
    weird.reload
    assert_equal 'value', weird.send('a$b')
637
    assert_equal 'value', weird.read_attribute('a$b')
638

639
    weird.update_columns('a$b' => 'value2')
640 641
    weird.reload
    assert_equal 'value2', weird.send('a$b')
642
    assert_equal 'value2', weird.read_attribute('a$b')
643 644
  end

645 646 647 648 649 650
  def test_group_weirds_by_from
    Weird.create('a$b' => 'value', :from => 'aaron')
    count = Weird.group(Weird.arel_table[:from]).count
    assert_equal 1, count['aaron']
  end

651
  def test_attributes_on_dummy_time
652
    # Oracle, and Sybase do not have a TIME datatype.
653
    return true if current_adapter?(:OracleAdapter, :SybaseAdapter)
654

655 656 657 658 659 660 661 662
    with_timezone_config default: :local do
      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
663 664
  end

665 666 667 668 669 670 671 672 673 674 675 676
  def test_attributes_on_dummy_time_with_invalid_time
    # Oracle, and Sybase do not have a TIME datatype.
    return true if current_adapter?(:OracleAdapter, :SybaseAdapter)

    attributes = {
      "bonus_time" => "not a time"
    }
    topic = Topic.find(1)
    topic.attributes = attributes
    assert_nil topic.bonus_time
  end

D
Initial  
David Heinemeier Hansson 已提交
677
  def test_boolean
678
    b_nil = Boolean.create({ "value" => nil })
679
    nil_id = b_nil.id
680
    b_false = Boolean.create({ "value" => false })
D
Initial  
David Heinemeier Hansson 已提交
681
    false_id = b_false.id
682
    b_true = Boolean.create({ "value" => true })
D
Initial  
David Heinemeier Hansson 已提交
683 684
    true_id = b_true.id

685
    b_nil = Boolean.find(nil_id)
686
    assert_nil b_nil.value
687
    b_false = Boolean.find(false_id)
D
Initial  
David Heinemeier Hansson 已提交
688
    assert !b_false.value?
689
    b_true = Boolean.find(true_id)
D
Initial  
David Heinemeier Hansson 已提交
690 691
    assert b_true.value?
  end
692

693 694 695 696 697 698 699 700 701 702
  def test_boolean_without_questionmark
    b_true = Boolean.create({ "value" => true })
    true_id = b_true.id

    subclass   = Class.new(Boolean).find true_id
    superclass = Boolean.find true_id

    assert_equal superclass.read_attribute(:has_fun), subclass.read_attribute(:has_fun)
  end

703
  def test_boolean_cast_from_string
704
    b_blank = Boolean.create({ "value" => "" })
705
    blank_id = b_blank.id
706
    b_false = Boolean.create({ "value" => "0" })
707
    false_id = b_false.id
708
    b_true = Boolean.create({ "value" => "1" })
709 710
    true_id = b_true.id

711
    b_blank = Boolean.find(blank_id)
712
    assert_nil b_blank.value
713
    b_false = Boolean.find(false_id)
714
    assert !b_false.value?
715
    b_true = Boolean.find(true_id)
J
Jeremy Kemper 已提交
716
    assert b_true.value?
717
  end
J
Jeremy Kemper 已提交
718

719
  def test_new_record_returns_boolean
720 721
    assert_equal false, Topic.new.persisted?
    assert_equal true, Topic.find(1).persisted?
722 723
  end

A
Aaron Patterson 已提交
724
  def test_dup
D
Initial  
David Heinemeier Hansson 已提交
725
    topic = Topic.find(1)
A
Aaron Patterson 已提交
726 727 728 729
    duped_topic = nil
    assert_nothing_raised { duped_topic = topic.dup }
    assert_equal topic.title, duped_topic.title
    assert !duped_topic.persisted?
D
Initial  
David Heinemeier Hansson 已提交
730

A
Aaron Patterson 已提交
731
    # test if the attributes have been duped
J
Jeremy Kemper 已提交
732
    topic.title = "a"
A
Aaron Patterson 已提交
733
    duped_topic.title = "b"
D
Initial  
David Heinemeier Hansson 已提交
734
    assert_equal "a", topic.title
A
Aaron Patterson 已提交
735
    assert_equal "b", duped_topic.title
D
Initial  
David Heinemeier Hansson 已提交
736

A
Aaron Patterson 已提交
737 738
    # test if the attribute values have been duped
    duped_topic = topic.dup
739 740
    duped_topic.title.replace "c"
    assert_equal "a", topic.title
741

A
Aaron Patterson 已提交
742 743
    # test if attributes set as part of after_initialize are duped correctly
    assert_equal topic.author_email_address, duped_topic.author_email_address
744 745

    # test if saved clone object differs from original
A
Aaron Patterson 已提交
746 747 748
    duped_topic.save
    assert duped_topic.persisted?
    assert_not_equal duped_topic.id, topic.id
749

A
Aaron Patterson 已提交
750
    duped_topic.reload
751
    assert_equal("c", duped_topic.title)
D
Initial  
David Heinemeier Hansson 已提交
752
  end
753

754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
  def test_dup_with_aggregate_of_same_name_as_attribute
    dev = DeveloperWithAggregate.find(1)
    assert_kind_of DeveloperSalary, dev.salary

    dup = nil
    assert_nothing_raised { dup = dev.dup }
    assert_kind_of DeveloperSalary, dup.salary
    assert_equal dev.salary.amount, dup.salary.amount
    assert !dup.persisted?

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

    assert dup.save
    assert dup.persisted?
    assert_not_equal dup.id, dev.id
  end

A
Aaron Patterson 已提交
774
  def test_dup_does_not_copy_associations
775 776
    author = authors(:david)
    assert_not_equal [], author.posts
A
Aaron Patterson 已提交
777
    author.send(:clear_association_cache)
778

A
Aaron Patterson 已提交
779 780
    author_dup = author.dup
    assert_equal [], author_dup.posts
781 782
  end

783 784 785 786 787 788
  def test_clone_preserves_subtype
    clone = nil
    assert_nothing_raised { clone = Company.find(3).clone }
    assert_kind_of Client, clone
  end

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
  def test_clone_of_new_object_with_defaults
    developer = Developer.new
    assert !developer.name_changed?
    assert !developer.salary_changed?

    cloned_developer = developer.clone
    assert !cloned_developer.name_changed?
    assert !cloned_developer.salary_changed?
  end

  def test_clone_of_new_object_marks_attributes_as_dirty
    developer = Developer.new :name => 'Bjorn', :salary => 100000
    assert developer.name_changed?
    assert developer.salary_changed?

    cloned_developer = developer.clone
    assert cloned_developer.name_changed?
    assert cloned_developer.salary_changed?
  end

  def test_clone_of_new_object_marks_as_dirty_only_changed_attributes
    developer = Developer.new :name => 'Bjorn'
    assert developer.name_changed?            # obviously
    assert !developer.salary_changed?         # attribute has non-nil default value, so treated as not changed

    cloned_developer = developer.clone
    assert cloned_developer.name_changed?
    assert !cloned_developer.salary_changed?  # ... and cloned instance should behave same
  end

A
Aaron Patterson 已提交
819
  def test_dup_of_saved_object_marks_attributes_as_dirty
820 821 822 823
    developer = Developer.create! :name => 'Bjorn', :salary => 100000
    assert !developer.name_changed?
    assert !developer.salary_changed?

A
Aaron Patterson 已提交
824
    cloned_developer = developer.dup
825 826 827 828
    assert cloned_developer.name_changed?     # both attributes differ from defaults
    assert cloned_developer.salary_changed?
  end

A
Aaron Patterson 已提交
829
  def test_dup_of_saved_object_marks_as_dirty_only_changed_attributes
830
    developer = Developer.create! :name => 'Bjorn'
R
R.T. Lechow 已提交
831
    assert !developer.name_changed?           # both attributes of saved object should be treated as not changed
832 833
    assert !developer.salary_changed?

A
Aaron Patterson 已提交
834
    cloned_developer = developer.dup
835
    assert cloned_developer.name_changed?     # ... but on cloned object should be
R
R.T. Lechow 已提交
836
    assert !cloned_developer.salary_changed?  # ... BUT salary has non-nil default which should be treated as not changed on cloned instance
837 838
  end

D
Initial  
David Heinemeier Hansson 已提交
839 840 841 842 843 844 845 846
  def test_bignum
    company = Company.find(1)
    company.rating = 2147483647
    company.save
    company = Company.find(1)
    assert_equal 2147483647, company.rating
  end

847
  # TODO: extend defaults tests to other databases!
848
  if current_adapter?(:PostgreSQLAdapter)
849
    def test_default
850 851 852 853 854 855 856 857 858 859 860 861
      with_timezone_config default: :local do
        default = Default.new

        # 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

        # char types
        assert_equal 'Y', default.char1
        assert_equal 'a varchar field', default.char2
        assert_equal 'a text field', default.char3
      end
D
Initial  
David Heinemeier Hansson 已提交
862
    end
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879

    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 已提交
880

881 882 883
      assert g.save

      # Reload and check that we have all the geometric attributes.
C
Carlos Antonio da Silva 已提交
884
      h = Geometric.find(g.id)
885

886
      assert_equal [5.0, 6.1], h.a_point
887 888 889 890 891 892 893 894
      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]
895 896

      assert_equal true, objs[0].isopen
897 898

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

900 901 902 903 904 905 906 907 908 909 910 911 912
      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.
C
Carlos Antonio da Silva 已提交
913
      h = Geometric.find(g.id)
J
Jeremy Kemper 已提交
914

915
      assert_equal [5.0, 6.1], h.a_point
916 917 918 919 920 921 922 923
      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]
924 925

      assert_equal true, objs[0].isclosed
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948

      # test native ruby formats when defining the geometric types
      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)

      assert_equal [5.0, 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
949
    end
D
Initial  
David Heinemeier Hansson 已提交
950 951
  end

952 953 954 955
  class NumericData < ActiveRecord::Base
    self.table_name = 'numeric_data'
  end

956 957 958 959 960 961 962 963 964 965 966
  def test_big_decimal_conditions
    m = NumericData.new(
      :bank_balance => 1586.43,
      :big_bank_balance => BigDecimal("1000234000567.95"),
      :world_population => 6000000000,
      :my_house_population => 3
    )
    assert m.save
    assert_equal 0, NumericData.where("bank_balance > ?", 2000.0).count
  end

967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
  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 已提交
995 996 997
  def test_auto_id
    auto = AutoId.new
    auto.save
998
    assert(auto.id > 0)
D
Initial  
David Heinemeier Hansson 已提交
999
  end
1000

1001
  def test_sql_injection_via_find
1002
    assert_raise(ActiveRecord::RecordNotFound, ActiveRecord::StatementInvalid) do
1003 1004 1005 1006
      Topic.find("123456 OR id > 0")
    end
  end

D
Initial  
David Heinemeier Hansson 已提交
1007 1008 1009
  def test_column_name_properly_quoted
    col_record = ColumnName.new
    col_record.references = 40
1010
    assert col_record.save
D
Initial  
David Heinemeier Hansson 已提交
1011
    col_record.references = 41
1012 1013
    assert col_record.save
    assert_not_nil c2 = ColumnName.find(col_record.id)
D
Initial  
David Heinemeier Hansson 已提交
1014 1015 1016
    assert_equal(41, c2.references)
  end

1017
  def test_quoting_arrays
1018
    replies = Reply.all.merge!(:where => [ "id IN (?)", topics(:first).replies.collect(&:id) ]).to_a
1019 1020
    assert_equal topics(:first).replies.size, replies.size

1021
    replies = Reply.all.merge!(:where => [ "id IN (?)", [] ]).to_a
1022 1023 1024
    assert_equal 0, replies.size
  end

D
Initial  
David Heinemeier Hansson 已提交
1025
  def test_quote
1026 1027 1028
    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 已提交
1029
  end
1030

1031
  def test_toggle_attribute
1032 1033 1034
    assert !topics(:first).approved?
    topics(:first).toggle!(:approved)
    assert topics(:first).approved?
1035 1036 1037 1038 1039
    topic = topics(:first)
    topic.toggle(:approved)
    assert !topic.approved?
    topic.reload
    assert topic.approved?
1040
  end
1041 1042 1043 1044 1045 1046 1047 1048 1049

  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
1050

1051 1052
  def test_reload_with_exclusive_scope
    dev = DeveloperCalledDavid.first
1053
    dev.update!(name: "NotDavid" )
1054 1055 1056
    assert_equal dev, dev.reload
  end

1057 1058
  def test_switching_between_table_name
    assert_difference("GoodJoke.count") do
1059
      Joke.table_name = "cold_jokes"
1060 1061
      Joke.create

1062
      Joke.table_name = "funny_jokes"
1063 1064 1065 1066
      Joke.create
    end
  end

1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
  def test_clear_cash_when_setting_table_name
    Joke.table_name = "cold_jokes"
    before_columns = Joke.columns
    before_seq     = Joke.sequence_name

    Joke.table_name = "funny_jokes"
    after_columns = Joke.columns
    after_seq     = Joke.sequence_name

    assert_not_equal before_columns, after_columns
1077
    assert_not_equal before_seq, after_seq unless before_seq.nil? && after_seq.nil?
1078 1079
  end

1080 1081 1082 1083 1084 1085 1086 1087
  def test_dont_clear_sequence_name_when_setting_explicitly
    Joke.sequence_name = "black_jokes_seq"
    Joke.table_name    = "cold_jokes"
    before_seq         = Joke.sequence_name

    Joke.table_name    = "funny_jokes"
    after_seq          = Joke.sequence_name

1088
    assert_equal before_seq, after_seq unless before_seq.nil? && after_seq.nil?
1089 1090
  ensure
    Joke.reset_sequence_name
1091 1092
  end

1093
  def test_dont_clear_inheritance_column_when_setting_explicitly
1094 1095 1096 1097 1098 1099 1100 1101 1102
    Joke.inheritance_column = "my_type"
    before_inherit = Joke.inheritance_column

    Joke.reset_column_information
    after_inherit = Joke.inheritance_column

    assert_equal before_inherit, after_inherit unless before_inherit.blank? && after_inherit.blank?
  end

1103 1104 1105 1106 1107
  def test_set_table_name_symbol_converted_to_string
    Joke.table_name = :cold_jokes
    assert_equal 'cold_jokes', Joke.table_name
  end

1108 1109 1110
  def test_quoted_table_name_after_set_table_name
    klass = Class.new(ActiveRecord::Base)

1111
    klass.table_name = "foo"
1112 1113 1114
    assert_equal "foo", klass.table_name
    assert_equal klass.connection.quote_table_name("foo"), klass.quoted_table_name

1115
    klass.table_name = "bar"
1116 1117 1118 1119
    assert_equal "bar", klass.table_name
    assert_equal klass.connection.quote_table_name("bar"), klass.quoted_table_name
  end

1120 1121 1122 1123 1124
  def test_set_table_name_with_inheritance
    k = Class.new( ActiveRecord::Base )
    def k.name; "Foo"; end
    def k.table_name; super + "ks"; end
    assert_equal "foosks", k.table_name
1125 1126
  end

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
  def test_sequence_name_with_abstract_class
    ak = Class.new(ActiveRecord::Base)
    ak.abstract_class = true
    k = Class.new(ak)
    k.table_name = "projects"
    orig_name = k.sequence_name
    return skip "sequences not supported by db" unless orig_name
    assert_equal k.reset_sequence_name, orig_name
  end

1137
  def test_count_with_join
1138
    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 已提交
1139

J
Jon Leighton 已提交
1140
    res2 = Post.where("posts.#{QUOTED_TYPE} = 'Post'").joins("LEFT JOIN comments ON posts.id=comments.post_id").count
1141
    assert_equal res, res2
J
Jeremy Kemper 已提交
1142

1143
    res3 = nil
1144
    assert_nothing_raised do
J
Jon Leighton 已提交
1145
      res3 = Post.where("posts.#{QUOTED_TYPE} = 'Post'").joins("LEFT JOIN comments ON posts.id=comments.post_id").count
1146 1147
    end
    assert_equal res, res3
J
Jeremy Kemper 已提交
1148

1149
    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"
1150 1151
    res5 = nil
    assert_nothing_raised do
J
Jon Leighton 已提交
1152
      res5 = Post.where("p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id").joins("p, comments co").select("p.id").count
1153 1154
    end

J
Jeremy Kemper 已提交
1155
    assert_equal res4, res5
1156

P
Pratik Naik 已提交
1157 1158 1159
    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
1160
      res7 = Post.where("p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id").joins("p, comments co").select("p.id").distinct.count
1161
    end
P
Pratik Naik 已提交
1162
    assert_equal res6, res7
1163
  end
J
Jeremy Kemper 已提交
1164

1165 1166
  def test_no_limit_offset
    assert_nothing_raised do
1167
      Developer.all.merge!(:offset => 2).to_a
1168 1169 1170
    end
  end

1171
  def test_find_last
1172
    last  = Developer.last
1173
    assert_equal last, Developer.all.merge!(:order => 'id desc').first
1174
  end
1175

1176
  def test_last
1177
    assert_equal Developer.all.merge!(:order => 'id desc').first, Developer.last
1178
  end
1179

1180
  def test_all
J
Jon Leighton 已提交
1181 1182 1183
    developers = Developer.all
    assert_kind_of ActiveRecord::Relation, developers
    assert_equal Developer.all, developers
1184 1185
  end

1186
  def test_all_with_conditions
1187
    assert_equal Developer.all.merge!(:order => 'id desc').to_a, Developer.order('id desc').to_a
1188
  end
1189

1190
  def test_find_ordered_last
1191 1192
    last  = Developer.all.merge!(:order => 'developers.salary ASC').last
    assert_equal last, Developer.all.merge!(:order => 'developers.salary ASC').to_a.last
1193 1194 1195
  end

  def test_find_reverse_ordered_last
1196 1197
    last  = Developer.all.merge!(:order => 'developers.salary DESC').last
    assert_equal last, Developer.all.merge!(:order => 'developers.salary DESC').to_a.last
1198 1199 1200
  end

  def test_find_multiple_ordered_last
1201 1202
    last  = Developer.all.merge!(:order => 'developers.name, developers.salary DESC').last
    assert_equal last, Developer.all.merge!(:order => 'developers.name, developers.salary DESC').to_a.last
1203
  end
1204

1205
  def test_find_keeps_multiple_order_values
1206 1207
    combined = Developer.all.merge!(:order => 'developers.name, developers.salary').to_a
    assert_equal combined, Developer.all.merge!(:order => ['developers.name', 'developers.salary']).to_a
1208 1209 1210
  end

  def test_find_keeps_multiple_group_values
1211 1212
    combined = Developer.all.merge!(:group => 'developers.name, developers.salary, developers.id, developers.created_at, developers.updated_at, developers.created_on, developers.updated_on').to_a
    assert_equal combined, Developer.all.merge!(:group => ['developers.name', 'developers.salary', 'developers.id', 'developers.created_at', 'developers.updated_at', 'developers.created_on', 'developers.updated_on']).to_a
1213 1214
  end

1215
  def test_find_symbol_ordered_last
1216 1217
    last  = Developer.all.merge!(:order => :salary).last
    assert_equal last, Developer.all.merge!(:order => :salary).to_a.last
1218 1219
  end

1220
  def test_abstract_class
1221
    assert !ActiveRecord::Base.abstract_class?
1222 1223
    assert LoosePerson.abstract_class?
    assert !LooseDescendant.abstract_class?
1224 1225
  end

1226 1227 1228 1229
  def test_abstract_class_table_name
    assert_nil AbstractCompany.table_name
  end

1230
  def test_descends_from_active_record
1231
    assert !ActiveRecord::Base.descends_from_active_record?
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252

    # 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.
1253
    assert !SubStiPost.descends_from_active_record?
1254 1255 1256 1257 1258 1259
  end

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

1260
    descendant = old_class.create! :first_name => 'bob'
1261 1262 1263 1264 1265
    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
1266 1267
  end

1268 1269 1270 1271 1272 1273 1274
  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

1275 1276 1277
  def test_benchmark_with_log_level
    original_logger = ActiveRecord::Base.logger
    log = StringIO.new
1278
    ActiveRecord::Base.logger = ActiveSupport::Logger.new(log)
1279
    ActiveRecord::Base.logger.level = Logger::WARN
J
José Valim 已提交
1280 1281 1282
    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 }
1283 1284 1285
    assert_no_match(/Debug Topic Count/, log.string)
    assert_match(/Warn Topic Count/, log.string)
    assert_match(/Error Topic Count/, log.string)
1286 1287 1288 1289 1290 1291 1292
  ensure
    ActiveRecord::Base.logger = original_logger
  end

  def test_benchmark_with_use_silence
    original_logger = ActiveRecord::Base.logger
    log = StringIO.new
1293
    ActiveRecord::Base.logger = ActiveSupport::Logger.new(log)
J
José Valim 已提交
1294
    ActiveRecord::Base.benchmark("Logging", :level => :debug, :silence => false)  { ActiveRecord::Base.logger.debug "Quiet" }
1295
    assert_match(/Quiet/, log.string)
1296 1297 1298
  ensure
    ActiveRecord::Base.logger = original_logger
  end
1299

1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
  def test_compute_type_success
    assert_equal Author, ActiveRecord::Base.send(:compute_type, 'Author')
  end

  def test_compute_type_nonexistent_constant
    assert_raises NameError do
      ActiveRecord::Base.send :compute_type, 'NonexistentModel'
    end
  end

  def test_compute_type_no_method_error
1311
    ActiveSupport::Dependencies.stubs(:constantize).raises(NoMethodError)
1312 1313 1314 1315 1316
    assert_raises NoMethodError do
      ActiveRecord::Base.send :compute_type, 'InvalidModel'
    end
  end

1317 1318 1319 1320 1321 1322 1323
  def test_compute_type_argument_error
    ActiveSupport::Dependencies.stubs(:constantize).raises(ArgumentError)
    assert_raises ArgumentError do
      ActiveRecord::Base.send :compute_type, 'InvalidModel'
    end
  end

1324 1325
  def test_clear_cache!
    # preheat cache
1326
    c1 = Post.connection.schema_cache.columns('posts')
1327
    ActiveRecord::Base.clear_cache!
1328
    c2 = Post.connection.schema_cache.columns('posts')
1329 1330 1331
    assert_not_equal c1, c2
  end

1332
  def test_current_scope_is_reset
1333
    Object.const_set :UnloadablePost, Class.new(ActiveRecord::Base)
1334
    UnloadablePost.send(:current_scope=, UnloadablePost.all)
1335 1336

    UnloadablePost.unloadable
1337
    assert_not_nil ActiveRecord::Scoping::ScopeRegistry.value_for(:current_scope, "UnloadablePost")
1338
    ActiveSupport::Dependencies.remove_unloadable_constants!
1339
    assert_nil ActiveRecord::Scoping::ScopeRegistry.value_for(:current_scope, "UnloadablePost")
1340 1341 1342
  ensure
    Object.class_eval{ remove_const :UnloadablePost } if defined?(UnloadablePost)
  end
J
Jon Leighton 已提交
1343 1344 1345

  def test_marshal_round_trip
    expected = posts(:welcome)
1346 1347
    marshalled = Marshal.dump(expected)
    actual   = Marshal.load(marshalled)
J
Jon Leighton 已提交
1348 1349 1350

    assert_equal expected.attributes, actual.attributes
  end
1351

1352
  def test_marshal_new_record_round_trip
1353 1354 1355
    marshalled = Marshal.dump(Post.new)
    post       = Marshal.load(marshalled)

1356 1357 1358 1359 1360 1361
    assert post.new_record?, "should be a new record"
  end

  def test_marshalling_with_associations
    post = Post.new
    post.comments.build
1362 1363 1364

    marshalled = Marshal.dump(post)
    post       = Marshal.load(marshalled)
1365 1366 1367 1368

    assert_equal 1, post.comments.length
  end

1369
  def test_marshal_between_processes
Y
Yves Senn 已提交
1370
    skip "can't marshal between processes when using an in-memory db" if in_memory_db?
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
    skip "fork isn't supported" unless Process.respond_to?(:fork)

    # Define a new model to ensure there are no caches
    if self.class.const_defined?("Post", false)
      flunk "there should be no post constant"
    end

    self.class.const_set("Post", Class.new(ActiveRecord::Base) {
      has_many :comments
    })

    rd, wr = IO.pipe
1383 1384 1385

    ActiveRecord::Base.connection_handler.clear_all_connections!

A
Aaron Patterson 已提交
1386
    fork do
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
      rd.close
      post = Post.new
      post.comments.build
      wr.write Marshal.dump(post)
      wr.close
    end

    wr.close
    assert Marshal.load rd.read
    rd.close
  end

1399 1400 1401 1402 1403 1404 1405 1406 1407
  def test_marshalling_new_record_round_trip_with_associations
    post = Post.new
    post.comments.build

    post = Marshal.load(Marshal.dump(post))

    assert post.new_record?, "should be a new record"
  end

1408
  def test_attribute_names
1409
    assert_equal ["id", "type", "firm_id", "firm_name", "name", "client_of", "rating", "account_id", "description"],
1410 1411 1412 1413 1414 1415 1416
                 Company.attribute_names
  end

  def test_attribute_names_on_table_not_exists
    assert_equal [], NonExistentTable.attribute_names
  end

J
Jari Jokinen 已提交
1417
  def test_attribute_names_on_abstract_class
1418 1419
    assert_equal [], AbstractCompany.attribute_names
  end
1420

1421 1422 1423 1424 1425 1426 1427
  def test_touch_should_raise_error_on_a_new_object
    company = Company.new(:rating => 1, :name => "37signals", :firm_name => "37signals")
    assert_raises(ActiveRecord::ActiveRecordError) do
      company.touch :updated_at
    end
  end

1428 1429
  def test_uniq_delegates_to_scoped
    scope = stub
1430
    Bird.stubs(:all).returns(mock(:uniq => scope))
1431 1432
    assert_equal scope, Bird.uniq
  end
1433

1434 1435 1436 1437 1438 1439
  def test_distinct_delegates_to_scoped
    scope = stub
    Bird.stubs(:all).returns(mock(:distinct => scope))
    assert_equal scope, Bird.distinct
  end

1440 1441 1442
  def test_table_name_with_2_abstract_subclasses
    assert_equal "photos", Photo.table_name
  end
1443

1444 1445
  def test_column_types_typecast
    topic = Topic.first
1446
    assert_not_equal 't.lo', topic.author_name
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464

    attrs = topic.attributes.dup
    attrs.delete 'id'

    typecast = Class.new {
      def type_cast value
        "t.lo"
      end
    }

    types = { 'author_name' => typecast.new }
    topic = Topic.allocate.init_with 'attributes' => attrs,
                                     'column_types' => types

    assert_equal 't.lo', topic.author_name
  end

  def test_typecasting_aliases
1465 1466
    assert_equal 10, Topic.select('10 as tenderlove').first.tenderlove
  end
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478

  def test_slice
    company = Company.new(:rating => 1, :name => "37signals", :firm_name => "37signals")
    hash = company.slice(:name, :rating, "arbitrary_method")
    assert_equal hash[:name], company.name
    assert_equal hash['name'], company.name
    assert_equal hash[:rating], company.rating
    assert_equal hash['arbitrary_method'], company.arbitrary_method
    assert_equal hash[:arbitrary_method], company.arbitrary_method
    assert_nil hash[:firm_name]
    assert_nil hash['firm_name']
  end
1479

1480 1481 1482 1483 1484 1485
  def test_default_values_are_deeply_dupped
    company = Company.new
    company.description << "foo"
    assert_equal "", Company.new.description
  end

1486 1487 1488 1489 1490 1491 1492 1493
  ["find_by", "find_by!"].each do |meth|
    test "#{meth} delegates to scoped" do
      record = stub

      scope = mock
      scope.expects(meth).with(:foo, :bar).returns(record)

      klass = Class.new(ActiveRecord::Base)
1494
      klass.stubs(:all => scope)
1495 1496 1497 1498

      assert_equal record, klass.public_send(meth, :foo, :bar)
    end
  end
J
Jon Leighton 已提交
1499 1500 1501

  test "scoped can take a values hash" do
    klass = Class.new(ActiveRecord::Base)
1502
    assert_equal ['foo'], klass.all.merge!(select: 'foo').select_values
J
Jon Leighton 已提交
1503
  end
1504

1505
  test "connection_handler can be overridden" do
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
    klass = Class.new(ActiveRecord::Base)
    orig_handler = klass.connection_handler
    new_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
    thread_connection_handler = nil

    t = Thread.new do
      klass.connection_handler = new_handler
      thread_connection_handler = klass.connection_handler
    end
    t.join

    assert_equal klass.connection_handler, orig_handler
    assert_equal thread_connection_handler, new_handler
  end

  test "new threads get default the default connection handler" do
    klass = Class.new(ActiveRecord::Base)
    orig_handler = klass.connection_handler
    handler = nil

    t = Thread.new do
      handler = klass.connection_handler
    end
    t.join

    assert_equal handler, orig_handler
    assert_equal klass.connection_handler, orig_handler
    assert_equal klass.default_connection_handler, orig_handler
  end

  test "changing a connection handler in a main thread does not poison the other threads" do
    klass = Class.new(ActiveRecord::Base)
    orig_handler = klass.connection_handler
    new_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
    after_handler = nil
1541 1542
    latch1 = ActiveSupport::Concurrency::Latch.new
    latch2 = ActiveSupport::Concurrency::Latch.new
1543 1544 1545

    t = Thread.new do
      klass.connection_handler = new_handler
1546 1547
      latch1.release
      latch2.await
1548 1549 1550
      after_handler = klass.connection_handler
    end

1551
    latch1.await
1552 1553

    klass.connection_handler = orig_handler
1554
    latch2.release
1555 1556 1557 1558 1559
    t.join

    assert_equal after_handler, new_handler
    assert_equal orig_handler, klass.connection_handler
  end
1560
end