diff options
Diffstat (limited to 'activerecord/test')
51 files changed, 1483 insertions, 582 deletions
diff --git a/activerecord/test/active_record/connection_adapters/fake_adapter.rb b/activerecord/test/active_record/connection_adapters/fake_adapter.rb index 69dfd2503e..1199be68eb 100644 --- a/activerecord/test/active_record/connection_adapters/fake_adapter.rb +++ b/activerecord/test/active_record/connection_adapters/fake_adapter.rb @@ -1,6 +1,6 @@ module ActiveRecord - class Base - def self.fake_connection(config) + module ConnectionHandling + def fake_connection(config) ConnectionAdapters::FakeAdapter.new nil, logger end end diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb index 684c7f5929..276c499276 100644 --- a/activerecord/test/cases/adapters/mysql2/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb @@ -4,6 +4,13 @@ class MysqlConnectionTest < ActiveRecord::TestCase def setup super @connection = ActiveRecord::Model.connection + @connection.extend(LogIntercepter) + @connection.intercepted = true + end + + def teardown + @connection.intercepted = false + @connection.logged = [] end def test_no_automatic_reconnection_after_timeout @@ -45,6 +52,26 @@ class MysqlConnectionTest < ActiveRecord::TestCase end end + def test_logs_name_structure_dump + @connection.structure_dump + assert_equal "SCHEMA", @connection.logged[0][1] + assert_equal "SCHEMA", @connection.logged[2][1] + end + + def test_logs_name_show_variable + @connection.show_variable 'foo' + assert_equal "SCHEMA", @connection.logged[0][1] + end + + def test_logs_name_rename_column_sql + @connection.execute "CREATE TABLE `bar_baz` (`foo` varchar(255))" + @connection.logged = [] + @connection.send(:rename_column_sql, 'bar_baz', 'foo', 'foo2') + assert_equal "SCHEMA", @connection.logged[0][1] + ensure + @connection.execute "DROP TABLE `bar_baz`" + end + private def run_without_connection diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb index 4baec749ff..f6e168caf2 100644 --- a/activerecord/test/cases/adapters/postgresql/connection_test.rb +++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb @@ -8,12 +8,23 @@ module ActiveRecord def setup super @connection = ActiveRecord::Base.connection + @connection.extend(LogIntercepter) + @connection.intercepted = true + end + + def teardown + @connection.intercepted = false + @connection.logged = [] end def test_encoding assert_not_nil @connection.encoding end + def test_default_client_min_messages + assert_equal "warning", @connection.client_min_messages + end + # Ensure, we can set connection params using the example of Generic # Query Optimizer (geqo). It is 'on' per default. def test_connection_options @@ -25,5 +36,42 @@ module ActiveRecord expect = NonExistentTable.connection.query('show geqo').first.first assert_equal 'off', expect end + + def test_tables_logs_name + @connection.tables('hello') + assert_equal 'SCHEMA', @connection.logged[0][1] + end + + def test_indexes_logs_name + @connection.indexes('items', 'hello') + assert_equal 'SCHEMA', @connection.logged[0][1] + end + + def test_table_exists_logs_name + @connection.table_exists?('items') + assert_equal 'SCHEMA', @connection.logged[0][1] + end + + def test_table_alias_length_logs_name + @connection.instance_variable_set("@table_alias_length", nil) + @connection.table_alias_length + assert_equal 'SCHEMA', @connection.logged[0][1] + end + + def test_current_database_logs_name + @connection.current_database + assert_equal 'SCHEMA', @connection.logged[0][1] + end + + def test_encoding_logs_name + @connection.encoding + assert_equal 'SCHEMA', @connection.logged[0][1] + end + + def test_schema_names_logs_name + @connection.schema_names + assert_equal 'SCHEMA', @connection.logged[0][1] + end + end end diff --git a/activerecord/test/cases/adapters/postgresql/datatype_test.rb b/activerecord/test/cases/adapters/postgresql/datatype_test.rb index 34660577da..a4d9286d52 100644 --- a/activerecord/test/cases/adapters/postgresql/datatype_test.rb +++ b/activerecord/test/cases/adapters/postgresql/datatype_test.rb @@ -27,6 +27,9 @@ end class PostgresqlTimestampWithZone < ActiveRecord::Base end +class PostgresqlUUID < ActiveRecord::Base +end + class PostgresqlDataTypeTest < ActiveRecord::TestCase self.use_transactional_fixtures = false @@ -61,6 +64,9 @@ class PostgresqlDataTypeTest < ActiveRecord::TestCase @first_oid = PostgresqlOid.find(1) @connection.execute("INSERT INTO postgresql_timestamp_with_zones (time) VALUES ('2010-01-01 10:00:00-1')") + + @connection.execute("INSERT INTO postgresql_uuids (guid, compact_guid) VALUES('d96c3da0-96c1-012f-1316-64ce8f32c6d8', 'f06c715096c1012f131764ce8f32c6d8')") + @first_uuid = PostgresqlUUID.find(1) end def test_data_type_of_array_types @@ -100,6 +106,10 @@ class PostgresqlDataTypeTest < ActiveRecord::TestCase assert_equal :integer, @first_oid.column_for_attribute(:obj_id).type end + def test_data_type_of_uuid_types + assert_equal :uuid, @first_uuid.column_for_attribute(:guid).type + end + def test_array_values assert_equal '{35000,21000,18000,17000}', @first_array.commission_by_quarter assert_equal '{foo,bar,baz}', @first_array.nicknames @@ -143,6 +153,11 @@ class PostgresqlDataTypeTest < ActiveRecord::TestCase assert_equal '01:23:45:67:89:0a', @first_network_address.mac_address end + def test_uuid_values + assert_equal 'd96c3da0-96c1-012f-1316-64ce8f32c6d8', @first_uuid.guid + assert_equal 'f06c7150-96c1-012f-1317-64ce8f32c6d8', @first_uuid.compact_guid + end + def test_bit_string_values assert_equal '00010101', @first_bit_string.bit_string assert_equal '00010101', @first_bit_string.bit_string_varying diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index 8a7f44d0a3..5e947799cc 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -20,6 +20,14 @@ module ActiveRecord number integer ) eosql + + @conn.extend(LogIntercepter) + @conn.intercepted = true + end + + def teardown + @conn.intercepted = false + @conn.logged = [] end def test_column_types @@ -232,13 +240,23 @@ module ActiveRecord end def test_tables_logs_name - name = "hello" - assert_logged [[name, []]] do - @conn.tables(name) + assert_logged [['SCHEMA', []]] do + @conn.tables('hello') assert_not_nil @conn.logged.first.shift end end + def test_indexes_logs_name + assert_logged [["PRAGMA index_list(\"items\")", 'SCHEMA', []]] do + @conn.indexes('items', 'hello') + end + end + + def test_table_exists_logs_name + assert @conn.table_exists?('items') + assert_equal 'SCHEMA', @conn.logged[0][1] + end + def test_columns columns = @conn.columns('items').sort_by { |x| x.name } assert_equal 2, columns.length @@ -274,7 +292,6 @@ module ActiveRecord end def test_indexes_logs - intercept_logs_on @conn assert_difference('@conn.logged.length') do @conn.indexes('items') end @@ -326,21 +343,10 @@ module ActiveRecord private def assert_logged logs - intercept_logs_on @conn yield assert_equal logs, @conn.logged end - def intercept_logs_on ctx - @conn.extend(Module.new { - attr_accessor :logged - def log sql, name, binds = [] - @logged << [sql, name, binds] - yield - end - }) - @conn.logged = [] - end end end end diff --git a/activerecord/test/cases/aggregations_test.rb b/activerecord/test/cases/aggregations_test.rb deleted file mode 100644 index 5bd8f76ba2..0000000000 --- a/activerecord/test/cases/aggregations_test.rb +++ /dev/null @@ -1,158 +0,0 @@ -require "cases/helper" -require 'models/customer' -require 'active_support/core_ext/exception' - -class AggregationsTest < ActiveRecord::TestCase - fixtures :customers - - def test_find_single_value_object - assert_equal 50, customers(:david).balance.amount - assert_kind_of Money, customers(:david).balance - assert_equal 300, customers(:david).balance.exchange_to("DKK").amount - end - - def test_find_multiple_value_object - assert_equal customers(:david).address_street, customers(:david).address.street - assert( - customers(:david).address.close_to?(Address.new("Different Street", customers(:david).address_city, customers(:david).address_country)) - ) - end - - def test_change_single_value_object - customers(:david).balance = Money.new(100) - customers(:david).save - assert_equal 100, customers(:david).reload.balance.amount - end - - def test_immutable_value_objects - customers(:david).balance = Money.new(100) - assert_raise(ActiveSupport::FrozenObjectError) { customers(:david).balance.instance_eval { @amount = 20 } } - end - - def test_inferred_mapping - assert_equal "35.544623640962634", customers(:david).gps_location.latitude - assert_equal "-105.9309951055148", customers(:david).gps_location.longitude - - customers(:david).gps_location = GpsLocation.new("39x-110") - - assert_equal "39", customers(:david).gps_location.latitude - assert_equal "-110", customers(:david).gps_location.longitude - - customers(:david).save - - customers(:david).reload - - assert_equal "39", customers(:david).gps_location.latitude - assert_equal "-110", customers(:david).gps_location.longitude - end - - def test_reloaded_instance_refreshes_aggregations - assert_equal "35.544623640962634", customers(:david).gps_location.latitude - assert_equal "-105.9309951055148", customers(:david).gps_location.longitude - - Customer.update_all("gps_location = '24x113'") - customers(:david).reload - assert_equal '24x113', customers(:david)['gps_location'] - - assert_equal GpsLocation.new('24x113'), customers(:david).gps_location - end - - def test_gps_equality - assert_equal GpsLocation.new('39x110'), GpsLocation.new('39x110') - end - - def test_gps_inequality - assert_not_equal GpsLocation.new('39x110'), GpsLocation.new('39x111') - end - - def test_allow_nil_gps_is_nil - assert_nil customers(:zaphod).gps_location - end - - def test_allow_nil_gps_set_to_nil - customers(:david).gps_location = nil - customers(:david).save - customers(:david).reload - assert_nil customers(:david).gps_location - end - - def test_allow_nil_set_address_attributes_to_nil - customers(:zaphod).address = nil - assert_nil customers(:zaphod).attributes[:address_street] - assert_nil customers(:zaphod).attributes[:address_city] - assert_nil customers(:zaphod).attributes[:address_country] - end - - def test_allow_nil_address_set_to_nil - customers(:zaphod).address = nil - customers(:zaphod).save - customers(:zaphod).reload - assert_nil customers(:zaphod).address - end - - def test_nil_raises_error_when_allow_nil_is_false - assert_raise(NoMethodError) { customers(:david).balance = nil } - end - - def test_allow_nil_address_loaded_when_only_some_attributes_are_nil - customers(:zaphod).address_street = nil - customers(:zaphod).save - customers(:zaphod).reload - assert_kind_of Address, customers(:zaphod).address - assert_nil customers(:zaphod).address.street - end - - def test_nil_assignment_results_in_nil - customers(:david).gps_location = GpsLocation.new('39x111') - assert_not_nil customers(:david).gps_location - customers(:david).gps_location = nil - assert_nil customers(:david).gps_location - end - - def test_nil_return_from_converter_is_respected_when_allow_nil_is_true - customers(:david).non_blank_gps_location = "" - customers(:david).save - customers(:david).reload - assert_nil customers(:david).non_blank_gps_location - end - - def test_nil_return_from_converter_results_in_failure_when_allow_nil_is_false - assert_raises(NoMethodError) do - customers(:barney).gps_location = "" - end - end - - def test_do_not_run_the_converter_when_nil_was_set - customers(:david).non_blank_gps_location = nil - assert_nil Customer.gps_conversion_was_run - end - - def test_custom_constructor - assert_equal 'Barney GUMBLE', customers(:barney).fullname.to_s - assert_kind_of Fullname, customers(:barney).fullname - end - - def test_custom_converter - customers(:barney).fullname = 'Barnoit Gumbleau' - assert_equal 'Barnoit GUMBLEAU', customers(:barney).fullname.to_s - assert_kind_of Fullname, customers(:barney).fullname - end -end - -class OverridingAggregationsTest < ActiveRecord::TestCase - class Name; end - class DifferentName; end - - class Person < ActiveRecord::Base - composed_of :composed_of, :mapping => %w(person_first_name first_name) - end - - class DifferentPerson < Person - composed_of :composed_of, :class_name => 'DifferentName', :mapping => %w(different_person_first_name first_name) - end - - def test_composed_of_aggregation_redefinition_reflections_should_differ_and_not_inherited - assert_not_equal Person.reflect_on_aggregation(:composed_of), - DifferentPerson.reflect_on_aggregation(:composed_of) - end -end diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index 08467900f9..31b11ee334 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -29,11 +29,6 @@ class EagerAssociationTest < ActiveRecord::TestCase :owners, :pets, :author_favorites, :jobs, :references, :subscribers, :subscriptions, :books, :developers, :projects, :developers_projects, :members, :memberships, :clubs, :sponsors - def setup - # preheat table existence caches - Comment.find_by_id(1) - end - def test_eager_with_has_one_through_join_model_with_conditions_on_the_through member = Member.scoped(:includes => :favourite_club).find(members(:some_other_guy).id) assert_nil member.favourite_club @@ -983,7 +978,6 @@ class EagerAssociationTest < ActiveRecord::TestCase Post.scoped(:includes => :author, :joins => {:taggings => {:tag => :taggings}}, :where => "taggings_tags.super_tag_id=2", :order => 'posts.id').all end assert_equal posts(:welcome, :thinking), posts - end def test_eager_loading_with_conditions_on_string_joined_table_preloads @@ -998,7 +992,6 @@ class EagerAssociationTest < ActiveRecord::TestCase end assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} - end def test_eager_loading_with_select_on_joined_table_preloads @@ -1010,8 +1003,6 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_eager_loading_with_conditions_on_join_model_preloads - Author.columns - authors = assert_queries(2) do Author.scoped(:includes => :author_address, :joins => :comments, :where => "posts.title like 'Welcome%'").all end diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index ed1caa2ef5..9d693bae0c 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -817,11 +817,14 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase # clear cache possibly created by other tests david.projects.reset_column_information - assert_queries(1) { david.projects.columns; david.projects.columns } + assert_queries(:any) { david.projects.columns } + assert_no_queries { david.projects.columns } ## and again to verify that reset_column_information clears the cache correctly david.projects.reset_column_information - assert_queries(1) { david.projects.columns; david.projects.columns } + + assert_queries(:any) { david.projects.columns } + assert_no_queries { david.projects.columns } end def test_attributes_are_being_set_when_initialized_from_habm_association_with_where_clause diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 8b384c2513..b8481175b2 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -936,10 +936,24 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal 2, summit.client_of end - def test_deleting_type_mismatch + def test_deleting_by_fixnum_id david = Developer.find(1) - david.projects.reload - assert_raise(ActiveRecord::AssociationTypeMismatch) { david.projects.delete(1) } + + assert_difference 'david.projects.count', -1 do + assert_equal 1, david.projects.delete(1).size + end + + assert_equal 1, david.projects.size + end + + def test_deleting_by_string_id + david = Developer.find(1) + + assert_difference 'david.projects.count', -1 do + assert_equal 1, david.projects.delete('1').size + end + + assert_equal 1, david.projects.size end def test_deleting_self_type_mismatch @@ -1344,7 +1358,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase end assert_equal author.essays, Essay.where(writer_id: "David") - end def test_has_many_custom_primary_key @@ -1424,7 +1437,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase :group => "#{Namespaced::Firm.table_name}.id" ).find firm.id assert_equal 1, stats.num_clients.to_i - ensure ActiveRecord::Base.store_full_sti_class = old end diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index ecc676f300..783b83631c 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -578,7 +578,27 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase end def test_deleting_junk_from_has_many_through_should_raise_type_mismatch - assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags.delete("Uhh what now?") } + assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags.delete(Object.new) } + end + + def test_deleting_by_fixnum_id_from_has_many_through + post = posts(:thinking) + + assert_difference 'post.tags.count', -1 do + assert_equal 1, post.tags.delete(1).size + end + + assert_equal 0, post.tags.size + end + + def test_deleting_by_string_id_from_has_many_through + post = posts(:thinking) + + assert_difference 'post.tags.count', -1 do + assert_equal 1, post.tags.delete('1').size + end + + assert_equal 0, post.tags.size end def test_has_many_through_sum_uses_calculations diff --git a/activerecord/test/cases/attribute_methods/read_test.rb b/activerecord/test/cases/attribute_methods/read_test.rb index 98c38535a6..f4c40b8b97 100644 --- a/activerecord/test/cases/attribute_methods/read_test.rb +++ b/activerecord/test/cases/attribute_methods/read_test.rb @@ -15,6 +15,7 @@ module ActiveRecord def self.active_record_super; Base; end def self.base_class; self; end + extend ActiveRecord::Configuration include ActiveRecord::AttributeMethods def self.define_attribute_methods diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 619fb881fa..2fee553cef 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -888,22 +888,6 @@ class BasicsTest < ActiveRecord::TestCase assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on end - def test_multiparameter_assignment_of_aggregation - customer = Customer.new - address = Address.new("The Street", "The City", "The Country") - attributes = { "address(1)" => address.street, "address(2)" => address.city, "address(3)" => address.country } - customer.attributes = attributes - assert_equal address, customer.address - end - - def test_multiparameter_assignment_of_aggregation_out_of_order - customer = Customer.new - address = Address.new("The Street", "The City", "The Country") - attributes = { "address(3)" => address.country, "address(2)" => address.city, "address(1)" => address.street } - customer.attributes = attributes - assert_equal address, customer.address - end - def test_multiparameter_assignment_of_aggregation_with_missing_values ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do customer = Customer.new @@ -914,14 +898,6 @@ class BasicsTest < ActiveRecord::TestCase assert_equal("address", ex.errors[0].attribute) end - def test_multiparameter_assignment_of_aggregation_with_blank_values - customer = Customer.new - address = Address.new("The Street", "The City", "The Country") - attributes = { "address(1)" => "", "address(2)" => address.city, "address(3)" => address.country } - customer.attributes = attributes - assert_equal Address.new(nil, "The City", "The Country"), customer.address - end - def test_multiparameter_assignment_of_aggregation_with_large_index ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do customer = Customer.new @@ -1021,26 +997,6 @@ class BasicsTest < ActiveRecord::TestCase assert_equal("c", duped_topic.title) end - def test_dup_with_aggregate_of_same_name_as_attribute - dev = DeveloperWithAggregate.find(1) - assert_kind_of DeveloperSalary, dev.salary - - dup = nil - assert_nothing_raised { dup = dev.dup } - assert_kind_of DeveloperSalary, dup.salary - assert_equal dev.salary.amount, dup.salary.amount - assert !dup.persisted? - - # test if the attributes have been dupd - original_amount = dup.salary.amount - dev.salary.amount = 1 - assert_equal original_amount, dup.salary.amount - - assert dup.save - assert dup.persisted? - assert_not_equal dup.id, dev.id - end - def test_dup_does_not_copy_associations author = authors(:david) assert_not_equal [], author.posts @@ -1309,6 +1265,15 @@ class BasicsTest < ActiveRecord::TestCase assert_equal({ :foo => :bar }, t.content_before_type_cast) end + def test_serialized_attribute_calling_dup_method + klass = Class.new(ActiveRecord::Base) + klass.table_name = "topics" + klass.serialize :content, JSON + + t = klass.new(:content => { :foo => :bar }).dup + assert_equal({ :foo => :bar }, t.content_before_type_cast) + end + def test_serialized_attribute_declared_in_subclass hash = { 'important1' => 'value1', 'important2' => 'value2' } important_topic = ImportantTopic.create("important" => hash) @@ -1514,6 +1479,8 @@ class BasicsTest < ActiveRecord::TestCase after_seq = Joke.sequence_name assert_equal before_seq, after_seq unless before_seq.nil? && after_seq.nil? + ensure + Joke.reset_sequence_name end def test_dont_clear_inheritnce_column_when_setting_explicitly @@ -1926,7 +1893,7 @@ class BasicsTest < ActiveRecord::TestCase def test_cache_key_format_for_existing_record_with_nil_updated_at dev = Developer.first - dev.update_attribute(:updated_at, nil) + dev.update_column(:updated_at, nil) assert_match(/\/#{dev.id}$/, dev.cache_key) end diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 041f8ffb7c..f748b897ee 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -376,6 +376,22 @@ class CalculationsTest < ActiveRecord::TestCase Company.where(:type => "Firm").from('companies').count(:type) end + def test_count_with_block_acts_as_array + accounts = Account.where('id > 0') + assert_equal Account.count, accounts.count { true } + assert_equal 0, accounts.count { false } + assert_equal Account.where('credit_limit > 50').size, accounts.count { |account| account.credit_limit > 50 } + assert_equal Account.count, Account.count { true } + assert_equal 0, Account.count { false } + end + + def test_sum_with_block_acts_as_array + accounts = Account.where('id > 0') + assert_equal Account.sum(:credit_limit), accounts.sum { |account| account.credit_limit } + assert_equal Account.sum(:credit_limit) + Account.count, accounts.sum{ |account| account.credit_limit + 1 } + assert_equal 0, accounts.sum { |account| 0 } + end + def test_sum_with_from_option assert_equal Account.sum(:credit_limit), Account.from('accounts').sum(:credit_limit) assert_equal Account.where("credit_limit > 50").sum(:credit_limit), @@ -404,6 +420,40 @@ class CalculationsTest < ActiveRecord::TestCase Account.where("credit_limit > 50").from('accounts').maximum(:credit_limit) end + def test_maximum_with_not_auto_table_name_prefix_if_column_included + Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)]) + + # TODO: Investigate why PG isn't being typecast + if current_adapter?(:PostgreSQLAdapter) + assert_equal "7", Company.includes(:contracts).maximum(:developer_id) + else + assert_equal 7, Company.includes(:contracts).maximum(:developer_id) + end + end + + def test_minimum_with_not_auto_table_name_prefix_if_column_included + Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)]) + + # TODO: Investigate why PG isn't being typecast + if current_adapter?(:PostgreSQLAdapter) + assert_equal "7", Company.includes(:contracts).minimum(:developer_id) + else + assert_equal 7, Company.includes(:contracts).minimum(:developer_id) + end + end + + def test_sum_with_not_auto_table_name_prefix_if_column_included + Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)]) + + # TODO: Investigate why PG isn't being typecast + if current_adapter?(:MysqlAdapter) || current_adapter?(:PostgreSQLAdapter) + assert_equal "7", Company.includes(:contracts).sum(:developer_id) + else + assert_equal 7, Company.includes(:contracts).sum(:developer_id) + end + end + + def test_from_option_with_specified_index if Edge.connection.adapter_name == 'MySQL' or Edge.connection.adapter_name == 'Mysql2' assert_equal Edge.count(:all), Edge.from('edges USE INDEX(unique_edge_index)').count(:all) @@ -461,6 +511,11 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal [c.id], Company.joins(:contracts).pluck(:id) end + def test_pluck_if_table_included + c = Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)]) + assert_equal [c.id], Company.includes(:contracts).where("contracts.id" => c.contracts.first).pluck(:id) + end + def test_pluck_not_auto_table_name_prefix_if_column_joined Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)]) assert_equal [7], Company.joins(:contracts).pluck(:developer_id) @@ -484,4 +539,11 @@ class CalculationsTest < ActiveRecord::TestCase def test_plucks_with_ids assert_equal Company.all.map(&:id).sort, Company.ids.sort end + + def test_pluck_not_auto_table_name_prefix_if_column_included + Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)]) + ids = Company.includes(:contracts).pluck(:developer_id) + assert_equal Company.count, ids.length + assert_equal [7], ids.compact + end end diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb index 7690769226..deeef3a3fd 100644 --- a/activerecord/test/cases/callbacks_test.rb +++ b/activerecord/test/cases/callbacks_test.rb @@ -426,11 +426,13 @@ class CallbacksTest < ActiveRecord::TestCase def test_before_destroy_returning_false david = ImmutableDeveloper.find(1) assert !david.destroy + assert_raise(ActiveRecord::RecordNotDestroyed) { david.destroy! } assert_not_nil ImmutableDeveloper.find_by_id(1) someone = CallbackCancellationDeveloper.find(1) someone.cancel_before_destroy = true assert !someone.destroy + assert_raise(ActiveRecord::RecordNotDestroyed) { someone.destroy! } assert !someone.after_destroy_called end diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb index a44b49466f..bd2fbaa7db 100644 --- a/activerecord/test/cases/column_definition_test.rb +++ b/activerecord/test/cases/column_definition_test.rb @@ -136,12 +136,6 @@ module ActiveRecord smallint_column = PostgreSQLColumn.new('number', nil, oid, "smallint") assert_equal :integer, smallint_column.type end - - def test_uuid_column_should_map_to_string - oid = PostgreSQLAdapter::OID::Identity.new - uuid_column = PostgreSQLColumn.new('unique_id', nil, oid, "uuid") - assert_equal :string, uuid_column.type - end end end end diff --git a/activerecord/test/cases/connection_adapters/connection_handler_test.rb b/activerecord/test/cases/connection_adapters/connection_handler_test.rb index dc99ac665c..17cb447105 100644 --- a/activerecord/test/cases/connection_adapters/connection_handler_test.rb +++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb @@ -7,12 +7,11 @@ module ActiveRecord @handler = ConnectionHandler.new @handler.establish_connection 'america', Base.connection_pool.spec @klass = Class.new do + include Model::Tag def self.name; 'america'; end - class << self - alias active_record_super superclass - end end @subklass = Class.new(@klass) do + include Model::Tag def self.name; 'north america'; end end end diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb index 6871e628aa..8287b35aaf 100644 --- a/activerecord/test/cases/connection_pool_test.rb +++ b/activerecord/test/cases/connection_pool_test.rb @@ -124,7 +124,7 @@ module ActiveRecord @pool.checkout @pool.checkout @pool.checkout - @pool.timeout = 0 + @pool.dead_connection_timeout = 0 connections = @pool.connections.dup @@ -137,7 +137,7 @@ module ActiveRecord @pool.checkout @pool.checkout @pool.checkout - @pool.timeout = 0 + @pool.dead_connection_timeout = 0 connections = @pool.connections.dup connections.each do |conn| @@ -213,13 +213,8 @@ module ActiveRecord # Thus this test prepares waiting threads and then trickles in # available connections slowly, ensuring the wakeup order is # correct in this case. - # - # Try a few times since it might work out just by chance. def test_checkout_fairness - 4.times { setup; do_checkout_fairness } - end - - def do_checkout_fairness + @pool.instance_variable_set(:@size, 10) expected = (1..@pool.size).to_a.freeze # check out all connections so our threads start out waiting conns = expected.map { @pool.checkout } @@ -230,7 +225,7 @@ module ActiveRecord threads = expected.map do |i| t = Thread.new { begin - conn = @pool.checkout # never checked back in + @pool.checkout # never checked back in mutex.synchronize { order << i } rescue => e mutex.synchronize { errors << e } @@ -256,13 +251,7 @@ module ActiveRecord # group2. Enough connections are checked in to wakeup all # group1 threads, and the fact that only group1 and no group2 # threads acquired a connection is enforced. - # - # Try a few times since it might work out just by chance. def test_checkout_fairness_by_group - 4.times { setup; do_checkout_fairness_by_group } - end - - def do_checkout_fairness_by_group @pool.instance_variable_set(:@size, 10) # take all the connections conns = (1..10).map { @pool.checkout } @@ -273,7 +262,7 @@ module ActiveRecord make_thread = proc do |i| t = Thread.new { begin - conn = @pool.checkout # never checked back in + @pool.checkout # never checked back in mutex.synchronize { successes << i } rescue => e mutex.synchronize { errors << e } diff --git a/activerecord/test/cases/connection_specification/resolver_test.rb b/activerecord/test/cases/connection_specification/resolver_test.rb index e6cb1b9521..673a2b2b88 100644 --- a/activerecord/test/cases/connection_specification/resolver_test.rb +++ b/activerecord/test/cases/connection_specification/resolver_test.rb @@ -9,6 +9,7 @@ module ActiveRecord end def test_url_host_no_db + skip "only if mysql is available" unless defined?(MysqlAdapter) spec = resolve 'mysql://foo?encoding=utf8' assert_equal({ :adapter => "mysql", @@ -18,6 +19,7 @@ module ActiveRecord end def test_url_host_db + skip "only if mysql is available" unless defined?(MysqlAdapter) spec = resolve 'mysql://foo/bar?encoding=utf8' assert_equal({ :adapter => "mysql", @@ -27,6 +29,7 @@ module ActiveRecord end def test_url_port + skip "only if mysql is available" unless defined?(MysqlAdapter) spec = resolve 'mysql://foo:123?encoding=utf8' assert_equal({ :adapter => "mysql", diff --git a/activerecord/test/cases/database_tasks_test.rb b/activerecord/test/cases/database_tasks_test.rb new file mode 100644 index 0000000000..5f36b2c841 --- /dev/null +++ b/activerecord/test/cases/database_tasks_test.rb @@ -0,0 +1,275 @@ +require 'cases/helper' + +module ActiveRecord + module DatabaseTasksSetupper + def setup + @mysql_tasks, @postgresql_tasks, @sqlite_tasks = stub, stub, stub + ActiveRecord::Tasks::MySQLDatabaseTasks.stubs(:new).returns @mysql_tasks + ActiveRecord::Tasks::PostgreSQLDatabaseTasks.stubs(:new).returns @postgresql_tasks + ActiveRecord::Tasks::SQLiteDatabaseTasks.stubs(:new).returns @sqlite_tasks + end + end + + ADAPTERS_TASKS = { + :mysql => :mysql_tasks, + :mysql2 => :mysql_tasks, + :postgresql => :postgresql_tasks, + :sqlite3 => :sqlite_tasks + } + + class DatabaseTasksCreateTest < ActiveRecord::TestCase + include DatabaseTasksSetupper + + ADAPTERS_TASKS.each do |k, v| + define_method("test_#{k}_create") do + eval("@#{v}").expects(:create) + ActiveRecord::Tasks::DatabaseTasks.create 'adapter' => k + end + end + end + + class DatabaseTasksCreateAllTest < ActiveRecord::TestCase + def setup + @configurations = {'development' => {'database' => 'my-db'}} + + ActiveRecord::Base.stubs(:configurations).returns(@configurations) + end + + def test_ignores_configurations_without_databases + @configurations['development'].merge!('database' => nil) + + ActiveRecord::Tasks::DatabaseTasks.expects(:create).never + + ActiveRecord::Tasks::DatabaseTasks.create_all + end + + def test_ignores_remote_databases + @configurations['development'].merge!('host' => 'my.server.tld') + $stderr.stubs(:puts).returns(nil) + + ActiveRecord::Tasks::DatabaseTasks.expects(:create).never + + ActiveRecord::Tasks::DatabaseTasks.create_all + end + + def test_warning_for_remote_databases + @configurations['development'].merge!('host' => 'my.server.tld') + + $stderr.expects(:puts).with('This task only modifies local databases. my-db is on a remote host.') + + ActiveRecord::Tasks::DatabaseTasks.create_all + end + + def test_creates_configurations_with_local_ip + @configurations['development'].merge!('host' => '127.0.0.1') + + ActiveRecord::Tasks::DatabaseTasks.expects(:create) + + ActiveRecord::Tasks::DatabaseTasks.create_all + end + + def test_creates_configurations_with_local_host + @configurations['development'].merge!('host' => 'localhost') + + ActiveRecord::Tasks::DatabaseTasks.expects(:create) + + ActiveRecord::Tasks::DatabaseTasks.create_all + end + + def test_creates_configurations_with_blank_hosts + @configurations['development'].merge!('host' => nil) + + ActiveRecord::Tasks::DatabaseTasks.expects(:create) + + ActiveRecord::Tasks::DatabaseTasks.create_all + end + end + + class DatabaseTasksCreateCurrentTest < ActiveRecord::TestCase + def setup + @configurations = { + 'development' => {'database' => 'dev-db'}, + 'test' => {'database' => 'test-db'}, + 'production' => {'database' => 'prod-db'} + } + + ActiveRecord::Base.stubs(:configurations).returns(@configurations) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_creates_current_environment_database + ActiveRecord::Tasks::DatabaseTasks.expects(:create). + with('database' => 'prod-db') + + ActiveRecord::Tasks::DatabaseTasks.create_current( + ActiveSupport::StringInquirer.new('production') + ) + end + + def test_creates_test_database_when_environment_is_database + ActiveRecord::Tasks::DatabaseTasks.expects(:create). + with('database' => 'dev-db') + ActiveRecord::Tasks::DatabaseTasks.expects(:create). + with('database' => 'test-db') + + ActiveRecord::Tasks::DatabaseTasks.create_current( + ActiveSupport::StringInquirer.new('development') + ) + end + + def test_establishes_connection_for_the_given_environment + ActiveRecord::Tasks::DatabaseTasks.stubs(:create).returns true + + ActiveRecord::Base.expects(:establish_connection).with('development') + + ActiveRecord::Tasks::DatabaseTasks.create_current( + ActiveSupport::StringInquirer.new('development') + ) + end + end + + class DatabaseTasksDropTest < ActiveRecord::TestCase + include DatabaseTasksSetupper + + ADAPTERS_TASKS.each do |k, v| + define_method("test_#{k}_drop") do + eval("@#{v}").expects(:drop) + ActiveRecord::Tasks::DatabaseTasks.drop 'adapter' => k + end + end + end + + class DatabaseTasksDropAllTest < ActiveRecord::TestCase + def setup + @configurations = {:development => {'database' => 'my-db'}} + + ActiveRecord::Base.stubs(:configurations).returns(@configurations) + end + + def test_ignores_configurations_without_databases + @configurations[:development].merge!('database' => nil) + + ActiveRecord::Tasks::DatabaseTasks.expects(:drop).never + + ActiveRecord::Tasks::DatabaseTasks.drop_all + end + + def test_ignores_remote_databases + @configurations[:development].merge!('host' => 'my.server.tld') + $stderr.stubs(:puts).returns(nil) + + ActiveRecord::Tasks::DatabaseTasks.expects(:drop).never + + ActiveRecord::Tasks::DatabaseTasks.drop_all + end + + def test_warning_for_remote_databases + @configurations[:development].merge!('host' => 'my.server.tld') + + $stderr.expects(:puts).with('This task only modifies local databases. my-db is on a remote host.') + + ActiveRecord::Tasks::DatabaseTasks.drop_all + end + + def test_creates_configurations_with_local_ip + @configurations[:development].merge!('host' => '127.0.0.1') + + ActiveRecord::Tasks::DatabaseTasks.expects(:drop) + + ActiveRecord::Tasks::DatabaseTasks.drop_all + end + + def test_creates_configurations_with_local_host + @configurations[:development].merge!('host' => 'localhost') + + ActiveRecord::Tasks::DatabaseTasks.expects(:drop) + + ActiveRecord::Tasks::DatabaseTasks.drop_all + end + + def test_creates_configurations_with_blank_hosts + @configurations[:development].merge!('host' => nil) + + ActiveRecord::Tasks::DatabaseTasks.expects(:drop) + + ActiveRecord::Tasks::DatabaseTasks.drop_all + end + end + + class DatabaseTasksDropCurrentTest < ActiveRecord::TestCase + def setup + @configurations = { + 'development' => {'database' => 'dev-db'}, + 'test' => {'database' => 'test-db'}, + 'production' => {'database' => 'prod-db'} + } + + ActiveRecord::Base.stubs(:configurations).returns(@configurations) + end + + def test_creates_current_environment_database + ActiveRecord::Tasks::DatabaseTasks.expects(:drop). + with('database' => 'prod-db') + + ActiveRecord::Tasks::DatabaseTasks.drop_current( + ActiveSupport::StringInquirer.new('production') + ) + end + + def test_creates_test_database_when_environment_is_database + ActiveRecord::Tasks::DatabaseTasks.expects(:drop). + with('database' => 'dev-db') + ActiveRecord::Tasks::DatabaseTasks.expects(:drop). + with('database' => 'test-db') + + ActiveRecord::Tasks::DatabaseTasks.drop_current( + ActiveSupport::StringInquirer.new('development') + ) + end + end + + + class DatabaseTasksPurgeTest < ActiveRecord::TestCase + include DatabaseTasksSetupper + + ADAPTERS_TASKS.each do |k, v| + define_method("test_#{k}_purge") do + eval("@#{v}").expects(:purge) + ActiveRecord::Tasks::DatabaseTasks.purge 'adapter' => k + end + end + end + + class DatabaseTasksCharsetTest < ActiveRecord::TestCase + include DatabaseTasksSetupper + + ADAPTERS_TASKS.each do |k, v| + define_method("test_#{k}_charset") do + eval("@#{v}").expects(:charset) + ActiveRecord::Tasks::DatabaseTasks.charset 'adapter' => k + end + end + end + + class DatabaseTasksStructureDumpTest < ActiveRecord::TestCase + include DatabaseTasksSetupper + + ADAPTERS_TASKS.each do |k, v| + define_method("test_#{k}_structure_dump") do + eval("@#{v}").expects(:structure_dump).with("awesome-file.sql") + ActiveRecord::Tasks::DatabaseTasks.structure_dump({'adapter' => k}, "awesome-file.sql") + end + end + end + + class DatabaseTasksStructureLoadTest < ActiveRecord::TestCase + include DatabaseTasksSetupper + + ADAPTERS_TASKS.each do |k, v| + define_method("test_#{k}_structure_load") do + eval("@#{v}").expects(:structure_load).with("awesome-file.sql") + ActiveRecord::Tasks::DatabaseTasks.structure_load({'adapter' => k}, "awesome-file.sql") + end + end + end +end diff --git a/activerecord/test/cases/deprecated_dynamic_methods_test.rb b/activerecord/test/cases/deprecated_dynamic_methods_test.rb index 77a609f49a..7c108b983e 100644 --- a/activerecord/test/cases/deprecated_dynamic_methods_test.rb +++ b/activerecord/test/cases/deprecated_dynamic_methods_test.rb @@ -45,32 +45,6 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase assert_equal [], Topic.find_all_by_title("The First Topic!!") end - def test_find_all_by_one_attribute_that_is_an_aggregate - balance = customers(:david).balance - assert_kind_of Money, balance - found_customers = Customer.find_all_by_balance(balance) - assert_equal 1, found_customers.size - assert_equal customers(:david), found_customers.first - end - - def test_find_all_by_two_attributes_that_are_both_aggregates - balance = customers(:david).balance - address = customers(:david).address - assert_kind_of Money, balance - assert_kind_of Address, address - found_customers = Customer.find_all_by_balance_and_address(balance, address) - assert_equal 1, found_customers.size - assert_equal customers(:david), found_customers.first - end - - def test_find_all_by_two_attributes_with_one_being_an_aggregate - balance = customers(:david).balance - assert_kind_of Money, balance - found_customers = Customer.find_all_by_balance_and_name(balance, customers(:david).name) - assert_equal 1, found_customers.size - assert_equal customers(:david), found_customers.first - end - def test_find_all_by_one_attribute_with_options topics = Topic.find_all_by_content("Have a nice day", :order => "id DESC") assert_equal topics(:first), topics.last @@ -137,14 +111,6 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase assert_equal 17, sig38.firm_id end - def test_find_or_create_from_two_attributes_with_one_being_an_aggregate - number_of_customers = Customer.count - created_customer = Customer.find_or_create_by_balance_and_name(Money.new(123), "Elizabeth") - assert_equal number_of_customers + 1, Customer.count - assert_equal created_customer, Customer.find_or_create_by_balance(Money.new(123), "Elizabeth") - assert created_customer.persisted? - end - def test_find_or_create_from_one_attribute_and_hash number_of_companies = Company.count sig38 = Company.find_or_create_by_name({:name => "38signals", :firm_id => 17, :client_of => 23}) @@ -167,38 +133,12 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase assert_equal 23, sig38.client_of end - def test_find_or_create_from_one_aggregate_attribute - number_of_customers = Customer.count - created_customer = Customer.find_or_create_by_balance(Money.new(123)) - assert_equal number_of_customers + 1, Customer.count - assert_equal created_customer, Customer.find_or_create_by_balance(Money.new(123)) - assert created_customer.persisted? - end - - def test_find_or_create_from_one_aggregate_attribute_and_hash - number_of_customers = Customer.count - balance = Money.new(123) - name = "Elizabeth" - created_customer = Customer.find_or_create_by_balance({:balance => balance, :name => name}) - assert_equal number_of_customers + 1, Customer.count - assert_equal created_customer, Customer.find_or_create_by_balance({:balance => balance, :name => name}) - assert created_customer.persisted? - assert_equal balance, created_customer.balance - assert_equal name, created_customer.name - end - def test_find_or_initialize_from_one_attribute sig38 = Company.find_or_initialize_by_name("38signals") assert_equal "38signals", sig38.name assert !sig38.persisted? end - def test_find_or_initialize_from_one_aggregate_attribute - new_customer = Customer.find_or_initialize_by_balance(Money.new(123)) - assert_equal 123, new_customer.balance.amount - assert !new_customer.persisted? - end - def test_find_or_initialize_from_one_attribute_should_not_set_attribute_even_when_protected c = Company.find_or_initialize_by_name({:name => "Fortune 1000", :rating => 1000}) assert_equal "Fortune 1000", c.name @@ -285,13 +225,6 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase assert_raise(ArgumentError) { Topic.find_or_initialize_by_title_and_author_name("Another topic") } end - def test_find_or_initialize_from_one_aggregate_attribute_and_one_not - new_customer = Customer.find_or_initialize_by_balance_and_name(Money.new(123), "Elizabeth") - assert_equal 123, new_customer.balance.amount - assert_equal "Elizabeth", new_customer.name - assert !new_customer.persisted? - end - def test_find_or_initialize_from_one_attribute_and_hash sig38 = Company.find_or_initialize_by_name({:name => "38signals", :firm_id => 17, :client_of => 23}) assert_equal "38signals", sig38.name @@ -300,15 +233,6 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase assert !sig38.persisted? end - def test_find_or_initialize_from_one_aggregate_attribute_and_hash - balance = Money.new(123) - name = "Elizabeth" - new_customer = Customer.find_or_initialize_by_balance({:balance => balance, :name => name}) - assert_equal balance, new_customer.balance - assert_equal name, new_customer.name - assert !new_customer.persisted? - end - def test_find_last_by_one_attribute assert_equal Topic.last, Topic.find_last_by_title(Topic.last.title) assert_nil Topic.find_last_by_title("A title with no matches") diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb index 2650040a80..97ffc068af 100644 --- a/activerecord/test/cases/dirty_test.rb +++ b/activerecord/test/cases/dirty_test.rb @@ -79,6 +79,17 @@ class DirtyTest < ActiveRecord::TestCase end end + def test_setting_time_attributes_with_time_zone_field_to_itself_should_not_be_marked_as_a_change + in_time_zone 'Paris' do + target = Class.new(ActiveRecord::Base) + target.table_name = 'pirates' + + pirate = target.create + pirate.created_on = pirate.created_on + assert !pirate.created_on_changed? + end + end + def test_time_attributes_changes_without_time_zone_by_skip in_time_zone 'Paris' do target = Class.new(ActiveRecord::Base) @@ -485,16 +496,6 @@ class DirtyTest < ActiveRecord::TestCase assert_not_nil pirate.previous_changes['updated_on'][1] assert !pirate.previous_changes.key?('parrot_id') assert !pirate.previous_changes.key?('created_on') - - pirate = Pirate.find_by_catchphrase("Ahoy!") - pirate.update_attribute(:catchphrase, "Ninjas suck!") - - assert_equal 2, pirate.previous_changes.size - assert_equal ["Ahoy!", "Ninjas suck!"], pirate.previous_changes['catchphrase'] - assert_not_nil pirate.previous_changes['updated_on'][0] - assert_not_nil pirate.previous_changes['updated_on'][1] - assert !pirate.previous_changes.key?('parrot_id') - assert !pirate.previous_changes.key?('created_on') end if ActiveRecord::Base.connection.supports_migrations? diff --git a/activerecord/test/cases/explain_subscriber_test.rb b/activerecord/test/cases/explain_subscriber_test.rb index e118add44c..91e1df91cd 100644 --- a/activerecord/test/cases/explain_subscriber_test.rb +++ b/activerecord/test/cases/explain_subscriber_test.rb @@ -6,14 +6,14 @@ if ActiveRecord::Base.connection.supports_explain? def test_collects_nothing_if_available_queries_for_explain_is_nil with_queries(nil) do - SUBSCRIBER.call + SUBSCRIBER.finish(nil, nil, {}) assert_nil Thread.current[:available_queries_for_explain] end end def test_collects_nothing_if_the_payload_has_an_exception with_queries([]) do |queries| - SUBSCRIBER.call(:exception => Exception.new) + SUBSCRIBER.finish(nil, nil, :exception => Exception.new) assert queries.empty? end end @@ -21,7 +21,7 @@ if ActiveRecord::Base.connection.supports_explain? def test_collects_nothing_for_ignored_payloads with_queries([]) do |queries| ActiveRecord::ExplainSubscriber::IGNORED_PAYLOADS.each do |ip| - SUBSCRIBER.call(:name => ip) + SUBSCRIBER.finish(nil, nil, :name => ip) end assert queries.empty? end @@ -31,7 +31,7 @@ if ActiveRecord::Base.connection.supports_explain? sql = 'select 1 from users' binds = [1, 2] with_queries([]) do |queries| - SUBSCRIBER.call(:name => 'SQL', :sql => sql, :binds => binds) + SUBSCRIBER.finish(nil, nil, :name => 'SQL', :sql => sql, :binds => binds) assert_equal 1, queries.size assert_equal sql, queries[0][0] assert_equal binds, queries[0][1] @@ -45,4 +45,4 @@ if ActiveRecord::Base.connection.supports_explain? Thread.current[:available_queries_for_explain] = nil end end -end
\ No newline at end of file +end diff --git a/activerecord/test/cases/finder_respond_to_test.rb b/activerecord/test/cases/finder_respond_to_test.rb index 810c1500cc..eedbaac3bd 100644 --- a/activerecord/test/cases/finder_respond_to_test.rb +++ b/activerecord/test/cases/finder_respond_to_test.rb @@ -80,7 +80,6 @@ class FinderRespondToTest < ActiveRecord::TestCase private def ensure_topic_method_is_not_cached(method_id) - class << Topic; self; end.send(:remove_method, method_id) if Topic.public_methods.any? { |m| m.to_s == method_id.to_s } + class << Topic; self; end.send(:remove_method, method_id) if Topic.public_methods.include? method_id end - end diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index f7ecab28ce..df21585961 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -45,6 +45,12 @@ class FinderTest < ActiveRecord::TestCase assert_raise(NoMethodError) { Topic.exists?([1,2]) } end + def test_exists_does_not_select_columns_without_alias + assert_sql(/SELECT\W+1 AS one FROM ["`]topics["`]/i) do + Topic.exists? + end + end + def test_exists_returns_true_with_one_record_and_no_args assert Topic.exists? end @@ -63,24 +69,14 @@ class FinderTest < ActiveRecord::TestCase assert Topic.order(:id).uniq.exists? end - def test_does_not_exist_with_empty_table_and_no_args_given - Topic.delete_all - assert !Topic.exists? + def test_exists_with_includes_limit_and_empty_result + assert !Topic.includes(:replies).limit(0).exists? + assert !Topic.includes(:replies).limit(1).where('0 = 1').exists? end - def test_exists_with_aggregate_having_three_mappings - existing_address = customers(:david).address - assert Customer.exists?(:address => existing_address) - end - - def test_exists_with_aggregate_having_three_mappings_with_one_difference - existing_address = customers(:david).address - assert !Customer.exists?(:address => - Address.new(existing_address.street, existing_address.city, existing_address.country + "1")) - assert !Customer.exists?(:address => - Address.new(existing_address.street, existing_address.city + "1", existing_address.country)) - assert !Customer.exists?(:address => - Address.new(existing_address.street + "1", existing_address.city, existing_address.country)) + def test_exists_with_empty_table_and_no_args_given + Topic.delete_all + assert !Topic.exists? end def test_exists_does_not_instantiate_records @@ -301,14 +297,6 @@ class FinderTest < ActiveRecord::TestCase assert_equal companies(:rails_core), firms.first end - def test_find_on_hash_conditions_with_explicit_table_name_and_aggregate - david = customers(:david) - assert Customer.scoped(:where => { 'customers.name' => david.name, :address => david.address }).find(david.id) - assert_raise(ActiveRecord::RecordNotFound) { - Customer.scoped(:where => { 'customers.name' => david.name + "1", :address => david.address }).find(david.id) - } - end - def test_find_on_association_proxy_conditions assert_equal [1, 2, 3, 5, 6, 7, 8, 9, 10, 12], Comment.where(post_id: authors(:david).posts).map(&:id).sort end @@ -383,48 +371,6 @@ class FinderTest < ActiveRecord::TestCase assert_nil topic.last_read end - def test_hash_condition_find_with_aggregate_having_one_mapping - balance = customers(:david).balance - assert_kind_of Money, balance - found_customer = Customer.scoped(:where => {:balance => balance}).first - assert_equal customers(:david), found_customer - end - - def test_hash_condition_find_with_aggregate_attribute_having_same_name_as_field_and_key_value_being_aggregate - gps_location = customers(:david).gps_location - assert_kind_of GpsLocation, gps_location - found_customer = Customer.scoped(:where => {:gps_location => gps_location}).first - assert_equal customers(:david), found_customer - end - - def test_hash_condition_find_with_aggregate_having_one_mapping_and_key_value_being_attribute_value - balance = customers(:david).balance - assert_kind_of Money, balance - found_customer = Customer.scoped(:where => {:balance => balance.amount}).first - assert_equal customers(:david), found_customer - end - - def test_hash_condition_find_with_aggregate_attribute_having_same_name_as_field_and_key_value_being_attribute_value - gps_location = customers(:david).gps_location - assert_kind_of GpsLocation, gps_location - found_customer = Customer.scoped(:where => {:gps_location => gps_location.gps_location}).first - assert_equal customers(:david), found_customer - end - - def test_hash_condition_find_with_aggregate_having_three_mappings - address = customers(:david).address - assert_kind_of Address, address - found_customer = Customer.scoped(:where => {:address => address}).first - assert_equal customers(:david), found_customer - end - - def test_hash_condition_find_with_one_condition_being_aggregate_and_another_not - address = customers(:david).address - assert_kind_of Address, address - found_customer = Customer.scoped(:where => {:address => address, :name => customers(:david).name}).first - assert_equal customers(:david), found_customer - end - def test_condition_utc_time_interpolation_with_default_timezone_local with_env_tz 'America/New_York' do with_active_record_default_timezone :local do @@ -593,43 +539,9 @@ class FinderTest < ActiveRecord::TestCase assert_equal accounts(:rails_core_account), Account.where('firm_id = ?', 6).find_by_credit_limit(50) end - def test_find_by_one_attribute_that_is_an_aggregate - address = customers(:david).address - assert_kind_of Address, address - found_customer = Customer.find_by_address(address) - assert_equal customers(:david), found_customer - end - - def test_find_by_one_attribute_that_is_an_aggregate_with_one_attribute_difference - address = customers(:david).address - assert_kind_of Address, address - missing_address = Address.new(address.street, address.city, address.country + "1") - assert_nil Customer.find_by_address(missing_address) - missing_address = Address.new(address.street, address.city + "1", address.country) - assert_nil Customer.find_by_address(missing_address) - missing_address = Address.new(address.street + "1", address.city, address.country) - assert_nil Customer.find_by_address(missing_address) - end - - def test_find_by_two_attributes_that_are_both_aggregates - balance = customers(:david).balance - address = customers(:david).address - assert_kind_of Money, balance - assert_kind_of Address, address - found_customer = Customer.find_by_balance_and_address(balance, address) - assert_equal customers(:david), found_customer - end - - def test_find_by_two_attributes_with_one_being_an_aggregate - balance = customers(:david).balance - assert_kind_of Money, balance - found_customer = Customer.find_by_balance_and_name(balance, customers(:david).name) - assert_equal customers(:david), found_customer - end - def test_dynamic_finder_on_one_attribute_with_conditions_returns_same_results_after_caching # ensure this test can run independently of order - class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' } + class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.include?(:find_by_credit_limit) a = Account.where('firm_id = ?', 6).find_by_credit_limit(50) assert_equal a, Account.where('firm_id = ?', 6).find_by_credit_limit(50) # find_by_credit_limit has been cached end diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 37fa13f771..afff020561 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -121,3 +121,19 @@ class << Time @now = nil end end + +module LogIntercepter + attr_accessor :logged, :intercepted + def self.extended(base) + base.logged = [] + end + def log(sql, name, binds = [], &block) + if @intercepted + @logged << [sql, name, binds] + yield + else + super(sql, name,binds, &block) + end + end +end + diff --git a/activerecord/test/cases/mass_assignment_security_test.rb b/activerecord/test/cases/mass_assignment_security_test.rb index 2f98d3c646..73a01906b9 100644 --- a/activerecord/test/cases/mass_assignment_security_test.rb +++ b/activerecord/test/cases/mass_assignment_security_test.rb @@ -95,7 +95,11 @@ class MassAssignmentSecurityTest < ActiveRecord::TestCase end def test_mass_assigning_does_not_choke_on_nil - Firm.new.assign_attributes(nil) + assert_nil Firm.new.assign_attributes(nil) + end + + def test_mass_assigning_does_not_choke_on_empty_hash + assert_nil Firm.new.assign_attributes({}) end def test_assign_attributes_uses_default_role_when_no_role_is_provided @@ -247,6 +251,65 @@ class MassAssignmentSecurityTest < ActiveRecord::TestCase assert !Task.new.respond_to?("#{method}=") end end + + test "ActiveRecord::Model.whitelist_attributes works for models which include Model" do + begin + prev, ActiveRecord::Model.whitelist_attributes = ActiveRecord::Model.whitelist_attributes, true + + klass = Class.new { include ActiveRecord::Model } + assert_equal ActiveModel::MassAssignmentSecurity::WhiteList, klass.active_authorizers[:default].class + assert_equal [], klass.active_authorizers[:default].to_a + ensure + ActiveRecord::Model.whitelist_attributes = prev + end + end + + test "ActiveRecord::Model.whitelist_attributes works for models which inherit Base" do + begin + prev, ActiveRecord::Model.whitelist_attributes = ActiveRecord::Model.whitelist_attributes, true + + klass = Class.new(ActiveRecord::Base) + assert_equal ActiveModel::MassAssignmentSecurity::WhiteList, klass.active_authorizers[:default].class + assert_equal [], klass.active_authorizers[:default].to_a + + klass.attr_accessible 'foo' + assert_equal ['foo'], Class.new(klass).active_authorizers[:default].to_a + ensure + ActiveRecord::Model.whitelist_attributes = prev + end + end + + test "ActiveRecord::Model.mass_assignment_sanitizer works for models which include Model" do + begin + sanitizer = Object.new + prev, ActiveRecord::Model.mass_assignment_sanitizer = ActiveRecord::Model.mass_assignment_sanitizer, sanitizer + + klass = Class.new { include ActiveRecord::Model } + assert_equal sanitizer, klass._mass_assignment_sanitizer + + ActiveRecord::Model.mass_assignment_sanitizer = nil + klass = Class.new { include ActiveRecord::Model } + assert_not_nil klass._mass_assignment_sanitizer + ensure + ActiveRecord::Model.mass_assignment_sanitizer = prev + end + end + + test "ActiveRecord::Model.mass_assignment_sanitizer works for models which inherit Base" do + begin + sanitizer = Object.new + prev, ActiveRecord::Model.mass_assignment_sanitizer = ActiveRecord::Model.mass_assignment_sanitizer, sanitizer + + klass = Class.new(ActiveRecord::Base) + assert_equal sanitizer, klass._mass_assignment_sanitizer + + sanitizer2 = Object.new + klass.mass_assignment_sanitizer = sanitizer2 + assert_equal sanitizer2, Class.new(klass)._mass_assignment_sanitizer + ensure + ActiveRecord::Model.mass_assignment_sanitizer = prev + end + end end @@ -878,4 +941,26 @@ class MassAssignmentSecurityNestedAttributesTest < ActiveRecord::TestCase assert_all_attributes(person.best_friends.first) end + def test_mass_assignment_options_are_reset_after_exception + person = NestedPerson.create!({ :first_name => 'David', :gender => 'm' }, :as => :admin) + person.create_best_friend!({ :first_name => 'Jeremy', :gender => 'm' }, :as => :admin) + + attributes = { :best_friend_attributes => { :comments => 'rides a sweet bike' } } + assert_raises(RuntimeError) { person.assign_attributes(attributes, :as => :admin) } + assert_equal 'm', person.best_friend.gender + + person.best_friend_attributes = { :gender => 'f' } + assert_equal 'm', person.best_friend.gender + end + + def test_mass_assignment_options_are_nested_correctly + person = NestedPerson.create!({ :first_name => 'David', :gender => 'm' }, :as => :admin) + person.create_best_friend!({ :first_name => 'Jeremy', :gender => 'm' }, :as => :admin) + + attributes = { :best_friend_first_name => 'Josh', :best_friend_attributes => { :gender => 'f' } } + person.assign_attributes(attributes, :as => :admin) + assert_equal 'Josh', person.best_friend.first_name + assert_equal 'f', person.best_friend.gender + end + end diff --git a/activerecord/test/cases/migration/column_attributes_test.rb b/activerecord/test/cases/migration/column_attributes_test.rb index 18f8d82bfe..3014bbe273 100644 --- a/activerecord/test/cases/migration/column_attributes_test.rb +++ b/activerecord/test/cases/migration/column_attributes_test.rb @@ -174,7 +174,7 @@ module ActiveRecord assert_not_equal "Z", bob.moment_of_truth.zone # US/Eastern is -5 hours from GMT assert_equal Rational(-5, 24), bob.moment_of_truth.offset - assert_match(/\A-05:?00\Z/, bob.moment_of_truth.zone) #ruby 1.8.6 uses HH:MM, prior versions use HHMM + assert_match(/\A-05:00\Z/, bob.moment_of_truth.zone) assert_equal DateTime::ITALY, bob.moment_of_truth.start end end diff --git a/activerecord/test/cases/migration/references_index_test.rb b/activerecord/test/cases/migration/references_index_test.rb index 8ab1c59724..264a99f9ce 100644 --- a/activerecord/test/cases/migration/references_index_test.rb +++ b/activerecord/test/cases/migration/references_index_test.rb @@ -51,6 +51,8 @@ module ActiveRecord end def test_creates_polymorphic_index + return skip "Oracle Adapter does not support foreign keys if :polymorphic => true is used" if current_adapter? :OracleAdapter + connection.create_table table_name do |t| t.references :foo, :polymorphic => true, :index => true end @@ -86,6 +88,7 @@ module ActiveRecord end def test_creates_polymorphic_index_for_existing_table + return skip "Oracle Adapter does not support foreign keys if :polymorphic => true is used" if current_adapter? :OracleAdapter connection.create_table table_name connection.change_table table_name do |t| t.references :foo, :polymorphic => true, :index => true diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 5d1bad0d54..3c0d2b18d9 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -56,6 +56,21 @@ class MigrationTest < ActiveRecord::TestCase Person.reset_column_information end + def test_migrator_versions + migrations_path = MIGRATIONS_ROOT + "/valid" + ActiveRecord::Migrator.migrations_paths = migrations_path + + ActiveRecord::Migrator.up(migrations_path) + assert_equal 3, ActiveRecord::Migrator.current_version + assert_equal 3, ActiveRecord::Migrator.last_version + assert_equal false, ActiveRecord::Migrator.needs_migration? + + ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid") + assert_equal 0, ActiveRecord::Migrator.current_version + assert_equal 3, ActiveRecord::Migrator.last_version + assert_equal true, ActiveRecord::Migrator.needs_migration? + end + def test_create_table_with_force_true_does_not_drop_nonexisting_table if Person.connection.table_exists?(:testings2) Person.connection.drop_table :testings2 @@ -523,7 +538,7 @@ if ActiveRecord::Base.connection.supports_bulk_alter? # One query for columns (delete_me table) # One query for primary key (delete_me table) # One query to do the bulk change - assert_queries(3) do + assert_queries(3, :ignore_none => true) do with_bulk_change_table do |t| t.change :name, :string, :default => 'NONAME' t.change :birthdate, :datetime diff --git a/activerecord/test/cases/mysql_rake_test.rb b/activerecord/test/cases/mysql_rake_test.rb new file mode 100644 index 0000000000..42a11b0171 --- /dev/null +++ b/activerecord/test/cases/mysql_rake_test.rb @@ -0,0 +1,246 @@ +require 'cases/helper' +require 'mysql' + +module ActiveRecord + class MysqlDBCreateTest < ActiveRecord::TestCase + def setup + @connection = stub(:create_database => true) + @configuration = { + 'adapter' => 'mysql', + 'database' => 'my-app-db' + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_establishes_connection_without_database + ActiveRecord::Base.expects(:establish_connection). + with('adapter' => 'mysql', 'database' => nil) + + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end + + def test_creates_database_with_default_options + @connection.expects(:create_database). + with('my-app-db', {:charset => 'utf8', :collation => 'utf8_unicode_ci'}) + + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end + + def test_creates_database_with_given_options + @connection.expects(:create_database). + with('my-app-db', {:charset => 'latin', :collation => 'latin_ci'}) + + ActiveRecord::Tasks::DatabaseTasks.create @configuration.merge( + 'charset' => 'latin', 'collation' => 'latin_ci' + ) + end + + def test_establishes_connection_to_database + ActiveRecord::Base.expects(:establish_connection).with(@configuration) + + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end + end + + class MysqlDBCreateAsRootTest < ActiveRecord::TestCase + def setup + @connection = stub(:create_database => true, :execute => true) + @error = Mysql::Error.new "Invalid permissions" + @configuration = { + 'adapter' => 'mysql', + 'database' => 'my-app-db', + 'username' => 'pat', + 'password' => 'wossname' + } + + $stdin.stubs(:gets).returns("secret\n") + $stdout.stubs(:print).returns(nil) + @error.stubs(:errno).returns(1045) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).raises(@error).then. + returns(true) + end + + def test_root_password_is_requested + $stdin.expects(:gets).returns("secret\n") + + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end + + def test_connection_established_as_root + ActiveRecord::Base.expects(:establish_connection).with({ + 'adapter' => 'mysql', + 'database' => nil, + 'username' => 'root', + 'password' => 'secret' + }) + + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end + + def test_database_created_by_root + @connection.expects(:create_database). + with('my-app-db', :charset => 'utf8', :collation => 'utf8_unicode_ci') + + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end + + def test_grant_privileges_for_normal_user + @connection.expects(:execute).with("GRANT ALL PRIVILEGES ON my-app-db.* TO 'pat'@'localhost' IDENTIFIED BY 'wossname' WITH GRANT OPTION;") + + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end + + def test_connection_established_as_normal_user + ActiveRecord::Base.expects(:establish_connection).returns do + ActiveRecord::Base.expects(:establish_connection).with({ + 'adapter' => 'mysql', + 'database' => 'my-app-db', + 'username' => 'pat', + 'password' => 'secret' + }) + + raise @error + end + + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end + + def test_sends_output_to_stderr_when_other_errors + @error.stubs(:errno).returns(42) + + $stderr.expects(:puts).at_least_once.returns(nil) + + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end + end + + class MySQLDBDropTest < ActiveRecord::TestCase + def setup + @connection = stub(:drop_database => true) + @configuration = { + 'adapter' => 'mysql', + 'database' => 'my-app-db' + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_establishes_connection_to_mysql_database + ActiveRecord::Base.expects(:establish_connection).with @configuration + + ActiveRecord::Tasks::DatabaseTasks.drop @configuration + end + + def test_drops_database + @connection.expects(:drop_database).with('my-app-db') + + ActiveRecord::Tasks::DatabaseTasks.drop @configuration + end + end + + class MySQLPurgeTest < ActiveRecord::TestCase + def setup + @connection = stub(:recreate_database => true) + @configuration = { + 'adapter' => 'mysql', + 'database' => 'test-db' + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_establishes_connection_to_test_database + ActiveRecord::Base.expects(:establish_connection).with(:test) + + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end + + def test_recreates_database_with_the_default_options + @connection.expects(:recreate_database). + with('test-db', {:charset => 'utf8', :collation => 'utf8_unicode_ci'}) + + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end + + def test_recreates_database_with_the_given_options + @connection.expects(:recreate_database). + with('test-db', {:charset => 'latin', :collation => 'latin_ci'}) + + ActiveRecord::Tasks::DatabaseTasks.purge @configuration.merge( + 'charset' => 'latin', 'collation' => 'latin_ci' + ) + end + end + + class MysqlDBCharsetTest < ActiveRecord::TestCase + def setup + @connection = stub(:create_database => true) + @configuration = { + 'adapter' => 'mysql', + 'database' => 'my-app-db' + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_db_retrieves_charset + @connection.expects(:charset) + ActiveRecord::Tasks::DatabaseTasks.charset @configuration + end + end + + class MySQLStructureDumpTest < ActiveRecord::TestCase + def setup + @connection = stub(:structure_dump => true) + @configuration = { + 'adapter' => 'mysql', + 'database' => 'test-db' + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_structure_dump + filename = "awesome-file.sql" + ActiveRecord::Base.expects(:establish_connection).with(@configuration) + @connection.expects(:structure_dump) + + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename) + assert File.exists?(filename) + ensure + FileUtils.rm(filename) + end + end + + class MySQLStructureLoadTest < ActiveRecord::TestCase + def setup + @connection = stub + @configuration = { + 'adapter' => 'mysql', + 'database' => 'test-db' + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_structure_load + filename = "awesome-file.sql" + ActiveRecord::Base.expects(:establish_connection).with(@configuration) + @connection.expects(:execute).twice + + open(filename, 'w') { |f| f.puts("SELECT CURDATE();") } + ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) + ensure + FileUtils.rm(filename) + end + end + +end diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index bf825c002a..c886160af3 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -19,7 +19,6 @@ class NamedScopeTest < ActiveRecord::TestCase end def test_found_items_are_cached - Topic.columns all_posts = Topic.base assert_queries(1) do @@ -46,6 +45,15 @@ class NamedScopeTest < ActiveRecord::TestCase assert_equal Topic.average(:replies_count), Topic.base.average(:replies_count) end + def test_method_missing_priority_when_delegating + klazz = Class.new(ActiveRecord::Base) do + self.table_name = "topics" + scope :since, Proc.new { where('written_on >= ?', Time.now - 1.day) } + scope :to, Proc.new { where('written_on <= ?', Time.now) } + end + assert_equal klazz.to.since.all, klazz.since.to.all + end + def test_scope_should_respond_to_own_methods_and_methods_of_the_proxy assert Topic.approved.respond_to?(:limit) assert Topic.approved.respond_to?(:count) diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index 0559bbbe9a..3daa033ed0 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -781,6 +781,16 @@ module NestedAttributesOnACollectionAssociationTests assert_nothing_raised(NoMethodError) { @pirate.save! } end + def test_numeric_colum_changes_from_zero_to_no_empty_string + Man.accepts_nested_attributes_for(:interests) + Interest.validates_numericality_of(:zine_id) + man = Man.create(:name => 'John') + interest = man.interests.create(:topic=>'bar',:zine_id => 0) + assert interest.save + + assert !man.update_attributes({:interests_attributes => { :id => interest.id, :zine_id => 'foo' }}) + end + private def association_setter diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb index 0933a4ff3d..b7b77b24af 100644 --- a/activerecord/test/cases/persistence_test.rb +++ b/activerecord/test/cases/persistence_test.rb @@ -305,6 +305,13 @@ class PersistencesTest < ActiveRecord::TestCase assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) } end + def test_destroy! + topic = Topic.find(1) + assert_equal topic, topic.destroy!, 'topic.destroy! did not return self' + assert topic.frozen?, 'topic not frozen after destroy!' + assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) } + end + def test_record_not_found_exception assert_raise(ActiveRecord::RecordNotFound) { Topic.find(99999) } end @@ -364,71 +371,10 @@ class PersistencesTest < ActiveRecord::TestCase assert_raise(ActiveSupport::FrozenObjectError) { client.name = "something else" } end - def test_update_attribute - assert !Topic.find(1).approved? - Topic.find(1).update_attribute("approved", true) - assert Topic.find(1).approved? - - Topic.find(1).update_attribute(:approved, false) - assert !Topic.find(1).approved? - end - def test_update_attribute_does_not_choke_on_nil assert Topic.find(1).update_attributes(nil) end - def test_update_attribute_for_readonly_attribute - minivan = Minivan.find('m1') - assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_attribute(:color, 'black') } - end - - # This test is correct, but it is hard to fix it since - # update_attribute trigger simply call save! that triggers - # all callbacks. - # def test_update_attribute_with_one_changed_and_one_updated - # t = Topic.order('id').limit(1).first - # title, author_name = t.title, t.author_name - # t.author_name = 'John' - # t.update_attribute(:title, 'super_title') - # assert_equal 'John', t.author_name - # assert_equal 'super_title', t.title - # assert t.changed?, "topic should have changed" - # assert t.author_name_changed?, "author_name should have changed" - # assert !t.title_changed?, "title should not have changed" - # assert_nil t.title_change, 'title change should be nil' - # assert_equal ['author_name'], t.changed - # - # t.reload - # assert_equal 'David', t.author_name - # assert_equal 'super_title', t.title - # end - - def test_update_attribute_with_one_updated - t = Topic.first - t.update_attribute(:title, 'super_title') - assert_equal 'super_title', t.title - assert !t.changed?, "topic should not have changed" - assert !t.title_changed?, "title should not have changed" - assert_nil t.title_change, 'title change should be nil' - - t.reload - assert_equal 'super_title', t.title - end - - def test_update_attribute_for_updated_at_on - developer = Developer.find(1) - prev_month = Time.now.prev_month - - developer.update_attribute(:updated_at, prev_month) - assert_equal prev_month, developer.updated_at - - developer.update_attribute(:salary, 80001) - assert_not_equal prev_month, developer.updated_at - - developer.reload - assert_not_equal prev_month, developer.updated_at - end - def test_update_column topic = Topic.find(1) topic.update_column("approved", true) @@ -460,7 +406,7 @@ class PersistencesTest < ActiveRecord::TestCase def test_update_column_should_not_leave_the_object_dirty topic = Topic.find(1) - topic.update_attribute("content", "Have a nice day") + topic.update_column("content", "Have a nice day") topic.reload topic.update_column(:content, "You too") diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index fba3006ebe..0a6354f5cc 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -17,7 +17,7 @@ class PooledConnectionsTest < ActiveRecord::TestCase end def checkout_connections - ActiveRecord::Model.establish_connection(@connection.merge({:pool => 2, :wait_timeout => 0.3})) + ActiveRecord::Model.establish_connection(@connection.merge({:pool => 2, :checkout_timeout => 0.3})) @connections = [] @timed_out = 0 @@ -34,7 +34,7 @@ class PooledConnectionsTest < ActiveRecord::TestCase # Will deadlock due to lack of Monitor timeouts in 1.9 def checkout_checkin_connections(pool_size, threads) - ActiveRecord::Model.establish_connection(@connection.merge({:pool => pool_size, :wait_timeout => 0.5})) + ActiveRecord::Model.establish_connection(@connection.merge({:pool => pool_size, :checkout_timeout => 0.5})) @connection_count = 0 @timed_out = 0 threads.times do diff --git a/activerecord/test/cases/postgresql_rake_test.rb b/activerecord/test/cases/postgresql_rake_test.rb new file mode 100644 index 0000000000..e8769bd4df --- /dev/null +++ b/activerecord/test/cases/postgresql_rake_test.rb @@ -0,0 +1,200 @@ +require 'cases/helper' + +module ActiveRecord + class PostgreSQLDBCreateTest < ActiveRecord::TestCase + def setup + @connection = stub(:create_database => true) + @configuration = { + 'adapter' => 'postgresql', + 'database' => 'my-app-db' + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_establishes_connection_to_postgresql_database + ActiveRecord::Base.expects(:establish_connection).with( + 'adapter' => 'postgresql', + 'database' => 'postgres', + 'schema_search_path' => 'public' + ) + + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end + + def test_creates_database_with_default_encoding + @connection.expects(:create_database). + with('my-app-db', @configuration.merge('encoding' => 'utf8')) + + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end + + def test_creates_database_with_given_encoding + @connection.expects(:create_database). + with('my-app-db', @configuration.merge('encoding' => 'latin')) + + ActiveRecord::Tasks::DatabaseTasks.create @configuration. + merge('encoding' => 'latin') + end + + def test_establishes_connection_to_new_database + ActiveRecord::Base.expects(:establish_connection).with(@configuration) + + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end + + def test_db_create_with_error_prints_message + ActiveRecord::Base.stubs(:establish_connection).raises(Exception) + + $stderr.stubs(:puts).returns(true) + $stderr.expects(:puts). + with("Couldn't create database for #{@configuration.inspect}") + + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end + end + + class PostgreSQLDBDropTest < ActiveRecord::TestCase + def setup + @connection = stub(:drop_database => true) + @configuration = { + 'adapter' => 'postgresql', + 'database' => 'my-app-db' + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_establishes_connection_to_postgresql_database + ActiveRecord::Base.expects(:establish_connection).with( + 'adapter' => 'postgresql', + 'database' => 'postgres', + 'schema_search_path' => 'public' + ) + + ActiveRecord::Tasks::DatabaseTasks.drop @configuration + end + + def test_drops_database + @connection.expects(:drop_database).with('my-app-db') + + ActiveRecord::Tasks::DatabaseTasks.drop @configuration + end + end + + class PostgreSQLPurgeTest < ActiveRecord::TestCase + def setup + @connection = stub(:create_database => true, :drop_database => true) + @configuration = { + 'adapter' => 'postgresql', + 'database' => 'my-app-db' + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:clear_active_connections!).returns(true) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_clears_active_connections + ActiveRecord::Base.expects(:clear_active_connections!) + + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end + + def test_establishes_connection_to_postgresql_database + ActiveRecord::Base.expects(:establish_connection).with( + 'adapter' => 'postgresql', + 'database' => 'postgres', + 'schema_search_path' => 'public' + ) + + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end + + def test_drops_database + @connection.expects(:drop_database).with('my-app-db') + + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end + + def test_creates_database + @connection.expects(:create_database). + with('my-app-db', @configuration.merge('encoding' => 'utf8')) + + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end + + def test_establishes_connection + ActiveRecord::Base.expects(:establish_connection).with(@configuration) + + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end + end + + class PostgreSQLDBCharsetTest < ActiveRecord::TestCase + def setup + @connection = stub(:create_database => true) + @configuration = { + 'adapter' => 'postgresql', + 'database' => 'my-app-db' + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_db_retrieves_charset + @connection.expects(:encoding) + ActiveRecord::Tasks::DatabaseTasks.charset @configuration + end + end + + class PostgreSQLStructureDumpTest < ActiveRecord::TestCase + def setup + @connection = stub(:structure_dump => true) + @configuration = { + 'adapter' => 'postgresql', + 'database' => 'my-app-db' + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + Kernel.stubs(:system) + end + + def test_structure_dump + filename = "awesome-file.sql" + Kernel.expects(:system).with("pg_dump -i -s -x -O -f #{filename} my-app-db").returns(true) + @connection.expects(:schema_search_path).returns("foo") + + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename) + assert File.exists?(filename) + ensure + FileUtils.rm(filename) + end + end + + class PostgreSQLStructureLoadTest < ActiveRecord::TestCase + def setup + @connection = stub + @configuration = { + 'adapter' => 'postgresql', + 'database' => 'my-app-db' + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + Kernel.stubs(:system) + end + + def test_structure_dump + filename = "awesome-file.sql" + Kernel.expects(:system).with("psql -f #{filename} my-app-db") + + ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) + end + end + +end diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb index a712e5f689..08f655d7fa 100644 --- a/activerecord/test/cases/query_cache_test.rb +++ b/activerecord/test/cases/query_cache_test.rb @@ -151,16 +151,11 @@ class QueryCacheTest < ActiveRecord::TestCase end def test_cache_does_not_wrap_string_results_in_arrays - if current_adapter?(:SQLite3Adapter) - require 'sqlite3/version' - sqlite3_version = RUBY_PLATFORM =~ /java/ ? Jdbc::SQLite3::VERSION : SQLite3::VERSION - end - Task.cache do # Oracle adapter returns count() as Fixnum or Float if current_adapter?(:OracleAdapter) assert_kind_of Numeric, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks") - elsif current_adapter?(:SQLite3Adapter) && sqlite3_version > '1.2.5' || current_adapter?(:Mysql2Adapter) || current_adapter?(:MysqlAdapter) + elsif current_adapter?(:SQLite3Adapter) || current_adapter?(:Mysql2Adapter) || current_adapter?(:MysqlAdapter) # Future versions of the sqlite3 adapter will return numeric assert_instance_of Fixnum, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks") diff --git a/activerecord/test/cases/reaper_test.rb b/activerecord/test/cases/reaper_test.rb index 576ab60090..e53a27d5dd 100644 --- a/activerecord/test/cases/reaper_test.rb +++ b/activerecord/test/cases/reaper_test.rb @@ -64,7 +64,7 @@ module ActiveRecord spec.config[:reaping_frequency] = 0.0001 pool = ConnectionPool.new spec - pool.timeout = 0 + pool.dead_connection_timeout = 0 conn = pool.checkout count = pool.connections.length diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 7dd5698dcf..bac3376c9f 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -83,30 +83,6 @@ class ReflectionTest < ActiveRecord::TestCase end end - def test_aggregation_reflection - reflection_for_address = AggregateReflection.new( - :composed_of, :address, { :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ] }, Customer - ) - - reflection_for_balance = AggregateReflection.new( - :composed_of, :balance, { :class_name => "Money", :mapping => %w(balance amount) }, Customer - ) - - reflection_for_gps_location = 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_reflect_on_all_autosave_associations expected = Pirate.reflect_on_all_associations.select { |r| r.options[:autosave] } received = Pirate.reflect_on_all_autosave_associations diff --git a/activerecord/test/cases/relation/where_test.rb b/activerecord/test/cases/relation/where_test.rb new file mode 100644 index 0000000000..90c690e266 --- /dev/null +++ b/activerecord/test/cases/relation/where_test.rb @@ -0,0 +1,19 @@ +require "cases/helper" +require 'models/post' + +module ActiveRecord + class WhereTest < ActiveRecord::TestCase + fixtures :posts + + def test_where_error + assert_raises(ActiveRecord::StatementInvalid) do + Post.where(:id => { 'posts.author_id' => 10 }).first + end + end + + def test_where_with_table_name + post = Post.first + assert_equal post, Post.where(:posts => { 'id' => post.id }).first + end + end +end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 2dc8f0053b..6c5bee7382 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -226,7 +226,6 @@ class RelationTest < ActiveRecord::TestCase assert_no_queries do assert_equal [], Developer.none assert_equal [], Developer.scoped.none - assert Developer.none.is_a?(ActiveRecord::NullRelation) end end @@ -236,6 +235,12 @@ class RelationTest < ActiveRecord::TestCase end end + def test_none_chainable_to_existing_scope_extension_method + assert_no_queries do + assert_equal 1, Topic.anonymous_extension.none.one + end + end + def test_none_chained_to_methods_firing_queries_straight_to_db assert_no_queries do assert_equal [], Developer.none.pluck(:id) # => uses select_all @@ -690,6 +695,14 @@ class RelationTest < ActiveRecord::TestCase assert_equal 1, comments.count end + def test_relation_merging_with_association + assert_queries(2) do # one for loading post, and another one merged query + post = Post.where(:body => 'Such a lovely day').first + comments = Comment.where(:body => 'Thank you for the welcome').merge(post.comments) + assert_equal 1, comments.count + end + end + def test_count posts = Post.scoped diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index ab80dd1d6d..01dd25a9df 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -257,6 +257,13 @@ class SchemaDumperTest < ActiveRecord::TestCase end end + def test_schema_dump_includes_uuid_shorthand_definition + output = standard_dump + if %r{create_table "poistgresql_uuids"} =~ output + assert_match %r{t.uuid "guid"}, output + end + end + def test_schema_dump_includes_hstores_shorthand_definition output = standard_dump if %r{create_table "postgresql_hstores"} =~ output @@ -294,4 +301,36 @@ class SchemaDumperTest < ActiveRecord::TestCase output = standard_dump assert_match %r{create_table "subscribers", :id => false}, output end + + class CreateDogMigration < ActiveRecord::Migration + def up + create_table("dogs") do |t| + t.column :name, :string + end + add_index "dogs", [:name] + end + def down + drop_table("dogs") + end + end + + def test_schema_dump_with_table_name_prefix_and_suffix + original, $stdout = $stdout, StringIO.new + ActiveRecord::Base.table_name_prefix = 'foo_' + ActiveRecord::Base.table_name_suffix = '_bar' + + migration = CreateDogMigration.new + migration.migrate(:up) + + output = standard_dump + assert_no_match %r{create_table "foo_.+_bar"}, output + assert_no_match %r{create_index "foo_.+_bar"}, output + assert_no_match %r{create_table "schema_migrations"}, output + ensure + migration.migrate(:down) + + ActiveRecord::Base.table_name_suffix = ActiveRecord::Base.table_name_prefix = '' + $stdout = original + end + end diff --git a/activerecord/test/cases/sqlite_rake_test.rb b/activerecord/test/cases/sqlite_rake_test.rb new file mode 100644 index 0000000000..b5557fc953 --- /dev/null +++ b/activerecord/test/cases/sqlite_rake_test.rb @@ -0,0 +1,170 @@ +require 'cases/helper' +require 'pathname' + +module ActiveRecord + class SqliteDBCreateTest < ActiveRecord::TestCase + def setup + @database = 'db_create.sqlite3' + @connection = stub :connection + @configuration = { + 'adapter' => 'sqlite3', + 'database' => @database + } + + File.stubs(:exist?).returns(false) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_db_checks_database_exists + File.expects(:exist?).with(@database).returns(false) + + ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root' + end + + def test_db_create_when_file_exists + File.stubs(:exist?).returns(true) + + $stderr.expects(:puts).with("#{@database} already exists") + + ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root' + end + + def test_db_create_with_file_does_nothing + File.stubs(:exist?).returns(true) + $stderr.stubs(:puts).returns(nil) + + ActiveRecord::Base.expects(:establish_connection).never + + ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root' + end + + def test_db_create_establishes_a_connection + ActiveRecord::Base.expects(:establish_connection).with(@configuration) + + ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root' + end + + def test_db_create_with_error_prints_message + ActiveRecord::Base.stubs(:establish_connection).raises(Exception) + + $stderr.stubs(:puts).returns(true) + $stderr.expects(:puts). + with("Couldn't create database for #{@configuration.inspect}") + + ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root' + end + end + + class SqliteDBDropTest < ActiveRecord::TestCase + def setup + @database = "db_create.sqlite3" + @path = stub(:to_s => '/absolute/path', :absolute? => true) + @configuration = { + 'adapter' => 'sqlite3', + 'database' => @database + } + + Pathname.stubs(:new).returns(@path) + File.stubs(:join).returns('/former/relative/path') + FileUtils.stubs(:rm).returns(true) + end + + def test_creates_path_from_database + Pathname.expects(:new).with(@database).returns(@path) + + ActiveRecord::Tasks::DatabaseTasks.drop @configuration, '/rails/root' + end + + def test_removes_file_with_absolute_path + File.stubs(:exist?).returns(true) + @path.stubs(:absolute?).returns(true) + + FileUtils.expects(:rm).with('/absolute/path') + + ActiveRecord::Tasks::DatabaseTasks.drop @configuration, '/rails/root' + end + + def test_generates_absolute_path_with_given_root + @path.stubs(:absolute?).returns(false) + + File.expects(:join).with('/rails/root', @path). + returns('/former/relative/path') + + ActiveRecord::Tasks::DatabaseTasks.drop @configuration, '/rails/root' + end + + def test_removes_file_with_relative_path + File.stubs(:exist?).returns(true) + @path.stubs(:absolute?).returns(false) + + FileUtils.expects(:rm).with('/former/relative/path') + + ActiveRecord::Tasks::DatabaseTasks.drop @configuration, '/rails/root' + end + end + + class SqliteDBCharsetTest < ActiveRecord::TestCase + def setup + @database = 'db_create.sqlite3' + @connection = stub :connection + @configuration = { + 'adapter' => 'sqlite3', + 'database' => @database + } + + File.stubs(:exist?).returns(false) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_db_retrieves_charset + @connection.expects(:encoding) + ActiveRecord::Tasks::DatabaseTasks.charset @configuration, '/rails/root' + end + end + + class SqliteStructureDumpTest < ActiveRecord::TestCase + def setup + @database = "db_create.sqlite3" + @configuration = { + 'adapter' => 'sqlite3', + 'database' => @database + } + end + + def test_structure_dump + dbfile = @database + filename = "awesome-file.sql" + + ActiveRecord::Tasks::DatabaseTasks.structure_dump @configuration, filename, '/rails/root' + assert File.exists?(dbfile) + assert File.exists?(filename) + ensure + FileUtils.rm(filename) + FileUtils.rm(dbfile) + end + end + + class SqliteStructureLoadTest < ActiveRecord::TestCase + def setup + @database = "db_create.sqlite3" + @configuration = { + 'adapter' => 'sqlite3', + 'database' => @database + } + end + + def test_structure_load + dbfile = @database + filename = "awesome-file.sql" + + open(filename, 'w') { |f| f.puts("select datetime('now', 'localtime');") } + ActiveRecord::Tasks::DatabaseTasks.structure_load @configuration, filename, '/rails/root' + assert File.exists?(dbfile) + ensure + FileUtils.rm(filename) + FileUtils.rm(dbfile) + end + end +end diff --git a/activerecord/test/cases/store_test.rb b/activerecord/test/cases/store_test.rb index e1d0f1f799..e401dd4b12 100644 --- a/activerecord/test/cases/store_test.rb +++ b/activerecord/test/cases/store_test.rb @@ -3,15 +3,17 @@ require 'models/admin' require 'models/admin/user' class StoreTest < ActiveRecord::TestCase + fixtures :'admin/users' + setup do - @john = Admin::User.create(:name => 'John Doe', :color => 'black', :remember_login => true, :height => 'tall', :is_a_good_guy => true) + @john = Admin::User.create!(:name => 'John Doe', :color => 'black', :remember_login => true, :height => 'tall', :is_a_good_guy => true) end test "reading store attributes through accessors" do assert_equal 'black', @john.color assert_nil @john.homepage end - + test "writing store attributes through accessors" do @john.color = 'red' @john.homepage = '37signals.com' @@ -41,6 +43,41 @@ class StoreTest < ActiveRecord::TestCase assert_equal false, @john.remember_login end + test "preserve store attributes data in HashWithIndifferentAccess format without any conversion" do + @john.json_data = HashWithIndifferentAccess.new(:height => 'tall', 'weight' => 'heavy') + @john.height = 'low' + assert_equal true, @john.json_data.instance_of?(HashWithIndifferentAccess) + assert_equal 'low', @john.json_data[:height] + assert_equal 'low', @john.json_data['height'] + assert_equal 'heavy', @john.json_data[:weight] + assert_equal 'heavy', @john.json_data['weight'] + end + + test "convert store attributes from Hash to HashWithIndifferentAccess saving the data and access attributes indifferently" do + user = Admin::User.find_by_name('Jamis') + assert_equal 'symbol', user.settings[:symbol] + assert_equal 'symbol', user.settings['symbol'] + assert_equal 'string', user.settings[:string] + assert_equal 'string', user.settings['string'] + assert_equal true, user.settings.instance_of?(ActiveSupport::HashWithIndifferentAccess) + + user.height = 'low' + assert_equal 'symbol', user.settings[:symbol] + assert_equal 'symbol', user.settings['symbol'] + assert_equal 'string', user.settings[:string] + assert_equal 'string', user.settings['string'] + assert_equal true, user.settings.instance_of?(ActiveSupport::HashWithIndifferentAccess) + end + + test "convert store attributes from any format other than Hash or HashWithIndifferent access losing the data" do + @john.json_data = "somedata" + @john.height = 'low' + assert_equal true, @john.json_data.instance_of?(HashWithIndifferentAccess) + assert_equal 'low', @john.json_data[:height] + assert_equal 'low', @john.json_data['height'] + assert_equal false, @john.json_data.delete_if { |k, v| k == 'height' }.any? + end + test "reading store attributes through accessors encoded with JSON" do assert_equal 'tall', @john.height assert_nil @john.weight @@ -74,4 +111,8 @@ class StoreTest < ActiveRecord::TestCase @john.is_a_good_guy = false assert_equal false, @john.is_a_good_guy end + + test "stored attributes are returned" do + assert_equal [:color, :homepage], Admin::User.stored_attributes[:settings] + end end diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index 447aa29ffe..7df6993b30 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -11,7 +11,7 @@ class TimestampTest < ActiveRecord::TestCase def setup @developer = Developer.first - @developer.update_attribute(:updated_at, Time.now.prev_month) + @developer.update_column(:updated_at, Time.now.prev_month) @previously_updated_at = @developer.updated_at end @@ -133,7 +133,7 @@ class TimestampTest < ActiveRecord::TestCase pet = Pet.first owner = pet.owner - owner.update_attribute(:happy_at, 3.days.ago) + owner.update_column(:happy_at, 3.days.ago) previously_owner_updated_at = owner.updated_at pet.name = "I'm a parrot" diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index 203dd054f1..a9ccd00fac 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -362,6 +362,16 @@ class TransactionTest < ActiveRecord::TestCase end end + def test_rollback_when_saving_a_frozen_record + topic = Topic.new(:title => 'test') + topic.freeze + e = assert_raise(RuntimeError) { topic.save } + assert_equal "can't modify frozen Hash", e.message + assert !topic.persisted?, 'not persisted' + assert_nil topic.id + assert topic.frozen?, 'not frozen' + end + def test_restore_active_record_state_for_all_records_in_a_transaction topic_1 = Topic.new(:title => 'test_1') topic_2 = Topic.new(:title => 'test_2') diff --git a/activerecord/test/cases/xml_serialization_test.rb b/activerecord/test/cases/xml_serialization_test.rb index 88751a72f9..12373333b0 100644 --- a/activerecord/test/cases/xml_serialization_test.rb +++ b/activerecord/test/cases/xml_serialization_test.rb @@ -92,7 +92,7 @@ class DefaultXmlSerializationTest < ActiveRecord::TestCase end def test_should_serialize_datetime - assert_match %r{<created-at type=\"datetime\">2006-08-01T00:00:00Z</created-at>}, @xml + assert_match %r{<created-at type=\"dateTime\">2006-08-01T00:00:00Z</created-at>}, @xml end def test_should_serialize_boolean @@ -109,7 +109,7 @@ class DefaultXmlSerializationTimezoneTest < ActiveRecord::TestCase timezone, Time.zone = Time.zone, "Pacific Time (US & Canada)" toy = Toy.create(:name => 'Mickey', :updated_at => Time.utc(2006, 8, 1)) - assert_match %r{<updated-at type=\"datetime\">2006-07-31T17:00:00-07:00</updated-at>}, toy.to_xml + assert_match %r{<updated-at type=\"dateTime\">2006-07-31T17:00:00-07:00</updated-at>}, toy.to_xml ensure Time.zone = timezone end @@ -118,7 +118,7 @@ class DefaultXmlSerializationTimezoneTest < ActiveRecord::TestCase timezone, Time.zone = Time.zone, "Pacific Time (US & Canada)" toy = Toy.create(:name => 'Minnie', :updated_at => Time.utc(2006, 8, 1)).reload - assert_match %r{<updated-at type=\"datetime\">2006-07-31T17:00:00-07:00</updated-at>}, toy.to_xml + assert_match %r{<updated-at type=\"dateTime\">2006-07-31T17:00:00-07:00</updated-at>}, toy.to_xml ensure Time.zone = timezone end @@ -152,7 +152,7 @@ class NilXmlSerializationTest < ActiveRecord::TestCase assert %r{<created-at (.*)></created-at>}.match(@xml) attributes = $1 assert_match %r{nil="true"}, attributes - assert_match %r{type="datetime"}, attributes + assert_match %r{type="dateTime"}, attributes end def test_should_serialize_boolean @@ -188,7 +188,7 @@ class DatabaseConnectedXmlSerializationTest < ActiveRecord::TestCase assert_equal "integer" , xml.elements["//replies-count"].attributes['type'] assert_equal written_on_in_current_timezone, xml.elements["//written-on"].text - assert_equal "datetime" , xml.elements["//written-on"].attributes['type'] + assert_equal "dateTime" , xml.elements["//written-on"].attributes['type'] assert_equal "david@loudthinking.com", xml.elements["//author-email-address"].text @@ -198,7 +198,7 @@ class DatabaseConnectedXmlSerializationTest < ActiveRecord::TestCase if current_adapter?(:SybaseAdapter) assert_equal last_read_in_current_timezone, xml.elements["//last-read"].text - assert_equal "datetime" , xml.elements["//last-read"].attributes['type'] + assert_equal "dateTime" , xml.elements["//last-read"].attributes['type'] else # Oracle enhanced adapter allows to define Date attributes in model class (see topic.rb) assert_equal "2004-04-15", xml.elements["//last-read"].text @@ -211,7 +211,7 @@ class DatabaseConnectedXmlSerializationTest < ActiveRecord::TestCase assert_equal "boolean" , xml.elements["//approved"].attributes['type'] assert_equal bonus_time_in_current_timezone, xml.elements["//bonus-time"].text - assert_equal "datetime" , xml.elements["//bonus-time"].attributes['type'] + assert_equal "dateTime" , xml.elements["//bonus-time"].attributes['type'] end end diff --git a/activerecord/test/fixtures/admin/users.yml b/activerecord/test/fixtures/admin/users.yml index 6f11f2509e..e2884beda5 100644 --- a/activerecord/test/fixtures/admin/users.yml +++ b/activerecord/test/fixtures/admin/users.yml @@ -5,3 +5,6 @@ david: jamis: name: Jamis account: signals37 + settings: + :symbol: symbol + string: string diff --git a/activerecord/test/models/customer.rb b/activerecord/test/models/customer.rb index 807f25b687..594c484f20 100644 --- a/activerecord/test/models/customer.rb +++ b/activerecord/test/models/customer.rb @@ -1,13 +1,5 @@ class Customer < ActiveRecord::Base - cattr_accessor :gps_conversion_was_run - - composed_of :address, :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ], :allow_nil => true - composed_of :balance, :class_name => "Money", :mapping => %w(balance amount), :converter => Proc.new { |balance| balance.to_money } - composed_of :gps_location, :allow_nil => true - composed_of :non_blank_gps_location, :class_name => "GpsLocation", :allow_nil => true, :mapping => %w(gps_location gps_location), - :converter => lambda { |gps| self.gps_conversion_was_run = true; gps.blank? ? nil : GpsLocation.new(gps)} - composed_of :fullname, :mapping => %w(name to_s), :constructor => Proc.new { |name| Fullname.parse(name) }, :converter => :parse end class Address diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb index 83482f4d07..9fefa9ad3a 100644 --- a/activerecord/test/models/developer.rb +++ b/activerecord/test/models/developer.rb @@ -65,11 +65,6 @@ class AuditLog < ActiveRecord::Base end DeveloperSalary = Struct.new(:amount) -class DeveloperWithAggregate < ActiveRecord::Base - self.table_name = 'developers' - composed_of :salary, :class_name => 'DeveloperSalary', :mapping => [%w(salary amount)] -end - class DeveloperWithBeforeDestroyRaise < ActiveRecord::Base self.table_name = 'developers' has_and_belongs_to_many :projects, :join_table => 'developers_projects', :foreign_key => 'developer_id' diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb index d5c0b351aa..33cd6020a1 100644 --- a/activerecord/test/models/person.rb +++ b/activerecord/test/models/person.rb @@ -88,6 +88,25 @@ class TightDescendant < TightPerson; end class RichPerson < ActiveRecord::Base self.table_name = 'people' - + has_and_belongs_to_many :treasures, :join_table => 'peoples_treasures' end + +class NestedPerson < ActiveRecord::Base + self.table_name = 'people' + + attr_accessible :first_name, :best_friend_first_name, :best_friend_attributes + attr_accessible :first_name, :gender, :comments, :as => :admin + attr_accessible :best_friend_attributes, :best_friend_first_name, :as => :admin + + has_one :best_friend, :class_name => 'NestedPerson', :foreign_key => :best_friend_id + accepts_nested_attributes_for :best_friend, :update_only => true + + def comments=(new_comments) + raise RuntimeError + end + + def best_friend_first_name=(new_name) + assign_attributes({ :best_friend_attributes => { :first_name => new_name } }) + end +end
\ No newline at end of file diff --git a/activerecord/test/schema/postgresql_specific_schema.rb b/activerecord/test/schema/postgresql_specific_schema.rb index e51db50ae3..5f01f1fc50 100644 --- a/activerecord/test/schema/postgresql_specific_schema.rb +++ b/activerecord/test/schema/postgresql_specific_schema.rb @@ -1,6 +1,6 @@ ActiveRecord::Schema.define do - %w(postgresql_tsvectors postgresql_hstores postgresql_arrays postgresql_moneys postgresql_numbers postgresql_times postgresql_network_addresses postgresql_bit_strings + %w(postgresql_tsvectors postgresql_hstores postgresql_arrays postgresql_moneys postgresql_numbers postgresql_times postgresql_network_addresses postgresql_bit_strings postgresql_uuids postgresql_oids postgresql_xml_data_type defaults geometrics postgresql_timestamp_with_zones postgresql_partitioned_table postgresql_partitioned_table_parent).each do |table_name| execute "DROP TABLE IF EXISTS #{quote_table_name table_name}" end @@ -59,6 +59,14 @@ _SQL _SQL execute <<_SQL + CREATE TABLE postgresql_uuids ( + id SERIAL PRIMARY KEY, + guid uuid, + compact_guid uuid + ); +_SQL + + execute <<_SQL CREATE TABLE postgresql_tsvectors ( id SERIAL PRIMARY KEY, text_vector tsvector |