Fix tests without assertions in the framework

This commit is contained in:
fatkodima 2024-04-29 11:25:46 +03:00 committed by Rafael Mendonça França
parent 90b3f57f17
commit 702638291c
No known key found for this signature in database
GPG Key ID: FC23B6D0F1EEE948
58 changed files with 235 additions and 121 deletions

@ -177,12 +177,14 @@ def test_get_post_request_switch
end end
def test_string_constraint def test_string_constraint
assert_nothing_raised do
with_routing do |set| with_routing do |set|
set.draw do set.draw do
get "photos", to: "action_pack_assertions#nothing", constraints: { subdomain: "admin" } get "photos", to: "action_pack_assertions#nothing", constraints: { subdomain: "admin" }
end end
end end
end end
end
def test_with_routing_works_with_api_only_controllers def test_with_routing_works_with_api_only_controllers
@controller = ApiOnlyController.new @controller = ApiOnlyController.new

@ -310,17 +310,21 @@ def test_setting_flash_does_not_raise_in_following_requests
with_test_route_set do with_test_route_set do
env = { "action_dispatch.request.flash_hash" => ActionDispatch::Flash::FlashHash.new } env = { "action_dispatch.request.flash_hash" => ActionDispatch::Flash::FlashHash.new }
get "/set_flash", env: env get "/set_flash", env: env
assert_nothing_raised do
get "/set_flash", env: env get "/set_flash", env: env
end end
end end
end
def test_setting_flash_now_does_not_raise_in_following_requests def test_setting_flash_now_does_not_raise_in_following_requests
with_test_route_set do with_test_route_set do
env = { "action_dispatch.request.flash_hash" => ActionDispatch::Flash::FlashHash.new } env = { "action_dispatch.request.flash_hash" => ActionDispatch::Flash::FlashHash.new }
get "/set_flash_now", env: env get "/set_flash_now", env: env
assert_nothing_raised do
get "/set_flash_now", env: env get "/set_flash_now", env: env
end end
end end
end
def test_added_flash_types_method def test_added_flash_types_method
with_test_route_set do with_test_route_set do

@ -430,6 +430,7 @@ def test_delayed_autoload_after_write_within_interlock_hook
res = get :write_sleep_autoload res = get :write_sleep_autoload
res.each { } res.each { }
ActiveSupport::Dependencies.interlock.done_running ActiveSupport::Dependencies.interlock.done_running
pass
end end
def test_async_stream def test_async_stream

@ -1000,6 +1000,7 @@ def test_live_head_ok
@response.stream.on_error { flunk "action should not raise any errors" } @response.stream.on_error { flunk "action should not raise any errors" }
sleep 0.2 sleep 0.2
pass
end end
end end

@ -508,12 +508,14 @@ def setup_for_named_route(options = {})
end end
def test_named_route_without_hash def test_named_route_without_hash
assert_nothing_raised do
rs.draw do rs.draw do
ActionDispatch.deprecator.silence do ActionDispatch.deprecator.silence do
get ":controller/:action/:id", as: "normal" get ":controller/:action/:id", as: "normal"
end end
end end
end end
end
def test_named_route_root def test_named_route_root
rs.draw do rs.draw do

@ -36,8 +36,10 @@ def asts
end end
def test_initialize def test_initialize
assert_nothing_raised do
Mapper.new FakeSet.new Mapper.new FakeSet.new
end end
end
def test_scope_raises_on_anchor def test_scope_raises_on_anchor
fakeset = FakeSet.new fakeset = FakeSet.new

@ -159,6 +159,7 @@ def teardown
fixture = FIXTURE_PATH + "/ruby_on_rails.jpg" fixture = FIXTURE_PATH + "/ruby_on_rails.jpg"
params = { uploaded_data: fixture_file_upload(fixture, "image/jpeg") } params = { uploaded_data: fixture_file_upload(fixture, "image/jpeg") }
post "/read", params: params post "/read", params: params
assert_equal Encoding::ASCII_8BIT, response.body.encoding
end end
end end

@ -1152,9 +1152,11 @@ class RequestParameters < BaseRequestTest
request = stub_request("QUERY_STRING" => "foo=%81E") request = stub_request("QUERY_STRING" => "foo=%81E")
ActionDispatch::Request::Utils.stub(:set_binary_encoding, { "foo" => "\x81E".b }) do ActionDispatch::Request::Utils.stub(:set_binary_encoding, { "foo" => "\x81E".b }) do
assert_nothing_raised do
request.parameters request.parameters
end end
end end
end
test "POST parameters specified as ASCII_8BIT encoded do not raise InvalidParameterError" do test "POST parameters specified as ASCII_8BIT encoded do not raise InvalidParameterError" do
data = "foo=%81E" data = "foo=%81E"
@ -1166,9 +1168,11 @@ class RequestParameters < BaseRequestTest
) )
ActionDispatch::Request::Utils.stub(:set_binary_encoding, { "foo" => "\x81E".b }) do ActionDispatch::Request::Utils.stub(:set_binary_encoding, { "foo" => "\x81E".b }) do
assert_nothing_raised do
request.parameters request.parameters
end end
end end
end
test "parameters not accessible after rack parse error 1" do test "parameters not accessible after rack parse error 1" do
request = stub_request( request = stub_request(

@ -30,8 +30,10 @@ class DriverTest < ActiveSupport::TestCase
test "initializing the driver with a headless chrome and custom path" do test "initializing the driver with a headless chrome and custom path" do
original_driver_path = ::Selenium::WebDriver::Chrome::Service.driver_path original_driver_path = ::Selenium::WebDriver::Chrome::Service.driver_path
assert_nothing_raised do
::Selenium::WebDriver::Chrome::Service.driver_path = "bin/test" ::Selenium::WebDriver::Chrome::Service.driver_path = "bin/test"
ActionDispatch::SystemTesting::Driver.new(:selenium, using: :headless_chrome, screen_size: [1400, 1400]) ActionDispatch::SystemTesting::Driver.new(:selenium, using: :headless_chrome, screen_size: [1400, 1400])
end
ensure ensure
::Selenium::WebDriver::Chrome::Service.driver_path = original_driver_path ::Selenium::WebDriver::Chrome::Service.driver_path = original_driver_path
end end
@ -47,8 +49,10 @@ class DriverTest < ActiveSupport::TestCase
test "initializing the driver with a headless firefox and custom path" do test "initializing the driver with a headless firefox and custom path" do
original_driver_path = ::Selenium::WebDriver::Firefox::Service.driver_path original_driver_path = ::Selenium::WebDriver::Firefox::Service.driver_path
assert_nothing_raised do
::Selenium::WebDriver::Firefox::Service.driver_path = "bin/test" ::Selenium::WebDriver::Firefox::Service.driver_path = "bin/test"
ActionDispatch::SystemTesting::Driver.new(:selenium, using: :headless_firefox, screen_size: [1400, 1400]) ActionDispatch::SystemTesting::Driver.new(:selenium, using: :headless_firefox, screen_size: [1400, 1400])
end
ensure ensure
::Selenium::WebDriver::Firefox::Service.driver_path = original_driver_path ::Selenium::WebDriver::Firefox::Service.driver_path = original_driver_path
end end

@ -28,14 +28,18 @@ class MessageWithFooter < MessageWithStrictLoading
records = MessageWithStrictLoading.with_rich_text_strict_loading_content.all records = MessageWithStrictLoading.with_rich_text_strict_loading_content.all
assert_nothing_raised do
records.map(&:strict_loading_content) records.map(&:strict_loading_content)
end end
end
test "has_rich_text accepts strict_loading: overrides" do test "has_rich_text accepts strict_loading: overrides" do
MessageWithFooter.create! footer: "ignored" MessageWithFooter.create! footer: "ignored"
records = MessageWithFooter.all records = MessageWithFooter.all
assert_nothing_raised do
records.map(&:footer) records.map(&:footer)
end end
end end
end

@ -2848,14 +2848,18 @@ def test_datetime_select_with_separators
def test_datetime_select_with_integer def test_datetime_select_with_integer
@post = Post.new @post = Post.new
@post.updated_at = 3 @post.updated_at = 3
assert_nothing_raised do
datetime_select("post", "updated_at") datetime_select("post", "updated_at")
end end
end
def test_datetime_select_with_infinity # Float def test_datetime_select_with_infinity # Float
@post = Post.new @post = Post.new
@post.updated_at = (-1.0 / 0) @post.updated_at = (-1.0 / 0)
assert_nothing_raised do
datetime_select("post", "updated_at") datetime_select("post", "updated_at")
end end
end
def test_datetime_select_with_default_prompt def test_datetime_select_with_default_prompt
@post = Post.new @post = Post.new

@ -229,8 +229,10 @@ def test_extra_locals_raises_error
def test_rails_injected_locals_does_not_raise_error_if_not_passed def test_rails_injected_locals_does_not_raise_error_if_not_passed
@template = new_template("<%# locals: (message:) -%>") @template = new_template("<%# locals: (message:) -%>")
assert_nothing_raised do
render(message: "Hi", message_counter: 1, message_iteration: 1, implicit_locals: %i[message_counter message_iteration]) render(message: "Hi", message_counter: 1, message_iteration: 1, implicit_locals: %i[message_counter message_iteration])
end end
end
def test_rails_injected_locals_can_be_specified def test_rails_injected_locals_can_be_specified
@template = new_template("<%# locals: (message: 'Hello') -%>\n<%= message %>") @template = new_template("<%# locals: (message: 'Hello') -%>\n<%= message %>")

@ -538,8 +538,10 @@ def test_reset_cycle
end end
def test_reset_unknown_cycle def test_reset_unknown_cycle
assert_nothing_raised do
reset_cycle("colors") reset_cycle("colors")
end end
end
def test_reset_named_cycle def test_reset_named_cycle
assert_equal("1", cycle(1, 2, 3, name: "numbers")) assert_equal("1", cycle(1, 2, 3, name: "numbers"))

@ -270,8 +270,10 @@ def test_enqueue_at_log_when_enqueue_error_is_set
def test_for_tagged_logger_support_is_consistent def test_for_tagged_logger_support_is_consistent
set_logger ::Logger.new(nil) set_logger ::Logger.new(nil)
assert_nothing_raised do
OverriddenLoggingJob.perform_later "Dummy" OverriddenLoggingJob.perform_later "Dummy"
end end
end
def test_job_error_logging def test_job_error_logging
perform_enqueued_jobs do perform_enqueued_jobs do

@ -26,6 +26,7 @@ class QueuingTest < ActiveSupport::TestCase
result = HelloJob.set(wait_until: 1.second.ago).perform_later "Jamie" result = HelloJob.set(wait_until: 1.second.ago).perform_later "Jamie"
assert result assert result
rescue NotImplementedError rescue NotImplementedError
pass
end end
test "job returned by enqueue has the arguments available" do test "job returned by enqueue has the arguments available" do
@ -37,6 +38,7 @@ class QueuingTest < ActiveSupport::TestCase
job = HelloJob.set(wait_until: Time.utc(2014, 1, 1)).perform_later job = HelloJob.set(wait_until: Time.utc(2014, 1, 1)).perform_later
assert_equal Time.utc(2014, 1, 1), job.scheduled_at assert_equal Time.utc(2014, 1, 1), job.scheduled_at
rescue NotImplementedError rescue NotImplementedError
pass
end end
test "job is yielded to block after enqueue with successfully_enqueued property set" do test "job is yielded to block after enqueue with successfully_enqueued property set" do
@ -80,6 +82,7 @@ class QueuingTest < ActiveSupport::TestCase
ActiveJob.perform_all_later(scheduled_job_1, scheduled_job_2) ActiveJob.perform_all_later(scheduled_job_1, scheduled_job_2)
assert_equal ["Scheduled 2014 says hello", "Scheduled 2015 says hello"], JobBuffer.values.sort assert_equal ["Scheduled 2014 says hello", "Scheduled 2015 says hello"], JobBuffer.values.sort
rescue NotImplementedError rescue NotImplementedError
pass
end end
test "perform_all_later instrumentation" do test "perform_all_later instrumentation" do

@ -67,6 +67,7 @@ class QueuingTest < ActiveSupport::TestCase
wait_for_jobs_to_finish_for(5.seconds) wait_for_jobs_to_finish_for(5.seconds)
assert_job_not_executed assert_job_not_executed
rescue NotImplementedError rescue NotImplementedError
pass
end end
test "should run job enqueued in the future at the specified time" do test "should run job enqueued in the future at the specified time" do
@ -76,6 +77,7 @@ class QueuingTest < ActiveSupport::TestCase
wait_for_jobs_to_finish_for(10.seconds) wait_for_jobs_to_finish_for(10.seconds)
assert_job_executed assert_job_executed
rescue NotImplementedError rescue NotImplementedError
pass
end end
test "should run job bulk enqueued in the future at the specified time" do test "should run job bulk enqueued in the future at the specified time" do
@ -85,6 +87,7 @@ class QueuingTest < ActiveSupport::TestCase
wait_for_jobs_to_finish_for(10.seconds) wait_for_jobs_to_finish_for(10.seconds)
assert_job_executed assert_job_executed
rescue NotImplementedError rescue NotImplementedError
pass
end end
if adapter_is?(:async, :delayed_job, :sidekiq, :queue_classic) if adapter_is?(:async, :delayed_job, :sidekiq, :queue_classic)

@ -15,14 +15,6 @@
class ActiveModel::TestCase < ActiveSupport::TestCase class ActiveModel::TestCase < ActiveSupport::TestCase
include ActiveSupport::Testing::MethodCallAssertions include ActiveSupport::Testing::MethodCallAssertions
class AssertionlessTest < StandardError; end
def after_teardown
super
raise AssertionlessTest, "No assertions made." if passed? && assertions.zero?
end
end end
require_relative "../../../tools/test_common" require_relative "../../../tools/test_common"

@ -65,10 +65,12 @@ def test_doesnt_error_when_a_select_query_has_encoding_errors
else else
def test_doesnt_error_when_a_select_query_has_encoding_errors def test_doesnt_error_when_a_select_query_has_encoding_errors
ActiveRecord::Base.while_preventing_writes do ActiveRecord::Base.while_preventing_writes do
assert_nothing_raised do
@connection.select_all("SELECT '\xC8'") @connection.select_all("SELECT '\xC8'")
end end
end end
end end
end
def test_doesnt_error_when_a_select_query_is_called_while_preventing_writes def test_doesnt_error_when_a_select_query_is_called_while_preventing_writes
@connection.insert("INSERT INTO subscribers(nick) VALUES ('138853948594')") @connection.insert("INSERT INTO subscribers(nick) VALUES ('138853948594')")

@ -121,6 +121,8 @@ def test_remove_index_when_name_and_wrong_column_name_specified_positional_argum
def test_current_database def test_current_database
if @connection.respond_to?(:current_database) if @connection.respond_to?(:current_database)
assert_equal ARTest.test_configuration_hashes["arunit"]["database"], @connection.current_database assert_equal ARTest.test_configuration_hashes["arunit"]["database"], @connection.current_database
else
skip
end end
end end
@ -887,6 +889,7 @@ class AdapterThreadSafetyTest < ActiveRecord::TestCase
threads(2, 25) { @connection.disconnect! } threads(2, 25) { @connection.disconnect! }
join join
pass
end end
test "#verify! is synchronized" do test "#verify! is synchronized" do
@ -894,6 +897,7 @@ class AdapterThreadSafetyTest < ActiveRecord::TestCase
threads(2, 25) { @connection.disconnect! } threads(2, 25) { @connection.disconnect! }
join join
pass
end end
end end

@ -96,6 +96,7 @@ def test_dump_indexes
def test_drop_temporary_table def test_drop_temporary_table
@connection.transaction do @connection.transaction do
@connection.create_table(:temp_table, temporary: true) @connection.create_table(:temp_table, temporary: true)
assert_nothing_raised do
# if it doesn't properly say DROP TEMPORARY TABLE, the transaction commit # if it doesn't properly say DROP TEMPORARY TABLE, the transaction commit
# will complain that no transaction is active # will complain that no transaction is active
@connection.drop_table(:temp_table, temporary: true) @connection.drop_table(:temp_table, temporary: true)
@ -105,6 +106,7 @@ def test_drop_temporary_table
end end
end end
end end
end
class MysqlAnsiQuotesTest < ActiveRecord::AbstractMysqlTestCase class MysqlAnsiQuotesTest < ActiveRecord::AbstractMysqlTestCase
def setup def setup

@ -167,16 +167,20 @@ def test_set_session_variable_false
def test_set_session_variable_nil def test_set_session_variable_nil
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
# This should be a no-op that does not raise an error # This should be a no-op that does not raise an error
assert_nothing_raised do
ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: nil })) ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: nil }))
end end
end end
end
def test_set_session_variable_default def test_set_session_variable_default
run_without_connection do |orig_connection| run_without_connection do |orig_connection|
# This should execute a query that does not raise an error # This should execute a query that does not raise an error
assert_nothing_raised do
ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: :default })) ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: :default }))
end end
end end
end
def test_set_session_timezone def test_set_session_timezone
run_without_connection do |orig_connection| run_without_connection do |orig_connection|

@ -184,10 +184,13 @@ def test_raise_wrapped_exception_on_bad_prepare
if ActiveRecord::Base.lease_connection.prepared_statements if ActiveRecord::Base.lease_connection.prepared_statements
def test_schema_change_with_prepared_stmt def test_schema_change_with_prepared_stmt
altered = false altered = false
assert_nothing_raised do
@connection.exec_query "select * from developers where id = $1", "sql", [bind_param(1)] @connection.exec_query "select * from developers where id = $1", "sql", [bind_param(1)]
@connection.exec_query "alter table developers add column zomg int", "sql", [] @connection.exec_query "alter table developers add column zomg int", "sql", []
altered = true altered = true
@connection.exec_query "select * from developers where id = $1", "sql", [bind_param(1)] @connection.exec_query "select * from developers where id = $1", "sql", [bind_param(1)]
end
pass
ensure ensure
# We are not using DROP COLUMN IF EXISTS because that syntax is only # We are not using DROP COLUMN IF EXISTS because that syntax is only
# supported by pg 9.X # supported by pg 9.X

@ -82,7 +82,8 @@ def test_schema_dumping
end end
def test_build_fixture_sql def test_build_fixture_sql
ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT, :virtual_columns) fixtures = ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT, :virtual_columns).first
assert_equal 2, fixtures.size
end end
end end
end end

@ -97,7 +97,8 @@ def test_schema_dumping
end end
def test_build_fixture_sql def test_build_fixture_sql
ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT, :virtual_columns) fixtures = ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT, :virtual_columns).first
assert_equal 2, fixtures.size
end end
end end
end end

@ -25,12 +25,14 @@ def assert_edge(edge_name, dot_string)
define_method("test_#{klass.name.gsub('::', '_')}") do define_method("test_#{klass.name.gsub('::', '_')}") do
op = klass.new(:a, "z") op = klass.new(:a, "z")
@visitor.accept op, Collectors::PlainString.new @visitor.accept op, Collectors::PlainString.new
pass
end end
end end
def test_named_function def test_named_function
func = Nodes::NamedFunction.new "omg", "omg" func = Nodes::NamedFunction.new "omg", "omg"
@visitor.accept func, Collectors::PlainString.new @visitor.accept func, Collectors::PlainString.new
pass
end end
# unary ops # unary ops
@ -48,6 +50,7 @@ def test_named_function
define_method("test_#{klass.name.gsub('::', '_')}") do define_method("test_#{klass.name.gsub('::', '_')}") do
op = klass.new(:a) op = klass.new(:a)
@visitor.accept op, Collectors::PlainString.new @visitor.accept op, Collectors::PlainString.new
pass
end end
end end
@ -73,6 +76,7 @@ def test_named_function
define_method("test_#{klass.name.gsub('::', '_')}") do define_method("test_#{klass.name.gsub('::', '_')}") do
binary = klass.new(:a, :b) binary = klass.new(:a, :b)
@visitor.accept binary, Collectors::PlainString.new @visitor.accept binary, Collectors::PlainString.new
pass
end end
end end
@ -84,6 +88,7 @@ def test_named_function
define_method("test_#{klass.name.gsub('::', '_')}") do define_method("test_#{klass.name.gsub('::', '_')}") do
binary = klass.new([:a, :b]) binary = klass.new([:a, :b])
@visitor.accept binary, Collectors::PlainString.new @visitor.accept binary, Collectors::PlainString.new
pass
end end
end end

@ -1159,9 +1159,11 @@ def test_belongs_to_proxy_should_not_respond_to_private_methods
end end
def test_belongs_to_proxy_should_respond_to_private_methods_via_send def test_belongs_to_proxy_should_respond_to_private_methods_via_send
assert_nothing_raised do
companies(:first_firm).send(:private_method) companies(:first_firm).send(:private_method)
companies(:second_client).firm.send(:private_method) companies(:second_client).firm.send(:private_method)
end end
end
def test_save_of_record_with_loaded_belongs_to def test_save_of_record_with_loaded_belongs_to
@account = companies(:first_firm).account @account = companies(:first_firm).account

@ -572,7 +572,7 @@ def test_string_id_column_joins
Subscription.create!(subscriber_id: "PL", book_id: b.id) Subscription.create!(subscriber_id: "PL", book_id: b.id)
s.reload s.reload
s.book_ids = s.book_ids assert_equal [b.id], s.book_ids
end end
def test_eager_load_has_many_through_with_string_keys def test_eager_load_has_many_through_with_string_keys
@ -816,7 +816,8 @@ def test_eager_association_loading_with_habtm
end end
def test_eager_with_inheritance def test_eager_with_inheritance
SpecialPost.all.merge!(includes: [ :comments ]).to_a posts = SpecialPost.all.merge!(includes: [ :comments ]).to_a
assert_equal 1, posts.size
end end
def test_eager_has_one_with_association_inheritance def test_eager_has_one_with_association_inheritance

@ -3201,12 +3201,14 @@ def test_invalid_key_raises_with_message_including_all_default_options
end end
def test_key_ensuring_owner_was_is_valid_when_dependent_option_is_destroy_async def test_key_ensuring_owner_was_is_valid_when_dependent_option_is_destroy_async
assert_nothing_raised do
Class.new(ActiveRecord::Base) do Class.new(ActiveRecord::Base) do
self.destroy_association_async_job = Class.new self.destroy_association_async_job = Class.new
has_many :books, dependent: :destroy_async, ensuring_owner_was: :destroyed? has_many :books, dependent: :destroy_async, ensuring_owner_was: :destroyed?
end end
end end
end
test "composite primary key malformed association class" do test "composite primary key malformed association class" do
error = assert_raises(ActiveRecord::CompositePrimaryKeyMismatchError) do error = assert_raises(ActiveRecord::CompositePrimaryKeyMismatchError) do

@ -1253,9 +1253,11 @@ def test_primary_key_option_on_source
def test_create_should_not_raise_exception_when_join_record_has_errors def test_create_should_not_raise_exception_when_join_record_has_errors
repair_validations(Categorization) do repair_validations(Categorization) do
Categorization.validate { |r| r.errors.add(:base, "Invalid Categorization") } Categorization.validate { |r| r.errors.add(:base, "Invalid Categorization") }
assert_nothing_raised do
Category.create(name: "Fishing", authors: [Author.first]) Category.create(name: "Fishing", authors: [Author.first])
end end
end end
end
def test_assign_array_to_new_record_builds_join_records def test_assign_array_to_new_record_builds_join_records
c = Category.new(name: "Fishing", authors: [Author.first]) c = Category.new(name: "Fishing", authors: [Author.first])

@ -493,9 +493,11 @@ def test_has_one_proxy_should_not_respond_to_private_methods
end end
def test_has_one_proxy_should_respond_to_private_methods_via_send def test_has_one_proxy_should_respond_to_private_methods_via_send
assert_nothing_raised do
accounts(:signals37).send(:private_method) accounts(:signals37).send(:private_method)
companies(:first_firm).account.send(:private_method) companies(:first_firm).account.send(:private_method)
end end
end
def test_save_of_record_with_loaded_has_one def test_save_of_record_with_loaded_has_one
@firm = companies(:first_firm) @firm = companies(:first_firm)

@ -245,8 +245,10 @@ def test_has_one_through_proxy_should_not_respond_to_private_methods
def test_has_one_through_proxy_should_respond_to_private_methods_via_send def test_has_one_through_proxy_should_respond_to_private_methods_via_send
clubs(:moustache_club).send(:private_method) clubs(:moustache_club).send(:private_method)
assert_nothing_raised do
@member.club.send(:private_method) @member.club.send(:private_method)
end end
end
def test_assigning_to_has_one_through_preserves_decorated_join_record def test_assigning_to_has_one_through_preserves_decorated_join_record
@organization = organizations(:nsa) @organization = organizations(:nsa)

@ -285,10 +285,12 @@ def test_can_swap_roles_while_shard_swapping_is_prohibited
ActiveRecord::Base.connects_to(shards: { default: { writing: :primary, reading: :primary_replica } }) ActiveRecord::Base.connects_to(shards: { default: { writing: :primary, reading: :primary_replica } })
assert_nothing_raised do
ActiveRecord::Base.prohibit_shard_swapping do # no exception ActiveRecord::Base.prohibit_shard_swapping do # no exception
ActiveRecord::Base.connected_to(role: :reading) do ActiveRecord::Base.connected_to(role: :reading) do
end end
end end
end
ensure ensure
ActiveRecord::Base.configurations = @prev_configs ActiveRecord::Base.configurations = @prev_configs
ActiveRecord::Base.establish_connection(:arunit) ActiveRecord::Base.establish_connection(:arunit)

@ -325,7 +325,13 @@ def test_data_source_exist
end end
def test_clear_data_source_cache def test_clear_data_source_cache
# Cache data sources list.
assert @cache.data_source_exists?("courses")
@cache.clear_data_source_cache!("courses") @cache.clear_data_source_cache!("courses")
assert_queries_count(1, include_schema: true) do
@cache.data_source_exists?("courses")
end
end end
test "#columns_hash? is populated by #columns_hash" do test "#columns_hash? is populated by #columns_hash" do

@ -31,6 +31,7 @@ def test_can_throw_away
def test_can_close def test_can_close
@connection.close @connection.close
assert_not @connection.active?
end end
end end
end end

@ -7,8 +7,8 @@ module ActiveRecord
class CustomLockingTest < ActiveRecord::TestCase class CustomLockingTest < ActiveRecord::TestCase
fixtures :people fixtures :people
def test_custom_lock
if current_adapter?(:Mysql2Adapter, :TrilogyAdapter) if current_adapter?(:Mysql2Adapter, :TrilogyAdapter)
def test_custom_lock
assert_match "SHARE MODE", Person.lock("LOCK IN SHARE MODE").to_sql assert_match "SHARE MODE", Person.lock("LOCK IN SHARE MODE").to_sql
assert_queries_match(/LOCK IN SHARE MODE/) do assert_queries_match(/LOCK IN SHARE MODE/) do
Person.all.merge!(lock: "LOCK IN SHARE MODE").find(1) Person.all.merge!(lock: "LOCK IN SHARE MODE").find(1)

@ -27,8 +27,10 @@ class ActiveRecord::Encryption::EncryptableRecordApiTest < ActiveRecord::Encrypt
end end
test "encrypt won't fail for classes without attributes to encrypt" do test "encrypt won't fail for classes without attributes to encrypt" do
assert_nothing_raised do
posts(:welcome).encrypt posts(:welcome).encrypt
end end
end
test "decrypt decrypts encrypted attributes" do test "decrypt decrypts encrypted attributes" do
title = "the Starfleet is here!" title = "the Starfleet is here!"

@ -70,7 +70,8 @@ class ActiveRecord::Encryption::EncryptorTest < ActiveRecord::EncryptionTestCase
encryptor = ActiveRecord::Encryption::Encryptor.new encryptor = ActiveRecord::Encryption::Encryptor.new
key_provider.stub :decryption_keys, ->(message) { [key] } do key_provider.stub :decryption_keys, ->(message) { [key] } do
encryptor.decrypt encryptor.encrypt("some text", key_provider: key_provider), key_provider: key_provider decrypted_text = encryptor.decrypt encryptor.encrypt("some text", key_provider: key_provider), key_provider: key_provider
assert decrypted_text
end end
end end

@ -7,6 +7,7 @@ def test_can_be_instantiated_with_no_args
base = ActiveRecord::ActiveRecordError base = ActiveRecord::ActiveRecordError
error_klasses = ObjectSpace.each_object(Class).select { |klass| klass < base } error_klasses = ObjectSpace.each_object(Class).select { |klass| klass < base }
assert_nothing_raised do
(error_klasses - [ActiveRecord::AmbiguousSourceReflectionForThroughAssociation]).each do |error_klass| (error_klasses - [ActiveRecord::AmbiguousSourceReflectionForThroughAssociation]).each do |error_klass|
error_klass.new.inspect error_klass.new.inspect
rescue ArgumentError rescue ArgumentError
@ -14,3 +15,4 @@ def test_can_be_instantiated_with_no_args
end end
end end
end end
end

@ -34,6 +34,7 @@
require "models/topic" require "models/topic"
require "models/traffic_light" require "models/traffic_light"
require "models/treasure" require "models/treasure"
require "models/tree"
require "models/cpk" require "models/cpk"
class FixturesTest < ActiveRecord::TestCase class FixturesTest < ActiveRecord::TestCase
@ -43,7 +44,7 @@ class FixturesTest < ActiveRecord::TestCase
self.use_transactional_tests = false self.use_transactional_tests = false
# other_topics fixture should not be included here # other_topics fixture should not be included here
fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries, :traffic_lights fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries, :traffic_lights, :trees
FIXTURES = %w( accounts binaries companies customers FIXTURES = %w( accounts binaries companies customers
developers developers_projects entrants developers developers_projects entrants
@ -550,6 +551,8 @@ def test_yaml_file_with_invalid_column
def test_yaml_file_with_symbol_columns def test_yaml_file_with_symbol_columns
ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT + "/naked/yml", "trees") ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT + "/naked/yml", "trees")
root = Tree.find(1)
assert root
end end
def test_omap_fixtures def test_omap_fixtures
@ -820,6 +823,7 @@ def setup
end end
def test_nothing def test_nothing
pass
end end
end end
@ -1428,10 +1432,12 @@ def test_supports_polymorphic_belongs_to
end end
def test_only_generates_a_pk_if_necessary def test_only_generates_a_pk_if_necessary
assert_nothing_raised do
m = Matey.first m = Matey.first
m.pirate = pirates(:blackbeard) m.pirate = pirates(:blackbeard)
m.target = pirates(:redbeard) m.target = pirates(:redbeard)
end end
end
def test_supports_sti def test_supports_sti
assert_kind_of DeadParrot, parrots(:polly) assert_kind_of DeadParrot, parrots(:polly)

@ -475,7 +475,9 @@ def test_migrations_can_handle_foreign_keys_to_specific_tables
migration = RevertCustomForeignKeyTable.new migration = RevertCustomForeignKeyTable.new
InvertibleMigration.migrate(:up) InvertibleMigration.migrate(:up)
migration.migrate(:up) migration.migrate(:up)
assert ActiveRecord::Base.lease_connection.column_exists?(:horses, :owner_id)
migration.migrate(:down) migration.migrate(:down)
assert_not ActiveRecord::Base.lease_connection.column_exists?(:horses, :owner_id)
end end
# MySQL 5.7 and Oracle do not allow to create duplicate indexes on the same columns # MySQL 5.7 and Oracle do not allow to create duplicate indexes on the same columns

@ -235,6 +235,7 @@ def test_create_table_with_timestamps_should_create_datetime_columns_with_option
def test_create_table_without_a_block def test_create_table_without_a_block
connection.create_table table_name connection.create_table table_name
assert connection.table_exists?(table_name)
end end
# SQLite3 will not allow you to add a NOT NULL # SQLite3 will not allow you to add a NOT NULL
@ -359,6 +360,8 @@ def test_change_column_quotes_column_names
else else
connection.execute "insert into testings (#{connection.quote_column_name('select')}) values ('7 chars')" connection.execute "insert into testings (#{connection.quote_column_name('select')}) values ('7 chars')"
end end
assert_equal 1, connection.select_value("SELECT COUNT(*) FROM testings")
end end
def test_keeping_default_and_notnull_constraints_on_change def test_keeping_default_and_notnull_constraints_on_change

@ -319,12 +319,16 @@ class NoForeignKeySupportTest < ActiveRecord::TestCase
end end
def test_add_check_constraint_should_be_noop def test_add_check_constraint_should_be_noop
assert_nothing_raised do
@connection.add_check_constraint :products, "discounted_price > 0", name: "discounted_price_check" @connection.add_check_constraint :products, "discounted_price > 0", name: "discounted_price_check"
end end
end
def test_remove_check_constraint_should_be_noop def test_remove_check_constraint_should_be_noop
assert_nothing_raised do
@connection.remove_check_constraint :products, name: "price_check" @connection.remove_check_constraint :products, name: "price_check"
end end
end
def test_check_constraints_should_raise_not_implemented def test_check_constraints_should_raise_not_implemented
assert_raises(NotImplementedError) do assert_raises(NotImplementedError) do

@ -220,7 +220,9 @@ def test_add_index_attribute_length_limit
def test_add_index def test_add_index
connection.add_index("testings", "last_name") connection.add_index("testings", "last_name")
assert connection.index_exists?("testings", "last_name")
connection.remove_index("testings", "last_name") connection.remove_index("testings", "last_name")
assert_not connection.index_exists?("testings", "last_name")
connection.add_index("testings", ["last_name", "first_name"]) connection.add_index("testings", ["last_name", "first_name"])
connection.remove_index("testings", column: ["last_name", "first_name"]) connection.remove_index("testings", column: ["last_name", "first_name"])

@ -31,7 +31,9 @@ def test_migration_should_be_run_without_logger
previous_logger = ActiveRecord::Base.logger previous_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = nil ActiveRecord::Base.logger = nil
migrations = [Migration.new("a", 1), Migration.new("b", 2), Migration.new("c", 3)] migrations = [Migration.new("a", 1), Migration.new("b", 2), Migration.new("c", 3)]
assert_nothing_raised do
ActiveRecord::Migrator.new(:up, migrations, @schema_migration, @internal_metadata).migrate ActiveRecord::Migrator.new(:up, migrations, @schema_migration, @internal_metadata).migrate
end
ensure ensure
ActiveRecord::Base.logger = previous_logger ActiveRecord::Base.logger = previous_logger
end end

@ -380,6 +380,7 @@ def test_should_automatically_enable_autosave_on_the_association
def test_should_accept_update_only_option def test_should_accept_update_only_option
@pirate.update(update_only_ship_attributes: { id: @pirate.ship.id, name: "Mayflower" }) @pirate.update(update_only_ship_attributes: { id: @pirate.ship.id, name: "Mayflower" })
assert_equal "Mayflower", @pirate.reload.ship.name
end end
def test_should_create_new_model_when_nothing_is_there_and_update_only_is_true def test_should_create_new_model_when_nothing_is_there_and_update_only_is_true

@ -457,7 +457,6 @@ def test_id_predicate_composite
end end
def test_derives_composite_primary_key def test_derives_composite_primary_key
def test_primary_key_issues_warning
model = Class.new(ActiveRecord::Base) do model = Class.new(ActiveRecord::Base) do
def self.table_name def self.table_name
"uber_barcodes" "uber_barcodes"
@ -466,7 +465,6 @@ def self.table_name
assert_equal ["region", "code"], model.primary_key assert_equal ["region", "code"], model.primary_key
end end
end
def test_collectly_dump_composite_primary_key def test_collectly_dump_composite_primary_key
schema = dump_table_schema "uber_barcodes" schema = dump_table_schema "uber_barcodes"

@ -118,9 +118,11 @@ def test_reap_flush_on_discarded_pool
pool = ConnectionPool.new(pool_config) pool = ConnectionPool.new(pool_config)
pool.discard! pool.discard!
assert_nothing_raised do
pool.reap pool.reap
pool.flush pool.flush
end end
end
if Process.respond_to?(:fork) if Process.respond_to?(:fork)
def test_connection_pool_starts_reaper_in_fork def test_connection_pool_starts_reaper_in_fork

@ -434,10 +434,13 @@ def test_serialized_attribute_can_be_defined_in_abstract_classes
end end
subclass = Class.new(klass) do subclass = Class.new(klass) do
self.table_name = "posts" self.table_name = "topics"
end end
subclass.define_attribute_methods subclass.define_attribute_methods
topic = subclass.create!(content: { foo: 1 })
assert_equal [topic], subclass.where(content: { foo: 1 }).to_a
end end
def test_nil_is_always_persisted_as_null def test_nil_is_always_persisted_as_null

@ -85,9 +85,11 @@ class Tag2 < ActiveRecord::Base
# constraint. # constraint.
test "serializable" do test "serializable" do
Tag.transaction(isolation: :serializable) do Tag.transaction(isolation: :serializable) do
assert_nothing_raised do
Tag.create Tag.create
end end
end end
end
test "setting isolation when joining a transaction raises an error" do test "setting isolation when joining a transaction raises an error" do
Tag.transaction do Tag.transaction do

@ -469,8 +469,10 @@ def transaction_with_shallow_return
def test_add_to_null_transaction def test_add_to_null_transaction
topic = Topic.new topic = Topic.new
assert_nothing_raised do
topic.send(:add_to_transaction) topic.send(:add_to_transaction)
end end
end
def test_successful_with_return_outside_inner_transaction def test_successful_with_return_outside_inner_transaction
committed = false committed = false
@ -1084,7 +1086,7 @@ def test_rollback_when_saving_a_frozen_record
end end
def test_rollback_when_thread_killed def test_rollback_when_thread_killed
return if in_memory_db? skip if in_memory_db?
queue = Queue.new queue = Queue.new
thread = Thread.new do thread = Thread.new do
@ -1342,9 +1344,8 @@ def test_rollback_for_freshly_persisted_records
assert_predicate topic, :persisted?, "persisted" assert_predicate topic, :persisted?, "persisted"
end end
if current_adapter?(:SQLite3Adapter)
def test_sqlite_add_column_in_transaction def test_sqlite_add_column_in_transaction
return true unless current_adapter?(:SQLite3Adapter)
# Test first if column creation/deletion works correctly when no # Test first if column creation/deletion works correctly when no
# transaction is in place. # transaction is in place.
# #
@ -1379,6 +1380,7 @@ def test_sqlite_add_column_in_transaction
Topic.reset_column_information Topic.reset_column_information
end end
end end
end
def test_transactions_state_from_rollback def test_transactions_state_from_rollback
connection = Topic.lease_connection connection = Topic.lease_connection

@ -45,8 +45,10 @@ def test_psych_roundtrip_new_object
end end
def test_active_record_relation_serialization def test_active_record_relation_serialization
assert_nothing_raised do
[Topic.all].to_yaml [Topic.all].to_yaml
end end
end
def test_raw_types_are_not_changed_on_round_trip def test_raw_types_are_not_changed_on_round_trip
topic = Topic.new(parent_id: "123") topic = Topic.new(parent_id: "123")

@ -43,6 +43,7 @@ class ActiveStorage::DiskControllerTest < ActionDispatch::IntegrationTest
blob.delete blob.delete
get blob.url get blob.url
assert_response :not_found
end end
test "showing blob with invalid key" do test "showing blob with invalid key" do

@ -5,6 +5,8 @@
module ActiveSupport module ActiveSupport
module RaiseWarnings # :nodoc: module RaiseWarnings # :nodoc:
class WarningError < StandardError; end
PROJECT_ROOT = File.expand_path("../../../../", __dir__) PROJECT_ROOT = File.expand_path("../../../../", __dir__)
ALLOWED_WARNINGS = Regexp.union( ALLOWED_WARNINGS = Regexp.union(
/circular require considered harmful.*delayed_job/, # Bug in delayed job. /circular require considered harmful.*delayed_job/, # Bug in delayed job.
@ -34,7 +36,7 @@ def warn(message, ...)
return if ALLOWED_WARNINGS.match?(message) return if ALLOWED_WARNINGS.match?(message)
return unless ENV["RAILS_STRICT_WARNINGS"] || ENV["BUILDKITE"] return unless ENV["RAILS_STRICT_WARNINGS"] || ENV["BUILDKITE"]
raise message raise WarningError.new(message)
end end
end end
end end

@ -9,12 +9,9 @@ module TestsWithoutAssertions # :nodoc:
def after_teardown def after_teardown
super super
return if skipped? || error? if assertions.zero? && !skipped? && !error?
if assertions == 0
file, line = method(name).source_location file, line = method(name).source_location
message = "Test is missing assertions: `#{name}` #{file}:#{line}" warn "Test is missing assertions: `#{name}` #{file}:#{line}"
warn message
end end
end end
end end

@ -55,6 +55,7 @@ def test_cleanup_clears_local_cache_but_not_remote_cache
begin begin
@cache.cleanup @cache.cleanup
rescue NotImplementedError rescue NotImplementedError
pass
return # Not implementing cleanup is valid return # Not implementing cleanup is valid
end end

@ -123,8 +123,10 @@ class InitializationTest < ActiveSupport::TestCase
end end
test "instantiating the store doesn't connect to Redis" do test "instantiating the store doesn't connect to Redis" do
assert_nothing_raised do
build(url: "redis://localhost:1") build(url: "redis://localhost:1")
end end
end
private private
def build(**kwargs) def build(**kwargs)

@ -14,6 +14,7 @@ module AfterTeardown
def after_teardown def after_teardown
_out, err = capture_io do _out, err = capture_io do
super super
rescue ActiveSupport::RaiseWarnings::WarningError
end end
assert_match(/Test is missing assertions: `test_without_assertions` .+test_without_assertions_test\.rb:\d+/, err) assert_match(/Test is missing assertions: `test_without_assertions` .+test_without_assertions_test\.rb:\d+/, err)

@ -124,6 +124,7 @@ def test_app_update_does_not_generate_unnecessary_bin_files
generator = Rails::Generators::AppGenerator.new ["rails"], generator = Rails::Generators::AppGenerator.new ["rails"],
{ api: true, update: true }, { destination_root: destination_root, shell: @shell } { api: true, update: true }, { destination_root: destination_root, shell: @shell }
quietly { generator.update_bin_files } quietly { generator.update_bin_files }
pass
end end
private private