root/lang/ruby/pritter/vendor/rails/activerecord/test/finder_test.rb

Revision 5644, 19.5 kB (checked in by nakamud, 5 years ago)

lang/ruby/pritter: freezed gems to ease installation

Line 
1require 'abstract_unit'
2require 'fixtures/company'
3require 'fixtures/topic'
4require 'fixtures/reply'
5require 'fixtures/entrant'
6require 'fixtures/developer'
7require 'fixtures/post'
8
9class FinderTest < Test::Unit::TestCase
10  fixtures :companies, :topics, :entrants, :developers, :developers_projects, :posts, :accounts
11
12  def test_find
13    assert_equal(topics(:first).title, Topic.find(1).title)
14  end
15 
16  # find should handle strings that come from URLs
17  # (example: Category.find(params[:id]))
18  def test_find_with_string
19    assert_equal(Topic.find(1).title,Topic.find("1").title)
20  end
21 
22  def test_exists
23    assert Topic.exists?(1)
24    assert Topic.exists?("1")
25    assert Topic.exists?(:author_name => "David")
26    assert Topic.exists?(:author_name => "Mary", :approved => true)
27    assert Topic.exists?(["parent_id = ?", 1])
28    assert !Topic.exists?(45)
29    assert !Topic.exists?("foo")
30    assert_raise(NoMethodError) { Topic.exists?([1,2]) }
31  end
32 
33  def test_find_by_array_of_one_id
34    assert_kind_of(Array, Topic.find([ 1 ]))
35    assert_equal(1, Topic.find([ 1 ]).length)
36  end
37 
38  def test_find_by_ids
39    assert_equal(2, Topic.find(1, 2).length)
40    assert_equal(topics(:second).title, Topic.find([ 2 ]).first.title)
41  end
42
43  def test_find_an_empty_array
44    assert_equal [], Topic.find([])
45  end
46
47  def test_find_by_ids_missing_one
48    assert_raises(ActiveRecord::RecordNotFound) {
49      Topic.find(1, 2, 45)
50    }
51  end
52 
53  def test_find_all_with_limit
54    entrants = Entrant.find(:all, :order => "id ASC", :limit => 2)
55   
56    assert_equal(2, entrants.size)
57    assert_equal(entrants(:first).name, entrants.first.name)
58  end
59
60  def test_find_all_with_prepared_limit_and_offset
61    entrants = Entrant.find(:all, :order => "id ASC", :limit => 2, :offset => 1)
62
63    assert_equal(2, entrants.size)
64    assert_equal(entrants(:second).name, entrants.first.name)
65
66    entrants = Entrant.find(:all, :order => "id ASC", :limit => 2, :offset => 2)
67    assert_equal(1, entrants.size)
68    assert_equal(entrants(:third).name, entrants.first.name)
69  end
70 
71  def test_find_all_with_limit_and_offset_and_multiple_orderings
72    developers = Developer.find(:all, :order => "salary ASC, id DESC", :limit => 3, :offset => 1)
73    assert_equal ["David", "fixture_10", "fixture_9"], developers.collect {|d| d.name}
74  end
75 
76  def test_find_with_limit_and_condition
77    developers = Developer.find(:all, :order => "id DESC", :conditions => "salary = 100000", :limit => 3, :offset =>7)
78    assert_equal(1, developers.size)
79    assert_equal("fixture_3", developers.first.name)
80  end
81
82  def test_find_with_entire_select_statement
83    topics = Topic.find_by_sql "SELECT * FROM topics WHERE author_name = 'Mary'"
84   
85    assert_equal(1, topics.size)
86    assert_equal(topics(:second).title, topics.first.title)
87  end
88 
89  def test_find_with_prepared_select_statement
90    topics = Topic.find_by_sql ["SELECT * FROM topics WHERE author_name = ?", "Mary"]
91   
92    assert_equal(1, topics.size)
93    assert_equal(topics(:second).title, topics.first.title)
94  end
95 
96  def test_find_by_sql_with_sti_on_joined_table
97    accounts = Account.find_by_sql("SELECT * FROM accounts INNER JOIN companies ON companies.id = accounts.firm_id")
98    assert_equal [Account], accounts.collect(&:class).uniq
99  end
100 
101  def test_find_first
102    first = Topic.find(:first, :conditions => "title = 'The First Topic'")
103    assert_equal(topics(:first).title, first.title)
104  end
105 
106  def test_find_first_failing
107    first = Topic.find(:first, :conditions => "title = 'The First Topic!'")
108    assert_nil(first)
109  end
110
111  def test_unexisting_record_exception_handling
112    assert_raises(ActiveRecord::RecordNotFound) {
113      Topic.find(1).parent
114    }
115   
116    Topic.find(2).topic
117  end
118 
119  def test_find_only_some_columns
120    topic = Topic.find(1, :select => "author_name")
121    assert_raises(NoMethodError) { topic.title }
122    assert_equal "David", topic.author_name
123    assert !topic.attribute_present?("title")
124    assert !topic.respond_to?("title")
125    assert topic.attribute_present?("author_name")
126    assert topic.respond_to?("author_name")
127  end
128
129  def test_find_on_array_conditions
130    assert Topic.find(1, :conditions => ["approved = ?", false])
131    assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => ["approved = ?", true]) }
132  end
133 
134  def test_find_on_hash_conditions
135    assert Topic.find(1, :conditions => { :approved => false })
136    assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :approved => true }) }
137  end
138 
139  def test_find_on_hash_conditions_with_range
140    assert_equal [1,2], Topic.find(:all, :conditions => { :id => 1..2 }).map(&:id).sort
141    assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :id => 2..3 }) }
142  end
143 
144  def test_find_on_hash_conditions_with_multiple_ranges
145    assert_equal [1,2,3], Comment.find(:all, :conditions => { :id => 1..3, :post_id => 1..2 }).map(&:id).sort
146    assert_equal [1], Comment.find(:all, :conditions => { :id => 1..1, :post_id => 1..10 }).map(&:id).sort
147  end
148 
149  def test_find_on_multiple_hash_conditions
150    assert Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => false })
151    assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }) }
152    assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "HHC", :replies_count => 1, :approved => false }) }
153    assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }) }
154  end
155 
156  def test_condition_array_interpolation
157    assert_kind_of Firm, Company.find(:first, :conditions => ["name = '%s'", "37signals"])
158    assert_nil Company.find(:first, :conditions => ["name = '%s'", "37signals!"])
159    assert_nil Company.find(:first, :conditions => ["name = '%s'", "37signals!' OR 1=1"])
160    assert_kind_of Time, Topic.find(:first, :conditions => ["id = %d", 1]).written_on
161  end
162 
163  def test_condition_hash_interpolation
164    assert_kind_of Firm, Company.find(:first, :conditions => { :name => "37signals"})
165    assert_nil Company.find(:first, :conditions => { :name => "37signals!"})
166    assert_kind_of Time, Topic.find(:first, :conditions => {:id => 1}).written_on
167  end
168 
169  def test_hash_condition_find_malformed
170    assert_raises(ActiveRecord::StatementInvalid) {
171      Company.find(:first, :conditions => { :id => 2, :dhh => true })
172    }
173  end
174
175  def test_hash_condition_find_with_escaped_characters
176    Company.create("name" => "Ain't noth'n like' \#stuff")
177    assert Company.find(:first, :conditions => { :name => "Ain't noth'n like' \#stuff" })
178  end
179
180  def test_hash_condition_find_with_array
181    p1, p2 = Post.find(:all, :limit => 2, :order => 'id asc')
182    assert_equal [p1, p2], Post.find(:all, :conditions => { :id => [p1, p2] }, :order => 'id asc')
183    assert_equal [p1, p2], Post.find(:all, :conditions => { :id => [p1, p2.id] }, :order => 'id asc')
184  end
185
186  def test_hash_condition_find_with_nil
187    topic = Topic.find(:first, :conditions => { :last_read => nil } )
188    assert_not_nil topic
189    assert_nil topic.last_read
190  end
191
192  def test_bind_variables
193    assert_kind_of Firm, Company.find(:first, :conditions => ["name = ?", "37signals"])
194    assert_nil Company.find(:first, :conditions => ["name = ?", "37signals!"])
195    assert_nil Company.find(:first, :conditions => ["name = ?", "37signals!' OR 1=1"])
196    assert_kind_of Time, Topic.find(:first, :conditions => ["id = ?", 1]).written_on
197    assert_raises(ActiveRecord::PreparedStatementInvalid) {
198      Company.find(:first, :conditions => ["id=? AND name = ?", 2])
199    }
200    assert_raises(ActiveRecord::PreparedStatementInvalid) {
201           Company.find(:first, :conditions => ["id=?", 2, 3, 4])
202    }
203  end
204 
205  def test_bind_variables_with_quotes
206    Company.create("name" => "37signals' go'es agains")
207    assert Company.find(:first, :conditions => ["name = ?", "37signals' go'es agains"])
208  end
209
210  def test_named_bind_variables_with_quotes
211    Company.create("name" => "37signals' go'es agains")
212    assert Company.find(:first, :conditions => ["name = :name", {:name => "37signals' go'es agains"}])
213  end
214
215  def test_bind_arity
216    assert_nothing_raised                                 { bind '' }
217    assert_raises(ActiveRecord::PreparedStatementInvalid) { bind '', 1 }
218 
219    assert_raises(ActiveRecord::PreparedStatementInvalid) { bind '?' }
220    assert_nothing_raised                                 { bind '?', 1 }
221    assert_raises(ActiveRecord::PreparedStatementInvalid) { bind '?', 1, 1  }
222  end
223 
224  def test_named_bind_variables
225    assert_equal '1', bind(':a', :a => 1) # ' ruby-mode
226    assert_equal '1 1', bind(':a :a', :a => 1)  # ' ruby-mode
227 
228    assert_kind_of Firm, Company.find(:first, :conditions => ["name = :name", { :name => "37signals" }])
229    assert_nil Company.find(:first, :conditions => ["name = :name", { :name => "37signals!" }])
230    assert_nil Company.find(:first, :conditions => ["name = :name", { :name => "37signals!' OR 1=1" }])
231    assert_kind_of Time, Topic.find(:first, :conditions => ["id = :id", { :id => 1 }]).written_on
232  end
233
234  def test_bind_enumerable
235    assert_equal '1,2,3', bind('?', [1, 2, 3])
236    assert_equal %('a','b','c'), bind('?', %w(a b c))
237
238    assert_equal '1,2,3', bind(':a', :a => [1, 2, 3])
239    assert_equal %('a','b','c'), bind(':a', :a => %w(a b c)) # '
240
241    require 'set'
242    assert_equal '1,2,3', bind('?', Set.new([1, 2, 3]))
243    assert_equal %('a','b','c'), bind('?', Set.new(%w(a b c)))
244
245    assert_equal '1,2,3', bind(':a', :a => Set.new([1, 2, 3]))
246    assert_equal %('a','b','c'), bind(':a', :a => Set.new(%w(a b c))) # '
247  end
248
249  def test_bind_empty_enumerable
250    quoted_nil = ActiveRecord::Base.connection.quote(nil)
251    assert_equal quoted_nil, bind('?', [])
252    assert_equal " in (#{quoted_nil})", bind(' in (?)', [])
253    assert_equal "foo in (#{quoted_nil})", bind('foo in (?)', [])
254  end
255
256  def test_bind_string
257    assert_equal "''", bind('?', '')
258  end
259
260  def test_bind_record
261    o = Struct.new(:quoted_id).new(1)
262    assert_equal '1', bind('?', o)
263
264    os = [o] * 3
265    assert_equal '1,1,1', bind('?', os)
266  end
267
268  def test_string_sanitation
269    assert_not_equal "'something ' 1=1'", ActiveRecord::Base.sanitize("something ' 1=1")
270    assert_equal "'something; select table'", ActiveRecord::Base.sanitize("something; select table")
271  end
272
273  def test_count
274    assert_equal(0, Entrant.count(:conditions => "id > 3"))
275    assert_equal(1, Entrant.count(:conditions => ["id > ?", 2]))
276    assert_equal(2, Entrant.count(:conditions => ["id > ?", 1]))
277  end
278
279  def test_count_by_sql
280    assert_equal(0, Entrant.count_by_sql("SELECT COUNT(*) FROM entrants WHERE id > 3"))
281    assert_equal(1, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 2]))
282    assert_equal(2, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 1]))
283  end
284
285  def test_find_by_one_attribute
286    assert_equal topics(:first), Topic.find_by_title("The First Topic")
287    assert_nil Topic.find_by_title("The First Topic!")
288  end
289
290  def test_find_by_one_attribute_with_order_option
291    assert_equal accounts(:signals37), Account.find_by_credit_limit(50, :order => 'id')
292    assert_equal accounts(:rails_core_account), Account.find_by_credit_limit(50, :order => 'id DESC')
293  end
294
295  def test_find_by_one_attribute_with_conditions
296    assert_equal accounts(:rails_core_account), Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6])
297  end
298
299  def test_find_by_one_attribute_with_several_options
300    assert_equal accounts(:unknown), Account.find_by_credit_limit(50, :order => 'id DESC', :conditions => ['id != ?', 3])
301  end
302 
303  def test_find_by_one_missing_attribute
304    assert_raises(NoMethodError) { Topic.find_by_undertitle("The First Topic!") }
305  end
306 
307  def test_find_by_invalid_method_syntax
308    assert_raises(NoMethodError) { Topic.fail_to_find_by_title("The First Topic") }
309    assert_raises(NoMethodError) { Topic.find_by_title?("The First Topic") }
310    assert_raises(NoMethodError) { Topic.fail_to_find_or_create_by_title("Nonexistent Title") }
311    assert_raises(NoMethodError) { Topic.find_or_create_by_title?("Nonexistent Title") }
312  end
313
314  def test_find_by_two_attributes
315    assert_equal topics(:first), Topic.find_by_title_and_author_name("The First Topic", "David")
316    assert_nil Topic.find_by_title_and_author_name("The First Topic", "Mary")
317  end
318
319  def test_find_all_by_one_attribute
320    topics = Topic.find_all_by_content("Have a nice day")
321    assert_equal 2, topics.size
322    assert topics.include?(topics(:first))
323
324    assert_equal [], Topic.find_all_by_title("The First Topic!!")
325  end
326 
327  def test_find_all_by_one_attribute_with_options
328    topics = Topic.find_all_by_content("Have a nice day", :order => "id DESC")
329    assert topics(:first), topics.last
330
331    topics = Topic.find_all_by_content("Have a nice day", :order => "id")
332    assert topics(:first), topics.first
333  end
334
335  def test_find_all_by_array_attribute
336    assert_equal 2, Topic.find_all_by_title(["The First Topic", "The Second Topic's of the day"]).size
337  end
338
339  def test_find_all_by_boolean_attribute
340    topics = Topic.find_all_by_approved(false)
341    assert_equal 1, topics.size
342    assert topics.include?(topics(:first))
343
344    topics = Topic.find_all_by_approved(true)
345    assert_equal 1, topics.size
346    assert topics.include?(topics(:second))
347  end
348 
349  def test_find_by_nil_attribute
350    topic = Topic.find_by_last_read nil
351    assert_not_nil topic
352    assert_nil topic.last_read
353  end
354 
355  def test_find_all_by_nil_attribute
356    topics = Topic.find_all_by_last_read nil
357    assert_equal 1, topics.size
358    assert_nil topics[0].last_read
359  end
360 
361  def test_find_by_nil_and_not_nil_attributes
362    topic = Topic.find_by_last_read_and_author_name nil, "Mary"
363    assert_equal "Mary", topic.author_name
364  end
365
366  def test_find_all_by_nil_and_not_nil_attributes
367    topics = Topic.find_all_by_last_read_and_author_name nil, "Mary"
368    assert_equal 1, topics.size
369    assert_equal "Mary", topics[0].author_name
370  end
371
372  def test_find_or_create_from_one_attribute
373    number_of_companies = Company.count
374    sig38 = Company.find_or_create_by_name("38signals")
375    assert_equal number_of_companies + 1, Company.count
376    assert_equal sig38, Company.find_or_create_by_name("38signals")
377    assert !sig38.new_record?
378  end
379
380  def test_find_or_create_from_two_attributes
381    number_of_topics = Topic.count
382    another = Topic.find_or_create_by_title_and_author_name("Another topic","John")
383    assert_equal number_of_topics + 1, Topic.count
384    assert_equal another, Topic.find_or_create_by_title_and_author_name("Another topic", "John")
385    assert !another.new_record?
386  end
387 
388  def test_find_or_initialize_from_one_attribute
389    sig38 = Company.find_or_initialize_by_name("38signals")
390    assert_equal "38signals", sig38.name
391    assert sig38.new_record?
392  end
393 
394  def test_find_or_initialize_from_two_attributes
395    another = Topic.find_or_initialize_by_title_and_author_name("Another topic","John")
396    assert_equal "Another topic", another.title
397    assert_equal "John", another.author_name
398    assert another.new_record?
399  end
400
401  def test_find_with_bad_sql
402    assert_raises(ActiveRecord::StatementInvalid) { Topic.find_by_sql "select 1 from badtable" }
403  end
404
405  def test_find_with_invalid_params
406    assert_raises(ArgumentError) { Topic.find :first, :join => "It should be `joins'" }
407    assert_raises(ArgumentError) { Topic.find :first, :conditions => '1 = 1', :join => "It should be `joins'" }
408  end
409
410  def test_find_all_with_limit
411    first_five_developers = Developer.find :all, :order => 'id ASC', :limit =>  5
412    assert_equal 5, first_five_developers.length
413    assert_equal 'David', first_five_developers.first.name
414    assert_equal 'fixture_5', first_five_developers.last.name
415   
416    no_developers = Developer.find :all, :order => 'id ASC', :limit => 0
417    assert_equal 0, no_developers.length
418  end
419
420  def test_find_all_with_limit_and_offset
421    first_three_developers = Developer.find :all, :order => 'id ASC', :limit => 3, :offset => 0
422    second_three_developers = Developer.find :all, :order => 'id ASC', :limit => 3, :offset => 3
423    last_two_developers = Developer.find :all, :order => 'id ASC', :limit => 2, :offset => 8
424   
425    assert_equal 3, first_three_developers.length
426    assert_equal 3, second_three_developers.length
427    assert_equal 2, last_two_developers.length
428   
429    assert_equal 'David', first_three_developers.first.name
430    assert_equal 'fixture_4', second_three_developers.first.name
431    assert_equal 'fixture_9', last_two_developers.first.name
432  end
433
434  def test_find_all_with_limit_and_offset_and_multiple_order_clauses
435    first_three_posts = Post.find :all, :order => 'author_id, id', :limit => 3, :offset => 0
436    second_three_posts = Post.find :all, :order => ' author_id,id ', :limit => 3, :offset => 3
437    last_posts = Post.find :all, :order => ' author_id, id  ', :limit => 3, :offset => 6
438
439    assert_equal [[0,3],[1,1],[1,2]], first_three_posts.map { |p| [p.author_id, p.id] }
440    assert_equal [[1,4],[1,5],[1,6]], second_three_posts.map { |p| [p.author_id, p.id] }
441    assert_equal [[2,7]], last_posts.map { |p| [p.author_id, p.id] }
442  end
443
444  def test_find_all_with_join
445    developers_on_project_one = Developer.find(
446      :all,
447      :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id',
448      :conditions => 'project_id=1'
449    )
450    assert_equal 3, developers_on_project_one.length
451    developer_names = developers_on_project_one.map { |d| d.name }
452    assert developer_names.include?('David')
453    assert developer_names.include?('Jamis')
454  end
455
456  def test_find_by_id_with_conditions_with_or
457    assert_nothing_raised do
458      Post.find([1,2,3],
459        :conditions => "posts.id <= 3 OR posts.#{QUOTED_TYPE} = 'Post'")
460    end
461  end
462
463  # http://dev.rubyonrails.org/ticket/6778
464  def test_find_ignores_previously_inserted_record
465    post = Post.create!(:title => 'test', :body => 'it out')
466    assert_equal [], Post.find_all_by_id(nil)
467  end
468
469  def test_find_by_empty_ids
470    assert_equal [], Post.find([])
471  end
472
473  def test_find_by_empty_in_condition
474    assert_equal [], Post.find(:all, :conditions => ['id in (?)', []])
475  end
476
477  def test_find_by_records
478    p1, p2 = Post.find(:all, :limit => 2, :order => 'id asc')
479    assert_equal [p1, p2], Post.find(:all, :conditions => ['id in (?)', [p1, p2]], :order => 'id asc')
480    assert_equal [p1, p2], Post.find(:all, :conditions => ['id in (?)', [p1, p2.id]], :order => 'id asc')
481  end
482
483  def test_select_value
484    assert_equal "37signals", Company.connection.select_value("SELECT name FROM companies WHERE id = 1")
485    assert_nil Company.connection.select_value("SELECT name FROM companies WHERE id = -1")
486    # make sure we didn't break count...
487    assert_equal 0, Company.count_by_sql("SELECT COUNT(*) FROM companies WHERE name = 'Halliburton'")
488    assert_equal 1, Company.count_by_sql("SELECT COUNT(*) FROM companies WHERE name = '37signals'")
489  end
490
491  def test_select_values
492    assert_equal ["1","2","3","4","5","6","7","8","9"], Company.connection.select_values("SELECT id FROM companies ORDER BY id").map! { |i| i.to_s }
493    assert_equal ["37signals","Summit","Microsoft", "Flamboyant Software", "Ex Nihilo", "RailsCore", "Leetsoft", "Jadedpixel", "Odegy"], Company.connection.select_values("SELECT name FROM companies ORDER BY id")
494  end
495
496  protected
497    def bind(statement, *vars)
498      if vars.first.is_a?(Hash)
499        ActiveRecord::Base.send(:replace_named_bind_variables, statement, vars.first)
500      else
501        ActiveRecord::Base.send(:replace_bind_variables, statement, vars)
502      end
503    end
504end
Note: See TracBrowser for help on using the browser.