PageRenderTime 45ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/rails/activerecord/test/fixtures_test.rb

https://github.com/dharmon/insoshi
Ruby | 602 lines | 473 code | 115 blank | 14 comment | 5 complexity | 9ab986eabf81f056a8bf2db29f96e9ae MD5 | raw file
Possible License(s): AGPL-3.0, GPL-2.0, MIT
  1. require 'abstract_unit'
  2. require 'fixtures/post'
  3. require 'fixtures/binary'
  4. require 'fixtures/topic'
  5. require 'fixtures/computer'
  6. require 'fixtures/developer'
  7. require 'fixtures/company'
  8. require 'fixtures/task'
  9. require 'fixtures/reply'
  10. require 'fixtures/joke'
  11. require 'fixtures/course'
  12. require 'fixtures/category'
  13. require 'fixtures/parrot'
  14. require 'fixtures/pirate'
  15. require 'fixtures/treasure'
  16. require 'fixtures/matey'
  17. require 'fixtures/ship'
  18. class FixturesTest < Test::Unit::TestCase
  19. self.use_instantiated_fixtures = true
  20. self.use_transactional_fixtures = false
  21. fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries
  22. FIXTURES = %w( accounts binaries companies customers
  23. developers developers_projects entrants
  24. movies projects subscribers topics tasks )
  25. MATCH_ATTRIBUTE_NAME = /[a-zA-Z][-_\w]*/
  26. BINARY_FIXTURE_PATH = File.dirname(__FILE__) + '/fixtures/flowers.jpg'
  27. def test_clean_fixtures
  28. FIXTURES.each do |name|
  29. fixtures = nil
  30. assert_nothing_raised { fixtures = create_fixtures(name) }
  31. assert_kind_of(Fixtures, fixtures)
  32. fixtures.each { |name, fixture|
  33. fixture.each { |key, value|
  34. assert_match(MATCH_ATTRIBUTE_NAME, key)
  35. }
  36. }
  37. end
  38. end
  39. def test_multiple_clean_fixtures
  40. fixtures_array = nil
  41. assert_nothing_raised { fixtures_array = create_fixtures(*FIXTURES) }
  42. assert_kind_of(Array, fixtures_array)
  43. fixtures_array.each { |fixtures| assert_kind_of(Fixtures, fixtures) }
  44. end
  45. def test_attributes
  46. topics = create_fixtures("topics")
  47. assert_equal("The First Topic", topics["first"]["title"])
  48. assert_nil(topics["second"]["author_email_address"])
  49. end
  50. def test_inserts
  51. topics = create_fixtures("topics")
  52. first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM topics WHERE author_name = 'David'")
  53. assert_equal("The First Topic", first_row["title"])
  54. second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM topics WHERE author_name = 'Mary'")
  55. assert_nil(second_row["author_email_address"])
  56. end
  57. if ActiveRecord::Base.connection.supports_migrations?
  58. def test_inserts_with_pre_and_suffix
  59. # Reset cache to make finds on the new table work
  60. Fixtures.reset_cache
  61. ActiveRecord::Base.connection.create_table :prefix_topics_suffix do |t|
  62. t.column :title, :string
  63. t.column :author_name, :string
  64. t.column :author_email_address, :string
  65. t.column :written_on, :datetime
  66. t.column :bonus_time, :time
  67. t.column :last_read, :date
  68. t.column :content, :string
  69. t.column :approved, :boolean, :default => true
  70. t.column :replies_count, :integer, :default => 0
  71. t.column :parent_id, :integer
  72. t.column :type, :string, :limit => 50
  73. end
  74. # Store existing prefix/suffix
  75. old_prefix = ActiveRecord::Base.table_name_prefix
  76. old_suffix = ActiveRecord::Base.table_name_suffix
  77. # Set a prefix/suffix we can test against
  78. ActiveRecord::Base.table_name_prefix = 'prefix_'
  79. ActiveRecord::Base.table_name_suffix = '_suffix'
  80. topics = create_fixtures("topics")
  81. first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_topics_suffix WHERE author_name = 'David'")
  82. assert_equal("The First Topic", first_row["title"])
  83. second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_topics_suffix WHERE author_name = 'Mary'")
  84. assert_nil(second_row["author_email_address"])
  85. ensure
  86. # Restore prefix/suffix to its previous values
  87. ActiveRecord::Base.table_name_prefix = old_prefix
  88. ActiveRecord::Base.table_name_suffix = old_suffix
  89. ActiveRecord::Base.connection.drop_table :prefix_topics_suffix rescue nil
  90. end
  91. end
  92. def test_insert_with_datetime
  93. topics = create_fixtures("tasks")
  94. first = Task.find(1)
  95. assert first
  96. end
  97. def test_bad_format
  98. path = File.join(File.dirname(__FILE__), 'fixtures', 'bad_fixtures')
  99. Dir.entries(path).each do |file|
  100. next unless File.file?(file) and file !~ Fixtures::DEFAULT_FILTER_RE
  101. assert_raise(Fixture::FormatError) {
  102. Fixture.new(bad_fixtures_path, file)
  103. }
  104. end
  105. end
  106. def test_deprecated_yaml_extension
  107. assert_raise(Fixture::FormatError) {
  108. Fixtures.new(nil, 'bad_extension', 'BadExtension', File.join(File.dirname(__FILE__), 'fixtures'))
  109. }
  110. end
  111. def test_logger_level_invariant
  112. level = ActiveRecord::Base.logger.level
  113. create_fixtures('topics')
  114. assert_equal level, ActiveRecord::Base.logger.level
  115. end
  116. def test_instantiation
  117. topics = create_fixtures("topics")
  118. assert_kind_of Topic, topics["first"].find
  119. end
  120. def test_complete_instantiation
  121. assert_equal 2, @topics.size
  122. assert_equal "The First Topic", @first.title
  123. end
  124. def test_fixtures_from_root_yml_with_instantiation
  125. # assert_equal 2, @accounts.size
  126. assert_equal 50, @unknown.credit_limit
  127. end
  128. def test_erb_in_fixtures
  129. assert_equal 11, @developers.size
  130. assert_equal "fixture_5", @dev_5.name
  131. end
  132. def test_empty_yaml_fixture
  133. assert_not_nil Fixtures.new( Account.connection, "accounts", 'Account', File.dirname(__FILE__) + "/fixtures/naked/yml/accounts")
  134. end
  135. def test_empty_yaml_fixture_with_a_comment_in_it
  136. assert_not_nil Fixtures.new( Account.connection, "companies", 'Company', File.dirname(__FILE__) + "/fixtures/naked/yml/companies")
  137. end
  138. def test_dirty_dirty_yaml_file
  139. assert_raises(Fixture::FormatError) do
  140. Fixtures.new( Account.connection, "courses", 'Course', File.dirname(__FILE__) + "/fixtures/naked/yml/courses")
  141. end
  142. end
  143. def test_empty_csv_fixtures
  144. assert_not_nil Fixtures.new( Account.connection, "accounts", 'Account', File.dirname(__FILE__) + "/fixtures/naked/csv/accounts")
  145. end
  146. def test_omap_fixtures
  147. assert_nothing_raised do
  148. fixtures = Fixtures.new(Account.connection, 'categories', 'Category', File.dirname(__FILE__) + '/fixtures/categories_ordered')
  149. i = 0
  150. fixtures.each do |name, fixture|
  151. assert_equal "fixture_no_#{i}", name
  152. assert_equal "Category #{i}", fixture['name']
  153. i += 1
  154. end
  155. end
  156. end
  157. def test_yml_file_in_subdirectory
  158. assert_equal(categories(:sub_special_1).name, "A special category in a subdir file")
  159. assert_equal(categories(:sub_special_1).class, SpecialCategory)
  160. end
  161. def test_subsubdir_file_with_arbitrary_name
  162. assert_equal(categories(:sub_special_3).name, "A special category in an arbitrarily named subsubdir file")
  163. assert_equal(categories(:sub_special_3).class, SpecialCategory)
  164. end
  165. def test_binary_in_fixtures
  166. assert_equal 1, @binaries.size
  167. data = File.open(BINARY_FIXTURE_PATH, "rb").read.freeze
  168. assert_equal data, @flowers.data
  169. end
  170. end
  171. if Account.connection.respond_to?(:reset_pk_sequence!)
  172. class FixturesResetPkSequenceTest < Test::Unit::TestCase
  173. fixtures :accounts
  174. fixtures :companies
  175. def setup
  176. @instances = [Account.new(:credit_limit => 50), Company.new(:name => 'RoR Consulting')]
  177. Fixtures.reset_cache # make sure tables get reinitialized
  178. end
  179. def test_resets_to_min_pk_with_specified_pk_and_sequence
  180. @instances.each do |instance|
  181. model = instance.class
  182. model.delete_all
  183. model.connection.reset_pk_sequence!(model.table_name, model.primary_key, model.sequence_name)
  184. instance.save!
  185. assert_equal 1, instance.id, "Sequence reset for #{model.table_name} failed."
  186. end
  187. end
  188. def test_resets_to_min_pk_with_default_pk_and_sequence
  189. @instances.each do |instance|
  190. model = instance.class
  191. model.delete_all
  192. model.connection.reset_pk_sequence!(model.table_name)
  193. instance.save!
  194. assert_equal 1, instance.id, "Sequence reset for #{model.table_name} failed."
  195. end
  196. end
  197. def test_create_fixtures_resets_sequences_when_not_cached
  198. @instances.each do |instance|
  199. max_id = create_fixtures(instance.class.table_name).inject(0) do |max_id, (name, fixture)|
  200. fixture_id = fixture['id'].to_i
  201. fixture_id > max_id ? fixture_id : max_id
  202. end
  203. # Clone the last fixture to check that it gets the next greatest id.
  204. instance.save!
  205. assert_equal max_id + 1, instance.id, "Sequence reset for #{instance.class.table_name} failed."
  206. end
  207. end
  208. end
  209. end
  210. class FixturesWithoutInstantiationTest < Test::Unit::TestCase
  211. self.use_instantiated_fixtures = false
  212. fixtures :topics, :developers, :accounts
  213. def test_without_complete_instantiation
  214. assert_nil @first
  215. assert_nil @topics
  216. assert_nil @developers
  217. assert_nil @accounts
  218. end
  219. def test_fixtures_from_root_yml_without_instantiation
  220. assert_nil @unknown
  221. end
  222. def test_accessor_methods
  223. assert_equal "The First Topic", topics(:first).title
  224. assert_equal "Jamis", developers(:jamis).name
  225. assert_equal 50, accounts(:signals37).credit_limit
  226. end
  227. def test_accessor_methods_with_multiple_args
  228. assert_equal 2, topics(:first, :second).size
  229. assert_raise(StandardError) { topics([:first, :second]) }
  230. end
  231. uses_mocha 'reloading_fixtures_through_accessor_methods' do
  232. def test_reloading_fixtures_through_accessor_methods
  233. assert_equal "The First Topic", topics(:first).title
  234. @loaded_fixtures['topics']['first'].expects(:find).returns(stub(:title => "Fresh Topic!"))
  235. assert_equal "Fresh Topic!", topics(:first, true).title
  236. end
  237. end
  238. end
  239. class FixturesWithoutInstanceInstantiationTest < Test::Unit::TestCase
  240. self.use_instantiated_fixtures = true
  241. self.use_instantiated_fixtures = :no_instances
  242. fixtures :topics, :developers, :accounts
  243. def test_without_instance_instantiation
  244. assert_nil @first
  245. assert_not_nil @topics
  246. assert_not_nil @developers
  247. assert_not_nil @accounts
  248. end
  249. end
  250. class TransactionalFixturesTest < Test::Unit::TestCase
  251. self.use_instantiated_fixtures = true
  252. self.use_transactional_fixtures = true
  253. fixtures :topics
  254. def test_destroy
  255. assert_not_nil @first
  256. @first.destroy
  257. end
  258. def test_destroy_just_kidding
  259. assert_not_nil @first
  260. end
  261. end
  262. class MultipleFixturesTest < Test::Unit::TestCase
  263. fixtures :topics
  264. fixtures :developers, :accounts
  265. def test_fixture_table_names
  266. assert_equal %w(topics developers accounts), fixture_table_names
  267. end
  268. end
  269. # This is to reproduce a bug where if a TestCase is loaded
  270. # twice by Ruby, it loses its fixture setup hook.
  271. class_def = <<-CODE
  272. class DoubleLoadedTestCase < Test::Unit::TestCase
  273. fixtures :topics
  274. def setup
  275. end
  276. def test_should_properly_setup_fixtures
  277. assert_nothing_raised { topics(:first) }
  278. end
  279. end
  280. CODE
  281. 2.times { eval(class_def) }
  282. class OverlappingFixturesTest < Test::Unit::TestCase
  283. fixtures :topics, :developers
  284. fixtures :developers, :accounts
  285. def test_fixture_table_names
  286. assert_equal %w(topics developers accounts), fixture_table_names
  287. end
  288. end
  289. class ForeignKeyFixturesTest < Test::Unit::TestCase
  290. fixtures :fk_test_has_pk, :fk_test_has_fk
  291. # if foreign keys are implemented and fixtures
  292. # are not deleted in reverse order then this test
  293. # case will raise StatementInvalid
  294. def test_number1
  295. assert true
  296. end
  297. def test_number2
  298. assert true
  299. end
  300. end
  301. class SetTableNameFixturesTest < Test::Unit::TestCase
  302. set_fixture_class :funny_jokes => 'Joke'
  303. fixtures :funny_jokes
  304. def test_table_method
  305. assert_kind_of Joke, funny_jokes(:a_joke)
  306. end
  307. end
  308. class CustomConnectionFixturesTest < Test::Unit::TestCase
  309. set_fixture_class :courses => Course
  310. fixtures :courses
  311. def test_connection
  312. assert_kind_of Course, courses(:ruby)
  313. assert_equal Course.connection, courses(:ruby).connection
  314. end
  315. end
  316. class InvalidTableNameFixturesTest < Test::Unit::TestCase
  317. fixtures :funny_jokes
  318. def test_raises_error
  319. assert_raises FixtureClassNotFound do
  320. funny_jokes(:a_joke)
  321. end
  322. end
  323. end
  324. class CheckEscapedYamlFixturesTest < Test::Unit::TestCase
  325. set_fixture_class :funny_jokes => 'Joke'
  326. fixtures :funny_jokes
  327. def test_proper_escaped_fixture
  328. assert_equal "The \\n Aristocrats\nAte the candy\n", funny_jokes(:another_joke).name
  329. end
  330. end
  331. class DevelopersProject; end
  332. class ManyToManyFixturesWithClassDefined < Test::Unit::TestCase
  333. fixtures :developers_projects
  334. def test_this_should_run_cleanly
  335. assert true
  336. end
  337. end
  338. class FixturesBrokenRollbackTest < Test::Unit::TestCase
  339. def blank_setup; end
  340. alias_method :ar_setup_with_fixtures, :setup_with_fixtures
  341. alias_method :setup_with_fixtures, :blank_setup
  342. alias_method :setup, :blank_setup
  343. def blank_teardown; end
  344. alias_method :ar_teardown_with_fixtures, :teardown_with_fixtures
  345. alias_method :teardown_with_fixtures, :blank_teardown
  346. alias_method :teardown, :blank_teardown
  347. def test_no_rollback_in_teardown_unless_transaction_active
  348. assert_equal 0, Thread.current['open_transactions']
  349. assert_raise(RuntimeError) { ar_setup_with_fixtures }
  350. assert_equal 0, Thread.current['open_transactions']
  351. assert_nothing_raised { ar_teardown_with_fixtures }
  352. assert_equal 0, Thread.current['open_transactions']
  353. end
  354. private
  355. def load_fixtures
  356. raise 'argh'
  357. end
  358. end
  359. class LoadAllFixturesTest < Test::Unit::TestCase
  360. self.fixture_path= File.join(File.dirname(__FILE__), '/fixtures/all')
  361. fixtures :all
  362. def test_all_there
  363. assert_equal %w(developers people tasks), fixture_table_names.sort
  364. end
  365. end
  366. class FasterFixturesTest < Test::Unit::TestCase
  367. fixtures :categories, :authors
  368. def load_extra_fixture(name)
  369. fixture = create_fixtures(name)
  370. assert fixture.is_a?(Fixtures)
  371. @loaded_fixtures[fixture.table_name] = fixture
  372. end
  373. def test_cache
  374. assert Fixtures.fixture_is_cached?(ActiveRecord::Base.connection, 'categories')
  375. assert Fixtures.fixture_is_cached?(ActiveRecord::Base.connection, 'authors')
  376. assert_no_queries do
  377. create_fixtures('categories')
  378. create_fixtures('authors')
  379. end
  380. load_extra_fixture('posts')
  381. assert Fixtures.fixture_is_cached?(ActiveRecord::Base.connection, 'posts')
  382. self.class.setup_fixture_accessors('posts')
  383. assert_equal 'Welcome to the weblog', posts(:welcome).title
  384. end
  385. end
  386. class FoxyFixturesTest < Test::Unit::TestCase
  387. fixtures :parrots, :parrots_pirates, :pirates, :treasures, :mateys, :ships, :computers, :developers
  388. def test_identifies_strings
  389. assert_equal(Fixtures.identify("foo"), Fixtures.identify("foo"))
  390. assert_not_equal(Fixtures.identify("foo"), Fixtures.identify("FOO"))
  391. end
  392. def test_identifies_symbols
  393. assert_equal(Fixtures.identify(:foo), Fixtures.identify(:foo))
  394. end
  395. TIMESTAMP_COLUMNS = %w(created_at created_on updated_at updated_on)
  396. def test_populates_timestamp_columns
  397. TIMESTAMP_COLUMNS.each do |property|
  398. assert_not_nil(parrots(:george).send(property), "should set #{property}")
  399. end
  400. end
  401. def test_does_not_populate_timestamp_columns_if_model_has_set_record_timestamps_to_false
  402. TIMESTAMP_COLUMNS.each do |property|
  403. assert_nil(ships(:black_pearl).send(property), "should not set #{property}")
  404. end
  405. end
  406. def test_populates_all_columns_with_the_same_time
  407. last = nil
  408. TIMESTAMP_COLUMNS.each do |property|
  409. current = parrots(:george).send(property)
  410. last ||= current
  411. assert_equal(last, current)
  412. last = current
  413. end
  414. end
  415. def test_only_populates_columns_that_exist
  416. assert_not_nil(pirates(:blackbeard).created_on)
  417. assert_not_nil(pirates(:blackbeard).updated_on)
  418. end
  419. def test_preserves_existing_fixture_data
  420. assert_equal(2.weeks.ago.to_date, pirates(:redbeard).created_on.to_date)
  421. assert_equal(2.weeks.ago.to_date, pirates(:redbeard).updated_on.to_date)
  422. end
  423. def test_generates_unique_ids
  424. assert_not_nil(parrots(:george).id)
  425. assert_not_equal(parrots(:george).id, parrots(:louis).id)
  426. end
  427. def test_automatically_sets_primary_key
  428. assert_not_nil(ships(:black_pearl))
  429. end
  430. def test_preserves_existing_primary_key
  431. assert_equal(2, ships(:interceptor).id)
  432. end
  433. def test_resolves_belongs_to_symbols
  434. assert_equal(parrots(:george), pirates(:blackbeard).parrot)
  435. end
  436. def test_ignores_belongs_to_symbols_if_association_and_foreign_key_are_named_the_same
  437. assert_equal(developers(:david), computers(:workstation).developer)
  438. end
  439. def test_supports_join_tables
  440. assert(pirates(:blackbeard).parrots.include?(parrots(:george)))
  441. assert(pirates(:blackbeard).parrots.include?(parrots(:louis)))
  442. assert(parrots(:george).pirates.include?(pirates(:blackbeard)))
  443. end
  444. def test_supports_inline_habtm
  445. assert(parrots(:george).treasures.include?(treasures(:diamond)))
  446. assert(parrots(:george).treasures.include?(treasures(:sapphire)))
  447. assert(!parrots(:george).treasures.include?(treasures(:ruby)))
  448. end
  449. def test_supports_inline_habtm_with_specified_id
  450. assert(parrots(:polly).treasures.include?(treasures(:ruby)))
  451. assert(parrots(:polly).treasures.include?(treasures(:sapphire)))
  452. assert(!parrots(:polly).treasures.include?(treasures(:diamond)))
  453. end
  454. def test_supports_yaml_arrays
  455. assert(parrots(:louis).treasures.include?(treasures(:diamond)))
  456. assert(parrots(:louis).treasures.include?(treasures(:sapphire)))
  457. end
  458. def test_strips_DEFAULTS_key
  459. assert_raise(StandardError) { parrots(:DEFAULTS) }
  460. # this lets us do YAML defaults and not have an extra fixture entry
  461. %w(sapphire ruby).each { |t| assert(parrots(:davey).treasures.include?(treasures(t))) }
  462. end
  463. def test_supports_label_interpolation
  464. assert_equal("frederick", parrots(:frederick).name)
  465. end
  466. def test_supports_polymorphic_belongs_to
  467. assert_equal(pirates(:redbeard), treasures(:sapphire).looter)
  468. assert_equal(parrots(:louis), treasures(:ruby).looter)
  469. end
  470. def test_only_generates_a_pk_if_necessary
  471. m = Matey.find(:first)
  472. m.pirate = pirates(:blackbeard)
  473. m.target = pirates(:redbeard)
  474. end
  475. def test_supports_sti
  476. assert_kind_of DeadParrot, parrots(:polly)
  477. assert_equal pirates(:blackbeard), parrots(:polly).killer
  478. end
  479. end
  480. class ActiveSupportSubclassWithFixturesTest < ActiveSupport::TestCase
  481. fixtures :parrots
  482. # This seemingly useless assertion catches a bug that caused the fixtures
  483. # setup code call nil[]
  484. def test_foo
  485. assert_equal parrots(:louis), Parrot.find_by_name("King Louis")
  486. end
  487. end