calculations_test.rb 17.1 KB
Newer Older
1
require "cases/helper"
J
Jeremy Kemper 已提交
2
require 'models/company'
3
require "models/contract"
J
Jeremy Kemper 已提交
4
require 'models/topic'
5
require 'models/edge'
6 7
require 'models/club'
require 'models/organization'
8 9 10

Company.has_many :accounts

11 12 13 14
class NumericData < ActiveRecord::Base
  self.table_name = 'numeric_data'
end

15
class CalculationsTest < ActiveRecord::TestCase
16 17 18
  fixtures :companies, :accounts, :topics

  def test_should_sum_field
19
    assert_equal 318, Account.sum(:credit_limit)
20 21 22 23
  end

  def test_should_average_field
    value = Account.average(:credit_limit)
24
    assert_equal 53.0, value
25 26
  end

27 28 29 30 31
  def test_should_return_decimal_average_of_integer_field
    value = Account.average(:id)
    assert_equal 3.5, value
  end

32 33 34 35 36 37
  def test_should_return_integer_average_if_db_returns_such
    Account.connection.stubs :select_value => 3
    value = Account.average(:id)
    assert_equal 3, value
  end

38 39 40
  def test_should_return_nil_as_average
    assert_nil NumericData.average(:bank_balance)
  end
41

42
  def test_type_cast_calculated_value_should_convert_db_averages_of_fixnum_class_to_decimal
43 44
    assert_equal 0, NumericData.scoped.send(:type_cast_calculated_value, 0, nil, 'avg')
    assert_equal 53.0, NumericData.scoped.send(:type_cast_calculated_value, 53, nil, 'avg')
45
  end
46

47 48 49 50
  def test_should_get_maximum_of_field
    assert_equal 60, Account.maximum(:credit_limit)
  end

51
  def test_should_get_maximum_of_field_with_include
52
    assert_equal 55, Account.maximum(:credit_limit, :include => :firm, :references => :companies, :conditions => "companies.name != 'Summit'")
53 54 55
  end

  def test_should_get_maximum_of_field_with_scoped_include
56
    Account.send :with_scope, :find => { :include => :firm, :references => :companies, :conditions => "companies.name != 'Summit'" } do
57
      assert_equal 55, Account.maximum(:credit_limit)
58 59 60
    end
  end

61 62 63 64 65 66
  def test_should_get_minimum_of_field
    assert_equal 50, Account.minimum(:credit_limit)
  end

  def test_should_group_by_field
    c = Account.sum(:credit_limit, :group => :firm_id)
67
    [1,6,2].each { |firm_id| assert c.keys.include?(firm_id) }
68
  end
69

70 71 72 73 74 75 76 77 78 79 80 81
  def test_should_group_by_multiple_fields
    c = Account.count(:all, :group => ['firm_id', :credit_limit])
    [ [nil, 50], [1, 50], [6, 50], [6, 55], [9, 53], [2, 60] ].each { |firm_and_limit| assert c.keys.include?(firm_and_limit) }
  end

  def test_should_group_by_multiple_fields_having_functions
    c = Topic.group(:author_name, 'COALESCE(type, title)').count(:all)
    assert_equal 1, c[["Carl", "The Third Topic of the day"]]
    assert_equal 1, c[["Mary", "Reply"]]
    assert_equal 1, c[["David", "The First Topic"]]
    assert_equal 1, c[["Carl", "Reply"]]
  end
82 83 84

  def test_should_group_by_summed_field
    c = Account.sum(:credit_limit, :group => :firm_id)
85 86 87
    assert_equal 50,   c[1]
    assert_equal 105,  c[6]
    assert_equal 60,   c[2]
88 89
  end

90 91
  def test_should_order_by_grouped_field
    c = Account.sum(:credit_limit, :group => :firm_id, :order => "firm_id")
92
    assert_equal [1, 2, 6, 9], c.keys.compact
93 94 95 96
  end

  def test_should_order_by_calculation
    c = Account.sum(:credit_limit, :group => :firm_id, :order => "sum_credit_limit desc, firm_id")
97 98
    assert_equal [105, 60, 53, 50, 50], c.keys.collect { |k| c[k] }
    assert_equal [6, 2, 9, 1], c.keys.compact
99 100
  end

101 102 103 104 105 106 107 108 109 110 111 112
  def test_should_limit_calculation
    c = Account.sum(:credit_limit, :conditions => "firm_id IS NOT NULL",
                    :group => :firm_id, :order => "firm_id", :limit => 2)
    assert_equal [1, 2], c.keys.compact
  end

  def test_should_limit_calculation_with_offset
    c = Account.sum(:credit_limit, :conditions => "firm_id IS NOT NULL",
                    :group => :firm_id, :order => "firm_id", :limit => 2, :offset => 1)
    assert_equal [2, 6], c.keys.compact
  end

113 114 115 116 117 118 119 120 121 122 123 124 125 126
  def test_limit_should_apply_before_count
    accounts = Account.limit(3).where('firm_id IS NOT NULL')

    assert_equal 3, accounts.count(:firm_id)
    assert_equal 3, accounts.select(:firm_id).count
  end

  def test_count_should_shortcut_with_limit_zero
    accounts = Account.limit(0)

    assert_no_queries { assert_equal 0, accounts.count }
  end

  def test_limit_is_kept
A
Aaron Patterson 已提交
127 128
    return if current_adapter?(:OracleAdapter)

129
    queries = assert_sql { Account.limit(1).count }
130 131 132 133
    assert_equal 1, queries.length
    assert_match(/LIMIT/, queries.first)
  end

134 135 136
  def test_offset_is_kept
    return if current_adapter?(:OracleAdapter)

137 138
    queries = assert_sql { Account.offset(1).count }
    assert_equal 1, queries.length
139
    assert_match(/OFFSET/, queries.first)
140 141
  end

142 143 144 145
  def test_limit_with_offset_is_kept
    return if current_adapter?(:OracleAdapter)

    queries = assert_sql { Account.limit(1).offset(1).count }
146
    assert_equal 1, queries.length
147 148
    assert_match(/LIMIT/, queries.first)
    assert_match(/OFFSET/, queries.first)
149 150 151 152 153 154 155 156 157
  end

  def test_no_limit_no_offset
    queries = assert_sql { Account.count }
    assert_equal 1, queries.length
    assert_no_match(/LIMIT/, queries.first)
    assert_no_match(/OFFSET/, queries.first)
  end

158
  def test_should_group_by_summed_field_having_condition
J
Jeremy Kemper 已提交
159
    c = Account.sum(:credit_limit, :group => :firm_id,
160
                                   :having => 'sum(credit_limit) > 50')
161 162 163
    assert_nil        c[1]
    assert_equal 105, c[6]
    assert_equal 60,  c[2]
164 165
  end

166 167 168 169 170 171 172 173
  def test_should_group_by_summed_field_having_sanitized_condition
    c = Account.sum(:credit_limit, :group => :firm_id,
                                   :having => ['sum(credit_limit) > ?', 50])
    assert_nil        c[1]
    assert_equal 105, c[6]
    assert_equal 60,  c[2]
  end

174
  def test_should_group_by_summed_field_having_condition_from_select
175
    c = Account.select("MIN(credit_limit) AS min_credit_limit").group(:firm_id).having("MIN(credit_limit) > 50").sum(:credit_limit)
176 177 178 179 180
    assert_nil       c[1]
    assert_equal 60, c[2]
    assert_equal 53, c[9]
  end

181 182 183 184 185 186
  def test_should_group_by_summed_association
    c = Account.sum(:credit_limit, :group => :firm)
    assert_equal 50,   c[companies(:first_firm)]
    assert_equal 105,  c[companies(:rails_core)]
    assert_equal 60,   c[companies(:first_client)]
  end
J
Jeremy Kemper 已提交
187

188 189 190 191
  def test_should_sum_field_with_conditions
    assert_equal 105, Account.sum(:credit_limit, :conditions => 'firm_id = 6')
  end

192 193
  def test_should_return_zero_if_sum_conditions_return_nothing
    assert_equal 0, Account.sum(:credit_limit, :conditions => '1 = 2')
194
    assert_equal 0, companies(:rails_core).companies.sum(:id, :conditions => '1 = 2')
195 196
  end

197 198 199 200 201
  def test_sum_should_return_valid_values_for_decimals
    NumericData.create(:bank_balance => 19.83)
    assert_equal 19.83, NumericData.sum(:bank_balance)
  end

202
  def test_should_group_by_summed_field_with_conditions
J
Jeremy Kemper 已提交
203
    c = Account.sum(:credit_limit, :conditions => 'firm_id > 1',
204
                                   :group => :firm_id)
205 206 207
    assert_nil        c[1]
    assert_equal 105, c[6]
    assert_equal 60,  c[2]
208
  end
J
Jeremy Kemper 已提交
209

210
  def test_should_group_by_summed_field_with_conditions_and_having
J
Jeremy Kemper 已提交
211 212
    c = Account.sum(:credit_limit, :conditions => 'firm_id > 1',
                                   :group => :firm_id,
213
                                   :having => 'sum(credit_limit) > 60')
214 215 216
    assert_nil        c[1]
    assert_equal 105, c[6]
    assert_nil        c[2]
217 218 219 220
  end

  def test_should_group_by_fields_with_table_alias
    c = Account.sum(:credit_limit, :group => 'accounts.firm_id')
221 222 223
    assert_equal 50,  c[1]
    assert_equal 105, c[6]
    assert_equal 60,  c[2]
224
  end
J
Jeremy Kemper 已提交
225

226
  def test_should_calculate_with_invalid_field
227 228
    assert_equal 6, Account.calculate(:count, '*')
    assert_equal 6, Account.calculate(:count, :all)
229
  end
J
Jeremy Kemper 已提交
230

231 232
  def test_should_calculate_grouped_with_invalid_field
    c = Account.count(:all, :group => 'accounts.firm_id')
233 234 235
    assert_equal 1, c[1]
    assert_equal 2, c[6]
    assert_equal 1, c[2]
236
  end
J
Jeremy Kemper 已提交
237

238 239 240 241 242 243
  def test_should_calculate_grouped_association_with_invalid_field
    c = Account.count(:all, :group => :firm)
    assert_equal 1, c[companies(:first_firm)]
    assert_equal 2, c[companies(:rails_core)]
    assert_equal 1, c[companies(:first_client)]
  end
244

245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  def test_should_group_by_association_with_non_numeric_foreign_key
    ActiveRecord::Base.connection.expects(:select_all).returns([{"count_all" => 1, "firm_id" => "ABC"}])

    firm = mock()
    firm.expects(:id).returns("ABC")
    firm.expects(:class).returns(Firm)
    Company.expects(:find).with(["ABC"]).returns([firm])

    column = mock()
    column.expects(:name).at_least_once.returns(:firm_id)
    column.expects(:type_cast).with("ABC").returns("ABC")
    Account.expects(:columns).at_least_once.returns([column])

    c = Account.count(:all, :group => :firm)
    first_key = c.keys.first
    assert_equal Firm, first_key.class
    assert_equal 1, c[first_key]
262
  end
J
Jeremy Kemper 已提交
263

264 265 266 267 268 269 270 271
  def test_should_calculate_grouped_association_with_foreign_key_option
    Account.belongs_to :another_firm, :class_name => 'Firm', :foreign_key => 'firm_id'
    c = Account.count(:all, :group => :another_firm)
    assert_equal 1, c[companies(:first_firm)]
    assert_equal 2, c[companies(:rails_core)]
    assert_equal 1, c[companies(:first_client)]
  end

272
  def test_should_not_modify_options_when_using_includes
273
    options = {:conditions => 'companies.id > 1', :include => :firm, :references => :companies}
274
    options_copy = options.dup
J
Jeremy Kemper 已提交
275

276 277 278
    Account.count(:all, options)
    assert_equal options_copy, options
  end
279 280

  def test_should_calculate_grouped_by_function
281
    c = Company.count(:all, :group => "UPPER(#{QUOTED_TYPE})")
282 283
    assert_equal 2, c[nil]
    assert_equal 1, c['DEPENDENTFIRM']
284
    assert_equal 4, c['CLIENT']
285 286
    assert_equal 2, c['FIRM']
  end
J
Jeremy Kemper 已提交
287

288
  def test_should_calculate_grouped_by_function_with_table_alias
289
    c = Company.count(:all, :group => "UPPER(companies.#{QUOTED_TYPE})")
290 291
    assert_equal 2, c[nil]
    assert_equal 1, c['DEPENDENTFIRM']
292
    assert_equal 4, c['CLIENT']
293
    assert_equal 2, c['FIRM']
294
  end
J
Jeremy Kemper 已提交
295

296 297 298
  def test_should_not_overshadow_enumerable_sum
    assert_equal 6, [1, 2, 3].sum(&:abs)
  end
299 300 301 302 303

  def test_should_sum_scoped_field
    assert_equal 15, companies(:rails_core).companies.sum(:id)
  end

304 305 306 307
  def test_should_sum_scoped_field_with_from
    assert_equal Club.count, Organization.clubs.count
  end

308 309 310 311 312 313 314 315 316 317
  def test_should_sum_scoped_field_with_conditions
    assert_equal 8,  companies(:rails_core).companies.sum(:id, :conditions => 'id > 7')
  end

  def test_should_group_by_scoped_field
    c = companies(:rails_core).companies.sum(:id, :group => :name)
    assert_equal 7, c['Leetsoft']
    assert_equal 8, c['Jadedpixel']
  end

E
Emilio Tagua 已提交
318
  def test_should_group_by_summed_field_through_association_and_having
319 320 321 322 323
    c = companies(:rails_core).companies.sum(:id, :group => :name,
                                                  :having => 'sum(id) > 7')
    assert_nil      c['Leetsoft']
    assert_equal 8, c['Jadedpixel']
  end
324

325
  def test_should_count_selected_field_with_include
326 327
    assert_equal 6, Account.count(:distinct => true, :include => :firm)
    assert_equal 4, Account.count(:distinct => true, :include => :firm, :select => :credit_limit)
328
  end
J
Jeremy Kemper 已提交
329

330 331 332 333 334 335 336
  def test_should_not_perform_joined_include_by_default
    assert_equal Account.count, Account.includes(:firm).count
    queries = assert_sql { Account.includes(:firm).count }
    assert_no_match(/join/i, queries.last)
  end

  def test_should_perform_joined_include_when_referencing_included_tables
337
    joined_count = Account.includes(:firm).where(:companies => {:name => '37signals'}).count
338 339 340
    assert_equal 1, joined_count
  end

341
  def test_should_count_scoped_select
342 343
    Account.update_all("credit_limit = NULL")
    assert_equal 0, Account.scoped(:select => "credit_limit").count
344 345 346
  end

  def test_should_count_scoped_select_with_options
347
    Account.update_all("credit_limit = NULL")
348 349
    Account.last.update_column('credit_limit', 49)
    Account.first.update_column('credit_limit', 51)
350 351

    assert_equal 1, Account.scoped(:select => "credit_limit").count(:conditions => ['credit_limit >= 50'])
352 353
  end

354 355 356 357
  def test_should_count_manual_select_with_include
    assert_equal 6, Account.count(:select => "DISTINCT accounts.id", :include => :firm)
  end

358 359 360
  def test_count_with_column_parameter
    assert_equal 5, Account.count(:firm_id)
  end
J
Jeremy Kemper 已提交
361

362
  def test_count_with_column_and_options_parameter
363
    assert_equal 2, Account.count(:firm_id, :conditions => "credit_limit = 50 AND firm_id IS NOT NULL")
364
  end
J
Jeremy Kemper 已提交
365

O
oleg dashevskii 已提交
366 367 368 369 370 371
  def test_should_count_field_in_joined_table
    assert_equal 5, Account.count('companies.id', :joins => :firm)
    assert_equal 4, Account.count('companies.id', :joins => :firm, :distinct => true)
  end

  def test_should_count_field_in_joined_table_with_group_by
372
    c = Account.count('companies.id', :group => 'accounts.firm_id', :joins => :firm)
O
oleg dashevskii 已提交
373 374 375 376

    [1,6,2,9].each { |firm_id| assert c.keys.include?(firm_id) }
  end

377 378 379 380 381 382 383
  def test_count_with_no_parameters_isnt_deprecated
    assert_not_deprecated { Account.count }
  end

  def test_count_with_too_many_parameters_raises
    assert_raise(ArgumentError) { Account.count(1, 2, 3) }
  end
384 385

  def test_should_sum_expression
386 387 388 389
    # Oracle adapter returns floating point value 636.0 after SUM
    if current_adapter?(:OracleAdapter)
      assert_equal 636, Account.sum("2 * credit_limit")
    else
390
      assert_equal 636, Account.sum("2 * credit_limit").to_i
391
    end
392
  end
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407

  def test_count_with_from_option
    assert_equal Company.count(:all), Company.count(:all, :from => 'companies')
    assert_equal Account.count(:all, :conditions => "credit_limit = 50"),
        Account.count(:all, :from => 'accounts', :conditions => "credit_limit = 50")
    assert_equal Company.count(:type, :conditions => {:type => "Firm"}),
        Company.count(:type, :conditions => {:type => "Firm"}, :from => 'companies')
  end

  def test_sum_with_from_option
    assert_equal Account.sum(:credit_limit), Account.sum(:credit_limit, :from => 'accounts')
    assert_equal Account.sum(:credit_limit, :conditions => "credit_limit > 50"),
        Account.sum(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50")
  end

408 409 410 411
  def test_sum_array_compatibility
    assert_equal Account.sum(:credit_limit), Account.sum(&:credit_limit)
  end

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
  def test_average_with_from_option
    assert_equal Account.average(:credit_limit), Account.average(:credit_limit, :from => 'accounts')
    assert_equal Account.average(:credit_limit, :conditions => "credit_limit > 50"),
        Account.average(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50")
  end

  def test_minimum_with_from_option
    assert_equal Account.minimum(:credit_limit), Account.minimum(:credit_limit, :from => 'accounts')
    assert_equal Account.minimum(:credit_limit, :conditions => "credit_limit > 50"),
        Account.minimum(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50")
  end

  def test_maximum_with_from_option
    assert_equal Account.maximum(:credit_limit), Account.maximum(:credit_limit, :from => 'accounts')
    assert_equal Account.maximum(:credit_limit, :conditions => "credit_limit > 50"),
        Account.maximum(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50")
  end

  def test_from_option_with_specified_index
B
Brian Lopez 已提交
431
    if Edge.connection.adapter_name == 'MySQL' or Edge.connection.adapter_name == 'Mysql2'
432 433 434 435 436 437 438 439 440
      assert_equal Edge.count(:all), Edge.count(:all, :from => 'edges USE INDEX(unique_edge_index)')
      assert_equal Edge.count(:all, :conditions => 'sink_id < 5'),
          Edge.count(:all, :from => 'edges USE INDEX(unique_edge_index)', :conditions => 'sink_id < 5')
    end
  end

  def test_from_option_with_table_different_than_class
    assert_equal Account.count(:all), Company.count(:all, :from => 'accounts')
  end
441 442 443 444 445 446 447 448 449

  def test_distinct_is_honored_when_used_with_count_operation_after_group
    # Count the number of authors for approved topics
    approved_topics_count = Topic.group(:approved).count(:author_name)[true]
    assert_equal approved_topics_count, 3
    # Count the number of distinct authors for approved Topics
    distinct_authors_for_approved_count = Topic.group(:approved).count(:author_name, :distinct => true)[true]
    assert_equal distinct_authors_for_approved_count, 2
  end
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472

  def test_pluck
    assert_equal [1,2,3,4], Topic.order(:id).pluck(:id)
  end

  def test_pluck_type_cast
    topic = topics(:first)
    relation = Topic.where(:id => topic.id)
    assert_equal [ topic.approved ], relation.pluck(:approved)
    assert_equal [ topic.last_read ], relation.pluck(:last_read)
    assert_equal [ topic.written_on ], relation.pluck(:written_on)
  end

  def test_pluck_and_uniq
    assert_equal [50, 53, 55, 60], Account.order(:credit_limit).uniq.pluck(:credit_limit)
  end

  def test_pluck_in_relation
    company = Company.first
    contract = company.contracts.create!
    assert_equal [contract.id], company.contracts.pluck(:id)
  end

473 474 475 476 477 478 479 480
  def test_pluck_with_serialization
    t = Topic.create!(:content => { :foo => :bar })
    assert_equal [{:foo => :bar}], Topic.where(:id => t.id).pluck(:content)
  end

  def test_pluck_with_qualified_column_name
    assert_equal [1,2,3,4], Topic.order(:id).pluck("topics.id")
  end
481 482 483 484 485 486 487 488 489 490 491

  def test_pluck_auto_table_name_prefix
    c = Company.create!(:name => "test", :contracts => [Contract.new])
    assert_equal [c.id], Company.joins(:contracts).pluck(:id)
  end

  def test_pluck_not_auto_table_name_prefix_if_column_joined
    c = Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
    # No chance for typecast here
    assert_equal ["7"], Company.joins(:contracts).pluck(:developer_id)
  end
492
end