Index: activerecord/test/test_helper.rb =================================================================== --- activerecord/test/test_helper.rb (revision 0) +++ activerecord/test/test_helper.rb (revision 0) @@ -0,0 +1,93 @@ +AR_SUPPORT_PATH = File.expand_path(File.dirname(__FILE__) + "/support") +AR_ASSETS_PATH = AR_SUPPORT_PATH + "/assets" +AR_FIXTURES_PATH = AR_SUPPORT_PATH + "/fixtures" +AR_MIGRATIONS_PATH = AR_SUPPORT_PATH + "/migrations" +AR_MODELS_PATH = AR_SUPPORT_PATH + "/models" +AR_SCHEMA_PATH = AR_SUPPORT_PATH + "/schema" + +["/../lib", "/../../activesupport/lib"].each do |path| + $:.unshift(File.expand_path(File.dirname(__FILE__) + path)) +end + +# for access to test models +$:.unshift(AR_SUPPORT_PATH) + +require "test/unit" +require "active_record" +require "active_record/fixtures" +require "active_support/test_case" +require "connection" + +# Show backtraces for deprecated behavior for quicker cleanup. +ActiveSupport::Deprecation.debug = true + +unless Object.const_defined?(:QUOTED_TYPE) + QUOTED_TYPE = ActiveRecord::Base.connection.quote_column_name("type") +end + +class ActiveSupport::TestCase #:nodoc: + self.fixture_path = AR_FIXTURES_PATH + self.use_instantiated_fixtures = false + self.use_transactional_fixtures = true + + def create_fixtures(*table_names, &block) + Fixtures.create_fixtures(AR_FIXTURES_PATH, table_names, {}, &block) + end + + def assert_date_from_db(expected, actual, message = nil) + # SQL Server doesn't have a separate column type just for dates, + # so the time is in the string and incorrectly formatted + if current_adapter?(:SQLServerAdapter) + assert_equal expected.strftime("%Y/%m/%d 00:00:00"), actual.strftime("%Y/%m/%d 00:00:00") + elsif current_adapter?(:SybaseAdapter) + assert_equal expected.to_s, actual.to_date.to_s, message + else + assert_equal expected.to_s, actual.to_s, message + end + end + + def assert_queries(num = 1) + $query_count = 0 + yield + ensure + assert_equal num, $query_count, "#{$query_count} instead of #{num} queries were executed." + end + + def assert_no_queries(&block) + assert_queries(0, &block) + end +end + +def current_adapter?(*types) + types.any? do |type| + ActiveRecord::ConnectionAdapters.const_defined?(type) && + ActiveRecord::Base.connection.is_a?(ActiveRecord::ConnectionAdapters.const_get(type)) + end +end + +def uses_mocha(test_name) + require 'rubygems' + require 'mocha' + yield +rescue LoadError + $stderr.puts "Skipping #{test_name} tests. `gem install mocha` and try again." +end + +ActiveRecord::Base.connection.class.class_eval do + unless defined? IGNORED_SQL + IGNORED_SQL = [/^PRAGMA/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/] + + def execute_with_counting(sql, name = nil, &block) + $query_count ||= 0 + $query_count += 1 unless IGNORED_SQL.any? { |r| sql =~ r } + execute_without_counting(sql, name, &block) + end + + alias_method_chain :execute, :counting + end +end + +# Make with_scope public for tests +class << ActiveRecord::Base + public :with_scope, :with_exclusive_scope +end Index: activerecord/test/all.sh =================================================================== --- activerecord/test/all.sh (revision 8601) +++ activerecord/test/all.sh (working copy) @@ -1,8 +0,0 @@ -#!/bin/sh - -if [ -z "$1" ]; then - echo "Usage: $0 " 1>&2 - exit 1 -fi - -ruby -I connections/native_$1 -e 'Dir["**/*_test.rb"].each { |path| require path }' Index: activerecord/test/connections/native_openbase/connection.rb =================================================================== --- activerecord/test/connections/native_openbase/connection.rb (revision 8601) +++ activerecord/test/connections/native_openbase/connection.rb (working copy) @@ -1,21 +0,0 @@ -print "Using native OpenBase\n" -require_dependency 'fixtures/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'openbase', - :username => 'admin', - :database => 'activerecord_unittest', - }, - 'arunit2' => { - :adapter => 'openbase', - :username => 'admin', - :database => 'activerecord_unittest2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' Index: activerecord/test/connections/native_sqlite/connection.rb =================================================================== --- activerecord/test/connections/native_sqlite/connection.rb (revision 8601) +++ activerecord/test/connections/native_sqlite/connection.rb (working copy) @@ -1,25 +0,0 @@ -print "Using native SQlite\n" -require_dependency 'fixtures/course' -require 'logger' -ActiveRecord::Base.logger = Logger.new("debug.log") - -class SqliteError < StandardError -end - -BASE_DIR = File.expand_path(File.dirname(__FILE__) + '/../../fixtures') -sqlite_test_db = "#{BASE_DIR}/fixture_database.sqlite" -sqlite_test_db2 = "#{BASE_DIR}/fixture_database_2.sqlite" - -def make_connection(clazz, db_file) - ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'sqlite', :database => db_file } } - unless File.exist?(db_file) - puts "SQLite database not found at #{db_file}. Rebuilding it." - sqlite_command = %Q{sqlite "#{db_file}" "create table a (a integer); drop table a;"} - puts "Executing '#{sqlite_command}'" - raise SqliteError.new("Seems that there is no sqlite executable available") unless system(sqlite_command) - end - clazz.establish_connection(clazz.name) -end - -make_connection(ActiveRecord::Base, sqlite_test_db) -make_connection(Course, sqlite_test_db2) Index: activerecord/test/connections/native_frontbase/connection.rb =================================================================== --- activerecord/test/connections/native_frontbase/connection.rb (revision 8601) +++ activerecord/test/connections/native_frontbase/connection.rb (working copy) @@ -1,27 +0,0 @@ -puts 'Using native Frontbase' -require_dependency 'fixtures/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'frontbase', - :host => 'localhost', - :username => 'rails', - :password => '', - :database => 'activerecord_unittest', - :session_name => "unittest-#{$$}" - }, - 'arunit2' => { - :adapter => 'frontbase', - :host => 'localhost', - :username => 'rails', - :password => '', - :database => 'activerecord_unittest2', - :session_name => "unittest-#{$$}" - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' Index: activerecord/test/connections/native_postgresql/connection.rb =================================================================== --- activerecord/test/connections/native_postgresql/connection.rb (revision 8601) +++ activerecord/test/connections/native_postgresql/connection.rb (working copy) @@ -1,23 +0,0 @@ -print "Using native PostgreSQL\n" -require_dependency 'fixtures/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'postgresql', - :username => 'postgres', - :database => 'activerecord_unittest', - :min_messages => 'warning' - }, - 'arunit2' => { - :adapter => 'postgresql', - :username => 'postgres', - :database => 'activerecord_unittest2', - :min_messages => 'warning' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' Index: activerecord/test/connections/native_sqlite3/in_memory_connection.rb =================================================================== --- activerecord/test/connections/native_sqlite3/in_memory_connection.rb (revision 8601) +++ activerecord/test/connections/native_sqlite3/in_memory_connection.rb (working copy) @@ -1,18 +0,0 @@ -print "Using native SQLite3\n" -require_dependency 'fixtures/course' -require 'logger' -ActiveRecord::Base.logger = Logger.new("debug.log") - -class SqliteError < StandardError -end - -def make_connection(clazz, db_definitions_file) - clazz.establish_connection(:adapter => 'sqlite3', :database => ':memory:') - File.read("#{File.dirname(__FILE__)}/../../fixtures/db_definitions/#{db_definitions_file}").split(';').each do |command| - clazz.connection.execute(command) unless command.strip.empty? - end -end - -make_connection(ActiveRecord::Base, 'sqlite.sql') -make_connection(Course, 'sqlite2.sql') -load("#{File.dirname(__FILE__)}/../../fixtures/db_definitions/schema.rb") Index: activerecord/test/connections/native_sqlite3/connection.rb =================================================================== --- activerecord/test/connections/native_sqlite3/connection.rb (revision 8601) +++ activerecord/test/connections/native_sqlite3/connection.rb (working copy) @@ -1,25 +0,0 @@ -print "Using native SQLite3\n" -require_dependency 'fixtures/course' -require 'logger' -ActiveRecord::Base.logger = Logger.new("debug.log") - -class SqliteError < StandardError -end - -BASE_DIR = File.expand_path(File.dirname(__FILE__) + '/../../fixtures') -sqlite_test_db = "#{BASE_DIR}/fixture_database.sqlite3" -sqlite_test_db2 = "#{BASE_DIR}/fixture_database_2.sqlite3" - -def make_connection(clazz, db_file) - ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'sqlite3', :database => db_file, :timeout => 5000 } } - unless File.exist?(db_file) - puts "SQLite3 database not found at #{db_file}. Rebuilding it." - sqlite_command = %Q{sqlite3 "#{db_file}" "create table a (a integer); drop table a;"} - puts "Executing '#{sqlite_command}'" - raise SqliteError.new("Seems that there is no sqlite3 executable available") unless system(sqlite_command) - end - clazz.establish_connection(clazz.name) -end - -make_connection(ActiveRecord::Base, sqlite_test_db) -make_connection(Course, sqlite_test_db2) Index: activerecord/test/connections/native_mysql/connection.rb =================================================================== --- activerecord/test/connections/native_mysql/connection.rb (revision 8601) +++ activerecord/test/connections/native_mysql/connection.rb (working copy) @@ -1,27 +0,0 @@ -print "Using native MySQL\n" -require_dependency 'fixtures/course' -require 'logger' - -RAILS_DEFAULT_LOGGER = Logger.new('debug.log') -RAILS_DEFAULT_LOGGER.level = Logger::DEBUG -ActiveRecord::Base.logger = RAILS_DEFAULT_LOGGER - -# GRANT ALL PRIVILEGES ON activerecord_unittest.* to 'rails'@'localhost'; -# GRANT ALL PRIVILEGES ON activerecord_unittest2.* to 'rails'@'localhost'; - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'mysql', - :username => 'rails', - :encoding => 'utf8', - :database => 'activerecord_unittest', - }, - 'arunit2' => { - :adapter => 'mysql', - :username => 'rails', - :database => 'activerecord_unittest2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' Index: activerecord/test/connections/native_oracle/connection.rb =================================================================== --- activerecord/test/connections/native_oracle/connection.rb (revision 8601) +++ activerecord/test/connections/native_oracle/connection.rb (working copy) @@ -1,27 +0,0 @@ -print "Using Oracle\n" -require_dependency 'fixtures/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new STDOUT -ActiveRecord::Base.logger.level = Logger::WARN - -# Set these to your database connection strings -db = ENV['ARUNIT_DB'] || 'activerecord_unittest' - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'oracle', - :username => 'arunit', - :password => 'arunit', - :database => db, - }, - 'arunit2' => { - :adapter => 'oracle', - :username => 'arunit2', - :password => 'arunit2', - :database => db - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' Index: activerecord/test/connections/native_firebird/connection.rb =================================================================== --- activerecord/test/connections/native_firebird/connection.rb (revision 8601) +++ activerecord/test/connections/native_firebird/connection.rb (working copy) @@ -1,26 +0,0 @@ -print "Using native Firebird\n" -require_dependency 'fixtures/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'firebird', - :host => 'localhost', - :username => 'rails', - :password => 'rails', - :database => 'activerecord_unittest', - :charset => 'UTF8' - }, - 'arunit2' => { - :adapter => 'firebird', - :host => 'localhost', - :username => 'rails', - :password => 'rails', - :database => 'activerecord_unittest2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' Index: activerecord/test/connections/native_sybase/connection.rb =================================================================== --- activerecord/test/connections/native_sybase/connection.rb (revision 8601) +++ activerecord/test/connections/native_sybase/connection.rb (working copy) @@ -1,23 +0,0 @@ -print "Using native Sybase Open Client\n" -require_dependency 'fixtures/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'sybase', - :host => 'database_ASE', - :username => 'sa', - :database => 'activerecord_unittest' - }, - 'arunit2' => { - :adapter => 'sybase', - :host => 'database_ASE', - :username => 'sa', - :database => 'activerecord_unittest2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' Index: activerecord/test/connections/native_db2/connection.rb =================================================================== --- activerecord/test/connections/native_db2/connection.rb (revision 8601) +++ activerecord/test/connections/native_db2/connection.rb (working copy) @@ -1,25 +0,0 @@ -print "Using native DB2\n" -require_dependency 'fixtures/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'db2', - :host => 'localhost', - :username => 'arunit', - :password => 'arunit', - :database => 'arunit' - }, - 'arunit2' => { - :adapter => 'db2', - :host => 'localhost', - :username => 'arunit', - :password => 'arunit', - :database => 'arunit2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' Index: activerecord/test/ar_schema_test.rb =================================================================== --- activerecord/test/ar_schema_test.rb (revision 8601) +++ activerecord/test/ar_schema_test.rb (working copy) @@ -1,33 +0,0 @@ -require 'abstract_unit' -require "#{File.dirname(__FILE__)}/../lib/active_record/schema" - -if ActiveRecord::Base.connection.supports_migrations? - - class ActiveRecordSchemaTest < ActiveSupport::TestCase - self.use_transactional_fixtures = false - - def setup - @connection = ActiveRecord::Base.connection - end - - def teardown - @connection.drop_table :fruits rescue nil - end - - def test_schema_define - ActiveRecord::Schema.define(:version => 7) do - create_table :fruits do |t| - t.column :color, :string - t.column :fruit_size, :string # NOTE: "size" is reserved in Oracle - t.column :texture, :string - t.column :flavor, :string - end - end - - assert_nothing_raised { @connection.select_all "SELECT * FROM fruits" } - assert_nothing_raised { @connection.select_all "SELECT * FROM schema_info" } - assert_equal 7, @connection.select_one("SELECT version FROM schema_info")['version'].to_i - end - end - -end Index: activerecord/test/connection_test_mysql.rb =================================================================== --- activerecord/test/connection_test_mysql.rb (revision 8601) +++ activerecord/test/connection_test_mysql.rb (working copy) @@ -1,30 +0,0 @@ -require "#{File.dirname(__FILE__)}/abstract_unit" - -class MysqlConnectionTest < ActiveSupport::TestCase - def setup - @connection = ActiveRecord::Base.connection - end - - def test_no_automatic_reconnection_after_timeout - assert @connection.active? - @connection.update('set @@wait_timeout=1') - sleep 2 - assert !@connection.active? - end - - def test_successful_reconnection_after_timeout_with_manual_reconnect - assert @connection.active? - @connection.update('set @@wait_timeout=1') - sleep 2 - @connection.reconnect! - assert @connection.active? - end - - def test_successful_reconnection_after_timeout_with_verify - assert @connection.active? - @connection.update('set @@wait_timeout=1') - sleep 2 - @connection.verify!(0) - assert @connection.active? - end -end Index: activerecord/test/mixin_test.rb =================================================================== --- activerecord/test/mixin_test.rb (revision 8601) +++ activerecord/test/mixin_test.rb (working copy) @@ -1,95 +0,0 @@ -require 'abstract_unit' - -class Mixin < ActiveRecord::Base -end - -# Let us control what Time.now returns for the TouchTest suite -class Time - @@forced_now_time = nil - cattr_accessor :forced_now_time - - class << self - def now_with_forcing - if @@forced_now_time - @@forced_now_time - else - now_without_forcing - end - end - alias_method_chain :now, :forcing - end -end - - -class TouchTest < ActiveSupport::TestCase - fixtures :mixins - - def setup - Time.forced_now_time = Time.now - end - - def teardown - Time.forced_now_time = nil - end - - def test_time_mocking - five_minutes_ago = 5.minutes.ago - Time.forced_now_time = five_minutes_ago - assert_equal five_minutes_ago, Time.now - - Time.forced_now_time = nil - assert_not_equal five_minutes_ago, Time.now - end - - def test_update - stamped = Mixin.new - - assert_nil stamped.updated_at - assert_nil stamped.created_at - stamped.save - assert_equal Time.now, stamped.updated_at - assert_equal Time.now, stamped.created_at - end - - def test_create - obj = Mixin.create - assert_equal Time.now, obj.updated_at - assert_equal Time.now, obj.created_at - end - - def test_many_updates - stamped = Mixin.new - - assert_nil stamped.updated_at - assert_nil stamped.created_at - stamped.save - assert_equal Time.now, stamped.created_at - assert_equal Time.now, stamped.updated_at - - old_updated_at = stamped.updated_at - - Time.forced_now_time = 5.minutes.from_now - stamped.save - - assert_equal Time.now, stamped.updated_at - assert_equal old_updated_at, stamped.created_at - end - - def test_create_turned_off - Mixin.record_timestamps = false - - mixin = Mixin.new - - assert_nil mixin.updated_at - mixin.save - assert_nil mixin.updated_at - - # Make sure Mixin.record_timestamps gets reset, even if this test fails, - # so that other tests do not fail because Mixin.record_timestamps == false - rescue Exception => e - raise e - ensure - Mixin.record_timestamps = true - end - -end Index: activerecord/test/attribute_methods_test.rb =================================================================== --- activerecord/test/attribute_methods_test.rb (revision 8601) +++ activerecord/test/attribute_methods_test.rb (working copy) @@ -1,146 +0,0 @@ -require 'abstract_unit' -require 'fixtures/topic' - -class AttributeMethodsTest < ActiveSupport::TestCase - fixtures :topics - def setup - @old_suffixes = ActiveRecord::Base.send(:attribute_method_suffixes).dup - @target = Class.new(ActiveRecord::Base) - @target.table_name = 'topics' - end - - def teardown - ActiveRecord::Base.send(:attribute_method_suffixes).clear - ActiveRecord::Base.attribute_method_suffix *@old_suffixes - end - - - def test_match_attribute_method_query_returns_match_data - assert_not_nil md = @target.match_attribute_method?('title=') - assert_equal 'title', md.pre_match - assert_equal ['='], md.captures - - %w(_hello_world ist! _maybe?).each do |suffix| - @target.class_eval "def attribute#{suffix}(*args) args end" - @target.attribute_method_suffix suffix - - assert_not_nil md = @target.match_attribute_method?("title#{suffix}") - assert_equal 'title', md.pre_match - assert_equal [suffix], md.captures - end - end - - def test_declared_attribute_method_affects_respond_to_and_method_missing - topic = @target.new(:title => 'Budget') - assert topic.respond_to?('title') - assert_equal 'Budget', topic.title - assert !topic.respond_to?('title_hello_world') - assert_raise(NoMethodError) { topic.title_hello_world } - - %w(_hello_world _it! _candidate= able?).each do |suffix| - @target.class_eval "def attribute#{suffix}(*args) args end" - @target.attribute_method_suffix suffix - - meth = "title#{suffix}" - assert topic.respond_to?(meth) - assert_equal ['title'], topic.send(meth) - assert_equal ['title', 'a'], topic.send(meth, 'a') - assert_equal ['title', 1, 2, 3], topic.send(meth, 1, 2, 3) - end - end - - def test_should_unserialize_attributes_for_frozen_records - myobj = {:value1 => :value2} - topic = Topic.create("content" => myobj) - topic.freeze - assert_equal myobj, topic.content - end - - def test_kernel_methods_not_implemented_in_activerecord - %w(test name display y).each do |method| - assert_equal false, ActiveRecord::Base.instance_method_already_implemented?(method), "##{method} is defined" - end - end - - def test_primary_key_implemented - assert_equal true, Class.new(ActiveRecord::Base).instance_method_already_implemented?('id') - end - - def test_defined_kernel_methods_implemented_in_model - %w(test name display y).each do |method| - klass = Class.new ActiveRecord::Base - klass.class_eval "def #{method}() 'defined #{method}' end" - assert_equal true, klass.instance_method_already_implemented?(method), "##{method} is not defined" - end - end - - def test_defined_kernel_methods_implemented_in_model_abstract_subclass - %w(test name display y).each do |method| - abstract = Class.new ActiveRecord::Base - abstract.class_eval "def #{method}() 'defined #{method}' end" - abstract.abstract_class = true - klass = Class.new abstract - assert_equal true, klass.instance_method_already_implemented?(method), "##{method} is not defined" - end - end - - def test_raises_dangerous_attribute_error_when_defining_activerecord_method_in_model - %w(save create_or_update).each do |method| - klass = Class.new ActiveRecord::Base - klass.class_eval "def #{method}() 'defined #{method}' end" - assert_raises ActiveRecord::DangerousAttributeError do - klass.instance_method_already_implemented?(method) - end - end - end - - def test_only_time_related_columns_are_meant_to_be_cached_by_default - expected = %w(datetime timestamp time date).sort - assert_equal expected, ActiveRecord::Base.attribute_types_cached_by_default.map(&:to_s).sort -end - - def test_declaring_attributes_as_cached_adds_them_to_the_attributes_cached_by_default - default_attributes = Topic.cached_attributes - Topic.cache_attributes :replies_count - expected = default_attributes + ["replies_count"] - assert_equal expected.sort, Topic.cached_attributes.sort - Topic.instance_variable_set "@cached_attributes", nil - end - - def test_time_related_columns_are_actually_cached - column_types = %w(datetime timestamp time date).map(&:to_sym) - column_names = Topic.columns.select{|c| column_types.include?(c.type) }.map(&:name) - - assert_equal column_names.sort, Topic.cached_attributes.sort - assert_equal time_related_columns_on_topic.sort, Topic.cached_attributes.sort - end - - def test_accessing_cached_attributes_caches_the_converted_values_and_nothing_else - t = topics(:first) - cache = t.instance_variable_get "@attributes_cache" - - assert_not_nil cache - assert cache.empty? - - all_columns = Topic.columns.map(&:name) - cached_columns = time_related_columns_on_topic - uncached_columns = all_columns - cached_columns - - all_columns.each do |attr_name| - attribute_gets_cached = Topic.cache_attribute?(attr_name) - val = t.send attr_name unless attr_name == "type" - if attribute_gets_cached - assert cached_columns.include?(attr_name) - assert_equal val, cache[attr_name] - else - assert uncached_columns.include?(attr_name) - assert !cache.include?(attr_name) - end - end - end - - private - def time_related_columns_on_topic - Topic.columns.select{|c| [:time, :date, :datetime, :timestamp].include?(c.type)}.map(&:name) - end -end Index: activerecord/test/locking_test.rb =================================================================== --- activerecord/test/locking_test.rb (revision 8601) +++ activerecord/test/locking_test.rb (working copy) @@ -1,282 +0,0 @@ -require 'abstract_unit' -require 'fixtures/person' -require 'fixtures/reader' -require 'fixtures/legacy_thing' - -class LockWithoutDefault < ActiveRecord::Base; end - -class LockWithCustomColumnWithoutDefault < ActiveRecord::Base - set_table_name :lock_without_defaults_cust - set_locking_column :custom_lock_version -end - -class ReadonlyFirstNamePerson < Person - attr_readonly :first_name -end - -class OptimisticLockingTest < ActiveSupport::TestCase - fixtures :people, :legacy_things - - # need to disable transactional fixtures, because otherwise the sqlite3 - # adapter (at least) chokes when we try and change the schema in the middle - # of a test (see test_increment_counter_*). - self.use_transactional_fixtures = false - - def test_lock_existing - p1 = Person.find(1) - p2 = Person.find(1) - assert_equal 0, p1.lock_version - assert_equal 0, p2.lock_version - - p1.save! - assert_equal 1, p1.lock_version - assert_equal 0, p2.lock_version - - assert_raises(ActiveRecord::StaleObjectError) { p2.save! } - end - - def test_lock_repeating - p1 = Person.find(1) - p2 = Person.find(1) - assert_equal 0, p1.lock_version - assert_equal 0, p2.lock_version - - p1.save! - assert_equal 1, p1.lock_version - assert_equal 0, p2.lock_version - - assert_raises(ActiveRecord::StaleObjectError) { p2.save! } - assert_raises(ActiveRecord::StaleObjectError) { p2.save! } - end - - def test_lock_new - p1 = Person.new(:first_name => 'anika') - assert_equal 0, p1.lock_version - - p1.save! - p2 = Person.find(p1.id) - assert_equal 0, p1.lock_version - assert_equal 0, p2.lock_version - - p1.save! - assert_equal 1, p1.lock_version - assert_equal 0, p2.lock_version - - assert_raises(ActiveRecord::StaleObjectError) { p2.save! } - end - - def test_lock_new_with_nil - p1 = Person.new(:first_name => 'anika') - p1.save! - p1.lock_version = nil # simulate bad fixture or column with no default - p1.save! - assert_equal 1, p1.lock_version - end - - - def test_lock_column_name_existing - t1 = LegacyThing.find(1) - t2 = LegacyThing.find(1) - assert_equal 0, t1.version - assert_equal 0, t2.version - - t1.save! - assert_equal 1, t1.version - assert_equal 0, t2.version - - assert_raises(ActiveRecord::StaleObjectError) { t2.save! } - end - - def test_lock_column_is_mass_assignable - p1 = Person.create(:first_name => 'bianca') - assert_equal 0, p1.lock_version - assert_equal p1.lock_version, Person.new(p1.attributes).lock_version - - p1.save! - assert_equal 1, p1.lock_version - assert_equal p1.lock_version, Person.new(p1.attributes).lock_version - end - - def test_lock_without_default_sets_version_to_zero - t1 = LockWithoutDefault.new - assert_equal 0, t1.lock_version - end - - def test_lock_with_custom_column_without_default_sets_version_to_zero - t1 = LockWithCustomColumnWithoutDefault.new - assert_equal 0, t1.custom_lock_version - end - - def test_readonly_attributes - assert_equal Set.new([ 'first_name' ]), ReadonlyFirstNamePerson.readonly_attributes - - p = ReadonlyFirstNamePerson.create(:first_name => "unchangeable name") - p.reload - assert_equal "unchangeable name", p.first_name - - p.update_attributes(:first_name => "changed name") - p.reload - assert_equal "unchangeable name", p.first_name - end - - { :lock_version => Person, :custom_lock_version => LegacyThing }.each do |name, model| - define_method("test_increment_counter_updates_#{name}") do - counter_test model, 1 do |id| - model.increment_counter :test_count, id - end - end - - define_method("test_decrement_counter_updates_#{name}") do - counter_test model, -1 do |id| - model.decrement_counter :test_count, id - end - end - - define_method("test_update_counters_updates_#{name}") do - counter_test model, 1 do |id| - model.update_counters id, :test_count => 1 - end - end - end - - private - - def add_counter_column_to(model) - model.connection.add_column model.table_name, :test_count, :integer, :null => false, :default => 0 - model.reset_column_information - # OpenBase does not set a value to existing rows when adding a not null default column - model.update_all(:test_count => 0) if current_adapter?(:OpenBaseAdapter) - end - - def remove_counter_column_from(model) - model.connection.remove_column model.table_name, :test_count - model.reset_column_information - end - - def counter_test(model, expected_count) - add_counter_column_to(model) - object = model.find(:first) - assert_equal 0, object.test_count - assert_equal 0, object.send(model.locking_column) - yield object.id - object.reload - assert_equal expected_count, object.test_count - assert_equal 1, object.send(model.locking_column) - ensure - remove_counter_column_from(model) - end -end - - -# TODO: test against the generated SQL since testing locking behavior itself -# is so cumbersome. Will deadlock Ruby threads if the underlying db.execute -# blocks, so separate script called by Kernel#system is needed. -# (See exec vs. async_exec in the PostgreSQL adapter.) - -# TODO: The SQL Server, Sybase, and OpenBase adapters currently have no support for pessimistic locking - -unless current_adapter?(:SQLServerAdapter, :SybaseAdapter, :OpenBaseAdapter) - class PessimisticLockingTest < ActiveSupport::TestCase - self.use_transactional_fixtures = false - fixtures :people, :readers - - def setup - # Avoid introspection queries during tests. - Person.columns; Reader.columns - - @allow_concurrency = ActiveRecord::Base.allow_concurrency - ActiveRecord::Base.allow_concurrency = true - end - - def teardown - ActiveRecord::Base.allow_concurrency = @allow_concurrency - end - - # Test typical find. - def test_sane_find_with_lock - assert_nothing_raised do - Person.transaction do - Person.find 1, :lock => true - end - end - end - - # Test scoped lock. - def test_sane_find_with_scoped_lock - assert_nothing_raised do - Person.transaction do - Person.with_scope(:find => { :lock => true }) do - Person.find 1 - end - end - end - end - - # PostgreSQL protests SELECT ... FOR UPDATE on an outer join. - unless current_adapter?(:PostgreSQLAdapter) - # Test locked eager find. - def test_eager_find_with_lock - assert_nothing_raised do - Person.transaction do - Person.find 1, :include => :readers, :lock => true - end - end - end - end - - # Locking a record reloads it. - def test_sane_lock_method - assert_nothing_raised do - Person.transaction do - person = Person.find 1 - old, person.first_name = person.first_name, 'fooman' - person.lock! - assert_equal old, person.first_name - end - end - end - - if current_adapter?(:PostgreSQLAdapter, :OracleAdapter) - def test_no_locks_no_wait - first, second = duel { Person.find 1 } - assert first.end > second.end - end - - def test_second_lock_waits - assert [0.2, 1, 5].any? { |zzz| - first, second = duel(zzz) { Person.find 1, :lock => true } - second.end > first.end - } - end - - protected - def duel(zzz = 5) - t0, t1, t2, t3 = nil, nil, nil, nil - - a = Thread.new do - t0 = Time.now - Person.transaction do - yield - sleep zzz # block thread 2 for zzz seconds - end - t1 = Time.now - end - - b = Thread.new do - sleep zzz / 2.0 # ensure thread 1 tx starts first - t2 = Time.now - Person.transaction { yield } - t3 = Time.now - end - - a.join - b.join - - assert t1 > t0 + zzz - assert t2 > t0 - assert t3 > t2 - [t0.to_f..t1.to_f, t2.to_f..t3.to_f] - end - end - end -end Index: activerecord/test/query_cache_test.rb =================================================================== --- activerecord/test/query_cache_test.rb (revision 8601) +++ activerecord/test/query_cache_test.rb (working copy) @@ -1,104 +0,0 @@ -require 'abstract_unit' -require 'fixtures/topic' -require 'fixtures/reply' -require 'fixtures/task' -require 'fixtures/course' - - -class QueryCacheTest < ActiveSupport::TestCase - fixtures :tasks, :topics - - def test_find_queries - assert_queries(2) { Task.find(1); Task.find(1) } - end - - def test_find_queries_with_cache - Task.cache do - assert_queries(1) { Task.find(1); Task.find(1) } - end - end - - def test_count_queries_with_cache - Task.cache do - assert_queries(1) { Task.count; Task.count } - end - end - - def test_query_cache_dups_results_correctly - Task.cache do - now = Time.now.utc - task = Task.find 1 - assert_not_equal now, task.starting - task.starting = now - task.reload - assert_not_equal now, task.starting - end - end - - def test_cache_is_flat - Task.cache do - Topic.columns # don't count this query - assert_queries(1) { Topic.find(1); Topic.find(1); } - end - - ActiveRecord::Base.cache do - assert_queries(1) { Task.find(1); Task.find(1) } - end - end - - def test_cache_does_not_wrap_string_results_in_arrays - Task.cache do - assert_instance_of String, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks") - end - end -end - -uses_mocha 'QueryCacheExpiryTest' do - -class QueryCacheExpiryTest < ActiveSupport::TestCase - fixtures :tasks - - def test_find - Task.connection.expects(:clear_query_cache).times(1) - - assert !Task.connection.query_cache_enabled - Task.cache do - assert Task.connection.query_cache_enabled - Task.find(1) - - Task.uncached do - assert !Task.connection.query_cache_enabled - Task.find(1) - end - - assert Task.connection.query_cache_enabled - end - assert !Task.connection.query_cache_enabled - end - - def test_update - Task.connection.expects(:clear_query_cache).times(2) - - Task.cache do - Task.find(1).save! - end - end - - def test_destroy - Task.connection.expects(:clear_query_cache).times(2) - - Task.cache do - Task.find(1).destroy - end - end - - def test_insert - ActiveRecord::Base.connection.expects(:clear_query_cache).times(2) - - Task.cache do - Task.create! - end - end -end - -end Index: activerecord/test/reflection_test.rb =================================================================== --- activerecord/test/reflection_test.rb (revision 8601) +++ activerecord/test/reflection_test.rb (working copy) @@ -1,175 +0,0 @@ -require 'abstract_unit' -require 'fixtures/topic' -require 'fixtures/customer' -require 'fixtures/company' -require 'fixtures/company_in_module' -require 'fixtures/subscriber' - -class ReflectionTest < ActiveSupport::TestCase - fixtures :topics, :customers, :companies, :subscribers - - def setup - @first = Topic.find(1) - end - - def test_column_null_not_null - subscriber = Subscriber.find(:first) - assert subscriber.column_for_attribute("name").null - assert !subscriber.column_for_attribute("nick").null - end - - def test_read_attribute_names - assert_equal( - %w( id title author_name author_email_address bonus_time written_on last_read content approved replies_count parent_id type ).sort, - @first.attribute_names - ) - end - - def test_columns - assert_equal 12, Topic.columns.length - end - - def test_columns_are_returned_in_the_order_they_were_declared - column_names = Topic.columns.map { |column| column.name } - assert_equal %w(id title author_name author_email_address written_on bonus_time last_read content approved replies_count parent_id type), column_names - end - - def test_content_columns - content_columns = Topic.content_columns - content_column_names = content_columns.map {|column| column.name} - assert_equal 8, content_columns.length - assert_equal %w(title author_name author_email_address written_on bonus_time last_read content approved).sort, content_column_names.sort - end - - def test_column_string_type_and_limit - assert_equal :string, @first.column_for_attribute("title").type - assert_equal 255, @first.column_for_attribute("title").limit - end - - def test_column_null_not_null - subscriber = Subscriber.find(:first) - assert subscriber.column_for_attribute("name").null - assert !subscriber.column_for_attribute("nick").null - end - - def test_human_name_for_column - assert_equal "Author name", @first.column_for_attribute("author_name").human_name - end - - def test_integer_columns - assert_equal :integer, @first.column_for_attribute("id").type - end - - def test_reflection_klass_for_nested_class_name - reflection = ActiveRecord::Reflection::MacroReflection.new(nil, nil, { :class_name => 'MyApplication::Business::Company' }, nil) - assert_nothing_raised do - assert_equal MyApplication::Business::Company, reflection.klass - end - end - - def test_aggregation_reflection - reflection_for_address = ActiveRecord::Reflection::AggregateReflection.new( - :composed_of, :address, { :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ] }, Customer - ) - - reflection_for_balance = ActiveRecord::Reflection::AggregateReflection.new( - :composed_of, :balance, { :class_name => "Money", :mapping => %w(balance amount) }, Customer - ) - - reflection_for_gps_location = ActiveRecord::Reflection::AggregateReflection.new( - :composed_of, :gps_location, { }, Customer - ) - - assert Customer.reflect_on_all_aggregations.include?(reflection_for_gps_location) - assert Customer.reflect_on_all_aggregations.include?(reflection_for_balance) - assert Customer.reflect_on_all_aggregations.include?(reflection_for_address) - - assert_equal reflection_for_address, Customer.reflect_on_aggregation(:address) - - assert_equal Address, Customer.reflect_on_aggregation(:address).klass - - assert_equal Money, Customer.reflect_on_aggregation(:balance).klass - end - - def test_has_many_reflection - reflection_for_clients = ActiveRecord::Reflection::AssociationReflection.new(:has_many, :clients, { :order => "id", :dependent => :destroy }, Firm) - - assert_equal reflection_for_clients, Firm.reflect_on_association(:clients) - - assert_equal Client, Firm.reflect_on_association(:clients).klass - assert_equal 'companies', Firm.reflect_on_association(:clients).table_name - - assert_equal Client, Firm.reflect_on_association(:clients_of_firm).klass - assert_equal 'companies', Firm.reflect_on_association(:clients_of_firm).table_name - end - - def test_has_one_reflection - reflection_for_account = ActiveRecord::Reflection::AssociationReflection.new(:has_one, :account, { :foreign_key => "firm_id", :dependent => :destroy }, Firm) - assert_equal reflection_for_account, Firm.reflect_on_association(:account) - - assert_equal Account, Firm.reflect_on_association(:account).klass - assert_equal 'accounts', Firm.reflect_on_association(:account).table_name - end - - def test_belongs_to_inferred_foreign_key_from_assoc_name - Company.belongs_to :foo - assert_equal "foo_id", Company.reflect_on_association(:foo).primary_key_name - Company.belongs_to :bar, :class_name => "Xyzzy" - assert_equal "bar_id", Company.reflect_on_association(:bar).primary_key_name - Company.belongs_to :baz, :class_name => "Xyzzy", :foreign_key => "xyzzy_id" - assert_equal "xyzzy_id", Company.reflect_on_association(:baz).primary_key_name - end - - def test_association_reflection_in_modules - assert_reflection MyApplication::Business::Firm, - :clients_of_firm, - :klass => MyApplication::Business::Client, - :class_name => 'Client', - :table_name => 'companies' - - assert_reflection MyApplication::Billing::Account, - :firm, - :klass => MyApplication::Business::Firm, - :class_name => 'MyApplication::Business::Firm', - :table_name => 'companies' - - assert_reflection MyApplication::Billing::Account, - :qualified_billing_firm, - :klass => MyApplication::Billing::Firm, - :class_name => 'MyApplication::Billing::Firm', - :table_name => 'companies' - - assert_reflection MyApplication::Billing::Account, - :unqualified_billing_firm, - :klass => MyApplication::Billing::Firm, - :class_name => 'Firm', - :table_name => 'companies' - - assert_reflection MyApplication::Billing::Account, - :nested_qualified_billing_firm, - :klass => MyApplication::Billing::Nested::Firm, - :class_name => 'MyApplication::Billing::Nested::Firm', - :table_name => 'companies' - - assert_reflection MyApplication::Billing::Account, - :nested_unqualified_billing_firm, - :klass => MyApplication::Billing::Nested::Firm, - :class_name => 'Nested::Firm', - :table_name => 'companies' - end - - def test_reflection_of_all_associations - assert_equal 17, Firm.reflect_on_all_associations.size - assert_equal 15, Firm.reflect_on_all_associations(:has_many).size - assert_equal 2, Firm.reflect_on_all_associations(:has_one).size - assert_equal 0, Firm.reflect_on_all_associations(:belongs_to).size - end - - private - def assert_reflection(klass, association, options) - assert reflection = klass.reflect_on_association(association) - options.each do |method, value| - assert_equal(value, reflection.send(method)) - end - end -end Index: activerecord/test/aaa_create_tables_test.rb =================================================================== --- activerecord/test/aaa_create_tables_test.rb (revision 8601) +++ activerecord/test/aaa_create_tables_test.rb (working copy) @@ -1,72 +0,0 @@ -# The filename begins with "aaa" to ensure this is the first test. -require 'abstract_unit' - -class AAACreateTablesTest < ActiveSupport::TestCase - self.use_transactional_fixtures = false - - def setup - @base_path = "#{File.dirname(__FILE__)}/fixtures/db_definitions" - end - - def test_drop_and_create_main_tables - recreate ActiveRecord::Base unless use_migrations? - assert true - end - - def test_load_schema - if ActiveRecord::Base.connection.supports_migrations? - eval(File.read("#{File.dirname(__FILE__)}/fixtures/db_definitions/schema.rb")) - else - recreate ActiveRecord::Base, '3' - end - assert true - end - - def test_drop_and_create_courses_table - if Course.connection.supports_migrations? - eval(File.read("#{File.dirname(__FILE__)}/fixtures/db_definitions/schema2.rb")) - end - recreate Course, '2' unless use_migrations_for_courses? - assert true - end - - private - def use_migrations? - unittest_sql_filename = ActiveRecord::Base.connection.adapter_name.downcase + ".sql" - not File.exist? "#{@base_path}/#{unittest_sql_filename}" - end - - def use_migrations_for_courses? - unittest2_sql_filename = ActiveRecord::Base.connection.adapter_name.downcase + "2.sql" - not File.exist? "#{@base_path}/#{unittest2_sql_filename}" - end - - def recreate(base, suffix = nil) - connection = base.connection - adapter_name = connection.adapter_name.downcase + suffix.to_s - execute_sql_file "#{@base_path}/#{adapter_name}.drop.sql", connection - execute_sql_file "#{@base_path}/#{adapter_name}.sql", connection - end - - def execute_sql_file(path, connection) - # OpenBase has a different format for sql files - if current_adapter?(:OpenBaseAdapter) then - File.read(path).split("go").each_with_index do |sql, i| - begin - # OpenBase does not support comments embedded in sql - connection.execute(sql,"SQL statement ##{i}") unless sql.blank? - rescue ActiveRecord::StatementInvalid - #$stderr.puts "warning: #{$!}" - end - end - else - File.read(path).split(';').each_with_index do |sql, i| - begin - connection.execute("\n\n-- statement ##{i}\n#{sql}\n") unless sql.blank? - rescue ActiveRecord::StatementInvalid - #$stderr.puts "warning: #{$!}" - end - end - end - end -end Index: activerecord/test/associations_test.rb =================================================================== --- activerecord/test/associations_test.rb (revision 8601) +++ activerecord/test/associations_test.rb (working copy) @@ -1,2177 +0,0 @@ -require 'abstract_unit' -require 'fixtures/developer' -require 'fixtures/project' -require 'fixtures/company' -require 'fixtures/topic' -require 'fixtures/reply' -require 'fixtures/computer' -require 'fixtures/customer' -require 'fixtures/order' -require 'fixtures/categorization' -require 'fixtures/category' -require 'fixtures/post' -require 'fixtures/author' -require 'fixtures/comment' -require 'fixtures/tag' -require 'fixtures/tagging' -require 'fixtures/person' -require 'fixtures/reader' - -class AssociationsTest < ActiveSupport::TestCase - fixtures :accounts, :companies, :developers, :projects, :developers_projects, - :computers - - def test_bad_collection_keys - assert_raise(ArgumentError, 'ActiveRecord should have barked on bad collection keys') do - Class.new(ActiveRecord::Base).has_many(:wheels, :name => 'wheels') - end - end - - def test_should_construct_new_finder_sql_after_create - person = Person.new - assert_equal [], person.readers.find(:all) - person.save! - reader = Reader.create! :person => person, :post => Post.new(:title => "foo", :body => "bar") - assert_equal [reader], person.readers.find(:all) - end - - def test_force_reload - firm = Firm.new("name" => "A New Firm, Inc") - firm.save - firm.clients.each {|c|} # forcing to load all clients - assert firm.clients.empty?, "New firm shouldn't have client objects" - assert_equal 0, firm.clients.size, "New firm should have 0 clients" - - client = Client.new("name" => "TheClient.com", "firm_id" => firm.id) - client.save - - assert firm.clients.empty?, "New firm should have cached no client objects" - assert_equal 0, firm.clients.size, "New firm should have cached 0 clients count" - - assert !firm.clients(true).empty?, "New firm should have reloaded client objects" - assert_equal 1, firm.clients(true).size, "New firm should have reloaded clients count" - end - - def test_storing_in_pstore - require "tmpdir" - store_filename = File.join(Dir.tmpdir, "ar-pstore-association-test") - File.delete(store_filename) if File.exist?(store_filename) - require "pstore" - apple = Firm.create("name" => "Apple") - natural = Client.new("name" => "Natural Company") - apple.clients << natural - - db = PStore.new(store_filename) - db.transaction do - db["apple"] = apple - end - - db = PStore.new(store_filename) - db.transaction do - assert_equal "Natural Company", db["apple"].clients.first.name - end - end -end - -class AssociationProxyTest < ActiveSupport::TestCase - fixtures :authors, :posts, :categorizations, :categories, :developers, :projects, :developers_projects - - def test_proxy_accessors - welcome = posts(:welcome) - assert_equal welcome, welcome.author.proxy_owner - assert_equal welcome.class.reflect_on_association(:author), welcome.author.proxy_reflection - welcome.author.class # force load target - assert_equal welcome.author, welcome.author.proxy_target - - david = authors(:david) - assert_equal david, david.posts.proxy_owner - assert_equal david.class.reflect_on_association(:posts), david.posts.proxy_reflection - david.posts.first # force load target - assert_equal david.posts, david.posts.proxy_target - - assert_equal david, david.posts_with_extension.testing_proxy_owner - assert_equal david.class.reflect_on_association(:posts_with_extension), david.posts_with_extension.testing_proxy_reflection - david.posts_with_extension.first # force load target - assert_equal david.posts_with_extension, david.posts_with_extension.testing_proxy_target - end - - def test_push_does_not_load_target - david = authors(:david) - - david.posts << (post = Post.new(:title => "New on Edge", :body => "More cool stuff!")) - assert !david.posts.loaded? - assert david.posts.include?(post) - end - - def test_push_has_many_through_does_not_load_target - david = authors(:david) - - david.categories << categories(:technology) - assert !david.categories.loaded? - assert david.categories.include?(categories(:technology)) - end - - def test_push_followed_by_save_does_not_load_target - david = authors(:david) - - david.posts << (post = Post.new(:title => "New on Edge", :body => "More cool stuff!")) - assert !david.posts.loaded? - david.save - assert !david.posts.loaded? - assert david.posts.include?(post) - end - - def test_push_does_not_lose_additions_to_new_record - josh = Author.new(:name => "Josh") - josh.posts << Post.new(:title => "New on Edge", :body => "More cool stuff!") - assert josh.posts.loaded? - assert_equal 1, josh.posts.size - end - - def test_save_on_parent_does_not_load_target - david = developers(:david) - - assert !david.projects.loaded? - david.update_attribute(:created_at, Time.now) - assert !david.projects.loaded? - end - - def test_save_on_parent_saves_children - developer = Developer.create :name => "Bryan", :salary => 50_000 - assert_equal 1, developer.reload.audit_logs.size - end - - def test_failed_reload_returns_nil - p = setup_dangling_association - assert_nil p.author.reload - end - - def test_failed_reset_returns_nil - p = setup_dangling_association - assert_nil p.author.reset - end - - def test_reload_returns_assocition - david = developers(:david) - assert_nothing_raised do - assert_equal david.projects, david.projects.reload.reload - end - end - - def setup_dangling_association - josh = Author.create(:name => "Josh") - p = Post.create(:title => "New on Edge", :body => "More cool stuff!", :author => josh) - josh.destroy - p - end -end - -class HasOneAssociationsTest < ActiveSupport::TestCase - fixtures :accounts, :companies, :developers, :projects, :developers_projects - - def setup - Account.destroyed_account_ids.clear - end - - def test_has_one - assert_equal companies(:first_firm).account, Account.find(1) - assert_equal Account.find(1).credit_limit, companies(:first_firm).account.credit_limit - end - - def test_has_one_cache_nils - firm = companies(:another_firm) - assert_queries(1) { assert_nil firm.account } - assert_queries(0) { assert_nil firm.account } - - firms = Firm.find(:all, :include => :account) - assert_queries(0) { firms.each(&:account) } - end - - def test_can_marshal_has_one_association_with_nil_target - firm = Firm.new - assert_nothing_raised do - assert_equal firm.attributes, Marshal.load(Marshal.dump(firm)).attributes - end - - firm.account - assert_nothing_raised do - assert_equal firm.attributes, Marshal.load(Marshal.dump(firm)).attributes - end - end - - def test_proxy_assignment - company = companies(:first_firm) - assert_nothing_raised { company.account = company.account } - end - - def test_triple_equality - assert Account === companies(:first_firm).account - assert companies(:first_firm).account === Account - end - - def test_type_mismatch - assert_raises(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = 1 } - assert_raises(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = Project.find(1) } - end - - def test_natural_assignment - apple = Firm.create("name" => "Apple") - citibank = Account.create("credit_limit" => 10) - apple.account = citibank - assert_equal apple.id, citibank.firm_id - end - - def test_natural_assignment_to_nil - old_account_id = companies(:first_firm).account.id - companies(:first_firm).account = nil - companies(:first_firm).save - assert_nil companies(:first_firm).account - # account is dependent, therefore is destroyed when reference to owner is lost - assert_raises(ActiveRecord::RecordNotFound) { Account.find(old_account_id) } - end - - def test_assignment_without_replacement - apple = Firm.create("name" => "Apple") - citibank = Account.create("credit_limit" => 10) - apple.account = citibank - assert_equal apple.id, citibank.firm_id - - hsbc = apple.build_account({ :credit_limit => 20}, false) - assert_equal apple.id, hsbc.firm_id - hsbc.save - assert_equal apple.id, citibank.firm_id - - nykredit = apple.create_account({ :credit_limit => 30}, false) - assert_equal apple.id, nykredit.firm_id - assert_equal apple.id, citibank.firm_id - assert_equal apple.id, hsbc.firm_id - end - - def test_assignment_without_replacement_on_create - apple = Firm.create("name" => "Apple") - citibank = Account.create("credit_limit" => 10) - apple.account = citibank - assert_equal apple.id, citibank.firm_id - - hsbc = apple.create_account({:credit_limit => 10}, false) - assert_equal apple.id, hsbc.firm_id - hsbc.save - assert_equal apple.id, citibank.firm_id - end - - def test_dependence - num_accounts = Account.count - - firm = Firm.find(1) - assert !firm.account.nil? - account_id = firm.account.id - assert_equal [], Account.destroyed_account_ids[firm.id] - - firm.destroy - assert_equal num_accounts - 1, Account.count - assert_equal [account_id], Account.destroyed_account_ids[firm.id] - end - - def test_exclusive_dependence - num_accounts = Account.count - - firm = ExclusivelyDependentFirm.find(9) - assert !firm.account.nil? - account_id = firm.account.id - assert_equal [], Account.destroyed_account_ids[firm.id] - - firm.destroy - assert_equal num_accounts - 1, Account.count - assert_equal [], Account.destroyed_account_ids[firm.id] - end - - def test_dependence_with_nil_associate - firm = DependentFirm.new(:name => 'nullify') - firm.save! - assert_nothing_raised { firm.destroy } - end - - def test_succesful_build_association - firm = Firm.new("name" => "GlobalMegaCorp") - firm.save - - account = firm.build_account("credit_limit" => 1000) - assert account.save - assert_equal account, firm.account - end - - def test_failing_build_association - firm = Firm.new("name" => "GlobalMegaCorp") - firm.save - - account = firm.build_account - assert !account.save - assert_equal "can't be empty", account.errors.on("credit_limit") - end - - def test_build_association_twice_without_saving_affects_nothing - count_of_account = Account.count - firm = Firm.find(:first) - account1 = firm.build_account("credit_limit" => 1000) - account2 = firm.build_account("credit_limit" => 2000) - - assert_equal count_of_account, Account.count - end - - def test_create_association - firm = Firm.create(:name => "GlobalMegaCorp") - account = firm.create_account(:credit_limit => 1000) - assert_equal account, firm.reload.account - end - - def test_build - firm = Firm.new("name" => "GlobalMegaCorp") - firm.save - - firm.account = account = Account.new("credit_limit" => 1000) - assert_equal account, firm.account - assert account.save - assert_equal account, firm.account - end - - def test_build_before_child_saved - firm = Firm.find(1) - - account = firm.account.build("credit_limit" => 1000) - assert_equal account, firm.account - assert account.new_record? - assert firm.save - assert_equal account, firm.account - assert !account.new_record? - end - - def test_build_before_either_saved - firm = Firm.new("name" => "GlobalMegaCorp") - - firm.account = account = Account.new("credit_limit" => 1000) - assert_equal account, firm.account - assert account.new_record? - assert firm.save - assert_equal account, firm.account - assert !account.new_record? - end - - def test_failing_build_association - firm = Firm.new("name" => "GlobalMegaCorp") - firm.save - - firm.account = account = Account.new - assert_equal account, firm.account - assert !account.save - assert_equal account, firm.account - assert_equal "can't be empty", account.errors.on("credit_limit") - end - - def test_create - firm = Firm.new("name" => "GlobalMegaCorp") - firm.save - firm.account = account = Account.create("credit_limit" => 1000) - assert_equal account, firm.account - end - - def test_create_before_save - firm = Firm.new("name" => "GlobalMegaCorp") - firm.account = account = Account.create("credit_limit" => 1000) - assert_equal account, firm.account - end - - def test_dependence_with_missing_association - Account.destroy_all - firm = Firm.find(1) - assert firm.account.nil? - firm.destroy - end - - def test_dependence_with_missing_association_and_nullify - Account.destroy_all - firm = DependentFirm.find(:first) - assert firm.account.nil? - firm.destroy - end - - def test_assignment_before_parent_saved - firm = Firm.new("name" => "GlobalMegaCorp") - firm.account = a = Account.find(1) - assert firm.new_record? - assert_equal a, firm.account - assert firm.save - assert_equal a, firm.account - assert_equal a, firm.account(true) - end - - def test_finding_with_interpolated_condition - firm = Firm.find(:first) - superior = firm.clients.create(:name => 'SuperiorCo') - superior.rating = 10 - superior.save - assert_equal 10, firm.clients_with_interpolated_conditions.first.rating - end - - def test_assignment_before_child_saved - firm = Firm.find(1) - firm.account = a = Account.new("credit_limit" => 1000) - assert !a.new_record? - assert_equal a, firm.account - assert_equal a, firm.account - assert_equal a, firm.account(true) - end - - def test_assignment_before_either_saved - firm = Firm.new("name" => "GlobalMegaCorp") - firm.account = a = Account.new("credit_limit" => 1000) - assert firm.new_record? - assert a.new_record? - assert_equal a, firm.account - assert firm.save - assert !firm.new_record? - assert !a.new_record? - assert_equal a, firm.account - assert_equal a, firm.account(true) - end - - def test_not_resaved_when_unchanged - firm = Firm.find(:first, :include => :account) - assert_queries(1) { firm.save! } - - firm = Firm.find(:first) - firm.account = Account.find(:first) - assert_queries(1) { firm.save! } - - firm = Firm.find(:first).clone - firm.account = Account.find(:first) - assert_queries(2) { firm.save! } - - firm = Firm.find(:first).clone - firm.account = Account.find(:first).clone - assert_queries(2) { firm.save! } - end - - def test_save_still_works_after_accessing_nil_has_one - jp = Company.new :name => 'Jaded Pixel' - jp.dummy_account.nil? - - assert_nothing_raised do - jp.save! - end - end - -end - - -class HasManyAssociationsTest < ActiveSupport::TestCase - fixtures :accounts, :companies, :developers, :projects, - :developers_projects, :topics, :authors, :comments - - def setup - Client.destroyed_client_ids.clear - end - - def force_signal37_to_load_all_clients_of_firm - companies(:first_firm).clients_of_firm.each {|f| } - end - - def test_counting_with_counter_sql - assert_equal 2, Firm.find(:first).clients.count - end - - def test_counting - assert_equal 2, Firm.find(:first).plain_clients.count - end - - def test_counting_with_single_conditions - assert_equal 2, Firm.find(:first).plain_clients.count(:conditions => '1=1') - end - - def test_counting_with_single_hash - assert_equal 2, Firm.find(:first).plain_clients.count(:conditions => '1=1') - end - - def test_counting_with_column_name_and_hash - assert_equal 2, Firm.find(:first).plain_clients.count(:all, :conditions => '1=1') - end - - def test_finding - assert_equal 2, Firm.find(:first).clients.length - end - - def test_find_many_with_merged_options - assert_equal 1, companies(:first_firm).limited_clients.size - assert_equal 1, companies(:first_firm).limited_clients.find(:all).size - assert_equal 2, companies(:first_firm).limited_clients.find(:all, :limit => nil).size - end - - def test_dynamic_find_should_respect_association_order - assert_equal companies(:second_client), companies(:first_firm).clients_sorted_desc.find(:first, :conditions => "type = 'Client'") - assert_equal companies(:second_client), companies(:first_firm).clients_sorted_desc.find_by_type('Client') - end - - def test_dynamic_find_order_should_override_association_order - assert_equal companies(:first_client), companies(:first_firm).clients_sorted_desc.find(:first, :conditions => "type = 'Client'", :order => 'id') - assert_equal companies(:first_client), companies(:first_firm).clients_sorted_desc.find_by_type('Client', :order => 'id') - end - - def test_dynamic_find_all_should_respect_association_order - assert_equal [companies(:second_client), companies(:first_client)], companies(:first_firm).clients_sorted_desc.find(:all, :conditions => "type = 'Client'") - assert_equal [companies(:second_client), companies(:first_client)], companies(:first_firm).clients_sorted_desc.find_all_by_type('Client') - end - - def test_dynamic_find_all_order_should_override_association_order - assert_equal [companies(:first_client), companies(:second_client)], companies(:first_firm).clients_sorted_desc.find(:all, :conditions => "type = 'Client'", :order => 'id') - assert_equal [companies(:first_client), companies(:second_client)], companies(:first_firm).clients_sorted_desc.find_all_by_type('Client', :order => 'id') - end - - def test_dynamic_find_all_should_respect_association_limit - assert_equal 1, companies(:first_firm).limited_clients.find(:all, :conditions => "type = 'Client'").length - assert_equal 1, companies(:first_firm).limited_clients.find_all_by_type('Client').length - end - - def test_dynamic_find_all_limit_should_override_association_limit - assert_equal 2, companies(:first_firm).limited_clients.find(:all, :conditions => "type = 'Client'", :limit => 9_000).length - assert_equal 2, companies(:first_firm).limited_clients.find_all_by_type('Client', :limit => 9_000).length - end - - def test_triple_equality - assert !(Array === Firm.find(:first).clients) - assert Firm.find(:first).clients === Array - end - - def test_finding_default_orders - assert_equal "Summit", Firm.find(:first).clients.first.name - end - - def test_finding_with_different_class_name_and_order - assert_equal "Microsoft", Firm.find(:first).clients_sorted_desc.first.name - end - - def test_finding_with_foreign_key - assert_equal "Microsoft", Firm.find(:first).clients_of_firm.first.name - end - - def test_finding_with_condition - assert_equal "Microsoft", Firm.find(:first).clients_like_ms.first.name - end - - def test_finding_with_condition_hash - assert_equal "Microsoft", Firm.find(:first).clients_like_ms_with_hash_conditions.first.name - end - - def test_finding_using_sql - firm = Firm.find(:first) - first_client = firm.clients_using_sql.first - assert_not_nil first_client - assert_equal "Microsoft", first_client.name - assert_equal 1, firm.clients_using_sql.size - assert_equal 1, Firm.find(:first).clients_using_sql.size - end - - def test_counting_using_sql - assert_equal 1, Firm.find(:first).clients_using_counter_sql.size - assert Firm.find(:first).clients_using_counter_sql.any? - assert_equal 0, Firm.find(:first).clients_using_zero_counter_sql.size - assert !Firm.find(:first).clients_using_zero_counter_sql.any? - end - - def test_counting_non_existant_items_using_sql - assert_equal 0, Firm.find(:first).no_clients_using_counter_sql.size - end - - def test_belongs_to_sanity - c = Client.new - assert_nil c.firm - - if c.firm - assert false, "belongs_to failed if check" - end - - unless c.firm - else - assert false, "belongs_to failed unless check" - end - end - - def test_find_ids - firm = Firm.find(:first) - - assert_raises(ActiveRecord::RecordNotFound) { firm.clients.find } - - client = firm.clients.find(2) - assert_kind_of Client, client - - client_ary = firm.clients.find([2]) - assert_kind_of Array, client_ary - assert_equal client, client_ary.first - - client_ary = firm.clients.find(2, 3) - assert_kind_of Array, client_ary - assert_equal 2, client_ary.size - assert_equal client, client_ary.first - - assert_raises(ActiveRecord::RecordNotFound) { firm.clients.find(2, 99) } - end - - def test_find_string_ids_when_using_finder_sql - firm = Firm.find(:first) - - client = firm.clients_using_finder_sql.find("2") - assert_kind_of Client, client - - client_ary = firm.clients_using_finder_sql.find(["2"]) - assert_kind_of Array, client_ary - assert_equal client, client_ary.first - - client_ary = firm.clients_using_finder_sql.find("2", "3") - assert_kind_of Array, client_ary - assert_equal 2, client_ary.size - assert client_ary.include?(client) - end - - def test_find_all - firm = Firm.find(:first) - assert_equal 2, firm.clients.find(:all, :conditions => "#{QUOTED_TYPE} = 'Client'").length - assert_equal 1, firm.clients.find(:all, :conditions => "name = 'Summit'").length - end - - def test_find_all_sanitized - firm = Firm.find(:first) - summit = firm.clients.find(:all, :conditions => "name = 'Summit'") - assert_equal summit, firm.clients.find(:all, :conditions => ["name = ?", "Summit"]) - assert_equal summit, firm.clients.find(:all, :conditions => ["name = :name", { :name => "Summit" }]) - end - - def test_find_first - firm = Firm.find(:first) - client2 = Client.find(2) - assert_equal firm.clients.first, firm.clients.find(:first) - assert_equal client2, firm.clients.find(:first, :conditions => "#{QUOTED_TYPE} = 'Client'") - end - - def test_find_first_sanitized - firm = Firm.find(:first) - client2 = Client.find(2) - assert_equal client2, firm.clients.find(:first, :conditions => ["#{QUOTED_TYPE} = ?", 'Client']) - assert_equal client2, firm.clients.find(:first, :conditions => ["#{QUOTED_TYPE} = :type", { :type => 'Client' }]) - end - - def test_find_in_collection - assert_equal Client.find(2).name, companies(:first_firm).clients.find(2).name - assert_raises(ActiveRecord::RecordNotFound) { companies(:first_firm).clients.find(6) } - end - - def test_find_grouped - all_clients_of_firm1 = Client.find(:all, :conditions => "firm_id = 1") - grouped_clients_of_firm1 = Client.find(:all, :conditions => "firm_id = 1", :group => "firm_id", :select => 'firm_id, count(id) as clients_count') - assert_equal 2, all_clients_of_firm1.size - assert_equal 1, grouped_clients_of_firm1.size - end - - def test_adding - force_signal37_to_load_all_clients_of_firm - natural = Client.new("name" => "Natural Company") - companies(:first_firm).clients_of_firm << natural - assert_equal 2, companies(:first_firm).clients_of_firm.size # checking via the collection - assert_equal 2, companies(:first_firm).clients_of_firm(true).size # checking using the db - assert_equal natural, companies(:first_firm).clients_of_firm.last - end - - def test_adding_using_create - first_firm = companies(:first_firm) - assert_equal 2, first_firm.plain_clients.size - natural = first_firm.plain_clients.create(:name => "Natural Company") - assert_equal 3, first_firm.plain_clients.length - assert_equal 3, first_firm.plain_clients.size - end - - def test_create_with_bang_on_has_many_when_parent_is_new_raises - assert_raises(ActiveRecord::RecordNotSaved) do - firm = Firm.new - firm.plain_clients.create! :name=>"Whoever" - end - end - - def test_regular_create_on_has_many_when_parent_is_new_raises - assert_raises(ActiveRecord::RecordNotSaved) do - firm = Firm.new - firm.plain_clients.create :name=>"Whoever" - end - end - - def test_create_with_bang_on_has_many_raises_when_record_not_saved - assert_raises(ActiveRecord::RecordInvalid) do - firm = Firm.find(:first) - firm.plain_clients.create! - end - end - - def test_create_with_bang_on_habtm_when_parent_is_new_raises - assert_raises(ActiveRecord::RecordNotSaved) do - Developer.new("name" => "Aredridel").projects.create! - end - end - - def test_adding_a_mismatch_class - assert_raises(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << nil } - assert_raises(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << 1 } - assert_raises(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << Topic.find(1) } - end - - def test_adding_a_collection - force_signal37_to_load_all_clients_of_firm - companies(:first_firm).clients_of_firm.concat([Client.new("name" => "Natural Company"), Client.new("name" => "Apple")]) - assert_equal 3, companies(:first_firm).clients_of_firm.size - assert_equal 3, companies(:first_firm).clients_of_firm(true).size - end - - def test_adding_before_save - no_of_firms = Firm.count - no_of_clients = Client.count - - new_firm = Firm.new("name" => "A New Firm, Inc") - c = Client.new("name" => "Apple") - - new_firm.clients_of_firm.push Client.new("name" => "Natural Company") - assert_equal 1, new_firm.clients_of_firm.size - new_firm.clients_of_firm << c - assert_equal 2, new_firm.clients_of_firm.size - - assert_equal no_of_firms, Firm.count # Firm was not saved to database. - assert_equal no_of_clients, Client.count # Clients were not saved to database. - assert new_firm.save - assert !new_firm.new_record? - assert !c.new_record? - assert_equal new_firm, c.firm - assert_equal no_of_firms+1, Firm.count # Firm was saved to database. - assert_equal no_of_clients+2, Client.count # Clients were saved to database. - - assert_equal 2, new_firm.clients_of_firm.size - assert_equal 2, new_firm.clients_of_firm(true).size - end - - def test_invalid_adding - firm = Firm.find(1) - assert !(firm.clients_of_firm << c = Client.new) - assert c.new_record? - assert !firm.valid? - assert !firm.save - assert c.new_record? - end - - def test_invalid_adding_before_save - no_of_firms = Firm.count - no_of_clients = Client.count - new_firm = Firm.new("name" => "A New Firm, Inc") - new_firm.clients_of_firm.concat([c = Client.new, Client.new("name" => "Apple")]) - assert c.new_record? - assert !c.valid? - assert !new_firm.valid? - assert !new_firm.save - assert c.new_record? - assert new_firm.new_record? - end - - def test_build - new_client = companies(:first_firm).clients_of_firm.build("name" => "Another Client") - assert_equal "Another Client", new_client.name - assert new_client.new_record? - assert_equal new_client, companies(:first_firm).clients_of_firm.last - assert companies(:first_firm).save - assert !new_client.new_record? - assert_equal 2, companies(:first_firm).clients_of_firm(true).size - end - - def test_build_many - new_clients = companies(:first_firm).clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) - assert_equal 2, new_clients.size - - assert companies(:first_firm).save - assert_equal 3, companies(:first_firm).clients_of_firm(true).size - end - - def test_build_followed_by_save_does_not_load_target - new_client = companies(:first_firm).clients_of_firm.build("name" => "Another Client") - assert companies(:first_firm).save - assert !companies(:first_firm).clients_of_firm.loaded? - end - - def test_build_without_loading_association - first_topic = topics(:first) - Reply.column_names - - assert_equal 1, first_topic.replies.length - - assert_no_queries do - first_topic.replies.build(:title => "Not saved", :content => "Superstars") - assert_equal 2, first_topic.replies.size - end - - assert_equal 2, first_topic.replies.to_ary.size - end - - def test_create_without_loading_association - first_firm = companies(:first_firm) - Firm.column_names - Client.column_names - - assert_equal 1, first_firm.clients_of_firm.size - first_firm.clients_of_firm.reset - - assert_queries(1) do - first_firm.clients_of_firm.create(:name => "Superstars") - end - - assert_equal 2, first_firm.clients_of_firm.size - end - - def test_invalid_build - new_client = companies(:first_firm).clients_of_firm.build - assert new_client.new_record? - assert !new_client.valid? - assert_equal new_client, companies(:first_firm).clients_of_firm.last - assert !companies(:first_firm).save - assert new_client.new_record? - assert_equal 1, companies(:first_firm).clients_of_firm(true).size - end - - def test_create - force_signal37_to_load_all_clients_of_firm - new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client") - assert !new_client.new_record? - assert_equal new_client, companies(:first_firm).clients_of_firm.last - assert_equal new_client, companies(:first_firm).clients_of_firm(true).last - end - - def test_create_many - companies(:first_firm).clients_of_firm.create([{"name" => "Another Client"}, {"name" => "Another Client II"}]) - assert_equal 3, companies(:first_firm).clients_of_firm(true).size - end - - def test_create_followed_by_save_does_not_load_target - new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client") - assert companies(:first_firm).save - assert !companies(:first_firm).clients_of_firm.loaded? - end - - def test_find_or_initialize - the_client = companies(:first_firm).clients.find_or_initialize_by_name("Yet another client") - assert_equal companies(:first_firm).id, the_client.firm_id - assert_equal "Yet another client", the_client.name - assert the_client.new_record? - end - - def test_find_or_create - number_of_clients = companies(:first_firm).clients.size - the_client = companies(:first_firm).clients.find_or_create_by_name("Yet another client") - assert_equal number_of_clients + 1, companies(:first_firm, :reload).clients.size - assert_equal the_client, companies(:first_firm).clients.find_or_create_by_name("Yet another client") - assert_equal number_of_clients + 1, companies(:first_firm, :reload).clients.size - end - - def test_deleting - force_signal37_to_load_all_clients_of_firm - companies(:first_firm).clients_of_firm.delete(companies(:first_firm).clients_of_firm.first) - assert_equal 0, companies(:first_firm).clients_of_firm.size - assert_equal 0, companies(:first_firm).clients_of_firm(true).size - end - - def test_deleting_before_save - new_firm = Firm.new("name" => "A New Firm, Inc.") - new_client = new_firm.clients_of_firm.build("name" => "Another Client") - assert_equal 1, new_firm.clients_of_firm.size - new_firm.clients_of_firm.delete(new_client) - assert_equal 0, new_firm.clients_of_firm.size - end - - def test_deleting_a_collection - force_signal37_to_load_all_clients_of_firm - companies(:first_firm).clients_of_firm.create("name" => "Another Client") - assert_equal 2, companies(:first_firm).clients_of_firm.size - companies(:first_firm).clients_of_firm.delete([companies(:first_firm).clients_of_firm[0], companies(:first_firm).clients_of_firm[1]]) - assert_equal 0, companies(:first_firm).clients_of_firm.size - assert_equal 0, companies(:first_firm).clients_of_firm(true).size - end - - def test_delete_all - force_signal37_to_load_all_clients_of_firm - companies(:first_firm).clients_of_firm.create("name" => "Another Client") - assert_equal 2, companies(:first_firm).clients_of_firm.size - companies(:first_firm).clients_of_firm.delete_all - assert_equal 0, companies(:first_firm).clients_of_firm.size - assert_equal 0, companies(:first_firm).clients_of_firm(true).size - end - - def test_delete_all_with_not_yet_loaded_association_collection - force_signal37_to_load_all_clients_of_firm - companies(:first_firm).clients_of_firm.create("name" => "Another Client") - assert_equal 2, companies(:first_firm).clients_of_firm.size - companies(:first_firm).clients_of_firm.reset - companies(:first_firm).clients_of_firm.delete_all - assert_equal 0, companies(:first_firm).clients_of_firm.size - assert_equal 0, companies(:first_firm).clients_of_firm(true).size - end - - def test_clearing_an_association_collection - firm = companies(:first_firm) - client_id = firm.clients_of_firm.first.id - assert_equal 1, firm.clients_of_firm.size - - firm.clients_of_firm.clear - - assert_equal 0, firm.clients_of_firm.size - assert_equal 0, firm.clients_of_firm(true).size - assert_equal [], Client.destroyed_client_ids[firm.id] - - # Should not be destroyed since the association is not dependent. - assert_nothing_raised do - assert Client.find(client_id).firm.nil? - end - end - - def test_clearing_a_dependent_association_collection - firm = companies(:first_firm) - client_id = firm.dependent_clients_of_firm.first.id - assert_equal 1, firm.dependent_clients_of_firm.size - - # :dependent means destroy is called on each client - firm.dependent_clients_of_firm.clear - - assert_equal 0, firm.dependent_clients_of_firm.size - assert_equal 0, firm.dependent_clients_of_firm(true).size - assert_equal [client_id], Client.destroyed_client_ids[firm.id] - - # Should be destroyed since the association is dependent. - assert Client.find_by_id(client_id).nil? - end - - def test_clearing_an_exclusively_dependent_association_collection - firm = companies(:first_firm) - client_id = firm.exclusively_dependent_clients_of_firm.first.id - assert_equal 1, firm.exclusively_dependent_clients_of_firm.size - - assert_equal [], Client.destroyed_client_ids[firm.id] - - # :exclusively_dependent means each client is deleted directly from - # the database without looping through them calling destroy. - firm.exclusively_dependent_clients_of_firm.clear - - assert_equal 0, firm.exclusively_dependent_clients_of_firm.size - assert_equal 0, firm.exclusively_dependent_clients_of_firm(true).size - # no destroy-filters should have been called - assert_equal [], Client.destroyed_client_ids[firm.id] - - # Should be destroyed since the association is exclusively dependent. - assert Client.find_by_id(client_id).nil? - end - - def test_dependent_association_respects_optional_conditions_on_delete - firm = companies(:odegy) - Client.create(:client_of => firm.id, :name => "BigShot Inc.") - Client.create(:client_of => firm.id, :name => "SmallTime Inc.") - # only one of two clients is included in the association due to the :conditions key - assert_equal 2, Client.find_all_by_client_of(firm.id).size - assert_equal 1, firm.dependent_conditional_clients_of_firm.size - firm.destroy - # only the correctly associated client should have been deleted - assert_equal 1, Client.find_all_by_client_of(firm.id).size - end - - def test_dependent_association_respects_optional_sanitized_conditions_on_delete - firm = companies(:odegy) - Client.create(:client_of => firm.id, :name => "BigShot Inc.") - Client.create(:client_of => firm.id, :name => "SmallTime Inc.") - # only one of two clients is included in the association due to the :conditions key - assert_equal 2, Client.find_all_by_client_of(firm.id).size - assert_equal 1, firm.dependent_sanitized_conditional_clients_of_firm.size - firm.destroy - # only the correctly associated client should have been deleted - assert_equal 1, Client.find_all_by_client_of(firm.id).size - end - - def test_clearing_without_initial_access - firm = companies(:first_firm) - - firm.clients_of_firm.clear - - assert_equal 0, firm.clients_of_firm.size - assert_equal 0, firm.clients_of_firm(true).size - end - - def test_deleting_a_item_which_is_not_in_the_collection - force_signal37_to_load_all_clients_of_firm - summit = Client.find_by_name('Summit') - companies(:first_firm).clients_of_firm.delete(summit) - assert_equal 1, companies(:first_firm).clients_of_firm.size - assert_equal 1, companies(:first_firm).clients_of_firm(true).size - assert_equal 2, summit.client_of - end - - def test_deleting_type_mismatch - david = Developer.find(1) - david.projects.reload - assert_raises(ActiveRecord::AssociationTypeMismatch) { david.projects.delete(1) } - end - - def test_deleting_self_type_mismatch - david = Developer.find(1) - david.projects.reload - assert_raises(ActiveRecord::AssociationTypeMismatch) { david.projects.delete(Project.find(1).developers) } - end - - def test_destroy_all - force_signal37_to_load_all_clients_of_firm - assert !companies(:first_firm).clients_of_firm.empty?, "37signals has clients after load" - companies(:first_firm).clients_of_firm.destroy_all - assert companies(:first_firm).clients_of_firm.empty?, "37signals has no clients after destroy all" - assert companies(:first_firm).clients_of_firm(true).empty?, "37signals has no clients after destroy all and refresh" - end - - def test_dependence - firm = companies(:first_firm) - assert_equal 2, firm.clients.size - firm.destroy - assert Client.find(:all, :conditions => "firm_id=#{firm.id}").empty? - end - - def test_destroy_dependent_when_deleted_from_association - firm = Firm.find(:first) - assert_equal 2, firm.clients.size - - client = firm.clients.first - firm.clients.delete(client) - - assert_raise(ActiveRecord::RecordNotFound) { Client.find(client.id) } - assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find(client.id) } - assert_equal 1, firm.clients.size - end - - def test_three_levels_of_dependence - topic = Topic.create "title" => "neat and simple" - reply = topic.replies.create "title" => "neat and simple", "content" => "still digging it" - silly_reply = reply.replies.create "title" => "neat and simple", "content" => "ain't complaining" - - assert_nothing_raised { topic.destroy } - end - - uses_transaction :test_dependence_with_transaction_support_on_failure - def test_dependence_with_transaction_support_on_failure - firm = companies(:first_firm) - clients = firm.clients - assert_equal 2, clients.length - clients.last.instance_eval { def before_destroy() raise "Trigger rollback" end } - - firm.destroy rescue "do nothing" - - assert_equal 2, Client.find(:all, :conditions => "firm_id=#{firm.id}").size - end - - def test_dependence_on_account - num_accounts = Account.count - companies(:first_firm).destroy - assert_equal num_accounts - 1, Account.count - end - - def test_depends_and_nullify - num_accounts = Account.count - num_companies = Company.count - - core = companies(:rails_core) - assert_equal accounts(:rails_core_account), core.account - assert_equal companies(:leetsoft, :jadedpixel), core.companies - core.destroy - assert_nil accounts(:rails_core_account).reload.firm_id - assert_nil companies(:leetsoft).reload.client_of - assert_nil companies(:jadedpixel).reload.client_of - - - assert_equal num_accounts, Account.count - end - - def test_included_in_collection - assert companies(:first_firm).clients.include?(Client.find(2)) - end - - def test_adding_array_and_collection - assert_nothing_raised { Firm.find(:first).clients + Firm.find(:all).last.clients } - end - - def test_find_all_without_conditions - firm = companies(:first_firm) - assert_equal 2, firm.clients.find(:all).length - end - - def test_replace_with_less - firm = Firm.find(:first) - firm.clients = [companies(:first_client)] - assert firm.save, "Could not save firm" - firm.reload - assert_equal 1, firm.clients.length - end - - def test_replace_with_less_and_dependent_nullify - num_companies = Company.count - companies(:rails_core).companies = [] - assert_equal num_companies, Company.count - end - - def test_replace_with_new - firm = Firm.find(:first) - firm.clients = [companies(:second_client), Client.new("name" => "New Client")] - firm.save - firm.reload - assert_equal 2, firm.clients.length - assert !firm.clients.include?(:first_client) - end - - def test_replace_on_new_object - firm = Firm.new("name" => "New Firm") - firm.clients = [companies(:second_client), Client.new("name" => "New Client")] - assert firm.save - firm.reload - assert_equal 2, firm.clients.length - assert firm.clients.include?(Client.find_by_name("New Client")) - end - - def test_get_ids - assert_equal [companies(:first_client).id, companies(:second_client).id], companies(:first_firm).client_ids - end - - def test_assign_ids - firm = Firm.new("name" => "Apple") - firm.client_ids = [companies(:first_client).id, companies(:second_client).id] - firm.save - firm.reload - assert_equal 2, firm.clients.length - assert firm.clients.include?(companies(:second_client)) - end - - def test_assign_ids_ignoring_blanks - firm = Firm.create!(:name => 'Apple') - firm.client_ids = [companies(:first_client).id, nil, companies(:second_client).id, ''] - firm.save! - - assert_equal 2, firm.clients(true).size - assert firm.clients.include?(companies(:second_client)) - end - - def test_get_ids_for_through - assert_equal [comments(:eager_other_comment1).id], authors(:mary).comment_ids - end - - def test_assign_ids_for_through - assert_raise(NoMethodError) { authors(:mary).comment_ids = [123] } - end - - def test_dynamic_find_should_respect_association_order_for_through - assert_equal Comment.find(10), authors(:david).comments_desc.find(:first, :conditions => "comments.type = 'SpecialComment'") - assert_equal Comment.find(10), authors(:david).comments_desc.find_by_type('SpecialComment') - end - - def test_dynamic_find_order_should_override_association_order_for_through - assert_equal Comment.find(3), authors(:david).comments_desc.find(:first, :conditions => "comments.type = 'SpecialComment'", :order => 'comments.id') - assert_equal Comment.find(3), authors(:david).comments_desc.find_by_type('SpecialComment', :order => 'comments.id') - end - - def test_dynamic_find_all_should_respect_association_order_for_through - assert_equal [Comment.find(10), Comment.find(7), Comment.find(6), Comment.find(3)], authors(:david).comments_desc.find(:all, :conditions => "comments.type = 'SpecialComment'") - assert_equal [Comment.find(10), Comment.find(7), Comment.find(6), Comment.find(3)], authors(:david).comments_desc.find_all_by_type('SpecialComment') - end - - def test_dynamic_find_all_order_should_override_association_order_for_through - assert_equal [Comment.find(3), Comment.find(6), Comment.find(7), Comment.find(10)], authors(:david).comments_desc.find(:all, :conditions => "comments.type = 'SpecialComment'", :order => 'comments.id') - assert_equal [Comment.find(3), Comment.find(6), Comment.find(7), Comment.find(10)], authors(:david).comments_desc.find_all_by_type('SpecialComment', :order => 'comments.id') - end - - def test_dynamic_find_all_should_respect_association_limit_for_through - assert_equal 1, authors(:david).limited_comments.find(:all, :conditions => "comments.type = 'SpecialComment'").length - assert_equal 1, authors(:david).limited_comments.find_all_by_type('SpecialComment').length - end - - def test_dynamic_find_all_order_should_override_association_limit_for_through - assert_equal 4, authors(:david).limited_comments.find(:all, :conditions => "comments.type = 'SpecialComment'", :limit => 9_000).length - assert_equal 4, authors(:david).limited_comments.find_all_by_type('SpecialComment', :limit => 9_000).length - end - -end - -class BelongsToAssociationsTest < ActiveSupport::TestCase - fixtures :accounts, :companies, :developers, :projects, :topics, - :developers_projects, :computers, :authors, :posts, :tags, :taggings - - def test_belongs_to - Client.find(3).firm.name - assert_equal companies(:first_firm).name, Client.find(3).firm.name - assert !Client.find(3).firm.nil?, "Microsoft should have a firm" - end - - def test_proxy_assignment - account = Account.find(1) - assert_nothing_raised { account.firm = account.firm } - end - - def test_triple_equality - assert Client.find(3).firm === Firm - assert Firm === Client.find(3).firm - end - - def test_type_mismatch - assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = 1 } - assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = Project.find(1) } - end - - def test_natural_assignment - apple = Firm.create("name" => "Apple") - citibank = Account.create("credit_limit" => 10) - citibank.firm = apple - assert_equal apple.id, citibank.firm_id - end - - def test_no_unexpected_aliasing - first_firm = companies(:first_firm) - another_firm = companies(:another_firm) - - citibank = Account.create("credit_limit" => 10) - citibank.firm = first_firm - original_proxy = citibank.firm - citibank.firm = another_firm - - assert_equal first_firm.object_id, original_proxy.object_id - assert_equal another_firm.object_id, citibank.firm.object_id - end - - def test_creating_the_belonging_object - citibank = Account.create("credit_limit" => 10) - apple = citibank.create_firm("name" => "Apple") - assert_equal apple, citibank.firm - citibank.save - citibank.reload - assert_equal apple, citibank.firm - end - - def test_building_the_belonging_object - citibank = Account.create("credit_limit" => 10) - apple = citibank.build_firm("name" => "Apple") - citibank.save - assert_equal apple.id, citibank.firm_id - end - - def test_natural_assignment_to_nil - client = Client.find(3) - client.firm = nil - client.save - assert_nil client.firm(true) - assert_nil client.client_of - end - - def test_with_different_class_name - assert_equal Company.find(1).name, Company.find(3).firm_with_other_name.name - assert_not_nil Company.find(3).firm_with_other_name, "Microsoft should have a firm" - end - - def test_with_condition - assert_equal Company.find(1).name, Company.find(3).firm_with_condition.name - assert_not_nil Company.find(3).firm_with_condition, "Microsoft should have a firm" - end - - def test_belongs_to_counter - debate = Topic.create("title" => "debate") - assert_equal 0, debate.send(:read_attribute, "replies_count"), "No replies yet" - - trash = debate.replies.create("title" => "blah!", "content" => "world around!") - assert_equal 1, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply created" - - trash.destroy - assert_equal 0, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply deleted" - end - - def test_belongs_to_counter_with_reassigning - t1 = Topic.create("title" => "t1") - t2 = Topic.create("title" => "t2") - r1 = Reply.new("title" => "r1", "content" => "r1") - r1.topic = t1 - - assert r1.save - assert_equal 1, Topic.find(t1.id).replies.size - assert_equal 0, Topic.find(t2.id).replies.size - - r1.topic = Topic.find(t2.id) - - assert r1.save - assert_equal 0, Topic.find(t1.id).replies.size - assert_equal 1, Topic.find(t2.id).replies.size - - r1.topic = nil - - assert_equal 0, Topic.find(t1.id).replies.size - assert_equal 0, Topic.find(t2.id).replies.size - - r1.topic = t1 - - assert_equal 1, Topic.find(t1.id).replies.size - assert_equal 0, Topic.find(t2.id).replies.size - - r1.destroy - - assert_equal 0, Topic.find(t1.id).replies.size - assert_equal 0, Topic.find(t2.id).replies.size - end - - def test_belongs_to_counter_after_save - topic = Topic.create!(:title => "monday night") - topic.replies.create!(:title => "re: monday night", :content => "football") - assert_equal 1, Topic.find(topic.id)[:replies_count] - - topic.save! - assert_equal 1, Topic.find(topic.id)[:replies_count] - end - - def test_belongs_to_counter_after_update_attributes - topic = Topic.create!(:title => "37s") - topic.replies.create!(:title => "re: 37s", :content => "rails") - assert_equal 1, Topic.find(topic.id)[:replies_count] - - topic.update_attributes(:title => "37signals") - assert_equal 1, Topic.find(topic.id)[:replies_count] - end - - def test_belongs_to_counter_after_save - topic = Topic.create("title" => "monday night") - topic.replies.create("title" => "re: monday night", "content" => "football") - assert_equal 1, Topic.find(topic.id).send(:read_attribute, "replies_count") - - topic.save - assert_equal 1, Topic.find(topic.id).send(:read_attribute, "replies_count") - end - - def test_belongs_to_counter_after_update_attributes - topic = Topic.create("title" => "37s") - topic.replies.create("title" => "re: 37s", "content" => "rails") - assert_equal 1, Topic.find(topic.id).send(:read_attribute, "replies_count") - - topic.update_attributes("title" => "37signals") - assert_equal 1, Topic.find(topic.id).send(:read_attribute, "replies_count") - end - - def test_assignment_before_parent_saved - client = Client.find(:first) - apple = Firm.new("name" => "Apple") - client.firm = apple - assert_equal apple, client.firm - assert apple.new_record? - assert client.save - assert apple.save - assert !apple.new_record? - assert_equal apple, client.firm - assert_equal apple, client.firm(true) - end - - def test_assignment_before_child_saved - final_cut = Client.new("name" => "Final Cut") - firm = Firm.find(1) - final_cut.firm = firm - assert final_cut.new_record? - assert final_cut.save - assert !final_cut.new_record? - assert !firm.new_record? - assert_equal firm, final_cut.firm - assert_equal firm, final_cut.firm(true) - end - - def test_assignment_before_either_saved - final_cut = Client.new("name" => "Final Cut") - apple = Firm.new("name" => "Apple") - final_cut.firm = apple - assert final_cut.new_record? - assert apple.new_record? - assert final_cut.save - assert !final_cut.new_record? - assert !apple.new_record? - assert_equal apple, final_cut.firm - assert_equal apple, final_cut.firm(true) - end - - def test_new_record_with_foreign_key_but_no_object - c = Client.new("firm_id" => 1) - assert_equal Firm.find(:first), c.firm_with_basic_id - end - - def test_forgetting_the_load_when_foreign_key_enters_late - c = Client.new - assert_nil c.firm_with_basic_id - - c.firm_id = 1 - assert_equal Firm.find(:first), c.firm_with_basic_id - end - - def test_field_name_same_as_foreign_key - computer = Computer.find(1) - assert_not_nil computer.developer, ":foreign key == attribute didn't lock up" # ' - end - - def test_counter_cache - topic = Topic.create :title => "Zoom-zoom-zoom" - assert_equal 0, topic[:replies_count] - - reply = Reply.create(:title => "re: zoom", :content => "speedy quick!") - reply.topic = topic - - assert_equal 1, topic.reload[:replies_count] - assert_equal 1, topic.replies.size - - topic[:replies_count] = 15 - assert_equal 15, topic.replies.size - end - - def test_custom_counter_cache - reply = Reply.create(:title => "re: zoom", :content => "speedy quick!") - assert_equal 0, reply[:replies_count] - - silly = SillyReply.create(:title => "gaga", :content => "boo-boo") - silly.reply = reply - - assert_equal 1, reply.reload[:replies_count] - assert_equal 1, reply.replies.size - - reply[:replies_count] = 17 - assert_equal 17, reply.replies.size - end - - def test_store_two_association_with_one_save - num_orders = Order.count - num_customers = Customer.count - order = Order.new - - customer1 = order.billing = Customer.new - customer2 = order.shipping = Customer.new - assert order.save - assert_equal customer1, order.billing - assert_equal customer2, order.shipping - - order.reload - - assert_equal customer1, order.billing - assert_equal customer2, order.shipping - - assert_equal num_orders +1, Order.count - assert_equal num_customers +2, Customer.count - end - - - def test_store_association_in_two_relations_with_one_save - num_orders = Order.count - num_customers = Customer.count - order = Order.new - - customer = order.billing = order.shipping = Customer.new - assert order.save - assert_equal customer, order.billing - assert_equal customer, order.shipping - - order.reload - - assert_equal customer, order.billing - assert_equal customer, order.shipping - - assert_equal num_orders +1, Order.count - assert_equal num_customers +1, Customer.count - end - - def test_store_association_in_two_relations_with_one_save_in_existing_object - num_orders = Order.count - num_customers = Customer.count - order = Order.create - - customer = order.billing = order.shipping = Customer.new - assert order.save - assert_equal customer, order.billing - assert_equal customer, order.shipping - - order.reload - - assert_equal customer, order.billing - assert_equal customer, order.shipping - - assert_equal num_orders +1, Order.count - assert_equal num_customers +1, Customer.count - end - - def test_store_association_in_two_relations_with_one_save_in_existing_object_with_values - num_orders = Order.count - num_customers = Customer.count - order = Order.create - - customer = order.billing = order.shipping = Customer.new - assert order.save - assert_equal customer, order.billing - assert_equal customer, order.shipping - - order.reload - - customer = order.billing = order.shipping = Customer.new - - assert order.save - order.reload - - assert_equal customer, order.billing - assert_equal customer, order.shipping - - assert_equal num_orders +1, Order.count - assert_equal num_customers +2, Customer.count - end - - - def test_association_assignment_sticks - post = Post.find(:first) - - author1, author2 = Author.find(:all, :limit => 2) - assert_not_nil author1 - assert_not_nil author2 - - # make sure the association is loaded - post.author - - # set the association by id, directly - post.author_id = author2.id - - # save and reload - post.save! - post.reload - - # the author id of the post should be the id we set - assert_equal post.author_id, author2.id - end - -end - - -class ProjectWithAfterCreateHook < ActiveRecord::Base - set_table_name 'projects' - has_and_belongs_to_many :developers, - :class_name => "DeveloperForProjectWithAfterCreateHook", - :join_table => "developers_projects", - :foreign_key => "project_id", - :association_foreign_key => "developer_id" - - after_create :add_david - - def add_david - david = DeveloperForProjectWithAfterCreateHook.find_by_name('David') - david.projects << self - end -end - -class DeveloperForProjectWithAfterCreateHook < ActiveRecord::Base - set_table_name 'developers' - has_and_belongs_to_many :projects, - :class_name => "ProjectWithAfterCreateHook", - :join_table => "developers_projects", - :association_foreign_key => "project_id", - :foreign_key => "developer_id" -end - - -class HasAndBelongsToManyAssociationsTest < ActiveSupport::TestCase - fixtures :accounts, :companies, :categories, :posts, :categories_posts, :developers, :projects, :developers_projects - - def test_has_and_belongs_to_many - david = Developer.find(1) - - assert !david.projects.empty? - assert_equal 2, david.projects.size - - active_record = Project.find(1) - assert !active_record.developers.empty? - assert_equal 3, active_record.developers.size - assert active_record.developers.include?(david) - end - - def test_triple_equality - assert !(Array === Developer.find(1).projects) - assert Developer.find(1).projects === Array - end - - def test_adding_single - jamis = Developer.find(2) - jamis.projects.reload # causing the collection to load - action_controller = Project.find(2) - assert_equal 1, jamis.projects.size - assert_equal 1, action_controller.developers.size - - jamis.projects << action_controller - - assert_equal 2, jamis.projects.size - assert_equal 2, jamis.projects(true).size - assert_equal 2, action_controller.developers(true).size - end - - def test_adding_type_mismatch - jamis = Developer.find(2) - assert_raise(ActiveRecord::AssociationTypeMismatch) { jamis.projects << nil } - assert_raise(ActiveRecord::AssociationTypeMismatch) { jamis.projects << 1 } - end - - def test_adding_from_the_project - jamis = Developer.find(2) - action_controller = Project.find(2) - action_controller.developers.reload - assert_equal 1, jamis.projects.size - assert_equal 1, action_controller.developers.size - - action_controller.developers << jamis - - assert_equal 2, jamis.projects(true).size - assert_equal 2, action_controller.developers.size - assert_equal 2, action_controller.developers(true).size - end - - def test_adding_from_the_project_fixed_timestamp - jamis = Developer.find(2) - action_controller = Project.find(2) - action_controller.developers.reload - assert_equal 1, jamis.projects.size - assert_equal 1, action_controller.developers.size - updated_at = jamis.updated_at - - action_controller.developers << jamis - - assert_equal updated_at, jamis.updated_at - assert_equal 2, jamis.projects(true).size - assert_equal 2, action_controller.developers.size - assert_equal 2, action_controller.developers(true).size - end - - def test_adding_multiple - aredridel = Developer.new("name" => "Aredridel") - aredridel.save - aredridel.projects.reload - aredridel.projects.push(Project.find(1), Project.find(2)) - assert_equal 2, aredridel.projects.size - assert_equal 2, aredridel.projects(true).size - end - - def test_adding_a_collection - aredridel = Developer.new("name" => "Aredridel") - aredridel.save - aredridel.projects.reload - aredridel.projects.concat([Project.find(1), Project.find(2)]) - assert_equal 2, aredridel.projects.size - assert_equal 2, aredridel.projects(true).size - end - - def test_adding_uses_default_values_on_join_table - ac = projects(:action_controller) - assert !developers(:jamis).projects.include?(ac) - developers(:jamis).projects << ac - - assert developers(:jamis, :reload).projects.include?(ac) - project = developers(:jamis).projects.detect { |p| p == ac } - assert_equal 1, project.access_level.to_i - end - - def test_habtm_attribute_access_and_respond_to - project = developers(:jamis).projects[0] - assert project.has_attribute?("name") - assert project.has_attribute?("joined_on") - assert project.has_attribute?("access_level") - assert project.respond_to?("name") - assert project.respond_to?("name=") - assert project.respond_to?("name?") - assert project.respond_to?("joined_on") - # given that the 'join attribute' won't be persisted, I don't - # think we should define the mutators - #assert project.respond_to?("joined_on=") - assert project.respond_to?("joined_on?") - assert project.respond_to?("access_level") - #assert project.respond_to?("access_level=") - assert project.respond_to?("access_level?") - end - - def test_habtm_adding_before_save - no_of_devels = Developer.count - no_of_projects = Project.count - aredridel = Developer.new("name" => "Aredridel") - aredridel.projects.concat([Project.find(1), p = Project.new("name" => "Projekt")]) - assert aredridel.new_record? - assert p.new_record? - assert aredridel.save - assert !aredridel.new_record? - assert_equal no_of_devels+1, Developer.count - assert_equal no_of_projects+1, Project.count - assert_equal 2, aredridel.projects.size - assert_equal 2, aredridel.projects(true).size - end - - def test_habtm_saving_multiple_relationships - new_project = Project.new("name" => "Grimetime") - amount_of_developers = 4 - developers = (0...amount_of_developers).collect {|i| Developer.create(:name => "JME #{i}") }.reverse - - new_project.developer_ids = [developers[0].id, developers[1].id] - new_project.developers_with_callback_ids = [developers[2].id, developers[3].id] - assert new_project.save - - new_project.reload - assert_equal amount_of_developers, new_project.developers.size - assert_equal developers, new_project.developers - end - - def test_habtm_unique_order_preserved - assert_equal developers(:poor_jamis, :jamis, :david), projects(:active_record).non_unique_developers - assert_equal developers(:poor_jamis, :jamis, :david), projects(:active_record).developers - end - - def test_build - devel = Developer.find(1) - proj = devel.projects.build("name" => "Projekt") - assert_equal devel.projects.last, proj - assert proj.new_record? - devel.save - assert !proj.new_record? - assert_equal devel.projects.last, proj - assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated - end - - def test_build_by_new_record - devel = Developer.new(:name => "Marcel", :salary => 75000) - proj1 = devel.projects.build(:name => "Make bed") - proj2 = devel.projects.build(:name => "Lie in it") - assert_equal devel.projects.last, proj2 - assert proj2.new_record? - devel.save - assert !devel.new_record? - assert !proj2.new_record? - assert_equal devel.projects.last, proj2 - assert_equal Developer.find_by_name("Marcel").projects.last, proj2 # prove join table is updated - end - - def test_create - devel = Developer.find(1) - proj = devel.projects.create("name" => "Projekt") - assert_equal devel.projects.last, proj - assert !proj.new_record? - assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated - end - - def test_create_by_new_record - devel = Developer.new(:name => "Marcel", :salary => 75000) - proj1 = devel.projects.build(:name => "Make bed") - proj2 = devel.projects.build(:name => "Lie in it") - assert_equal devel.projects.last, proj2 - assert proj2.new_record? - devel.save - assert !devel.new_record? - assert !proj2.new_record? - assert_equal devel.projects.last, proj2 - assert_equal Developer.find_by_name("Marcel").projects.last, proj2 # prove join table is updated - end - - def test_uniq_after_the_fact - developers(:jamis).projects << projects(:active_record) - developers(:jamis).projects << projects(:active_record) - assert_equal 3, developers(:jamis).projects.size - assert_equal 1, developers(:jamis).projects.uniq.size - end - - def test_uniq_before_the_fact - projects(:active_record).developers << developers(:jamis) - projects(:active_record).developers << developers(:david) - assert_equal 3, projects(:active_record, :reload).developers.size - end - - def test_deleting - david = Developer.find(1) - active_record = Project.find(1) - david.projects.reload - assert_equal 2, david.projects.size - assert_equal 3, active_record.developers.size - - david.projects.delete(active_record) - - assert_equal 1, david.projects.size - assert_equal 1, david.projects(true).size - assert_equal 2, active_record.developers(true).size - end - - def test_deleting_array - david = Developer.find(1) - david.projects.reload - david.projects.delete(Project.find(:all)) - assert_equal 0, david.projects.size - assert_equal 0, david.projects(true).size - end - - def test_deleting_with_sql - david = Developer.find(1) - active_record = Project.find(1) - active_record.developers.reload - assert_equal 3, active_record.developers_by_sql.size - - active_record.developers_by_sql.delete(david) - assert_equal 2, active_record.developers_by_sql(true).size - end - - def test_deleting_array_with_sql - active_record = Project.find(1) - active_record.developers.reload - assert_equal 3, active_record.developers_by_sql.size - - active_record.developers_by_sql.delete(Developer.find(:all)) - assert_equal 0, active_record.developers_by_sql(true).size - end - - def test_deleting_all - david = Developer.find(1) - david.projects.reload - david.projects.clear - assert_equal 0, david.projects.size - assert_equal 0, david.projects(true).size - end - - def test_removing_associations_on_destroy - david = DeveloperWithBeforeDestroyRaise.find(1) - assert !david.projects.empty? - assert_nothing_raised { david.destroy } - assert david.projects.empty? - assert DeveloperWithBeforeDestroyRaise.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = 1").empty? - end - - def test_additional_columns_from_join_table - assert_date_from_db Date.new(2004, 10, 10), Developer.find(1).projects.first.joined_on.to_date - end - - def test_destroy_all - david = Developer.find(1) - david.projects.reload - assert !david.projects.empty? - david.projects.destroy_all - assert david.projects.empty? - assert david.projects(true).empty? - end - - def test_deprecated_push_with_attributes_was_removed - jamis = developers(:jamis) - assert_raise(NoMethodError) do - jamis.projects.push_with_attributes(projects(:action_controller), :joined_on => Date.today) - end - end - - def test_associations_with_conditions - assert_equal 3, projects(:active_record).developers.size - assert_equal 1, projects(:active_record).developers_named_david.size - assert_equal 1, projects(:active_record).developers_named_david_with_hash_conditions.size - - assert_equal developers(:david), projects(:active_record).developers_named_david.find(developers(:david).id) - assert_equal developers(:david), projects(:active_record).developers_named_david_with_hash_conditions.find(developers(:david).id) - assert_equal developers(:david), projects(:active_record).salaried_developers.find(developers(:david).id) - - projects(:active_record).developers_named_david.clear - assert_equal 2, projects(:active_record, :reload).developers.size - end - - def test_find_in_association - # Using sql - assert_equal developers(:david), projects(:active_record).developers.find(developers(:david).id), "SQL find" - - # Using ruby - active_record = projects(:active_record) - active_record.developers.reload - assert_equal developers(:david), active_record.developers.find(developers(:david).id), "Ruby find" - end - - def test_find_in_association_with_custom_finder_sql - assert_equal developers(:david), projects(:active_record).developers_with_finder_sql.find(developers(:david).id), "SQL find" - - active_record = projects(:active_record) - active_record.developers_with_finder_sql.reload - assert_equal developers(:david), active_record.developers_with_finder_sql.find(developers(:david).id), "Ruby find" - end - - def test_find_in_association_with_custom_finder_sql_and_string_id - assert_equal developers(:david), projects(:active_record).developers_with_finder_sql.find(developers(:david).id.to_s), "SQL find" - end - - def test_find_with_merged_options - assert_equal 1, projects(:active_record).limited_developers.size - assert_equal 1, projects(:active_record).limited_developers.find(:all).size - assert_equal 3, projects(:active_record).limited_developers.find(:all, :limit => nil).size - end - - def test_dynamic_find_should_respect_association_order - # Developers are ordered 'name DESC, id DESC' - low_id_jamis = developers(:jamis) - middle_id_jamis = developers(:poor_jamis) - high_id_jamis = projects(:active_record).developers.create(:name => 'Jamis') - - assert_equal high_id_jamis, projects(:active_record).developers.find(:first, :conditions => "name = 'Jamis'") - assert_equal high_id_jamis, projects(:active_record).developers.find_by_name('Jamis') - end - - def test_dynamic_find_order_should_override_association_order - # Developers are ordered 'name DESC, id DESC' - low_id_jamis = developers(:jamis) - middle_id_jamis = developers(:poor_jamis) - high_id_jamis = projects(:active_record).developers.create(:name => 'Jamis') - - assert_equal low_id_jamis, projects(:active_record).developers.find(:first, :conditions => "name = 'Jamis'", :order => 'id') - assert_equal low_id_jamis, projects(:active_record).developers.find_by_name('Jamis', :order => 'id') - end - - def test_dynamic_find_all_should_respect_association_order - # Developers are ordered 'name DESC, id DESC' - low_id_jamis = developers(:jamis) - middle_id_jamis = developers(:poor_jamis) - high_id_jamis = projects(:active_record).developers.create(:name => 'Jamis') - - assert_equal [high_id_jamis, middle_id_jamis, low_id_jamis], projects(:active_record).developers.find(:all, :conditions => "name = 'Jamis'") - assert_equal [high_id_jamis, middle_id_jamis, low_id_jamis], projects(:active_record).developers.find_all_by_name('Jamis') - end - - def test_dynamic_find_all_order_should_override_association_order - # Developers are ordered 'name DESC, id DESC' - low_id_jamis = developers(:jamis) - middle_id_jamis = developers(:poor_jamis) - high_id_jamis = projects(:active_record).developers.create(:name => 'Jamis') - - assert_equal [low_id_jamis, middle_id_jamis, high_id_jamis], projects(:active_record).developers.find(:all, :conditions => "name = 'Jamis'", :order => 'id') - assert_equal [low_id_jamis, middle_id_jamis, high_id_jamis], projects(:active_record).developers.find_all_by_name('Jamis', :order => 'id') - end - - def test_dynamic_find_all_should_respect_association_limit - assert_equal 1, projects(:active_record).limited_developers.find(:all, :conditions => "name = 'Jamis'").length - assert_equal 1, projects(:active_record).limited_developers.find_all_by_name('Jamis').length - end - - def test_dynamic_find_all_order_should_override_association_limit - assert_equal 2, projects(:active_record).limited_developers.find(:all, :conditions => "name = 'Jamis'", :limit => 9_000).length - assert_equal 2, projects(:active_record).limited_developers.find_all_by_name('Jamis', :limit => 9_000).length - end - - def test_new_with_values_in_collection - jamis = DeveloperForProjectWithAfterCreateHook.find_by_name('Jamis') - david = DeveloperForProjectWithAfterCreateHook.find_by_name('David') - project = ProjectWithAfterCreateHook.new(:name => "Cooking with Bertie") - project.developers << jamis - project.save! - project.reload - - assert project.developers.include?(jamis) - assert project.developers.include?(david) - end - - def test_find_in_association_with_options - developers = projects(:active_record).developers.find(:all) - assert_equal 3, developers.size - - assert_equal developers(:poor_jamis), projects(:active_record).developers.find(:first, :conditions => "salary < 10000") - assert_equal developers(:jamis), projects(:active_record).developers.find(:first, :order => "salary DESC") - end - - def test_replace_with_less - david = developers(:david) - david.projects = [projects(:action_controller)] - assert david.save - assert_equal 1, david.projects.length - end - - def test_replace_with_new - david = developers(:david) - david.projects = [projects(:action_controller), Project.new("name" => "ActionWebSearch")] - david.save - assert_equal 2, david.projects.length - assert !david.projects.include?(projects(:active_record)) - end - - def test_replace_on_new_object - new_developer = Developer.new("name" => "Matz") - new_developer.projects = [projects(:action_controller), Project.new("name" => "ActionWebSearch")] - new_developer.save - assert_equal 2, new_developer.projects.length - end - - def test_consider_type - developer = Developer.find(:first) - special_project = SpecialProject.create("name" => "Special Project") - - other_project = developer.projects.first - developer.special_projects << special_project - developer.reload - - assert developer.projects.include?(special_project) - assert developer.special_projects.include?(special_project) - assert !developer.special_projects.include?(other_project) - end - - def test_update_attributes_after_push_without_duplicate_join_table_rows - developer = Developer.new("name" => "Kano") - project = SpecialProject.create("name" => "Special Project") - assert developer.save - developer.projects << project - developer.update_attribute("name", "Bruza") - assert_equal 1, Developer.connection.select_value(<<-end_sql).to_i - SELECT count(*) FROM developers_projects - WHERE project_id = #{project.id} - AND developer_id = #{developer.id} - end_sql - end - - def test_updating_attributes_on_non_rich_associations - welcome = categories(:technology).posts.first - welcome.title = "Something else" - assert welcome.save! - end - - def test_habtm_respects_select - categories(:technology).select_testing_posts(true).each do |o| - assert_respond_to o, :correctness_marker - end - assert_respond_to categories(:technology).select_testing_posts.find(:first), :correctness_marker - end - - def test_updating_attributes_on_rich_associations - david = projects(:action_controller).developers.first - david.name = "DHH" - assert_raises(ActiveRecord::ReadOnlyRecord) { david.save! } - end - - def test_updating_attributes_on_rich_associations_with_limited_find_from_reflection - david = projects(:action_controller).selected_developers.first - david.name = "DHH" - assert_nothing_raised { david.save! } - end - - - def test_updating_attributes_on_rich_associations_with_limited_find - david = projects(:action_controller).developers.find(:all, :select => "developers.*").first - david.name = "DHH" - assert david.save! - end - - def test_join_table_alias - assert_equal 3, Developer.find(:all, :include => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL').size - end - - def test_join_with_group - group = Developer.columns.inject([]) do |g, c| - g << "developers.#{c.name}" - g << "developers_projects_2.#{c.name}" - end - Project.columns.each { |c| group << "projects.#{c.name}" } - - assert_equal 3, Developer.find(:all, :include => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL', :group => group.join(",")).size - end - - def test_get_ids - assert_equal projects(:active_record, :action_controller).map(&:id).sort, developers(:david).project_ids.sort - assert_equal [projects(:active_record).id], developers(:jamis).project_ids - end - - def test_assign_ids - developer = Developer.new("name" => "Joe") - developer.project_ids = projects(:active_record, :action_controller).map(&:id) - developer.save - developer.reload - assert_equal 2, developer.projects.length - assert_equal projects(:active_record), developer.projects[0] - assert_equal projects(:action_controller), developer.projects[1] - end - - def test_assign_ids_ignoring_blanks - developer = Developer.new("name" => "Joe") - developer.project_ids = [projects(:active_record).id, nil, projects(:action_controller).id, ''] - developer.save - developer.reload - assert_equal 2, developer.projects.length - assert_equal projects(:active_record), developer.projects[0] - assert_equal projects(:action_controller), developer.projects[1] - end - - def test_select_limited_ids_list - # Set timestamps - Developer.transaction do - Developer.find(:all, :order => 'id').each_with_index do |record, i| - record.update_attributes(:created_at => 5.years.ago + (i * 5.minutes)) - end - end - - join_base = ActiveRecord::Associations::ClassMethods::JoinDependency::JoinBase.new(Project) - join_dep = ActiveRecord::Associations::ClassMethods::JoinDependency.new(join_base, :developers, nil) - projects = Project.send(:select_limited_ids_list, {:order => 'developers.created_at'}, join_dep) - assert !projects.include?("'"), projects - assert_equal %w(1 2), projects.scan(/\d/).sort - end - - def test_scoped_find_on_through_association_doesnt_return_read_only_records - tag = Post.find(1).tags.find_by_name("General") - - assert_nothing_raised do - tag.save! - end - end -end - - -class OverridingAssociationsTest < ActiveSupport::TestCase - class Person < ActiveRecord::Base; end - class DifferentPerson < ActiveRecord::Base; end - - class PeopleList < ActiveRecord::Base - has_and_belongs_to_many :has_and_belongs_to_many, :before_add => :enlist - has_many :has_many, :before_add => :enlist - belongs_to :belongs_to - has_one :has_one - end - - class DifferentPeopleList < PeopleList - # Different association with the same name, callbacks should be omitted here. - has_and_belongs_to_many :has_and_belongs_to_many, :class_name => 'DifferentPerson' - has_many :has_many, :class_name => 'DifferentPerson' - belongs_to :belongs_to, :class_name => 'DifferentPerson' - has_one :has_one, :class_name => 'DifferentPerson' - end - - def test_habtm_association_redefinition_callbacks_should_differ_and_not_inherited - # redeclared association on AR descendant should not inherit callbacks from superclass - callbacks = PeopleList.read_inheritable_attribute(:before_add_for_has_and_belongs_to_many) - assert_equal([:enlist], callbacks) - callbacks = DifferentPeopleList.read_inheritable_attribute(:before_add_for_has_and_belongs_to_many) - assert_equal([], callbacks) - end - - def test_has_many_association_redefinition_callbacks_should_differ_and_not_inherited - # redeclared association on AR descendant should not inherit callbacks from superclass - callbacks = PeopleList.read_inheritable_attribute(:before_add_for_has_many) - assert_equal([:enlist], callbacks) - callbacks = DifferentPeopleList.read_inheritable_attribute(:before_add_for_has_many) - assert_equal([], callbacks) - end - - def test_habtm_association_redefinition_reflections_should_differ_and_not_inherited - assert_not_equal( - PeopleList.reflect_on_association(:has_and_belongs_to_many), - DifferentPeopleList.reflect_on_association(:has_and_belongs_to_many) - ) - end - - def test_has_many_association_redefinition_reflections_should_differ_and_not_inherited - assert_not_equal( - PeopleList.reflect_on_association(:has_many), - DifferentPeopleList.reflect_on_association(:has_many) - ) - end - - def test_belongs_to_association_redefinition_reflections_should_differ_and_not_inherited - assert_not_equal( - PeopleList.reflect_on_association(:belongs_to), - DifferentPeopleList.reflect_on_association(:belongs_to) - ) - end - - def test_has_one_association_redefinition_reflections_should_differ_and_not_inherited - assert_not_equal( - PeopleList.reflect_on_association(:has_one), - DifferentPeopleList.reflect_on_association(:has_one) - ) - end -end Index: activerecord/test/reserved_word_test_mysql.rb =================================================================== --- activerecord/test/reserved_word_test_mysql.rb (revision 8601) +++ activerecord/test/reserved_word_test_mysql.rb (working copy) @@ -1,177 +0,0 @@ -require "#{File.dirname(__FILE__)}/abstract_unit" - -class Group < ActiveRecord::Base - Group.table_name = 'group' - belongs_to :select, :class_name => 'Select' - has_one :values -end - -class Select < ActiveRecord::Base - Select.table_name = 'select' - has_many :groups -end - -class Values < ActiveRecord::Base - Values.table_name = 'values' -end - -class Distinct < ActiveRecord::Base - Distinct.table_name = 'distinct' - has_and_belongs_to_many :selects - has_many :values, :through => :groups -end - -# a suite of tests to ensure the ConnectionAdapters#MysqlAdapter can handle tables with -# reserved word names (ie: group, order, values, etc...) -class MysqlReservedWordTest < ActiveSupport::TestCase - def setup - @connection = ActiveRecord::Base.connection - - # we call execute directly here (and do similar below) because ActiveRecord::Base#create_table() - # will fail with these table names if these test cases fail - - create_tables_directly 'group'=>'id int auto_increment primary key, `order` varchar(255), select_id int', - 'select'=>'id int auto_increment primary key', - 'values'=>'id int auto_increment primary key, group_id int', - 'distinct'=>'id int auto_increment primary key', - 'distincts_selects'=>'distinct_id int, select_id int' - end - - def teardown - drop_tables_directly ['group', 'select', 'values', 'distinct', 'distincts_selects', 'order'] - end - - # create tables with reserved-word names and columns - def test_create_tables - assert_nothing_raised { - @connection.create_table :order do |t| - t.column :group, :string - end - } - end - - # rename tables with reserved-word names - def test_rename_tables - assert_nothing_raised { @connection.rename_table(:group, :order) } - end - - # alter column with a reserved-word name in a table with a reserved-word name - def test_change_columns - assert_nothing_raised { @connection.change_column_default(:group, :order, 'whatever') } - #the quoting here will reveal any double quoting issues in change_column's interaction with the column method in the adapter - assert_nothing_raised { @connection.change_column('group', 'order', :Int, :default => 0) } - assert_nothing_raised { @connection.rename_column(:group, :order, :values) } - end - - # dump structure of table with reserved word name - def test_structure_dump - assert_nothing_raised { @connection.structure_dump } - end - - # introspect table with reserved word name - def test_introspect - assert_nothing_raised { @connection.columns(:group) } - assert_nothing_raised { @connection.indexes(:group) } - end - - #fixtures - self.use_instantiated_fixtures = true - self.use_transactional_fixtures = false - - #fixtures :group - - def test_fixtures - f = create_test_fixtures :select, :distinct, :group, :values, :distincts_selects - - assert_nothing_raised { - f.each do |x| - x.delete_existing_fixtures - end - } - - assert_nothing_raised { - f.each do |x| - x.insert_fixtures - end - } - end - - #activerecord model class with reserved-word table name - def test_activerecord_model - create_test_fixtures :select, :distinct, :group, :values, :distincts_selects - x = nil - assert_nothing_raised { x = Group.new } - x.order = 'x' - assert_nothing_raised { x.save } - x.order = 'y' - assert_nothing_raised { x.save } - assert_nothing_raised { y = Group.find_by_order('y') } - assert_nothing_raised { y = Group.find(1) } - x = Group.find(1) - end - - # has_one association with reserved-word table name - def test_has_one_associations - create_test_fixtures :select, :distinct, :group, :values, :distincts_selects - v = nil - assert_nothing_raised { v = Group.find(1).values } - assert_equal v.id, 2 - end - - # belongs_to association with reserved-word table name - def test_belongs_to_associations - create_test_fixtures :select, :distinct, :group, :values, :distincts_selects - gs = nil - assert_nothing_raised { gs = Select.find(2).groups } - assert_equal gs.length, 2 - assert(gs.collect{|x| x.id}.sort == [2, 3]) - end - - # has_and_belongs_to_many with reserved-word table name - def test_has_and_belongs_to_many - create_test_fixtures :select, :distinct, :group, :values, :distincts_selects - s = nil - assert_nothing_raised { s = Distinct.find(1).selects } - assert_equal s.length, 2 - assert(s.collect{|x|x.id}.sort == [1, 2]) - end - - # activerecord model introspection with reserved-word table and column names - def test_activerecord_introspection - assert_nothing_raised { Group.table_exists? } - assert_nothing_raised { Group.columns } - end - - # Calculations - def test_calculations_work_with_reserved_words - assert_nothing_raised { Group.count } - end - - def test_associations_work_with_reserved_words - assert_nothin