From 80e66cc4d90bf8c15d1a5f6e3152e90147f00772 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sat, 6 Aug 2016 19:55:02 +0200 Subject: normalizes indentation and whitespace across the project --- .../test/cases/adapters/mysql2/connection_test.rb | 6 +- .../test/cases/adapters/mysql2/json_test.rb | 270 +++++------ .../cases/adapters/mysql2/mysql2_adapter_test.rb | 6 +- .../cases/adapters/mysql2/reserved_word_test.rb | 22 +- .../adapters/mysql2/schema_migrations_test.rb | 32 +- .../test/cases/adapters/postgresql/array_test.rb | 26 +- .../cases/adapters/postgresql/composite_test.rb | 10 +- .../cases/adapters/postgresql/connection_test.rb | 12 +- .../cases/adapters/postgresql/geometric_test.rb | 14 +- .../test/cases/adapters/postgresql/hstore_test.rb | 52 +-- .../adapters/postgresql/postgresql_adapter_test.rb | 12 +- .../postgresql/referential_integrity_test.rb | 6 +- .../cases/adapters/postgresql/rename_table_test.rb | 6 +- .../postgresql/schema_authorization_test.rb | 2 +- .../cases/adapters/postgresql/transaction_test.rb | 12 +- .../test/cases/adapters/postgresql/uuid_test.rb | 4 +- .../cases/adapters/sqlite3/sqlite3_adapter_test.rb | 24 +- .../associations/eager_singularization_test.rb | 246 +++++----- .../test/cases/associations/required_test.rb | 12 +- activerecord/test/cases/attribute_methods_test.rb | 48 +- .../test/cases/autosave_association_test.rb | 18 +- activerecord/test/cases/column_alias_test.rb | 2 +- activerecord/test/cases/column_definition_test.rb | 6 +- activerecord/test/cases/comment_test.rb | 208 ++++----- .../connection_adapters/mysql_type_lookup_test.rb | 100 ++-- .../cases/connection_adapters/type_lookup_test.rb | 172 +++---- activerecord/test/cases/connection_pool_test.rb | 14 +- .../test/cases/database_statements_test.rb | 18 +- .../test/cases/date_time_precision_test.rb | 124 ++--- activerecord/test/cases/finder_respond_to_test.rb | 6 +- activerecord/test/cases/finder_test.rb | 2 +- activerecord/test/cases/fixture_set/file_test.rb | 18 +- activerecord/test/cases/helper.rb | 22 +- activerecord/test/cases/hot_compatibility_test.rb | 28 +- activerecord/test/cases/invalid_connection_test.rb | 30 +- activerecord/test/cases/json_serialization_test.rb | 16 +- activerecord/test/cases/locking_test.rb | 46 +- .../test/cases/migration/change_schema_test.rb | 12 +- activerecord/test/cases/migration/columns_test.rb | 2 +- .../test/cases/migration/foreign_key_test.rb | 464 +++++++++--------- activerecord/test/cases/migration/helper.rb | 2 +- .../cases/migration/references_foreign_key_test.rb | 314 ++++++------- .../cases/migration/references_statements_test.rb | 10 +- activerecord/test/cases/migration_test.rb | 36 +- activerecord/test/cases/migrator_test.rb | 52 +-- activerecord/test/cases/nested_attributes_test.rb | 12 +- .../cases/nested_attributes_with_callbacks_test.rb | 2 +- activerecord/test/cases/pooled_connections_test.rb | 6 +- .../test/cases/relation/delegation_test.rb | 2 +- .../test/cases/relation/where_clause_test.rb | 18 +- activerecord/test/cases/relation_test.rb | 22 +- activerecord/test/cases/tasks/mysql_rake_test.rb | 518 ++++++++++----------- .../test/cases/tasks/postgresql_rake_test.rb | 450 +++++++++--------- activerecord/test/cases/tasks/sqlite_rake_test.rb | 330 ++++++------- activerecord/test/cases/time_precision_test.rb | 120 ++--- activerecord/test/cases/timestamp_test.rb | 14 +- activerecord/test/cases/transactions_test.rb | 16 +- activerecord/test/cases/type/type_map_test.rb | 1 - activerecord/test/cases/view_test.rb | 206 ++++---- activerecord/test/cases/yaml_serialization_test.rb | 14 +- activerecord/test/models/club.rb | 6 +- activerecord/test/models/company.rb | 22 +- activerecord/test/models/company_in_module.rb | 6 +- activerecord/test/models/engine.rb | 1 - activerecord/test/models/eye.rb | 2 +- activerecord/test/models/mentor.rb | 2 +- activerecord/test/models/person.rb | 12 +- activerecord/test/models/vehicle.rb | 2 +- 68 files changed, 2163 insertions(+), 2165 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb index 475269d5cb..a3f83e73a6 100644 --- a/activerecord/test/cases/adapters/mysql2/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb @@ -167,7 +167,7 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase protected - def test_lock_free(lock_name) - @connection.select_value("SELECT IS_FREE_LOCK(#{@connection.quote(lock_name)})") == 1 - end + def test_lock_free(lock_name) + @connection.select_value("SELECT IS_FREE_LOCK(#{@connection.quote(lock_name)})") == 1 + end end diff --git a/activerecord/test/cases/adapters/mysql2/json_test.rb b/activerecord/test/cases/adapters/mysql2/json_test.rb index 87b6a07f65..f0e670d4b8 100644 --- a/activerecord/test/cases/adapters/mysql2/json_test.rb +++ b/activerecord/test/cases/adapters/mysql2/json_test.rb @@ -2,178 +2,178 @@ require "cases/helper" require "support/schema_dumping_helper" if ActiveRecord::Base.connection.supports_json? -class Mysql2JSONTest < ActiveRecord::Mysql2TestCase - include SchemaDumpingHelper - self.use_transactional_tests = false + class Mysql2JSONTest < ActiveRecord::Mysql2TestCase + include SchemaDumpingHelper + self.use_transactional_tests = false - class JsonDataType < ActiveRecord::Base - self.table_name = "json_data_type" + class JsonDataType < ActiveRecord::Base + self.table_name = "json_data_type" - store_accessor :settings, :resolution - end + store_accessor :settings, :resolution + end - def setup - @connection = ActiveRecord::Base.connection - begin - @connection.create_table("json_data_type") do |t| - t.json "payload" - t.json "settings" + def setup + @connection = ActiveRecord::Base.connection + begin + @connection.create_table("json_data_type") do |t| + t.json "payload" + t.json "settings" + end end end - end - def teardown - @connection.drop_table :json_data_type, if_exists: true - JsonDataType.reset_column_information - end + def teardown + @connection.drop_table :json_data_type, if_exists: true + JsonDataType.reset_column_information + end - def test_column - column = JsonDataType.columns_hash["payload"] - assert_equal :json, column.type - assert_equal "json", column.sql_type + def test_column + column = JsonDataType.columns_hash["payload"] + assert_equal :json, column.type + assert_equal "json", column.sql_type - type = JsonDataType.type_for_attribute("payload") - assert_not type.binary? - end + type = JsonDataType.type_for_attribute("payload") + assert_not type.binary? + end - def test_change_table_supports_json - @connection.change_table("json_data_type") do |t| - t.json "users" + def test_change_table_supports_json + @connection.change_table("json_data_type") do |t| + t.json "users" + end + JsonDataType.reset_column_information + column = JsonDataType.columns_hash["users"] + assert_equal :json, column.type end - JsonDataType.reset_column_information - column = JsonDataType.columns_hash["users"] - assert_equal :json, column.type - end - def test_schema_dumping - output = dump_table_schema("json_data_type") - assert_match(/t\.json\s+"settings"/, output) - end + def test_schema_dumping + output = dump_table_schema("json_data_type") + assert_match(/t\.json\s+"settings"/, output) + end - def test_cast_value_on_write - x = JsonDataType.new payload: {"string" => "foo", :symbol => :bar} - assert_equal({"string" => "foo", :symbol => :bar}, x.payload_before_type_cast) - assert_equal({"string" => "foo", "symbol" => "bar"}, x.payload) - x.save - assert_equal({"string" => "foo", "symbol" => "bar"}, x.reload.payload) - end + def test_cast_value_on_write + x = JsonDataType.new payload: {"string" => "foo", :symbol => :bar} + assert_equal({"string" => "foo", :symbol => :bar}, x.payload_before_type_cast) + assert_equal({"string" => "foo", "symbol" => "bar"}, x.payload) + x.save + assert_equal({"string" => "foo", "symbol" => "bar"}, x.reload.payload) + end - def test_type_cast_json - type = JsonDataType.type_for_attribute("payload") + def test_type_cast_json + type = JsonDataType.type_for_attribute("payload") - data = "{\"a_key\":\"a_value\"}" - hash = type.deserialize(data) - assert_equal({"a_key" => "a_value"}, hash) - assert_equal({"a_key" => "a_value"}, type.deserialize(data)) + data = "{\"a_key\":\"a_value\"}" + hash = type.deserialize(data) + assert_equal({"a_key" => "a_value"}, hash) + assert_equal({"a_key" => "a_value"}, type.deserialize(data)) - assert_equal({}, type.deserialize("{}")) - assert_equal({"key"=>nil}, type.deserialize('{"key": null}')) - assert_equal({"c"=>"}",'"a"'=>'b "a b'}, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"}))) - end + assert_equal({}, type.deserialize("{}")) + assert_equal({"key"=>nil}, type.deserialize('{"key": null}')) + assert_equal({"c"=>"}",'"a"'=>'b "a b'}, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"}))) + end - def test_rewrite - @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')" - x = JsonDataType.first - x.payload = { '"a\'' => "b" } - assert x.save! - end + def test_rewrite + @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')" + x = JsonDataType.first + x.payload = { '"a\'' => "b" } + assert x.save! + end - def test_select - @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')" - x = JsonDataType.first - assert_equal({"k" => "v"}, x.payload) - end + def test_select + @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')" + x = JsonDataType.first + assert_equal({"k" => "v"}, x.payload) + end - def test_select_multikey - @connection.execute %q|insert into json_data_type (payload) VALUES ('{"k1":"v1", "k2":"v2", "k3":[1,2,3]}')| - x = JsonDataType.first - assert_equal({"k1" => "v1", "k2" => "v2", "k3" => [1,2,3]}, x.payload) - end + def test_select_multikey + @connection.execute %q|insert into json_data_type (payload) VALUES ('{"k1":"v1", "k2":"v2", "k3":[1,2,3]}')| + x = JsonDataType.first + assert_equal({"k1" => "v1", "k2" => "v2", "k3" => [1,2,3]}, x.payload) + end - def test_null_json - @connection.execute %q|insert into json_data_type (payload) VALUES(null)| - x = JsonDataType.first - assert_equal(nil, x.payload) - end + def test_null_json + @connection.execute %q|insert into json_data_type (payload) VALUES(null)| + x = JsonDataType.first + assert_equal(nil, x.payload) + end - def test_select_array_json_value - @connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')| - x = JsonDataType.first - assert_equal(["v0", {"k1" => "v1"}], x.payload) - end + def test_select_array_json_value + @connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')| + x = JsonDataType.first + assert_equal(["v0", {"k1" => "v1"}], x.payload) + end - def test_rewrite_array_json_value - @connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')| - x = JsonDataType.first - x.payload = ["v1", {"k2" => "v2"}, "v3"] - assert x.save! - end + def test_rewrite_array_json_value + @connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')| + x = JsonDataType.first + x.payload = ["v1", {"k2" => "v2"}, "v3"] + assert x.save! + end - def test_with_store_accessors - x = JsonDataType.new(resolution: "320×480") - assert_equal "320×480", x.resolution + def test_with_store_accessors + x = JsonDataType.new(resolution: "320×480") + assert_equal "320×480", x.resolution - x.save! - x = JsonDataType.first - assert_equal "320×480", x.resolution + x.save! + x = JsonDataType.first + assert_equal "320×480", x.resolution - x.resolution = "640×1136" - x.save! + x.resolution = "640×1136" + x.save! - x = JsonDataType.first - assert_equal "640×1136", x.resolution - end + x = JsonDataType.first + assert_equal "640×1136", x.resolution + end - def test_duplication_with_store_accessors - x = JsonDataType.new(resolution: "320×480") - assert_equal "320×480", x.resolution + def test_duplication_with_store_accessors + x = JsonDataType.new(resolution: "320×480") + assert_equal "320×480", x.resolution - y = x.dup - assert_equal "320×480", y.resolution - end + y = x.dup + assert_equal "320×480", y.resolution + end - def test_yaml_round_trip_with_store_accessors - x = JsonDataType.new(resolution: "320×480") - assert_equal "320×480", x.resolution + def test_yaml_round_trip_with_store_accessors + x = JsonDataType.new(resolution: "320×480") + assert_equal "320×480", x.resolution - y = YAML.load(YAML.dump(x)) - assert_equal "320×480", y.resolution - end + y = YAML.load(YAML.dump(x)) + assert_equal "320×480", y.resolution + end - def test_changes_in_place - json = JsonDataType.new - assert_not json.changed? + def test_changes_in_place + json = JsonDataType.new + assert_not json.changed? - json.payload = { "one" => "two" } - assert json.changed? - assert json.payload_changed? + json.payload = { "one" => "two" } + assert json.changed? + assert json.payload_changed? - json.save! - assert_not json.changed? + json.save! + assert_not json.changed? - json.payload["three"] = "four" - assert json.payload_changed? + json.payload["three"] = "four" + assert json.payload_changed? - json.save! - json.reload + json.save! + json.reload - assert_equal({ "one" => "two", "three" => "four" }, json.payload) - assert_not json.changed? - end + assert_equal({ "one" => "two", "three" => "four" }, json.payload) + assert_not json.changed? + end - def test_assigning_string_literal - json = JsonDataType.create(payload: "foo") - assert_equal "foo", json.payload - end + def test_assigning_string_literal + json = JsonDataType.create(payload: "foo") + assert_equal "foo", json.payload + end - def test_assigning_number - json = JsonDataType.create(payload: 1.234) - assert_equal 1.234, json.payload - end + def test_assigning_number + json = JsonDataType.create(payload: 1.234) + assert_equal 1.234, json.payload + end - def test_assigning_boolean - json = JsonDataType.create(payload: true) - assert_equal true, json.payload + def test_assigning_boolean + json = JsonDataType.create(payload: true) + assert_equal true, json.payload + end end end -end diff --git a/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb b/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb index ac74b7f80f..69336eb906 100644 --- a/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb +++ b/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb @@ -67,7 +67,7 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase private - def with_example_table(definition = "id int auto_increment primary key, number int, data varchar(255)", &block) - super(@conn, "ex", definition, &block) - end + def with_example_table(definition = "id int auto_increment primary key, number int, data varchar(255)", &block) + super(@conn, "ex", definition, &block) + end end diff --git a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb index 8092cd1d4c..ff78bca173 100644 --- a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb +++ b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb @@ -131,22 +131,22 @@ class Mysql2ReservedWordTest < ActiveRecord::Mysql2TestCase private # custom fixture loader, uses FixtureSet#create_fixtures and appends base_path to the current file's path - def create_test_fixtures(*fixture_names) - ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT + "/reserved_words", fixture_names) - end + def create_test_fixtures(*fixture_names) + ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT + "/reserved_words", fixture_names) + end # custom drop table, uses execute on connection to drop a table if it exists. note: escapes table_name - def drop_tables_directly(table_names, connection = @connection) - table_names.each do |name| - connection.drop_table name, if_exists: true + def drop_tables_directly(table_names, connection = @connection) + table_names.each do |name| + connection.drop_table name, if_exists: true + end end - end # custom create table, uses execute on connection to create a table, note: escapes table_name, does NOT escape columns - def create_tables_directly (tables, connection = @connection) - tables.each do |table_name, column_properties| - connection.execute("CREATE TABLE `#{table_name}` ( #{column_properties} )") + def create_tables_directly (tables, connection = @connection) + tables.each do |table_name, column_properties| + connection.execute("CREATE TABLE `#{table_name}` ( #{column_properties} )") + end end - end end diff --git a/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb b/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb index cdd8f06801..fa54aac6b3 100644 --- a/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb +++ b/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb @@ -35,25 +35,25 @@ class SchemaMigrationsTest < ActiveRecord::Mysql2TestCase private - def with_encoding_utf8mb4 - database_name = connection.current_database - database_info = connection.select_one("SELECT * FROM information_schema.schemata WHERE schema_name = '#{database_name}'") + def with_encoding_utf8mb4 + database_name = connection.current_database + database_info = connection.select_one("SELECT * FROM information_schema.schemata WHERE schema_name = '#{database_name}'") - original_charset = database_info["DEFAULT_CHARACTER_SET_NAME"] - original_collation = database_info["DEFAULT_COLLATION_NAME"] + original_charset = database_info["DEFAULT_CHARACTER_SET_NAME"] + original_collation = database_info["DEFAULT_COLLATION_NAME"] - execute("ALTER DATABASE #{database_name} DEFAULT CHARACTER SET utf8mb4") + execute("ALTER DATABASE #{database_name} DEFAULT CHARACTER SET utf8mb4") - yield - ensure - execute("ALTER DATABASE #{database_name} DEFAULT CHARACTER SET #{original_charset} COLLATE #{original_collation}") - end + yield + ensure + execute("ALTER DATABASE #{database_name} DEFAULT CHARACTER SET #{original_charset} COLLATE #{original_collation}") + end - def connection - @connection ||= ActiveRecord::Base.connection - end + def connection + @connection ||= ActiveRecord::Base.connection + end - def execute(sql) - connection.execute(sql) - end + def execute(sql) + connection.execute(sql) + end end diff --git a/activerecord/test/cases/adapters/postgresql/array_test.rb b/activerecord/test/cases/adapters/postgresql/array_test.rb index a26547b8f1..26f3e66324 100644 --- a/activerecord/test/cases/adapters/postgresql/array_test.rb +++ b/activerecord/test/cases/adapters/postgresql/array_test.rb @@ -306,17 +306,17 @@ class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase end private - def assert_cycle field, array - # test creation - x = PgArray.create!(field => array) - x.reload - assert_equal(array, x.public_send(field)) - - # test updating - x = PgArray.create!(field => []) - x.public_send("#{field}=", array) - x.save! - x.reload - assert_equal(array, x.public_send(field)) - end + def assert_cycle field, array + # test creation + x = PgArray.create!(field => array) + x.reload + assert_equal(array, x.public_send(field)) + + # test updating + x = PgArray.create!(field => []) + x.public_send("#{field}=", array) + x.save! + x.reload + assert_equal(array, x.public_send(field)) + end end diff --git a/activerecord/test/cases/adapters/postgresql/composite_test.rb b/activerecord/test/cases/adapters/postgresql/composite_test.rb index 9377837810..1da2a9e2ac 100644 --- a/activerecord/test/cases/adapters/postgresql/composite_test.rb +++ b/activerecord/test/cases/adapters/postgresql/composite_test.rb @@ -69,12 +69,12 @@ class PostgresqlCompositeTest < ActiveRecord::PostgreSQLTestCase end private - def ensure_warning_is_issued - warning = capture(:stderr) do - PostgresqlComposite.columns_hash + def ensure_warning_is_issued + warning = capture(:stderr) do + PostgresqlComposite.columns_hash + end + assert_match(/unknown OID \d+: failed to recognize type of 'address'\. It will be treated as String\./, warning) end - assert_match(/unknown OID \d+: failed to recognize type of 'address'\. It will be treated as String\./, warning) - end end class PostgresqlCompositeWithCustomOIDTest < ActiveRecord::PostgreSQLTestCase diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb index 78b4bfbdaa..d01f601031 100644 --- a/activerecord/test/cases/adapters/postgresql/connection_test.rb +++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb @@ -247,11 +247,11 @@ module ActiveRecord protected - def with_warning_suppression - log_level = @connection.client_min_messages - @connection.client_min_messages = "error" - yield - @connection.client_min_messages = log_level - end + def with_warning_suppression + log_level = @connection.client_min_messages + @connection.client_min_messages = "error" + yield + @connection.client_min_messages = log_level + end end end diff --git a/activerecord/test/cases/adapters/postgresql/geometric_test.rb b/activerecord/test/cases/adapters/postgresql/geometric_test.rb index e35c5eb269..27a7467326 100644 --- a/activerecord/test/cases/adapters/postgresql/geometric_test.rb +++ b/activerecord/test/cases/adapters/postgresql/geometric_test.rb @@ -374,12 +374,12 @@ class PostgreSQLGeometricTypesTest < ActiveRecord::PostgreSQLTestCase private - def assert_column_exists(column_name) - assert connection.column_exists?(table_name, column_name) - end + def assert_column_exists(column_name) + assert connection.column_exists?(table_name, column_name) + end - def assert_type_correct(column_name, type) - column = connection.columns(table_name).find { |c| c.name == column_name.to_s } - assert_equal type, column.type - end + def assert_type_correct(column_name, type) + column = connection.columns(table_name).find { |c| c.name == column_name.to_s } + assert_equal type, column.type + end end diff --git a/activerecord/test/cases/adapters/postgresql/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb index 6197e517d5..5da4a3ac0f 100644 --- a/activerecord/test/cases/adapters/postgresql/hstore_test.rb +++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb @@ -322,32 +322,32 @@ if ActiveRecord::Base.connection.supports_extensions? end private - def assert_array_cycle(array) - # test creation - x = Hstore.create!(payload: array) - x.reload - assert_equal(array, x.payload) - - # test updating - x = Hstore.create!(payload: []) - x.payload = array - x.save! - x.reload - assert_equal(array, x.payload) - end - - def assert_cycle(hash) - # test creation - x = Hstore.create!(tags: hash) - x.reload - assert_equal(hash, x.tags) + def assert_array_cycle(array) + # test creation + x = Hstore.create!(payload: array) + x.reload + assert_equal(array, x.payload) + + # test updating + x = Hstore.create!(payload: []) + x.payload = array + x.save! + x.reload + assert_equal(array, x.payload) + end - # test updating - x = Hstore.create!(tags: {}) - x.tags = hash - x.save! - x.reload - assert_equal(hash, x.tags) - end + def assert_cycle(hash) + # test creation + x = Hstore.create!(tags: hash) + x.reload + assert_equal(hash, x.tags) + + # test updating + x = Hstore.create!(tags: {}) + x.tags = hash + x.save! + x.reload + assert_equal(hash, x.tags) + end end end diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb index 79d99c8a58..4b8d06be4b 100644 --- a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb +++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb @@ -390,13 +390,13 @@ module ActiveRecord private - def with_example_table(definition = "id serial primary key, number integer, data character varying(255)", &block) - super(@connection, "ex", definition, &block) - end + def with_example_table(definition = "id serial primary key, number integer, data character varying(255)", &block) + super(@connection, "ex", definition, &block) + end - def connection_without_insert_returning - ActiveRecord::Base.postgresql_connection(ActiveRecord::Base.configurations["arunit"].merge(insert_returning: false)) - end + def connection_without_insert_returning + ActiveRecord::Base.postgresql_connection(ActiveRecord::Base.configurations["arunit"].merge(insert_returning: false)) + end end end end diff --git a/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb b/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb index 6997044d81..0ff04bfa27 100644 --- a/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb +++ b/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb @@ -105,7 +105,7 @@ class PostgreSQLReferentialIntegrityTest < ActiveRecord::PostgreSQLTestCase private - def assert_transaction_is_not_broken - assert_equal 1, @connection.select_value("SELECT 1") - end + def assert_transaction_is_not_broken + assert_equal 1, @connection.select_value("SELECT 1") + end end diff --git a/activerecord/test/cases/adapters/postgresql/rename_table_test.rb b/activerecord/test/cases/adapters/postgresql/rename_table_test.rb index bd64bae308..461353d239 100644 --- a/activerecord/test/cases/adapters/postgresql/rename_table_test.rb +++ b/activerecord/test/cases/adapters/postgresql/rename_table_test.rb @@ -24,11 +24,11 @@ class PostgresqlRenameTableTest < ActiveRecord::PostgreSQLTestCase private - def num_indices_named(name) - @connection.execute(<<-SQL).values.length + def num_indices_named(name) + @connection.execute(<<-SQL).values.length SELECT 1 FROM "pg_index" JOIN "pg_class" ON "pg_index"."indexrelid" = "pg_class"."oid" WHERE "pg_class"."relname" = '#{name}' SQL - end + end end diff --git a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb index 72ae11966a..84af276874 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb @@ -110,7 +110,7 @@ class SchemaAuthorizationTest < ActiveRecord::PostgreSQLTestCase private def set_session_auth auth = nil - @connection.session_auth = auth || "default" + @connection.session_auth = auth || "default" end def bind_param(value) diff --git a/activerecord/test/cases/adapters/postgresql/transaction_test.rb b/activerecord/test/cases/adapters/postgresql/transaction_test.rb index c5164fc1f8..d992e22305 100644 --- a/activerecord/test/cases/adapters/postgresql/transaction_test.rb +++ b/activerecord/test/cases/adapters/postgresql/transaction_test.rb @@ -87,11 +87,11 @@ module ActiveRecord protected - def with_warning_suppression - log_level = @connection.client_min_messages - @connection.client_min_messages = "error" - yield - @connection.client_min_messages = log_level - end + def with_warning_suppression + log_level = @connection.client_min_messages + @connection.client_min_messages = "error" + yield + @connection.client_min_messages = log_level + end end end diff --git a/activerecord/test/cases/adapters/postgresql/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb index 2052d3851d..104c71f0d3 100644 --- a/activerecord/test/cases/adapters/postgresql/uuid_test.rb +++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb @@ -266,8 +266,8 @@ class PostgresqlUUIDTestInverseOf < ActiveRecord::PostgreSQLTestCase end teardown do - drop_table "pg_uuid_comments" - drop_table "pg_uuid_posts" + drop_table "pg_uuid_comments" + drop_table "pg_uuid_posts" end if ActiveRecord::Base.connection.supports_extensions? diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index 7edec0cb47..ca775e3704 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -420,22 +420,22 @@ module ActiveRecord private - def assert_logged logs - subscriber = SQLSubscriber.new - subscription = ActiveSupport::Notifications.subscribe("sql.active_record", subscriber) - yield - assert_equal logs, subscriber.logged - ensure - ActiveSupport::Notifications.unsubscribe(subscription) - end + def assert_logged logs + subscriber = SQLSubscriber.new + subscription = ActiveSupport::Notifications.subscribe("sql.active_record", subscriber) + yield + assert_equal logs, subscriber.logged + ensure + ActiveSupport::Notifications.unsubscribe(subscription) + end - def with_example_table(definition = nil, table_name = "ex", &block) - definition ||= <<-SQL + def with_example_table(definition = nil, table_name = "ex", &block) + definition ||= <<-SQL id integer PRIMARY KEY AUTOINCREMENT, number integer SQL - super(@conn, table_name, definition, &block) - end + super(@conn, table_name, definition, &block) + end end end end diff --git a/activerecord/test/cases/associations/eager_singularization_test.rb b/activerecord/test/cases/associations/eager_singularization_test.rb index df238b4859..373b17483c 100644 --- a/activerecord/test/cases/associations/eager_singularization_test.rb +++ b/activerecord/test/cases/associations/eager_singularization_test.rb @@ -2,147 +2,147 @@ require "cases/helper" if ActiveRecord::Base.connection.supports_migrations? -class EagerSingularizationTest < ActiveRecord::TestCase - class Virus < ActiveRecord::Base - belongs_to :octopus - end - - class Octopus < ActiveRecord::Base - has_one :virus - end - - class Pass < ActiveRecord::Base - belongs_to :bus - end - - class Bus < ActiveRecord::Base - has_many :passes - end - - class Mess < ActiveRecord::Base - has_and_belongs_to_many :crises - end - - class Crisis < ActiveRecord::Base - has_and_belongs_to_many :messes - has_many :analyses, dependent: :destroy - has_many :successes, through: :analyses - has_many :dresses, dependent: :destroy - has_many :compresses, through: :dresses - end - - class Analysis < ActiveRecord::Base - belongs_to :crisis - belongs_to :success - end - - class Success < ActiveRecord::Base - has_many :analyses, dependent: :destroy - has_many :crises, through: :analyses - end - - class Dress < ActiveRecord::Base - belongs_to :crisis - has_many :compresses - end + class EagerSingularizationTest < ActiveRecord::TestCase + class Virus < ActiveRecord::Base + belongs_to :octopus + end + + class Octopus < ActiveRecord::Base + has_one :virus + end + + class Pass < ActiveRecord::Base + belongs_to :bus + end - class Compress < ActiveRecord::Base - belongs_to :dress - end + class Bus < ActiveRecord::Base + has_many :passes + end - def setup - connection.create_table :viri do |t| - t.column :octopus_id, :integer - t.column :species, :string - end - connection.create_table :octopi do |t| - t.column :species, :string - end - connection.create_table :passes do |t| - t.column :bus_id, :integer - t.column :rides, :integer + class Mess < ActiveRecord::Base + has_and_belongs_to_many :crises end - connection.create_table :buses do |t| - t.column :name, :string - end - connection.create_table :crises_messes, id: false do |t| - t.column :crisis_id, :integer - t.column :mess_id, :integer - end - connection.create_table :messes do |t| - t.column :name, :string - end - connection.create_table :crises do |t| - t.column :name, :string - end - connection.create_table :successes do |t| - t.column :name, :string - end - connection.create_table :analyses do |t| - t.column :crisis_id, :integer - t.column :success_id, :integer - end - connection.create_table :dresses do |t| - t.column :crisis_id, :integer + + class Crisis < ActiveRecord::Base + has_and_belongs_to_many :messes + has_many :analyses, dependent: :destroy + has_many :successes, through: :analyses + has_many :dresses, dependent: :destroy + has_many :compresses, through: :dresses end - connection.create_table :compresses do |t| - t.column :dress_id, :integer + + class Analysis < ActiveRecord::Base + belongs_to :crisis + belongs_to :success end - end - teardown do - connection.drop_table :viri - connection.drop_table :octopi - connection.drop_table :passes - connection.drop_table :buses - connection.drop_table :crises_messes - connection.drop_table :messes - connection.drop_table :crises - connection.drop_table :successes - connection.drop_table :analyses - connection.drop_table :dresses - connection.drop_table :compresses - end + class Success < ActiveRecord::Base + has_many :analyses, dependent: :destroy + has_many :crises, through: :analyses + end - def connection - ActiveRecord::Base.connection - end + class Dress < ActiveRecord::Base + belongs_to :crisis + has_many :compresses + end - def test_eager_no_extra_singularization_belongs_to - assert_nothing_raised do - Virus.all.merge!(includes: :octopus).to_a + class Compress < ActiveRecord::Base + belongs_to :dress end - end - def test_eager_no_extra_singularization_has_one - assert_nothing_raised do - Octopus.all.merge!(includes: :virus).to_a + def setup + connection.create_table :viri do |t| + t.column :octopus_id, :integer + t.column :species, :string + end + connection.create_table :octopi do |t| + t.column :species, :string + end + connection.create_table :passes do |t| + t.column :bus_id, :integer + t.column :rides, :integer + end + connection.create_table :buses do |t| + t.column :name, :string + end + connection.create_table :crises_messes, id: false do |t| + t.column :crisis_id, :integer + t.column :mess_id, :integer + end + connection.create_table :messes do |t| + t.column :name, :string + end + connection.create_table :crises do |t| + t.column :name, :string + end + connection.create_table :successes do |t| + t.column :name, :string + end + connection.create_table :analyses do |t| + t.column :crisis_id, :integer + t.column :success_id, :integer + end + connection.create_table :dresses do |t| + t.column :crisis_id, :integer + end + connection.create_table :compresses do |t| + t.column :dress_id, :integer + end end - end - def test_eager_no_extra_singularization_has_many - assert_nothing_raised do - Bus.all.merge!(includes: :passes).to_a + teardown do + connection.drop_table :viri + connection.drop_table :octopi + connection.drop_table :passes + connection.drop_table :buses + connection.drop_table :crises_messes + connection.drop_table :messes + connection.drop_table :crises + connection.drop_table :successes + connection.drop_table :analyses + connection.drop_table :dresses + connection.drop_table :compresses end - end - def test_eager_no_extra_singularization_has_and_belongs_to_many - assert_nothing_raised do - Crisis.all.merge!(includes: :messes).to_a - Mess.all.merge!(includes: :crises).to_a + def connection + ActiveRecord::Base.connection end - end - def test_eager_no_extra_singularization_has_many_through_belongs_to - assert_nothing_raised do - Crisis.all.merge!(includes: :successes).to_a + def test_eager_no_extra_singularization_belongs_to + assert_nothing_raised do + Virus.all.merge!(includes: :octopus).to_a + end end - end - def test_eager_no_extra_singularization_has_many_through_has_many - assert_nothing_raised do - Crisis.all.merge!(includes: :compresses).to_a + def test_eager_no_extra_singularization_has_one + assert_nothing_raised do + Octopus.all.merge!(includes: :virus).to_a + end + end + + def test_eager_no_extra_singularization_has_many + assert_nothing_raised do + Bus.all.merge!(includes: :passes).to_a + end + end + + def test_eager_no_extra_singularization_has_and_belongs_to_many + assert_nothing_raised do + Crisis.all.merge!(includes: :messes).to_a + Mess.all.merge!(includes: :crises).to_a + end + end + + def test_eager_no_extra_singularization_has_many_through_belongs_to + assert_nothing_raised do + Crisis.all.merge!(includes: :successes).to_a + end + end + + def test_eager_no_extra_singularization_has_many_through_has_many + assert_nothing_raised do + Crisis.all.merge!(includes: :compresses).to_a + end end end end -end diff --git a/activerecord/test/cases/associations/required_test.rb b/activerecord/test/cases/associations/required_test.rb index 7d7da44629..f8b686721e 100644 --- a/activerecord/test/cases/associations/required_test.rb +++ b/activerecord/test/cases/associations/required_test.rb @@ -92,11 +92,11 @@ class RequiredAssociationsTest < ActiveRecord::TestCase private - def subclass_of(klass, &block) - subclass = Class.new(klass, &block) - def subclass.name - superclass.name + def subclass_of(klass, &block) + subclass = Class.new(klass, &block) + def subclass.name + superclass.name + end + subclass end - subclass - end end diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index 8aad272bfd..7a2041937d 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -975,38 +975,38 @@ class AttributeMethodsTest < ActiveRecord::TestCase private - def new_topic_like_ar_class(&block) - klass = Class.new(ActiveRecord::Base) do - self.table_name = "topics" - class_eval(&block) - end + def new_topic_like_ar_class(&block) + klass = Class.new(ActiveRecord::Base) do + self.table_name = "topics" + class_eval(&block) + end - assert_empty klass.generated_attribute_methods.instance_methods(false) - klass - end + assert_empty klass.generated_attribute_methods.instance_methods(false) + klass + end - def with_time_zone_aware_types(*types) - old_types = ActiveRecord::Base.time_zone_aware_types - ActiveRecord::Base.time_zone_aware_types = types - yield - ensure - ActiveRecord::Base.time_zone_aware_types = old_types - end + def with_time_zone_aware_types(*types) + old_types = ActiveRecord::Base.time_zone_aware_types + ActiveRecord::Base.time_zone_aware_types = types + yield + ensure + ActiveRecord::Base.time_zone_aware_types = old_types + end - def cached_columns - Topic.columns.map(&:name) - end + def cached_columns + Topic.columns.map(&:name) + end - def time_related_columns_on_topic - Topic.columns.select { |c| [:time, :date, :datetime, :timestamp].include?(c.type) } - end + def time_related_columns_on_topic + Topic.columns.select { |c| [:time, :date, :datetime, :timestamp].include?(c.type) } + end - def privatize(method_signature) - @target.class_eval(<<-private_method, __FILE__, __LINE__ + 1) + def privatize(method_signature) + @target.class_eval(<<-private_method, __FILE__, __LINE__ + 1) private def #{method_signature} "I'm private" end private_method - end + end end diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index d09e4cae3b..ae5127cc56 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -79,18 +79,18 @@ class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase private - def assert_no_difference_when_adding_callbacks_twice_for(model, association_name) - reflection = model.reflect_on_association(association_name) - assert_no_difference "callbacks_for_model(#{model.name}).length" do - model.send(:add_autosave_association_callbacks, reflection) + def assert_no_difference_when_adding_callbacks_twice_for(model, association_name) + reflection = model.reflect_on_association(association_name) + assert_no_difference "callbacks_for_model(#{model.name}).length" do + model.send(:add_autosave_association_callbacks, reflection) + end end - end - def callbacks_for_model(model) - model.instance_variables.grep(/_callbacks$/).flat_map do |ivar| - model.instance_variable_get(ivar) + def callbacks_for_model(model) + model.instance_variables.grep(/_callbacks$/).flat_map do |ivar| + model.instance_variable_get(ivar) + end end - end end class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase diff --git a/activerecord/test/cases/column_alias_test.rb b/activerecord/test/cases/column_alias_test.rb index 85d65b074c..ae64c99f33 100644 --- a/activerecord/test/cases/column_alias_test.rb +++ b/activerecord/test/cases/column_alias_test.rb @@ -5,7 +5,7 @@ class TestColumnAlias < ActiveRecord::TestCase fixtures :topics QUERY = if "Oracle" == ActiveRecord::Base.connection.adapter_name - "SELECT id AS pk FROM topics WHERE ROWNUM < 2" + "SELECT id AS pk FROM topics WHERE ROWNUM < 2" else "SELECT id AS pk FROM topics" end diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb index 9b38eda004..c5fe103efd 100644 --- a/activerecord/test/cases/column_definition_test.rb +++ b/activerecord/test/cases/column_definition_test.rb @@ -18,7 +18,7 @@ module ActiveRecord column_def = ColumnDefinition.new( column.name, "string", column.limit, column.precision, column.scale, column.default, column.null) - assert_equal "title varchar(20)", @viz.accept(column_def) + assert_equal "title varchar(20)", @viz.accept(column_def) end def test_should_include_default_clause_when_default_is_present @@ -26,7 +26,7 @@ module ActiveRecord column_def = ColumnDefinition.new( column.name, "string", column.limit, column.precision, column.scale, column.default, column.null) - assert_equal %Q{title varchar(20) DEFAULT 'Hello'}, @viz.accept(column_def) + assert_equal %Q{title varchar(20) DEFAULT 'Hello'}, @viz.accept(column_def) end def test_should_specify_not_null_if_null_option_is_false @@ -35,7 +35,7 @@ module ActiveRecord column_def = ColumnDefinition.new( column.name, "string", column.limit, column.precision, column.scale, column.default, column.null) - assert_equal %Q{title varchar(20) DEFAULT 'Hello' NOT NULL}, @viz.accept(column_def) + assert_equal %Q{title varchar(20) DEFAULT 'Hello' NOT NULL}, @viz.accept(column_def) end if current_adapter?(:Mysql2Adapter) diff --git a/activerecord/test/cases/comment_test.rb b/activerecord/test/cases/comment_test.rb index 87cc30f0d7..262ad319be 100644 --- a/activerecord/test/cases/comment_test.rb +++ b/activerecord/test/cases/comment_test.rb @@ -3,137 +3,137 @@ require "support/schema_dumping_helper" if ActiveRecord::Base.connection.supports_comments? -class CommentTest < ActiveRecord::TestCase - include SchemaDumpingHelper + class CommentTest < ActiveRecord::TestCase + include SchemaDumpingHelper - class Commented < ActiveRecord::Base - self.table_name = "commenteds" - end - - class BlankComment < ActiveRecord::Base - end - - setup do - @connection = ActiveRecord::Base.connection - - @connection.create_table("commenteds", comment: "A table with comment", force: true) do |t| - t.string "name", comment: "Comment should help clarify the column purpose" - t.boolean "obvious", comment: "Question is: should you comment obviously named objects?" - t.string "content" - t.index "name", comment: %Q["Very important" index that powers all the performance.\nAnd it's fun!] + class Commented < ActiveRecord::Base + self.table_name = "commenteds" end - @connection.create_table("blank_comments", comment: " ", force: true) do |t| - t.string :space_comment, comment: " " - t.string :empty_comment, comment: "" - t.string :nil_comment, comment: nil - t.string :absent_comment - t.index :space_comment, comment: " " - t.index :empty_comment, comment: "" - t.index :nil_comment, comment: nil - t.index :absent_comment + class BlankComment < ActiveRecord::Base end - Commented.reset_column_information - BlankComment.reset_column_information - end - - teardown do - @connection.drop_table "commenteds", if_exists: true - @connection.drop_table "blank_comments", if_exists: true - end + setup do + @connection = ActiveRecord::Base.connection + + @connection.create_table("commenteds", comment: "A table with comment", force: true) do |t| + t.string "name", comment: "Comment should help clarify the column purpose" + t.boolean "obvious", comment: "Question is: should you comment obviously named objects?" + t.string "content" + t.index "name", comment: %Q["Very important" index that powers all the performance.\nAnd it's fun!] + end + + @connection.create_table("blank_comments", comment: " ", force: true) do |t| + t.string :space_comment, comment: " " + t.string :empty_comment, comment: "" + t.string :nil_comment, comment: nil + t.string :absent_comment + t.index :space_comment, comment: " " + t.index :empty_comment, comment: "" + t.index :nil_comment, comment: nil + t.index :absent_comment + end + + Commented.reset_column_information + BlankComment.reset_column_information + end - def test_column_created_in_block - column = Commented.columns_hash["name"] - assert_equal :string, column.type - assert_equal "Comment should help clarify the column purpose", column.comment - end + teardown do + @connection.drop_table "commenteds", if_exists: true + @connection.drop_table "blank_comments", if_exists: true + end - def test_blank_columns_created_in_block - %w[ space_comment empty_comment nil_comment absent_comment ].each do |field| - column = BlankComment.columns_hash[field] + def test_column_created_in_block + column = Commented.columns_hash["name"] assert_equal :string, column.type - assert_nil column.comment + assert_equal "Comment should help clarify the column purpose", column.comment end - end - def test_blank_indexes_created_in_block - @connection.indexes("blank_comments").each do |index| - assert_nil index.comment + def test_blank_columns_created_in_block + %w[ space_comment empty_comment nil_comment absent_comment ].each do |field| + column = BlankComment.columns_hash[field] + assert_equal :string, column.type + assert_nil column.comment + end end - end - def test_add_column_with_comment_later - @connection.add_column :commenteds, :rating, :integer, comment: "I am running out of imagination" - Commented.reset_column_information - column = Commented.columns_hash["rating"] + def test_blank_indexes_created_in_block + @connection.indexes("blank_comments").each do |index| + assert_nil index.comment + end + end - assert_equal :integer, column.type - assert_equal "I am running out of imagination", column.comment - end + def test_add_column_with_comment_later + @connection.add_column :commenteds, :rating, :integer, comment: "I am running out of imagination" + Commented.reset_column_information + column = Commented.columns_hash["rating"] - def test_add_index_with_comment_later - @connection.add_index :commenteds, :obvious, name: "idx_obvious", comment: "We need to see obvious comments" - index = @connection.indexes("commenteds").find { |idef| idef.name == "idx_obvious" } - assert_equal "We need to see obvious comments", index.comment - end + assert_equal :integer, column.type + assert_equal "I am running out of imagination", column.comment + end - def test_add_comment_to_column - @connection.change_column :commenteds, :content, :string, comment: "Whoa, content describes itself!" + def test_add_index_with_comment_later + @connection.add_index :commenteds, :obvious, name: "idx_obvious", comment: "We need to see obvious comments" + index = @connection.indexes("commenteds").find { |idef| idef.name == "idx_obvious" } + assert_equal "We need to see obvious comments", index.comment + end - Commented.reset_column_information - column = Commented.columns_hash["content"] + def test_add_comment_to_column + @connection.change_column :commenteds, :content, :string, comment: "Whoa, content describes itself!" - assert_equal :string, column.type - assert_equal "Whoa, content describes itself!", column.comment - end + Commented.reset_column_information + column = Commented.columns_hash["content"] - def test_remove_comment_from_column - @connection.change_column :commenteds, :obvious, :string, comment: nil + assert_equal :string, column.type + assert_equal "Whoa, content describes itself!", column.comment + end - Commented.reset_column_information - column = Commented.columns_hash["obvious"] + def test_remove_comment_from_column + @connection.change_column :commenteds, :obvious, :string, comment: nil - assert_equal :string, column.type - assert_nil column.comment - end + Commented.reset_column_information + column = Commented.columns_hash["obvious"] - def test_schema_dump_with_comments - # Do all the stuff from other tests - @connection.add_column :commenteds, :rating, :integer, comment: "I am running out of imagination" - @connection.change_column :commenteds, :content, :string, comment: "Whoa, content describes itself!" - @connection.change_column :commenteds, :obvious, :string, comment: nil - @connection.add_index :commenteds, :obvious, name: "idx_obvious", comment: "We need to see obvious comments" - - # And check that these changes are reflected in dump - output = dump_table_schema "commenteds" - assert_match %r[create_table "commenteds",.+\s+comment: "A table with comment"], output - assert_match %r[t\.string\s+"name",\s+comment: "Comment should help clarify the column purpose"], output - assert_match %r[t\.string\s+"obvious"\n], output - assert_match %r[t\.string\s+"content",\s+comment: "Whoa, content describes itself!"], output - assert_match %r[t\.integer\s+"rating",\s+comment: "I am running out of imagination"], output - assert_match %r[t\.index\s+.+\s+comment: "\\\"Very important\\\" index that powers all the performance.\\nAnd it's fun!"], output - assert_match %r[t\.index\s+.+\s+name: "idx_obvious",.+\s+comment: "We need to see obvious comments"], output - end + assert_equal :string, column.type + assert_nil column.comment + end - def test_schema_dump_omits_blank_comments - output = dump_table_schema "blank_comments" + def test_schema_dump_with_comments + # Do all the stuff from other tests + @connection.add_column :commenteds, :rating, :integer, comment: "I am running out of imagination" + @connection.change_column :commenteds, :content, :string, comment: "Whoa, content describes itself!" + @connection.change_column :commenteds, :obvious, :string, comment: nil + @connection.add_index :commenteds, :obvious, name: "idx_obvious", comment: "We need to see obvious comments" + + # And check that these changes are reflected in dump + output = dump_table_schema "commenteds" + assert_match %r[create_table "commenteds",.+\s+comment: "A table with comment"], output + assert_match %r[t\.string\s+"name",\s+comment: "Comment should help clarify the column purpose"], output + assert_match %r[t\.string\s+"obvious"\n], output + assert_match %r[t\.string\s+"content",\s+comment: "Whoa, content describes itself!"], output + assert_match %r[t\.integer\s+"rating",\s+comment: "I am running out of imagination"], output + assert_match %r[t\.index\s+.+\s+comment: "\\\"Very important\\\" index that powers all the performance.\\nAnd it's fun!"], output + assert_match %r[t\.index\s+.+\s+name: "idx_obvious",.+\s+comment: "We need to see obvious comments"], output + end - assert_match %r[create_table "blank_comments"], output - assert_no_match %r[create_table "blank_comments",.+comment:], output + def test_schema_dump_omits_blank_comments + output = dump_table_schema "blank_comments" - assert_match %r[t\.string\s+"space_comment"\n], output - assert_no_match %r[t\.string\s+"space_comment", comment:\n], output + assert_match %r[create_table "blank_comments"], output + assert_no_match %r[create_table "blank_comments",.+comment:], output - assert_match %r[t\.string\s+"empty_comment"\n], output - assert_no_match %r[t\.string\s+"empty_comment", comment:\n], output + assert_match %r[t\.string\s+"space_comment"\n], output + assert_no_match %r[t\.string\s+"space_comment", comment:\n], output - assert_match %r[t\.string\s+"nil_comment"\n], output - assert_no_match %r[t\.string\s+"nil_comment", comment:\n], output + assert_match %r[t\.string\s+"empty_comment"\n], output + assert_no_match %r[t\.string\s+"empty_comment", comment:\n], output - assert_match %r[t\.string\s+"absent_comment"\n], output - assert_no_match %r[t\.string\s+"absent_comment", comment:\n], output + assert_match %r[t\.string\s+"nil_comment"\n], output + assert_no_match %r[t\.string\s+"nil_comment", comment:\n], output + + assert_match %r[t\.string\s+"absent_comment"\n], output + assert_no_match %r[t\.string\s+"absent_comment", comment:\n], output + end end -end end diff --git a/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb b/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb index 209802d34f..3657b8340d 100644 --- a/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb +++ b/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb @@ -1,69 +1,69 @@ require "cases/helper" if current_adapter?(:Mysql2Adapter) -module ActiveRecord - module ConnectionAdapters - class MysqlTypeLookupTest < ActiveRecord::TestCase - setup do - @connection = ActiveRecord::Base.connection - end + module ActiveRecord + module ConnectionAdapters + class MysqlTypeLookupTest < ActiveRecord::TestCase + setup do + @connection = ActiveRecord::Base.connection + end - def test_boolean_types - emulate_booleans(true) do - assert_lookup_type :boolean, "tinyint(1)" - assert_lookup_type :boolean, "TINYINT(1)" + def test_boolean_types + emulate_booleans(true) do + assert_lookup_type :boolean, "tinyint(1)" + assert_lookup_type :boolean, "TINYINT(1)" + end end - end - def test_string_types - assert_lookup_type :string, "enum('one', 'two', 'three')" - assert_lookup_type :string, "ENUM('one', 'two', 'three')" - assert_lookup_type :string, "set('one', 'two', 'three')" - assert_lookup_type :string, "SET('one', 'two', 'three')" - end + def test_string_types + assert_lookup_type :string, "enum('one', 'two', 'three')" + assert_lookup_type :string, "ENUM('one', 'two', 'three')" + assert_lookup_type :string, "set('one', 'two', 'three')" + assert_lookup_type :string, "SET('one', 'two', 'three')" + end - def test_set_type_with_value_matching_other_type - assert_lookup_type :string, "SET('unicode', '8bit', 'none', 'time')" - end + def test_set_type_with_value_matching_other_type + assert_lookup_type :string, "SET('unicode', '8bit', 'none', 'time')" + end - def test_enum_type_with_value_matching_other_type - assert_lookup_type :string, "ENUM('unicode', '8bit', 'none')" - end + def test_enum_type_with_value_matching_other_type + assert_lookup_type :string, "ENUM('unicode', '8bit', 'none')" + end - def test_binary_types - assert_lookup_type :binary, "bit" - assert_lookup_type :binary, "BIT" - end + def test_binary_types + assert_lookup_type :binary, "bit" + assert_lookup_type :binary, "BIT" + end - def test_integer_types - emulate_booleans(false) do - assert_lookup_type :integer, "tinyint(1)" - assert_lookup_type :integer, "TINYINT(1)" - assert_lookup_type :integer, "year" - assert_lookup_type :integer, "YEAR" + def test_integer_types + emulate_booleans(false) do + assert_lookup_type :integer, "tinyint(1)" + assert_lookup_type :integer, "TINYINT(1)" + assert_lookup_type :integer, "year" + assert_lookup_type :integer, "YEAR" + end end - end - private + private - def assert_lookup_type(type, lookup) - cast_type = @connection.type_map.lookup(lookup) - assert_equal type, cast_type.type - end + def assert_lookup_type(type, lookup) + cast_type = @connection.type_map.lookup(lookup) + assert_equal type, cast_type.type + end - def emulate_booleans(value) - old_emulate_booleans = @connection.emulate_booleans - change_emulate_booleans(value) - yield - ensure - change_emulate_booleans(old_emulate_booleans) - end + def emulate_booleans(value) + old_emulate_booleans = @connection.emulate_booleans + change_emulate_booleans(value) + yield + ensure + change_emulate_booleans(old_emulate_booleans) + end - def change_emulate_booleans(value) - @connection.emulate_booleans = value - @connection.clear_cache! + def change_emulate_booleans(value) + @connection.emulate_booleans = value + @connection.clear_cache! + end end end end end -end diff --git a/activerecord/test/cases/connection_adapters/type_lookup_test.rb b/activerecord/test/cases/connection_adapters/type_lookup_test.rb index c01464ed68..e2e5445a4e 100644 --- a/activerecord/test/cases/connection_adapters/type_lookup_test.rb +++ b/activerecord/test/cases/connection_adapters/type_lookup_test.rb @@ -1,110 +1,110 @@ require "cases/helper" unless current_adapter?(:PostgreSQLAdapter) # PostgreSQL does not use type strings for lookup -module ActiveRecord - module ConnectionAdapters - class TypeLookupTest < ActiveRecord::TestCase - setup do - @connection = ActiveRecord::Base.connection - end + module ActiveRecord + module ConnectionAdapters + class TypeLookupTest < ActiveRecord::TestCase + setup do + @connection = ActiveRecord::Base.connection + end - def test_boolean_types - assert_lookup_type :boolean, "boolean" - assert_lookup_type :boolean, "BOOLEAN" - end + def test_boolean_types + assert_lookup_type :boolean, "boolean" + assert_lookup_type :boolean, "BOOLEAN" + end - def test_string_types - assert_lookup_type :string, "char" - assert_lookup_type :string, "varchar" - assert_lookup_type :string, "VARCHAR" - assert_lookup_type :string, "varchar(255)" - assert_lookup_type :string, "character varying" - end + def test_string_types + assert_lookup_type :string, "char" + assert_lookup_type :string, "varchar" + assert_lookup_type :string, "VARCHAR" + assert_lookup_type :string, "varchar(255)" + assert_lookup_type :string, "character varying" + end - def test_binary_types - assert_lookup_type :binary, "binary" - assert_lookup_type :binary, "BINARY" - assert_lookup_type :binary, "blob" - assert_lookup_type :binary, "BLOB" - end + def test_binary_types + assert_lookup_type :binary, "binary" + assert_lookup_type :binary, "BINARY" + assert_lookup_type :binary, "blob" + assert_lookup_type :binary, "BLOB" + end - def test_text_types - assert_lookup_type :text, "text" - assert_lookup_type :text, "TEXT" - assert_lookup_type :text, "clob" - assert_lookup_type :text, "CLOB" - end + def test_text_types + assert_lookup_type :text, "text" + assert_lookup_type :text, "TEXT" + assert_lookup_type :text, "clob" + assert_lookup_type :text, "CLOB" + end - def test_date_types - assert_lookup_type :date, "date" - assert_lookup_type :date, "DATE" - end + def test_date_types + assert_lookup_type :date, "date" + assert_lookup_type :date, "DATE" + end - def test_time_types - assert_lookup_type :time, "time" - assert_lookup_type :time, "TIME" - end + def test_time_types + assert_lookup_type :time, "time" + assert_lookup_type :time, "TIME" + end - def test_datetime_types - assert_lookup_type :datetime, "datetime" - assert_lookup_type :datetime, "DATETIME" - assert_lookup_type :datetime, "timestamp" - assert_lookup_type :datetime, "TIMESTAMP" - end + def test_datetime_types + assert_lookup_type :datetime, "datetime" + assert_lookup_type :datetime, "DATETIME" + assert_lookup_type :datetime, "timestamp" + assert_lookup_type :datetime, "TIMESTAMP" + end - def test_decimal_types - assert_lookup_type :decimal, "decimal" - assert_lookup_type :decimal, "decimal(2,8)" - assert_lookup_type :decimal, "DECIMAL" - assert_lookup_type :decimal, "numeric" - assert_lookup_type :decimal, "numeric(2,8)" - assert_lookup_type :decimal, "NUMERIC" - assert_lookup_type :decimal, "number" - assert_lookup_type :decimal, "number(2,8)" - assert_lookup_type :decimal, "NUMBER" - end + def test_decimal_types + assert_lookup_type :decimal, "decimal" + assert_lookup_type :decimal, "decimal(2,8)" + assert_lookup_type :decimal, "DECIMAL" + assert_lookup_type :decimal, "numeric" + assert_lookup_type :decimal, "numeric(2,8)" + assert_lookup_type :decimal, "NUMERIC" + assert_lookup_type :decimal, "number" + assert_lookup_type :decimal, "number(2,8)" + assert_lookup_type :decimal, "NUMBER" + end - def test_float_types - assert_lookup_type :float, "float" - assert_lookup_type :float, "FLOAT" - assert_lookup_type :float, "double" - assert_lookup_type :float, "DOUBLE" - end + def test_float_types + assert_lookup_type :float, "float" + assert_lookup_type :float, "FLOAT" + assert_lookup_type :float, "double" + assert_lookup_type :float, "DOUBLE" + end - def test_integer_types - assert_lookup_type :integer, "integer" - assert_lookup_type :integer, "INTEGER" - assert_lookup_type :integer, "tinyint" - assert_lookup_type :integer, "smallint" - assert_lookup_type :integer, "bigint" - end + def test_integer_types + assert_lookup_type :integer, "integer" + assert_lookup_type :integer, "INTEGER" + assert_lookup_type :integer, "tinyint" + assert_lookup_type :integer, "smallint" + assert_lookup_type :integer, "bigint" + end - def test_bigint_limit - cast_type = @connection.type_map.lookup("bigint") - if current_adapter?(:OracleAdapter) - assert_equal 19, cast_type.limit - else - assert_equal 8, cast_type.limit + def test_bigint_limit + cast_type = @connection.type_map.lookup("bigint") + if current_adapter?(:OracleAdapter) + assert_equal 19, cast_type.limit + else + assert_equal 8, cast_type.limit + end end - end - def test_decimal_without_scale - types = %w{decimal(2) decimal(2,0) numeric(2) numeric(2,0) number(2) number(2,0)} - types.each do |type| - cast_type = @connection.type_map.lookup(type) + def test_decimal_without_scale + types = %w{decimal(2) decimal(2,0) numeric(2) numeric(2,0) number(2) number(2,0)} + types.each do |type| + cast_type = @connection.type_map.lookup(type) - assert_equal :decimal, cast_type.type - assert_equal 2, cast_type.cast(2.1) + assert_equal :decimal, cast_type.type + assert_equal 2, cast_type.cast(2.1) + end end - end - private + private - def assert_lookup_type(type, lookup) - cast_type = @connection.type_map.lookup(lookup) - assert_equal type, cast_type.type + def assert_lookup_type(type, lookup) + cast_type = @connection.type_map.lookup(lookup) + assert_equal type, cast_type.type + end end end end end -end diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb index 8324fecd3a..d7ff9d6880 100644 --- a/activerecord/test/cases/connection_pool_test.rb +++ b/activerecord/test/cases/connection_pool_test.rb @@ -527,13 +527,13 @@ module ActiveRecord end private - def with_single_connection_pool - one_conn_spec = ActiveRecord::Base.connection_pool.spec.dup - one_conn_spec.config[:pool] = 1 # this is safe to do, because .dupped ConnectionSpecification also auto-dups its config - yield(pool = ConnectionPool.new(one_conn_spec)) - ensure - pool.disconnect! if pool - end + def with_single_connection_pool + one_conn_spec = ActiveRecord::Base.connection_pool.spec.dup + one_conn_spec.config[:pool] = 1 # this is safe to do, because .dupped ConnectionSpecification also auto-dups its config + yield(pool = ConnectionPool.new(one_conn_spec)) + ensure + pool.disconnect! if pool + end end end end diff --git a/activerecord/test/cases/database_statements_test.rb b/activerecord/test/cases/database_statements_test.rb index 3169408ac0..ac9912d4d1 100644 --- a/activerecord/test/cases/database_statements_test.rb +++ b/activerecord/test/cases/database_statements_test.rb @@ -21,14 +21,14 @@ class DatabaseStatementsTest < ActiveRecord::TestCase private - def return_the_inserted_id(method:) - # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method - if current_adapter?(:OracleAdapter) - sequence_name = "accounts_seq" - id_value = @connection.next_sequence_value(sequence_name) - @connection.send(method, "INSERT INTO accounts (id, firm_id,credit_limit) VALUES (accounts_seq.nextval,42,5000)", nil, :id, id_value, sequence_name) - else - @connection.send(method, "INSERT INTO accounts (firm_id,credit_limit) VALUES (42,5000)") + def return_the_inserted_id(method:) + # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method + if current_adapter?(:OracleAdapter) + sequence_name = "accounts_seq" + id_value = @connection.next_sequence_value(sequence_name) + @connection.send(method, "INSERT INTO accounts (id, firm_id,credit_limit) VALUES (accounts_seq.nextval,42,5000)", nil, :id, id_value, sequence_name) + else + @connection.send(method, "INSERT INTO accounts (firm_id,credit_limit) VALUES (42,5000)") + end end - end end diff --git a/activerecord/test/cases/date_time_precision_test.rb b/activerecord/test/cases/date_time_precision_test.rb index 40c68f9dc8..7876542379 100644 --- a/activerecord/test/cases/date_time_precision_test.rb +++ b/activerecord/test/cases/date_time_precision_test.rb @@ -2,87 +2,87 @@ require "cases/helper" require "support/schema_dumping_helper" if subsecond_precision_supported? -class DateTimePrecisionTest < ActiveRecord::TestCase - include SchemaDumpingHelper - self.use_transactional_tests = false + class DateTimePrecisionTest < ActiveRecord::TestCase + include SchemaDumpingHelper + self.use_transactional_tests = false - class Foo < ActiveRecord::Base; end + class Foo < ActiveRecord::Base; end - setup do - @connection = ActiveRecord::Base.connection - Foo.reset_column_information - end - - teardown do - @connection.drop_table :foos, if_exists: true - end + setup do + @connection = ActiveRecord::Base.connection + Foo.reset_column_information + end - def test_datetime_data_type_with_precision - @connection.create_table(:foos, force: true) - @connection.add_column :foos, :created_at, :datetime, precision: 0 - @connection.add_column :foos, :updated_at, :datetime, precision: 5 - assert_equal 0, Foo.columns_hash["created_at"].precision - assert_equal 5, Foo.columns_hash["updated_at"].precision - end + teardown do + @connection.drop_table :foos, if_exists: true + end - def test_timestamps_helper_with_custom_precision - @connection.create_table(:foos, force: true) do |t| - t.timestamps precision: 4 + def test_datetime_data_type_with_precision + @connection.create_table(:foos, force: true) + @connection.add_column :foos, :created_at, :datetime, precision: 0 + @connection.add_column :foos, :updated_at, :datetime, precision: 5 + assert_equal 0, Foo.columns_hash["created_at"].precision + assert_equal 5, Foo.columns_hash["updated_at"].precision end - assert_equal 4, Foo.columns_hash["created_at"].precision - assert_equal 4, Foo.columns_hash["updated_at"].precision - end - def test_passing_precision_to_datetime_does_not_set_limit - @connection.create_table(:foos, force: true) do |t| - t.timestamps precision: 4 + def test_timestamps_helper_with_custom_precision + @connection.create_table(:foos, force: true) do |t| + t.timestamps precision: 4 + end + assert_equal 4, Foo.columns_hash["created_at"].precision + assert_equal 4, Foo.columns_hash["updated_at"].precision end - assert_nil Foo.columns_hash["created_at"].limit - assert_nil Foo.columns_hash["updated_at"].limit - end - def test_invalid_datetime_precision_raises_error - assert_raises ActiveRecord::ActiveRecordError do + def test_passing_precision_to_datetime_does_not_set_limit @connection.create_table(:foos, force: true) do |t| - t.timestamps precision: 7 + t.timestamps precision: 4 end + assert_nil Foo.columns_hash["created_at"].limit + assert_nil Foo.columns_hash["updated_at"].limit end - end - def test_formatting_datetime_according_to_precision - @connection.create_table(:foos, force: true) do |t| - t.datetime :created_at, precision: 0 - t.datetime :updated_at, precision: 4 + def test_invalid_datetime_precision_raises_error + assert_raises ActiveRecord::ActiveRecordError do + @connection.create_table(:foos, force: true) do |t| + t.timestamps precision: 7 + end + end end - date = ::Time.utc(2014, 8, 17, 12, 30, 0, 999999) - Foo.create!(created_at: date, updated_at: date) - assert foo = Foo.find_by(created_at: date) - assert_equal 1, Foo.where(updated_at: date).count - assert_equal date.to_s, foo.created_at.to_s - assert_equal date.to_s, foo.updated_at.to_s - assert_equal 000000, foo.created_at.usec - assert_equal 999900, foo.updated_at.usec - end - def test_schema_dump_includes_datetime_precision - @connection.create_table(:foos, force: true) do |t| - t.timestamps precision: 6 + def test_formatting_datetime_according_to_precision + @connection.create_table(:foos, force: true) do |t| + t.datetime :created_at, precision: 0 + t.datetime :updated_at, precision: 4 + end + date = ::Time.utc(2014, 8, 17, 12, 30, 0, 999999) + Foo.create!(created_at: date, updated_at: date) + assert foo = Foo.find_by(created_at: date) + assert_equal 1, Foo.where(updated_at: date).count + assert_equal date.to_s, foo.created_at.to_s + assert_equal date.to_s, foo.updated_at.to_s + assert_equal 000000, foo.created_at.usec + assert_equal 999900, foo.updated_at.usec end - output = dump_table_schema("foos") - assert_match %r{t\.datetime\s+"created_at",\s+precision: 6,\s+null: false$}, output - assert_match %r{t\.datetime\s+"updated_at",\s+precision: 6,\s+null: false$}, output - end - if current_adapter?(:PostgreSQLAdapter) - def test_datetime_precision_with_zero_should_be_dumped + def test_schema_dump_includes_datetime_precision @connection.create_table(:foos, force: true) do |t| - t.timestamps precision: 0 + t.timestamps precision: 6 end output = dump_table_schema("foos") - assert_match %r{t\.datetime\s+"created_at",\s+precision: 0,\s+null: false$}, output - assert_match %r{t\.datetime\s+"updated_at",\s+precision: 0,\s+null: false$}, output + assert_match %r{t\.datetime\s+"created_at",\s+precision: 6,\s+null: false$}, output + assert_match %r{t\.datetime\s+"updated_at",\s+precision: 6,\s+null: false$}, output end - end -end + if current_adapter?(:PostgreSQLAdapter) + def test_datetime_precision_with_zero_should_be_dumped + @connection.create_table(:foos, force: true) do |t| + t.timestamps precision: 0 + end + output = dump_table_schema("foos") + assert_match %r{t\.datetime\s+"created_at",\s+precision: 0,\s+null: false$}, output + assert_match %r{t\.datetime\s+"updated_at",\s+precision: 0,\s+null: false$}, output + end + end + + end end diff --git a/activerecord/test/cases/finder_respond_to_test.rb b/activerecord/test/cases/finder_respond_to_test.rb index 1b3d6a71b2..6e772c9d8a 100644 --- a/activerecord/test/cases/finder_respond_to_test.rb +++ b/activerecord/test/cases/finder_respond_to_test.rb @@ -54,7 +54,7 @@ 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.include? method_id - end + def ensure_topic_method_is_not_cached(method_id) + 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 b3745d9dec..3855bf4420 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -853,7 +853,7 @@ class FinderTest < ActiveRecord::TestCase Company.where(["id=? AND name = ?", 2]).first } assert_raise(ActiveRecord::PreparedStatementInvalid) { - Company.where(["id=?", 2, 3, 4]).first + Company.where(["id=?", 2, 3, 4]).first } end diff --git a/activerecord/test/cases/fixture_set/file_test.rb b/activerecord/test/cases/fixture_set/file_test.rb index 45b770ab8c..e69c9f303a 100644 --- a/activerecord/test/cases/fixture_set/file_test.rb +++ b/activerecord/test/cases/fixture_set/file_test.rb @@ -142,15 +142,15 @@ END end private - def tmp_yaml(name, contents) - t = Tempfile.new name - t.binmode - t.write contents - t.close - yield t - ensure - t.close true - end + def tmp_yaml(name, contents) + t = Tempfile.new name + t.binmode + t.write contents + t.close + yield t + ensure + t.close true + end end end end diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 16b8a19dc4..ebd4437a87 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -188,17 +188,17 @@ end module InTimeZone private - def in_time_zone(zone) - old_zone = Time.zone - old_tz = ActiveRecord::Base.time_zone_aware_attributes - - Time.zone = zone ? ActiveSupport::TimeZone[zone] : nil - ActiveRecord::Base.time_zone_aware_attributes = !zone.nil? - yield - ensure - Time.zone = old_zone - ActiveRecord::Base.time_zone_aware_attributes = old_tz - end + def in_time_zone(zone) + old_zone = Time.zone + old_tz = ActiveRecord::Base.time_zone_aware_attributes + + Time.zone = zone ? ActiveSupport::TimeZone[zone] : nil + ActiveRecord::Base.time_zone_aware_attributes = !zone.nil? + yield + ensure + Time.zone = old_zone + ActiveRecord::Base.time_zone_aware_attributes = old_tz + end end require "mocha/setup" # FIXME: stop using mocha diff --git a/activerecord/test/cases/hot_compatibility_test.rb b/activerecord/test/cases/hot_compatibility_test.rb index 42e7235fba..e0946544ef 100644 --- a/activerecord/test/cases/hot_compatibility_test.rb +++ b/activerecord/test/cases/hot_compatibility_test.rb @@ -114,29 +114,29 @@ class HotCompatibilityTest < ActiveRecord::TestCase private - def get_prepared_statement_cache(connection) - connection.instance_variable_get(:@statements) - .instance_variable_get(:@cache)[Process.pid] - end + def get_prepared_statement_cache(connection) + connection.instance_variable_get(:@statements) + .instance_variable_get(:@cache)[Process.pid] + end # Rails will automatically clear the prepared statements on the connection # that runs the migration, so we use two connections to simulate what would # actually happen on a production system; we'd have one connection running the # migration from the rake task ("ddl_connection" here), and we'd have another # connection in a web worker. - def with_two_connections - run_without_connection do |original_connection| - ActiveRecord::Base.establish_connection(original_connection.merge(pool_size: 2)) - begin - ddl_connection = ActiveRecord::Base.connection_pool.checkout + def with_two_connections + run_without_connection do |original_connection| + ActiveRecord::Base.establish_connection(original_connection.merge(pool_size: 2)) begin - yield original_connection, ddl_connection + ddl_connection = ActiveRecord::Base.connection_pool.checkout + begin + yield original_connection, ddl_connection + ensure + ActiveRecord::Base.connection_pool.checkin ddl_connection + end ensure - ActiveRecord::Base.connection_pool.checkin ddl_connection + ActiveRecord::Base.clear_all_connections! end - ensure - ActiveRecord::Base.clear_all_connections! end end - end end diff --git a/activerecord/test/cases/invalid_connection_test.rb b/activerecord/test/cases/invalid_connection_test.rb index 04fb4ed24e..1367af2859 100644 --- a/activerecord/test/cases/invalid_connection_test.rb +++ b/activerecord/test/cases/invalid_connection_test.rb @@ -1,24 +1,24 @@ require "cases/helper" if current_adapter?(:Mysql2Adapter) -class TestAdapterWithInvalidConnection < ActiveRecord::TestCase - self.use_transactional_tests = false + class TestAdapterWithInvalidConnection < ActiveRecord::TestCase + self.use_transactional_tests = false - class Bird < ActiveRecord::Base - end + class Bird < ActiveRecord::Base + end - def setup - # Can't just use current adapter; sqlite3 will create a database - # file on the fly. - Bird.establish_connection adapter: "mysql2", database: "i_do_not_exist" - end + def setup + # Can't just use current adapter; sqlite3 will create a database + # file on the fly. + Bird.establish_connection adapter: "mysql2", database: "i_do_not_exist" + end - teardown do - Bird.remove_connection - end + teardown do + Bird.remove_connection + end - test "inspect on Model class does not raise" do - assert_equal "#{Bird.name} (call '#{Bird.name}.connection' to establish a connection)", Bird.inspect + test "inspect on Model class does not raise" do + assert_equal "#{Bird.name} (call '#{Bird.name}.connection' to establish a connection)", Bird.inspect + end end end -end diff --git a/activerecord/test/cases/json_serialization_test.rb b/activerecord/test/cases/json_serialization_test.rb index 7f407f84da..814d3b63b2 100644 --- a/activerecord/test/cases/json_serialization_test.rb +++ b/activerecord/test/cases/json_serialization_test.rb @@ -9,13 +9,13 @@ require "models/comment" module JsonSerializationHelpers private - def set_include_root_in_json(value) - original_root_in_json = ActiveRecord::Base.include_root_in_json - ActiveRecord::Base.include_root_in_json = value - yield - ensure - ActiveRecord::Base.include_root_in_json = original_root_in_json - end + def set_include_root_in_json(value) + original_root_in_json = ActiveRecord::Base.include_root_in_json + ActiveRecord::Base.include_root_in_json = value + yield + ensure + ActiveRecord::Base.include_root_in_json = original_root_in_json + end end class JsonSerializationTest < ActiveRecord::TestCase @@ -275,7 +275,7 @@ class DatabaseConnectedJsonEncodingTest < ActiveRecord::TestCase ['"name":"David"', '"posts":[', '{"id":1}', '{"id":2}', '{"id":4}', '{"id":5}', '{"id":6}', '"name":"Mary"', '"posts":[', '{"id":7}', '{"id":9}'].each do |fragment| - assert json.include?(fragment), json + assert json.include?(fragment), json end end diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index f5c9945b37..84f252d5d1 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -461,33 +461,33 @@ unless in_memory_db? end protected - def duel(zzz = 5) - t0, t1, t2, t3 = nil, nil, nil, nil - - a = Thread.new do - t0 = Time.now - Person.transaction do - yield - sleep zzz # block thread 2 for zzz seconds - end - t1 = Time.now - end + def duel(zzz = 5) + t0, t1, t2, t3 = nil, nil, nil, nil - b = Thread.new do - sleep zzz / 2.0 # ensure thread 1 tx starts first - t2 = Time.now - Person.transaction { yield } - t3 = Time.now + a = Thread.new do + t0 = Time.now + Person.transaction do + yield + sleep zzz # block thread 2 for zzz seconds end + t1 = Time.now + end - a.join - b.join - - assert t1 > t0 + zzz - assert t2 > t0 - assert t3 > t2 - [t0.to_f..t1.to_f, t2.to_f..t3.to_f] + b = Thread.new do + sleep zzz / 2.0 # ensure thread 1 tx starts first + t2 = Time.now + Person.transaction { yield } + t3 = Time.now end + + a.join + b.join + + assert t1 > t0 + zzz + assert t2 > t0 + assert t3 > t2 + [t0.to_f..t1.to_f, t2.to_f..t3.to_f] + end end end end diff --git a/activerecord/test/cases/migration/change_schema_test.rb b/activerecord/test/cases/migration/change_schema_test.rb index 7f6364bc57..0191c9d03b 100644 --- a/activerecord/test/cases/migration/change_schema_test.rb +++ b/activerecord/test/cases/migration/change_schema_test.rb @@ -415,13 +415,13 @@ module ActiveRecord end private - def testing_table_with_only_foo_attribute - connection.create_table :testings, id: false do |t| - t.column :foo, :string - end + def testing_table_with_only_foo_attribute + connection.create_table :testings, id: false do |t| + t.column :foo, :string + end - yield - end + yield + end end if ActiveRecord::Base.connection.supports_foreign_keys? diff --git a/activerecord/test/cases/migration/columns_test.rb b/activerecord/test/cases/migration/columns_test.rb index 95c3f51539..baf0a0eb9f 100644 --- a/activerecord/test/cases/migration/columns_test.rb +++ b/activerecord/test/cases/migration/columns_test.rb @@ -74,7 +74,7 @@ module ActiveRecord def test_rename_nonexistent_column exception = if current_adapter?(:PostgreSQLAdapter, :OracleAdapter) - ActiveRecord::StatementInvalid + ActiveRecord::StatementInvalid else ActiveRecord::ActiveRecordError end diff --git a/activerecord/test/cases/migration/foreign_key_test.rb b/activerecord/test/cases/migration/foreign_key_test.rb index b47df24b13..a9a3885e32 100644 --- a/activerecord/test/cases/migration/foreign_key_test.rb +++ b/activerecord/test/cases/migration/foreign_key_test.rb @@ -3,315 +3,315 @@ require "support/ddl_helper" require "support/schema_dumping_helper" if ActiveRecord::Base.connection.supports_foreign_keys? -module ActiveRecord - class Migration - class ForeignKeyTest < ActiveRecord::TestCase - include DdlHelper - include SchemaDumpingHelper - include ActiveSupport::Testing::Stream - - class Rocket < ActiveRecord::Base - end - - class Astronaut < ActiveRecord::Base - end - - setup do - @connection = ActiveRecord::Base.connection - @connection.create_table "rockets", force: true do |t| - t.string :name + module ActiveRecord + class Migration + class ForeignKeyTest < ActiveRecord::TestCase + include DdlHelper + include SchemaDumpingHelper + include ActiveSupport::Testing::Stream + + class Rocket < ActiveRecord::Base end - @connection.create_table "astronauts", force: true do |t| - t.string :name - t.references :rocket + class Astronaut < ActiveRecord::Base end - end - teardown do - if defined?(@connection) - @connection.drop_table "astronauts", if_exists: true - @connection.drop_table "rockets", if_exists: true - end - end - - def test_foreign_keys - foreign_keys = @connection.foreign_keys("fk_test_has_fk") - assert_equal 1, foreign_keys.size + setup do + @connection = ActiveRecord::Base.connection + @connection.create_table "rockets", force: true do |t| + t.string :name + end - fk = foreign_keys.first - assert_equal "fk_test_has_fk", fk.from_table - assert_equal "fk_test_has_pk", fk.to_table - assert_equal "fk_id", fk.column - assert_equal "pk_id", fk.primary_key - assert_equal "fk_name", fk.name - end + @connection.create_table "astronauts", force: true do |t| + t.string :name + t.references :rocket + end + end - def test_add_foreign_key_inferes_column - @connection.add_foreign_key :astronauts, :rockets + teardown do + if defined?(@connection) + @connection.drop_table "astronauts", if_exists: true + @connection.drop_table "rockets", if_exists: true + end + end - foreign_keys = @connection.foreign_keys("astronauts") - assert_equal 1, foreign_keys.size + def test_foreign_keys + foreign_keys = @connection.foreign_keys("fk_test_has_fk") + assert_equal 1, foreign_keys.size - fk = foreign_keys.first - assert_equal "astronauts", fk.from_table - assert_equal "rockets", fk.to_table - assert_equal "rocket_id", fk.column - assert_equal "id", fk.primary_key - assert_equal("fk_rails_78146ddd2e", fk.name) - end + fk = foreign_keys.first + assert_equal "fk_test_has_fk", fk.from_table + assert_equal "fk_test_has_pk", fk.to_table + assert_equal "fk_id", fk.column + assert_equal "pk_id", fk.primary_key + assert_equal "fk_name", fk.name + end - def test_add_foreign_key_with_column - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id" + def test_add_foreign_key_inferes_column + @connection.add_foreign_key :astronauts, :rockets - foreign_keys = @connection.foreign_keys("astronauts") - assert_equal 1, foreign_keys.size + foreign_keys = @connection.foreign_keys("astronauts") + assert_equal 1, foreign_keys.size - fk = foreign_keys.first - assert_equal "astronauts", fk.from_table - assert_equal "rockets", fk.to_table - assert_equal "rocket_id", fk.column - assert_equal "id", fk.primary_key - assert_equal("fk_rails_78146ddd2e", fk.name) - end + fk = foreign_keys.first + assert_equal "astronauts", fk.from_table + assert_equal "rockets", fk.to_table + assert_equal "rocket_id", fk.column + assert_equal "id", fk.primary_key + assert_equal("fk_rails_78146ddd2e", fk.name) + end - def test_add_foreign_key_with_non_standard_primary_key - with_example_table @connection, "space_shuttles", "pk integer PRIMARY KEY" do - @connection.add_foreign_key(:astronauts, :space_shuttles, - column: "rocket_id", primary_key: "pk", name: "custom_pk") + def test_add_foreign_key_with_column + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id" foreign_keys = @connection.foreign_keys("astronauts") assert_equal 1, foreign_keys.size fk = foreign_keys.first assert_equal "astronauts", fk.from_table - assert_equal "space_shuttles", fk.to_table - assert_equal "pk", fk.primary_key - - @connection.remove_foreign_key :astronauts, name: "custom_pk" + assert_equal "rockets", fk.to_table + assert_equal "rocket_id", fk.column + assert_equal "id", fk.primary_key + assert_equal("fk_rails_78146ddd2e", fk.name) end - end - def test_add_on_delete_restrict_foreign_key - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :restrict + def test_add_foreign_key_with_non_standard_primary_key + with_example_table @connection, "space_shuttles", "pk integer PRIMARY KEY" do + @connection.add_foreign_key(:astronauts, :space_shuttles, + column: "rocket_id", primary_key: "pk", name: "custom_pk") + + foreign_keys = @connection.foreign_keys("astronauts") + assert_equal 1, foreign_keys.size - foreign_keys = @connection.foreign_keys("astronauts") - assert_equal 1, foreign_keys.size + fk = foreign_keys.first + assert_equal "astronauts", fk.from_table + assert_equal "space_shuttles", fk.to_table + assert_equal "pk", fk.primary_key - fk = foreign_keys.first - if current_adapter?(:Mysql2Adapter) - # ON DELETE RESTRICT is the default on MySQL - assert_equal nil, fk.on_delete - else - assert_equal :restrict, fk.on_delete + @connection.remove_foreign_key :astronauts, name: "custom_pk" + end end - end - def test_add_on_delete_cascade_foreign_key - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :cascade + def test_add_on_delete_restrict_foreign_key + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :restrict - foreign_keys = @connection.foreign_keys("astronauts") - assert_equal 1, foreign_keys.size + foreign_keys = @connection.foreign_keys("astronauts") + assert_equal 1, foreign_keys.size - fk = foreign_keys.first - assert_equal :cascade, fk.on_delete - end + fk = foreign_keys.first + if current_adapter?(:Mysql2Adapter) + # ON DELETE RESTRICT is the default on MySQL + assert_equal nil, fk.on_delete + else + assert_equal :restrict, fk.on_delete + end + end - def test_add_on_delete_nullify_foreign_key - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :nullify + def test_add_on_delete_cascade_foreign_key + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :cascade - foreign_keys = @connection.foreign_keys("astronauts") - assert_equal 1, foreign_keys.size + foreign_keys = @connection.foreign_keys("astronauts") + assert_equal 1, foreign_keys.size - fk = foreign_keys.first - assert_equal :nullify, fk.on_delete - end + fk = foreign_keys.first + assert_equal :cascade, fk.on_delete + end + + def test_add_on_delete_nullify_foreign_key + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :nullify + + foreign_keys = @connection.foreign_keys("astronauts") + assert_equal 1, foreign_keys.size - def test_on_update_and_on_delete_raises_with_invalid_values - assert_raises ArgumentError do - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :invalid + fk = foreign_keys.first + assert_equal :nullify, fk.on_delete end - assert_raises ArgumentError do - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_update: :invalid + def test_on_update_and_on_delete_raises_with_invalid_values + assert_raises ArgumentError do + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :invalid + end + + assert_raises ArgumentError do + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_update: :invalid + end end - end - def test_add_foreign_key_with_on_update - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_update: :nullify + def test_add_foreign_key_with_on_update + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_update: :nullify + + foreign_keys = @connection.foreign_keys("astronauts") + assert_equal 1, foreign_keys.size - foreign_keys = @connection.foreign_keys("astronauts") - assert_equal 1, foreign_keys.size + fk = foreign_keys.first + assert_equal :nullify, fk.on_update + end - fk = foreign_keys.first - assert_equal :nullify, fk.on_update - end + def test_foreign_key_exists + @connection.add_foreign_key :astronauts, :rockets - def test_foreign_key_exists - @connection.add_foreign_key :astronauts, :rockets + assert @connection.foreign_key_exists?(:astronauts, :rockets) + assert_not @connection.foreign_key_exists?(:astronauts, :stars) + end - assert @connection.foreign_key_exists?(:astronauts, :rockets) - assert_not @connection.foreign_key_exists?(:astronauts, :stars) - end + def test_foreign_key_exists_by_column + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id" - def test_foreign_key_exists_by_column - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id" + assert @connection.foreign_key_exists?(:astronauts, column: "rocket_id") + assert_not @connection.foreign_key_exists?(:astronauts, column: "star_id") + end - assert @connection.foreign_key_exists?(:astronauts, column: "rocket_id") - assert_not @connection.foreign_key_exists?(:astronauts, column: "star_id") - end + def test_foreign_key_exists_by_name + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk" - def test_foreign_key_exists_by_name - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk" + assert @connection.foreign_key_exists?(:astronauts, name: "fancy_named_fk") + assert_not @connection.foreign_key_exists?(:astronauts, name: "other_fancy_named_fk") + end - assert @connection.foreign_key_exists?(:astronauts, name: "fancy_named_fk") - assert_not @connection.foreign_key_exists?(:astronauts, name: "other_fancy_named_fk") - end + def test_remove_foreign_key_inferes_column + @connection.add_foreign_key :astronauts, :rockets - def test_remove_foreign_key_inferes_column - @connection.add_foreign_key :astronauts, :rockets + assert_equal 1, @connection.foreign_keys("astronauts").size + @connection.remove_foreign_key :astronauts, :rockets + assert_equal [], @connection.foreign_keys("astronauts") + end - assert_equal 1, @connection.foreign_keys("astronauts").size - @connection.remove_foreign_key :astronauts, :rockets - assert_equal [], @connection.foreign_keys("astronauts") - end + def test_remove_foreign_key_by_column + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id" - def test_remove_foreign_key_by_column - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id" + assert_equal 1, @connection.foreign_keys("astronauts").size + @connection.remove_foreign_key :astronauts, column: "rocket_id" + assert_equal [], @connection.foreign_keys("astronauts") + end - assert_equal 1, @connection.foreign_keys("astronauts").size - @connection.remove_foreign_key :astronauts, column: "rocket_id" - assert_equal [], @connection.foreign_keys("astronauts") - end + def test_remove_foreign_key_by_symbol_column + @connection.add_foreign_key :astronauts, :rockets, column: :rocket_id - def test_remove_foreign_key_by_symbol_column - @connection.add_foreign_key :astronauts, :rockets, column: :rocket_id + assert_equal 1, @connection.foreign_keys("astronauts").size + @connection.remove_foreign_key :astronauts, column: :rocket_id + assert_equal [], @connection.foreign_keys("astronauts") + end - assert_equal 1, @connection.foreign_keys("astronauts").size - @connection.remove_foreign_key :astronauts, column: :rocket_id - assert_equal [], @connection.foreign_keys("astronauts") - end + def test_remove_foreign_key_by_name + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk" - def test_remove_foreign_key_by_name - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk" + assert_equal 1, @connection.foreign_keys("astronauts").size + @connection.remove_foreign_key :astronauts, name: "fancy_named_fk" + assert_equal [], @connection.foreign_keys("astronauts") + end - assert_equal 1, @connection.foreign_keys("astronauts").size - @connection.remove_foreign_key :astronauts, name: "fancy_named_fk" - assert_equal [], @connection.foreign_keys("astronauts") - end + def test_remove_foreign_non_existing_foreign_key_raises + assert_raises ArgumentError do + @connection.remove_foreign_key :astronauts, :rockets + end + end - def test_remove_foreign_non_existing_foreign_key_raises - assert_raises ArgumentError do - @connection.remove_foreign_key :astronauts, :rockets + def test_schema_dumping + @connection.add_foreign_key :astronauts, :rockets + output = dump_table_schema "astronauts" + assert_match %r{\s+add_foreign_key "astronauts", "rockets"$}, output end - end - def test_schema_dumping - @connection.add_foreign_key :astronauts, :rockets - output = dump_table_schema "astronauts" - assert_match %r{\s+add_foreign_key "astronauts", "rockets"$}, output - end + def test_schema_dumping_with_options + output = dump_table_schema "fk_test_has_fk" + assert_match %r{\s+add_foreign_key "fk_test_has_fk", "fk_test_has_pk", column: "fk_id", primary_key: "pk_id", name: "fk_name"$}, output + end - def test_schema_dumping_with_options - output = dump_table_schema "fk_test_has_fk" - assert_match %r{\s+add_foreign_key "fk_test_has_fk", "fk_test_has_pk", column: "fk_id", primary_key: "pk_id", name: "fk_name"$}, output - end + def test_schema_dumping_on_delete_and_on_update_options + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :nullify, on_update: :cascade - def test_schema_dumping_on_delete_and_on_update_options - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :nullify, on_update: :cascade + output = dump_table_schema "astronauts" + assert_match %r{\s+add_foreign_key "astronauts",.+on_update: :cascade,.+on_delete: :nullify$}, output + end - output = dump_table_schema "astronauts" - assert_match %r{\s+add_foreign_key "astronauts",.+on_update: :cascade,.+on_delete: :nullify$}, output - end + class CreateCitiesAndHousesMigration < ActiveRecord::Migration::Current + def change + create_table("cities") { |t| } - class CreateCitiesAndHousesMigration < ActiveRecord::Migration::Current - def change - create_table("cities") { |t| } + create_table("houses") do |t| + t.column :city_id, :integer + end + add_foreign_key :houses, :cities, column: "city_id" - create_table("houses") do |t| - t.column :city_id, :integer + # remove and re-add to test that schema is updated and not accidentally cached + remove_foreign_key :houses, :cities + add_foreign_key :houses, :cities, column: "city_id", on_delete: :cascade end - add_foreign_key :houses, :cities, column: "city_id" - - # remove and re-add to test that schema is updated and not accidentally cached - remove_foreign_key :houses, :cities - add_foreign_key :houses, :cities, column: "city_id", on_delete: :cascade end - end - def test_add_foreign_key_is_reversible - migration = CreateCitiesAndHousesMigration.new - silence_stream($stdout) { migration.migrate(:up) } - assert_equal 1, @connection.foreign_keys("houses").size - ensure - silence_stream($stdout) { migration.migrate(:down) } - end + def test_add_foreign_key_is_reversible + migration = CreateCitiesAndHousesMigration.new + silence_stream($stdout) { migration.migrate(:up) } + assert_equal 1, @connection.foreign_keys("houses").size + ensure + silence_stream($stdout) { migration.migrate(:down) } + end - def test_foreign_key_constraint_is_not_cached_incorrectly - migration = CreateCitiesAndHousesMigration.new - silence_stream($stdout) { migration.migrate(:up) } - output = dump_table_schema "houses" - assert_match %r{\s+add_foreign_key "houses",.+on_delete: :cascade$}, output - ensure - silence_stream($stdout) { migration.migrate(:down) } - end + def test_foreign_key_constraint_is_not_cached_incorrectly + migration = CreateCitiesAndHousesMigration.new + silence_stream($stdout) { migration.migrate(:up) } + output = dump_table_schema "houses" + assert_match %r{\s+add_foreign_key "houses",.+on_delete: :cascade$}, output + ensure + silence_stream($stdout) { migration.migrate(:down) } + end - class CreateSchoolsAndClassesMigration < ActiveRecord::Migration::Current - def change - create_table(:schools) + class CreateSchoolsAndClassesMigration < ActiveRecord::Migration::Current + def change + create_table(:schools) - create_table(:classes) do |t| - t.column :school_id, :integer + create_table(:classes) do |t| + t.column :school_id, :integer + end + add_foreign_key :classes, :schools end - add_foreign_key :classes, :schools end - end - def test_add_foreign_key_with_prefix - ActiveRecord::Base.table_name_prefix = "p_" - migration = CreateSchoolsAndClassesMigration.new - silence_stream($stdout) { migration.migrate(:up) } - assert_equal 1, @connection.foreign_keys("p_classes").size - ensure - silence_stream($stdout) { migration.migrate(:down) } - ActiveRecord::Base.table_name_prefix = nil - end + def test_add_foreign_key_with_prefix + ActiveRecord::Base.table_name_prefix = "p_" + migration = CreateSchoolsAndClassesMigration.new + silence_stream($stdout) { migration.migrate(:up) } + assert_equal 1, @connection.foreign_keys("p_classes").size + ensure + silence_stream($stdout) { migration.migrate(:down) } + ActiveRecord::Base.table_name_prefix = nil + end - def test_add_foreign_key_with_suffix - ActiveRecord::Base.table_name_suffix = "_s" - migration = CreateSchoolsAndClassesMigration.new - silence_stream($stdout) { migration.migrate(:up) } - assert_equal 1, @connection.foreign_keys("classes_s").size - ensure - silence_stream($stdout) { migration.migrate(:down) } - ActiveRecord::Base.table_name_suffix = nil - end + def test_add_foreign_key_with_suffix + ActiveRecord::Base.table_name_suffix = "_s" + migration = CreateSchoolsAndClassesMigration.new + silence_stream($stdout) { migration.migrate(:up) } + assert_equal 1, @connection.foreign_keys("classes_s").size + ensure + silence_stream($stdout) { migration.migrate(:down) } + ActiveRecord::Base.table_name_suffix = nil + end + end end end -end else -module ActiveRecord - class Migration - class NoForeignKeySupportTest < ActiveRecord::TestCase - setup do - @connection = ActiveRecord::Base.connection - end + module ActiveRecord + class Migration + class NoForeignKeySupportTest < ActiveRecord::TestCase + setup do + @connection = ActiveRecord::Base.connection + end - def test_add_foreign_key_should_be_noop - @connection.add_foreign_key :clubs, :categories - end + def test_add_foreign_key_should_be_noop + @connection.add_foreign_key :clubs, :categories + end - def test_remove_foreign_key_should_be_noop - @connection.remove_foreign_key :clubs, :categories - end + def test_remove_foreign_key_should_be_noop + @connection.remove_foreign_key :clubs, :categories + end - def test_foreign_keys_should_raise_not_implemented - assert_raises NotImplementedError do - @connection.foreign_keys("clubs") + def test_foreign_keys_should_raise_not_implemented + assert_raises NotImplementedError do + @connection.foreign_keys("clubs") + end end end end end end -end diff --git a/activerecord/test/cases/migration/helper.rb b/activerecord/test/cases/migration/helper.rb index ad85684c0b..9c0fa7339d 100644 --- a/activerecord/test/cases/migration/helper.rb +++ b/activerecord/test/cases/migration/helper.rb @@ -33,7 +33,7 @@ module ActiveRecord private - delegate(*CONNECTION_METHODS, to: :connection) + delegate(*CONNECTION_METHODS, to: :connection) end end end diff --git a/activerecord/test/cases/migration/references_foreign_key_test.rb b/activerecord/test/cases/migration/references_foreign_key_test.rb index 992d003e7e..8436435170 100644 --- a/activerecord/test/cases/migration/references_foreign_key_test.rb +++ b/activerecord/test/cases/migration/references_foreign_key_test.rb @@ -1,216 +1,216 @@ require "cases/helper" if ActiveRecord::Base.connection.supports_foreign_keys? -module ActiveRecord - class Migration - class ReferencesForeignKeyTest < ActiveRecord::TestCase - setup do - @connection = ActiveRecord::Base.connection - @connection.create_table(:testing_parents, force: true) - end - - teardown do - @connection.drop_table "testings", if_exists: true - @connection.drop_table "testing_parents", if_exists: true - end + module ActiveRecord + class Migration + class ReferencesForeignKeyTest < ActiveRecord::TestCase + setup do + @connection = ActiveRecord::Base.connection + @connection.create_table(:testing_parents, force: true) + end - test "foreign keys can be created with the table" do - @connection.create_table :testings do |t| - t.references :testing_parent, foreign_key: true + teardown do + @connection.drop_table "testings", if_exists: true + @connection.drop_table "testing_parents", if_exists: true end - fk = @connection.foreign_keys("testings").first - assert_equal "testings", fk.from_table - assert_equal "testing_parents", fk.to_table - end + test "foreign keys can be created with the table" do + @connection.create_table :testings do |t| + t.references :testing_parent, foreign_key: true + end - test "no foreign key is created by default" do - @connection.create_table :testings do |t| - t.references :testing_parent + fk = @connection.foreign_keys("testings").first + assert_equal "testings", fk.from_table + assert_equal "testing_parents", fk.to_table end - assert_equal [], @connection.foreign_keys("testings") - end - - test "foreign keys can be created in one query when index is not added" do - assert_queries(1) do + test "no foreign key is created by default" do @connection.create_table :testings do |t| - t.references :testing_parent, foreign_key: true, index: false + t.references :testing_parent end - end - end - test "options hash can be passed" do - @connection.change_table :testing_parents do |t| - t.integer :other_id - t.index :other_id, unique: true + assert_equal [], @connection.foreign_keys("testings") end - @connection.create_table :testings do |t| - t.references :testing_parent, foreign_key: { primary_key: :other_id } + + test "foreign keys can be created in one query when index is not added" do + assert_queries(1) do + @connection.create_table :testings do |t| + t.references :testing_parent, foreign_key: true, index: false + end + end end - fk = @connection.foreign_keys("testings").find { |k| k.to_table == "testing_parents" } - assert_equal "other_id", fk.primary_key - end + test "options hash can be passed" do + @connection.change_table :testing_parents do |t| + t.integer :other_id + t.index :other_id, unique: true + end + @connection.create_table :testings do |t| + t.references :testing_parent, foreign_key: { primary_key: :other_id } + end - test "to_table option can be passed" do - @connection.create_table :testings do |t| - t.references :parent, foreign_key: { to_table: :testing_parents } + fk = @connection.foreign_keys("testings").find { |k| k.to_table == "testing_parents" } + assert_equal "other_id", fk.primary_key end - fks = @connection.foreign_keys("testings") - assert_equal([["testings", "testing_parents", "parent_id"]], - fks.map {|fk| [fk.from_table, fk.to_table, fk.column] }) - end - test "foreign keys cannot be added to polymorphic relations when creating the table" do - @connection.create_table :testings do |t| - assert_raises(ArgumentError) do - t.references :testing_parent, polymorphic: true, foreign_key: true + test "to_table option can be passed" do + @connection.create_table :testings do |t| + t.references :parent, foreign_key: { to_table: :testing_parents } end + fks = @connection.foreign_keys("testings") + assert_equal([["testings", "testing_parents", "parent_id"]], + fks.map {|fk| [fk.from_table, fk.to_table, fk.column] }) end - end - test "foreign keys can be created while changing the table" do - @connection.create_table :testings - @connection.change_table :testings do |t| - t.references :testing_parent, foreign_key: true + test "foreign keys cannot be added to polymorphic relations when creating the table" do + @connection.create_table :testings do |t| + assert_raises(ArgumentError) do + t.references :testing_parent, polymorphic: true, foreign_key: true + end + end end - fk = @connection.foreign_keys("testings").first - assert_equal "testings", fk.from_table - assert_equal "testing_parents", fk.to_table - end + test "foreign keys can be created while changing the table" do + @connection.create_table :testings + @connection.change_table :testings do |t| + t.references :testing_parent, foreign_key: true + end - test "foreign keys are not added by default when changing the table" do - @connection.create_table :testings - @connection.change_table :testings do |t| - t.references :testing_parent + fk = @connection.foreign_keys("testings").first + assert_equal "testings", fk.from_table + assert_equal "testing_parents", fk.to_table end - assert_equal [], @connection.foreign_keys("testings") - end + test "foreign keys are not added by default when changing the table" do + @connection.create_table :testings + @connection.change_table :testings do |t| + t.references :testing_parent + end - test "foreign keys accept options when changing the table" do - @connection.change_table :testing_parents do |t| - t.integer :other_id - t.index :other_id, unique: true - end - @connection.create_table :testings - @connection.change_table :testings do |t| - t.references :testing_parent, foreign_key: { primary_key: :other_id } + assert_equal [], @connection.foreign_keys("testings") end - fk = @connection.foreign_keys("testings").find { |k| k.to_table == "testing_parents" } - assert_equal "other_id", fk.primary_key - end - - test "foreign keys cannot be added to polymorphic relations when changing the table" do - @connection.create_table :testings - @connection.change_table :testings do |t| - assert_raises(ArgumentError) do - t.references :testing_parent, polymorphic: true, foreign_key: true + test "foreign keys accept options when changing the table" do + @connection.change_table :testing_parents do |t| + t.integer :other_id + t.index :other_id, unique: true + end + @connection.create_table :testings + @connection.change_table :testings do |t| + t.references :testing_parent, foreign_key: { primary_key: :other_id } end - end - end - test "foreign key column can be removed" do - @connection.create_table :testings do |t| - t.references :testing_parent, index: true, foreign_key: true + fk = @connection.foreign_keys("testings").find { |k| k.to_table == "testing_parents" } + assert_equal "other_id", fk.primary_key end - assert_difference "@connection.foreign_keys('testings').size", -1 do - @connection.remove_reference :testings, :testing_parent, foreign_key: true + test "foreign keys cannot be added to polymorphic relations when changing the table" do + @connection.create_table :testings + @connection.change_table :testings do |t| + assert_raises(ArgumentError) do + t.references :testing_parent, polymorphic: true, foreign_key: true + end + end end - end - test "foreign key methods respect pluralize_table_names" do - begin - original_pluralize_table_names = ActiveRecord::Base.pluralize_table_names - ActiveRecord::Base.pluralize_table_names = false - @connection.create_table :testing - @connection.change_table :testing_parents do |t| - t.references :testing, foreign_key: true + test "foreign key column can be removed" do + @connection.create_table :testings do |t| + t.references :testing_parent, index: true, foreign_key: true end - fk = @connection.foreign_keys("testing_parents").first - assert_equal "testing_parents", fk.from_table - assert_equal "testing", fk.to_table + assert_difference "@connection.foreign_keys('testings').size", -1 do + @connection.remove_reference :testings, :testing_parent, foreign_key: true + end + end - assert_difference "@connection.foreign_keys('testing_parents').size", -1 do - @connection.remove_reference :testing_parents, :testing, foreign_key: true + test "foreign key methods respect pluralize_table_names" do + begin + original_pluralize_table_names = ActiveRecord::Base.pluralize_table_names + ActiveRecord::Base.pluralize_table_names = false + @connection.create_table :testing + @connection.change_table :testing_parents do |t| + t.references :testing, foreign_key: true + end + + fk = @connection.foreign_keys("testing_parents").first + assert_equal "testing_parents", fk.from_table + assert_equal "testing", fk.to_table + + assert_difference "@connection.foreign_keys('testing_parents').size", -1 do + @connection.remove_reference :testing_parents, :testing, foreign_key: true + end + ensure + ActiveRecord::Base.pluralize_table_names = original_pluralize_table_names + @connection.drop_table "testing", if_exists: true end - ensure - ActiveRecord::Base.pluralize_table_names = original_pluralize_table_names - @connection.drop_table "testing", if_exists: true end - end - class CreateDogsMigration < ActiveRecord::Migration::Current - def change - create_table :dog_owners + class CreateDogsMigration < ActiveRecord::Migration::Current + def change + create_table :dog_owners - create_table :dogs do |t| - t.references :dog_owner, foreign_key: true + create_table :dogs do |t| + t.references :dog_owner, foreign_key: true + end end end - end - def test_references_foreign_key_with_prefix - ActiveRecord::Base.table_name_prefix = "p_" - migration = CreateDogsMigration.new - silence_stream($stdout) { migration.migrate(:up) } - assert_equal 1, @connection.foreign_keys("p_dogs").size - ensure - silence_stream($stdout) { migration.migrate(:down) } - ActiveRecord::Base.table_name_prefix = nil - end + def test_references_foreign_key_with_prefix + ActiveRecord::Base.table_name_prefix = "p_" + migration = CreateDogsMigration.new + silence_stream($stdout) { migration.migrate(:up) } + assert_equal 1, @connection.foreign_keys("p_dogs").size + ensure + silence_stream($stdout) { migration.migrate(:down) } + ActiveRecord::Base.table_name_prefix = nil + end - def test_references_foreign_key_with_suffix - ActiveRecord::Base.table_name_suffix = "_s" - migration = CreateDogsMigration.new - silence_stream($stdout) { migration.migrate(:up) } - assert_equal 1, @connection.foreign_keys("dogs_s").size - ensure - silence_stream($stdout) { migration.migrate(:down) } - ActiveRecord::Base.table_name_suffix = nil - end + def test_references_foreign_key_with_suffix + ActiveRecord::Base.table_name_suffix = "_s" + migration = CreateDogsMigration.new + silence_stream($stdout) { migration.migrate(:up) } + assert_equal 1, @connection.foreign_keys("dogs_s").size + ensure + silence_stream($stdout) { migration.migrate(:down) } + ActiveRecord::Base.table_name_suffix = nil + end - test "multiple foreign keys can be added to the same table" do - @connection.create_table :testings do |t| - t.integer :col_1 - t.integer :col_2 + test "multiple foreign keys can be added to the same table" do + @connection.create_table :testings do |t| + t.integer :col_1 + t.integer :col_2 - t.foreign_key :testing_parents, column: :col_1 - t.foreign_key :testing_parents, column: :col_2 - end + t.foreign_key :testing_parents, column: :col_1 + t.foreign_key :testing_parents, column: :col_2 + end - fks = @connection.foreign_keys("testings") + fks = @connection.foreign_keys("testings") - fk_definitions = fks.map {|fk| [fk.from_table, fk.to_table, fk.column] } - assert_equal([["testings", "testing_parents", "col_1"], - ["testings", "testing_parents", "col_2"]], fk_definitions) + fk_definitions = fks.map {|fk| [fk.from_table, fk.to_table, fk.column] } + assert_equal([["testings", "testing_parents", "col_1"], + ["testings", "testing_parents", "col_2"]], fk_definitions) + end end end end -end else -class ReferencesWithoutForeignKeySupportTest < ActiveRecord::TestCase - setup do - @connection = ActiveRecord::Base.connection - @connection.create_table(:testing_parents, force: true) - end - - teardown do - @connection.drop_table("testings", if_exists: true) - @connection.drop_table("testing_parents", if_exists: true) - end + class ReferencesWithoutForeignKeySupportTest < ActiveRecord::TestCase + setup do + @connection = ActiveRecord::Base.connection + @connection.create_table(:testing_parents, force: true) + end - test "ignores foreign keys defined with the table" do - @connection.create_table :testings do |t| - t.references :testing_parent, foreign_key: true + teardown do + @connection.drop_table("testings", if_exists: true) + @connection.drop_table("testing_parents", if_exists: true) end - assert_includes @connection.data_sources, "testings" + test "ignores foreign keys defined with the table" do + @connection.create_table :testings do |t| + t.references :testing_parent, foreign_key: true + end + + assert_includes @connection.data_sources, "testings" + end end end -end diff --git a/activerecord/test/cases/migration/references_statements_test.rb b/activerecord/test/cases/migration/references_statements_test.rb index 8d0acaaa6e..8fbe60f24e 100644 --- a/activerecord/test/cases/migration/references_statements_test.rb +++ b/activerecord/test/cases/migration/references_statements_test.rb @@ -110,12 +110,12 @@ module ActiveRecord private - def with_polymorphic_column - add_column table_name, :supplier_type, :string - add_index table_name, [:supplier_id, :supplier_type] + def with_polymorphic_column + add_column table_name, :supplier_type, :string + add_index table_name, [:supplier_id, :supplier_type] - yield - end + yield + end end end end diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index d3d6931ea4..b8ffc8a154 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -873,30 +873,30 @@ if ActiveRecord::Base.connection.supports_bulk_alter? protected - def with_bulk_change_table - # Reset columns/indexes cache as we're changing the table - @columns = @indexes = nil + def with_bulk_change_table + # Reset columns/indexes cache as we're changing the table + @columns = @indexes = nil - Person.connection.change_table(:delete_me, bulk: true) do |t| - yield t + Person.connection.change_table(:delete_me, bulk: true) do |t| + yield t + end end - end - def column(name) - columns.detect {|c| c.name == name.to_s } - end + def column(name) + columns.detect {|c| c.name == name.to_s } + end - def columns - @columns ||= Person.connection.columns("delete_me") - end + def columns + @columns ||= Person.connection.columns("delete_me") + end - def index(name) - indexes.detect {|i| i.name == name.to_s } - end + def index(name) + indexes.detect {|i| i.name == name.to_s } + end - def indexes - @indexes ||= Person.connection.indexes("delete_me") - end + def indexes + @indexes ||= Person.connection.indexes("delete_me") + end end # AlterTableMigrationsTest end diff --git a/activerecord/test/cases/migrator_test.rb b/activerecord/test/cases/migrator_test.rb index 67af04e2e8..a44bf08095 100644 --- a/activerecord/test/cases/migrator_test.rb +++ b/activerecord/test/cases/migrator_test.rb @@ -92,8 +92,8 @@ class MigratorTest < ActiveRecord::TestCase [20100101010101, "ValidWithTimestampsPeopleHaveLastNames"], [20100201010101, "ValidWithTimestampsWeNeedReminders"], [20100301010101, "ValidWithTimestampsInnocentJointable"]].each_with_index do |pair, i| - assert_equal pair.first, migrations[i].version - assert_equal pair.last, migrations[i].name + assert_equal pair.first, migrations[i].version + assert_equal pair.last, migrations[i].name end end @@ -357,32 +357,32 @@ class MigratorTest < ActiveRecord::TestCase end private - def m(name, version) - x = Sensor.new name, version - x.extend(Module.new { - define_method(:up) { yield(:up, x); super() } - define_method(:down) { yield(:down, x); super() } - }) if block_given? - end + def m(name, version) + x = Sensor.new name, version + x.extend(Module.new { + define_method(:up) { yield(:up, x); super() } + define_method(:down) { yield(:down, x); super() } + }) if block_given? + end - def sensors(count) - calls = [] - migrations = count.times.map { |i| - m(nil, i + 1) { |c,migration| - calls << [c, migration.version] + def sensors(count) + calls = [] + migrations = count.times.map { |i| + m(nil, i + 1) { |c,migration| + calls << [c, migration.version] + } } - } - [calls, migrations] - end + [calls, migrations] + end - def migrator_class(count) - calls, migrations = sensors(count) + def migrator_class(count) + calls, migrations = sensors(count) - migrator = Class.new(ActiveRecord::Migrator).extend(Module.new { - define_method(:migrations) { |paths| - migrations - } - }) - [calls, migrator] - end + migrator = Class.new(ActiveRecord::Migrator).extend(Module.new { + define_method(:migrations) { |paths| + migrations + } + }) + [calls, migrator] + end end diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index d3923173a7..fc47c42ed1 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -839,13 +839,13 @@ module NestedAttributesOnACollectionAssociationTests private - def association_setter - @association_setter ||= "#{@association_name}_attributes=".to_sym - end + def association_setter + @association_setter ||= "#{@association_name}_attributes=".to_sym + end - def association_getter - @association_getter ||= "#{@association_name}_attributes".to_sym - end + def association_getter + @association_getter ||= "#{@association_name}_attributes".to_sym + end end class TestNestedAttributesOnAHasManyAssociation < ActiveRecord::TestCase diff --git a/activerecord/test/cases/nested_attributes_with_callbacks_test.rb b/activerecord/test/cases/nested_attributes_with_callbacks_test.rb index d41b7c2213..d606a6c12d 100644 --- a/activerecord/test/cases/nested_attributes_with_callbacks_test.rb +++ b/activerecord/test/cases/nested_attributes_with_callbacks_test.rb @@ -46,7 +46,7 @@ class NestedAttributesWithCallbacksTest < ActiveRecord::TestCase end def new_bird_attributes - [{"name" => "New Bird"}] + [{"name" => "New Bird"}] end def destroy_bird_attributes diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index f200770562..f1b0d08765 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -75,7 +75,7 @@ class PooledConnectionsTest < ActiveRecord::TestCase private - def add_record(name) - ActiveRecord::Base.connection_pool.with_connection { Project.create! name: name } - end + def add_record(name) + ActiveRecord::Base.connection_pool.with_connection { Project.create! name: name } + end end unless in_memory_db? diff --git a/activerecord/test/cases/relation/delegation_test.rb b/activerecord/test/cases/relation/delegation_test.rb index fbae212e65..d2382b9bb2 100644 --- a/activerecord/test/cases/relation/delegation_test.rb +++ b/activerecord/test/cases/relation/delegation_test.rb @@ -18,7 +18,7 @@ module ActiveRecord target.public_send(method, 1) end elsif method_arity == 1 - target.public_send(method, 1) + target.public_send(method, 1) else raise NotImplementedError end diff --git a/activerecord/test/cases/relation/where_clause_test.rb b/activerecord/test/cases/relation/where_clause_test.rb index 2e2bb9fe36..d8e4c304f0 100644 --- a/activerecord/test/cases/relation/where_clause_test.rb +++ b/activerecord/test/cases/relation/where_clause_test.rb @@ -167,16 +167,16 @@ class ActiveRecord::Relation private - def table - Arel::Table.new("table") - end + def table + Arel::Table.new("table") + end - def bind_param - Arel::Nodes::BindParam.new - end + def bind_param + Arel::Nodes::BindParam.new + end - def attribute(name, value) - ActiveRecord::Attribute.with_cast_value(name, value, ActiveRecord::Type::Value.new) - end + def attribute(name, value) + ActiveRecord::Attribute.with_cast_value(name, value, ActiveRecord::Type::Value.new) + end end end diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb index 99f739c6c9..0802afac5a 100644 --- a/activerecord/test/cases/relation_test.rb +++ b/activerecord/test/cases/relation_test.rb @@ -306,23 +306,23 @@ module ActiveRecord private - def skip_if_sqlite3_version_includes_quoting_bug - if sqlite3_version_includes_quoting_bug? - skip <<-ERROR.squish + def skip_if_sqlite3_version_includes_quoting_bug + if sqlite3_version_includes_quoting_bug? + skip <<-ERROR.squish You are using an outdated version of SQLite3 which has a bug in quoted column names. Please update SQLite3 and rebuild the sqlite3 ruby gem ERROR + end end - end - def sqlite3_version_includes_quoting_bug? - if current_adapter?(:SQLite3Adapter) - selected_quoted_column_names = ActiveRecord::Base.connection.exec_query( - 'SELECT "join" FROM (SELECT id AS "join" FROM posts) subquery' - ).columns - ["join"] != selected_quoted_column_names + def sqlite3_version_includes_quoting_bug? + if current_adapter?(:SQLite3Adapter) + selected_quoted_column_names = ActiveRecord::Base.connection.exec_query( + 'SELECT "join" FROM (SELECT id AS "join" FROM posts) subquery' + ).columns + ["join"] != selected_quoted_column_names + end end - end end end diff --git a/activerecord/test/cases/tasks/mysql_rake_test.rb b/activerecord/test/cases/tasks/mysql_rake_test.rb index be2f2e5939..dbe935808e 100644 --- a/activerecord/test/cases/tasks/mysql_rake_test.rb +++ b/activerecord/test/cases/tasks/mysql_rake_test.rb @@ -2,344 +2,344 @@ require "cases/helper" require "active_record/tasks/database_tasks" if current_adapter?(:Mysql2Adapter) -module ActiveRecord - class MysqlDBCreateTest < ActiveRecord::TestCase - def setup - @connection = stub(create_database: true) - @configuration = { - "adapter" => "mysql2", - "database" => "my-app-db" - } - - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - - $stdout, @original_stdout = StringIO.new, $stdout - $stderr, @original_stderr = StringIO.new, $stderr - end - - def teardown - $stdout, $stderr = @original_stdout, @original_stderr - end - - def test_establishes_connection_without_database - ActiveRecord::Base.expects(:establish_connection). - with("adapter" => "mysql2", "database" => nil) - - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end - - def test_creates_database_with_no_default_options - @connection.expects(:create_database). - with("my-app-db", {}) + module ActiveRecord + class MysqlDBCreateTest < ActiveRecord::TestCase + def setup + @connection = stub(create_database: true) + @configuration = { + "adapter" => "mysql2", + "database" => "my-app-db" + } - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) - def test_creates_database_with_given_encoding - @connection.expects(:create_database). - with("my-app-db", charset: "latin1") + $stdout, @original_stdout = StringIO.new, $stdout + $stderr, @original_stderr = StringIO.new, $stderr + end - ActiveRecord::Tasks::DatabaseTasks.create @configuration.merge("encoding" => "latin1") - end + def teardown + $stdout, $stderr = @original_stdout, @original_stderr + end - def test_creates_database_with_given_collation - @connection.expects(:create_database). - with("my-app-db", collation: "latin1_swedish_ci") + def test_establishes_connection_without_database + ActiveRecord::Base.expects(:establish_connection). + with("adapter" => "mysql2", "database" => nil) - ActiveRecord::Tasks::DatabaseTasks.create @configuration.merge("collation" => "latin1_swedish_ci") - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - def test_establishes_connection_to_database - ActiveRecord::Base.expects(:establish_connection).with(@configuration) + def test_creates_database_with_no_default_options + @connection.expects(:create_database). + with("my-app-db", {}) - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - def test_when_database_created_successfully_outputs_info_to_stdout - ActiveRecord::Tasks::DatabaseTasks.create @configuration + def test_creates_database_with_given_encoding + @connection.expects(:create_database). + with("my-app-db", charset: "latin1") - assert_equal $stdout.string, "Created database 'my-app-db'\n" - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration.merge("encoding" => "latin1") + end - def test_create_when_database_exists_outputs_info_to_stderr - ActiveRecord::Base.connection.stubs(:create_database).raises( - ActiveRecord::Tasks::DatabaseAlreadyExists - ) + def test_creates_database_with_given_collation + @connection.expects(:create_database). + with("my-app-db", collation: "latin1_swedish_ci") - ActiveRecord::Tasks::DatabaseTasks.create @configuration + ActiveRecord::Tasks::DatabaseTasks.create @configuration.merge("collation" => "latin1_swedish_ci") + end - assert_equal $stderr.string, "Database 'my-app-db' already exists\n" - end - end + def test_establishes_connection_to_database + ActiveRecord::Base.expects(:establish_connection).with(@configuration) - class MysqlDBCreateAsRootTest < ActiveRecord::TestCase - def setup - @connection = stub("Connection", create_database: true) - @error = Mysql2::Error.new("Invalid permissions") - @configuration = { - "adapter" => "mysql2", - "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) - - $stdout, @original_stdout = StringIO.new, $stdout - $stderr, @original_stderr = StringIO.new, $stderr - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - def teardown - $stdout, $stderr = @original_stdout, @original_stderr - end + def test_when_database_created_successfully_outputs_info_to_stdout + ActiveRecord::Tasks::DatabaseTasks.create @configuration - def test_root_password_is_requested - assert_permissions_granted_for("pat") - $stdin.expects(:gets).returns("secret\n") + assert_equal $stdout.string, "Created database 'my-app-db'\n" + end - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + def test_create_when_database_exists_outputs_info_to_stderr + ActiveRecord::Base.connection.stubs(:create_database).raises( + ActiveRecord::Tasks::DatabaseAlreadyExists + ) - def test_connection_established_as_root - assert_permissions_granted_for("pat") - ActiveRecord::Base.expects(:establish_connection).with( - "adapter" => "mysql2", - "database" => nil, - "username" => "root", - "password" => "secret" - ) + ActiveRecord::Tasks::DatabaseTasks.create @configuration - ActiveRecord::Tasks::DatabaseTasks.create @configuration + assert_equal $stderr.string, "Database 'my-app-db' already exists\n" + end end - def test_database_created_by_root - assert_permissions_granted_for("pat") - @connection.expects(:create_database). - with("my-app-db", {}) + class MysqlDBCreateAsRootTest < ActiveRecord::TestCase + def setup + @connection = stub("Connection", create_database: true) + @error = Mysql2::Error.new("Invalid permissions") + @configuration = { + "adapter" => "mysql2", + "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) + + $stdout, @original_stdout = StringIO.new, $stdout + $stderr, @original_stderr = StringIO.new, $stderr + end - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + def teardown + $stdout, $stderr = @original_stdout, @original_stderr + end - def test_grant_privileges_for_normal_user - assert_permissions_granted_for("pat") - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + def test_root_password_is_requested + assert_permissions_granted_for("pat") + $stdin.expects(:gets).returns("secret\n") - def test_do_not_grant_privileges_for_root_user - @configuration["username"] = "root" - @configuration["password"] = "" - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - def test_connection_established_as_normal_user - assert_permissions_granted_for("pat") - ActiveRecord::Base.expects(:establish_connection).returns do + def test_connection_established_as_root + assert_permissions_granted_for("pat") ActiveRecord::Base.expects(:establish_connection).with( "adapter" => "mysql2", - "database" => "my-app-db", - "username" => "pat", + "database" => nil, + "username" => "root", "password" => "secret" ) - raise @error + ActiveRecord::Tasks::DatabaseTasks.create @configuration end - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + def test_database_created_by_root + assert_permissions_granted_for("pat") + @connection.expects(:create_database). + with("my-app-db", {}) - def test_sends_output_to_stderr_when_other_errors - @error.stubs(:errno).returns(42) + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - $stderr.expects(:puts).at_least_once.returns(nil) + def test_grant_privileges_for_normal_user + assert_permissions_granted_for("pat") + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + def test_do_not_grant_privileges_for_root_user + @configuration["username"] = "root" + @configuration["password"] = "" + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - private + def test_connection_established_as_normal_user + assert_permissions_granted_for("pat") + ActiveRecord::Base.expects(:establish_connection).returns do + ActiveRecord::Base.expects(:establish_connection).with( + "adapter" => "mysql2", + "database" => "my-app-db", + "username" => "pat", + "password" => "secret" + ) - def assert_permissions_granted_for(db_user) - db_name = @configuration["database"] - db_password = @configuration["password"] - @connection.expects(:execute).with("GRANT ALL PRIVILEGES ON #{db_name}.* TO '#{db_user}'@'localhost' IDENTIFIED BY '#{db_password}' WITH GRANT OPTION;") - end - end + raise @error + end - class MySQLDBDropTest < ActiveRecord::TestCase - def setup - @connection = stub(drop_database: true) - @configuration = { - "adapter" => "mysql2", - "database" => "my-app-db" - } + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) + def test_sends_output_to_stderr_when_other_errors + @error.stubs(:errno).returns(42) - $stdout, @original_stdout = StringIO.new, $stdout - $stderr, @original_stderr = StringIO.new, $stderr - end + $stderr.expects(:puts).at_least_once.returns(nil) - def teardown - $stdout, $stderr = @original_stdout, @original_stderr - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - def test_establishes_connection_to_mysql_database - ActiveRecord::Base.expects(:establish_connection).with @configuration + private - ActiveRecord::Tasks::DatabaseTasks.drop @configuration + def assert_permissions_granted_for(db_user) + db_name = @configuration["database"] + db_password = @configuration["password"] + @connection.expects(:execute).with("GRANT ALL PRIVILEGES ON #{db_name}.* TO '#{db_user}'@'localhost' IDENTIFIED BY '#{db_password}' WITH GRANT OPTION;") + end end - def test_drops_database - @connection.expects(:drop_database).with("my-app-db") + class MySQLDBDropTest < ActiveRecord::TestCase + def setup + @connection = stub(drop_database: true) + @configuration = { + "adapter" => "mysql2", + "database" => "my-app-db" + } - ActiveRecord::Tasks::DatabaseTasks.drop @configuration - end + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) - def test_when_database_dropped_successfully_outputs_info_to_stdout - ActiveRecord::Tasks::DatabaseTasks.drop @configuration + $stdout, @original_stdout = StringIO.new, $stdout + $stderr, @original_stderr = StringIO.new, $stderr + end - assert_equal $stdout.string, "Dropped database 'my-app-db'\n" - end - end + def teardown + $stdout, $stderr = @original_stdout, @original_stderr + end - class MySQLPurgeTest < ActiveRecord::TestCase - def setup - @connection = stub(recreate_database: true) - @configuration = { - "adapter" => "mysql2", - "database" => "test-db" - } + def test_establishes_connection_to_mysql_database + ActiveRecord::Base.expects(:establish_connection).with @configuration - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - end + ActiveRecord::Tasks::DatabaseTasks.drop @configuration + end - def test_establishes_connection_to_the_appropriate_database - ActiveRecord::Base.expects(:establish_connection).with(@configuration) + def test_drops_database + @connection.expects(:drop_database).with("my-app-db") - ActiveRecord::Tasks::DatabaseTasks.purge @configuration - end + ActiveRecord::Tasks::DatabaseTasks.drop @configuration + end - def test_recreates_database_with_no_default_options - @connection.expects(:recreate_database). - with("test-db", {}) + def test_when_database_dropped_successfully_outputs_info_to_stdout + ActiveRecord::Tasks::DatabaseTasks.drop @configuration - ActiveRecord::Tasks::DatabaseTasks.purge @configuration + assert_equal $stdout.string, "Dropped database 'my-app-db'\n" + end end - def test_recreates_database_with_the_given_options - @connection.expects(:recreate_database). - with("test-db", charset: "latin", collation: "latin1_swedish_ci") + class MySQLPurgeTest < ActiveRecord::TestCase + def setup + @connection = stub(recreate_database: true) + @configuration = { + "adapter" => "mysql2", + "database" => "test-db" + } - ActiveRecord::Tasks::DatabaseTasks.purge @configuration.merge( - "encoding" => "latin", "collation" => "latin1_swedish_ci") - end - end + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end - class MysqlDBCharsetTest < ActiveRecord::TestCase - def setup - @connection = stub(create_database: true) - @configuration = { - "adapter" => "mysql2", - "database" => "my-app-db" - } + def test_establishes_connection_to_the_appropriate_database + ActiveRecord::Base.expects(:establish_connection).with(@configuration) - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - end + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end - def test_db_retrieves_charset - @connection.expects(:charset) - ActiveRecord::Tasks::DatabaseTasks.charset @configuration - end - end + def test_recreates_database_with_no_default_options + @connection.expects(:recreate_database). + with("test-db", {}) - class MysqlDBCollationTest < ActiveRecord::TestCase - def setup - @connection = stub(create_database: true) - @configuration = { - "adapter" => "mysql2", - "database" => "my-app-db" - } + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - end + def test_recreates_database_with_the_given_options + @connection.expects(:recreate_database). + with("test-db", charset: "latin", collation: "latin1_swedish_ci") - def test_db_retrieves_collation - @connection.expects(:collation) - ActiveRecord::Tasks::DatabaseTasks.collation @configuration + ActiveRecord::Tasks::DatabaseTasks.purge @configuration.merge( + "encoding" => "latin", "collation" => "latin1_swedish_ci") + end end - end - class MySQLStructureDumpTest < ActiveRecord::TestCase - def setup - @configuration = { - "adapter" => "mysql2", - "database" => "test-db" - } + class MysqlDBCharsetTest < ActiveRecord::TestCase + def setup + @connection = stub(create_database: true) + @configuration = { + "adapter" => "mysql2", + "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 - def test_structure_dump - filename = "awesome-file.sql" - Kernel.expects(:system).with("mysqldump", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db").returns(true) + class MysqlDBCollationTest < ActiveRecord::TestCase + def setup + @connection = stub(create_database: true) + @configuration = { + "adapter" => "mysql2", + "database" => "my-app-db" + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end - ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename) + def test_db_retrieves_collation + @connection.expects(:collation) + ActiveRecord::Tasks::DatabaseTasks.collation @configuration + end end - def test_warn_when_external_structure_dump_command_execution_fails - filename = "awesome-file.sql" - Kernel.expects(:system) - .with("mysqldump", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db") - .returns(false) + class MySQLStructureDumpTest < ActiveRecord::TestCase + def setup + @configuration = { + "adapter" => "mysql2", + "database" => "test-db" + } + end + + def test_structure_dump + filename = "awesome-file.sql" + Kernel.expects(:system).with("mysqldump", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db").returns(true) - e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename) - } - assert_match(/^failed to execute: `mysqldump`$/, e.message) - end + end - def test_structure_dump_with_port_number - filename = "awesome-file.sql" - Kernel.expects(:system).with("mysqldump", "--port=10000", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db").returns(true) + def test_warn_when_external_structure_dump_command_execution_fails + filename = "awesome-file.sql" + Kernel.expects(:system) + .with("mysqldump", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db") + .returns(false) - ActiveRecord::Tasks::DatabaseTasks.structure_dump( - @configuration.merge("port" => 10000), - filename) - end + e = assert_raise(RuntimeError) { + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename) + } + assert_match(/^failed to execute: `mysqldump`$/, e.message) + end - def test_structure_dump_with_ssl - filename = "awesome-file.sql" - Kernel.expects(:system).with("mysqldump", "--ssl-ca=ca.crt", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db").returns(true) + def test_structure_dump_with_port_number + filename = "awesome-file.sql" + Kernel.expects(:system).with("mysqldump", "--port=10000", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db").returns(true) - ActiveRecord::Tasks::DatabaseTasks.structure_dump( - @configuration.merge("sslca" => "ca.crt"), - filename) - end - end + ActiveRecord::Tasks::DatabaseTasks.structure_dump( + @configuration.merge("port" => 10000), + filename) + end + + def test_structure_dump_with_ssl + filename = "awesome-file.sql" + Kernel.expects(:system).with("mysqldump", "--ssl-ca=ca.crt", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db").returns(true) - class MySQLStructureLoadTest < ActiveRecord::TestCase - def setup - @configuration = { - "adapter" => "mysql2", - "database" => "test-db" - } + ActiveRecord::Tasks::DatabaseTasks.structure_dump( + @configuration.merge("sslca" => "ca.crt"), + filename) + end end - def test_structure_load - filename = "awesome-file.sql" - Kernel.expects(:system).with("mysql", "--execute", %{SET FOREIGN_KEY_CHECKS = 0; SOURCE #{filename}; SET FOREIGN_KEY_CHECKS = 1}, "--database", "test-db") - .returns(true) + class MySQLStructureLoadTest < ActiveRecord::TestCase + def setup + @configuration = { + "adapter" => "mysql2", + "database" => "test-db" + } + end + + def test_structure_load + filename = "awesome-file.sql" + Kernel.expects(:system).with("mysql", "--execute", %{SET FOREIGN_KEY_CHECKS = 0; SOURCE #{filename}; SET FOREIGN_KEY_CHECKS = 1}, "--database", "test-db") + .returns(true) - ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) + ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) + end end end end -end diff --git a/activerecord/test/cases/tasks/postgresql_rake_test.rb b/activerecord/test/cases/tasks/postgresql_rake_test.rb index fdfe4e979f..b8c8ec88f0 100644 --- a/activerecord/test/cases/tasks/postgresql_rake_test.rb +++ b/activerecord/test/cases/tasks/postgresql_rake_test.rb @@ -2,303 +2,303 @@ require "cases/helper" require "active_record/tasks/database_tasks" if current_adapter?(:PostgreSQLAdapter) -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) - - $stdout, @original_stdout = StringIO.new, $stdout - $stderr, @original_stderr = StringIO.new, $stderr - end + 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) + + $stdout, @original_stdout = StringIO.new, $stdout + $stderr, @original_stderr = StringIO.new, $stderr + end - def teardown - $stdout, $stderr = @original_stdout, @original_stderr - end + def teardown + $stdout, $stderr = @original_stdout, @original_stderr + end - def test_establishes_connection_to_postgresql_database - ActiveRecord::Base.expects(:establish_connection).with( - "adapter" => "postgresql", - "database" => "postgres", - "schema_search_path" => "public" - ) + 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 + 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")) + 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 + 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")) + 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 + ActiveRecord::Tasks::DatabaseTasks.create @configuration. + merge("encoding" => "latin") + end - def test_creates_database_with_given_collation_and_ctype - @connection.expects(:create_database). - with("my-app-db", @configuration.merge("encoding" => "utf8", "collation" => "ja_JP.UTF8", "ctype" => "ja_JP.UTF8")) + def test_creates_database_with_given_collation_and_ctype + @connection.expects(:create_database). + with("my-app-db", @configuration.merge("encoding" => "utf8", "collation" => "ja_JP.UTF8", "ctype" => "ja_JP.UTF8")) - ActiveRecord::Tasks::DatabaseTasks.create @configuration. - merge("collation" => "ja_JP.UTF8", "ctype" => "ja_JP.UTF8") - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration. + merge("collation" => "ja_JP.UTF8", "ctype" => "ja_JP.UTF8") + end - def test_establishes_connection_to_new_database - ActiveRecord::Base.expects(:establish_connection).with(@configuration) + def test_establishes_connection_to_new_database + ActiveRecord::Base.expects(:establish_connection).with(@configuration) - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - def test_db_create_with_error_prints_message - ActiveRecord::Base.stubs(:establish_connection).raises(Exception) + 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}") + $stderr.stubs(:puts).returns(true) + $stderr.expects(:puts). + with("Couldn't create database for #{@configuration.inspect}") - assert_raises(Exception) { ActiveRecord::Tasks::DatabaseTasks.create @configuration } - end + assert_raises(Exception) { ActiveRecord::Tasks::DatabaseTasks.create @configuration } + end - def test_when_database_created_successfully_outputs_info_to_stdout - ActiveRecord::Tasks::DatabaseTasks.create @configuration + def test_when_database_created_successfully_outputs_info_to_stdout + ActiveRecord::Tasks::DatabaseTasks.create @configuration - assert_equal $stdout.string, "Created database 'my-app-db'\n" - end + assert_equal $stdout.string, "Created database 'my-app-db'\n" + end - def test_create_when_database_exists_outputs_info_to_stderr - ActiveRecord::Base.connection.stubs(:create_database).raises( - ActiveRecord::Tasks::DatabaseAlreadyExists - ) + def test_create_when_database_exists_outputs_info_to_stderr + ActiveRecord::Base.connection.stubs(:create_database).raises( + ActiveRecord::Tasks::DatabaseAlreadyExists + ) - ActiveRecord::Tasks::DatabaseTasks.create @configuration + ActiveRecord::Tasks::DatabaseTasks.create @configuration - assert_equal $stderr.string, "Database 'my-app-db' already exists\n" + assert_equal $stderr.string, "Database 'my-app-db' already exists\n" + end end - end - class PostgreSQLDBDropTest < ActiveRecord::TestCase - def setup - @connection = stub(drop_database: true) - @configuration = { - "adapter" => "postgresql", - "database" => "my-app-db" - } + 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) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) - $stdout, @original_stdout = StringIO.new, $stdout - $stderr, @original_stderr = StringIO.new, $stderr - end + $stdout, @original_stdout = StringIO.new, $stdout + $stderr, @original_stderr = StringIO.new, $stderr + end - def teardown - $stdout, $stderr = @original_stdout, @original_stderr - end + def teardown + $stdout, $stderr = @original_stdout, @original_stderr + end - def test_establishes_connection_to_postgresql_database - ActiveRecord::Base.expects(:establish_connection).with( - "adapter" => "postgresql", - "database" => "postgres", - "schema_search_path" => "public" - ) + 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 + ActiveRecord::Tasks::DatabaseTasks.drop @configuration + end - def test_drops_database - @connection.expects(:drop_database).with("my-app-db") + def test_drops_database + @connection.expects(:drop_database).with("my-app-db") - ActiveRecord::Tasks::DatabaseTasks.drop @configuration - end + ActiveRecord::Tasks::DatabaseTasks.drop @configuration + end - def test_when_database_dropped_successfully_outputs_info_to_stdout - ActiveRecord::Tasks::DatabaseTasks.drop @configuration + def test_when_database_dropped_successfully_outputs_info_to_stdout + ActiveRecord::Tasks::DatabaseTasks.drop @configuration - assert_equal $stdout.string, "Dropped database 'my-app-db'\n" + assert_equal $stdout.string, "Dropped database 'my-app-db'\n" + end 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 + class PostgreSQLPurgeTest < ActiveRecord::TestCase + def setup + @connection = stub(create_database: true, drop_database: true) + @configuration = { + "adapter" => "postgresql", + "database" => "my-app-db" + } - def test_clears_active_connections - ActiveRecord::Base.expects(:clear_active_connections!) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:clear_active_connections!).returns(true) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end - ActiveRecord::Tasks::DatabaseTasks.purge @configuration - 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" - ) + 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 + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end - def test_drops_database - @connection.expects(:drop_database).with("my-app-db") + def test_drops_database + @connection.expects(:drop_database).with("my-app-db") - ActiveRecord::Tasks::DatabaseTasks.purge @configuration - end + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end - def test_creates_database - @connection.expects(:create_database). - with("my-app-db", @configuration.merge("encoding" => "utf8")) + def test_creates_database + @connection.expects(:create_database). + with("my-app-db", @configuration.merge("encoding" => "utf8")) - ActiveRecord::Tasks::DatabaseTasks.purge @configuration - end + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end - def test_establishes_connection - ActiveRecord::Base.expects(:establish_connection).with(@configuration) + def test_establishes_connection + ActiveRecord::Base.expects(:establish_connection).with(@configuration) - ActiveRecord::Tasks::DatabaseTasks.purge @configuration + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end end - end - class PostgreSQLDBCharsetTest < ActiveRecord::TestCase - def setup - @connection = stub(create_database: true) - @configuration = { - "adapter" => "postgresql", - "database" => "my-app-db" - } + 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 + 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 + def test_db_retrieves_charset + @connection.expects(:encoding) + ActiveRecord::Tasks::DatabaseTasks.charset @configuration + end end - end - class PostgreSQLDBCollationTest < ActiveRecord::TestCase - def setup - @connection = stub(create_database: true) - @configuration = { - "adapter" => "postgresql", - "database" => "my-app-db" - } + class PostgreSQLDBCollationTest < 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 + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end - def test_db_retrieves_collation - @connection.expects(:collation) - ActiveRecord::Tasks::DatabaseTasks.collation @configuration + def test_db_retrieves_collation + @connection.expects(:collation) + ActiveRecord::Tasks::DatabaseTasks.collation @configuration + end end - end - class PostgreSQLStructureDumpTest < ActiveRecord::TestCase - def setup - @connection = stub(structure_dump: true) - @configuration = { - "adapter" => "postgresql", - "database" => "my-app-db" - } - @filename = "awesome-file.sql" - - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - Kernel.stubs(:system) - File.stubs(:open) - end + class PostgreSQLStructureDumpTest < ActiveRecord::TestCase + def setup + @connection = stub(structure_dump: true) + @configuration = { + "adapter" => "postgresql", + "database" => "my-app-db" + } + @filename = "awesome-file.sql" - def test_structure_dump - Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "my-app-db").returns(true) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + Kernel.stubs(:system) + File.stubs(:open) + end - ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) - end + def test_structure_dump + Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "my-app-db").returns(true) - def test_structure_dump_with_schema_search_path - @configuration["schema_search_path"] = "foo,bar" + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + end - Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "--schema=foo", "--schema=bar", "my-app-db").returns(true) + def test_structure_dump_with_schema_search_path + @configuration["schema_search_path"] = "foo,bar" - ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) - end + Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "--schema=foo", "--schema=bar", "my-app-db").returns(true) - def test_structure_dump_with_schema_search_path_and_dump_schemas_all - @configuration["schema_search_path"] = "foo,bar" + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + end - Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "my-app-db").returns(true) + def test_structure_dump_with_schema_search_path_and_dump_schemas_all + @configuration["schema_search_path"] = "foo,bar" - with_dump_schemas(:all) do - ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "my-app-db").returns(true) + + with_dump_schemas(:all) do + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + end end - end - def test_structure_dump_with_dump_schemas_string - Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "--schema=foo", "--schema=bar", "my-app-db").returns(true) + def test_structure_dump_with_dump_schemas_string + Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "--schema=foo", "--schema=bar", "my-app-db").returns(true) - with_dump_schemas("foo,bar") do - ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + with_dump_schemas("foo,bar") do + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + end end - end - private + private - def with_dump_schemas(value, &block) - old_dump_schemas = ActiveRecord::Base.dump_schemas - ActiveRecord::Base.dump_schemas = value - yield - ensure - ActiveRecord::Base.dump_schemas = old_dump_schemas + def with_dump_schemas(value, &block) + old_dump_schemas = ActiveRecord::Base.dump_schemas + ActiveRecord::Base.dump_schemas = value + yield + ensure + ActiveRecord::Base.dump_schemas = old_dump_schemas + end 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 + class PostgreSQLStructureLoadTest < ActiveRecord::TestCase + def setup + @connection = stub + @configuration = { + "adapter" => "postgresql", + "database" => "my-app-db" + } - def test_structure_load - filename = "awesome-file.sql" - Kernel.expects(:system).with("psql", "-v", "ON_ERROR_STOP=1", "-q", "-f", filename, @configuration["database"]).returns(true) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + Kernel.stubs(:system) + end - ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) - end + def test_structure_load + filename = "awesome-file.sql" + Kernel.expects(:system).with("psql", "-v", "ON_ERROR_STOP=1", "-q", "-f", filename, @configuration["database"]).returns(true) - def test_structure_load_accepts_path_with_spaces - filename = "awesome file.sql" - Kernel.expects(:system).with("psql", "-v", "ON_ERROR_STOP=1", "-q", "-f", filename, @configuration["database"]).returns(true) + ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) + end + + def test_structure_load_accepts_path_with_spaces + filename = "awesome file.sql" + Kernel.expects(:system).with("psql", "-v", "ON_ERROR_STOP=1", "-q", "-f", filename, @configuration["database"]).returns(true) - ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) + ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) + end end end end -end diff --git a/activerecord/test/cases/tasks/sqlite_rake_test.rb b/activerecord/test/cases/tasks/sqlite_rake_test.rb index 9aeeef1aee..141048bfe7 100644 --- a/activerecord/test/cases/tasks/sqlite_rake_test.rb +++ b/activerecord/test/cases/tasks/sqlite_rake_test.rb @@ -3,218 +3,218 @@ require "active_record/tasks/database_tasks" require "pathname" if current_adapter?(:SQLite3Adapter) -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) - - $stdout, @original_stdout = StringIO.new, $stdout - $stderr, @original_stderr = StringIO.new, $stderr - end + 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) + + $stdout, @original_stdout = StringIO.new, $stdout + $stderr, @original_stderr = StringIO.new, $stderr + end - def teardown - $stdout, $stderr = @original_stdout, @original_stderr - end + def teardown + $stdout, $stderr = @original_stdout, @original_stderr + end - def test_db_checks_database_exists - File.expects(:exist?).with(@database).returns(false) + def test_db_checks_database_exists + File.expects(:exist?).with(@database).returns(false) - ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" + end - def test_when_db_created_successfully_outputs_info_to_stdout - ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" + def test_when_db_created_successfully_outputs_info_to_stdout + ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" - assert_equal $stdout.string, "Created database '#{@database}'\n" - end + assert_equal $stdout.string, "Created database '#{@database}'\n" + end - def test_db_create_when_file_exists - File.stubs(:exist?).returns(true) + def test_db_create_when_file_exists + File.stubs(:exist?).returns(true) - ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" + ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" - assert_equal $stderr.string, "Database '#{@database}' already exists\n" - end + assert_equal $stderr.string, "Database '#{@database}' already exists\n" + end - def test_db_create_with_file_does_nothing - File.stubs(:exist?).returns(true) - $stderr.stubs(:puts).returns(nil) + 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::Base.expects(:establish_connection).never - ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" + end - def test_db_create_establishes_a_connection - ActiveRecord::Base.expects(:establish_connection).with(@configuration) + def test_db_create_establishes_a_connection + ActiveRecord::Base.expects(:establish_connection).with(@configuration) - ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" + end - def test_db_create_with_error_prints_message - ActiveRecord::Base.stubs(:establish_connection).raises(Exception) + 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}") + $stderr.stubs(:puts).returns(true) + $stderr.expects(:puts). + with("Couldn't create database for #{@configuration.inspect}") - assert_raises(Exception) { ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" } + assert_raises(Exception) { ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" } + end 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) - - $stdout, @original_stdout = StringIO.new, $stdout - $stderr, @original_stderr = StringIO.new, $stderr - end + class SqliteDBDropTest < ActiveRecord::TestCase + def setup + @database = "db_create.sqlite3" + @path = stub(to_s: "/absolute/path", absolute?: true) + @configuration = { + "adapter" => "sqlite3", + "database" => @database + } - def teardown - $stdout, $stderr = @original_stdout, @original_stderr - end + Pathname.stubs(:new).returns(@path) + File.stubs(:join).returns("/former/relative/path") + FileUtils.stubs(:rm).returns(true) - def test_creates_path_from_database - Pathname.expects(:new).with(@database).returns(@path) + $stdout, @original_stdout = StringIO.new, $stdout + $stderr, @original_stderr = StringIO.new, $stderr + end - ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" - end + def teardown + $stdout, $stderr = @original_stdout, @original_stderr + end - def test_removes_file_with_absolute_path - File.stubs(:exist?).returns(true) - @path.stubs(:absolute?).returns(true) + def test_creates_path_from_database + Pathname.expects(:new).with(@database).returns(@path) - FileUtils.expects(:rm).with("/absolute/path") + ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" + end - 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) - def test_generates_absolute_path_with_given_root - @path.stubs(:absolute?).returns(false) + FileUtils.expects(:rm).with("/absolute/path") - File.expects(:join).with("/rails/root", @path). - returns("/former/relative/path") + ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" + end - ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" - end + def test_generates_absolute_path_with_given_root + @path.stubs(:absolute?).returns(false) - def test_removes_file_with_relative_path - File.stubs(:exist?).returns(true) - @path.stubs(:absolute?).returns(false) + File.expects(:join).with("/rails/root", @path). + returns("/former/relative/path") - FileUtils.expects(:rm).with("/former/relative/path") + ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" + end - 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) - def test_when_db_dropped_successfully_outputs_info_to_stdout - ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" + FileUtils.expects(:rm).with("/former/relative/path") - assert_equal $stdout.string, "Dropped database '#{@database}'\n" - end - end + ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" + 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_when_db_dropped_successfully_outputs_info_to_stdout + ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" - def test_db_retrieves_charset - @connection.expects(:encoding) - ActiveRecord::Tasks::DatabaseTasks.charset @configuration, "/rails/root" + assert_equal $stdout.string, "Dropped database '#{@database}'\n" + end end - end - class SqliteDBCollationTest < 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 + class SqliteDBCharsetTest < ActiveRecord::TestCase + def setup + @database = "db_create.sqlite3" + @connection = stub :connection + @configuration = { + "adapter" => "sqlite3", + "database" => @database + } - def test_db_retrieves_collation - assert_raise NoMethodError do - ActiveRecord::Tasks::DatabaseTasks.collation @configuration, "/rails/root" + File.stubs(:exist?).returns(false) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) end - end - end - class SqliteStructureDumpTest < ActiveRecord::TestCase - def setup - @database = "db_create.sqlite3" - @configuration = { - "adapter" => "sqlite3", - "database" => @database - } + def test_db_retrieves_charset + @connection.expects(:encoding) + ActiveRecord::Tasks::DatabaseTasks.charset @configuration, "/rails/root" + end end - def test_structure_dump - dbfile = @database - filename = "awesome-file.sql" + class SqliteDBCollationTest < ActiveRecord::TestCase + def setup + @database = "db_create.sqlite3" + @connection = stub :connection + @configuration = { + "adapter" => "sqlite3", + "database" => @database + } - ActiveRecord::Tasks::DatabaseTasks.structure_dump @configuration, filename, "/rails/root" - assert File.exist?(dbfile) - assert File.exist?(filename) - ensure - FileUtils.rm_f(filename) - FileUtils.rm_f(dbfile) + File.stubs(:exist?).returns(false) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_db_retrieves_collation + assert_raise NoMethodError do + ActiveRecord::Tasks::DatabaseTasks.collation @configuration, "/rails/root" + end + end end - end - class SqliteStructureLoadTest < ActiveRecord::TestCase - def setup - @database = "db_create.sqlite3" - @configuration = { - "adapter" => "sqlite3", - "database" => @database - } + 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.exist?(dbfile) + assert File.exist?(filename) + ensure + FileUtils.rm_f(filename) + FileUtils.rm_f(dbfile) + end end - def test_structure_load - dbfile = @database - filename = "awesome-file.sql" + 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.exist?(dbfile) - ensure - FileUtils.rm_f(filename) - FileUtils.rm_f(dbfile) + open(filename, "w") { |f| f.puts("select datetime('now', 'localtime');") } + ActiveRecord::Tasks::DatabaseTasks.structure_load @configuration, filename, "/rails/root" + assert File.exist?(dbfile) + ensure + FileUtils.rm_f(filename) + FileUtils.rm_f(dbfile) + end end end end -end diff --git a/activerecord/test/cases/time_precision_test.rb b/activerecord/test/cases/time_precision_test.rb index c7f6e9c698..4668dc1890 100644 --- a/activerecord/test/cases/time_precision_test.rb +++ b/activerecord/test/cases/time_precision_test.rb @@ -2,83 +2,83 @@ require "cases/helper" require "support/schema_dumping_helper" if subsecond_precision_supported? -class TimePrecisionTest < ActiveRecord::TestCase - include SchemaDumpingHelper - self.use_transactional_tests = false + class TimePrecisionTest < ActiveRecord::TestCase + include SchemaDumpingHelper + self.use_transactional_tests = false - class Foo < ActiveRecord::Base; end + class Foo < ActiveRecord::Base; end - setup do - @connection = ActiveRecord::Base.connection - Foo.reset_column_information - end - - teardown do - @connection.drop_table :foos, if_exists: true - end + setup do + @connection = ActiveRecord::Base.connection + Foo.reset_column_information + end - def test_time_data_type_with_precision - @connection.create_table(:foos, force: true) - @connection.add_column :foos, :start, :time, precision: 3 - @connection.add_column :foos, :finish, :time, precision: 6 - assert_equal 3, Foo.columns_hash["start"].precision - assert_equal 6, Foo.columns_hash["finish"].precision - end + teardown do + @connection.drop_table :foos, if_exists: true + end - def test_passing_precision_to_time_does_not_set_limit - @connection.create_table(:foos, force: true) do |t| - t.time :start, precision: 3 - t.time :finish, precision: 6 + def test_time_data_type_with_precision + @connection.create_table(:foos, force: true) + @connection.add_column :foos, :start, :time, precision: 3 + @connection.add_column :foos, :finish, :time, precision: 6 + assert_equal 3, Foo.columns_hash["start"].precision + assert_equal 6, Foo.columns_hash["finish"].precision end - assert_nil Foo.columns_hash["start"].limit - assert_nil Foo.columns_hash["finish"].limit - end - def test_invalid_time_precision_raises_error - assert_raises ActiveRecord::ActiveRecordError do + def test_passing_precision_to_time_does_not_set_limit @connection.create_table(:foos, force: true) do |t| - t.time :start, precision: 7 - t.time :finish, precision: 7 + t.time :start, precision: 3 + t.time :finish, precision: 6 end + assert_nil Foo.columns_hash["start"].limit + assert_nil Foo.columns_hash["finish"].limit end - end - def test_formatting_time_according_to_precision - @connection.create_table(:foos, force: true) do |t| - t.time :start, precision: 0 - t.time :finish, precision: 4 + def test_invalid_time_precision_raises_error + assert_raises ActiveRecord::ActiveRecordError do + @connection.create_table(:foos, force: true) do |t| + t.time :start, precision: 7 + t.time :finish, precision: 7 + end + end end - time = ::Time.utc(2000, 1, 1, 12, 30, 0, 999999) - Foo.create!(start: time, finish: time) - assert foo = Foo.find_by(start: time) - assert_equal 1, Foo.where(finish: time).count - assert_equal time.to_s, foo.start.to_s - assert_equal time.to_s, foo.finish.to_s - assert_equal 000000, foo.start.usec - assert_equal 999900, foo.finish.usec - end - def test_schema_dump_includes_time_precision - @connection.create_table(:foos, force: true) do |t| - t.time :start, precision: 4 - t.time :finish, precision: 6 + def test_formatting_time_according_to_precision + @connection.create_table(:foos, force: true) do |t| + t.time :start, precision: 0 + t.time :finish, precision: 4 + end + time = ::Time.utc(2000, 1, 1, 12, 30, 0, 999999) + Foo.create!(start: time, finish: time) + assert foo = Foo.find_by(start: time) + assert_equal 1, Foo.where(finish: time).count + assert_equal time.to_s, foo.start.to_s + assert_equal time.to_s, foo.finish.to_s + assert_equal 000000, foo.start.usec + assert_equal 999900, foo.finish.usec end - output = dump_table_schema("foos") - assert_match %r{t\.time\s+"start",\s+precision: 4$}, output - assert_match %r{t\.time\s+"finish",\s+precision: 6$}, output - end - if current_adapter?(:PostgreSQLAdapter) - def test_time_precision_with_zero_should_be_dumped + def test_schema_dump_includes_time_precision @connection.create_table(:foos, force: true) do |t| - t.time :start, precision: 0 - t.time :finish, precision: 0 + t.time :start, precision: 4 + t.time :finish, precision: 6 end output = dump_table_schema("foos") - assert_match %r{t\.time\s+"start",\s+precision: 0$}, output - assert_match %r{t\.time\s+"finish",\s+precision: 0$}, output + assert_match %r{t\.time\s+"start",\s+precision: 4$}, output + assert_match %r{t\.time\s+"finish",\s+precision: 6$}, output end - end -end + if current_adapter?(:PostgreSQLAdapter) + def test_time_precision_with_zero_should_be_dumped + @connection.create_table(:foos, force: true) do |t| + t.time :start, precision: 0 + t.time :finish, precision: 0 + end + output = dump_table_schema("foos") + assert_match %r{t\.time\s+"start",\s+precision: 0$}, output + assert_match %r{t\.time\s+"finish",\s+precision: 0$}, output + end + end + + end end diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index c77cc1a4a6..519d9db601 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -74,12 +74,12 @@ class TimestampTest < ActiveRecord::TestCase end def test_touching_updates_timestamp_with_given_time - previously_updated_at = @developer.updated_at - new_time = Time.utc(2015, 2, 16, 0, 0, 0) - @developer.touch(time: new_time) + previously_updated_at = @developer.updated_at + new_time = Time.utc(2015, 2, 16, 0, 0, 0) + @developer.touch(time: new_time) - assert_not_equal previously_updated_at, @developer.updated_at - assert_equal new_time, @developer.updated_at + assert_not_equal previously_updated_at, @developer.updated_at + assert_equal new_time, @developer.updated_at end def test_touching_an_attribute_updates_timestamp @@ -106,9 +106,9 @@ class TimestampTest < ActiveRecord::TestCase end def test_touching_an_attribute_updates_timestamp_with_given_time - previously_updated_at = @developer.updated_at + previously_updated_at = @developer.updated_at previously_created_at = @developer.created_at - new_time = Time.utc(2015, 2, 16, 4, 54, 0) + new_time = Time.utc(2015, 2, 16, 4, 54, 0) @developer.touch(:created_at, time: new_time) assert_not_equal previously_created_at, @developer.created_at diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index 6dcbc9559c..c8963ada63 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -687,7 +687,7 @@ class TransactionTest < ActiveRecord::TestCase def test_transaction_rollback_with_primarykeyless_tables connection = ActiveRecord::Base.connection connection.create_table(:transaction_without_primary_keys, force: true, id: false) do |t| - t.integer :thing_id + t.integer :thing_id end klass = Class.new(ActiveRecord::Base) do @@ -707,15 +707,15 @@ class TransactionTest < ActiveRecord::TestCase private - %w(validation save destroy).each do |filter| - define_method("add_cancelling_before_#{filter}_with_db_side_effect_to_topic") do |topic| - meta = class << topic; self; end - meta.send("define_method", "before_#{filter}_for_transaction") do - Book.create - throw(:abort) + %w(validation save destroy).each do |filter| + define_method("add_cancelling_before_#{filter}_with_db_side_effect_to_topic") do |topic| + meta = class << topic; self; end + meta.send("define_method", "before_#{filter}_for_transaction") do + Book.create + throw(:abort) + end end end - end end class TransactionsWithTransactionalFixturesTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/type/type_map_test.rb b/activerecord/test/cases/type/type_map_test.rb index 0be173b87d..2959d36466 100644 --- a/activerecord/test/cases/type/type_map_test.rb +++ b/activerecord/test/cases/type/type_map_test.rb @@ -174,4 +174,3 @@ module ActiveRecord end end end - diff --git a/activerecord/test/cases/view_test.rb b/activerecord/test/cases/view_test.rb index f3c2d2f30e..5f85c5ff8b 100644 --- a/activerecord/test/cases/view_test.rb +++ b/activerecord/test/cases/view_test.rb @@ -78,139 +78,139 @@ module ViewBehavior end if ActiveRecord::Base.connection.supports_views? -class ViewWithPrimaryKeyTest < ActiveRecord::TestCase - include ViewBehavior + class ViewWithPrimaryKeyTest < ActiveRecord::TestCase + include ViewBehavior - private - def create_view(name, query) - @connection.execute "CREATE VIEW #{name} AS #{query}" - end + private + def create_view(name, query) + @connection.execute "CREATE VIEW #{name} AS #{query}" + end - def drop_view(name) - @connection.execute "DROP VIEW #{name}" if @connection.view_exists? name + def drop_view(name) + @connection.execute "DROP VIEW #{name}" if @connection.view_exists? name + end end -end -class ViewWithoutPrimaryKeyTest < ActiveRecord::TestCase - include SchemaDumpingHelper - fixtures :books + class ViewWithoutPrimaryKeyTest < ActiveRecord::TestCase + include SchemaDumpingHelper + fixtures :books - class Paperback < ActiveRecord::Base; end + class Paperback < ActiveRecord::Base; end - setup do - @connection = ActiveRecord::Base.connection - @connection.execute <<-SQL + setup do + @connection = ActiveRecord::Base.connection + @connection.execute <<-SQL CREATE VIEW paperbacks AS SELECT name, status FROM books WHERE format = 'paperback' SQL - end + end - teardown do - @connection.execute "DROP VIEW paperbacks" if @connection.view_exists? "paperbacks" - end + teardown do + @connection.execute "DROP VIEW paperbacks" if @connection.view_exists? "paperbacks" + end - def test_reading - books = Paperback.all - assert_equal ["Agile Web Development with Rails"], books.map(&:name) - end + def test_reading + books = Paperback.all + assert_equal ["Agile Web Development with Rails"], books.map(&:name) + end - def test_views - assert_equal [Paperback.table_name], @connection.views - end + def test_views + assert_equal [Paperback.table_name], @connection.views + end - def test_view_exists - view_name = Paperback.table_name - assert @connection.view_exists?(view_name), "'#{view_name}' view should exist" - end + def test_view_exists + view_name = Paperback.table_name + assert @connection.view_exists?(view_name), "'#{view_name}' view should exist" + end - def test_table_exists - view_name = Paperback.table_name - # TODO: switch this assertion around once we changed #tables to not return views. - ActiveSupport::Deprecation.silence { assert @connection.table_exists?(view_name), "'#{view_name}' table should exist" } - end + def test_table_exists + view_name = Paperback.table_name + # TODO: switch this assertion around once we changed #tables to not return views. + ActiveSupport::Deprecation.silence { assert @connection.table_exists?(view_name), "'#{view_name}' table should exist" } + end - def test_column_definitions - assert_equal([["name", :string], - ["status", :integer]], Paperback.columns.map { |c| [c.name, c.type] }) - end + def test_column_definitions + assert_equal([["name", :string], + ["status", :integer]], Paperback.columns.map { |c| [c.name, c.type] }) + end - def test_attributes - assert_equal({"name" => "Agile Web Development with Rails", "status" => 2}, - Paperback.first.attributes) - end + def test_attributes + assert_equal({"name" => "Agile Web Development with Rails", "status" => 2}, + Paperback.first.attributes) + end - def test_does_not_have_a_primary_key - assert_nil Paperback.primary_key - end + def test_does_not_have_a_primary_key + assert_nil Paperback.primary_key + end - def test_does_not_dump_view_as_table - schema = dump_table_schema "paperbacks" - assert_no_match %r{create_table "paperbacks"}, schema + def test_does_not_dump_view_as_table + schema = dump_table_schema "paperbacks" + assert_no_match %r{create_table "paperbacks"}, schema + end end -end # sqlite dose not support CREATE, INSERT, and DELETE for VIEW -if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter) -class UpdateableViewTest < ActiveRecord::TestCase - self.use_transactional_tests = false - fixtures :books - - class PrintedBook < ActiveRecord::Base - self.primary_key = "id" - end - - setup do - @connection = ActiveRecord::Base.connection - @connection.execute <<-SQL + if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter) + class UpdateableViewTest < ActiveRecord::TestCase + self.use_transactional_tests = false + fixtures :books + + class PrintedBook < ActiveRecord::Base + self.primary_key = "id" + end + + setup do + @connection = ActiveRecord::Base.connection + @connection.execute <<-SQL CREATE VIEW printed_books AS SELECT id, name, status, format FROM books WHERE format = 'paperback' SQL - end - - teardown do - @connection.execute "DROP VIEW printed_books" if @connection.view_exists? "printed_books" - end - - def test_update_record - book = PrintedBook.first - book.name = "AWDwR" - book.save! - book.reload - assert_equal "AWDwR", book.name - end - - def test_insert_record - PrintedBook.create! name: "Rails in Action", status: 0, format: "paperback" - - new_book = PrintedBook.last - assert_equal "Rails in Action", new_book.name - end - - def test_update_record_to_fail_view_conditions - book = PrintedBook.first - book.format = "ebook" - book.save! - - assert_raises ActiveRecord::RecordNotFound do - book.reload + end + + teardown do + @connection.execute "DROP VIEW printed_books" if @connection.view_exists? "printed_books" + end + + def test_update_record + book = PrintedBook.first + book.name = "AWDwR" + book.save! + book.reload + assert_equal "AWDwR", book.name + end + + def test_insert_record + PrintedBook.create! name: "Rails in Action", status: 0, format: "paperback" + + new_book = PrintedBook.last + assert_equal "Rails in Action", new_book.name + end + + def test_update_record_to_fail_view_conditions + book = PrintedBook.first + book.format = "ebook" + book.save! + + assert_raises ActiveRecord::RecordNotFound do + book.reload + end + end end - end -end -end # end fo `if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter)` + end # end fo `if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter)` end # end fo `if ActiveRecord::Base.connection.supports_views?` if ActiveRecord::Base.connection.respond_to?(:supports_materialized_views?) && ActiveRecord::Base.connection.supports_materialized_views? -class MaterializedViewTest < ActiveRecord::PostgreSQLTestCase - include ViewBehavior + class MaterializedViewTest < ActiveRecord::PostgreSQLTestCase + include ViewBehavior - private - def create_view(name, query) - @connection.execute "CREATE MATERIALIZED VIEW #{name} AS #{query}" - end + private + def create_view(name, query) + @connection.execute "CREATE MATERIALIZED VIEW #{name} AS #{query}" + end - def drop_view(name) - @connection.execute "DROP MATERIALIZED VIEW #{name}" if @connection.view_exists? name + def drop_view(name) + @connection.execute "DROP MATERIALIZED VIEW #{name}" if @connection.view_exists? name + end end end -end diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb index 6556771a9d..ade6e6095b 100644 --- a/activerecord/test/cases/yaml_serialization_test.rb +++ b/activerecord/test/cases/yaml_serialization_test.rb @@ -121,11 +121,11 @@ class YamlSerializationTest < ActiveRecord::TestCase private - def yaml_fixture(file_name) - path = File.expand_path( - "../../support/yaml_compatibility_fixtures/#{file_name}.yml", - __FILE__ - ) - File.read(path) - end + def yaml_fixture(file_name) + path = File.expand_path( + "../../support/yaml_compatibility_fixtures/#{file_name}.yml", + __FILE__ + ) + File.read(path) + end end diff --git a/activerecord/test/models/club.rb b/activerecord/test/models/club.rb index b2986a8c58..49d7b24a3b 100644 --- a/activerecord/test/models/club.rb +++ b/activerecord/test/models/club.rb @@ -10,9 +10,9 @@ class Club < ActiveRecord::Base private - def private_method - "I'm sorry sir, this is a *private* club, not a *pirate* club" - end + def private_method + "I'm sorry sir, this is a *private* club, not a *pirate* club" + end end class SuperClub < ActiveRecord::Base diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index 921cf10f30..025630087c 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -22,12 +22,12 @@ class Company < AbstractCompany private - def private_method - "I am Jack's innermost fears and aspirations" - end + def private_method + "I am Jack's innermost fears and aspirations" + end - class SpecialCo < Company - end + class SpecialCo < Company + end end module Namespaced @@ -218,13 +218,13 @@ class Account < ActiveRecord::Base protected - def check_empty_credit_limit - errors.add("credit_limit", :blank) if credit_limit.blank? - end + def check_empty_credit_limit + errors.add("credit_limit", :blank) if credit_limit.blank? + end private - def private_method - "Sir, yes sir!" - end + def private_method + "Sir, yes sir!" + end end diff --git a/activerecord/test/models/company_in_module.rb b/activerecord/test/models/company_in_module.rb index e035a80ab8..682f99e365 100644 --- a/activerecord/test/models/company_in_module.rb +++ b/activerecord/test/models/company_in_module.rb @@ -90,9 +90,9 @@ module MyApplication protected - def check_empty_credit_limit - errors.add("credit_card", :blank) if credit_card.blank? - end + def check_empty_credit_limit + errors.add("credit_card", :blank) if credit_card.blank? + end end end end diff --git a/activerecord/test/models/engine.rb b/activerecord/test/models/engine.rb index 50c6717037..eada171f6a 100644 --- a/activerecord/test/models/engine.rb +++ b/activerecord/test/models/engine.rb @@ -1,4 +1,3 @@ class Engine < ActiveRecord::Base belongs_to :my_car, class_name: "Car", foreign_key: "car_id", counter_cache: :engines_count end - diff --git a/activerecord/test/models/eye.rb b/activerecord/test/models/eye.rb index dc8ae2b3f6..ab3b3eacf3 100644 --- a/activerecord/test/models/eye.rb +++ b/activerecord/test/models/eye.rb @@ -15,7 +15,7 @@ class Eye < ActiveRecord::Base after_create :trace_after_create2 after_update :trace_after_update2 after_save :trace_after_save2 - + def trace_after_create (@after_create_callbacks_stack ||= []) << !iris.persisted? end diff --git a/activerecord/test/models/mentor.rb b/activerecord/test/models/mentor.rb index 11f1e4bff8..66504b4e91 100644 --- a/activerecord/test/models/mentor.rb +++ b/activerecord/test/models/mentor.rb @@ -1,3 +1,3 @@ class Mentor < ActiveRecord::Base has_many :developers -end \ No newline at end of file +end diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb index ea215eeb81..eb117f92e1 100644 --- a/activerecord/test/models/person.rb +++ b/activerecord/test/models/person.rb @@ -96,13 +96,13 @@ class RichPerson < ActiveRecord::Base private - def run_before_create - self.first_name = first_name.to_s + "run_before_create" - end + def run_before_create + self.first_name = first_name.to_s + "run_before_create" + end - def run_before_validation - self.first_name = first_name.to_s + "run_before_validation" - end + def run_before_validation + self.first_name = first_name.to_s + "run_before_validation" + end end class NestedPerson < ActiveRecord::Base diff --git a/activerecord/test/models/vehicle.rb b/activerecord/test/models/vehicle.rb index ef26170f1f..855bc4e325 100644 --- a/activerecord/test/models/vehicle.rb +++ b/activerecord/test/models/vehicle.rb @@ -4,4 +4,4 @@ class Vehicle < ActiveRecord::Base end class Bus < Vehicle -end \ No newline at end of file +end -- cgit v1.2.3