diff options
Diffstat (limited to 'activesupport/test')
83 files changed, 2425 insertions, 1059 deletions
diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb index 8a67b148c3..65de48a7f6 100644 --- a/activesupport/test/abstract_unit.rb +++ b/activesupport/test/abstract_unit.rb @@ -8,18 +8,29 @@ ensure end require 'active_support/core_ext/kernel/reporting' -require 'active_support/core_ext/string/encoding' silence_warnings do Encoding.default_internal = "UTF-8" Encoding.default_external = "UTF-8" end -require 'minitest/autorun' +require 'active_support/testing/autorun' require 'empty_bool' ENV['NO_RELOAD'] = '1' require 'active_support' +Thread.abort_on_exception = true + # Show backtraces for deprecated behavior for quicker cleanup. ActiveSupport::Deprecation.debug = true + +# Skips the current run on Rubinius using Minitest::Assertions#skip +def rubinius_skip(message = '') + skip message if RUBY_ENGINE == 'rbx' +end + +# Skips the current run on JRuby using Minitest::Assertions#skip +def jruby_skip(message = '') + skip message if RUBY_ENGINE == 'jruby' +end diff --git a/activesupport/test/autoloading_fixtures/html/some_class.rb b/activesupport/test/autoloading_fixtures/html/some_class.rb new file mode 100644 index 0000000000..b43d15d891 --- /dev/null +++ b/activesupport/test/autoloading_fixtures/html/some_class.rb @@ -0,0 +1,4 @@ +module HTML + class SomeClass + end +end diff --git a/activesupport/test/autoloading_fixtures/should_not_be_required.rb b/activesupport/test/autoloading_fixtures/should_not_be_required.rb new file mode 100644 index 0000000000..1fcf170cc5 --- /dev/null +++ b/activesupport/test/autoloading_fixtures/should_not_be_required.rb @@ -0,0 +1 @@ +ShouldNotBeAutoloaded = 0 diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index 9f76f4c90b..51007402a1 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -1,6 +1,7 @@ require 'logger' require 'abstract_unit' require 'active_support/cache' +require 'dependencies_test_helpers' class CacheKeyTest < ActiveSupport::TestCase def test_entry_legacy_optional_ivars @@ -83,7 +84,7 @@ class CacheKeyTest < ActiveSupport::TestCase def test_expand_cache_key_of_true assert_equal 'true', ActiveSupport::Cache.expand_cache_key(true) end - + def test_expand_cache_key_of_array_like_object assert_equal 'foo/bar/baz', ActiveSupport::Cache.expand_cache_key(%w{foo bar baz}.to_enum) end @@ -197,6 +198,16 @@ module CacheStoreBehavior assert_equal 'baz', @cache.fetch('foo') { 'baz' } end + def test_fetch_with_cache_miss_passes_key_to_block + cache_miss = false + assert_equal 3, @cache.fetch('foo') { |key| cache_miss = true; key.length } + assert cache_miss + + cache_miss = false + assert_equal 3, @cache.fetch('foo') { |key| cache_miss = true; key.length } + assert !cache_miss + end + def test_fetch_with_forced_cache_miss @cache.write('foo', 'bar') @cache.expects(:read).never @@ -246,6 +257,26 @@ module CacheStoreBehavior assert_equal({"fu" => "baz"}, @cache.read_multi('foo', 'fu')) end + def test_fetch_multi + @cache.write('foo', 'bar') + @cache.write('fud', 'biz') + + values = @cache.fetch_multi('foo', 'fu', 'fud') {|value| value * 2 } + + assert_equal(["bar", "fufu", "biz"], values) + assert_equal("fufu", @cache.read('fu')) + end + + def test_multi_with_objects + foo = stub(:title => "FOO!", :cache_key => "foo") + bar = stub(:cache_key => "bar") + + @cache.write('bar', "BAM!") + + values = @cache.fetch_multi(foo, bar) {|object| object.title } + assert_equal(["FOO!", "BAM!"], values) + end + def test_read_and_write_compressed_small_data @cache.write('foo', 'bar', :compress => true) assert_equal 'bar', @cache.read('foo') @@ -296,8 +327,8 @@ module CacheStoreBehavior def test_exist @cache.write('foo', 'bar') - assert @cache.exist?('foo') - assert !@cache.exist?('bar') + assert_equal true, @cache.exist?('foo') + assert_equal false, @cache.exist?('bar') end def test_nil_exist @@ -394,7 +425,7 @@ module CacheStoreBehavior end # https://rails.lighthouseapp.com/projects/8994/tickets/6225-memcachestore-cant-deal-with-umlauts-and-special-characters -# The error is caused by charcter encodings that can't be compared with ASCII-8BIT regular expressions and by special +# The error is caused by character encodings that can't be compared with ASCII-8BIT regular expressions and by special # characters like the umlaut in UTF-8. module EncodedKeyCacheBehavior Encoding.list.each do |encoding| @@ -552,6 +583,45 @@ module LocalCacheBehavior end end +module AutoloadingCacheBehavior + include DependenciesTestHelpers + def test_simple_autoloading + with_autoloading_fixtures do + @cache.write('foo', E.new) + end + + remove_constants(:E) + ActiveSupport::Dependencies.clear + + with_autoloading_fixtures do + assert_kind_of E, @cache.read('foo') + end + + remove_constants(:E) + ActiveSupport::Dependencies.clear + end + + def test_two_classes_autoloading + with_autoloading_fixtures do + @cache.write('foo', [E.new, ClassFolder.new]) + end + + remove_constants(:E, :ClassFolder) + ActiveSupport::Dependencies.clear + + with_autoloading_fixtures do + loaded = @cache.read('foo') + assert_kind_of Array, loaded + assert_equal 2, loaded.size + assert_kind_of E, loaded[0] + assert_kind_of ClassFolder, loaded[1] + end + + remove_constants(:E, :ClassFolder) + ActiveSupport::Dependencies.clear + end +end + class FileStoreTest < ActiveSupport::TestCase def setup Dir.mkdir(cache_dir) unless File.exist?(cache_dir) @@ -575,6 +645,7 @@ class FileStoreTest < ActiveSupport::TestCase include LocalCacheBehavior include CacheDeleteMatchedBehavior include CacheIncrementDecrementBehavior + include AutoloadingCacheBehavior def test_clear filepath = File.join(cache_dir, ".gitkeep") @@ -594,7 +665,7 @@ class FileStoreTest < ActiveSupport::TestCase assert_equal "views/index?id=1", @cache_with_pathname.send(:file_path_key, key) end - # Test that generated cache keys are short enough to have Tempfile stuff added to them and + # Test that generated cache keys are short enough to have Tempfile stuff added to them and # remain valid def test_filename_max_size key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}" @@ -621,17 +692,48 @@ class FileStoreTest < ActiveSupport::TestCase end end + def test_delete_does_not_delete_empty_parent_dir + sub_cache_dir = File.join(cache_dir, 'subdir/') + sub_cache_store = ActiveSupport::Cache::FileStore.new(sub_cache_dir) + assert_nothing_raised(Exception) do + assert sub_cache_store.write('foo', 'bar') + assert sub_cache_store.delete('foo') + end + assert File.exist?(cache_dir), "Parent of top level cache dir was deleted!" + assert File.exist?(sub_cache_dir), "Top level cache dir was deleted!" + assert Dir.entries(sub_cache_dir).reject {|f| ActiveSupport::Cache::FileStore::EXCLUDED_DIRS.include?(f)}.empty? + end + def test_log_exception_when_cache_read_fails File.expects(:exist?).raises(StandardError, "failed") @cache.send(:read_entry, "winston", {}) - assert_present @buffer.string + assert @buffer.string.present? + end + + def test_cleanup_removes_all_expired_entries + time = Time.now + @cache.write('foo', 'bar', expires_in: 10) + @cache.write('baz', 'qux') + @cache.write('quux', 'corge', expires_in: 20) + Time.stubs(:now).returns(time + 15) + @cache.cleanup + assert_not @cache.exist?('foo') + assert @cache.exist?('baz') + assert @cache.exist?('quux') + end + + def test_write_with_unless_exist + assert_equal true, @cache.write(1, "aaaaaaaaaa") + assert_equal false, @cache.write(1, "aaaaaaaaaa", unless_exist: true) + @cache.write(1, nil) + assert_equal false, @cache.write(1, "aaaaaaaaaa", unless_exist: true) end end class MemoryStoreTest < ActiveSupport::TestCase def setup - @record_size = ActiveSupport::Cache::Entry.new("aaaaaaaaaa").size - @cache = ActiveSupport::Cache.lookup_store(:memory_store, :expires_in => 60, :size => @record_size * 10) + @record_size = ActiveSupport::Cache.lookup_store(:memory_store).send(:cached_size, 1, ActiveSupport::Cache::Entry.new("aaaaaaaaaa")) + @cache = ActiveSupport::Cache.lookup_store(:memory_store, :expires_in => 60, :size => @record_size * 10 + 1) end include CacheStoreBehavior @@ -681,6 +783,30 @@ class MemoryStoreTest < ActiveSupport::TestCase assert !@cache.exist?(1), "no entry" end + def test_prune_size_on_write_based_on_key_length + @cache.write(1, "aaaaaaaaaa") && sleep(0.001) + @cache.write(2, "bbbbbbbbbb") && sleep(0.001) + @cache.write(3, "cccccccccc") && sleep(0.001) + @cache.write(4, "dddddddddd") && sleep(0.001) + @cache.write(5, "eeeeeeeeee") && sleep(0.001) + @cache.write(6, "ffffffffff") && sleep(0.001) + @cache.write(7, "gggggggggg") && sleep(0.001) + @cache.write(8, "hhhhhhhhhh") && sleep(0.001) + @cache.write(9, "iiiiiiiiii") && sleep(0.001) + long_key = '*' * 2 * @record_size + @cache.write(long_key, "llllllllll") + assert @cache.exist?(long_key) + assert @cache.exist?(9) + assert @cache.exist?(8) + assert @cache.exist?(7) + assert @cache.exist?(6) + assert !@cache.exist?(5), "no entry" + assert !@cache.exist?(4), "no entry" + assert !@cache.exist?(3), "no entry" + assert !@cache.exist?(2), "no entry" + assert !@cache.exist?(1), "no entry" + end + def test_pruning_is_capped_at_a_max_time def @cache.delete_entry (*args) sleep(0.01) @@ -735,6 +861,7 @@ class MemCacheStoreTest < ActiveSupport::TestCase include LocalCacheBehavior include CacheIncrementDecrementBehavior include EncodedKeyCacheBehavior + include AutoloadingCacheBehavior def test_raw_values cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :raw => true) @@ -845,12 +972,12 @@ class CacheStoreLoggerTest < ActiveSupport::TestCase def test_logging @cache.fetch('foo') { 'bar' } - assert_present @buffer.string + assert @buffer.string.present? end def test_mute_logging @cache.mute { @cache.fetch('foo') { 'bar' } } - assert_blank @buffer.string + assert @buffer.string.blank? end end @@ -879,29 +1006,28 @@ class CacheEntryTest < ActiveSupport::TestCase assert_equal value.bytesize, entry.size end - def test_restoring_version_3_entries - version_3_entry = ActiveSupport::Cache::Entry.allocate - version_3_entry.instance_variable_set(:@value, "hello") - version_3_entry.instance_variable_set(:@created_at, Time.now - 60) - entry = Marshal.load(Marshal.dump(version_3_entry)) + def test_restoring_version_4beta1_entries + version_4beta1_entry = ActiveSupport::Cache::Entry.allocate + version_4beta1_entry.instance_variable_set(:@v, "hello") + version_4beta1_entry.instance_variable_set(:@x, Time.now.to_i + 60) + entry = Marshal.load(Marshal.dump(version_4beta1_entry)) assert_equal "hello", entry.value assert_equal false, entry.expired? end - def test_restoring_compressed_version_3_entries - version_3_entry = ActiveSupport::Cache::Entry.allocate - version_3_entry.instance_variable_set(:@value, Zlib::Deflate.deflate(Marshal.dump("hello"))) - version_3_entry.instance_variable_set(:@compressed, true) - entry = Marshal.load(Marshal.dump(version_3_entry)) + def test_restoring_compressed_version_4beta1_entries + version_4beta1_entry = ActiveSupport::Cache::Entry.allocate + version_4beta1_entry.instance_variable_set(:@v, Zlib::Deflate.deflate(Marshal.dump("hello"))) + version_4beta1_entry.instance_variable_set(:@c, true) + entry = Marshal.load(Marshal.dump(version_4beta1_entry)) assert_equal "hello", entry.value end - def test_restoring_expired_version_3_entries - version_3_entry = ActiveSupport::Cache::Entry.allocate - version_3_entry.instance_variable_set(:@value, "hello") - version_3_entry.instance_variable_set(:@created_at, Time.now - 60) - version_3_entry.instance_variable_set(:@expires_in, 58.9) - entry = Marshal.load(Marshal.dump(version_3_entry)) + def test_restoring_expired_version_4beta1_entries + version_4beta1_entry = ActiveSupport::Cache::Entry.allocate + version_4beta1_entry.instance_variable_set(:@v, "hello") + version_4beta1_entry.instance_variable_set(:@x, Time.now.to_i - 1) + entry = Marshal.load(Marshal.dump(version_4beta1_entry)) assert_equal "hello", entry.value assert_equal true, entry.expired? end diff --git a/activesupport/test/callback_inheritance_test.rb b/activesupport/test/callback_inheritance_test.rb index 6be8ea8b84..1adfe4edf4 100644 --- a/activesupport/test/callback_inheritance_test.rb +++ b/activesupport/test/callback_inheritance_test.rb @@ -109,7 +109,6 @@ class BasicCallbacksTest < ActiveSupport::TestCase @index = GrandParent.new("index").dispatch @update = GrandParent.new("update").dispatch @delete = GrandParent.new("delete").dispatch - @unknown = GrandParent.new("unknown").dispatch end def test_basic_conditional_callback1 @@ -130,7 +129,6 @@ class InheritedCallbacksTest < ActiveSupport::TestCase @index = Parent.new("index").dispatch @update = Parent.new("update").dispatch @delete = Parent.new("delete").dispatch - @unknown = Parent.new("unknown").dispatch end def test_inherited_excluded diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb index 8810302f40..f8e2ce22fa 100644 --- a/activesupport/test/callbacks_test.rb +++ b/activesupport/test/callbacks_test.rb @@ -66,6 +66,16 @@ module CallbacksTest end end + class CallbackClass + def self.before(model) + model.history << [:before_save, :class] + end + + def self.after(model) + model.history << [:after_save, :class] + end + end + class Person < Record [:before_save, :after_save].each do |callback_method| callback_method_sym = callback_method.to_sym @@ -73,6 +83,7 @@ module CallbacksTest send(callback_method, callback_string(callback_method_sym)) send(callback_method, callback_proc(callback_method_sym)) send(callback_method, callback_object(callback_method_sym.to_s.gsub(/_save/, ''))) + send(callback_method, CallbackClass) send(callback_method) { |model| model.history << [callback_method_sym, :block] } end @@ -86,10 +97,14 @@ module CallbacksTest skip_callback :save, :after, :before_save_method, :unless => :yes skip_callback :save, :after, :before_save_method, :if => :no skip_callback :save, :before, :before_save_method, :unless => :no + skip_callback :save, :before, CallbackClass , :if => :yes def yes; true; end def no; false; end end + class PersonForProgrammaticSkipping < Person + end + class ParentController include ActiveSupport::Callbacks @@ -297,7 +312,7 @@ module CallbacksTest end end end - + class AroundPersonResult < MySuper attr_reader :result @@ -308,7 +323,7 @@ module CallbacksTest def tweedle_dum @result = yield end - + def tweedle_1 :tweedle_1 end @@ -316,7 +331,7 @@ module CallbacksTest def tweedle_2 :tweedle_2 end - + def save run_callbacks :save do :running @@ -410,7 +425,7 @@ module CallbacksTest ], around.history end end - + class AroundCallbackResultTest < ActiveSupport::TestCase def test_save_around around = AroundPersonResult.new @@ -430,6 +445,26 @@ module CallbacksTest [:before_save, :object], [:before_save, :block], [:after_save, :block], + [:after_save, :class], + [:after_save, :object], + [:after_save, :proc], + [:after_save, :string], + [:after_save, :symbol] + ], person.history + end + + def test_skip_person_programmatically + PersonForProgrammaticSkipping._save_callbacks.each do |save_callback| + if "before" == save_callback.kind.to_s + PersonForProgrammaticSkipping.skip_callback("save", save_callback.kind, save_callback.filter) + end + end + person = PersonForProgrammaticSkipping.new + assert_equal [], person.history + person.save + assert_equal [ + [:after_save, :block], + [:after_save, :class], [:after_save, :object], [:after_save, :proc], [:after_save, :string], @@ -449,8 +484,10 @@ module CallbacksTest [:before_save, :string], [:before_save, :proc], [:before_save, :object], + [:before_save, :class], [:before_save, :block], [:after_save, :block], + [:after_save, :class], [:after_save, :object], [:after_save, :proc], [:after_save, :string], @@ -488,7 +525,7 @@ module CallbacksTest class CallbackTerminator include ActiveSupport::Callbacks - define_callbacks :save, :terminator => "result == :halt" + define_callbacks :save, :terminator => ->(_,result) { result == :halt } set_callback :save, :before, :first set_callback :save, :before, :second @@ -607,6 +644,45 @@ module CallbacksTest end end + class OneTwoThreeSave + include ActiveSupport::Callbacks + + define_callbacks :save + + attr_accessor :record + + def initialize + @record = [] + end + + def save + run_callbacks :save do + @record << "yielded" + end + end + + def first + @record << "one" + end + + def second + @record << "two" + end + + def third + @record << "three" + end + end + + class DuplicatingCallbacks < OneTwoThreeSave + set_callback :save, :before, :first, :second + set_callback :save, :before, :first, :third + end + + class DuplicatingCallbacksInSameCall < OneTwoThreeSave + set_callback :save, :before, :first, :second, :first, :third + end + class UsingObjectTest < ActiveSupport::TestCase def test_before_object u = UsingObjectBefore.new @@ -642,7 +718,7 @@ module CallbacksTest def test_termination_invokes_hook terminator = CallbackTerminator.new terminator.save - assert_equal ":second", terminator.halted + assert_equal :second, terminator.halted end def test_block_never_called_if_terminated @@ -676,8 +752,10 @@ module CallbacksTest [:before_save, :string], [:before_save, :proc], [:before_save, :object], + [:before_save, :class], [:before_save, :block], [:after_save, :block], + [:after_save, :class], [:after_save, :object], [:after_save, :proc], [:after_save, :string], @@ -694,20 +772,253 @@ module CallbacksTest end end - class PerKeyOptionDeprecationTest < ActiveSupport::TestCase + class ExcludingDuplicatesCallbackTest < ActiveSupport::TestCase + def test_excludes_duplicates_in_separate_calls + model = DuplicatingCallbacks.new + model.save + assert_equal ["two", "one", "three", "yielded"], model.record + end - def test_per_key_option_deprecaton - assert_raise NotImplementedError do - Phone.class_eval do - set_callback :save, :before, :before_save1, :per_key => {:if => "true"} - end + def test_excludes_duplicates_in_one_call + model = DuplicatingCallbacksInSameCall.new + model.save + assert_equal ["two", "one", "three", "yielded"], model.record + end + end + + class CallbackProcTest < ActiveSupport::TestCase + def build_class(callback) + Class.new { + include ActiveSupport::Callbacks + define_callbacks :foo + set_callback :foo, :before, callback + def run; run_callbacks :foo; end + } + end + + def test_proc_arity_0 + calls = [] + klass = build_class(->() { calls << :foo }) + klass.new.run + assert_equal [:foo], calls + end + + def test_proc_arity_1 + calls = [] + klass = build_class(->(o) { calls << o }) + instance = klass.new + instance.run + assert_equal [instance], calls + end + + def test_proc_arity_2 + assert_raises(ArgumentError) do + klass = build_class(->(x,y) { }) + klass.new.run end - assert_raise NotImplementedError do - Phone.class_eval do - skip_callback :save, :before, :before_save1, :per_key => {:if => "true"} - end + end + + def test_proc_negative_called_with_empty_list + calls = [] + klass = build_class(->(*args) { calls << args }) + klass.new.run + assert_equal [[]], calls + end + end + + class ConditionalTests < ActiveSupport::TestCase + def build_class(callback) + Class.new { + include ActiveSupport::Callbacks + define_callbacks :foo + set_callback :foo, :before, :foo, :if => callback + def foo; end + def run; run_callbacks :foo; end + } + end + + # FIXME: do we really want to support classes as conditionals? There were + # no tests for it previous to this. + def test_class_conditional_with_scope + z = [] + callback = Class.new { + define_singleton_method(:foo) { |o| z << o } + } + klass = Class.new { + include ActiveSupport::Callbacks + define_callbacks :foo, :scope => [:name] + set_callback :foo, :before, :foo, :if => callback + def run; run_callbacks :foo; end + private + def foo; end + } + object = klass.new + object.run + assert_equal [object], z + end + + # FIXME: do we really want to support classes as conditionals? There were + # no tests for it previous to this. + def test_class + z = [] + klass = build_class Class.new { + define_singleton_method(:before) { |o| z << o } + } + object = klass.new + object.run + assert_equal [object], z + end + + def test_proc_negative_arity # passes an empty list if *args + z = [] + object = build_class(->(*args) { z << args }).new + object.run + assert_equal [], z.flatten + end + + def test_proc_arity0 + z = [] + object = build_class(->() { z << 0 }).new + object.run + assert_equal [0], z + end + + def test_proc_arity1 + z = [] + object = build_class(->(x) { z << x }).new + object.run + assert_equal [object], z + end + + def test_proc_arity2 + assert_raises(ArgumentError) do + object = build_class(->(a,b) { }).new + object.run end end end - + + class ResetCallbackTest < ActiveSupport::TestCase + def build_class(memo) + klass = Class.new { + include ActiveSupport::Callbacks + define_callbacks :foo + set_callback :foo, :before, :hello + def run; run_callbacks :foo; end + } + klass.class_eval { + define_method(:hello) { memo << :hi } + } + klass + end + + def test_reset_callbacks + events = [] + klass = build_class events + klass.new.run + assert_equal 1, events.length + + klass.reset_callbacks :foo + klass.new.run + assert_equal 1, events.length + end + + def test_reset_impacts_subclasses + events = [] + klass = build_class events + subclass = Class.new(klass) { set_callback :foo, :before, :world } + subclass.class_eval { define_method(:world) { events << :world } } + + subclass.new.run + assert_equal 2, events.length + + klass.reset_callbacks :foo + subclass.new.run + assert_equal 3, events.length + end + end + + class CallbackTypeTest < ActiveSupport::TestCase + def build_class(callback, n = 10) + Class.new { + include ActiveSupport::Callbacks + define_callbacks :foo + n.times { set_callback :foo, :before, callback } + def run; run_callbacks :foo; end + def self.skip(thing); skip_callback :foo, :before, thing; end + } + end + + def test_add_class + calls = [] + callback = Class.new { + define_singleton_method(:before) { |o| calls << o } + } + build_class(callback).new.run + assert_equal 10, calls.length + end + + def test_add_lambda + calls = [] + build_class(->(o) { calls << o }).new.run + assert_equal 10, calls.length + end + + def test_add_symbol + calls = [] + klass = build_class(:bar) + klass.class_eval { define_method(:bar) { calls << klass } } + klass.new.run + assert_equal 1, calls.length + end + + def test_add_eval + calls = [] + klass = build_class("bar") + klass.class_eval { define_method(:bar) { calls << klass } } + klass.new.run + assert_equal 1, calls.length + end + + def test_skip_class # removes one at a time + calls = [] + callback = Class.new { + define_singleton_method(:before) { |o| calls << o } + } + klass = build_class(callback) + 9.downto(0) { |i| + klass.skip callback + klass.new.run + assert_equal i, calls.length + calls.clear + } + end + + def test_skip_lambda # removes nothing + calls = [] + callback = ->(o) { calls << o } + klass = build_class(callback) + 10.times { klass.skip callback } + klass.new.run + assert_equal 10, calls.length + end + + def test_skip_symbol # removes all + calls = [] + klass = build_class(:bar) + klass.class_eval { define_method(:bar) { calls << klass } } + klass.skip :bar + klass.new.run + assert_equal 0, calls.length + end + + def test_skip_eval # removes nothing + calls = [] + klass = build_class("bar") + klass.class_eval { define_method(:bar) { calls << klass } } + klass.skip "bar" + klass.new.run + assert_equal 1, calls.length + end + end end diff --git a/activesupport/test/clean_backtrace_test.rb b/activesupport/test/clean_backtrace_test.rb index b14950acb3..dd67a45cf6 100644 --- a/activesupport/test/clean_backtrace_test.rb +++ b/activesupport/test/clean_backtrace_test.rb @@ -36,6 +36,27 @@ class BacktraceCleanerSilencerTest < ActiveSupport::TestCase end end +class BacktraceCleanerMultipleSilencersTest < ActiveSupport::TestCase + def setup + @bc = ActiveSupport::BacktraceCleaner.new + @bc.add_silencer { |line| line =~ /mongrel/ } + @bc.add_silencer { |line| line =~ /yolo/ } + end + + test "backtrace should not contain lines that match the silencers" do + assert_equal \ + [ "/other/class.rb" ], + @bc.clean([ "/mongrel/class.rb", "/other/class.rb", "/mongrel/stuff.rb", "/other/yolo.rb" ]) + end + + test "backtrace should only contain lines that match the silencers" do + assert_equal \ + [ "/mongrel/class.rb", "/mongrel/stuff.rb", "/other/yolo.rb" ], + @bc.clean([ "/mongrel/class.rb", "/other/class.rb", "/mongrel/stuff.rb", "/other/yolo.rb" ], + :noise) + end +end + class BacktraceCleanerFilterAndSilencerTest < ActiveSupport::TestCase def setup @bc = ActiveSupport::BacktraceCleaner.new diff --git a/activesupport/test/concern_test.rb b/activesupport/test/concern_test.rb index 912ce30c29..a74ee880b2 100644 --- a/activesupport/test/concern_test.rb +++ b/activesupport/test/concern_test.rb @@ -56,10 +56,6 @@ class ConcernTest < ActiveSupport::TestCase @klass.send(:include, Baz) assert_equal "baz", @klass.new.baz assert @klass.included_modules.include?(ConcernTest::Baz) - - @klass.send(:include, Baz) - assert_equal "baz", @klass.new.baz - assert @klass.included_modules.include?(ConcernTest::Baz) end def test_class_methods_are_extended @@ -68,12 +64,6 @@ class ConcernTest < ActiveSupport::TestCase assert_equal ConcernTest::Baz::ClassMethods, (class << @klass; self.included_modules; end)[0] end - def test_instance_methods_are_included - @klass.send(:include, Baz) - assert_equal "baz", @klass.new.baz - assert @klass.included_modules.include?(ConcernTest::Baz) - end - def test_included_block_is_ran @klass.send(:include, Baz) assert_equal true, @klass.included_ran @@ -91,4 +81,18 @@ class ConcernTest < ActiveSupport::TestCase @klass.send(:include, Foo) assert_equal [ConcernTest::Foo, ConcernTest::Bar, ConcernTest::Baz], @klass.included_modules[0..2] end + + def test_raise_on_multiple_included_calls + assert_raises(ActiveSupport::Concern::MultipleIncludedBlocks) do + Module.new do + extend ActiveSupport::Concern + + included do + end + + included do + end + end + end + end end diff --git a/activesupport/test/configurable_test.rb b/activesupport/test/configurable_test.rb index 215a6e06b0..d00273a028 100644 --- a/activesupport/test/configurable_test.rb +++ b/activesupport/test/configurable_test.rb @@ -38,7 +38,7 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase assert_equal :bar, Parent.config.foo end - test "configuration accessors is not available on instance" do + test "configuration accessors are not available on instance" do instance = Parent.new assert !instance.respond_to?(:bar) diff --git a/activesupport/test/constantize_test_cases.rb b/activesupport/test/constantize_test_cases.rb index ec05213409..bbeb710a0c 100644 --- a/activesupport/test/constantize_test_cases.rb +++ b/activesupport/test/constantize_test_cases.rb @@ -24,52 +24,52 @@ end module ConstantizeTestCases def run_constantize_tests_on - assert_nothing_raised { assert_equal Ace::Base::Case, yield("Ace::Base::Case") } - assert_nothing_raised { assert_equal Ace::Base::Case, yield("::Ace::Base::Case") } - assert_nothing_raised { assert_equal Ace::Base::Case::Dice, yield("Ace::Base::Case::Dice") } - assert_nothing_raised { assert_equal Ace::Base::Fase::Dice, yield("Ace::Base::Fase::Dice") } - assert_nothing_raised { assert_equal Ace::Gas::Case, yield("Ace::Gas::Case") } - assert_nothing_raised { assert_equal Ace::Gas::Case::Dice, yield("Ace::Gas::Case::Dice") } - assert_nothing_raised { assert_equal Case::Dice, yield("Case::Dice") } - assert_nothing_raised { assert_equal Case::Dice, yield("Object::Case::Dice") } - assert_nothing_raised { assert_equal ConstantizeTestCases, yield("ConstantizeTestCases") } - assert_nothing_raised { assert_equal ConstantizeTestCases, yield("::ConstantizeTestCases") } - assert_nothing_raised { assert_equal Object, yield("") } - assert_nothing_raised { assert_equal Object, yield("::") } - assert_raise(NameError) { yield("UnknownClass") } - assert_raise(NameError) { yield("UnknownClass::Ace") } - assert_raise(NameError) { yield("UnknownClass::Ace::Base") } - assert_raise(NameError) { yield("An invalid string") } - assert_raise(NameError) { yield("InvalidClass\n") } - assert_raise(NameError) { yield("Ace::ConstantizeTestCases") } - assert_raise(NameError) { yield("Ace::Base::ConstantizeTestCases") } - assert_raise(NameError) { yield("Ace::Gas::Base") } - assert_raise(NameError) { yield("Ace::Gas::ConstantizeTestCases") } + assert_equal Ace::Base::Case, yield("Ace::Base::Case") + assert_equal Ace::Base::Case, yield("::Ace::Base::Case") + assert_equal Ace::Base::Case::Dice, yield("Ace::Base::Case::Dice") + assert_equal Ace::Base::Fase::Dice, yield("Ace::Base::Fase::Dice") + assert_equal Ace::Gas::Case, yield("Ace::Gas::Case") + assert_equal Ace::Gas::Case::Dice, yield("Ace::Gas::Case::Dice") + assert_equal Case::Dice, yield("Case::Dice") + assert_equal Case::Dice, yield("Object::Case::Dice") + assert_equal ConstantizeTestCases, yield("ConstantizeTestCases") + assert_equal ConstantizeTestCases, yield("::ConstantizeTestCases") + assert_raises(NameError) { yield("UnknownClass") } + assert_raises(NameError) { yield("UnknownClass::Ace") } + assert_raises(NameError) { yield("UnknownClass::Ace::Base") } + assert_raises(NameError) { yield("An invalid string") } + assert_raises(NameError) { yield("InvalidClass\n") } + assert_raises(NameError) { yield("Ace::ConstantizeTestCases") } + assert_raises(NameError) { yield("Ace::Base::ConstantizeTestCases") } + assert_raises(NameError) { yield("Ace::Gas::Base") } + assert_raises(NameError) { yield("Ace::Gas::ConstantizeTestCases") } + assert_raises(NameError) { yield("") } + assert_raises(NameError) { yield("::") } end def run_safe_constantize_tests_on - assert_nothing_raised { assert_equal Ace::Base::Case, yield("Ace::Base::Case") } - assert_nothing_raised { assert_equal Ace::Base::Case, yield("::Ace::Base::Case") } - assert_nothing_raised { assert_equal Ace::Base::Case::Dice, yield("Ace::Base::Case::Dice") } - assert_nothing_raised { assert_equal Ace::Base::Fase::Dice, yield("Ace::Base::Fase::Dice") } - assert_nothing_raised { assert_equal Ace::Gas::Case, yield("Ace::Gas::Case") } - assert_nothing_raised { assert_equal Ace::Gas::Case::Dice, yield("Ace::Gas::Case::Dice") } - assert_nothing_raised { assert_equal Case::Dice, yield("Case::Dice") } - assert_nothing_raised { assert_equal Case::Dice, yield("Object::Case::Dice") } - assert_nothing_raised { assert_equal ConstantizeTestCases, yield("ConstantizeTestCases") } - assert_nothing_raised { assert_equal ConstantizeTestCases, yield("::ConstantizeTestCases") } - assert_nothing_raised { assert_equal Object, yield("") } - assert_nothing_raised { assert_equal Object, yield("::") } - assert_nothing_raised { assert_equal nil, yield("UnknownClass") } - assert_nothing_raised { assert_equal nil, yield("UnknownClass::Ace") } - assert_nothing_raised { assert_equal nil, yield("UnknownClass::Ace::Base") } - assert_nothing_raised { assert_equal nil, yield("An invalid string") } - assert_nothing_raised { assert_equal nil, yield("InvalidClass\n") } - assert_nothing_raised { assert_equal nil, yield("blargle") } - assert_nothing_raised { assert_equal nil, yield("Ace::ConstantizeTestCases") } - assert_nothing_raised { assert_equal nil, yield("Ace::Base::ConstantizeTestCases") } - assert_nothing_raised { assert_equal nil, yield("Ace::Gas::Base") } - assert_nothing_raised { assert_equal nil, yield("Ace::Gas::ConstantizeTestCases") } - assert_nothing_raised { assert_equal nil, yield("#<Class:0x7b8b718b>::Nested_1") } + assert_equal Ace::Base::Case, yield("Ace::Base::Case") + assert_equal Ace::Base::Case, yield("::Ace::Base::Case") + assert_equal Ace::Base::Case::Dice, yield("Ace::Base::Case::Dice") + assert_equal Ace::Base::Fase::Dice, yield("Ace::Base::Fase::Dice") + assert_equal Ace::Gas::Case, yield("Ace::Gas::Case") + assert_equal Ace::Gas::Case::Dice, yield("Ace::Gas::Case::Dice") + assert_equal Case::Dice, yield("Case::Dice") + assert_equal Case::Dice, yield("Object::Case::Dice") + assert_equal ConstantizeTestCases, yield("ConstantizeTestCases") + assert_equal ConstantizeTestCases, yield("::ConstantizeTestCases") + assert_nil yield("") + assert_nil yield("::") + assert_nil yield("UnknownClass") + assert_nil yield("UnknownClass::Ace") + assert_nil yield("UnknownClass::Ace::Base") + assert_nil yield("An invalid string") + assert_nil yield("InvalidClass\n") + assert_nil yield("blargle") + assert_nil yield("Ace::ConstantizeTestCases") + assert_nil yield("Ace::Base::ConstantizeTestCases") + assert_nil yield("Ace::Gas::Base") + assert_nil yield("Ace::Gas::ConstantizeTestCases") + assert_nil yield("#<Class:0x7b8b718b>::Nested_1") end end diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb index 0b33a63460..6cd0eb39b7 100644 --- a/activesupport/test/core_ext/array_ext_test.rb +++ b/activesupport/test/core_ext/array_ext_test.rb @@ -1,6 +1,7 @@ require 'abstract_unit' require 'active_support/core_ext/array' require 'active_support/core_ext/big_decimal' +require 'active_support/core_ext/object/conversions' require 'active_support/core_ext' # FIXME: pulling in all to_xml extensions require 'active_support/hash_with_indifferent_access' @@ -95,6 +96,10 @@ class ArrayExtToSentenceTests < ActiveSupport::TestCase assert_equal "one two, and three", ['one', 'two', 'three'].to_sentence(options) assert_equal({ words_connector: ' ' }, options) end + + def test_with_blank_elements + assert_equal ", one, , two, and three", [nil, 'one', '', 'two', 'three'].to_sentence + end end class ArrayExtToSTests < ActiveSupport::TestCase @@ -111,6 +116,14 @@ class ArrayExtToSTests < ActiveSupport::TestCase end class ArrayExtGroupingTests < ActiveSupport::TestCase + def setup + Fixnum.send :private, :/ # test we avoid Integer#/ (redefined by mathn) + end + + def teardown + Fixnum.send :public, :/ + end + def test_in_groups_of_with_perfect_fit groups = [] ('a'..'i').to_a.in_groups_of(3) do |group| @@ -346,36 +359,6 @@ class ArrayExtractOptionsTests < ActiveSupport::TestCase end end -class ArrayUniqByTests < ActiveSupport::TestCase - def test_uniq_by - ActiveSupport::Deprecation.silence do - assert_equal [1,2], [1,2,3,4].uniq_by { |i| i.odd? } - assert_equal [1,2], [1,2,3,4].uniq_by(&:even?) - assert_equal((-5..0).to_a, (-5..5).to_a.uniq_by{ |i| i**2 }) - end - end - - def test_uniq_by! - a = [1,2,3,4] - ActiveSupport::Deprecation.silence do - a.uniq_by! { |i| i.odd? } - end - assert_equal [1,2], a - - a = [1,2,3,4] - ActiveSupport::Deprecation.silence do - a.uniq_by! { |i| i.even? } - end - assert_equal [1,2], a - - a = (-5..5).to_a - ActiveSupport::Deprecation.silence do - a.uniq_by! { |i| i**2 } - end - assert_equal((-5..0).to_a, a) - end -end - class ArrayWrapperTests < ActiveSupport::TestCase class FakeCollection def to_ary diff --git a/activesupport/test/core_ext/bigdecimal_test.rb b/activesupport/test/core_ext/bigdecimal_test.rb index a5987044b9..b386e55d6c 100644 --- a/activesupport/test/core_ext/bigdecimal_test.rb +++ b/activesupport/test/core_ext/bigdecimal_test.rb @@ -1,5 +1,4 @@ require 'abstract_unit' -require 'bigdecimal' require 'active_support/core_ext/big_decimal' class BigDecimalTest < ActiveSupport::TestCase diff --git a/activesupport/test/core_ext/class/attribute_accessor_test.rb b/activesupport/test/core_ext/class/attribute_accessor_test.rb index 8d827f054e..0d5f39a72b 100644 --- a/activesupport/test/core_ext/class/attribute_accessor_test.rb +++ b/activesupport/test/core_ext/class/attribute_accessor_test.rb @@ -44,16 +44,18 @@ class ClassAttributeAccessorTest < ActiveSupport::TestCase end def test_should_raise_name_error_if_attribute_name_is_invalid - assert_raises NameError do + exception = assert_raises NameError do Class.new do - cattr_reader "invalid attribute name" + cattr_reader "1nvalid" end end + assert_equal "invalid class attribute name: 1nvalid", exception.message - assert_raises NameError do + exception = assert_raises NameError do Class.new do - cattr_writer "invalid attribute name" + cattr_writer "1nvalid" end end + assert_equal "invalid class attribute name: 1nvalid", exception.message end end diff --git a/activesupport/test/core_ext/class/attribute_test.rb b/activesupport/test/core_ext/class/attribute_test.rb index 1c3ba8a7a0..e7a1334db3 100644 --- a/activesupport/test/core_ext/class/attribute_test.rb +++ b/activesupport/test/core_ext/class/attribute_test.rb @@ -27,7 +27,7 @@ class ClassAttributeTest < ActiveSupport::TestCase assert_equal 1, Class.new(@sub).setting end - test 'query method' do + test 'predicate method' do assert_equal false, @klass.setting? @klass.setting = 1 assert_equal true, @klass.setting? @@ -48,7 +48,7 @@ class ClassAttributeTest < ActiveSupport::TestCase assert_equal 1, object.setting end - test 'instance query' do + test 'instance predicate' do object = @klass.new assert_equal false, object.setting? object.setting = 1 @@ -73,6 +73,11 @@ class ClassAttributeTest < ActiveSupport::TestCase assert_raise(NoMethodError) { object.setting = 'boom' } end + test 'disabling instance predicate' do + object = Class.new { class_attribute :setting, instance_predicate: false }.new + assert_raise(NoMethodError) { object.setting? } + end + test 'works well with singleton classes' do object = @klass.new object.singleton_class.setting = 'foo' diff --git a/activesupport/test/core_ext/date_and_time_behavior.rb b/activesupport/test/core_ext/date_and_time_behavior.rb index 9927856aa2..b4ef5a0597 100644 --- a/activesupport/test/core_ext/date_and_time_behavior.rb +++ b/activesupport/test/core_ext/date_and_time_behavior.rb @@ -95,6 +95,11 @@ module DateAndTimeBehavior end def test_next_week + # M | T | W | T | F | S | S # M | T | W | T | F | S | S # + # | 22/2 | | | | | # 28/2 | | | | | | # monday in next week `next_week` + # | 22/2 | | | | | # | | | | 4/3 | | # friday in next week `next_week(:friday)` + # 23/10 | | | | | | # 30/10 | | | | | | # monday in next week `next_week` + # 23/10 | | | | | | # | | 1/11 | | | | # wednesday in next week `next_week(:wednesday)` assert_equal date_time_init(2005,2,28,0,0,0), date_time_init(2005,2,22,15,15,10).next_week assert_equal date_time_init(2005,3,4,0,0,0), date_time_init(2005,2,22,15,15,10).next_week(:friday) assert_equal date_time_init(2006,10,30,0,0,0), date_time_init(2006,10,23,0,0,0).next_week diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb index 7ae1f67785..eab3aa7a6e 100644 --- a/activesupport/test/core_ext/date_ext_test.rb +++ b/activesupport/test/core_ext/date_ext_test.rb @@ -25,6 +25,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase assert_equal "February 21st, 2005", date.to_s(:long_ordinal) assert_equal "2005-02-21", date.to_s(:db) assert_equal "21 Feb 2005", date.to_s(:rfc822) + assert_equal "2005-02-21", date.to_s(:iso8601) end def test_readable_inspect @@ -33,8 +34,12 @@ class DateExtCalculationsTest < ActiveSupport::TestCase end def test_to_time - assert_equal Time.local(2005, 2, 21), Date.new(2005, 2, 21).to_time - assert_equal Time.local_time(2039, 2, 21), Date.new(2039, 2, 21).to_time + with_env_tz 'US/Eastern' do + assert_equal Time, Date.new(2005, 2, 21).to_time.class + assert_equal Time.local(2005, 2, 21), Date.new(2005, 2, 21).to_time + assert_equal Time.local(2005, 2, 21).utc_offset, Date.new(2005, 2, 21).to_time.utc_offset + end + silence_warnings do 0.upto(138) do |year| [:utc, :local].each do |format| @@ -44,6 +49,10 @@ class DateExtCalculationsTest < ActiveSupport::TestCase end end + def test_compare_to_time + assert Date.yesterday < Time.now + end + def test_to_datetime assert_equal DateTime.civil(2005, 2, 21), Date.new(2005, 2, 21).to_datetime assert_equal 0, Date.new(2005, 2, 21).to_datetime.offset # use UTC offset @@ -239,6 +248,10 @@ class DateExtCalculationsTest < ActiveSupport::TestCase assert_equal Time.local(2005,2,21,0,0,0), Date.new(2005,2,21).beginning_of_day end + def test_middle_of_day + assert_equal Time.local(2005,2,21,12,0,0), Date.new(2005,2,21).middle_of_day + end + def test_beginning_of_day_when_zone_is_set zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] with_env_tz 'UTC' do @@ -354,3 +367,4 @@ class DateExtBehaviorTest < ActiveSupport::TestCase end end end + diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb index b1d1e8ecb4..0a40aeb96c 100644 --- a/activesupport/test/core_ext/date_time_ext_test.rb +++ b/activesupport/test/core_ext/date_time_ext_test.rb @@ -18,6 +18,12 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase assert_equal "Mon, 21 Feb 2005 14:30:00 +0000", datetime.to_s(:rfc822) assert_equal "February 21st, 2005 14:30", datetime.to_s(:long_ordinal) assert_match(/^2005-02-21T14:30:00(Z|\+00:00)$/, datetime.to_s) + + with_env_tz "US/Central" do + assert_equal "2009-02-05T14:30:05-06:00", DateTime.civil(2009, 2, 5, 14, 30, 5, Rational(-21600, 86400)).to_s(:iso8601) + assert_equal "2008-06-09T04:05:01-05:00", DateTime.civil(2008, 6, 9, 4, 5, 1, Rational(-18000, 86400)).to_s(:iso8601) + assert_equal "2009-02-05T14:30:05+00:00", DateTime.civil(2009, 2, 5, 14, 30, 5).to_s(:iso8601) + end end def test_readable_inspect @@ -41,11 +47,14 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase end def test_to_time - assert_equal Time.utc(2005, 2, 21, 10, 11, 12), DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time - assert_equal Time.utc_time(2039, 2, 21, 10, 11, 12), DateTime.new(2039, 2, 21, 10, 11, 12, 0).to_time - # DateTimes with offsets other than 0 are returned unaltered - assert_equal DateTime.new(2005, 2, 21, 10, 11, 12, Rational(-5, 24)), DateTime.new(2005, 2, 21, 10, 11, 12, Rational(-5, 24)).to_time - # Fractional seconds are preserved + with_env_tz 'US/Eastern' do + assert_equal Time, DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time.class + assert_equal Time.local(2005, 2, 21, 5, 11, 12), DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time + assert_equal Time.local(2005, 2, 21, 5, 11, 12).utc_offset, DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time.utc_offset + end + end + + def test_to_time_preserves_fractional_seconds assert_equal Time.utc(2005, 2, 21, 10, 11, 12, 256), DateTime.new(2005, 2, 21, 10, 11, 12 + Rational(256, 1000000), 0).to_time end @@ -61,10 +70,22 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase assert_equal 86399,DateTime.civil(2005,1,1,23,59,59).seconds_since_midnight end + def test_seconds_until_end_of_day + assert_equal 0, DateTime.civil(2005,1,1,23,59,59).seconds_until_end_of_day + assert_equal 1, DateTime.civil(2005,1,1,23,59,58).seconds_until_end_of_day + assert_equal 60, DateTime.civil(2005,1,1,23,58,59).seconds_until_end_of_day + assert_equal 3660, DateTime.civil(2005,1,1,22,58,59).seconds_until_end_of_day + assert_equal 86399, DateTime.civil(2005,1,1,0,0,0).seconds_until_end_of_day + end + def test_beginning_of_day assert_equal DateTime.civil(2005,2,4,0,0,0), DateTime.civil(2005,2,4,10,10,10).beginning_of_day end + def test_middle_of_day + assert_equal DateTime.civil(2005,2,4,12,0,0), DateTime.civil(2005,2,4,10,10,10).middle_of_day + end + def test_end_of_day assert_equal DateTime.civil(2005,2,4,23,59,59), DateTime.civil(2005,2,4,10,10,10).end_of_day end @@ -77,6 +98,14 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase assert_equal DateTime.civil(2005,2,4,19,59,59), DateTime.civil(2005,2,4,19,30,10).end_of_hour end + def test_beginning_of_minute + assert_equal DateTime.civil(2005,2,4,19,30,0), DateTime.civil(2005,2,4,19,30,10).beginning_of_minute + end + + def test_end_of_minute + assert_equal DateTime.civil(2005,2,4,19,30,59), DateTime.civil(2005,2,4,19,30,10).end_of_minute + end + def test_end_of_month assert_equal DateTime.civil(2005,3,31,23,59,59), DateTime.civil(2005,3,20,10,10,10).end_of_month assert_equal DateTime.civil(2005,2,28,23,59,59), DateTime.civil(2005,2,20,10,10,10).end_of_month @@ -110,6 +139,9 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase assert_equal DateTime.civil(2005,2,22,16), DateTime.civil(2005,2,22,15,15,10).change(:hour => 16) assert_equal DateTime.civil(2005,2,22,16,45), DateTime.civil(2005,2,22,15,15,10).change(:hour => 16, :min => 45) assert_equal DateTime.civil(2005,2,22,15,45), DateTime.civil(2005,2,22,15,15,10).change(:min => 45) + + # datetime with fractions of a second + assert_equal DateTime.civil(2005,2,1,15,15,10.7), DateTime.civil(2005,2,22,15,15,10.7).change(:day => 1) end def test_advance @@ -234,6 +266,10 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase end end + def test_acts_like_date + assert DateTime.new.acts_like_date? + end + def test_acts_like_time assert DateTime.new.acts_like_time? end @@ -301,6 +337,16 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase assert_equal 946684800, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_i end + def test_usec + assert_equal 0, DateTime.civil(2000).usec + assert_equal 500000, DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)).usec + end + + def test_nsec + assert_equal 0, DateTime.civil(2000).nsec + assert_equal 500000000, DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)).nsec + end + protected def with_env_tz(new_tz = 'US/Eastern') old_tz, ENV['TZ'] = ENV['TZ'], new_tz diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb index c8312aa653..ed267cf4b9 100644 --- a/activesupport/test/core_ext/duration_test.rb +++ b/activesupport/test/core_ext/duration_test.rb @@ -21,12 +21,13 @@ class DurationTest < ActiveSupport::TestCase assert ActiveSupport::Duration === 1.day assert !(ActiveSupport::Duration === 1.day.to_i) assert !(ActiveSupport::Duration === 'foo') - assert !(ActiveSupport::Duration === ActiveSupport::BasicObject.new) + assert !(ActiveSupport::Duration === ActiveSupport::ProxyObject.new) end def test_equals assert 1.day == 1.day assert 1.day == 1.day.to_i + assert 1.day.to_i == 1.day assert !(1.day == 'foo') end @@ -37,6 +38,8 @@ class DurationTest < ActiveSupport::TestCase assert_equal '6 months and -2 days', (6.months - 2.days).inspect assert_equal '10 seconds', 10.seconds.inspect assert_equal '10 years, 2 months, and 1 day', (10.years + 2.months + 1.day).inspect + assert_equal '10 years, 2 months, and 1 day', (10.years + 1.month + 1.day + 1.month).inspect + assert_equal '10 years, 2 months, and 1 day', (1.day + 10.years + 2.months).inspect assert_equal '7 days', 1.week.inspect assert_equal '14 days', 1.fortnight.inspect end @@ -50,14 +53,12 @@ class DurationTest < ActiveSupport::TestCase end def test_argument_error - begin - 1.second.ago('') - flunk("no exception was raised") - rescue ArgumentError => e - assert_equal 'expected a time or date, got ""', e.message, "ensure ArgumentError is not being raised by dependencies.rb" - rescue Exception => e - flunk("ArgumentError should be raised, but we got #{e.class} instead") - end + 1.second.ago('') + flunk("no exception was raised") + rescue ArgumentError => e + assert_equal 'expected a time or date, got ""', e.message, "ensure ArgumentError is not being raised by dependencies.rb" + rescue Exception => e + flunk("ArgumentError should be raised, but we got #{e.class} instead") end def test_fractional_weeks @@ -131,7 +132,7 @@ class DurationTest < ActiveSupport::TestCase assert_equal Time.local(2009,3,29,0,0,0) + 1.day, Time.local(2009,3,30,0,0,0) end end - + def test_delegation_with_block_works counter = 0 assert_nothing_raised do diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index 0a1abac767..6781e3c20e 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -24,10 +24,8 @@ class EnumerableTests < ActiveSupport::TestCase def test_group_by names = %w(marcel sam david jeremy) klass = Struct.new(:name) - objects = (1..50).inject([]) do |people,| - p = klass.new - p.name = names.sort_by { rand }.first - people << p + objects = (1..50).map do + klass.new names.sample end enum = GenericEnumerable.new(objects) diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index b208767490..b059bc3e89 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -3,11 +3,12 @@ require 'active_support/core_ext/hash' require 'bigdecimal' require 'active_support/core_ext/string/access' require 'active_support/ordered_hash' +require 'active_support/core_ext/object/conversions' require 'active_support/core_ext/object/deep_dup' require 'active_support/inflections' class HashExtTest < ActiveSupport::TestCase - class IndifferentHash < HashWithIndifferentAccess + class IndifferentHash < ActiveSupport::HashWithIndifferentAccess end class SubclassingArray < Array @@ -427,6 +428,18 @@ class HashExtTest < ActiveSupport::TestCase assert_equal 2, hash['b'] end + def test_indifferent_replace + hash = HashWithIndifferentAccess.new + hash[:a] = 42 + + replaced = hash.replace(b: 12) + + assert hash.key?('b') + assert !hash.key?(:a) + assert_equal 12, hash[:b] + assert_same hash, replaced + end + def test_indifferent_merging_with_block hash = HashWithIndifferentAccess.new hash[:a] = 1 @@ -467,6 +480,42 @@ class HashExtTest < ActiveSupport::TestCase assert_equal hash.delete('a'), nil end + def test_indifferent_select + hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).select {|k,v| v == 1} + + assert_equal({ 'a' => 1 }, hash) + assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash + end + + def test_indifferent_select_returns_a_hash_when_unchanged + hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).select {|k,v| true} + + assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash + end + + def test_indifferent_select_bang + indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings) + indifferent_strings.select! {|k,v| v == 1} + + assert_equal({ 'a' => 1 }, indifferent_strings) + assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings + end + + def test_indifferent_reject + hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).reject {|k,v| v != 1} + + assert_equal({ 'a' => 1 }, hash) + assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash + end + + def test_indifferent_reject_bang + indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings) + indifferent_strings.reject! {|k,v| v != 1} + + assert_equal({ 'a' => 1 }, indifferent_strings) + assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings + end + def test_indifferent_to_hash # Should convert to a Hash with String keys. assert_equal @strings, @mixed.with_indifferent_access.to_hash @@ -477,6 +526,10 @@ class HashExtTest < ActiveSupport::TestCase roundtrip = mixed_with_default.with_indifferent_access.to_hash assert_equal @strings, roundtrip assert_equal '1234', roundtrip.default + new_to_hash = @nested_mixed.with_indifferent_access.to_hash + assert_not new_to_hash.instance_of?(HashWithIndifferentAccess) + assert_not new_to_hash["a"].instance_of?(HashWithIndifferentAccess) + assert_not new_to_hash["a"]["b"].instance_of?(HashWithIndifferentAccess) end def test_lookup_returns_the_same_object_that_is_stored_in_hash_indifferent_access @@ -486,9 +539,21 @@ class HashExtTest < ActiveSupport::TestCase assert_equal [1], hash[:a] end + def test_with_indifferent_access_has_no_side_effects_on_existing_hash + hash = {content: [{:foo => :bar, 'bar' => 'baz'}]} + hash.with_indifferent_access + + assert_equal [:foo, "bar"], hash[:content].first.keys + end + def test_indifferent_hash_with_array_of_hashes hash = { "urls" => { "url" => [ { "address" => "1" }, { "address" => "2" } ] }}.with_indifferent_access assert_equal "1", hash[:urls][:url].first[:address] + + hash = hash.to_hash + assert_not hash.instance_of?(HashWithIndifferentAccess) + assert_not hash["urls"].instance_of?(HashWithIndifferentAccess) + assert_not hash["urls"]["url"].first.instance_of?(HashWithIndifferentAccess) end def test_should_preserve_array_subclass_when_value_is_array @@ -642,10 +707,6 @@ class HashExtTest < ActiveSupport::TestCase assert_equal expected, merged end - def test_diff - assert_equal({ :a => 2 }, { :a => 2, :b => 5 }.diff({ :a => 1, :b => 5 })) - end - def test_slice original = { :a => 'x', :b => 'y', :c => 10 } expected = { :a => 'x', :b => 'y' } @@ -720,6 +781,24 @@ class HashExtTest < ActiveSupport::TestCase assert_equal 'bender', slice['login'] end + def test_slice_bang_does_not_override_default + hash = Hash.new(0) + hash.update(a: 1, b: 2) + + hash.slice!(:a) + + assert_equal 0, hash[:c] + end + + def test_slice_bang_does_not_override_default_proc + hash = Hash.new { |h, k| h[k] = [] } + hash.update(a: 1, b: 2) + + hash.slice!(:a) + + assert_equal [], hash[:c] + end + def test_extract original = {:a => 1, :b => 2, :c => 3, :d => 4} expected = {:a => 1, :b => 2} @@ -1000,12 +1079,10 @@ class HashToXmlTest < ActiveSupport::TestCase <replies-close-in type="integer">2592000000</replies-close-in> <written-on type="date">2003-07-16</written-on> <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at> - <content type="yaml">--- \n1: should be an integer\n:message: Have a nice day\narray: \n- should-have-dashes: true\n should_have_underscores: true\n</content> <author-email-address>david@loudthinking.com</author-email-address> <parent-id></parent-id> <ad-revenue type="decimal">1.5</ad-revenue> <optimum-viewing-angle type="float">135</optimum-viewing-angle> - <resident type="symbol">yes</resident> </topic> EOT @@ -1018,12 +1095,10 @@ class HashToXmlTest < ActiveSupport::TestCase :replies_close_in => 2592000000, :written_on => Date.new(2003, 7, 16), :viewed_at => Time.utc(2003, 7, 16, 9, 28), - :content => { :message => "Have a nice day", 1 => "should be an integer", "array" => [{ "should-have-dashes" => true, "should_have_underscores" => true }] }, :author_email_address => "david@loudthinking.com", :parent_id => nil, :ad_revenue => BigDecimal("1.50"), :optimum_viewing_angle => 135.0, - :resident => :yes }.stringify_keys assert_equal expected_topic_hash, Hash.from_xml(topic_xml)["topic"] @@ -1037,7 +1112,6 @@ class HashToXmlTest < ActiveSupport::TestCase <approved type="boolean"></approved> <written-on type="date"></written-on> <viewed-at type="datetime"></viewed-at> - <content type="yaml"></content> <parent-id></parent-id> </topic> EOT @@ -1048,7 +1122,6 @@ class HashToXmlTest < ActiveSupport::TestCase :approved => nil, :written_on => nil, :viewed_at => nil, - :content => nil, :parent_id => nil }.stringify_keys @@ -1275,6 +1348,28 @@ class HashToXmlTest < ActiveSupport::TestCase assert_equal expected_product_hash, Hash.from_xml(product_xml)["product"] end + def test_from_xml_raises_on_disallowed_type_attributes + assert_raise ActiveSupport::XMLConverter::DisallowedType do + Hash.from_xml '<product><name type="foo">value</name></product>', %w(foo) + end + end + + def test_from_xml_disallows_symbol_and_yaml_types_by_default + assert_raise ActiveSupport::XMLConverter::DisallowedType do + Hash.from_xml '<product><name type="symbol">value</name></product>' + end + + assert_raise ActiveSupport::XMLConverter::DisallowedType do + Hash.from_xml '<product><name type="yaml">value</name></product>' + end + end + + def test_from_trusted_xml_allows_symbol_and_yaml_types + expected = { 'product' => { 'name' => :value }} + assert_equal expected, Hash.from_trusted_xml('<product><name type="symbol">value</name></product>') + assert_equal expected, Hash.from_trusted_xml('<product><name type="yaml">:value</name></product>') + end + def test_should_use_default_value_for_unknown_key hash_wia = HashWithIndifferentAccess.new(3) assert_equal 3, hash_wia[:new_key] @@ -1315,7 +1410,7 @@ class HashToXmlTest < ActiveSupport::TestCase def test_empty_string_works_for_typecast_xml_value assert_nothing_raised do - Hash.__send__(:typecast_xml_value, "") + ActiveSupport::XMLConverter.new("").to_h end end diff --git a/activesupport/test/core_ext/kernel_test.rb b/activesupport/test/core_ext/kernel_test.rb index 439bc87323..b8951de402 100644 --- a/activesupport/test/core_ext/kernel_test.rb +++ b/activesupport/test/core_ext/kernel_test.rb @@ -38,6 +38,18 @@ class KernelTest < ActiveSupport::TestCase # Skip if we can't STDERR.tell end + def test_quietly + old_stdout_position, old_stderr_position = STDOUT.tell, STDERR.tell + quietly do + puts 'see me, feel me' + STDERR.puts 'touch me, heal me' + end + assert_equal old_stdout_position, STDOUT.tell + assert_equal old_stderr_position, STDERR.tell + rescue Errno::ESPIPE + # Skip if we can't STDERR.tell + end + def test_silence_stderr_with_return_value assert_equal 1, silence_stderr { 1 } end @@ -51,6 +63,8 @@ class KernelTest < ActiveSupport::TestCase def test_capture assert_equal 'STDERR', capture(:stderr) { $stderr.print 'STDERR' } assert_equal 'STDOUT', capture(:stdout) { print 'STDOUT' } + assert_equal "STDERR\n", capture(:stderr) { system('echo STDERR 1>&2') } + assert_equal "STDOUT\n", capture(:stdout) { system('echo STDOUT') } end end diff --git a/activesupport/test/core_ext/marshal_test.rb b/activesupport/test/core_ext/marshal_test.rb new file mode 100644 index 0000000000..8f3f710dfd --- /dev/null +++ b/activesupport/test/core_ext/marshal_test.rb @@ -0,0 +1,124 @@ +require 'abstract_unit' +require 'active_support/core_ext/marshal' +require 'dependencies_test_helpers' + +class MarshalTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + include DependenciesTestHelpers + + def teardown + ActiveSupport::Dependencies.clear + remove_constants(:E, :ClassFolder) + end + + test "that Marshal#load still works" do + sanity_data = ["test", [1, 2, 3], {a: [1, 2, 3]}, ActiveSupport::TestCase] + sanity_data.each do |obj| + dumped = Marshal.dump(obj) + assert_equal Marshal.load_without_autoloading(dumped), Marshal.load(dumped) + end + end + + test "that a missing class is autoloaded from string" do + dumped = nil + with_autoloading_fixtures do + dumped = Marshal.dump(E.new) + end + + remove_constants(:E) + ActiveSupport::Dependencies.clear + + with_autoloading_fixtures do + assert_kind_of E, Marshal.load(dumped) + end + end + + test "that classes in sub modules work" do + dumped = nil + with_autoloading_fixtures do + dumped = Marshal.dump(ClassFolder::ClassFolderSubclass.new) + end + + remove_constants(:ClassFolder) + ActiveSupport::Dependencies.clear + + with_autoloading_fixtures do + assert_kind_of ClassFolder::ClassFolderSubclass, Marshal.load(dumped) + end + end + + test "that more than one missing class is autoloaded" do + dumped = nil + with_autoloading_fixtures do + dumped = Marshal.dump([E.new, ClassFolder.new]) + end + + remove_constants(:E, :ClassFolder) + ActiveSupport::Dependencies.clear + + with_autoloading_fixtures do + loaded = Marshal.load(dumped) + assert_equal 2, loaded.size + assert_kind_of E, loaded[0] + assert_kind_of ClassFolder, loaded[1] + end + end + + test "that a real missing class is causing an exception" do + dumped = nil + with_autoloading_fixtures do + dumped = Marshal.dump(E.new) + end + + remove_constants(:E) + ActiveSupport::Dependencies.clear + + assert_raise(NameError) do + Marshal.load(dumped) + end + end + + test "when first class is autoloaded and second not" do + dumped = nil + class SomeClass + end + + with_autoloading_fixtures do + dumped = Marshal.dump([E.new, SomeClass.new]) + end + + remove_constants(:E) + self.class.send(:remove_const, :SomeClass) + ActiveSupport::Dependencies.clear + + with_autoloading_fixtures do + assert_raise(NameError) do + Marshal.load(dumped) + end + + assert_nothing_raised("E failed to load while we expect only SomeClass to fail loading") do + E.new + end + + assert_raise(NameError, "We expected SomeClass to not be loaded but it is!") do + SomeClass.new + end + end + end + + test "loading classes from files trigger autoloading" do + Tempfile.open("object_serializer_test") do |f| + with_autoloading_fixtures do + Marshal.dump(E.new, f) + end + + f.rewind + remove_constants(:E) + ActiveSupport::Dependencies.clear + + with_autoloading_fixtures do + assert_kind_of E, Marshal.load(f) + end + end + end +end
\ No newline at end of file diff --git a/activesupport/test/core_ext/module/qualified_const_test.rb b/activesupport/test/core_ext/module/qualified_const_test.rb index 343a848a42..37c9228a64 100644 --- a/activesupport/test/core_ext/module/qualified_const_test.rb +++ b/activesupport/test/core_ext/module/qualified_const_test.rb @@ -89,13 +89,20 @@ class QualifiedConstTest < ActiveSupport::TestCase end test "reject absolute paths" do - assert_raise(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X")} - assert_raise(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X::Y")} + assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X")} + assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X::Y")} - assert_raise(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X")} - assert_raise(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X::Y")} + assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X")} + assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X::Y")} - assert_raise(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X", nil)} - assert_raise(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X::Y", nil)} + assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X", nil)} + assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X::Y", nil)} + end + + private + + def assert_raise_with_message(expected_exception, expected_message, &block) + exception = assert_raise(expected_exception, &block) + assert_equal expected_message, exception.message end end diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb index 82249ddd1b..283b13ff8b 100644 --- a/activesupport/test/core_ext/module_test.rb +++ b/activesupport/test/core_ext/module_test.rb @@ -66,6 +66,23 @@ Tester = Struct.new(:client) do delegate :name, :to => :client, :prefix => false end +Product = Struct.new(:name) do + delegate :name, :to => :manufacturer, :prefix => true + delegate :name, :to => :type, :prefix => true + + def manufacturer + @manufacturer ||= begin + nil.unknown_method + end + end + + def type + @type ||= begin + nil.type_name + end + end +end + class ParameterSet delegate :[], :[]=, :to => :@params @@ -82,6 +99,21 @@ class Name end end +class SideEffect + attr_reader :ints + + delegate :to_i, :to => :shift, :allow_nil => true + delegate :to_s, :to => :shift + + def initialize + @ints = [1, 2, 3] + end + + def shift + @ints.shift + end +end + class ModuleTest < ActiveSupport::TestCase def setup @david = Someone.new("David", Somewhere.new("Paulina", "Chicago")) @@ -171,6 +203,17 @@ class ModuleTest < ActiveSupport::TestCase assert_nil rails.name end + # Ensures with check for nil, not for a falseish target. + def test_delegation_with_allow_nil_and_false_value + project = Project.new(false, false) + assert_raise(NoMethodError) { project.name } + end + + def test_delegation_with_allow_nil_and_invalid_value + rails = Project.new("Rails", "David") + assert_raise(NoMethodError) { rails.name } + end + def test_delegation_with_allow_nil_and_nil_value_and_prefix Project.class_eval do delegate :name, :to => :person, :allow_nil => true, :prefix => true @@ -181,7 +224,7 @@ class ModuleTest < ActiveSupport::TestCase def test_delegation_without_allow_nil_and_nil_value david = Someone.new("David") - assert_raise(RuntimeError) { david.street } + assert_raise(Module::DelegationError) { david.street } end def test_delegation_to_method_that_exists_on_nil @@ -228,6 +271,26 @@ class ModuleTest < ActiveSupport::TestCase "[#{e.backtrace.inspect}] did not include [#{file_and_line}]" end + def test_delegation_invokes_the_target_exactly_once + se = SideEffect.new + + assert_equal 1, se.to_i + assert_equal [2, 3], se.ints + + assert_equal '2', se.to_s + assert_equal [3], se.ints + end + + def test_delegation_doesnt_mask_nested_no_method_error_on_nil_receiver + product = Product.new('Widget') + + # Nested NoMethodError is a different name from the delegation + assert_raise(NoMethodError) { product.manufacturer_name } + + # Nested NoMethodError is the same name as the delegation + assert_raise(NoMethodError) { product.type_name } + end + def test_parent assert_equal Yz::Zy, Yz::Zy::Cd.parent assert_equal Yz, Yz::Zy.parent @@ -242,12 +305,6 @@ class ModuleTest < ActiveSupport::TestCase def test_local_constants assert_equal %w(Constant1 Constant3), Ab.local_constants.sort.map(&:to_s) end - - def test_local_constant_names - ActiveSupport::Deprecation.silence do - assert_equal %w(Constant1 Constant3), Ab.local_constant_names.sort.map(&:to_s) - end - end end module BarMethodAliaser diff --git a/activesupport/test/core_ext/numeric_ext_test.rb b/activesupport/test/core_ext/numeric_ext_test.rb index 435f4aa5a1..1da72eb17d 100644 --- a/activesupport/test/core_ext/numeric_ext_test.rb +++ b/activesupport/test/core_ext/numeric_ext_test.rb @@ -77,7 +77,7 @@ class NumericExtTimeAndDateTimeTest < ActiveSupport::TestCase assert_equal @dtnow.advance(:days => 1).advance(:months => 2), @dtnow + 1.day + 2.months end - def test_duration_after_convertion_is_no_longer_accurate + def test_duration_after_conversion_is_no_longer_accurate assert_equal 30.days.to_i.since(@now), 1.month.to_i.since(@now) assert_equal 365.25.days.to_f.since(@now), 1.year.to_f.since(@now) assert_equal 30.days.to_i.since(@dtnow), 1.month.to_i.since(@dtnow) @@ -153,22 +153,16 @@ end class NumericExtSizeTest < ActiveSupport::TestCase def test_unit_in_terms_of_another - relationships = { - 1024.bytes => 1.kilobyte, - 1024.kilobytes => 1.megabyte, - 3584.0.kilobytes => 3.5.megabytes, - 3584.0.megabytes => 3.5.gigabytes, - 1.kilobyte ** 4 => 1.terabyte, - 1024.kilobytes + 2.megabytes => 3.megabytes, - 2.gigabytes / 4 => 512.megabytes, - 256.megabytes * 20 + 5.gigabytes => 10.gigabytes, - 1.kilobyte ** 5 => 1.petabyte, - 1.kilobyte ** 6 => 1.exabyte - } - - relationships.each do |left, right| - assert_equal right, left - end + assert_equal 1024.bytes, 1.kilobyte + assert_equal 1024.kilobytes, 1.megabyte + assert_equal 3584.0.kilobytes, 3.5.megabytes + assert_equal 3584.0.megabytes, 3.5.gigabytes + assert_equal 1.kilobyte ** 4, 1.terabyte + assert_equal 1024.kilobytes + 2.megabytes, 3.megabytes + assert_equal 2.gigabytes / 4, 512.megabytes + assert_equal 256.megabytes * 20 + 5.gigabytes, 10.gigabytes + assert_equal 1.kilobyte ** 5, 1.petabyte + assert_equal 1.kilobyte ** 6, 1.exabyte end def test_units_as_bytes_independently @@ -203,7 +197,7 @@ class NumericExtFormattingTest < ActiveSupport::TestCase def terabytes(number) gigabytes(number) * 1024 end - + def test_to_s__phone assert_equal("555-1234", 5551234.to_s(:phone)) assert_equal("800-555-1212", 8005551212.to_s(:phone)) @@ -217,7 +211,7 @@ class NumericExtFormattingTest < ActiveSupport::TestCase assert_equal("22-555-1212", 225551212.to_s(:phone)) assert_equal("+45-22-555-1212", 225551212.to_s(:phone, :country_code => 45)) end - + def test_to_s__currency assert_equal("$1,234,567,890.50", 1234567890.50.to_s(:currency)) assert_equal("$1,234,567,890.51", 1234567890.506.to_s(:currency)) @@ -228,8 +222,8 @@ class NumericExtFormattingTest < ActiveSupport::TestCase assert_equal("$1,234,567,890.5", 1234567890.50.to_s(:currency, :precision => 1)) assert_equal("£1234567890,50", 1234567890.50.to_s(:currency, :unit => "£", :separator => ",", :delimiter => "")) end - - + + def test_to_s__rounded assert_equal("-111.235", -111.2346.to_s(:rounded)) assert_equal("111.235", 111.2346.to_s(:rounded)) @@ -246,7 +240,7 @@ class NumericExtFormattingTest < ActiveSupport::TestCase assert_equal("11.00", 10.995.to_s(:rounded, :precision => 2)) assert_equal("0.00", -0.001.to_s(:rounded, :precision => 2)) end - + def test_to_s__percentage assert_equal("100.000%", 100.to_s(:percentage)) assert_equal("100%", 100.to_s(:percentage, :precision => 0)) @@ -274,7 +268,7 @@ class NumericExtFormattingTest < ActiveSupport::TestCase assert_equal '12.345.678,05', 12345678.05.to_s(:delimited, :separator => ',', :delimiter => '.') assert_equal '12.345.678,05', 12345678.05.to_s(:delimited, :delimiter => '.', :separator => ',') end - + def test_to_s__rounded_with_custom_delimiter_and_separator assert_equal '31,83', 31.825.to_s(:rounded, :precision => 2, :separator => ',') @@ -350,7 +344,7 @@ class NumericExtFormattingTest < ActiveSupport::TestCase assert_equal '1.23 GB', 1234567890.to_s(:human_size, :prefix => :si) assert_equal '1.23 TB', 1234567890123.to_s(:human_size, :prefix => :si) end - + def test_to_s__human_size_with_options_hash assert_equal '1.2 MB', 1234567.to_s(:human_size, :precision => 2) assert_equal '3 Bytes', 3.14159265.to_s(:human_size, :precision => 4) @@ -366,13 +360,13 @@ class NumericExtFormattingTest < ActiveSupport::TestCase assert_equal '1.012 KB', kilobytes(1.0123).to_s(:human_size, :precision => 3, :significant => false) assert_equal '1 KB', kilobytes(1.0123).to_s(:human_size, :precision => 0, :significant => true) #ignores significant it precision is 0 end - + def test_to_s__human_size_with_custom_delimiter_and_separator assert_equal '1,01 KB', kilobytes(1.0123).to_s(:human_size, :precision => 3, :separator => ',') assert_equal '1,01 KB', kilobytes(1.0100).to_s(:human_size, :precision => 4, :separator => ',') assert_equal '1.000,1 TB', terabytes(1000.1).to_s(:human_size, :precision => 5, :delimiter => '.', :separator => ',') end - + def test_number_to_human assert_equal '-123', -123.to_s(:human) assert_equal '-0.5', -0.5.to_s(:human) @@ -436,7 +430,7 @@ class NumericExtFormattingTest < ActiveSupport::TestCase def test_to_s__injected_on_proper_types assert_equal Fixnum, 1230.class assert_equal '1.23 Thousand', 1230.to_s(:human) - + assert_equal Float, Float(1230).class assert_equal '1.23 Thousand', Float(1230).to_s(:human) diff --git a/activesupport/test/core_ext/object/inclusion_test.rb b/activesupport/test/core_ext/object/inclusion_test.rb index 22888333f5..478706eeae 100644 --- a/activesupport/test/core_ext/object/inclusion_test.rb +++ b/activesupport/test/core_ext/object/inclusion_test.rb @@ -2,16 +2,6 @@ require 'abstract_unit' require 'active_support/core_ext/object/inclusion' class InTest < ActiveSupport::TestCase - def test_in_multiple_args - assert :b.in?(:a,:b) - assert !:c.in?(:a,:b) - end - - def test_in_multiple_arrays - assert [1,2].in?([1,2],[2,3]) - assert ![1,2].in?([1,3],[2,1]) - end - def test_in_array assert 1.in?([1,2]) assert !3.in?([1,2]) diff --git a/activesupport/test/core_ext/object/json_test.rb b/activesupport/test/core_ext/object/json_test.rb new file mode 100644 index 0000000000..d3d31530df --- /dev/null +++ b/activesupport/test/core_ext/object/json_test.rb @@ -0,0 +1,9 @@ +require 'abstract_unit' + +class JsonTest < ActiveSupport::TestCase + # See activesupport/test/json/encoding_test.rb for JSON encoding tests + + def test_deprecated_require_to_json_rb + assert_deprecated { require 'active_support/core_ext/object/to_json' } + end +end diff --git a/activesupport/test/core_ext/object/to_query_test.rb b/activesupport/test/core_ext/object/to_query_test.rb index 8d1a8c628c..92f996f9a4 100644 --- a/activesupport/test/core_ext/object/to_query_test.rb +++ b/activesupport/test/core_ext/object/to_query_test.rb @@ -47,7 +47,7 @@ class ToQueryTest < ActiveSupport::TestCase end private - def assert_query_equal(expected, actual, message = nil) + def assert_query_equal(expected, actual) assert_equal expected.split('&'), actual.to_query.split('&') end end diff --git a/activesupport/test/core_ext/object_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb index ec7dd6d4fb..8d748791e3 100644 --- a/activesupport/test/core_ext/object_and_class_ext_test.rb +++ b/activesupport/test/core_ext/object_and_class_ext_test.rb @@ -120,6 +120,10 @@ class ObjectTryTest < ActiveSupport::TestCase assert_raise(NoMethodError) { @string.try!(method, 'llo', 'y') } end + def test_try_only_block_bang + assert_equal @string.reverse, @string.try! { |s| s.reverse } + end + def test_valid_method assert_equal 5, @string.try(:size) end diff --git a/activesupport/test/core_ext/proc_test.rb b/activesupport/test/core_ext/proc_test.rb deleted file mode 100644 index c4d5592196..0000000000 --- a/activesupport/test/core_ext/proc_test.rb +++ /dev/null @@ -1,14 +0,0 @@ -require 'abstract_unit' -require 'active_support/core_ext/proc' - -class ProcTests < ActiveSupport::TestCase - def test_bind_returns_method_with_changed_self - assert_deprecated do - block = Proc.new { self } - assert_equal self, block.call - bound_block = block.bind("hello") - assert_not_equal block, bound_block - assert_equal "hello", bound_block.call - end - end -end diff --git a/activesupport/test/core_ext/range_ext_test.rb b/activesupport/test/core_ext/range_ext_test.rb index f0cdc0bfd4..854b0a38bd 100644 --- a/activesupport/test/core_ext/range_ext_test.rb +++ b/activesupport/test/core_ext/range_ext_test.rb @@ -12,6 +12,11 @@ class RangeTest < ActiveSupport::TestCase date_range = Time.utc(2005, 12, 10, 15, 30)..Time.utc(2005, 12, 10, 17, 30) assert_equal "BETWEEN '2005-12-10 15:30:00' AND '2005-12-10 17:30:00'", date_range.to_s(:db) end + + def test_date_range + assert_instance_of Range, DateTime.new..DateTime.new + assert_instance_of Range, DateTime::Infinity.new..DateTime::Infinity.new + end def test_overlaps_last_inclusive assert((1..5).overlaps?(5..10)) @@ -49,7 +54,7 @@ class RangeTest < ActiveSupport::TestCase assert((1...10) === (1...10)) end - def test_should_compare_other_with_exlusive_end + def test_should_compare_other_with_exclusive_end assert((1..10) === (1...10)) end @@ -85,4 +90,26 @@ class RangeTest < ActiveSupport::TestCase time_range_2 = Time.utc(2005, 12, 10, 17, 31)..Time.utc(2005, 12, 10, 18, 00) assert !time_range_1.overlaps?(time_range_2) end + + def test_each_on_time_with_zone + twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone['Eastern Time (US & Canada)'] , Time.utc(2006,11,28,10,30)) + assert_raises TypeError do + ((twz - 1.hour)..twz).each {} + end + end + + def test_step_on_time_with_zone + twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone['Eastern Time (US & Canada)'] , Time.utc(2006,11,28,10,30)) + assert_raises TypeError do + ((twz - 1.hour)..twz).step(1) {} + end + end + + def test_include_on_time_with_zone + twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone['Eastern Time (US & Canada)'] , Time.utc(2006,11,28,10,30)) + assert_raises TypeError do + ((twz - 1.hour)..twz).include?(twz) + end + end + end diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 6720ed42f0..3cb66d4eec 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -11,13 +11,6 @@ require 'active_support/core_ext/string/strip' require 'active_support/core_ext/string/output_safety' require 'active_support/core_ext/string/indent' -module Ace - module Base - class Case - end - end -end - class StringInflectionsTest < ActiveSupport::TestCase include InflectorTestCases include ConstantizeTestCases @@ -87,6 +80,12 @@ class StringInflectionsTest < ActiveSupport::TestCase assert_equal('capital', 'Capital'.camelize(:lower)) end + def test_dasherize + UnderscoresToDashes.each do |underscored, dasherized| + assert_equal(dasherized, underscored.dasherize) + end + end + def test_underscore CamelToUnderscore.each do |camel, underscore| assert_equal(underscore, camel.underscore) @@ -161,30 +160,6 @@ class StringInflectionsTest < ActiveSupport::TestCase assert_equal 97, 'abc'.ord end - def test_string_to_time - assert_equal Time.utc(2005, 2, 27, 23, 50), "2005-02-27 23:50".to_time - assert_equal Time.local(2005, 2, 27, 23, 50), "2005-02-27 23:50".to_time(:local) - assert_equal Time.utc(2005, 2, 27, 23, 50, 19, 275038), "2005-02-27T23:50:19.275038".to_time - assert_equal Time.local(2005, 2, 27, 23, 50, 19, 275038), "2005-02-27T23:50:19.275038".to_time(:local) - assert_equal DateTime.civil(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_time - assert_equal Time.local_time(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_time(:local) - assert_equal Time.utc(2011, 2, 27, 23, 50), "2011-02-27 22:50 -0100".to_time - assert_nil "".to_time - end - - def test_string_to_datetime - assert_equal DateTime.civil(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_datetime - assert_equal 0, "2039-02-27 23:50".to_datetime.offset # use UTC offset - assert_equal ::Date::ITALY, "2039-02-27 23:50".to_datetime.start # use Ruby's default start value - assert_equal DateTime.civil(2039, 2, 27, 23, 50, 19 + Rational(275038, 1000000), "-04:00"), "2039-02-27T23:50:19.275038-04:00".to_datetime - assert_nil "".to_datetime - end - - def test_string_to_date - assert_equal Date.new(2005, 2, 27), "2005-02-27".to_date - assert_nil "".to_date - end - def test_access s = "hello" assert_equal "h", s.at(0) @@ -247,10 +222,11 @@ class StringInflectionsTest < ActiveSupport::TestCase end def test_string_squish - original = %{ A string with tabs(\t\t), newlines(\n\n), and - many spaces( ). } + original = %{\u180E\u180E A string surrounded by unicode mongolian vowel separators, + with tabs(\t\t), newlines(\n\n), unicode nextlines(\u0085\u0085) and many spaces( ). \u180E\u180E} - expected = "A string with tabs( ), newlines( ), and many spaces( )." + expected = "A string surrounded by unicode mongolian vowel separators, " + + "with tabs( ), newlines( ), unicode nextlines( ) and many spaces( )." # Make sure squish returns what we expect: assert_equal original.squish, expected @@ -287,13 +263,18 @@ class StringInflectionsTest < ActiveSupport::TestCase end def test_truncate_multibyte - assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...".force_encoding('UTF-8'), - "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".force_encoding('UTF-8').truncate(10) + assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...".force_encoding(Encoding::UTF_8), + "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".force_encoding(Encoding::UTF_8).truncate(10) end def test_truncate_should_not_be_html_safe assert !"Hello World!".truncate(12).html_safe? end + + def test_remove + assert_equal "Summer", "Fast Summer".remove(/Fast /) + assert_equal "Summer", "Fast Summer".remove!(/Fast /) + end def test_constantize run_constantize_tests_on do |string| @@ -308,6 +289,186 @@ class StringInflectionsTest < ActiveSupport::TestCase end end +class StringConversionsTest < ActiveSupport::TestCase + def test_string_to_time + with_env_tz "Europe/Moscow" do + assert_equal Time.utc(2005, 2, 27, 23, 50), "2005-02-27 23:50".to_time(:utc) + assert_equal Time.local(2005, 2, 27, 23, 50), "2005-02-27 23:50".to_time + assert_equal Time.utc(2005, 2, 27, 23, 50, 19, 275038), "2005-02-27T23:50:19.275038".to_time(:utc) + assert_equal Time.local(2005, 2, 27, 23, 50, 19, 275038), "2005-02-27T23:50:19.275038".to_time + assert_equal Time.utc(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_time(:utc) + assert_equal Time.local(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_time + assert_equal Time.local(2011, 2, 27, 17, 50), "2011-02-27 13:50 -0100".to_time + assert_equal Time.utc(2011, 2, 27, 23, 50), "2011-02-27 22:50 -0100".to_time(:utc) + assert_equal Time.local(2005, 2, 27, 22, 50), "2005-02-27 14:50 -0500".to_time + assert_nil "".to_time + end + end + + def test_string_to_time_utc_offset + with_env_tz "US/Eastern" do + assert_equal 0, "2005-02-27 23:50".to_time(:utc).utc_offset + assert_equal(-18000, "2005-02-27 23:50".to_time.utc_offset) + assert_equal 0, "2005-02-27 22:50 -0100".to_time(:utc).utc_offset + assert_equal(-18000, "2005-02-27 22:50 -0100".to_time.utc_offset) + end + end + + def test_partial_string_to_time + with_env_tz "Europe/Moscow" do + now = Time.now + assert_equal Time.local(now.year, now.month, now.day, 23, 50), "23:50".to_time + assert_equal Time.utc(now.year, now.month, now.day, 23, 50), "23:50".to_time(:utc) + assert_equal Time.local(now.year, now.month, now.day, 18, 50), "13:50 -0100".to_time + assert_equal Time.utc(now.year, now.month, now.day, 23, 50), "22:50 -0100".to_time(:utc) + end + end + + def test_standard_time_string_to_time_when_current_time_is_standard_time + with_env_tz "US/Eastern" do + Time.stubs(:now).returns(Time.local(2012, 1, 1)) + assert_equal Time.local(2012, 1, 1, 10, 0), "2012-01-01 10:00".to_time + assert_equal Time.utc(2012, 1, 1, 10, 0), "2012-01-01 10:00".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 13, 0), "2012-01-01 10:00 -0800".to_time + assert_equal Time.utc(2012, 1, 1, 18, 0), "2012-01-01 10:00 -0800".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 10, 0), "2012-01-01 10:00 -0500".to_time + assert_equal Time.utc(2012, 1, 1, 15, 0), "2012-01-01 10:00 -0500".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 5, 0), "2012-01-01 10:00 UTC".to_time + assert_equal Time.utc(2012, 1, 1, 10, 0), "2012-01-01 10:00 UTC".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 13, 0), "2012-01-01 10:00 PST".to_time + assert_equal Time.utc(2012, 1, 1, 18, 0), "2012-01-01 10:00 PST".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 10, 0), "2012-01-01 10:00 EST".to_time + assert_equal Time.utc(2012, 1, 1, 15, 0), "2012-01-01 10:00 EST".to_time(:utc) + end + end + + def test_standard_time_string_to_time_when_current_time_is_daylight_savings + with_env_tz "US/Eastern" do + Time.stubs(:now).returns(Time.local(2012, 7, 1)) + assert_equal Time.local(2012, 1, 1, 10, 0), "2012-01-01 10:00".to_time + assert_equal Time.utc(2012, 1, 1, 10, 0), "2012-01-01 10:00".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 13, 0), "2012-01-01 10:00 -0800".to_time + assert_equal Time.utc(2012, 1, 1, 18, 0), "2012-01-01 10:00 -0800".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 10, 0), "2012-01-01 10:00 -0500".to_time + assert_equal Time.utc(2012, 1, 1, 15, 0), "2012-01-01 10:00 -0500".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 5, 0), "2012-01-01 10:00 UTC".to_time + assert_equal Time.utc(2012, 1, 1, 10, 0), "2012-01-01 10:00 UTC".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 13, 0), "2012-01-01 10:00 PST".to_time + assert_equal Time.utc(2012, 1, 1, 18, 0), "2012-01-01 10:00 PST".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 10, 0), "2012-01-01 10:00 EST".to_time + assert_equal Time.utc(2012, 1, 1, 15, 0), "2012-01-01 10:00 EST".to_time(:utc) + end + end + + def test_daylight_savings_string_to_time_when_current_time_is_standard_time + with_env_tz "US/Eastern" do + Time.stubs(:now).returns(Time.local(2012, 1, 1)) + assert_equal Time.local(2012, 7, 1, 10, 0), "2012-07-01 10:00".to_time + assert_equal Time.utc(2012, 7, 1, 10, 0), "2012-07-01 10:00".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 13, 0), "2012-07-01 10:00 -0700".to_time + assert_equal Time.utc(2012, 7, 1, 17, 0), "2012-07-01 10:00 -0700".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 10, 0), "2012-07-01 10:00 -0400".to_time + assert_equal Time.utc(2012, 7, 1, 14, 0), "2012-07-01 10:00 -0400".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 6, 0), "2012-07-01 10:00 UTC".to_time + assert_equal Time.utc(2012, 7, 1, 10, 0), "2012-07-01 10:00 UTC".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 13, 0), "2012-07-01 10:00 PDT".to_time + assert_equal Time.utc(2012, 7, 1, 17, 0), "2012-07-01 10:00 PDT".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 10, 0), "2012-07-01 10:00 EDT".to_time + assert_equal Time.utc(2012, 7, 1, 14, 0), "2012-07-01 10:00 EDT".to_time(:utc) + end + end + + def test_daylight_savings_string_to_time_when_current_time_is_daylight_savings + with_env_tz "US/Eastern" do + Time.stubs(:now).returns(Time.local(2012, 7, 1)) + assert_equal Time.local(2012, 7, 1, 10, 0), "2012-07-01 10:00".to_time + assert_equal Time.utc(2012, 7, 1, 10, 0), "2012-07-01 10:00".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 13, 0), "2012-07-01 10:00 -0700".to_time + assert_equal Time.utc(2012, 7, 1, 17, 0), "2012-07-01 10:00 -0700".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 10, 0), "2012-07-01 10:00 -0400".to_time + assert_equal Time.utc(2012, 7, 1, 14, 0), "2012-07-01 10:00 -0400".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 6, 0), "2012-07-01 10:00 UTC".to_time + assert_equal Time.utc(2012, 7, 1, 10, 0), "2012-07-01 10:00 UTC".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 13, 0), "2012-07-01 10:00 PDT".to_time + assert_equal Time.utc(2012, 7, 1, 17, 0), "2012-07-01 10:00 PDT".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 10, 0), "2012-07-01 10:00 EDT".to_time + assert_equal Time.utc(2012, 7, 1, 14, 0), "2012-07-01 10:00 EDT".to_time(:utc) + end + end + + def test_partial_string_to_time_when_current_time_is_standard_time + with_env_tz "US/Eastern" do + Time.stubs(:now).returns(Time.local(2012, 1, 1)) + assert_equal Time.local(2012, 1, 1, 10, 0), "10:00".to_time + assert_equal Time.utc(2012, 1, 1, 10, 0), "10:00".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 6, 0), "10:00 -0100".to_time + assert_equal Time.utc(2012, 1, 1, 11, 0), "10:00 -0100".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 10, 0), "10:00 -0500".to_time + assert_equal Time.utc(2012, 1, 1, 15, 0), "10:00 -0500".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 5, 0), "10:00 UTC".to_time + assert_equal Time.utc(2012, 1, 1, 10, 0), "10:00 UTC".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 13, 0), "10:00 PST".to_time + assert_equal Time.utc(2012, 1, 1, 18, 0), "10:00 PST".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 12, 0), "10:00 PDT".to_time + assert_equal Time.utc(2012, 1, 1, 17, 0), "10:00 PDT".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 10, 0), "10:00 EST".to_time + assert_equal Time.utc(2012, 1, 1, 15, 0), "10:00 EST".to_time(:utc) + assert_equal Time.local(2012, 1, 1, 9, 0), "10:00 EDT".to_time + assert_equal Time.utc(2012, 1, 1, 14, 0), "10:00 EDT".to_time(:utc) + end + end + + def test_partial_string_to_time_when_current_time_is_daylight_savings + with_env_tz "US/Eastern" do + Time.stubs(:now).returns(Time.local(2012, 7, 1)) + assert_equal Time.local(2012, 7, 1, 10, 0), "10:00".to_time + assert_equal Time.utc(2012, 7, 1, 10, 0), "10:00".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 7, 0), "10:00 -0100".to_time + assert_equal Time.utc(2012, 7, 1, 11, 0), "10:00 -0100".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 11, 0), "10:00 -0500".to_time + assert_equal Time.utc(2012, 7, 1, 15, 0), "10:00 -0500".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 6, 0), "10:00 UTC".to_time + assert_equal Time.utc(2012, 7, 1, 10, 0), "10:00 UTC".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 14, 0), "10:00 PST".to_time + assert_equal Time.utc(2012, 7, 1, 18, 0), "10:00 PST".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 13, 0), "10:00 PDT".to_time + assert_equal Time.utc(2012, 7, 1, 17, 0), "10:00 PDT".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 11, 0), "10:00 EST".to_time + assert_equal Time.utc(2012, 7, 1, 15, 0), "10:00 EST".to_time(:utc) + assert_equal Time.local(2012, 7, 1, 10, 0), "10:00 EDT".to_time + assert_equal Time.utc(2012, 7, 1, 14, 0), "10:00 EDT".to_time(:utc) + end + end + + def test_string_to_datetime + assert_equal DateTime.civil(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_datetime + assert_equal 0, "2039-02-27 23:50".to_datetime.offset # use UTC offset + assert_equal ::Date::ITALY, "2039-02-27 23:50".to_datetime.start # use Ruby's default start value + assert_equal DateTime.civil(2039, 2, 27, 23, 50, 19 + Rational(275038, 1000000), "-04:00"), "2039-02-27T23:50:19.275038-04:00".to_datetime + assert_nil "".to_datetime + end + + def test_partial_string_to_datetime + now = DateTime.now + assert_equal DateTime.civil(now.year, now.month, now.day, 23, 50), "23:50".to_datetime + assert_equal DateTime.civil(now.year, now.month, now.day, 23, 50, 0, "-04:00"), "23:50 -0400".to_datetime + end + + def test_string_to_date + assert_equal Date.new(2005, 2, 27), "2005-02-27".to_date + assert_nil "".to_date + assert_equal Date.new(Date.today.year, 2, 3), "Feb 3rd".to_date + end + + protected + def with_env_tz(new_tz = 'US/Eastern') + old_tz, ENV['TZ'] = ENV['TZ'], new_tz + yield + ensure + old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ') + end +end + class StringBehaviourTest < ActiveSupport::TestCase def test_acts_like_string assert 'Bambi'.acts_like_string? @@ -315,22 +476,24 @@ class StringBehaviourTest < ActiveSupport::TestCase end class CoreExtStringMultibyteTest < ActiveSupport::TestCase - UNICODE_STRING = 'こにちわ' - ASCII_STRING = 'ohayo' - BYTE_STRING = "\270\236\010\210\245" + UTF8_STRING = 'こにちわ' + ASCII_STRING = 'ohayo'.encode('US-ASCII') + EUC_JP_STRING = 'さよなら'.encode('EUC-JP') + INVALID_UTF8_STRING = "\270\236\010\210\245" def test_core_ext_adds_mb_chars - assert_respond_to UNICODE_STRING, :mb_chars + assert_respond_to UTF8_STRING, :mb_chars end def test_string_should_recognize_utf8_strings - assert UNICODE_STRING.is_utf8? + assert UTF8_STRING.is_utf8? assert ASCII_STRING.is_utf8? - assert !BYTE_STRING.is_utf8? + assert !EUC_JP_STRING.is_utf8? + assert !INVALID_UTF8_STRING.is_utf8? end def test_mb_chars_returns_instance_of_proxy_class - assert_kind_of ActiveSupport::Multibyte.proxy_class, UNICODE_STRING.mb_chars + assert_kind_of ActiveSupport::Multibyte.proxy_class, UTF8_STRING.mb_chars end end @@ -486,12 +649,6 @@ class OutputSafetyTest < ActiveSupport::TestCase assert_equal 'foo'.to_yaml, 'foo'.html_safe.to_yaml(:foo => 1) end - test 'knows whether it is encoding aware' do - assert_deprecated do - assert 'ruby'.encoding_aware? - end - end - test "call to_param returns a normal string" do string = @string.html_safe assert string.html_safe? diff --git a/activesupport/test/core_ext/struct_test.rb b/activesupport/test/core_ext/struct_test.rb new file mode 100644 index 0000000000..0dff7b32d2 --- /dev/null +++ b/activesupport/test/core_ext/struct_test.rb @@ -0,0 +1,10 @@ +require 'abstract_unit' +require 'active_support/core_ext/struct' + +class StructExt < ActiveSupport::TestCase + def test_to_h + x = Struct.new(:foo, :bar) + z = x.new(1, 2) + assert_equal({ foo: 1, bar: 2 }, z.to_h) + end +end diff --git a/activesupport/test/core_ext/thread_test.rb b/activesupport/test/core_ext/thread_test.rb new file mode 100644 index 0000000000..6a7c6e0604 --- /dev/null +++ b/activesupport/test/core_ext/thread_test.rb @@ -0,0 +1,75 @@ +require 'abstract_unit' +require 'active_support/core_ext/thread' + +class ThreadExt < ActiveSupport::TestCase + def test_main_thread_variable_in_enumerator + assert_equal Thread.main, Thread.current + + Thread.current.thread_variable_set :foo, "bar" + + thread, value = Fiber.new { + Fiber.yield [Thread.current, Thread.current.thread_variable_get(:foo)] + }.resume + + assert_equal Thread.current, thread + assert_equal Thread.current.thread_variable_get(:foo), value + end + + def test_thread_variable_in_enumerator + Thread.new { + Thread.current.thread_variable_set :foo, "bar" + + thread, value = Fiber.new { + Fiber.yield [Thread.current, Thread.current.thread_variable_get(:foo)] + }.resume + + assert_equal Thread.current, thread + assert_equal Thread.current.thread_variable_get(:foo), value + }.join + end + + def test_thread_variables + assert_equal [], Thread.new { Thread.current.thread_variables }.join.value + + t = Thread.new { + Thread.current.thread_variable_set(:foo, "bar") + Thread.current.thread_variables + } + assert_equal [:foo], t.join.value + end + + def test_thread_variable? + assert_not Thread.new { Thread.current.thread_variable?("foo") }.join.value + t = Thread.new { + Thread.current.thread_variable_set("foo", "bar") + }.join + + assert t.thread_variable?("foo") + assert t.thread_variable?(:foo) + assert_not t.thread_variable?(:bar) + end + + def test_thread_variable_strings_and_symbols_are_the_same_key + t = Thread.new {}.join + t.thread_variable_set("foo", "bar") + assert_equal "bar", t.thread_variable_get(:foo) + end + + def test_thread_variable_frozen + t = Thread.new { }.join + t.freeze + assert_raises(RuntimeError) do + t.thread_variable_set(:foo, "bar") + end + end + + def test_thread_variable_frozen_after_set + t = Thread.new { }.join + t.thread_variable_set :foo, "bar" + t.freeze + assert_raises(RuntimeError) do + t.thread_variable_set(:baz, "qux") + end + end + +end diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb index 6d6757a1b6..41a1df084e 100644 --- a/activesupport/test/core_ext/time_ext_test.rb +++ b/activesupport/test/core_ext/time_ext_test.rb @@ -57,6 +57,54 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase end end + def test_seconds_until_end_of_day + assert_equal 0, Time.local(2005,1,1,23,59,59).seconds_until_end_of_day + assert_equal 1, Time.local(2005,1,1,23,59,58).seconds_until_end_of_day + assert_equal 60, Time.local(2005,1,1,23,58,59).seconds_until_end_of_day + assert_equal 3660, Time.local(2005,1,1,22,58,59).seconds_until_end_of_day + assert_equal 86399, Time.local(2005,1,1,0,0,0).seconds_until_end_of_day + end + + def test_seconds_until_end_of_day_at_daylight_savings_time_start + with_env_tz 'US/Eastern' do + # dt: US: 2005 April 3rd 2:00am ST => April 3rd 3:00am DT + assert_equal 21*3600, Time.local(2005,4,3,1,59,59).seconds_until_end_of_day, 'just before DST start' + assert_equal 21*3600-2, Time.local(2005,4,3,3,0,1).seconds_until_end_of_day, 'just after DST start' + end + + with_env_tz 'NZ' do + # dt: New Zealand: 2006 October 1st 2:00am ST => October 1st 3:00am DT + assert_equal 21*3600, Time.local(2006,10,1,1,59,59).seconds_until_end_of_day, 'just before DST start' + assert_equal 21*3600-2, Time.local(2006,10,1,3,0,1).seconds_until_end_of_day, 'just after DST start' + end + end + + def test_seconds_until_end_of_day_at_daylight_savings_time_end + with_env_tz 'US/Eastern' do + # st: US: 2005 October 30th 2:00am DT => October 30th 1:00am ST + # avoid setting a time between 1:00 and 2:00 since that requires specifying whether DST is active + assert_equal 24*3600, Time.local(2005,10,30,0,59,59).seconds_until_end_of_day, 'just before DST end' + assert_equal 22*3600-2, Time.local(2005,10,30,2,0,1).seconds_until_end_of_day, 'just after DST end' + + # now set a time between 1:00 and 2:00 by specifying whether DST is active + # uses: Time.local( sec, min, hour, day, month, year, wday, yday, isdst, tz ) + assert_equal 24*3600-30*60-1, Time.local(0,30,1,30,10,2005,0,0,true,ENV['TZ']).seconds_until_end_of_day, 'before DST end' + assert_equal 23*3600-30*60-1, Time.local(0,30,1,30,10,2005,0,0,false,ENV['TZ']).seconds_until_end_of_day, 'after DST end' + end + + with_env_tz 'NZ' do + # st: New Zealand: 2006 March 19th 3:00am DT => March 19th 2:00am ST + # avoid setting a time between 2:00 and 3:00 since that requires specifying whether DST is active + assert_equal 23*3600, Time.local(2006,3,19,1,59,59).seconds_until_end_of_day, 'just before DST end' + assert_equal 21*3600-2, Time.local(2006,3,19,3,0,1).seconds_until_end_of_day, 'just after DST end' + + # now set a time between 2:00 and 3:00 by specifying whether DST is active + # uses: Time.local( sec, min, hour, day, month, year, wday, yday, isdst, tz ) + assert_equal 23*3600-30*60-1, Time.local(0,30,2,19,3,2006,0,0,true, ENV['TZ']).seconds_until_end_of_day, 'before DST end' + assert_equal 22*3600-30*60-1, Time.local(0,30,2,19,3,2006,0,0,false,ENV['TZ']).seconds_until_end_of_day, 'after DST end' + end + end + def test_beginning_of_day assert_equal Time.local(2005,2,4,0,0,0), Time.local(2005,2,4,10,10,10).beginning_of_day with_env_tz 'US/Eastern' do @@ -69,10 +117,26 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase end end + def test_middle_of_day + assert_equal Time.local(2005,2,4,12,0,0), Time.local(2005,2,4,10,10,10).middle_of_day + with_env_tz 'US/Eastern' do + assert_equal Time.local(2006,4,2,12,0,0), Time.local(2006,4,2,10,10,10).middle_of_day, 'start DST' + assert_equal Time.local(2006,10,29,12,0,0), Time.local(2006,10,29,10,10,10).middle_of_day, 'ends DST' + end + with_env_tz 'NZ' do + assert_equal Time.local(2006,3,19,12,0,0), Time.local(2006,3,19,10,10,10).middle_of_day, 'ends DST' + assert_equal Time.local(2006,10,1,12,0,0), Time.local(2006,10,1,10,10,10).middle_of_day, 'start DST' + end + end + def test_beginning_of_hour assert_equal Time.local(2005,2,4,19,0,0), Time.local(2005,2,4,19,30,10).beginning_of_hour end + def test_beginning_of_minute + assert_equal Time.local(2005,2,4,19,30,0), Time.local(2005,2,4,19,30,10).beginning_of_minute + end + def test_end_of_day assert_equal Time.local(2007,8,12,23,59,59,Rational(999999999, 1000)), Time.local(2007,8,12,10,10,10).end_of_day with_env_tz 'US/Eastern' do @@ -89,6 +153,10 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase assert_equal Time.local(2005,2,4,19,59,59,Rational(999999999, 1000)), Time.local(2005,2,4,19,30,10).end_of_hour end + def test_end_of_minute + assert_equal Time.local(2005,2,4,19,30,59,Rational(999999999, 1000)), Time.local(2005,2,4,19,30,10).end_of_minute + end + def test_last_year assert_equal Time.local(2004,6,5,10), Time.local(2005,6,5,10,0,0).last_year end @@ -453,6 +521,9 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase with_env_tz "US/Central" do assert_equal "Thu, 05 Feb 2009 14:30:05 -0600", Time.local(2009, 2, 5, 14, 30, 5).to_s(:rfc822) assert_equal "Mon, 09 Jun 2008 04:05:01 -0500", Time.local(2008, 6, 9, 4, 5, 1).to_s(:rfc822) + assert_equal "2009-02-05T14:30:05-06:00", Time.local(2009, 2, 5, 14, 30, 5).to_s(:iso8601) + assert_equal "2008-06-09T04:05:01-05:00", Time.local(2008, 6, 9, 4, 5, 1).to_s(:iso8601) + assert_equal "2009-02-05T14:30:05Z", Time.utc(2009, 2, 5, 14, 30, 5).to_s(:iso8601) end end @@ -478,7 +549,11 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase end def test_to_time - assert_equal Time.local(2005, 2, 21, 17, 44, 30), Time.local(2005, 2, 21, 17, 44, 30).to_time + with_env_tz 'US/Eastern' do + assert_equal Time, Time.local(2005, 2, 21, 17, 44, 30).to_time.class + assert_equal Time.local(2005, 2, 21, 17, 44, 30), Time.local(2005, 2, 21, 17, 44, 30).to_time + assert_equal Time.local(2005, 2, 21, 17, 44, 30).utc_offset, Time.local(2005, 2, 21, 17, 44, 30).to_time.utc_offset + end end # NOTE: this test seems to fail (changeset 1958) only on certain platforms, @@ -518,46 +593,6 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase assert_equal 29, Time.days_in_month(2) end - def test_time_with_datetime_fallback - assert_equal Time.time_with_datetime_fallback(:utc, 2005, 2, 21, 17, 44, 30), Time.utc(2005, 2, 21, 17, 44, 30) - assert_equal Time.time_with_datetime_fallback(:local, 2005, 2, 21, 17, 44, 30), Time.local(2005, 2, 21, 17, 44, 30) - assert_equal Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30), DateTime.civil(2039, 2, 21, 17, 44, 30, 0) - assert_equal Time.time_with_datetime_fallback(:local, 2039, 2, 21, 17, 44, 30), DateTime.civil_from_format(:local, 2039, 2, 21, 17, 44, 30) - assert_equal Time.time_with_datetime_fallback(:utc, 1900, 2, 21, 17, 44, 30), DateTime.civil(1900, 2, 21, 17, 44, 30, 0) - assert_equal Time.time_with_datetime_fallback(:utc, 2005), Time.utc(2005) - assert_equal Time.time_with_datetime_fallback(:utc, 2039), DateTime.civil(2039, 1, 1, 0, 0, 0, 0) - assert_equal Time.time_with_datetime_fallback(:utc, 2005, 2, 21, 17, 44, 30, 1), Time.utc(2005, 2, 21, 17, 44, 30, 1) #with usec - # This won't overflow on 64bit linux - unless time_is_64bits? - assert_equal Time.time_with_datetime_fallback(:local, 1900, 2, 21, 17, 44, 30), DateTime.civil_from_format(:local, 1900, 2, 21, 17, 44, 30) - assert_equal Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30, 1), - DateTime.civil(2039, 2, 21, 17, 44, 30, 0, 0) - assert_equal ::Date::ITALY, Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30, 1).start # use Ruby's default start value - end - silence_warnings do - 0.upto(138) do |year| - [:utc, :local].each do |format| - assert_equal year, Time.time_with_datetime_fallback(format, year).year - end - end - end - end - - def test_utc_time - assert_equal Time.utc_time(2005, 2, 21, 17, 44, 30), Time.utc(2005, 2, 21, 17, 44, 30) - assert_equal Time.utc_time(2039, 2, 21, 17, 44, 30), DateTime.civil(2039, 2, 21, 17, 44, 30, 0) - assert_equal Time.utc_time(1901, 2, 21, 17, 44, 30), DateTime.civil(1901, 2, 21, 17, 44, 30, 0) - end - - def test_local_time - assert_equal Time.local_time(2005, 2, 21, 17, 44, 30), Time.local(2005, 2, 21, 17, 44, 30) - assert_equal Time.local_time(2039, 2, 21, 17, 44, 30), DateTime.civil_from_format(:local, 2039, 2, 21, 17, 44, 30) - - unless time_is_64bits? - assert_equal Time.local_time(1901, 2, 21, 17, 44, 30), DateTime.civil_from_format(:local, 1901, 2, 21, 17, 44, 30) - end - end - def test_last_month_on_31st assert_equal Time.local(2004, 2, 29), Time.local(2004, 3, 31).last_month end @@ -669,6 +704,82 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase assert_equal(-1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone['UTC'] )) end + def test_at_with_datetime + assert_equal Time.utc(2000, 1, 1, 0, 0, 0), Time.at(DateTime.civil(2000, 1, 1, 0, 0, 0)) + + # Only test this if the underlying Time.at raises a TypeError + begin + Time.at_without_coercion(Time.now, 0) + rescue TypeError + assert_raise(TypeError) { assert_equal(Time.utc(2000, 1, 1, 0, 0, 0), Time.at(DateTime.civil(2000, 1, 1, 0, 0, 0), 0)) } + end + end + + def test_at_with_datetime_returns_local_time + with_env_tz 'US/Eastern' do + dt = DateTime.civil(2000, 1, 1, 0, 0, 0, '+0') + assert_equal Time.local(1999, 12, 31, 19, 0, 0), Time.at(dt) + assert_equal 'EST', Time.at(dt).zone + assert_equal(-18000, Time.at(dt).utc_offset) + + # Daylight savings + dt = DateTime.civil(2000, 7, 1, 1, 0, 0, '+1') + assert_equal Time.local(2000, 6, 30, 20, 0, 0), Time.at(dt) + assert_equal 'EDT', Time.at(dt).zone + assert_equal(-14400, Time.at(dt).utc_offset) + end + end + + def test_at_with_time_with_zone + assert_equal Time.utc(2000, 1, 1, 0, 0, 0), Time.at(ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC'])) + + # Only test this if the underlying Time.at raises a TypeError + begin + Time.at_without_coercion(Time.now, 0) + rescue TypeError + assert_raise(TypeError) { assert_equal(Time.utc(2000, 1, 1, 0, 0, 0), Time.at(ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC']), 0)) } + end + end + + def test_at_with_time_with_zone_returns_local_time + with_env_tz 'US/Eastern' do + twz = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['London']) + assert_equal Time.local(1999, 12, 31, 19, 0, 0), Time.at(twz) + assert_equal 'EST', Time.at(twz).zone + assert_equal(-18000, Time.at(twz).utc_offset) + + # Daylight savings + twz = ActiveSupport::TimeWithZone.new(Time.utc(2000, 7, 1, 0, 0, 0), ActiveSupport::TimeZone['London']) + assert_equal Time.local(2000, 6, 30, 20, 0, 0), Time.at(twz) + assert_equal 'EDT', Time.at(twz).zone + assert_equal(-14400, Time.at(twz).utc_offset) + end + end + + def test_at_with_time_microsecond_precision + assert_equal Time.at(Time.utc(2000, 1, 1, 0, 0, 0, 111)).to_f, Time.utc(2000, 1, 1, 0, 0, 0, 111).to_f + end + + def test_at_with_utc_time + with_env_tz 'US/Eastern' do + assert_equal Time.utc(2000), Time.at(Time.utc(2000)) + assert_equal 'UTC', Time.at(Time.utc(2000)).zone + assert_equal(0, Time.at(Time.utc(2000)).utc_offset) + end + end + + def test_at_with_local_time + with_env_tz 'US/Eastern' do + assert_equal Time.local(2000), Time.at(Time.local(2000)) + assert_equal 'EST', Time.at(Time.local(2000)).zone + assert_equal(-18000, Time.at(Time.local(2000)).utc_offset) + + assert_equal Time.local(2000, 7, 1), Time.at(Time.local(2000, 7, 1)) + assert_equal 'EDT', Time.at(Time.local(2000, 7, 1)).zone + assert_equal(-14400, Time.at(Time.local(2000, 7, 1)).utc_offset) + end + end + def test_eql? assert_equal true, Time.utc(2000).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC']) ) assert_equal true, Time.utc(2000).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]) ) @@ -738,9 +849,6 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ') end - def time_is_64bits? - Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30, 1).is_a?(Time) - end end class TimeExtMarshalingTest < ActiveSupport::TestCase diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb index 1293f104e5..5494824a40 100644 --- a/activesupport/test/core_ext/time_with_zone_test.rb +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -75,11 +75,16 @@ class TimeWithZoneTest < ActiveSupport::TestCase def test_to_json_with_use_standard_json_time_format_config_set_to_true old, ActiveSupport.use_standard_json_time_format = ActiveSupport.use_standard_json_time_format, true - assert_equal "\"1999-12-31T19:00:00-05:00\"", ActiveSupport::JSON.encode(@twz) + assert_equal "\"1999-12-31T19:00:00.000-05:00\"", ActiveSupport::JSON.encode(@twz) ensure ActiveSupport.use_standard_json_time_format = old end + def test_to_json_when_wrapping_a_date_time + twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000), @time_zone) + assert_equal '"1999-12-31T19:00:00.000-05:00"', ActiveSupport::JSON.encode(twz) + end + def test_nsec local = Time.local(2011,6,7,23,59,59,Rational(999999999, 1000)) with_zone = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Hawaii"], local) @@ -326,8 +331,23 @@ class TimeWithZoneTest < ActiveSupport::TestCase assert_equal 946684800, twz.to_i end + def test_to_r + result = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), ActiveSupport::TimeZone['Hawaii']).to_r + assert_equal Rational(946684800, 1), result + assert_kind_of Rational, result + end + + def test_time_at + time = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), ActiveSupport::TimeZone['Hawaii']) + assert_equal time, Time.at(time) + end + def test_to_time - assert_equal @twz, @twz.to_time + with_env_tz 'US/Eastern' do + assert_equal Time, @twz.to_time.class + assert_equal Time.local(1999, 12, 31, 19), @twz.to_time + assert_equal Time.local(1999, 12, 31, 19).utc_offset, @twz.to_time.utc_offset + end end def test_to_date @@ -430,6 +450,16 @@ class TimeWithZoneTest < ActiveSupport::TestCase assert_equal 0, twz.usec end + def test_usec_returns_sec_fraction_when_datetime_is_wrapped + twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)), @time_zone) + assert_equal 500000, twz.usec + end + + def test_nsec_returns_sec_fraction_when_datetime_is_wrapped + twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)), @time_zone) + assert_equal 500000000, twz.nsec + end + def test_utc_to_local_conversion_saves_period_in_instance_variable assert_nil @twz.instance_variable_get('@period') @twz.time @@ -535,6 +565,20 @@ class TimeWithZoneTest < ActiveSupport::TestCase assert_equal "Fri, 31 Dec 1999 19:59:59 EST -05:00", twz.end_of_hour.inspect end + def test_beginning_of_minute + utc = Time.utc(2000, 1, 1, 0, 30, 10) + twz = ActiveSupport::TimeWithZone.new(utc, @time_zone) + assert_equal "Fri, 31 Dec 1999 19:30:10 EST -05:00", twz.inspect + assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", twz.beginning_of_hour.inspect + end + + def test_end_of_minute + utc = Time.utc(2000, 1, 1, 0, 30, 10) + twz = ActiveSupport::TimeWithZone.new(utc, @time_zone) + assert_equal "Fri, 31 Dec 1999 19:30:10 EST -05:00", twz.inspect + assert_equal "Fri, 31 Dec 1999 19:30:59 EST -05:00", twz.end_of_minute.inspect + end + def test_since assert_equal "Fri, 31 Dec 1999 19:00:01 EST -05:00", @twz.since(1).inspect end @@ -750,6 +794,14 @@ class TimeWithZoneTest < ActiveSupport::TestCase assert_equal "Sun, 15 Jul 2007 10:30:00 EDT -04:00", (twz - 1.year).inspect end + def test_no_method_error_has_proper_context + e = assert_raises(NoMethodError) { + @twz.this_method_does_not_exist + } + assert_equal "undefined method `this_method_does_not_exist' for Fri, 31 Dec 1999 19:00:00 EST -05:00:Time", e.message + assert_no_match "rescue", e.backtrace.first + end + protected def with_env_tz(new_tz = 'US/Eastern') old_tz, ENV['TZ'] = ENV['TZ'], new_tz @@ -945,6 +997,15 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < ActiveSupport::TestCase Time.zone = nil end + def test_time_in_time_zone_doesnt_affect_receiver + with_env_tz 'Europe/London' do + time = Time.local(2000, 7, 1) + time_with_zone = time.in_time_zone('Eastern Time (US & Canada)') + assert_equal Time.utc(2000, 6, 30, 23, 0, 0), time_with_zone + assert_not time.utc?, 'time expected to be local, but is UTC' + end + end + protected def with_env_tz(new_tz = 'US/Eastern') old_tz, ENV['TZ'] = ENV['TZ'], new_tz @@ -953,3 +1014,131 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < ActiveSupport::TestCase old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ') end end + +class TimeWithZoneMethodsForDate < ActiveSupport::TestCase + def setup + @d = Date.civil(2000) + end + + def teardown + Time.zone = nil + end + + def test_in_time_zone + with_tz_default 'Alaska' do + assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @d.in_time_zone.inspect + end + with_tz_default 'Hawaii' do + assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @d.in_time_zone.inspect + end + with_tz_default nil do + assert_equal @d.to_time, @d.in_time_zone + end + end + + def test_nil_time_zone + with_tz_default nil do + assert !@d.in_time_zone.respond_to?(:period), 'no period method' + end + end + + def test_in_time_zone_with_argument + with_tz_default 'Eastern Time (US & Canada)' do # Time.zone will not affect #in_time_zone(zone) + assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @d.in_time_zone('Alaska').inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @d.in_time_zone('Hawaii').inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @d.in_time_zone('UTC').inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @d.in_time_zone(-9.hours).inspect + end + end + + def test_in_time_zone_with_invalid_argument + assert_raise(ArgumentError) { @d.in_time_zone("No such timezone exists") } + assert_raise(ArgumentError) { @d.in_time_zone(-15.hours) } + assert_raise(ArgumentError) { @d.in_time_zone(Object.new) } + end + + protected + def with_tz_default(tz = nil) + old_tz = Time.zone + Time.zone = tz + yield + ensure + Time.zone = old_tz + end +end + +class TimeWithZoneMethodsForString < ActiveSupport::TestCase + def setup + @s = "Sat, 01 Jan 2000 00:00:00" + @u = "Sat, 01 Jan 2000 00:00:00 UTC +00:00" + @z = "Fri, 31 Dec 1999 19:00:00 EST -05:00" + end + + def teardown + Time.zone = nil + end + + def test_in_time_zone + with_tz_default 'Alaska' do + assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @s.in_time_zone.inspect + assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @u.in_time_zone.inspect + assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @z.in_time_zone.inspect + end + with_tz_default 'Hawaii' do + assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @s.in_time_zone.inspect + assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @u.in_time_zone.inspect + assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @z.in_time_zone.inspect + end + with_tz_default nil do + assert_equal @s.to_time, @s.in_time_zone + assert_equal @u.to_time, @u.in_time_zone + assert_equal @z.to_time, @z.in_time_zone + end + end + + def test_nil_time_zone + with_tz_default nil do + assert !@s.in_time_zone.respond_to?(:period), 'no period method' + assert !@u.in_time_zone.respond_to?(:period), 'no period method' + assert !@z.in_time_zone.respond_to?(:period), 'no period method' + end + end + + def test_in_time_zone_with_argument + with_tz_default 'Eastern Time (US & Canada)' do # Time.zone will not affect #in_time_zone(zone) + assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @s.in_time_zone('Alaska').inspect + assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @u.in_time_zone('Alaska').inspect + assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @z.in_time_zone('Alaska').inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @s.in_time_zone('Hawaii').inspect + assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @u.in_time_zone('Hawaii').inspect + assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @z.in_time_zone('Hawaii').inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @s.in_time_zone('UTC').inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @u.in_time_zone('UTC').inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @z.in_time_zone('UTC').inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @s.in_time_zone(-9.hours).inspect + assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @u.in_time_zone(-9.hours).inspect + assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @z.in_time_zone(-9.hours).inspect + end + end + + def test_in_time_zone_with_invalid_argument + assert_raise(ArgumentError) { @s.in_time_zone("No such timezone exists") } + assert_raise(ArgumentError) { @u.in_time_zone("No such timezone exists") } + assert_raise(ArgumentError) { @z.in_time_zone("No such timezone exists") } + assert_raise(ArgumentError) { @s.in_time_zone(-15.hours) } + assert_raise(ArgumentError) { @u.in_time_zone(-15.hours) } + assert_raise(ArgumentError) { @z.in_time_zone(-15.hours) } + assert_raise(ArgumentError) { @s.in_time_zone(Object.new) } + assert_raise(ArgumentError) { @u.in_time_zone(Object.new) } + assert_raise(ArgumentError) { @z.in_time_zone(Object.new) } + end + + protected + def with_tz_default(tz = nil) + old_tz = Time.zone + Time.zone = tz + yield + ensure + Time.zone = old_tz + end +end diff --git a/activesupport/test/dependencies/raises_exception_without_blame_file.rb b/activesupport/test/dependencies/raises_exception_without_blame_file.rb new file mode 100644 index 0000000000..4b2da6ff30 --- /dev/null +++ b/activesupport/test/dependencies/raises_exception_without_blame_file.rb @@ -0,0 +1,5 @@ +exception = Exception.new('I am not blamable!') +class << exception + undef_method(:blame_file!) +end +raise exception diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index e5bc806397..2392b71960 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -1,6 +1,7 @@ require 'abstract_unit' require 'pp' require 'active_support/dependencies' +require 'dependencies_test_helpers' module ModuleWithMissing mattr_accessor :missing_count @@ -19,25 +20,7 @@ class DependenciesTest < ActiveSupport::TestCase ActiveSupport::Dependencies.clear end - def with_loading(*from) - old_mechanism, ActiveSupport::Dependencies.mechanism = ActiveSupport::Dependencies.mechanism, :load - this_dir = File.dirname(__FILE__) - parent_dir = File.dirname(this_dir) - path_copy = $LOAD_PATH.dup - $LOAD_PATH.unshift(parent_dir) unless $LOAD_PATH.include?(parent_dir) - prior_autoload_paths = ActiveSupport::Dependencies.autoload_paths - ActiveSupport::Dependencies.autoload_paths = from.collect { |f| "#{this_dir}/#{f}" } - yield - ensure - $LOAD_PATH.replace(path_copy) - ActiveSupport::Dependencies.autoload_paths = prior_autoload_paths - ActiveSupport::Dependencies.mechanism = old_mechanism - ActiveSupport::Dependencies.explicitly_unloadable_constants = [] - end - - def with_autoloading_fixtures(&block) - with_loading 'autoloading_fixtures', &block - end + include DependenciesTestHelpers def test_depend_on_path skip "LoadError#path does not exist" if RUBY_VERSION < '2.0.0' @@ -52,6 +35,17 @@ class DependenciesTest < ActiveSupport::TestCase assert_equal expected.path, e.path end + def test_require_dependency_accepts_an_object_which_implements_to_path + o = Object.new + def o.to_path; 'dependencies/service_one'; end + assert_nothing_raised { + require_dependency o + } + assert defined?(ServiceOne) + ensure + remove_constants(:ServiceOne) + end + def test_tracking_loaded_files require_dependency 'dependencies/service_one' require_dependency 'dependencies/service_two' @@ -93,6 +87,14 @@ class DependenciesTest < ActiveSupport::TestCase end end + def test_dependency_which_raises_doesnt_blindly_call_blame_file! + with_loading do + filename = 'dependencies/raises_exception_without_blame_file' + + assert_raises(Exception) { require_dependency filename } + end + end + def test_warnings_should_be_enabled_on_first_load with_loading 'dependencies' do old_warnings, ActiveSupport::Dependencies.warnings_on_first_load = ActiveSupport::Dependencies.warnings_on_first_load, true @@ -147,7 +149,8 @@ class DependenciesTest < ActiveSupport::TestCase def test_circular_autoloading_detection with_autoloading_fixtures do - assert_raise(RuntimeError, "Circular dependency detected while autoloading constant Circular1") { Circular1 } + e = assert_raise(RuntimeError) { Circular1 } + assert_equal "Circular dependency detected while autoloading constant Circular1", e.message end end @@ -379,12 +382,10 @@ class DependenciesTest < ActiveSupport::TestCase end def test_smart_name_error_strings - begin - Object.module_eval "ImaginaryObject" - flunk "No raise!!" - rescue NameError => e - assert e.message.include?("uninitialized constant ImaginaryObject") - end + Object.module_eval "ImaginaryObject" + flunk "No raise!!" + rescue NameError => e + assert e.message.include?("uninitialized constant ImaginaryObject") end def test_loadable_constants_for_path_should_handle_empty_autoloads @@ -544,7 +545,6 @@ class DependenciesTest < ActiveSupport::TestCase m = Module.new m.module_eval "def a() CountingLoader; end" extend m - kls = nil with_autoloading_fixtures do kls = nil assert_nothing_raised { kls = a } @@ -658,6 +658,14 @@ class DependenciesTest < ActiveSupport::TestCase Object.class_eval { remove_const :E } end + def test_constants_in_capitalized_nesting_marked_as_autoloaded + with_autoloading_fixtures do + ActiveSupport::Dependencies.load_missing_constant(HTML, "SomeClass") + + assert ActiveSupport::Dependencies.autoloaded?("HTML::SomeClass") + end + end + def test_unloadable with_autoloading_fixtures do Object.const_set :M, Module.new @@ -896,7 +904,7 @@ class DependenciesTest < ActiveSupport::TestCase def test_autoload_doesnt_shadow_name_error with_autoloading_fixtures do Object.send(:remove_const, :RaisesNameError) if defined?(::RaisesNameError) - 2.times do |i| + 2.times do begin ::RaisesNameError::FooBarBaz.object_id flunk 'should have raised NameError when autoloaded file referenced FooBarBaz' @@ -927,10 +935,30 @@ class DependenciesTest < ActiveSupport::TestCase assert ! defined?(DeleteMe) end + def test_remove_constant_does_not_trigger_loading_autoloads + constant = 'ShouldNotBeAutoloaded' + Object.class_eval do + autoload constant, File.expand_path('../autoloading_fixtures/should_not_be_required', __FILE__) + end + + assert_nil ActiveSupport::Dependencies.remove_constant(constant), "Kernel#autoload has been triggered by remove_constant" + assert !defined?(ShouldNotBeAutoloaded) + end + + def test_remove_constant_does_not_autoload_already_removed_parents_as_a_side_effect + with_autoloading_fixtures do + _ = ::A # assignment to silence parse-time warning "possibly useless use of :: in void context" + _ = ::A::B # assignment to silence parse-time warning "possibly useless use of :: in void context" + ActiveSupport::Dependencies.remove_constant('A') + ActiveSupport::Dependencies.remove_constant('A::B') + assert !defined?(A) + end + end + def test_load_once_constants_should_not_be_unloaded with_autoloading_fixtures do ActiveSupport::Dependencies.autoload_once_paths = ActiveSupport::Dependencies.autoload_paths - ::A.to_s + _ = ::A # assignment to silence parse-time warning "possibly useless use of :: in void context" assert defined?(A) ActiveSupport::Dependencies.clear assert defined?(A) diff --git a/activesupport/test/dependencies_test_helpers.rb b/activesupport/test/dependencies_test_helpers.rb new file mode 100644 index 0000000000..9268512a97 --- /dev/null +++ b/activesupport/test/dependencies_test_helpers.rb @@ -0,0 +1,27 @@ +module DependenciesTestHelpers + def with_loading(*from) + old_mechanism, ActiveSupport::Dependencies.mechanism = ActiveSupport::Dependencies.mechanism, :load + this_dir = File.dirname(__FILE__) + parent_dir = File.dirname(this_dir) + path_copy = $LOAD_PATH.dup + $LOAD_PATH.unshift(parent_dir) unless $LOAD_PATH.include?(parent_dir) + prior_autoload_paths = ActiveSupport::Dependencies.autoload_paths + ActiveSupport::Dependencies.autoload_paths = from.collect { |f| "#{this_dir}/#{f}" } + yield + ensure + $LOAD_PATH.replace(path_copy) + ActiveSupport::Dependencies.autoload_paths = prior_autoload_paths + ActiveSupport::Dependencies.mechanism = old_mechanism + ActiveSupport::Dependencies.explicitly_unloadable_constants = [] + end + + def with_autoloading_fixtures(&block) + with_loading 'autoloading_fixtures', &block + end + + def remove_constants(*constants) + constants.each do |constant| + Object.send(:remove_const, constant) if Object.const_defined?(constant) + end + end +end
\ No newline at end of file diff --git a/activesupport/test/deprecation_test.rb b/activesupport/test/deprecation_test.rb index c081103cc7..9674851b9d 100644 --- a/activesupport/test/deprecation_test.rb +++ b/activesupport/test/deprecation_test.rb @@ -9,7 +9,7 @@ class Deprecatee def old_request; @request end def partially(foo = nil) - ActiveSupport::Deprecation.warn('calling with foo=nil is out', caller) if foo.nil? + ActiveSupport::Deprecation.warn('calling with foo=nil is out') if foo.nil? end def not() 2 end @@ -75,6 +75,11 @@ class DeprecationTest < ActiveSupport::TestCase end end + def test_deprecate_object + deprecated_object = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(Object.new, ':bomb:') + assert_deprecated(/:bomb:/) { deprecated_object.to_s } + end + def test_nil_behavior_is_ignored ActiveSupport::Deprecation.behavior = nil assert_deprecated(/foo=nil/) { @dtc.partially } @@ -93,6 +98,22 @@ class DeprecationTest < ActiveSupport::TestCase assert_match(/foo=nil/, @b) end + def test_raise_behaviour + ActiveSupport::Deprecation.behavior = :raise + + message = 'Revise this deprecated stuff now!' + callstack = %w(foo bar baz) + + begin + ActiveSupport::Deprecation.behavior.first.call(message, callstack) + rescue ActiveSupport::DeprecationException => e + assert_equal message, e.message + assert_equal callstack, e.backtrace + else + flunk 'the :raise deprecation behaviour should raise the expected exception' + end + end + def test_default_stderr_behavior ActiveSupport::Deprecation.behavior = :stderr behavior = ActiveSupport::Deprecation.behavior.first @@ -119,9 +140,10 @@ class DeprecationTest < ActiveSupport::TestCase ActiveSupport::Deprecation.behavior = :silence behavior = ActiveSupport::Deprecation.behavior.first - assert_blank capture(:stderr) { + stderr_output = capture(:stderr) { assert_nil behavior.call('Some error!', ['call stack!']) } + assert stderr_output.blank? end def test_deprecated_instance_variable_proxy @@ -138,6 +160,7 @@ class DeprecationTest < ActiveSupport::TestCase def test_deprecated_constant_proxy assert_not_deprecated { Deprecatee::B::C } assert_deprecated('Deprecatee::A') { assert_equal Deprecatee::B::C, Deprecatee::A } + assert_not_deprecated { assert_equal Deprecatee::B::C.class, Deprecatee::A.class } end def test_assert_deprecation_without_match @@ -254,10 +277,10 @@ class DeprecationTest < ActiveSupport::TestCase klass::OLD.to_s end end - + def test_deprecated_instance_variable_with_instance_deprecator deprecator = deprecator_with_messages - + klass = Class.new() do def initialize(deprecator) @request = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(self, :request, :@request, deprecator) diff --git a/activesupport/test/descendants_tracker_test_cases.rb b/activesupport/test/descendants_tracker_test_cases.rb index 066ec8549b..69e046998e 100644 --- a/activesupport/test/descendants_tracker_test_cases.rb +++ b/activesupport/test/descendants_tracker_test_cases.rb @@ -1,3 +1,5 @@ +require 'set' + module DescendantsTrackerTestCases class Parent extend ActiveSupport::DescendantsTracker @@ -18,15 +20,15 @@ module DescendantsTrackerTestCases ALL = [Parent, Child1, Child2, Grandchild1, Grandchild2] def test_descendants - assert_equal [Child1, Grandchild1, Grandchild2, Child2], Parent.descendants - assert_equal [Grandchild1, Grandchild2], Child1.descendants - assert_equal [], Child2.descendants + assert_equal_sets [Child1, Grandchild1, Grandchild2, Child2], Parent.descendants + assert_equal_sets [Grandchild1, Grandchild2], Child1.descendants + assert_equal_sets [], Child2.descendants end def test_direct_descendants - assert_equal [Child1, Child2], Parent.direct_descendants - assert_equal [Grandchild1, Grandchild2], Child1.direct_descendants - assert_equal [], Child2.direct_descendants + assert_equal_sets [Child1, Child2], Parent.direct_descendants + assert_equal_sets [Grandchild1, Grandchild2], Child1.direct_descendants + assert_equal_sets [], Child2.direct_descendants end def test_clear @@ -40,6 +42,10 @@ module DescendantsTrackerTestCases protected + def assert_equal_sets(expected, actual) + assert_equal Set.new(expected), Set.new(actual) + end + def mark_as_autoloaded(*klasses) # If ActiveSupport::Dependencies is not loaded, forget about autoloading. # This allows using AS::DescendantsTracker without AS::Dependencies. @@ -56,4 +62,4 @@ module DescendantsTrackerTestCases ActiveSupport::Dependencies.autoloaded_constants = old_autoloaded if defined? ActiveSupport::Dependencies ActiveSupport::DescendantsTracker.class_eval("@@direct_descendants").replace(old_descendants) end -end
\ No newline at end of file +end diff --git a/activesupport/test/descendants_tracker_with_autoloading_test.rb b/activesupport/test/descendants_tracker_with_autoloading_test.rb index 9180f1f977..a2ae066a21 100644 --- a/activesupport/test/descendants_tracker_with_autoloading_test.rb +++ b/activesupport/test/descendants_tracker_with_autoloading_test.rb @@ -6,7 +6,7 @@ require 'descendants_tracker_test_cases' class DescendantsTrackerWithAutoloadingTest < ActiveSupport::TestCase include DescendantsTrackerTestCases - def test_clear_with_autoloaded_parent_children_and_granchildren + def test_clear_with_autoloaded_parent_children_and_grandchildren mark_as_autoloaded(*ALL) do ActiveSupport::DescendantsTracker.clear ALL.each do |k| @@ -15,20 +15,20 @@ class DescendantsTrackerWithAutoloadingTest < ActiveSupport::TestCase end end - def test_clear_with_autoloaded_children_and_granchildren + def test_clear_with_autoloaded_children_and_grandchildren mark_as_autoloaded Child1, Grandchild1, Grandchild2 do ActiveSupport::DescendantsTracker.clear - assert_equal [Child2], Parent.descendants - assert_equal [], Child2.descendants + assert_equal_sets [Child2], Parent.descendants + assert_equal_sets [], Child2.descendants end end - def test_clear_with_autoloaded_granchildren + def test_clear_with_autoloaded_grandchildren mark_as_autoloaded Grandchild1, Grandchild2 do ActiveSupport::DescendantsTracker.clear - assert_equal [Child1, Child2], Parent.descendants - assert_equal [], Child1.descendants - assert_equal [], Child2.descendants + assert_equal_sets [Child1, Child2], Parent.descendants + assert_equal_sets [], Child1.descendants + assert_equal_sets [], Child2.descendants end end end diff --git a/activesupport/test/descendants_tracker_without_autoloading_test.rb b/activesupport/test/descendants_tracker_without_autoloading_test.rb index 74669aaca1..00b449af51 100644 --- a/activesupport/test/descendants_tracker_without_autoloading_test.rb +++ b/activesupport/test/descendants_tracker_without_autoloading_test.rb @@ -4,4 +4,14 @@ require 'descendants_tracker_test_cases' class DescendantsTrackerWithoutAutoloadingTest < ActiveSupport::TestCase include DescendantsTrackerTestCases + + # Regression test for #8422. https://github.com/rails/rails/issues/8442 + def test_clear_without_autoloaded_singleton_parent + mark_as_autoloaded do + parent_instance = Parent.new + parent_instance.singleton_class.descendants + ActiveSupport::DescendantsTracker.clear + assert !ActiveSupport::DescendantsTracker.class_variable_get(:@@direct_descendants).key?(parent_instance.singleton_class) + end + end end diff --git a/activesupport/test/fixtures/xml/jdom_doctype.dtd b/activesupport/test/fixtures/xml/jdom_doctype.dtd new file mode 100644 index 0000000000..89480496ef --- /dev/null +++ b/activesupport/test/fixtures/xml/jdom_doctype.dtd @@ -0,0 +1 @@ +<!ENTITY a "external entity"> diff --git a/activesupport/test/fixtures/xml/jdom_entities.txt b/activesupport/test/fixtures/xml/jdom_entities.txt new file mode 100644 index 0000000000..0337fdaa08 --- /dev/null +++ b/activesupport/test/fixtures/xml/jdom_entities.txt @@ -0,0 +1 @@ +<!ENTITY a "hello"> diff --git a/activesupport/test/fixtures/xml/jdom_include.txt b/activesupport/test/fixtures/xml/jdom_include.txt new file mode 100644 index 0000000000..239ca3afaf --- /dev/null +++ b/activesupport/test/fixtures/xml/jdom_include.txt @@ -0,0 +1 @@ +include me diff --git a/activesupport/test/gzip_test.rb b/activesupport/test/gzip_test.rb index 75a0505899..0e3cf3b429 100644 --- a/activesupport/test/gzip_test.rb +++ b/activesupport/test/gzip_test.rb @@ -4,6 +4,12 @@ require 'active_support/core_ext/object/blank' class GzipTest < ActiveSupport::TestCase def test_compress_should_decompress_to_the_same_value assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World")) + assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World", Zlib::NO_COMPRESSION)) + assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World", Zlib::BEST_SPEED)) + assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World", Zlib::BEST_COMPRESSION)) + assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World", nil, Zlib::FILTERED)) + assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World", nil, Zlib::HUFFMAN_ONLY)) + assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World", nil, nil)) end def test_compress_should_return_a_binary_string @@ -12,4 +18,16 @@ class GzipTest < ActiveSupport::TestCase assert_equal Encoding.find('binary'), compressed.encoding assert !compressed.blank?, "a compressed blank string should not be blank" end + + def test_compress_should_return_gzipped_string_by_compression_level + source_string = "Hello World"*100 + + gzipped_by_speed = ActiveSupport::Gzip.compress(source_string, Zlib::BEST_SPEED) + assert_equal 1, Zlib::GzipReader.new(StringIO.new(gzipped_by_speed)).level + + gzipped_by_best_compression = ActiveSupport::Gzip.compress(source_string, Zlib::BEST_COMPRESSION) + assert_equal 9, Zlib::GzipReader.new(StringIO.new(gzipped_by_best_compression)).level + + assert_equal true, (gzipped_by_best_compression.bytesize < gzipped_by_speed.bytesize) + end end diff --git a/activesupport/test/i18n_test.rb b/activesupport/test/i18n_test.rb index ddbba444cf..5ef59b6e6b 100644 --- a/activesupport/test/i18n_test.rb +++ b/activesupport/test/i18n_test.rb @@ -62,7 +62,7 @@ class I18nTest < ActiveSupport::TestCase end def test_date_order - assert_equal [:year, :month, :day], I18n.translate(:'date.order') + assert_equal %w(year month day), I18n.translate(:'date.order') end def test_time_am diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb index aa41e57928..32739d45a9 100644 --- a/activesupport/test/inflector_test.rb +++ b/activesupport/test/inflector_test.rb @@ -61,9 +61,7 @@ class InflectorTest < ActiveSupport::TestCase assert_equal(plural, ActiveSupport::Inflector.pluralize(plural)) assert_equal(plural.capitalize, ActiveSupport::Inflector.pluralize(plural.capitalize)) end - end - SingularToPlural.each do |singular, plural| define_method "test_singularize_singular_#{singular}" do assert_equal(singular, ActiveSupport::Inflector.singularize(singular)) assert_equal(singular.capitalize, ActiveSupport::Inflector.singularize(singular.capitalize)) @@ -78,9 +76,10 @@ class InflectorTest < ActiveSupport::TestCase ActiveSupport::Inflector.inflections.uncountable "series" # Return to normal end - MixtureToTitleCase.each do |before, titleized| - define_method "test_titleize_#{before}" do - assert_equal(titleized, ActiveSupport::Inflector.titleize(before)) + MixtureToTitleCase.each_with_index do |(before, titleized), index| + define_method "test_titleize_mixture_to_title_case_#{index}" do + assert_equal(titleized, ActiveSupport::Inflector.titleize(before), "mixture \ + to TitleCase failed for #{before}") end end @@ -231,25 +230,35 @@ class InflectorTest < ActiveSupport::TestCase end end +# FIXME: get following tests to pass on jruby, currently skipped +# +# Currently this fails because ActiveSupport::Multibyte::Unicode#tidy_bytes +# required a specific Encoding::Converter(UTF-8 to UTF8-MAC) which unavailable on JRuby +# causing our tests to error out. +# related bug http://jira.codehaus.org/browse/JRUBY-7194 def test_parameterize + jruby_skip "UTF-8 to UTF8-MAC Converter is unavailable" StringToParameterized.each do |some_string, parameterized_string| assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string)) end end def test_parameterize_and_normalize + jruby_skip "UTF-8 to UTF8-MAC Converter is unavailable" StringToParameterizedAndNormalized.each do |some_string, parameterized_string| assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string)) end end def test_parameterize_with_custom_separator + jruby_skip "UTF-8 to UTF8-MAC Converter is unavailable" StringToParameterizeWithUnderscore.each do |some_string, parameterized_string| assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string, '_')) end end def test_parameterize_with_multi_character_separator + jruby_skip "UTF-8 to UTF8-MAC Converter is unavailable" StringToParameterized.each do |some_string, parameterized_string| assert_equal(parameterized_string.gsub('-', '__sep__'), ActiveSupport::Inflector.parameterize(some_string, '__sep__')) end @@ -326,7 +335,7 @@ class InflectorTest < ActiveSupport::TestCase end def test_underscore_as_reverse_of_dasherize - UnderscoresToDashes.each do |underscored, dasherized| + UnderscoresToDashes.each_key do |underscored| assert_equal(underscored, ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.dasherize(underscored))) end end @@ -361,7 +370,7 @@ class InflectorTest < ActiveSupport::TestCase inflect.singular(/s$/, '') inflect.singular(/es$/, '') - + inflect.irregular('el', 'los') end @@ -421,33 +430,36 @@ class InflectorTest < ActiveSupport::TestCase end end - Irregularities.each do |irregularity| - singular, plural = *irregularity - ActiveSupport::Inflector.inflections do |inflect| - define_method("test_irregularity_between_#{singular}_and_#{plural}") do - inflect.irregular(singular, plural) - assert_equal singular, ActiveSupport::Inflector.singularize(plural) - assert_equal plural, ActiveSupport::Inflector.pluralize(singular) + Irregularities.each do |singular, plural| + define_method("test_irregularity_between_#{singular}_and_#{plural}") do + with_dup do + ActiveSupport::Inflector.inflections do |inflect| + inflect.irregular(singular, plural) + assert_equal singular, ActiveSupport::Inflector.singularize(plural) + assert_equal plural, ActiveSupport::Inflector.pluralize(singular) + end end end end - Irregularities.each do |irregularity| - singular, plural = *irregularity - ActiveSupport::Inflector.inflections do |inflect| - define_method("test_pluralize_of_irregularity_#{plural}_should_be_the_same") do - inflect.irregular(singular, plural) - assert_equal plural, ActiveSupport::Inflector.pluralize(plural) + Irregularities.each do |singular, plural| + define_method("test_pluralize_of_irregularity_#{plural}_should_be_the_same") do + with_dup do + ActiveSupport::Inflector.inflections do |inflect| + inflect.irregular(singular, plural) + assert_equal plural, ActiveSupport::Inflector.pluralize(plural) + end end end end - Irregularities.each do |irregularity| - singular, plural = *irregularity - ActiveSupport::Inflector.inflections do |inflect| - define_method("test_singularize_of_irregularity_#{singular}_should_be_the_same") do - inflect.irregular(singular, plural) - assert_equal singular, ActiveSupport::Inflector.singularize(singular) + Irregularities.each do |singular, plural| + define_method("test_singularize_of_irregularity_#{singular}_should_be_the_same") do + with_dup do + ActiveSupport::Inflector.inflections do |inflect| + inflect.irregular(singular, plural) + assert_equal singular, ActiveSupport::Inflector.singularize(singular) + end end end end diff --git a/activesupport/test/inflector_test_cases.rb b/activesupport/test/inflector_test_cases.rb index ca4efd2e59..cc36d62138 100644 --- a/activesupport/test/inflector_test_cases.rb +++ b/activesupport/test/inflector_test_cases.rb @@ -105,7 +105,6 @@ module InflectorTestCases "prize" => "prizes", "edge" => "edges", - "cow" => "kine", "database" => "databases", # regression tests against improper inflection regexes @@ -310,5 +309,6 @@ module InflectorTestCases 'move' => 'moves', 'cow' => 'kine', 'zombie' => 'zombies', + 'genus' => 'genera' } end diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index d1454902e5..07d7e530ca 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -4,6 +4,12 @@ require 'active_support/json' require 'active_support/time' class TestJSONDecoding < ActiveSupport::TestCase + class Foo + def self.json_create(object) + "Foo" + end + end + TESTS = { %q({"returnTo":{"\/categories":"\/"}}) => {"returnTo" => {"/categories" => "/"}}, %q({"return\\"To\\":":{"\/categories":"\/"}}) => {"return\"To\":" => {"/categories" => "/"}}, @@ -52,36 +58,48 @@ class TestJSONDecoding < ActiveSupport::TestCase # tests escaping of "\n" char with Yaml backend %q({"a":"\n"}) => {"a"=>"\n"}, %q({"a":"\u000a"}) => {"a"=>"\n"}, - %q({"a":"Line1\u000aLine2"}) => {"a"=>"Line1\nLine2"} + %q({"a":"Line1\u000aLine2"}) => {"a"=>"Line1\nLine2"}, + # prevent json unmarshalling + %q({"json_class":"TestJSONDecoding::Foo"}) => {"json_class"=>"TestJSONDecoding::Foo"}, + # json "fragments" - these are invalid JSON, but ActionPack relies on this + %q("a string") => "a string", + %q(1.1) => 1.1, + %q(1) => 1, + %q(-1) => -1, + %q(true) => true, + %q(false) => false, + %q(null) => nil } - backends = [:ok_json] - backends << :json_gem if defined?(::JSON) - backends << :yajl if defined?(::Yajl) - - backends.each do |backend| - TESTS.each do |json, expected| - test "json decodes #{json} with the #{backend} backend" do - ActiveSupport.parse_json_times = true - silence_warnings do - ActiveSupport::JSON.with_backend backend do - assert_equal expected, ActiveSupport::JSON.decode(json) - end - end + TESTS.each_with_index do |(json, expected), index| + test "json decodes #{index}" do + prev = ActiveSupport.parse_json_times + ActiveSupport.parse_json_times = true + silence_warnings do + assert_equal expected, ActiveSupport::JSON.decode(json), "JSON decoding \ + failed for #{json}" end + ActiveSupport.parse_json_times = prev end + end - test "json decodes time json with time parsing disabled with the #{backend} backend" do - ActiveSupport.parse_json_times = false - expected = {"a" => "2007-01-01 01:12:34 Z"} - ActiveSupport::JSON.with_backend backend do - assert_equal expected, ActiveSupport::JSON.decode(%({"a": "2007-01-01 01:12:34 Z"})) - end - end + test "json decodes time json with time parsing disabled" do + prev = ActiveSupport.parse_json_times + ActiveSupport.parse_json_times = false + expected = {"a" => "2007-01-01 01:12:34 Z"} + assert_equal expected, ActiveSupport::JSON.decode(%({"a": "2007-01-01 01:12:34 Z"})) + ActiveSupport.parse_json_times = prev end def test_failed_json_decoding + assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%(undefined)) } + assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%({a: 1})) } assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%({: 1})) } + assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%()) } + end + + def test_cannot_pass_unsupported_options + assert_raise(ArgumentError) { ActiveSupport::JSON.decode("", create_additions: true) } end end diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index 7ed71f9abc..d549113ff4 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -1,4 +1,5 @@ # encoding: utf-8 +require 'securerandom' require 'abstract_unit' require 'active_support/core_ext/string/inflections' require 'active_support/json' @@ -22,6 +23,15 @@ class TestJSONEncoding < ActiveSupport::TestCase end end + class CustomWithOptions + attr_accessor :foo, :bar + + def as_json(options={}) + options[:only] = %w(foo bar) + super(options) + end + end + TrueTests = [[ true, %(true) ]] FalseTests = [[ false, %(false) ]] NilTests = [[ nil, %(null) ]] @@ -36,8 +46,8 @@ class TestJSONEncoding < ActiveSupport::TestCase StringTests = [[ 'this is the <string>', %("this is the \\u003Cstring\\u003E")], [ 'a "string" with quotes & an ampersand', %("a \\"string\\" with quotes \\u0026 an ampersand") ], [ 'http://test.host/posts/1', %("http://test.host/posts/1")], - [ "Control characters: \x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f", - %("Control characters: \\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000B\\f\\r\\u000E\\u000F\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001A\\u001B\\u001C\\u001D\\u001E\\u001F") ]] + [ "Control characters: \x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\342\200\250\342\200\251", + %("Control characters: \\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000B\\f\\r\\u000E\\u000F\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001A\\u001B\\u001C\\u001D\\u001E\\u001F\\u2028\\u2029") ]] ArrayTests = [[ ['a', 'b', 'c'], %([\"a\",\"b\",\"c\"]) ], [ [1, 'a', :b, nil, false], %([1,\"a\",\"b\",null,false]) ]] @@ -73,6 +83,8 @@ class TestJSONEncoding < ActiveSupport::TestCase constants.grep(/Tests$/).each do |class_tests| define_method("test_#{class_tests[0..-6].underscore}") do begin + prev = ActiveSupport.use_standard_json_time_format + ActiveSupport.escape_html_entities_in_json = class_tests !~ /^Standard/ ActiveSupport.use_standard_json_time_format = class_tests =~ /^Standard/ self.class.const_get(class_tests).each do |pair| @@ -80,16 +92,16 @@ class TestJSONEncoding < ActiveSupport::TestCase end ensure ActiveSupport.escape_html_entities_in_json = false - ActiveSupport.use_standard_json_time_format = false + ActiveSupport.use_standard_json_time_format = prev end end end - def test_json_variable - assert_deprecated do - assert_equal ActiveSupport::JSON::Variable.new('foo'), 'foo' - assert_equal ActiveSupport::JSON::Variable.new('alert("foo")'), 'alert("foo")' - end + def test_process_status + # There doesn't seem to be a good way to get a handle on a Process::Status object without actually + # creating a child process, hence this to populate $? + system("not_a_real_program_#{SecureRandom.hex}") + assert_equal %({"exitstatus":#{$?.exitstatus},"pid":#{$?.pid}}), ActiveSupport::JSON.encode($?) end def test_hash_encoding @@ -103,21 +115,34 @@ class TestJSONEncoding < ActiveSupport::TestCase def test_utf8_string_encoded_properly result = ActiveSupport::JSON.encode('€2.99') - assert_equal '"\\u20ac2.99"', result + assert_equal '"€2.99"', result assert_equal(Encoding::UTF_8, result.encoding) result = ActiveSupport::JSON.encode('✎☺') - assert_equal '"\\u270e\\u263a"', result + assert_equal '"✎☺"', result assert_equal(Encoding::UTF_8, result.encoding) end def test_non_utf8_string_transcodes s = '二'.encode('Shift_JIS') result = ActiveSupport::JSON.encode(s) - assert_equal '"\\u4e8c"', result + assert_equal '"二"', result assert_equal Encoding::UTF_8, result.encoding end + def test_wide_utf8_chars + w = '𠜎' + result = ActiveSupport::JSON.encode(w) + assert_equal '"𠜎"', result + end + + def test_wide_utf8_roundtrip + hash = { string: "𐒑" } + json = ActiveSupport::JSON.encode(hash) + decoded_hash = ActiveSupport::JSON.decode(json) + assert_equal "𐒑", decoded_hash['string'] + end + def test_exception_raised_when_encoding_circular_reference_in_array a = [1] a << a @@ -150,23 +175,28 @@ class TestJSONEncoding < ActiveSupport::TestCase end def test_time_to_json_includes_local_offset + prev = ActiveSupport.use_standard_json_time_format ActiveSupport.use_standard_json_time_format = true with_env_tz 'US/Eastern' do assert_equal %("2005-02-01T15:15:10-05:00"), ActiveSupport::JSON.encode(Time.local(2005,2,1,15,15,10)) end ensure - ActiveSupport.use_standard_json_time_format = false + ActiveSupport.use_standard_json_time_format = prev end def test_hash_with_time_to_json + prev = ActiveSupport.use_standard_json_time_format + ActiveSupport.use_standard_json_time_format = false assert_equal '{"time":"2009/01/01 00:00:00 +0000"}', { :time => Time.utc(2009) }.to_json + ensure + ActiveSupport.use_standard_json_time_format = prev end def test_nested_hash_with_float assert_nothing_raised do hash = { "CHI" => { - :dislay_name => "chicago", + :display_name => "chicago", :latitude => 123.234 } } @@ -248,6 +278,16 @@ class TestJSONEncoding < ActiveSupport::TestCase assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json) end + def test_to_json_should_not_keep_options_around + f = CustomWithOptions.new + f.foo = "hello" + f.bar = "world" + + hash = {"foo" => f, "other_hash" => {"foo" => "other_foo", "test" => "other_test"}} + assert_equal({"foo"=>{"foo"=>"hello","bar"=>"world"}, + "other_hash" => {"foo"=>"other_foo","test"=>"other_test"}}, JSON.parse(hash.to_json)) + end + def test_struct_encoding Struct.new('UserNameAndEmail', :name, :email) Struct.new('UserNameAndDate', :name, :date) @@ -270,12 +310,12 @@ class TestJSONEncoding < ActiveSupport::TestCase assert_equal({"name" => "David", "sub" => { "name" => "David", - "date" => "2010/01/01" }}, JSON.parse(json_custom)) + "date" => "2010-01-01" }}, JSON.parse(json_custom)) assert_equal({"name" => "David", "email" => "sample@example.com"}, JSON.parse(json_strings)) - assert_equal({"name" => "David", "date" => "2010/01/01"}, + assert_equal({"name" => "David", "date" => "2010-01-01"}, JSON.parse(json_string_and_date)) end diff --git a/activesupport/test/load_paths_test.rb b/activesupport/test/load_paths_test.rb index 979e25bdf3..ac617a9fd8 100644 --- a/activesupport/test/load_paths_test.rb +++ b/activesupport/test/load_paths_test.rb @@ -10,7 +10,7 @@ class LoadPathsTest < ActiveSupport::TestCase } load_paths_count[File.expand_path('../../lib', __FILE__)] -= 1 - filtered = load_paths_count.select { |k, v| v > 1 } - assert filtered.empty?, filtered.inspect + load_paths_count.select! { |k, v| v > 1 } + assert load_paths_count.empty?, load_paths_count.inspect end end diff --git a/activesupport/test/logger_test.rb b/activesupport/test/logger_test.rb index eedeca30a8..d2801849ca 100644 --- a/activesupport/test/logger_test.rb +++ b/activesupport/test/logger_test.rb @@ -120,4 +120,14 @@ class LoggerTest < ActiveSupport::TestCase byte_string.force_encoding("ASCII-8BIT") assert byte_string.include?(BYTE_STRING) end + + def test_silencing_everything_but_errors + @logger.silence do + @logger.debug "NOT THERE" + @logger.error "THIS IS HERE" + end + + assert !@output.string.include?("NOT THERE") + assert @output.string.include?("THIS IS HERE") + end end diff --git a/activesupport/test/message_encryptor_test.rb b/activesupport/test/message_encryptor_test.rb index b544742300..509c453b5c 100644 --- a/activesupport/test/message_encryptor_test.rb +++ b/activesupport/test/message_encryptor_test.rb @@ -29,9 +29,9 @@ class MessageEncryptorTest < ActiveSupport::TestCase end def test_encrypting_twice_yields_differing_cipher_text - first_messqage = @encryptor.encrypt_and_sign(@data).split("--").first + first_message = @encryptor.encrypt_and_sign(@data).split("--").first second_message = @encryptor.encrypt_and_sign(@data).split("--").first - assert_not_equal first_messqage, second_message + assert_not_equal first_message, second_message end def test_messing_with_either_encrypted_values_causes_failure @@ -56,9 +56,14 @@ class MessageEncryptorTest < ActiveSupport::TestCase end def test_alternative_serialization_method - encryptor = ActiveSupport::MessageEncryptor.new(SecureRandom.hex(64), :serializer => JSONSerializer.new) + prev = ActiveSupport.use_standard_json_time_format + ActiveSupport.use_standard_json_time_format = true + encryptor = ActiveSupport::MessageEncryptor.new(SecureRandom.hex(64), SecureRandom.hex(64), :serializer => JSONSerializer.new) message = encryptor.encrypt_and_sign({ :foo => 123, 'bar' => Time.utc(2010) }) - assert_equal encryptor.decrypt_and_verify(message), { "foo" => 123, "bar" => "2010-01-01T00:00:00Z" } + exp = { "foo" => 123, "bar" => "2010-01-01T00:00:00Z" } + assert_equal exp, encryptor.decrypt_and_verify(message) + ensure + ActiveSupport.use_standard_json_time_format = prev end private diff --git a/activesupport/test/message_verifier_test.rb b/activesupport/test/message_verifier_test.rb index 5adff41653..a8633f7299 100644 --- a/activesupport/test/message_verifier_test.rb +++ b/activesupport/test/message_verifier_test.rb @@ -45,9 +45,14 @@ class MessageVerifierTest < ActiveSupport::TestCase end def test_alternative_serialization_method + prev = ActiveSupport.use_standard_json_time_format + ActiveSupport.use_standard_json_time_format = true verifier = ActiveSupport::MessageVerifier.new("Hey, I'm a secret!", :serializer => JSONSerializer.new) message = verifier.generate({ :foo => 123, 'bar' => Time.utc(2010) }) - assert_equal verifier.verify(message), { "foo" => 123, "bar" => "2010-01-01T00:00:00Z" } + exp = { "foo" => 123, "bar" => "2010-01-01T00:00:00Z" } + assert_equal exp, verifier.verify(message) + ensure + ActiveSupport.use_standard_json_time_format = prev end def assert_not_verified(message) diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index ef289692bc..2bf73291a2 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -47,7 +47,10 @@ class MultibyteCharsTest < ActiveSupport::TestCase end def test_methods_are_forwarded_to_wrapped_string_for_byte_strings - assert_equal BYTE_STRING.class, BYTE_STRING.mb_chars.class + original_encoding = BYTE_STRING.encoding + assert_equal BYTE_STRING.length, BYTE_STRING.mb_chars.length + ensure + BYTE_STRING.force_encoding(original_encoding) end def test_forwarded_method_with_non_string_result_should_be_returned_vertabim @@ -673,6 +676,9 @@ class MultibyteCharsExtrasTest < ActiveSupport::TestCase assert_equal "𥤤", chars(byte_string).tidy_bytes(true) end + def test_class_is_not_forwarded + assert_equal BYTE_STRING.dup.mb_chars.class, ActiveSupport::Multibyte::Chars + end private diff --git a/activesupport/test/notifications/instrumenter_test.rb b/activesupport/test/notifications/instrumenter_test.rb new file mode 100644 index 0000000000..f46e96f636 --- /dev/null +++ b/activesupport/test/notifications/instrumenter_test.rb @@ -0,0 +1,58 @@ +require 'abstract_unit' +require 'active_support/notifications/instrumenter' + +module ActiveSupport + module Notifications + class InstrumenterTest < ActiveSupport::TestCase + class TestNotifier + attr_reader :starts, :finishes + + def initialize + @starts = [] + @finishes = [] + end + + def start(*args); @starts << args; end + def finish(*args); @finishes << args; end + end + + attr_reader :instrumenter, :notifier, :payload + + def setup + super + @notifier = TestNotifier.new + @instrumenter = Instrumenter.new @notifier + @payload = { :foo => Object.new } + end + + def test_instrument + called = false + instrumenter.instrument("foo", payload) { + called = true + } + + assert called + end + + def test_instrument_yields_the_payload_for_further_modification + assert_equal 2, instrumenter.instrument("awesome") { |p| p[:result] = 1 + 1 } + assert_equal 1, notifier.finishes.size + name, _, payload = notifier.finishes.first + assert_equal "awesome", name + assert_equal Hash[:result => 2], payload + end + + def test_start + instrumenter.start("foo", payload) + assert_equal [["foo", instrumenter.id, payload]], notifier.starts + assert_predicate notifier.finishes, :empty? + end + + def test_finish + instrumenter.finish("foo", payload) + assert_equal [["foo", instrumenter.id, payload]], notifier.finishes + assert_predicate notifier.starts, :empty? + end + end + end +end diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb index bcb393c7bc..f729f0a95b 100644 --- a/activesupport/test/notifications_test.rb +++ b/activesupport/test/notifications_test.rb @@ -81,6 +81,20 @@ module Notifications end end + class TestSubscriber + attr_reader :starts, :finishes, :publishes + + def initialize + @starts = [] + @finishes = [] + @publishes = [] + end + + def start(*args); @starts << args; end + def finish(*args); @finishes << args; end + def publish(*args); @publishes << args; end + end + class SyncPubSubTest < TestCase def test_events_are_published_to_a_listener @notifier.publish :foo @@ -99,7 +113,7 @@ module Notifications @notifier.publish :foo @notifier.publish :foo - @notifier.subscribe("not_existant") do |*args| + @notifier.subscribe("not_existent") do |*args| @events << ActiveSupport::Notifications::Event.new(*args) end @@ -144,6 +158,14 @@ module Notifications assert_equal [[:foo]], @another end + def test_publish_with_subscriber + subscriber = TestSubscriber.new + @notifier.subscribe nil, subscriber + @notifier.publish :foo + + assert_equal [[:foo]], subscriber.publishes + end + private def event(*args) args @@ -157,7 +179,7 @@ module Notifications assert_equal 2, instrument(:awesome) { 1 + 1 } end - def test_instrument_yields_the_paylod_for_further_modification + def test_instrument_yields_the_payload_for_further_modification assert_equal 2, instrument(:awesome) { |p| p[:result] = 1 + 1 } assert_equal 1, @events.size assert_equal :awesome, @events.first.name diff --git a/activesupport/test/number_helper_test.rb b/activesupport/test/number_helper_test.rb index 5f54587f93..1fadef3637 100644 --- a/activesupport/test/number_helper_test.rb +++ b/activesupport/test/number_helper_test.rb @@ -301,6 +301,13 @@ module ActiveSupport end end + def test_number_to_human_with_custom_units_that_are_missing_the_needed_key + [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper| + assert_equal '123', number_helper.number_to_human(123, units: { thousand: 'k'}) + assert_equal '123', number_helper.number_to_human(123, units: {}) + end + end + def test_number_to_human_with_custom_format [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper| assert_equal '123 times Thousand', number_helper.number_to_human(123456, :format => "%n times %u") diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index 14ba4e0076..0b54026c64 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -1,7 +1,8 @@ require 'abstract_unit' require 'active_support/json' -require 'active_support/core_ext/object/to_json' +require 'active_support/core_ext/object/json' require 'active_support/core_ext/hash/indifferent_access' +require 'active_support/core_ext/array/extract_options' class OrderedHashTest < ActiveSupport::TestCase def setup @@ -243,11 +244,7 @@ class OrderedHashTest < ActiveSupport::TestCase end def test_each_after_yaml_serialization - values = [] - @deserialized_ordered_hash = YAML.load(YAML.dump(@ordered_hash)) - - @deserialized_ordered_hash.each {|key, value| values << value} - assert_equal @values, values + assert_equal @values, YAML.load(YAML.dump(@ordered_hash)).values end def test_each_when_yielding_to_block_with_splat diff --git a/activesupport/test/ordered_options_test.rb b/activesupport/test/ordered_options_test.rb index f60f9a58e3..fdc745b23b 100644 --- a/activesupport/test/ordered_options_test.rb +++ b/activesupport/test/ordered_options_test.rb @@ -7,13 +7,13 @@ class OrderedOptionsTest < ActiveSupport::TestCase assert_nil a[:not_set] - a[:allow_concurreny] = true + a[:allow_concurrency] = true assert_equal 1, a.size - assert a[:allow_concurreny] + assert a[:allow_concurrency] - a[:allow_concurreny] = false + a[:allow_concurrency] = false assert_equal 1, a.size - assert !a[:allow_concurreny] + assert !a[:allow_concurrency] a["else_where"] = 56 assert_equal 2, a.size @@ -23,10 +23,10 @@ class OrderedOptionsTest < ActiveSupport::TestCase def test_looping a = ActiveSupport::OrderedOptions.new - a[:allow_concurreny] = true + a[:allow_concurrency] = true a["else_where"] = 56 - test = [[:allow_concurreny, true], [:else_where, 56]] + test = [[:allow_concurrency, true], [:else_where, 56]] a.each_with_index do |(key, value), index| assert_equal test[index].first, key @@ -39,13 +39,13 @@ class OrderedOptionsTest < ActiveSupport::TestCase assert_nil a.not_set - a.allow_concurreny = true + a.allow_concurrency = true assert_equal 1, a.size - assert a.allow_concurreny + assert a.allow_concurrency - a.allow_concurreny = false + a.allow_concurrency = false assert_equal 1, a.size - assert !a.allow_concurreny + assert !a.allow_concurrency a.else_where = 56 assert_equal 2, a.size diff --git a/activesupport/test/queueing/synchronous_queue_test.rb b/activesupport/test/queueing/synchronous_queue_test.rb deleted file mode 100644 index 86c39d0f6c..0000000000 --- a/activesupport/test/queueing/synchronous_queue_test.rb +++ /dev/null @@ -1,27 +0,0 @@ -require 'abstract_unit' -require 'active_support/queueing' - -class SynchronousQueueTest < ActiveSupport::TestCase - class Job - attr_reader :ran - def run; @ran = true end - end - - class ExceptionRaisingJob - def run; raise end - end - - def setup - @queue = ActiveSupport::SynchronousQueue.new - end - - def test_runs_jobs_immediately - job = Job.new - @queue.push job - assert job.ran - - assert_raises RuntimeError do - @queue.push ExceptionRaisingJob.new - end - end -end diff --git a/activesupport/test/queueing/test_queue_test.rb b/activesupport/test/queueing/test_queue_test.rb deleted file mode 100644 index 451fb68d3e..0000000000 --- a/activesupport/test/queueing/test_queue_test.rb +++ /dev/null @@ -1,146 +0,0 @@ -require 'abstract_unit' -require 'active_support/queueing' - -class TestQueueTest < ActiveSupport::TestCase - def setup - @queue = ActiveSupport::TestQueue.new - end - - class ExceptionRaisingJob - def run - raise - end - end - - def test_drain_raises_exceptions_from_running_jobs - @queue.push ExceptionRaisingJob.new - assert_raises(RuntimeError) { @queue.drain } - end - - def test_jobs - @queue.push 1 - @queue.push 2 - assert_equal [1,2], @queue.jobs - end - - class EquivalentJob - def initialize - @initial_id = self.object_id - end - - def run - end - - def ==(other) - other.same_initial_id?(@initial_id) - end - - def same_initial_id?(other_id) - other_id == @initial_id - end - end - - def test_contents - job = EquivalentJob.new - assert @queue.empty? - @queue.push job - refute @queue.empty? - assert_equal job, @queue.pop - end - - class ProcessingJob - def self.clear_processed - @processed = [] - end - - def self.processed - @processed - end - - def initialize(object) - @object = object - end - - def run - self.class.processed << @object - end - end - - def test_order - ProcessingJob.clear_processed - job1 = ProcessingJob.new(1) - job2 = ProcessingJob.new(2) - - @queue.push job1 - @queue.push job2 - @queue.drain - - assert_equal [1,2], ProcessingJob.processed - end - - class ThreadTrackingJob - attr_reader :thread_id - - def run - @thread_id = Thread.current.object_id - end - - def ran? - @thread_id - end - end - - def test_drain - @queue.push ThreadTrackingJob.new - job = @queue.jobs.last - @queue.drain - - assert @queue.empty? - assert job.ran?, "The job runs synchronously when the queue is drained" - assert_equal job.thread_id, Thread.current.object_id - end - - class IdentifiableJob - def initialize(id) - @id = id - end - - def ==(other) - other.same_id?(@id) - end - - def same_id?(other_id) - other_id == @id - end - - def run - end - end - - def test_queue_can_be_observed - jobs = (1..10).map do |id| - IdentifiableJob.new(id) - end - - jobs.each do |job| - @queue.push job - end - - assert_equal jobs, @queue.jobs - end - - def test_adding_an_unmarshallable_job - anonymous_class_instance = Struct.new(:run).new - - assert_raises TypeError do - @queue.push anonymous_class_instance - end - end - - def test_attempting_to_add_a_reference_to_itself - job = {reference: @queue} - assert_raises TypeError do - @queue.push job - end - end -end diff --git a/activesupport/test/queueing/threaded_consumer_test.rb b/activesupport/test/queueing/threaded_consumer_test.rb deleted file mode 100644 index fc43cb555a..0000000000 --- a/activesupport/test/queueing/threaded_consumer_test.rb +++ /dev/null @@ -1,92 +0,0 @@ -require 'abstract_unit' -require 'active_support/queueing' -require "active_support/log_subscriber/test_helper" - -class TestThreadConsumer < ActiveSupport::TestCase - class Job - attr_reader :id - def initialize(id = 1, &block) - @id = id - @block = block - end - - def run - @block.call if @block - end - end - - def setup - @logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new - @queue = ActiveSupport::Queue.new(logger: @logger) - end - - def teardown - @queue.drain - end - - test "the jobs are executed" do - ran = false - job = Job.new { ran = true } - - @queue.push job - @queue.drain - - assert_equal true, ran - end - - test "the jobs are not executed synchronously" do - run, ran = Queue.new, Queue.new - job = Job.new { ran.push run.pop } - - @queue.consumer.start - @queue.push job - assert ran.empty? - - run.push true - assert_equal true, ran.pop - end - - test "shutting down the queue synchronously drains the jobs" do - ran = false - job = Job.new do - sleep 0.1 - ran = true - end - - @queue.consumer.start - @queue.push job - assert_equal false, ran - - @queue.consumer.shutdown - assert_equal true, ran - end - - test "log job that raises an exception" do - job = Job.new { raise "RuntimeError: Error!" } - - @queue.push job - @queue.drain - - assert_equal 1, @logger.logged(:error).size - assert_match 'Job Error: RuntimeError: Error!', @logger.logged(:error).last - end - - test "test overriding exception handling" do - @queue.consumer.instance_eval do - def handle_exception(job, exception) - @last_error = exception.message - end - - def last_error - @last_error - end - end - - job = Job.new { raise "RuntimeError: Error!" } - - @queue.push job - @queue.drain - - assert_equal "RuntimeError: Error!", @queue.consumer.last_error - end -end diff --git a/activesupport/test/rescuable_test.rb b/activesupport/test/rescuable_test.rb index 3f8d09c18e..ec9d231125 100644 --- a/activesupport/test/rescuable_test.rb +++ b/activesupport/test/rescuable_test.rb @@ -21,7 +21,7 @@ class Stargate rescue_from WraithAttack, :with => :sos - rescue_from NuclearExplosion do + rescue_from 'NuclearExplosion' do @result = 'alldead' end @@ -97,10 +97,9 @@ class RescuableTest < ActiveSupport::TestCase assert_equal expected, result end - def test_children_should_inherit_rescue_defintions_from_parents_and_child_rescue_should_be_appended + def test_children_should_inherit_rescue_definitions_from_parents_and_child_rescue_should_be_appended expected = ["WraithAttack", "WraithAttack", "NuclearExplosion", "MadRonon", "CoolError"] result = @cool_stargate.send(:rescue_handlers).collect {|e| e.first} assert_equal expected, result end - end diff --git a/activesupport/test/spec_type_test.rb b/activesupport/test/spec_type_test.rb deleted file mode 100644 index 95a982d8fd..0000000000 --- a/activesupport/test/spec_type_test.rb +++ /dev/null @@ -1,23 +0,0 @@ -require "abstract_unit" -require "active_record" - -class SomeRandomModel < ActiveRecord::Base; end - -class SpecTypeTest < ActiveSupport::TestCase - - def assert_support actual - assert_equal ActiveSupport::TestCase, actual - end - - def assert_spec actual - assert_equal MiniTest::Spec, actual - end - - def test_spec_type_resolves_for_actitive_record_constants - assert_support MiniTest::Spec.spec_type(SomeRandomModel) - end - - def test_spec_type_doesnt_resolve_random_strings - assert_spec MiniTest::Spec.spec_type("Unmatched String") - end -end diff --git a/activesupport/test/string_inquirer_test.rb b/activesupport/test/string_inquirer_test.rb index 94d5fe197d..a2ed577eb0 100644 --- a/activesupport/test/string_inquirer_test.rb +++ b/activesupport/test/string_inquirer_test.rb @@ -10,7 +10,7 @@ class StringInquirerTest < ActiveSupport::TestCase end def test_miss - refute @string_inquirer.development? + assert_not @string_inquirer.development? end def test_missing_question_mark diff --git a/activesupport/test/subscriber_test.rb b/activesupport/test/subscriber_test.rb new file mode 100644 index 0000000000..253411aa3d --- /dev/null +++ b/activesupport/test/subscriber_test.rb @@ -0,0 +1,40 @@ +require 'abstract_unit' +require 'active_support/subscriber' + +class TestSubscriber < ActiveSupport::Subscriber + attach_to :doodle + + cattr_reader :event + + def self.clear + @@event = nil + end + + def open_party(event) + @@event = event + end + + private + + def private_party(event) + @@event = event + end +end + +class SubscriberTest < ActiveSupport::TestCase + def setup + TestSubscriber.clear + end + + def test_attaches_subscribers + ActiveSupport::Notifications.instrument("open_party.doodle") + + assert_equal "open_party.doodle", TestSubscriber.event.name + end + + def test_does_not_attach_private_methods + ActiveSupport::Notifications.instrument("private_party.doodle") + + assert_nil TestSubscriber.event + end +end diff --git a/activesupport/test/test_case_test.rb b/activesupport/test/test_case_test.rb deleted file mode 100644 index c02bfa8497..0000000000 --- a/activesupport/test/test_case_test.rb +++ /dev/null @@ -1,109 +0,0 @@ -require 'abstract_unit' - -module ActiveSupport - class TestCaseTest < ActiveSupport::TestCase - class FakeRunner - attr_reader :puked - - def initialize - @puked = [] - end - - def puke(klass, name, e) - @puked << [klass, name, e] - end - - def options - nil - end - end - - def test_standard_error_raised_within_setup_callback_is_puked - tc = Class.new(TestCase) do - def self.name; nil; end - - setup :bad_callback - def bad_callback; raise 'oh noes' end - def test_true; assert true end - end - - test_name = 'test_true' - fr = FakeRunner.new - - test = tc.new test_name - test.run fr - klass, name, exception = *fr.puked.first - - assert_equal tc, klass - assert_equal test_name, name - assert_equal 'oh noes', exception.message - end - - def test_standard_error_raised_within_teardown_callback_is_puked - tc = Class.new(TestCase) do - def self.name; nil; end - - teardown :bad_callback - def bad_callback; raise 'oh noes' end - def test_true; assert true end - end - - test_name = 'test_true' - fr = FakeRunner.new - - test = tc.new test_name - test.run fr - klass, name, exception = *fr.puked.first - - assert_equal tc, klass - assert_equal test_name, name - assert_equal 'oh noes', exception.message - end - - def test_passthrough_exception_raised_within_test_method_is_not_rescued - tc = Class.new(TestCase) do - def self.name; nil; end - - def test_which_raises_interrupt; raise Interrupt; end - end - - test_name = 'test_which_raises_interrupt' - fr = FakeRunner.new - - test = tc.new test_name - assert_raises(Interrupt) { test.run fr } - end - - def test_passthrough_exception_raised_within_setup_callback_is_not_rescued - tc = Class.new(TestCase) do - def self.name; nil; end - - setup :callback_which_raises_interrupt - def callback_which_raises_interrupt; raise Interrupt; end - def test_true; assert true end - end - - test_name = 'test_true' - fr = FakeRunner.new - - test = tc.new test_name - assert_raises(Interrupt) { test.run fr } - end - - def test_passthrough_exception_raised_within_teardown_callback_is_not_rescued - tc = Class.new(TestCase) do - def self.name; nil; end - - teardown :callback_which_raises_interrupt - def callback_which_raises_interrupt; raise Interrupt; end - def test_true; assert true end - end - - test_name = 'test_true' - fr = FakeRunner.new - - test = tc.new test_name - assert_raises(Interrupt) { test.run fr } - end - end -end diff --git a/activesupport/test/test_test.rb b/activesupport/test/test_test.rb index 9516556844..0c8cc1f883 100644 --- a/activesupport/test/test_test.rb +++ b/activesupport/test/test_test.rb @@ -15,6 +15,17 @@ class AssertDifferenceTest < ActiveSupport::TestCase @object.num = 0 end + def test_assert_not + assert_equal true, assert_not(nil) + assert_equal true, assert_not(false) + + e = assert_raises(MiniTest::Assertion) { assert_not true } + assert_equal 'Expected true to be nil or false', e.message + + e = assert_raises(MiniTest::Assertion) { assert_not true, 'custom' } + assert_equal 'custom', e.message + end + def test_assert_no_difference assert_no_difference '@object.num' do # ... @@ -76,58 +87,18 @@ class AssertDifferenceTest < ActiveSupport::TestCase end end -class AssertBlankTest < ActiveSupport::TestCase - BLANK = [ EmptyTrue.new, nil, false, '', ' ', " \n\t \r ", [], {} ] - NOT_BLANK = [ EmptyFalse.new, Object.new, true, 0, 1, 'x', [nil], { nil => 0 } ] - - def test_assert_blank_true - BLANK.each { |v| assert_blank v } - end - - def test_assert_blank_false - NOT_BLANK.each { |v| - begin - assert_blank v - fail 'should not get to here' - rescue Exception => e - assert_match(/is not blank/, e.message) - end - } - end -end - -class AssertPresentTest < ActiveSupport::TestCase - BLANK = [ EmptyTrue.new, nil, false, '', ' ', " \n\t \r ", [], {} ] - NOT_BLANK = [ EmptyFalse.new, Object.new, true, 0, 1, 'x', [nil], { nil => 0 } ] - - def test_assert_present_true - NOT_BLANK.each { |v| assert_present v } - end - - def test_assert_present_false - BLANK.each { |v| - begin - assert_present v - fail 'should not get to here' - rescue Exception => e - assert_match(/is blank/, e.message) - end - } - end -end - class AlsoDoingNothingTest < ActiveSupport::TestCase end # Setup and teardown callbacks. class SetupAndTeardownTest < ActiveSupport::TestCase setup :reset_callback_record, :foo - teardown :foo, :sentinel, :foo + teardown :foo, :sentinel def test_inherited_setup_callbacks assert_equal [:reset_callback_record, :foo], self.class._setup_callbacks.map(&:raw_filter) assert_equal [:foo], @called_back - assert_equal [:foo, :sentinel, :foo], self.class._teardown_callbacks.map(&:raw_filter) + assert_equal [:foo, :sentinel], self.class._teardown_callbacks.map(&:raw_filter) end def setup @@ -147,7 +118,7 @@ class SetupAndTeardownTest < ActiveSupport::TestCase end def sentinel - assert_equal [:foo, :foo], @called_back + assert_equal [:foo], @called_back end end @@ -159,7 +130,7 @@ class SubclassSetupAndTeardownTest < SetupAndTeardownTest def test_inherited_setup_callbacks assert_equal [:reset_callback_record, :foo, :bar], self.class._setup_callbacks.map(&:raw_filter) assert_equal [:foo, :bar], @called_back - assert_equal [:foo, :sentinel, :foo, :bar], self.class._teardown_callbacks.map(&:raw_filter) + assert_equal [:foo, :sentinel, :bar], self.class._teardown_callbacks.map(&:raw_filter) end protected @@ -168,7 +139,7 @@ class SubclassSetupAndTeardownTest < SetupAndTeardownTest end def sentinel - assert_equal [:foo, :bar, :bar, :foo], @called_back + assert_equal [:foo, :bar, :bar], @called_back end end @@ -182,7 +153,6 @@ class TestCaseTaggedLoggingTest < ActiveSupport::TestCase end def test_logs_tagged_with_current_test_case - tagged_logger.info 'test' - assert_equal "[#{self.class.name}] [#{__name__}] test\n", @out.string + assert_match "#{self.class}: #{name}\n", @out.string end end diff --git a/activesupport/test/testing/constant_lookup_test.rb b/activesupport/test/testing/constant_lookup_test.rb index c56c032cde..aca2951450 100644 --- a/activesupport/test/testing/constant_lookup_test.rb +++ b/activesupport/test/testing/constant_lookup_test.rb @@ -1,7 +1,8 @@ require 'abstract_unit' +require 'dependencies_test_helpers' class Foo; end -class Bar < Foo; +class Bar < Foo def index; end def self.index; end end @@ -10,6 +11,7 @@ module FooBar; end class ConstantLookupTest < ActiveSupport::TestCase include ActiveSupport::Testing::ConstantLookup + include DependenciesTestHelpers def find_foo(name) self.class.determine_constant_from_test_name(name) do |constant| @@ -56,4 +58,12 @@ class ConstantLookupTest < ActiveSupport::TestCase assert_nil find_module("DoesntExist::Nadda::Nope") assert_nil find_module("DoesntExist::Nadda::Nope::NotHere") end + + def test_does_not_swallow_exception_on_no_method_error + assert_raises(NoMethodError) { + with_autoloading_fixtures { + self.class.determine_constant_from_test_name("RaisesNoMethodError") + } + } + end end diff --git a/activesupport/test/testing/performance_test.rb b/activesupport/test/testing/performance_test.rb deleted file mode 100644 index 53073cb8db..0000000000 --- a/activesupport/test/testing/performance_test.rb +++ /dev/null @@ -1,59 +0,0 @@ -require 'abstract_unit' -require 'active_support/testing/performance' - - -module ActiveSupport - module Testing - class PerformanceTest < ActiveSupport::TestCase - def test_amount_format - amount_metric = ActiveSupport::Testing::Performance::Metrics[:amount].new - assert_equal "0", amount_metric.format(0) - assert_equal "1", amount_metric.format(1.23) - assert_equal "40,000,000", amount_metric.format(40000000) - end - - def test_time_format - time_metric = ActiveSupport::Testing::Performance::Metrics[:time].new - assert_equal "0 ms", time_metric.format(0) - assert_equal "40 ms", time_metric.format(0.04) - assert_equal "41 ms", time_metric.format(0.0415) - assert_equal "1.23 sec", time_metric.format(1.23) - assert_equal "40000.00 sec", time_metric.format(40000) - assert_equal "-5000 ms", time_metric.format(-5) - end - - def test_space_format - space_metric = ActiveSupport::Testing::Performance::Metrics[:digital_information_unit].new - assert_equal "0 Bytes", space_metric.format(0) - assert_equal "0 Bytes", space_metric.format(0.4) - assert_equal "1 Byte", space_metric.format(1.23) - assert_equal "123 Bytes", space_metric.format(123) - assert_equal "123 Bytes", space_metric.format(123.45) - assert_equal "12 KB", space_metric.format(12345) - assert_equal "1.2 MB", space_metric.format(1234567) - assert_equal "9.3 GB", space_metric.format(10**10) - assert_equal "91 TB", space_metric.format(10**14) - assert_equal "910000 TB", space_metric.format(10**18) - end - - def test_environment_format_without_rails - metric = ActiveSupport::Testing::Performance::Metrics[:time].new - benchmarker = ActiveSupport::Testing::Performance::Benchmarker.new(self, metric) - assert_equal "#{RUBY_ENGINE}-#{RUBY_VERSION}.#{RUBY_PATCHLEVEL},#{RUBY_PLATFORM}", benchmarker.environment - end - - def test_environment_format_with_rails - rails, version = Module.new, Module.new - version.const_set :STRING, "4.0.0" - rails.const_set :VERSION, version - Object.const_set :Rails, rails - - metric = ActiveSupport::Testing::Performance::Metrics[:time].new - benchmarker = ActiveSupport::Testing::Performance::Benchmarker.new(self, metric) - assert_equal "rails-4.0.0,#{RUBY_ENGINE}-#{RUBY_VERSION}.#{RUBY_PATCHLEVEL},#{RUBY_PLATFORM}", benchmarker.environment - ensure - Object.send :remove_const, :Rails - end - end - end -end
\ No newline at end of file diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb index bfd6863e40..84c3154e53 100644 --- a/activesupport/test/time_zone_test.rb +++ b/activesupport/test/time_zone_test.rb @@ -178,8 +178,8 @@ class TimeZoneTest < ActiveSupport::TestCase def test_parse_with_old_date zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] - twz = zone.parse('1850-12-31 19:00:00') - assert_equal [0,0,19,31,12,1850], twz.to_a[0,6] + twz = zone.parse('1883-12-31 19:00:00') + assert_equal [0,0,19,31,12,1883], twz.to_a[0,6] assert_equal zone, twz.time_zone end @@ -204,21 +204,48 @@ class TimeZoneTest < ActiveSupport::TestCase end def test_parse_should_not_black_out_system_timezone_dst_jump - zone = ActiveSupport::TimeZone['Pacific Time (US & Canada)'] - zone.stubs(:now).returns(zone.now) - Time.stubs(:parse).with('2012-03-25 03:29', zone.now). - returns(Time.local(0,29,4,25,3,2012,nil,nil,true,"+03:00")) - twz = zone.parse('2012-03-25 03:29') - assert_equal [0, 29, 3, 25, 3, 2012], twz.to_a[0,6] + with_env_tz('EET') do + zone = ActiveSupport::TimeZone['Pacific Time (US & Canada)'] + twz = zone.parse('2012-03-25 03:29:00') + assert_equal [0, 29, 3, 25, 3, 2012], twz.to_a[0,6] + end end def test_parse_should_black_out_app_timezone_dst_jump - zone = ActiveSupport::TimeZone['Pacific Time (US & Canada)'] - zone.stubs(:now).returns(zone.now) - Time.stubs(:parse).with('2012-03-11 02:29', zone.now). - returns(Time.local(0,29,2,11,3,2012,nil,nil,false,"+02:00")) - twz = zone.parse('2012-03-11 02:29') - assert_equal [0, 29, 3, 11, 3, 2012], twz.to_a[0,6] + with_env_tz('EET') do + zone = ActiveSupport::TimeZone['Pacific Time (US & Canada)'] + twz = zone.parse('2012-03-11 02:29:00') + assert_equal [0, 29, 3, 11, 3, 2012], twz.to_a[0,6] + end + end + + def test_parse_with_missing_time_components + zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] + zone.stubs(:now).returns zone.local(1999, 12, 31, 12, 59, 59) + twz = zone.parse('2012-12-01') + assert_equal Time.utc(2012, 12, 1), twz.time + end + + def test_parse_with_javascript_date + zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] + twz = zone.parse("Mon May 28 2012 00:00:00 GMT-0700 (PDT)") + assert_equal Time.utc(2012, 5, 28, 7, 0, 0), twz.utc + end + + def test_parse_doesnt_use_local_dst + with_env_tz 'US/Eastern' do + zone = ActiveSupport::TimeZone['UTC'] + twz = zone.parse('2013-03-10 02:00:00') + assert_equal Time.utc(2013, 3, 10, 2, 0, 0), twz.time + end + end + + def test_parse_handles_dst_jump + with_env_tz 'US/Eastern' do + zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] + twz = zone.parse('2013-03-10 02:00:00') + assert_equal Time.utc(2013, 3, 10, 3, 0, 0), twz.time + end end def test_utc_offset_lazy_loaded_from_tzinfo_when_not_passed_in_to_initialize diff --git a/activesupport/test/transliterate_test.rb b/activesupport/test/transliterate_test.rb index b5d8142458..e0f85f4e7c 100644 --- a/activesupport/test/transliterate_test.rb +++ b/activesupport/test/transliterate_test.rb @@ -3,7 +3,6 @@ require 'abstract_unit' require 'active_support/inflector/transliterate' class TransliterateTest < ActiveSupport::TestCase - def test_transliterate_should_not_change_ascii_chars (0..127).each do |byte| char = [byte].pack("U") @@ -17,19 +16,20 @@ class TransliterateTest < ActiveSupport::TestCase # some reason or other are floating in the middle of all the letters. string = (0xC0..0x17E).to_a.reject {|c| [0xD7, 0xF7].include?(c)}.pack("U*") string.each_char do |char| - assert_match %r{^[a-zA-Z']*$}, ActiveSupport::Inflector.transliterate(string) + assert_match %r{^[a-zA-Z']*$}, ActiveSupport::Inflector.transliterate(char) end end def test_transliterate_should_work_with_custom_i18n_rules_and_uncomposed_utf8 char = [117, 776].pack("U*") # "ü" as ASCII "u" plus COMBINING DIAERESIS I18n.backend.store_translations(:de, :i18n => {:transliterate => {:rule => {"ü" => "ue"}}}) - I18n.locale = :de + default_locale, I18n.locale = I18n.locale, :de assert_equal "ue", ActiveSupport::Inflector.transliterate(char) + ensure + I18n.locale = default_locale end def test_transliterate_should_allow_a_custom_replacement_char assert_equal "a*b", ActiveSupport::Inflector.transliterate("a索b", "*") end - end diff --git a/activesupport/test/ts_isolated.rb b/activesupport/test/ts_isolated.rb deleted file mode 100644 index 2c217157d3..0000000000 --- a/activesupport/test/ts_isolated.rb +++ /dev/null @@ -1,16 +0,0 @@ -require 'minitest/autorun' -require 'active_support/test_case' -require 'rbconfig' -require 'active_support/core_ext/kernel/reporting' - -class TestIsolated < ActiveSupport::TestCase - ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) - - Dir["#{File.dirname(__FILE__)}/**/*_test.rb"].each do |file| - define_method("test #{file}") do - command = "#{ruby} -Ilib:test #{file}" - result = silence_stderr { `#{command}` } - assert $?.to_i.zero?, "#{command}\n#{result}" - end - end -end diff --git a/activesupport/test/xml_mini/jdom_engine_test.rb b/activesupport/test/xml_mini/jdom_engine_test.rb index f77d78d42c..ed4de8aba2 100644 --- a/activesupport/test/xml_mini/jdom_engine_test.rb +++ b/activesupport/test/xml_mini/jdom_engine_test.rb @@ -3,9 +3,12 @@ if RUBY_PLATFORM =~ /java/ require 'active_support/xml_mini' require 'active_support/core_ext/hash/conversions' + class JDOMEngineTest < ActiveSupport::TestCase include ActiveSupport + FILES_DIR = File.dirname(__FILE__) + '/../fixtures/xml' + def setup @default_backend = XmlMini.backend XmlMini.backend = 'JDOM' @@ -30,10 +33,41 @@ if RUBY_PLATFORM =~ /java/ assert_equal 'image/png', file.content_type end + def test_not_allowed_to_expand_entities_to_files + attack_xml = <<-EOT + <!DOCTYPE member [ + <!ENTITY a SYSTEM "file://#{FILES_DIR}/jdom_include.txt"> + ]> + <member>x&a;</member> + EOT + assert_equal 'x', Hash.from_xml(attack_xml)["member"] + end + + def test_not_allowed_to_expand_parameter_entities_to_files + attack_xml = <<-EOT + <!DOCTYPE member [ + <!ENTITY % b SYSTEM "file://#{FILES_DIR}/jdom_entities.txt"> + %b; + ]> + <member>x&a;</member> + EOT + assert_raise Java::OrgXmlSax::SAXParseException do + assert_equal 'x', Hash.from_xml(attack_xml)["member"] + end + end + + + def test_not_allowed_to_load_external_doctypes + attack_xml = <<-EOT + <!DOCTYPE member SYSTEM "file://#{FILES_DIR}/jdom_doctype.dtd"> + <member>x&a;</member> + EOT + assert_equal 'x', Hash.from_xml(attack_xml)["member"] + end + def test_exception_thrown_on_expansion_attack - assert_raise NativeException do + assert_raise Java::OrgXmlSax::SAXParseException do attack_xml = <<-EOT - <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE member [ <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;"> <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;"> @@ -142,10 +176,11 @@ if RUBY_PLATFORM =~ /java/ end private - def assert_equal_rexml(xml) - hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) } - assert_equal(hash, XmlMini.parse(xml)) - end + def assert_equal_rexml(xml) + parsed_xml = XmlMini.parse(xml) + hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) } + assert_equal(hash, parsed_xml) + end end else diff --git a/activesupport/test/xml_mini/libxml_engine_test.rb b/activesupport/test/xml_mini/libxml_engine_test.rb index 5debb2fd59..a8df2e1f7b 100644 --- a/activesupport/test/xml_mini/libxml_engine_test.rb +++ b/activesupport/test/xml_mini/libxml_engine_test.rb @@ -1,12 +1,11 @@ -require 'abstract_unit' -require 'active_support/xml_mini' -require 'active_support/core_ext/hash/conversions' - begin require 'libxml' rescue LoadError # Skip libxml tests else +require 'abstract_unit' +require 'active_support/xml_mini' +require 'active_support/core_ext/hash/conversions' class LibxmlEngineTest < ActiveSupport::TestCase include ActiveSupport @@ -142,7 +141,7 @@ class LibxmlEngineTest < ActiveSupport::TestCase morning </root> eoxml - XmlMini.parse(io) + assert_equal_rexml(io) end def test_children_with_simple_cdata @@ -194,10 +193,12 @@ class LibxmlEngineTest < ActiveSupport::TestCase private - def assert_equal_rexml(xml) - hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) } - assert_equal(hash, XmlMini.parse(xml)) - end + def assert_equal_rexml(xml) + parsed_xml = XmlMini.parse(xml) + xml.rewind if xml.respond_to?(:rewind) + hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) } + assert_equal(hash, parsed_xml) + end end end diff --git a/activesupport/test/xml_mini/libxmlsax_engine_test.rb b/activesupport/test/xml_mini/libxmlsax_engine_test.rb index 94250d48ec..d6d90639e2 100644 --- a/activesupport/test/xml_mini/libxmlsax_engine_test.rb +++ b/activesupport/test/xml_mini/libxmlsax_engine_test.rb @@ -1,12 +1,11 @@ -require 'abstract_unit' -require 'active_support/xml_mini' -require 'active_support/core_ext/hash/conversions' - begin require 'libxml' rescue LoadError # Skip libxml tests else +require 'abstract_unit' +require 'active_support/xml_mini' +require 'active_support/core_ext/hash/conversions' class LibXMLSAXEngineTest < ActiveSupport::TestCase include ActiveSupport @@ -142,7 +141,7 @@ class LibXMLSAXEngineTest < ActiveSupport::TestCase morning </root> eoxml - XmlMini.parse(io) + assert_equal_rexml(io) end def test_children_with_simple_cdata @@ -185,10 +184,12 @@ class LibXMLSAXEngineTest < ActiveSupport::TestCase end private - def assert_equal_rexml(xml) - hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) } - assert_equal(hash, XmlMini.parse(xml)) - end + def assert_equal_rexml(xml) + parsed_xml = XmlMini.parse(xml) + xml.rewind if xml.respond_to?(:rewind) + hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) } + assert_equal(hash, parsed_xml) + end end end diff --git a/activesupport/test/xml_mini/nokogiri_engine_test.rb b/activesupport/test/xml_mini/nokogiri_engine_test.rb index 3f37c7cbb6..2e962576b5 100644 --- a/activesupport/test/xml_mini/nokogiri_engine_test.rb +++ b/activesupport/test/xml_mini/nokogiri_engine_test.rb @@ -1,12 +1,11 @@ -require 'abstract_unit' -require 'active_support/xml_mini' -require 'active_support/core_ext/hash/conversions' - begin require 'nokogiri' rescue LoadError # Skip nokogiri tests else +require 'abstract_unit' +require 'active_support/xml_mini' +require 'active_support/core_ext/hash/conversions' class NokogiriEngineTest < ActiveSupport::TestCase include ActiveSupport @@ -156,7 +155,7 @@ class NokogiriEngineTest < ActiveSupport::TestCase morning </root> eoxml - XmlMini.parse(io) + assert_equal_rexml(io) end def test_children_with_simple_cdata @@ -207,10 +206,12 @@ class NokogiriEngineTest < ActiveSupport::TestCase end private - def assert_equal_rexml(xml) - hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) } - assert_equal(hash, XmlMini.parse(xml)) - end + def assert_equal_rexml(xml) + parsed_xml = XmlMini.parse(xml) + xml.rewind if xml.respond_to?(:rewind) + hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) } + assert_equal(hash, parsed_xml) + end end end diff --git a/activesupport/test/xml_mini/nokogirisax_engine_test.rb b/activesupport/test/xml_mini/nokogirisax_engine_test.rb index d6ae7f12ae..4f078f31e0 100644 --- a/activesupport/test/xml_mini/nokogirisax_engine_test.rb +++ b/activesupport/test/xml_mini/nokogirisax_engine_test.rb @@ -1,12 +1,11 @@ -require 'abstract_unit' -require 'active_support/xml_mini' -require 'active_support/core_ext/hash/conversions' - begin require 'nokogiri' rescue LoadError # Skip nokogiri tests else +require 'abstract_unit' +require 'active_support/xml_mini' +require 'active_support/core_ext/hash/conversions' class NokogiriSAXEngineTest < ActiveSupport::TestCase include ActiveSupport @@ -57,9 +56,9 @@ class NokogiriSAXEngineTest < ActiveSupport::TestCase end end - def test_setting_nokogiri_as_backend - XmlMini.backend = 'Nokogiri' - assert_equal XmlMini_Nokogiri, XmlMini.backend + def test_setting_nokogirisax_as_backend + XmlMini.backend = 'NokogiriSAX' + assert_equal XmlMini_NokogiriSAX, XmlMini.backend end def test_blank_returns_empty_hash @@ -157,7 +156,7 @@ class NokogiriSAXEngineTest < ActiveSupport::TestCase morning </root> eoxml - XmlMini.parse(io) + assert_equal_rexml(io) end def test_children_with_simple_cdata @@ -208,10 +207,12 @@ class NokogiriSAXEngineTest < ActiveSupport::TestCase end private - def assert_equal_rexml(xml) - hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) } - assert_equal(hash, XmlMini.parse(xml)) - end + def assert_equal_rexml(xml) + parsed_xml = XmlMini.parse(xml) + xml.rewind if xml.respond_to?(:rewind) + hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) } + assert_equal(hash, parsed_xml) + end end end diff --git a/activesupport/test/xml_mini/rexml_engine_test.rb b/activesupport/test/xml_mini/rexml_engine_test.rb index c4770405f2..0c1f11803c 100644 --- a/activesupport/test/xml_mini/rexml_engine_test.rb +++ b/activesupport/test/xml_mini/rexml_engine_test.rb @@ -24,6 +24,14 @@ class REXMLEngineTest < ActiveSupport::TestCase morning </root> eoxml - XmlMini.parse(io) + assert_equal_rexml(io) end + + private + def assert_equal_rexml(xml) + parsed_xml = XmlMini.parse(xml) + xml.rewind if xml.respond_to?(:rewind) + hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) } + assert_equal(hash, parsed_xml) + end end diff --git a/activesupport/test/xml_mini_test.rb b/activesupport/test/xml_mini_test.rb index 504fc96493..d992028323 100644 --- a/activesupport/test/xml_mini_test.rb +++ b/activesupport/test/xml_mini_test.rb @@ -99,4 +99,74 @@ module XmlMiniTest end # TODO: test the remaining functions hidden in #to_tag. end + + class WithBackendTest < ActiveSupport::TestCase + module REXML end + module LibXML end + module Nokogiri end + + setup do + @xml, @default_backend = ActiveSupport::XmlMini, ActiveSupport::XmlMini.backend + end + + teardown do + ActiveSupport::XmlMini.backend = @default_backend + end + + test "#with_backend should switch backend and then switch back" do + @xml.backend = REXML + @xml.with_backend(LibXML) do + assert_equal LibXML, @xml.backend + @xml.with_backend(Nokogiri) do + assert_equal Nokogiri, @xml.backend + end + assert_equal LibXML, @xml.backend + end + assert_equal REXML, @xml.backend + end + + test "backend switch inside #with_backend block" do + @xml.with_backend(LibXML) do + @xml.backend = REXML + assert_equal REXML, @xml.backend + end + assert_equal REXML, @xml.backend + end + end + + class ThreadSafetyTest < ActiveSupport::TestCase + module REXML end + module LibXML end + + setup do + @xml, @default_backend = ActiveSupport::XmlMini, ActiveSupport::XmlMini.backend + end + + teardown do + ActiveSupport::XmlMini.backend = @default_backend + end + + test "#with_backend should be thread-safe" do + @xml.backend = REXML + t = Thread.new do + @xml.with_backend(LibXML) { sleep 1 } + end + sleep 0.1 while t.status != "sleep" + + # We should get `old_backend` here even while another + # thread is using `new_backend`. + assert_equal REXML, @xml.backend + end + + test "nested #with_backend should be thread-safe" do + @xml.with_backend(REXML) do + t = Thread.new do + @xml.with_backend(LibXML) { sleep 1 } + end + sleep 0.1 while t.status != "sleep" + + assert_equal REXML, @xml.backend + end + end + end end |