PageRenderTime 48ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/rails/activerecord/test/finder_test.rb

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