diff options
author | Dmitry Polushkin <dmitry.polushkin@gmail.com> | 2011-12-31 01:10:42 +0000 |
---|---|---|
committer | Dmitry Polushkin <dmitry.polushkin@gmail.com> | 2011-12-31 01:10:42 +0000 |
commit | 04bc40ff501b1bf81bec7ce3937cb06c896ffc69 (patch) | |
tree | 88a33663195900df8a7307aefa2c9aaa561c3973 /activesupport/test | |
parent | 84eece0a823e9c601ea99a8709f24605a19bcbfd (diff) | |
parent | ed17983ec56dec689a0311c7f8fcbeba9874e5a4 (diff) | |
download | rails-04bc40ff501b1bf81bec7ce3937cb06c896ffc69.tar.gz rails-04bc40ff501b1bf81bec7ce3937cb06c896ffc69.tar.bz2 rails-04bc40ff501b1bf81bec7ce3937cb06c896ffc69.zip |
Merge branch 'master' of git://github.com/rails/rails
Diffstat (limited to 'activesupport/test')
45 files changed, 836 insertions, 1132 deletions
diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb index 0382739871..504ac3e9b9 100644 --- a/activesupport/test/abstract_unit.rb +++ b/activesupport/test/abstract_unit.rb @@ -11,15 +11,11 @@ lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") $:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) require 'active_support/core_ext/kernel/reporting' - require 'active_support/core_ext/string/encoding' -if "ruby".encoding_aware? - # These are the normal settings that will be set up by Railties - # TODO: Have these tests support other combinations of these values - silence_warnings do - Encoding.default_internal = "UTF-8" - Encoding.default_external = "UTF-8" - end + +silence_warnings do + Encoding.default_internal = "UTF-8" + Encoding.default_external = "UTF-8" end require 'test/unit' @@ -30,9 +26,6 @@ silence_warnings { require 'mocha' } ENV['NO_RELOAD'] = '1' require 'active_support' -# Include shims until we get off 1.8.6 -require 'active_support/ruby/shim' if RUBY_VERSION < '1.8.7' - def uses_memcached(test_name) require 'memcache' begin @@ -43,22 +36,5 @@ def uses_memcached(test_name) end end -def with_kcode(code) - if RUBY_VERSION < '1.9' - begin - old_kcode, $KCODE = $KCODE, code - yield - ensure - $KCODE = old_kcode - end - else - yield - end -end - # Show backtraces for deprecated behavior for quicker cleanup. -ActiveSupport::Deprecation.debug = true - -if RUBY_VERSION < '1.9' - $KCODE = 'UTF8' -end +ActiveSupport::Deprecation.debug = true
\ No newline at end of file diff --git a/activesupport/test/benchmarkable_test.rb b/activesupport/test/benchmarkable_test.rb index 06f5172e1f..04d4f5e503 100644 --- a/activesupport/test/benchmarkable_test.rb +++ b/activesupport/test/benchmarkable_test.rb @@ -3,8 +3,23 @@ require 'abstract_unit' class BenchmarkableTest < ActiveSupport::TestCase include ActiveSupport::Benchmarkable - def teardown - logger.send(:clear_buffer) + attr_reader :buffer, :logger + + class Buffer + include Enumerable + + def initialize; @lines = []; end + def each(&block); @lines.each(&block); end + def write(x); @lines << x; end + def close; end + def last; @lines.last; end + def size; @lines.size; end + def empty?; @lines.empty?; end + end + + def setup + @buffer = Buffer.new + @logger = ActiveSupport::Logger.new(@buffer) end def test_without_block @@ -27,48 +42,20 @@ class BenchmarkableTest < ActiveSupport::TestCase end def test_within_level - logger.level = ActiveSupport::BufferedLogger::DEBUG + logger.level = ActiveSupport::Logger::DEBUG benchmark('included_debug_run', :level => :debug) { } assert_last_logged 'included_debug_run' end def test_outside_level - logger.level = ActiveSupport::BufferedLogger::ERROR + logger.level = ActiveSupport::Logger::ERROR benchmark('skipped_debug_run', :level => :debug) { } assert_no_match(/skipped_debug_run/, buffer.last) ensure - logger.level = ActiveSupport::BufferedLogger::DEBUG - end - - def test_without_silencing - benchmark('debug_run', :silence => false) do - logger.info "not silenced!" - end - - assert_equal 2, buffer.size - end - - def test_with_silencing - benchmark('debug_run', :silence => true) do - logger.info "silenced!" - end - - assert_equal 1, buffer.size + logger.level = ActiveSupport::Logger::DEBUG end private - def logger - @logger ||= begin - logger = ActiveSupport::BufferedLogger.new(StringIO.new) - logger.auto_flushing = false - logger - end - end - - def buffer - logger.send(:buffer) - end - def assert_last_logged(message = 'Benchmarking') assert_match(/^#{message} \(.*\)$/, buffer.last) end diff --git a/activesupport/test/buffered_logger_test.rb b/activesupport/test/buffered_logger_test.rb index 21049d685b..b9891c74c8 100644 --- a/activesupport/test/buffered_logger_test.rb +++ b/activesupport/test/buffered_logger_test.rb @@ -4,11 +4,13 @@ require 'stringio' require 'fileutils' require 'tempfile' require 'active_support/buffered_logger' +require 'active_support/testing/deprecation' class BufferedLoggerTest < Test::Unit::TestCase include MultibyteTestHelpers + include ActiveSupport::Testing::Deprecation - Logger = ActiveSupport::BufferedLogger + Logger = ActiveSupport::Logger def setup @message = "A debug message" @@ -23,16 +25,16 @@ class BufferedLoggerTest < Test::Unit::TestCase t.write 'hi mom!' t.close - logger = Logger.new t.path + f = File.open(t.path, 'w') + f.binmode + + logger = Logger.new f logger.level = Logger::DEBUG str = "\x80" - if str.respond_to?(:force_encoding) - str.force_encoding("ASCII-8BIT") - end + str.force_encoding("ASCII-8BIT") logger.add Logger::DEBUG, str - logger.flush ensure logger.close t.close true @@ -40,16 +42,17 @@ class BufferedLoggerTest < Test::Unit::TestCase def test_write_binary_data_create_file fname = File.join Dir.tmpdir, 'lol', 'rofl.log' - logger = Logger.new fname + FileUtils.mkdir_p File.dirname(fname) + f = File.open(fname, 'w') + f.binmode + + logger = Logger.new f logger.level = Logger::DEBUG str = "\x80" - if str.respond_to?(:force_encoding) - str.force_encoding("ASCII-8BIT") - end + str.force_encoding("ASCII-8BIT") logger.add Logger::DEBUG, str - logger.flush ensure logger.close File.unlink fname @@ -104,98 +107,20 @@ class BufferedLoggerTest < Test::Unit::TestCase assert_equal message_copy, @message end - - [false, nil, 0].each do |disable| - define_method "test_disabling_auto_flush_with_#{disable.inspect}_should_buffer_until_explicit_flush" do - @logger.auto_flushing = disable - - 4.times do - @logger.info 'wait for it..' - assert @output.string.empty?, "@output.string should be empty but it is #{@output.string}" - end - - @logger.flush - assert !@output.string.empty?, "@logger.send(:buffer).size.to_s should not be empty but it is empty" - end - - define_method "test_disabling_auto_flush_with_#{disable.inspect}_should_flush_at_max_buffer_size_as_failsafe" do - @logger.auto_flushing = disable - assert_equal Logger::MAX_BUFFER_SIZE, @logger.auto_flushing - - (Logger::MAX_BUFFER_SIZE - 1).times do - @logger.info 'wait for it..' - assert @output.string.empty?, "@output.string should be empty but is #{@output.string}" - end - - @logger.info 'there it is.' - assert !@output.string.empty?, "@logger.send(:buffer).size.to_s should not be empty but it is empty" - end - end - def test_should_know_if_its_loglevel_is_below_a_given_level Logger::Severity.constants.each do |level| + next if level.to_s == 'UNKNOWN' @logger.level = Logger::Severity.const_get(level) - 1 assert @logger.send("#{level.downcase}?"), "didn't know if it was #{level.downcase}? or below" end end - def test_should_auto_flush_every_n_messages - @logger.auto_flushing = 5 - - 4.times do - @logger.info 'wait for it..' - assert @output.string.empty?, "@output.string should be empty but it is #{@output.string}" - end - - @logger.info 'there it is.' - assert !@output.string.empty?, "@output.string should not be empty but it is empty" - end - - def test_should_create_the_log_directory_if_it_doesnt_exist - tmp_directory = File.join(File.dirname(__FILE__), "tmp") - log_file = File.join(tmp_directory, "development.log") - FileUtils.rm_rf(tmp_directory) - @logger = Logger.new(log_file) - assert File.exist?(tmp_directory) - end - - def test_logger_should_maintain_separate_buffers_for_each_thread - @logger.auto_flushing = false - - a = Thread.new do - @logger.info("a"); Thread.pass; - @logger.info("b"); Thread.pass; - @logger.info("c"); @logger.flush - end - - b = Thread.new do - @logger.info("x"); Thread.pass; - @logger.info("y"); Thread.pass; - @logger.info("z"); @logger.flush - end - - a.join - b.join - - assert @output.string.include?("a\nb\nc\n") - assert @output.string.include?("x\ny\nz\n") - end - - def test_flush_should_remove_empty_buffers - @logger.send :buffer - @logger.expects :clear_buffer - @logger.flush - end - def test_buffer_multibyte - @logger.auto_flushing = 2 @logger.info(UNICODE_STRING) @logger.info(BYTE_STRING) assert @output.string.include?(UNICODE_STRING) byte_string = @output.string.dup - if byte_string.respond_to?(:force_encoding) - byte_string.force_encoding("ASCII-8BIT") - end + byte_string.force_encoding("ASCII-8BIT") assert byte_string.include?(BYTE_STRING) end end diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index cb5362525f..aa6fb14e7b 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -4,19 +4,19 @@ require 'active_support/cache' class CacheKeyTest < ActiveSupport::TestCase def test_expand_cache_key - assert_equal '1/2/true', ActiveSupport::Cache.expand_cache_key([1, '2', true]) - assert_equal 'name/1/2/true', ActiveSupport::Cache.expand_cache_key([1, '2', true], :name) + assert_equal 'Array/1/2/true', ActiveSupport::Cache.expand_cache_key([1, '2', true]) + assert_equal 'name/Array/1/2/true', ActiveSupport::Cache.expand_cache_key([1, '2', true], :name) end def test_expand_cache_key_with_rails_cache_id begin ENV['RAILS_CACHE_ID'] = 'c99' assert_equal 'c99/foo', ActiveSupport::Cache.expand_cache_key(:foo) - assert_equal 'c99/foo', ActiveSupport::Cache.expand_cache_key([:foo]) - assert_equal 'c99/c99/foo/c99/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar]) + assert_equal 'c99/Array/foo', ActiveSupport::Cache.expand_cache_key([:foo]) + assert_equal 'c99/Array/foo/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar]) assert_equal 'nm/c99/foo', ActiveSupport::Cache.expand_cache_key(:foo, :nm) - assert_equal 'nm/c99/foo', ActiveSupport::Cache.expand_cache_key([:foo], :nm) - assert_equal 'nm/c99/c99/foo/c99/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar], :nm) + assert_equal 'nm/c99/Array/foo', ActiveSupport::Cache.expand_cache_key([:foo], :nm) + assert_equal 'nm/c99/Array/foo/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar], :nm) ensure ENV['RAILS_CACHE_ID'] = nil end @@ -42,7 +42,7 @@ class CacheKeyTest < ActiveSupport::TestCase end end - def test_respond_to_cache_key + def test_expand_cache_key_respond_to_cache_key key = 'foo' def key.cache_key :foo_key @@ -50,6 +50,33 @@ class CacheKeyTest < ActiveSupport::TestCase assert_equal 'foo_key', ActiveSupport::Cache.expand_cache_key(key) end + def test_expand_cache_key_array_with_something_that_responds_to_cache_key + key = 'foo' + def key.cache_key + :foo_key + end + assert_equal 'Array/foo_key', ActiveSupport::Cache.expand_cache_key([key]) + end + + def test_expand_cache_key_of_nil + assert_equal '', ActiveSupport::Cache.expand_cache_key(nil) + end + + def test_expand_cache_key_of_false + assert_equal 'false', ActiveSupport::Cache.expand_cache_key(false) + end + + def test_expand_cache_key_of_true + assert_equal 'true', ActiveSupport::Cache.expand_cache_key(true) + end + + def test_expand_cache_key_of_one_element_array_different_than_key_of_element + element = 'foo' + array = [element] + element_cache_key = ActiveSupport::Cache.expand_cache_key(element) + array_cache_key = ActiveSupport::Cache.expand_cache_key(array) + assert_not_equal element_cache_key, array_cache_key + end end class CacheStoreSettingTest < ActiveSupport::TestCase @@ -122,8 +149,8 @@ class CacheStoreNamespaceTest < ActiveSupport::TestCase cache.write("foo", "bar") cache.write("fu", "baz") cache.delete_matched(/^fo/) - assert_equal false, cache.exist?("foo") - assert_equal true, cache.exist?("fu") + assert !cache.exist?("foo") + assert cache.exist?("fu") end def test_delete_matched_key @@ -131,15 +158,15 @@ class CacheStoreNamespaceTest < ActiveSupport::TestCase cache.write("foo", "bar") cache.write("fu", "baz") cache.delete_matched(/OO/i) - assert_equal false, cache.exist?("foo") - assert_equal true, cache.exist?("fu") + assert !cache.exist?("foo") + assert cache.exist?("fu") end end # Tests the base functionality that should be identical across all cache stores. module CacheStoreBehavior def test_should_read_and_write_strings - assert_equal true, @cache.write('foo', 'bar') + assert @cache.write('foo', 'bar') assert_equal 'bar', @cache.read('foo') end @@ -174,22 +201,22 @@ module CacheStoreBehavior end def test_should_read_and_write_hash - assert_equal true, @cache.write('foo', {:a => "b"}) + assert @cache.write('foo', {:a => "b"}) assert_equal({:a => "b"}, @cache.read('foo')) end def test_should_read_and_write_integer - assert_equal true, @cache.write('foo', 1) + assert @cache.write('foo', 1) assert_equal 1, @cache.read('foo') end def test_should_read_and_write_nil - assert_equal true, @cache.write('foo', nil) + assert @cache.write('foo', nil) assert_equal nil, @cache.read('foo') end def test_should_read_and_write_false - assert_equal true, @cache.write('foo', false) + assert @cache.write('foo', false) assert_equal false, @cache.read('foo') end @@ -199,7 +226,7 @@ module CacheStoreBehavior @cache.write('fud', 'biz') assert_equal({"foo" => "bar", "fu" => "baz"}, @cache.read_multi('foo', 'fu')) end - + def test_read_multi_with_expires @cache.write('foo', 'bar', :expires_in => 0.001) @cache.write('fu', 'baz') @@ -262,19 +289,19 @@ module CacheStoreBehavior def test_exist @cache.write('foo', 'bar') - assert_equal true, @cache.exist?('foo') - assert_equal false, @cache.exist?('bar') + assert @cache.exist?('foo') + assert !@cache.exist?('bar') end def test_nil_exist @cache.write('foo', nil) - assert_equal true, @cache.exist?('foo') + assert @cache.exist?('foo') end def test_delete @cache.write('foo', 'bar') assert @cache.exist?('foo') - assert_equal true, @cache.delete('foo') + assert @cache.delete('foo') assert !@cache.exist?('foo') end @@ -346,10 +373,10 @@ module CacheStoreBehavior def test_crazy_key_characters crazy_key = "#/:*(<+=> )&$%@?;'\"\'`~-" - assert_equal true, @cache.write(crazy_key, "1", :raw => true) + assert @cache.write(crazy_key, "1", :raw => true) assert_equal "1", @cache.read(crazy_key) assert_equal "1", @cache.fetch(crazy_key) - assert_equal true, @cache.delete(crazy_key) + assert @cache.delete(crazy_key) assert_equal "2", @cache.fetch(crazy_key, :raw => true) { "2" } assert_equal 3, @cache.increment(crazy_key) assert_equal 2, @cache.decrement(crazy_key) @@ -358,12 +385,12 @@ module CacheStoreBehavior def test_really_long_keys key = "" 900.times{key << "x"} - assert_equal true, @cache.write(key, "bar") + assert @cache.write(key, "bar") assert_equal "bar", @cache.read(key) assert_equal "bar", @cache.fetch(key) assert_nil @cache.read("#{key}x") assert_equal({key => "bar"}, @cache.read_multi(key)) - assert_equal true, @cache.delete(key) + assert @cache.delete(key) end end @@ -371,36 +398,34 @@ end # The error is caused by charcter encodings that can't be compared with ASCII-8BIT regular expressions and by special # characters like the umlaut in UTF-8. module EncodedKeyCacheBehavior - if defined?(Encoding) - Encoding.list.each do |encoding| - define_method "test_#{encoding.name.underscore}_encoded_values" do - key = "foo".force_encoding(encoding) - assert_equal true, @cache.write(key, "1", :raw => true) - assert_equal "1", @cache.read(key) - assert_equal "1", @cache.fetch(key) - assert_equal true, @cache.delete(key) - assert_equal "2", @cache.fetch(key, :raw => true) { "2" } - assert_equal 3, @cache.increment(key) - assert_equal 2, @cache.decrement(key) - end - end - - def test_common_utf8_values - key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8) - assert_equal true, @cache.write(key, "1", :raw => true) + Encoding.list.each do |encoding| + define_method "test_#{encoding.name.underscore}_encoded_values" do + key = "foo".force_encoding(encoding) + assert @cache.write(key, "1", :raw => true) assert_equal "1", @cache.read(key) assert_equal "1", @cache.fetch(key) - assert_equal true, @cache.delete(key) + assert @cache.delete(key) assert_equal "2", @cache.fetch(key, :raw => true) { "2" } assert_equal 3, @cache.increment(key) assert_equal 2, @cache.decrement(key) end + end - def test_retains_encoding - key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8) - assert_equal true, @cache.write(key, "1", :raw => true) - assert_equal Encoding::UTF_8, key.encoding - end + def test_common_utf8_values + key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8) + assert @cache.write(key, "1", :raw => true) + assert_equal "1", @cache.read(key) + assert_equal "1", @cache.fetch(key) + assert @cache.delete(key) + assert_equal "2", @cache.fetch(key, :raw => true) { "2" } + assert_equal 3, @cache.increment(key) + assert_equal 2, @cache.decrement(key) + end + + def test_retains_encoding + key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8) + assert @cache.write(key, "1", :raw => true) + assert_equal Encoding::UTF_8, key.encoding end end @@ -411,10 +436,10 @@ module CacheDeleteMatchedBehavior @cache.write("foo/bar", "baz") @cache.write("fu/baz", "bar") @cache.delete_matched(/oo/) - assert_equal false, @cache.exist?("foo") - assert_equal true, @cache.exist?("fu") - assert_equal false, @cache.exist?("foo/bar") - assert_equal true, @cache.exist?("fu/baz") + assert !@cache.exist?("foo") + assert @cache.exist?("fu") + assert !@cache.exist?("foo/bar") + assert @cache.exist?("fu/baz") end end @@ -443,7 +468,7 @@ module LocalCacheBehavior retval = @cache.with_local_cache do @cache.write('foo', 'bar') end - assert_equal true, retval + assert retval assert_equal 'bar', @cache.read('foo') end @@ -557,12 +582,12 @@ class FileStoreTest < ActiveSupport::TestCase key = @cache_with_pathname.send(:key_file_path, "views/index?id=1") assert_equal "views/index?id=1", @cache_with_pathname.send(:file_path_key, key) end - + # Because file systems have a maximum filename size, filenames > max size should be split in to directories # If filename is 'AAAAB', where max size is 4, the returned path should be AAAA/B def test_key_transformation_max_filename_size key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}B" - path = @cache.send(:key_file_path, key) + path = @cache.send(:key_file_path, key) assert path.split('/').all? { |dir_name| dir_name.size <= ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE} assert_equal 'B', File.basename(path) end @@ -595,11 +620,11 @@ class MemoryStoreTest < ActiveSupport::TestCase @cache.read(2) && sleep(0.001) @cache.read(4) @cache.prune(@record_size * 3) - assert_equal true, @cache.exist?(5) - assert_equal true, @cache.exist?(4) - assert_equal false, @cache.exist?(3) - assert_equal true, @cache.exist?(2) - assert_equal false, @cache.exist?(1) + assert @cache.exist?(5) + assert @cache.exist?(4) + assert !@cache.exist?(3) + assert @cache.exist?(2) + assert !@cache.exist?(1) end def test_prune_size_on_write @@ -616,17 +641,17 @@ class MemoryStoreTest < ActiveSupport::TestCase @cache.read(2) && sleep(0.001) @cache.read(4) && sleep(0.001) @cache.write(11, "llllllllll") - assert_equal true, @cache.exist?(11) - assert_equal true, @cache.exist?(10) - assert_equal true, @cache.exist?(9) - assert_equal true, @cache.exist?(8) - assert_equal true, @cache.exist?(7) - assert_equal false, @cache.exist?(6) - assert_equal false, @cache.exist?(5) - assert_equal true, @cache.exist?(4) - assert_equal false, @cache.exist?(3) - assert_equal true, @cache.exist?(2) - assert_equal false, @cache.exist?(1) + assert @cache.exist?(11) + assert @cache.exist?(10) + assert @cache.exist?(9) + assert @cache.exist?(8) + assert @cache.exist?(7) + assert !@cache.exist?(6) + assert !@cache.exist?(5) + assert @cache.exist?(4) + assert !@cache.exist?(3) + assert @cache.exist?(2) + assert !@cache.exist?(1) end def test_pruning_is_capped_at_a_max_time @@ -640,11 +665,11 @@ class MemoryStoreTest < ActiveSupport::TestCase @cache.write(4, "dddddddddd") && sleep(0.001) @cache.write(5, "eeeeeeeeee") && sleep(0.001) @cache.prune(30, 0.001) - assert_equal true, @cache.exist?(5) - assert_equal true, @cache.exist?(4) - assert_equal true, @cache.exist?(3) - assert_equal true, @cache.exist?(2) - assert_equal false, @cache.exist?(1) + assert @cache.exist?(5) + assert @cache.exist?(4) + assert @cache.exist?(3) + assert @cache.exist?(2) + assert !@cache.exist?(1) end end @@ -670,14 +695,14 @@ uses_memcached 'memcached backed store' do cache.write("foo", 2) assert_equal "2", cache.read("foo") end - + def test_raw_values_with_marshal cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :raw => true) cache.clear cache.write("foo", Marshal.dump([])) - assert_equal [], cache.read("foo") + assert_equal [], cache.read("foo") end - + def test_local_cache_raw_values cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :raw => true) cache.clear @@ -698,6 +723,64 @@ uses_memcached 'memcached backed store' do end end +class NullStoreTest < ActiveSupport::TestCase + def setup + @cache = ActiveSupport::Cache.lookup_store(:null_store) + end + + def test_clear + @cache.clear + end + + def test_cleanup + @cache.cleanup + end + + def test_write + assert_equal true, @cache.write("name", "value") + end + + def test_read + @cache.write("name", "value") + assert_nil @cache.read("name") + end + + def test_delete + @cache.write("name", "value") + assert_equal false, @cache.delete("name") + end + + def test_increment + @cache.write("name", 1, :raw => true) + assert_nil @cache.increment("name") + end + + def test_decrement + @cache.write("name", 1, :raw => true) + assert_nil @cache.increment("name") + end + + def test_delete_matched + @cache.write("name", "value") + @cache.delete_matched(/name/) + end + + def test_local_store_strategy + @cache.with_local_cache do + @cache.write("name", "value") + assert_equal "value", @cache.read("name") + @cache.delete("name") + assert_nil @cache.read("name") + @cache.write("name", "value") + end + assert_nil @cache.read("name") + end + + def test_setting_nil_cache_store + assert ActiveSupport::Cache.lookup_store.class.name, ActiveSupport::Cache::NullStore.name + end +end + class CacheStoreLoggerTest < ActiveSupport::TestCase def setup @cache = ActiveSupport::Cache.lookup_store(:memory_store) @@ -723,7 +806,7 @@ class CacheEntryTest < ActiveSupport::TestCase entry = ActiveSupport::Cache::Entry.create("raw", time, :compress => false, :expires_in => 300) assert_equal "raw", entry.raw_value assert_equal time.to_f, entry.created_at - assert_equal false, entry.compressed? + assert !entry.compressed? assert_equal 300, entry.expires_in end @@ -740,7 +823,7 @@ class CacheEntryTest < ActiveSupport::TestCase def test_compress_values entry = ActiveSupport::Cache::Entry.new("value", :compress => true, :compress_threshold => 1) assert_equal "value", entry.value - assert_equal true, entry.compressed? + assert entry.compressed? assert_equal "value", Marshal.load(Zlib::Inflate.inflate(entry.raw_value)) end @@ -748,6 +831,6 @@ class CacheEntryTest < ActiveSupport::TestCase entry = ActiveSupport::Cache::Entry.new("value") assert_equal "value", entry.value assert_equal "value", Marshal.load(entry.raw_value) - assert_equal false, entry.compressed? + assert !entry.compressed? end end diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb index 2b4adda4d1..e723121bb4 100644 --- a/activesupport/test/callbacks_test.rb +++ b/activesupport/test/callbacks_test.rb @@ -461,7 +461,7 @@ module CallbacksTest set_callback :save, :after, :third - attr_reader :history, :saved + attr_reader :history, :saved, :halted def initialize @history = [] end @@ -490,6 +490,10 @@ module CallbacksTest @saved = true end end + + def halted_callback_hook(filter) + @halted = filter + end end class CallbackObject @@ -595,6 +599,12 @@ module CallbacksTest assert_equal ["first", "second", "third", "second", "first"], terminator.history end + def test_termination_invokes_hook + terminator = CallbackTerminator.new + terminator.save + assert_equal ":second", terminator.halted + end + def test_block_never_called_if_terminated obj = CallbackTerminator.new obj.save diff --git a/activesupport/test/class_cache_test.rb b/activesupport/test/class_cache_test.rb index 752c0ee478..b96f476ce6 100644 --- a/activesupport/test/class_cache_test.rb +++ b/activesupport/test/class_cache_test.rb @@ -10,45 +10,58 @@ module ActiveSupport def test_empty? assert @cache.empty? - @cache[ClassCacheTest] = ClassCacheTest + @cache.store(ClassCacheTest) assert !@cache.empty? end def test_clear! assert @cache.empty? - @cache[ClassCacheTest] = ClassCacheTest + @cache.store(ClassCacheTest) assert !@cache.empty? @cache.clear! assert @cache.empty? end def test_set_key - @cache[ClassCacheTest] = ClassCacheTest + @cache.store(ClassCacheTest) assert @cache.key?(ClassCacheTest.name) end - def test_set_rejects_strings - @cache[ClassCacheTest.name] = ClassCacheTest - assert @cache.empty? - end - def test_get_with_class - @cache[ClassCacheTest] = ClassCacheTest - assert_equal ClassCacheTest, @cache[ClassCacheTest] + @cache.store(ClassCacheTest) + assert_equal ClassCacheTest, @cache.get(ClassCacheTest) end def test_get_with_name - @cache[ClassCacheTest] = ClassCacheTest - assert_equal ClassCacheTest, @cache[ClassCacheTest.name] + @cache.store(ClassCacheTest) + assert_equal ClassCacheTest, @cache.get(ClassCacheTest.name) end def test_get_constantizes assert @cache.empty? - assert_equal ClassCacheTest, @cache[ClassCacheTest.name] + assert_equal ClassCacheTest, @cache.get(ClassCacheTest.name) end - def test_get_is_an_alias - assert_equal @cache[ClassCacheTest], @cache.get(ClassCacheTest.name) + def test_get_constantizes_fails_on_invalid_names + assert @cache.empty? + assert_raise NameError do + @cache.get("OmgTotallyInvalidConstantName") + end + end + + def test_get_alias + assert @cache.empty? + assert_equal @cache[ClassCacheTest.name], @cache.get(ClassCacheTest.name) + end + + def test_safe_get_constantizes + assert @cache.empty? + assert_equal ClassCacheTest, @cache.safe_get(ClassCacheTest.name) + end + + def test_safe_get_constantizes_doesnt_fail_on_invalid_names + assert @cache.empty? + assert_equal nil, @cache.safe_get("OmgTotallyInvalidConstantName") end def test_new_rejects_strings diff --git a/activesupport/test/clean_logger_test.rb b/activesupport/test/clean_logger_test.rb index 2cc46904b4..178c7c0b23 100644 --- a/activesupport/test/clean_logger_test.rb +++ b/activesupport/test/clean_logger_test.rb @@ -1,11 +1,11 @@ require 'abstract_unit' require 'stringio' -require 'active_support/core_ext/logger' +require 'active_support/logger' class CleanLoggerTest < Test::Unit::TestCase def setup @out = StringIO.new - @logger = Logger.new(@out) + @logger = ActiveSupport::Logger.new(@out) end def test_format_message @@ -13,40 +13,11 @@ class CleanLoggerTest < Test::Unit::TestCase assert_equal "error\n", @out.string end - def test_silence - # Without yielding self. - @logger.silence do - @logger.debug 'debug' - @logger.info 'info' - @logger.warn 'warn' - @logger.error 'error' - @logger.fatal 'fatal' - end - - # Yielding self. - @logger.silence do |logger| - logger.debug 'debug' - logger.info 'info' - logger.warn 'warn' - logger.error 'error' - logger.fatal 'fatal' - end - - # Silencer off. - Logger.silencer = false - @logger.silence do |logger| - logger.warn 'unsilenced' - end - Logger.silencer = true - - assert_equal "error\nfatal\nerror\nfatal\nunsilenced\n", @out.string - end - def test_datetime_format @logger.formatter = Logger::Formatter.new - @logger.datetime_format = "%Y-%m-%d" + @logger.formatter.datetime_format = "%Y-%m-%d" @logger.debug 'debug' - assert_equal "%Y-%m-%d", @logger.datetime_format + assert_equal "%Y-%m-%d", @logger.formatter.datetime_format assert_match(/D, \[\d\d\d\d-\d\d-\d\d#\d+\] DEBUG -- : debug/, @out.string) end diff --git a/activesupport/test/concern_test.rb b/activesupport/test/concern_test.rb index 4cbe56a2d2..0b0920ee03 100644 --- a/activesupport/test/concern_test.rb +++ b/activesupport/test/concern_test.rb @@ -19,9 +19,6 @@ class ConcernTest < Test::Unit::TestCase end end - module InstanceMethods - end - included do self.included_ran = true end @@ -74,7 +71,7 @@ class ConcernTest < Test::Unit::TestCase def test_instance_methods_are_included @klass.send(:include, Baz) assert_equal "baz", @klass.new.baz - assert @klass.included_modules.include?(ConcernTest::Baz::InstanceMethods) + assert @klass.included_modules.include?(ConcernTest::Baz) end def test_included_block_is_ran @@ -92,6 +89,6 @@ class ConcernTest < Test::Unit::TestCase def test_dependencies_with_multiple_modules @klass.send(:include, Foo) - assert_equal [ConcernTest::Foo, ConcernTest::Bar, ConcernTest::Baz::InstanceMethods, ConcernTest::Baz], @klass.included_modules[0..3] + assert_equal [ConcernTest::Foo, ConcernTest::Bar, ConcernTest::Baz], @klass.included_modules[0..2] end end diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb index 52231aaeb0..278734027a 100644 --- a/activesupport/test/core_ext/array_ext_test.rb +++ b/activesupport/test/core_ext/array_ext_test.rb @@ -343,54 +343,34 @@ end class ArrayUniqByTests < Test::Unit::TestCase def test_uniq_by - 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 }) + 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] - a.uniq_by! { |i| i.odd? } + ActiveSupport::Deprecation.silence do + a.uniq_by! { |i| i.odd? } + end assert_equal [1,2], a a = [1,2,3,4] - a.uniq_by! { |i| i.even? } + ActiveSupport::Deprecation.silence do + a.uniq_by! { |i| i.even? } + end assert_equal [1,2], a a = (-5..5).to_a - a.uniq_by! { |i| i**2 } + ActiveSupport::Deprecation.silence do + a.uniq_by! { |i| i**2 } + end assert_equal((-5..0).to_a, a) end end -class ArrayExtRandomTests < ActiveSupport::TestCase - def test_sample_from_array - assert_nil [].sample - assert_equal [], [].sample(5) - assert_equal 42, [42].sample - assert_equal [42], [42].sample(5) - - a = [:foo, :bar, 42] - s = a.sample(2) - assert_equal 2, s.size - assert_equal 1, (a-s).size - assert_equal [], a-(0..20).sum{a.sample(2)} - - o = Object.new - def o.to_int; 1; end - assert_equal [0], [0].sample(o) - - o = Object.new - assert_raises(TypeError) { [0].sample(o) } - - o = Object.new - def o.to_int; ''; end - assert_raises(TypeError) { [0].sample(o) } - - assert_raises(ArgumentError) { [0].sample(-7) } - end -end - class ArrayWrapperTests < Test::Unit::TestCase class FakeCollection def to_ary diff --git a/activesupport/test/core_ext/base64_ext_test.rb b/activesupport/test/core_ext/base64_ext_test.rb index bd0e9f843d..544c990b3c 100644 --- a/activesupport/test/core_ext/base64_ext_test.rb +++ b/activesupport/test/core_ext/base64_ext_test.rb @@ -2,7 +2,9 @@ require 'abstract_unit' class Base64Test < Test::Unit::TestCase def test_no_newline_in_encoded_value - assert_match(/\n/, ActiveSupport::Base64.encode64("oneverylongstringthatwouldnormallybesplitupbynewlinesbytheregularbase64")) - assert_no_match(/\n/, ActiveSupport::Base64.encode64s("oneverylongstringthatwouldnormallybesplitupbynewlinesbytheregularbase64")) + ActiveSupport::Deprecation.silence do + assert_match(/\n/, ActiveSupport::Base64.encode64("oneverylongstringthatwouldnormallybesplitupbynewlinesbytheregularbase64")) + assert_no_match(/\n/, ActiveSupport::Base64.encode64s("oneverylongstringthatwouldnormallybesplitupbynewlinesbytheregularbase64")) + end end end diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb index b4f848cd44..09d4765390 100644 --- a/activesupport/test/core_ext/date_ext_test.rb +++ b/activesupport/test/core_ext/date_ext_test.rb @@ -57,6 +57,16 @@ class DateExtCalculationsTest < ActiveSupport::TestCase assert_equal Date.new(2005,11,28), Date.new(2005,12,04).beginning_of_week #sunday end + def test_monday + assert_equal Date.new(2005,11,28), Date.new(2005,11,28).monday + assert_equal Date.new(2005,11,28), Date.new(2005,12,01).monday + end + + def test_sunday + assert_equal Date.new(2008,3,2), Date.new(2008,3,02).sunday + assert_equal Date.new(2008,3,2), Date.new(2008,2,29).sunday + end + def test_beginning_of_week_in_calendar_reform assert_equal Date.new(1582,10,1), Date.new(1582,10,15).beginning_of_week #friday end @@ -374,16 +384,6 @@ class DateExtCalculationsTest < ActiveSupport::TestCase end end - if RUBY_VERSION < '1.9' - def test_rfc3339 - assert_equal('1980-02-28', Date.new(1980, 2, 28).rfc3339) - end - - def test_iso8601 - assert_equal('1980-02-28', Date.new(1980, 2, 28).iso8601) - end - end - def test_today Date.stubs(:current).returns(Date.new(2000, 1, 1)) assert_equal false, Date.new(1999, 12, 31).today? diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb index 456736cbad..0087163faf 100644 --- a/activesupport/test/core_ext/date_time_ext_test.rb +++ b/activesupport/test/core_ext/date_time_ext_test.rb @@ -34,8 +34,8 @@ class DateTimeExtCalculationsTest < Test::Unit::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, 0).to_time - assert_equal Time.utc_time(2039, 2, 21, 10, 11, 12), DateTime.new(2039, 2, 21, 10, 11, 12, 0, 0).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 @@ -54,6 +54,24 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase assert_equal 86399,DateTime.civil(2005,1,1,23,59,59).seconds_since_midnight end + def test_days_to_week_start + assert_equal 0, Time.local(2011,11,01,0,0,0).days_to_week_start(:tuesday) + assert_equal 1, Time.local(2011,11,02,0,0,0).days_to_week_start(:tuesday) + assert_equal 2, Time.local(2011,11,03,0,0,0).days_to_week_start(:tuesday) + assert_equal 3, Time.local(2011,11,04,0,0,0).days_to_week_start(:tuesday) + assert_equal 4, Time.local(2011,11,05,0,0,0).days_to_week_start(:tuesday) + assert_equal 5, Time.local(2011,11,06,0,0,0).days_to_week_start(:tuesday) + assert_equal 6, Time.local(2011,11,07,0,0,0).days_to_week_start(:tuesday) + + assert_equal 3, Time.local(2011,11,03,0,0,0).days_to_week_start(:monday) + assert_equal 3, Time.local(2011,11,04,0,0,0).days_to_week_start(:tuesday) + assert_equal 3, Time.local(2011,11,05,0,0,0).days_to_week_start(:wednesday) + assert_equal 3, Time.local(2011,11,06,0,0,0).days_to_week_start(:thursday) + assert_equal 3, Time.local(2011,11,07,0,0,0).days_to_week_start(:friday) + assert_equal 3, Time.local(2011,11,8,0,0,0).days_to_week_start(:saturday) + assert_equal 3, Time.local(2011,11,9,0,0,0).days_to_week_start(:sunday) + end + def test_beginning_of_week assert_equal DateTime.civil(2005,1,31), DateTime.civil(2005,2,4,10,10,10).beginning_of_week assert_equal DateTime.civil(2005,11,28), DateTime.civil(2005,11,28,0,0,0).beginning_of_week #monday @@ -99,7 +117,7 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase assert_equal DateTime.civil(2005,5,1,10), DateTime.civil(2005,6,5,10,0,0).weeks_ago(5) assert_equal DateTime.civil(2005,4,24,10), DateTime.civil(2005,6,5,10,0,0).weeks_ago(6) assert_equal DateTime.civil(2005,2,27,10), DateTime.civil(2005,6,5,10,0,0).weeks_ago(14) - assert_equal DateTime.civil(2004,12,25,10), DateTime.civil(2005,1,1,10,0,0).weeks_ago(1) + assert_equal DateTime.civil(2004,12,25,10), DateTime.civil(2005,1,1,10,0,0).weeks_ago(1) end def test_months_ago diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index cdfa991a34..f10e6c82e4 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -86,15 +86,6 @@ class EnumerableTests < Test::Unit::TestCase assert_equal 'abc', ('a'..'c').sum end - def test_each_with_object - enum = GenericEnumerable.new(%w(foo bar)) - result = enum.each_with_object({}) { |str, hsh| hsh[str] = str.upcase } - assert_equal({'foo' => 'FOO', 'bar' => 'BAR'}, result) - assert_equal Enumerator, enum.each_with_object({}).class - result2 = enum.each_with_object({}).each{|str, hsh| hsh[str] = str.upcase} - assert_equal result, result2 - end - def test_index_by payments = GenericEnumerable.new([ Payment.new(5), Payment.new(15), Payment.new(10) ]) assert_equal({ 5 => Payment.new(5), 15 => Payment.new(15), 10 => Payment.new(10) }, diff --git a/activesupport/test/core_ext/file_test.rb b/activesupport/test/core_ext/file_test.rb index e1258b872e..26be694176 100644 --- a/activesupport/test/core_ext/file_test.rb +++ b/activesupport/test/core_ext/file_test.rb @@ -57,10 +57,6 @@ class AtomicWriteTest < Test::Unit::TestCase File.unlink(file_name) rescue nil end - def test_responds_to_to_path - assert_equal __FILE__, File.open(__FILE__, "r").to_path - end - private def file_name "atomic.file" diff --git a/activesupport/test/core_ext/float_ext_test.rb b/activesupport/test/core_ext/float_ext_test.rb deleted file mode 100644 index ac7e7a8ed6..0000000000 --- a/activesupport/test/core_ext/float_ext_test.rb +++ /dev/null @@ -1,26 +0,0 @@ -require 'abstract_unit' -require 'active_support/core_ext/float/rounding' - -class FloatExtRoundingTests < Test::Unit::TestCase - def test_round_for_positive_number - assert_equal 1, 1.4.round - assert_equal 2, 1.6.round - assert_equal 2, 1.6.round(0) - assert_equal 1.4, 1.4.round(1) - assert_equal 1.4, 1.4.round(3) - assert_equal 1.5, 1.45.round(1) - assert_equal 1.45, 1.445.round(2) - end - - def test_round_for_negative_number - assert_equal( -1, -1.4.round ) - assert_equal( -2, -1.6.round ) - assert_equal( -1.4, -1.4.round(1) ) - assert_equal( -1.5, -1.45.round(1) ) - end - - def test_round_with_negative_precision - assert_equal 123460.0, 123456.0.round(-1) - assert_equal 123500.0, 123456.0.round(-2) - end -end diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index fa800eada2..dfa0cdb478 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -27,11 +27,7 @@ class HashExtTest < Test::Unit::TestCase @symbols = { :a => 1, :b => 2 } @mixed = { :a => 1, 'b' => 2 } @fixnums = { 0 => 1, 1 => 2 } - if RUBY_VERSION < '1.9.0' - @illegal_symbols = { "\0" => 1, "" => 2, [] => 3 } - else - @illegal_symbols = { [] => 3 } - end + @illegal_symbols = { [] => 3 } end def test_methods @@ -121,6 +117,9 @@ class HashExtTest < Test::Unit::TestCase foo = { "foo" => NonIndifferentHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access assert_kind_of NonIndifferentHash, foo["foo"] + + foo = { "foo" => IndifferentHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access + assert_kind_of IndifferentHash, foo["foo"] end def test_indifferent_assorted diff --git a/activesupport/test/core_ext/integer_ext_test.rb b/activesupport/test/core_ext/integer_ext_test.rb index fe8c7eb224..b1f5f70a70 100644 --- a/activesupport/test/core_ext/integer_ext_test.rb +++ b/activesupport/test/core_ext/integer_ext_test.rb @@ -2,6 +2,8 @@ require 'abstract_unit' require 'active_support/core_ext/integer' class IntegerExtTest < Test::Unit::TestCase + PRIME = 22953686867719691230002707821868552601124472329079 + def test_multiple_of [ -7, 0, 7, 14 ].each { |i| assert i.multiple_of?(7) } [ -7, 7, 14 ].each { |i| assert ! i.multiple_of?(6) } @@ -11,10 +13,7 @@ class IntegerExtTest < Test::Unit::TestCase assert !5.multiple_of?(0) # test with a prime - assert !22953686867719691230002707821868552601124472329079.multiple_of?(2) - assert !22953686867719691230002707821868552601124472329079.multiple_of?(3) - assert !22953686867719691230002707821868552601124472329079.multiple_of?(5) - assert !22953686867719691230002707821868552601124472329079.multiple_of?(7) + [2, 3, 5, 7].each { |i| assert !PRIME.multiple_of?(i) } end def test_ordinalize diff --git a/activesupport/test/core_ext/io_test.rb b/activesupport/test/core_ext/io_test.rb deleted file mode 100644 index b9abf685da..0000000000 --- a/activesupport/test/core_ext/io_test.rb +++ /dev/null @@ -1,23 +0,0 @@ -require 'abstract_unit' - -require 'active_support/core_ext/io' - -class IOTest < Test::Unit::TestCase - def test_binread_one_arg - assert_equal File.read(__FILE__), IO.binread(__FILE__) - end - - def test_binread_two_args - assert_equal File.read(__FILE__).bytes.first(10).pack('C*'), - IO.binread(__FILE__, 10) - end - - def test_binread_three_args - actual = IO.binread(__FILE__, 5, 10) - expected = File.open(__FILE__, 'rb') { |f| - f.seek 10 - f.read 5 - } - assert_equal expected, actual - end -end diff --git a/activesupport/test/core_ext/kernel_test.rb b/activesupport/test/core_ext/kernel_test.rb index 995bc0751a..73a7179872 100644 --- a/activesupport/test/core_ext/kernel_test.rb +++ b/activesupport/test/core_ext/kernel_test.rb @@ -42,11 +42,6 @@ class KernelTest < Test::Unit::TestCase assert_equal 1, silence_stderr { 1 } end - def test_singleton_class - o = Object.new - assert_equal class << o; self end, o.singleton_class - end - def test_class_eval o = Object.new class << o; @x = 1; end @@ -112,4 +107,4 @@ class KernelDebuggerTest < Test::Unit::TestCase ensure Object.send(:remove_const, "Rails") end -end
\ No newline at end of file +end diff --git a/activesupport/test/core_ext/module/qualified_const_test.rb b/activesupport/test/core_ext/module/qualified_const_test.rb new file mode 100644 index 0000000000..8af0b9a023 --- /dev/null +++ b/activesupport/test/core_ext/module/qualified_const_test.rb @@ -0,0 +1,94 @@ +require 'abstract_unit' +require 'active_support/core_ext/module/qualified_const' + +module QualifiedConstTestMod + X = false + + module M + X = 1 + + class C + X = 2 + end + end + + module N + include M + end +end + +class QualifiedConstTest < ActiveSupport::TestCase + test "Object.qualified_const_defined?" do + assert Object.qualified_const_defined?("QualifiedConstTestMod") + assert !Object.qualified_const_defined?("NonExistingQualifiedConstTestMod") + + assert Object.qualified_const_defined?("QualifiedConstTestMod::X") + assert !Object.qualified_const_defined?("QualifiedConstTestMod::Y") + + assert Object.qualified_const_defined?("QualifiedConstTestMod::M::X") + assert !Object.qualified_const_defined?("QualifiedConstTestMod::M::Y") + + if Module.method(:const_defined?).arity == 1 + assert !Object.qualified_const_defined?("QualifiedConstTestMod::N::X") + else + assert Object.qualified_const_defined?("QualifiedConstTestMod::N::X") + assert !Object.qualified_const_defined?("QualifiedConstTestMod::N::X", false) + assert Object.qualified_const_defined?("QualifiedConstTestMod::N::X", true) + end + end + + test "mod.qualified_const_defined?" do + assert QualifiedConstTestMod.qualified_const_defined?("M") + assert !QualifiedConstTestMod.qualified_const_defined?("NonExistingM") + + assert QualifiedConstTestMod.qualified_const_defined?("M::X") + assert !QualifiedConstTestMod.qualified_const_defined?("M::Y") + + assert QualifiedConstTestMod.qualified_const_defined?("M::C::X") + assert !QualifiedConstTestMod.qualified_const_defined?("M::C::Y") + + if Module.method(:const_defined?).arity == 1 + assert !QualifiedConstTestMod.qualified_const_defined?("QualifiedConstTestMod::N::X") + else + assert QualifiedConstTestMod.qualified_const_defined?("N::X") + assert !QualifiedConstTestMod.qualified_const_defined?("N::X", false) + assert QualifiedConstTestMod.qualified_const_defined?("N::X", true) + end + end + + test "qualified_const_get" do + assert_equal false, Object.qualified_const_get("QualifiedConstTestMod::X") + assert_equal false, QualifiedConstTestMod.qualified_const_get("X") + assert_equal 1, QualifiedConstTestMod.qualified_const_get("M::X") + assert_equal 1, QualifiedConstTestMod.qualified_const_get("N::X") + assert_equal 2, QualifiedConstTestMod.qualified_const_get("M::C::X") + + assert_raise(NameError) { QualifiedConstTestMod.qualified_const_get("M::C::Y")} + end + + test "qualified_const_set" do + m = Module.new + assert_equal m, Object.qualified_const_set("QualifiedConstTestMod2", m) + assert_equal m, ::QualifiedConstTestMod2 + + # We are going to assign to existing constants on purpose, so silence warnings. + silence_warnings do + assert_equal true, QualifiedConstTestMod.qualified_const_set("QualifiedConstTestMod::X", true) + assert_equal true, QualifiedConstTestMod::X + + assert_equal 10, QualifiedConstTestMod::M.qualified_const_set("X", 10) + assert_equal 10, QualifiedConstTestMod::M::X + end + 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(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(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)} + end +end diff --git a/activesupport/test/core_ext/module/remove_method_test.rb b/activesupport/test/core_ext/module/remove_method_test.rb new file mode 100644 index 0000000000..4657f0c175 --- /dev/null +++ b/activesupport/test/core_ext/module/remove_method_test.rb @@ -0,0 +1,29 @@ +require 'abstract_unit' +require 'active_support/core_ext/module/remove_method' + +module RemoveMethodTests + class A + def do_something + return 1 + end + + end +end + +class RemoveMethodTest < ActiveSupport::TestCase + + def test_remove_method_from_an_object + RemoveMethodTests::A.class_eval{ + self.remove_possible_method(:do_something) + } + assert !RemoveMethodTests::A.new.respond_to?(:do_something) + end + + def test_redefine_method_in_an_object + RemoveMethodTests::A.class_eval{ + self.redefine_method(:do_something) { return 100 } + } + assert_equal 100, RemoveMethodTests::A.new.do_something + end + +end
\ No newline at end of file diff --git a/activesupport/test/core_ext/module/synchronization_test.rb b/activesupport/test/core_ext/module/synchronization_test.rb deleted file mode 100644 index 6c407e2260..0000000000 --- a/activesupport/test/core_ext/module/synchronization_test.rb +++ /dev/null @@ -1,89 +0,0 @@ -require 'thread' -require 'abstract_unit' - -require 'active_support/core_ext/class/attribute_accessors' -require 'active_support/core_ext/module/synchronization' - -class SynchronizationTest < Test::Unit::TestCase - def setup - @target = Class.new - @target.cattr_accessor :mutex, :instance_writer => false - @target.mutex = Mutex.new - @instance = @target.new - end - - def test_synchronize_aliases_method_chain_with_synchronize - @target.module_eval do - attr_accessor :value - synchronize :value, :with => :mutex - end - assert_respond_to @instance, :value_with_synchronization - assert_respond_to @instance, :value_without_synchronization - end - - def test_synchronize_does_not_change_behavior - @target.module_eval do - attr_accessor :value - synchronize :value, :with => :mutex - end - expected = "some state" - @instance.value = expected - assert_equal expected, @instance.value - end - - def test_synchronize_with_no_mutex_raises_an_argument_error - assert_raise(ArgumentError) do - @target.synchronize :to_s - end - end - - def test_double_synchronize_raises_an_argument_error - @target.synchronize :to_s, :with => :mutex - assert_raise(ArgumentError) do - @target.synchronize :to_s, :with => :mutex - end - end - - def dummy_sync - dummy = Object.new - def dummy.synchronize - @sync_count ||= 0 - @sync_count += 1 - yield - end - def dummy.sync_count; @sync_count; end - dummy - end - - def test_mutex_is_entered_during_method_call - @target.mutex = dummy_sync - @target.synchronize :to_s, :with => :mutex - @instance.to_s - @instance.to_s - assert_equal 2, @target.mutex.sync_count - end - - def test_can_synchronize_method_with_punctuation - @target.module_eval do - def dangerous? - @dangerous - end - def dangerous! - @dangerous = true - end - end - @target.synchronize :dangerous?, :dangerous!, :with => :mutex - @instance.dangerous! - assert @instance.dangerous? - end - - def test_can_synchronize_singleton_methods - @target.mutex = dummy_sync - class << @target - synchronize :to_s, :with => :mutex - end - assert_respond_to @target, :to_s_without_synchronization - assert_nothing_raised { @target.to_s; @target.to_s } - assert_equal 2, @target.mutex.sync_count - end -end diff --git a/activesupport/test/core_ext/object/inclusion_test.rb b/activesupport/test/core_ext/object/inclusion_test.rb index 1de857d678..568ebe9aab 100644 --- a/activesupport/test/core_ext/object/inclusion_test.rb +++ b/activesupport/test/core_ext/object/inclusion_test.rb @@ -2,6 +2,16 @@ require 'abstract_unit' require 'active_support/core_ext/object/inclusion' class InTest < Test::Unit::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_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb index beb371d987..782a01213d 100644 --- a/activesupport/test/core_ext/object_and_class_ext_test.rb +++ b/activesupport/test/core_ext/object_and_class_ext_test.rb @@ -99,13 +99,13 @@ class ObjectTryTest < Test::Unit::TestCase def test_nonexisting_method method = :undefined_method assert !@string.respond_to?(method) - assert_nil @string.try(method) + assert_raise(NoMethodError) { @string.try(method) } end def test_nonexisting_method_with_arguments method = :undefined_method assert !@string.respond_to?(method) - assert_nil @string.try(method, 'llo', 'y') + assert_raise(NoMethodError) { @string.try(method, 'llo', 'y') } end def test_valid_method diff --git a/activesupport/test/core_ext/range_ext_test.rb b/activesupport/test/core_ext/range_ext_test.rb index 1424fa4aca..7a620305f3 100644 --- a/activesupport/test/core_ext/range_ext_test.rb +++ b/activesupport/test/core_ext/range_ext_test.rb @@ -53,6 +53,10 @@ class RangeTest < Test::Unit::TestCase assert !(2..8).include?(5..9) end + def test_should_include_identical_exclusive_with_floats + assert (1.0...10.0).include?(1.0...10.0) + end + def test_blockless_step assert_equal [1,3,5,7,9], (1..10).step(2) end @@ -63,15 +67,8 @@ class RangeTest < Test::Unit::TestCase assert_equal [1,3,5,7,9], array end - if RUBY_VERSION < '1.9' - def test_cover - assert((1..3).cover?(2)) - assert !(1..3).cover?(4) - end - else - def test_cover_is_not_override - range = (1..3) - assert range.method(:include?) != range.method(:cover?) - end + def test_cover_is_not_override + range = (1..3) + assert range.method(:include?) != range.method(:cover?) end end diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 5c1dddaf96..2e44cbe247 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -20,12 +20,6 @@ end class StringInflectionsTest < Test::Unit::TestCase include InflectorTestCases include ConstantizeTestCases - - def test_erb_escape - string = [192, 60].pack('CC') - expected = 192.chr + "<" - assert_equal expected, ERB::Util.html_escape(string) - end def test_strip_heredoc_on_an_empty_string assert_equal '', ''.strip_heredoc @@ -64,6 +58,10 @@ class StringInflectionsTest < Test::Unit::TestCase end assert_equal("plurals", "plurals".pluralize) + + assert_equal("blargles", "blargle".pluralize(0)) + assert_equal("blargle", "blargle".pluralize(1)) + assert_equal("blargles", "blargle".pluralize(2)) end def test_singularize @@ -107,6 +105,10 @@ class StringInflectionsTest < Test::Unit::TestCase assert_equal "Account", "MyApplication::Billing::Account".demodulize end + def test_deconstantize + assert_equal "MyApplication::Billing", "MyApplication::Billing::Account".deconstantize + end + def test_foreign_key ClassNameToForeignKeyWithUnderscore.each do |klass, foreign_key| assert_equal(foreign_key, klass.foreign_key) @@ -158,14 +160,6 @@ class StringInflectionsTest < Test::Unit::TestCase assert_equal 97, 'abc'.ord end - if RUBY_VERSION < '1.9' - def test_getbyte - assert_equal 97, 'a'.getbyte(0) - assert_equal 99, 'abc'.getbyte(2) - assert_nil 'abc'.getbyte(3) - end - 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) @@ -285,29 +279,17 @@ class StringInflectionsTest < Test::Unit::TestCase assert_equal "Hello Big[...]", "Hello Big World!".truncate(15, :omission => "[...]", :separator => ' ') end - if RUBY_VERSION < '1.9.0' - def test_truncate_multibyte - with_kcode 'none' do - assert_equal "\354\225\210\353\205\225\355...", "\354\225\210\353\205\225\355\225\230\354\204\270\354\232\224".truncate(10) - end - with_kcode 'u' do - assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...", - "\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".truncate(10) - end - end - else - 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) - 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) end - + def test_constantize run_constantize_tests_on do |string| string.constantize end end - + def test_safe_constantize run_safe_constantize_tests_on do |string| string.safe_constantize @@ -336,22 +318,8 @@ class CoreExtStringMultibyteTest < ActiveSupport::TestCase assert !BYTE_STRING.is_utf8? end - if RUBY_VERSION < '1.9' - def test_mb_chars_returns_self_when_kcode_not_set - with_kcode('none') do - assert_kind_of String, UNICODE_STRING.mb_chars - end - end - - def test_mb_chars_returns_an_instance_of_the_chars_proxy_when_kcode_utf8 - with_kcode('UTF8') do - assert_kind_of ActiveSupport::Multibyte.proxy_class, UNICODE_STRING.mb_chars - end - end - else - def test_mb_chars_returns_instance_of_proxy_class - assert_kind_of ActiveSupport::Multibyte.proxy_class, UNICODE_STRING.mb_chars - end + def test_mb_chars_returns_instance_of_proxy_class + assert_kind_of ActiveSupport::Multibyte.proxy_class, UNICODE_STRING.mb_chars end end @@ -381,7 +349,7 @@ class OutputSafetyTest < ActiveSupport::TestCase test "A fixnum is safe by default" do assert 5.html_safe? end - + test "a float is safe by default" do assert 5.7.html_safe? end @@ -477,10 +445,8 @@ class OutputSafetyTest < ActiveSupport::TestCase end test 'knows whether it is encoding aware' do - if RUBY_VERSION >= "1.9" + assert_deprecated do assert 'ruby'.encoding_aware? - else - assert !'ruby'.encoding_aware? end end @@ -489,6 +455,23 @@ class OutputSafetyTest < ActiveSupport::TestCase assert string.html_safe? assert !string.to_param.html_safe? end + + test "ERB::Util.html_escape should escape unsafe characters" do + string = '<>&"' + expected = '<>&"' + assert_equal expected, ERB::Util.html_escape(string) + end + + test "ERB::Util.html_escape should correctly handle invalid UTF-8 strings" do + string = [192, 60].pack('CC') + expected = 192.chr + "<" + assert_equal expected, ERB::Util.html_escape(string) + end + + test "ERB::Util.html_escape should not escape safe strings" do + string = "<b>hello</b>".html_safe + assert_equal string, ERB::Util.html_escape(string) + end end class StringExcludeTest < ActiveSupport::TestCase diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb index ab9be4b18b..6cc63851e9 100644 --- a/activesupport/test/core_ext/time_ext_test.rb +++ b/activesupport/test/core_ext/time_ext_test.rb @@ -59,8 +59,28 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase assert_equal Time.local(2005,11,28), Time.local(2005,12,02,0,0,0).beginning_of_week #friday assert_equal Time.local(2005,11,28), Time.local(2005,12,03,0,0,0).beginning_of_week #saturday assert_equal Time.local(2005,11,28), Time.local(2005,12,04,0,0,0).beginning_of_week #sunday + + end + + def test_days_to_week_start + assert_equal 0, Time.local(2011,11,01,0,0,0).days_to_week_start(:tuesday) + assert_equal 1, Time.local(2011,11,02,0,0,0).days_to_week_start(:tuesday) + assert_equal 2, Time.local(2011,11,03,0,0,0).days_to_week_start(:tuesday) + assert_equal 3, Time.local(2011,11,04,0,0,0).days_to_week_start(:tuesday) + assert_equal 4, Time.local(2011,11,05,0,0,0).days_to_week_start(:tuesday) + assert_equal 5, Time.local(2011,11,06,0,0,0).days_to_week_start(:tuesday) + assert_equal 6, Time.local(2011,11,07,0,0,0).days_to_week_start(:tuesday) + + assert_equal 3, Time.local(2011,11,03,0,0,0).days_to_week_start(:monday) + assert_equal 3, Time.local(2011,11,04,0,0,0).days_to_week_start(:tuesday) + assert_equal 3, Time.local(2011,11,05,0,0,0).days_to_week_start(:wednesday) + assert_equal 3, Time.local(2011,11,06,0,0,0).days_to_week_start(:thursday) + assert_equal 3, Time.local(2011,11,07,0,0,0).days_to_week_start(:friday) + assert_equal 3, Time.local(2011,11,8,0,0,0).days_to_week_start(:saturday) + assert_equal 3, Time.local(2011,11,9,0,0,0).days_to_week_start(:sunday) 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 @@ -135,7 +155,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase assert_equal Time.local(2005,5,1,10), Time.local(2005,6,5,10,0,0).weeks_ago(5) assert_equal Time.local(2005,4,24,10), Time.local(2005,6,5,10,0,0).weeks_ago(6) assert_equal Time.local(2005,2,27,10), Time.local(2005,6,5,10,0,0).weeks_ago(14) - assert_equal Time.local(2004,12,25,10), Time.local(2005,1,1,10,0,0).weeks_ago(1) + assert_equal Time.local(2004,12,25,10), Time.local(2005,1,1,10,0,0).weeks_ago(1) end def test_months_ago @@ -479,7 +499,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase assert_equal Time.local(2006,10,30), Time.local(2006,11,6,0,0,0).prev_week assert_equal Time.local(2006,11,15), Time.local(2006,11,23,0,0,0).prev_week(:wednesday) end - end + end def test_next_week with_env_tz 'US/Eastern' do @@ -538,12 +558,12 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase end def test_to_datetime - assert_equal Time.utc(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, 0, 0) + assert_equal Time.utc(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, 0) with_env_tz 'US/Eastern' do - assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400), 0) + assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400)) end with_env_tz 'NZ' do - assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400), 0) + assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400)) end assert_equal ::Date::ITALY, Time.utc(2005, 2, 21, 17, 44, 30).to_datetime.start # use Ruby's default start value end @@ -592,11 +612,11 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase 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, 0) - assert_equal Time.time_with_datetime_fallback(:local, 2039, 2, 21, 17, 44, 30), DateTime.civil(2039, 2, 21, 17, 44, 30, DateTime.local_offset, 0) - assert_equal Time.time_with_datetime_fallback(:utc, 1900, 2, 21, 17, 44, 30), DateTime.civil(1900, 2, 21, 17, 44, 30, 0, 0) + 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(2039, 2, 21, 17, 44, 30, DateTime.local_offset) + 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, 0) + 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? @@ -616,16 +636,16 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase 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, 0) - assert_equal Time.utc_time(1901, 2, 21, 17, 44, 30), DateTime.civil(1901, 2, 21, 17, 44, 30, 0, 0) + 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(2039, 2, 21, 17, 44, 30, DateTime.local_offset, 0) + assert_equal Time.local_time(2039, 2, 21, 17, 44, 30), DateTime.civil(2039, 2, 21, 17, 44, 30, DateTime.local_offset) unless time_is_64bits? - assert_equal Time.local_time(1901, 2, 21, 17, 44, 30), DateTime.civil(1901, 2, 21, 17, 44, 30, DateTime.local_offset, 0) + assert_equal Time.local_time(1901, 2, 21, 17, 44, 30), DateTime.civil(1901, 2, 21, 17, 44, 30, DateTime.local_offset) end end @@ -744,6 +764,12 @@ 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_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"]) ) + assert_equal false,Time.utc(2000, 1, 1, 0, 0, 1).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC']) ) + end + def test_minus_with_time_with_zone assert_equal 86_400.0, Time.utc(2000, 1, 2) - ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), ActiveSupport::TimeZone['UTC'] ) end diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb index b2309ae806..04f5ea85a8 100644 --- a/activesupport/test/core_ext/time_with_zone_test.rb +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -200,8 +200,15 @@ class TimeWithZoneTest < Test::Unit::TestCase end def test_eql? - assert @twz.eql?(Time.utc(2000)) - assert @twz.eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]) ) + assert_equal true, @twz.eql?(Time.utc(2000)) + assert_equal true, @twz.eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]) ) + assert_equal false, @twz.eql?( Time.utc(2000, 1, 1, 0, 0, 1) ) + assert_equal false, @twz.eql?( DateTime.civil(1999, 12, 31, 23, 59, 59) ) + end + + def test_hash + assert_equal Time.utc(2000).hash, @twz.hash + assert_equal Time.utc(2000).hash, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]).hash end def test_plus_with_integer @@ -441,9 +448,8 @@ class TimeWithZoneTest < Test::Unit::TestCase end def test_ruby_19_weekday_name_query_methods - ruby_19_or_greater = RUBY_VERSION >= '1.9' %w(sunday? monday? tuesday? wednesday? thursday? friday? saturday?).each do |name| - assert_equal ruby_19_or_greater, @twz.respond_to?(name) + assert_respond_to @twz, name end end diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index fe8f51e11a..7039f90499 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -258,6 +258,85 @@ class DependenciesTest < Test::Unit::TestCase $:.replace(original_path) end + def test_require_returns_true_when_file_not_yet_required + path = File.expand_path("../autoloading_fixtures/load_path", __FILE__) + original_path = $:.dup + original_features = $".dup + $:.push(path) + + with_loading do + assert_equal true, require('loaded_constant') + end + ensure + remove_constants(:LoadedConstant) + $".replace(original_features) + $:.replace(original_path) + end + + def test_require_returns_true_when_file_not_yet_required_even_when_no_new_constants_added + path = File.expand_path("../autoloading_fixtures/load_path", __FILE__) + original_path = $:.dup + original_features = $".dup + $:.push(path) + + with_loading do + Object.module_eval "module LoadedConstant; end" + assert_equal true, require('loaded_constant') + end + ensure + remove_constants(:LoadedConstant) + $".replace(original_features) + $:.replace(original_path) + end + + def test_require_returns_false_when_file_already_required + path = File.expand_path("../autoloading_fixtures/load_path", __FILE__) + original_path = $:.dup + original_features = $".dup + $:.push(path) + + with_loading do + require 'loaded_constant' + assert_equal false, require('loaded_constant') + end + ensure + remove_constants(:LoadedConstant) + $".replace(original_features) + $:.replace(original_path) + end + + def test_require_raises_load_error_when_file_not_found + with_loading do + assert_raise(LoadError) { require 'this_file_dont_exist_dude' } + end + ensure + remove_constants(:LoadedConstant) + end + + def test_load_returns_true_when_file_found + path = File.expand_path("../autoloading_fixtures/load_path", __FILE__) + original_path = $:.dup + original_features = $".dup + $:.push(path) + + with_loading do + assert_equal true, load('loaded_constant.rb') + assert_equal true, load('loaded_constant.rb') + end + ensure + remove_constants(:LoadedConstant) + $".replace(original_features) + $:.replace(original_path) + end + + def test_load_raises_load_error_when_file_not_found + with_loading do + assert_raise(LoadError) { load 'this_file_dont_exist_dude.rb' } + end + ensure + remove_constants(:LoadedConstant) + end + def failing_test_access_thru_and_upwards_fails with_autoloading_fixtures do assert ! defined?(ModuleFolder) diff --git a/activesupport/test/file_update_checker_test.rb b/activesupport/test/file_update_checker_test.rb index b65bb1d024..dd19b58aa2 100644 --- a/activesupport/test/file_update_checker_test.rb +++ b/activesupport/test/file_update_checker_test.rb @@ -4,15 +4,17 @@ require 'fileutils' MTIME_FIXTURES_PATH = File.expand_path("../fixtures", __FILE__) -class FileUpdateCheckerTest < Test::Unit::TestCase +class FileUpdateCheckerWithEnumerableTest < Test::Unit::TestCase FILES = %w(1.txt 2.txt 3.txt) def setup + FileUtils.mkdir_p("tmp_watcher") FileUtils.touch(FILES) end def teardown - FileUtils.rm(FILES) + FileUtils.rm_rf("tmp_watcher") + FileUtils.rm_rf(FILES) end def test_should_not_execute_the_block_if_no_paths_are_given @@ -22,34 +24,60 @@ class FileUpdateCheckerTest < Test::Unit::TestCase assert_equal 0, i end - def test_should_invoke_the_block_on_first_call_if_it_does_not_calculate_last_updated_at_on_load + def test_should_not_invoke_the_block_if_no_file_has_changed i = 0 checker = ActiveSupport::FileUpdateChecker.new(FILES){ i += 1 } - checker.execute_if_updated - assert_equal 1, i + 5.times { assert !checker.execute_if_updated } + assert_equal 0, i end - def test_should_not_invoke_the_block_on_first_call_if_it_calculates_last_updated_at_on_load + def test_should_invoke_the_block_if_a_file_has_changed i = 0 - checker = ActiveSupport::FileUpdateChecker.new(FILES, true){ i += 1 } - checker.execute_if_updated - assert_equal 0, i + checker = ActiveSupport::FileUpdateChecker.new(FILES){ i += 1 } + sleep(1) + FileUtils.touch(FILES) + assert checker.execute_if_updated + assert_equal 1, i end - def test_should_not_invoke_the_block_if_no_file_has_changed + def test_should_be_robust_enough_to_handle_deleted_files i = 0 checker = ActiveSupport::FileUpdateChecker.new(FILES){ i += 1 } - 5.times { checker.execute_if_updated } - assert_equal 1, i + FileUtils.rm(FILES) + assert !checker.execute_if_updated + assert_equal 0, i end - def test_should_invoke_the_block_if_a_file_has_changed + def test_should_cache_updated_result_until_execute i = 0 checker = ActiveSupport::FileUpdateChecker.new(FILES){ i += 1 } - checker.execute_if_updated + assert !checker.updated? + sleep(1) FileUtils.touch(FILES) - checker.execute_if_updated - assert_equal 2, i + + assert checker.updated? + checker.execute + assert !checker.updated? + end + + def test_should_invoke_the_block_if_a_watched_dir_changed_its_glob + i = 0 + checker = ActiveSupport::FileUpdateChecker.new([], "tmp_watcher" => [:txt]){ i += 1 } + FileUtils.cd "tmp_watcher" do + FileUtils.touch(FILES) + end + assert checker.execute_if_updated + assert_equal 1, i + end + + def test_should_not_invoke_the_block_if_a_watched_dir_changed_its_glob + i = 0 + checker = ActiveSupport::FileUpdateChecker.new([], "tmp_watcher" => :rb){ i += 1 } + FileUtils.cd "tmp_watcher" do + FileUtils.touch(FILES) + end + assert !checker.execute_if_updated + assert_equal 0, i end -end +end
\ No newline at end of file diff --git a/activesupport/test/flush_cache_on_private_memoization_test.rb b/activesupport/test/flush_cache_on_private_memoization_test.rb deleted file mode 100644 index 20768b777a..0000000000 --- a/activesupport/test/flush_cache_on_private_memoization_test.rb +++ /dev/null @@ -1,45 +0,0 @@ -require 'abstract_unit' -require 'test/unit' - -class FlashCacheOnPrivateMemoizationTest < Test::Unit::TestCase - ActiveSupport::Deprecation.silence do - extend ActiveSupport::Memoizable - end - - def test_public - assert_method_unmemoizable :pub - end - - def test_protected - assert_method_unmemoizable :prot - end - - def test_private - assert_method_unmemoizable :priv - end - - def pub; rand end - memoize :pub - - protected - - def prot; rand end - memoize :prot - - private - - def priv; rand end - memoize :priv - - def assert_method_unmemoizable(meth, message=nil) - full_message = build_message(message, "<?> not unmemoizable.\n", meth) - assert_block(full_message) do - a = send meth - b = send meth - unmemoize_all - c = send meth - a == b && a != c - end - end - -end diff --git a/activesupport/test/gzip_test.rb b/activesupport/test/gzip_test.rb index f564e63f29..626981dc9d 100644 --- a/activesupport/test/gzip_test.rb +++ b/activesupport/test/gzip_test.rb @@ -9,10 +9,7 @@ class GzipTest < Test::Unit::TestCase def test_compress_should_return_a_binary_string compressed = ActiveSupport::Gzip.compress('') - if "".encoding_aware? - assert_equal Encoding.find('binary'), compressed.encoding - end - + assert_equal Encoding.find('binary'), compressed.encoding assert !compressed.blank?, "a compressed blank string should not be blank" end end diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb index 5c956e0075..6b7e839e43 100644 --- a/activesupport/test/inflector_test.rb +++ b/activesupport/test/inflector_test.rb @@ -194,6 +194,20 @@ class InflectorTest < Test::Unit::TestCase def test_demodulize assert_equal "Account", ActiveSupport::Inflector.demodulize("MyApplication::Billing::Account") + assert_equal "Account", ActiveSupport::Inflector.demodulize("Account") + assert_equal "", ActiveSupport::Inflector.demodulize("") + end + + def test_deconstantize + assert_equal "MyApplication::Billing", ActiveSupport::Inflector.deconstantize("MyApplication::Billing::Account") + assert_equal "::MyApplication::Billing", ActiveSupport::Inflector.deconstantize("::MyApplication::Billing::Account") + + assert_equal "MyApplication", ActiveSupport::Inflector.deconstantize("MyApplication::Billing") + assert_equal "::MyApplication", ActiveSupport::Inflector.deconstantize("::MyApplication::Billing") + + assert_equal "", ActiveSupport::Inflector.deconstantize("Account") + assert_equal "", ActiveSupport::Inflector.deconstantize("::Account") + assert_equal "", ActiveSupport::Inflector.deconstantize("") end def test_foreign_key diff --git a/activesupport/test/inflector_test_cases.rb b/activesupport/test/inflector_test_cases.rb index 0cb1f70657..eb2915c286 100644 --- a/activesupport/test/inflector_test_cases.rb +++ b/activesupport/test/inflector_test_cases.rb @@ -14,6 +14,7 @@ module InflectorTestCases "fish" => "fish", "jeans" => "jeans", "funky jeans" => "funky jeans", + "my money" => "my money", "category" => "categories", "query" => "queries", @@ -103,7 +104,11 @@ module InflectorTestCases "edge" => "edges", "cow" => "kine", - "database" => "databases" + "database" => "databases", + + # regression tests against improper inflection regexes + "|ice" => "|ices", + "|ouse" => "|ouses" } CamelToUnderscore = { diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index 8cf1a54a99..a6435a763a 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -88,25 +88,21 @@ class TestJSONEncoding < Test::Unit::TestCase assert_equal %({\"a\":\"b\",\"c\":\"d\"}), sorted_json(ActiveSupport::JSON.encode(:a => :b, :c => :d)) end - def test_utf8_string_encoded_properly_when_kcode_is_utf8 - with_kcode 'UTF8' do - result = ActiveSupport::JSON.encode('€2.99') - assert_equal '"\\u20ac2.99"', result - assert_equal(Encoding::UTF_8, result.encoding) if result.respond_to?(:encoding) - - result = ActiveSupport::JSON.encode('✎☺') - assert_equal '"\\u270e\\u263a"', result - assert_equal(Encoding::UTF_8, result.encoding) if result.respond_to?(:encoding) - end + def test_utf8_string_encoded_properly + result = ActiveSupport::JSON.encode('€2.99') + assert_equal '"\\u20ac2.99"', result + assert_equal(Encoding::UTF_8, result.encoding) + + result = ActiveSupport::JSON.encode('✎☺') + assert_equal '"\\u270e\\u263a"', result + assert_equal(Encoding::UTF_8, result.encoding) end - if '1.9'.respond_to?(:force_encoding) - def test_non_utf8_string_transcodes - s = '二'.encode('Shift_JIS') - result = ActiveSupport::JSON.encode(s) - assert_equal '"\\u4e8c"', 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 Encoding::UTF_8, result.encoding end def test_exception_raised_when_encoding_circular_reference_in_array diff --git a/activesupport/test/memoizable_test.rb b/activesupport/test/memoizable_test.rb deleted file mode 100644 index e333b9a78c..0000000000 --- a/activesupport/test/memoizable_test.rb +++ /dev/null @@ -1,290 +0,0 @@ -require 'abstract_unit' - -class MemoizableTest < ActiveSupport::TestCase - class Person - ActiveSupport::Deprecation.silence do - extend ActiveSupport::Memoizable - end - - attr_reader :name_calls, :age_calls, :is_developer_calls, :name_query_calls - - def initialize - @name_calls = 0 - @age_calls = 0 - @is_developer_calls = 0 - @name_query_calls = 0 - end - - def name - @name_calls += 1 - "Josh" - end - - def name? - @name_query_calls += 1 - true - end - memoize :name? - - def update(name) - "Joshua" - end - memoize :update - - def age - @age_calls += 1 - nil - end - - memoize :name, :age - - protected - - def memoize_protected_test - 'protected' - end - memoize :memoize_protected_test - - private - - def is_developer? - @is_developer_calls += 1 - "Yes" - end - memoize :is_developer? - end - - class Company - attr_reader :name_calls - def initialize - @name_calls = 0 - end - - def name - @name_calls += 1 - "37signals" - end - end - - module Rates - ActiveSupport::Deprecation.silence do - extend ActiveSupport::Memoizable - end - - attr_reader :sales_tax_calls - def sales_tax(price) - @sales_tax_calls ||= 0 - @sales_tax_calls += 1 - price * 0.1025 - end - memoize :sales_tax - end - - class Calculator - ActiveSupport::Deprecation.silence do - extend ActiveSupport::Memoizable - end - include Rates - - attr_reader :fib_calls - def initialize - @fib_calls = 0 - end - - def fib(n) - @fib_calls += 1 - - if n == 0 || n == 1 - n - else - fib(n - 1) + fib(n - 2) - end - end - memoize :fib - - def add_or_subtract(i, j, add) - if add - i + j - else - i - j - end - end - memoize :add_or_subtract - - def counter - @count ||= 0 - @count += 1 - end - memoize :counter - end - - def setup - @person = Person.new - @calculator = Calculator.new - end - - def test_memoization - assert_equal "Josh", @person.name - assert_equal 1, @person.name_calls - - 3.times { assert_equal "Josh", @person.name } - assert_equal 1, @person.name_calls - end - - def test_memoization_with_punctuation - assert_equal true, @person.name? - - assert_nothing_raised(NameError) do - @person.memoize_all - @person.unmemoize_all - end - end - - def test_memoization_flush_with_punctuation - assert_equal true, @person.name? - @person.flush_cache(:name?) - 3.times { assert_equal true, @person.name? } - assert_equal 2, @person.name_query_calls - end - - def test_memoization_with_nil_value - assert_equal nil, @person.age - assert_equal 1, @person.age_calls - - 3.times { assert_equal nil, @person.age } - assert_equal 1, @person.age_calls - end - - def test_reloadable - assert_equal 1, @calculator.counter - assert_equal 2, @calculator.counter(:reload) - assert_equal 2, @calculator.counter - assert_equal 3, @calculator.counter(true) - assert_equal 3, @calculator.counter - end - - def test_flush_cache - assert_equal 1, @calculator.counter - - assert @calculator.instance_variable_get(:@_memoized_counter).any? - @calculator.flush_cache(:counter) - assert @calculator.instance_variable_get(:@_memoized_counter).empty? - - assert_equal 2, @calculator.counter - end - - def test_unmemoize_all - assert_equal 1, @calculator.counter - - assert @calculator.instance_variable_get(:@_memoized_counter).any? - @calculator.unmemoize_all - assert @calculator.instance_variable_get(:@_memoized_counter).empty? - - assert_equal 2, @calculator.counter - end - - def test_memoize_all - @calculator.memoize_all - assert @calculator.instance_variable_defined?(:@_memoized_counter) - end - - def test_memoization_cache_is_different_for_each_instance - assert_equal 1, @calculator.counter - assert_equal 2, @calculator.counter(:reload) - assert_equal 1, Calculator.new.counter - end - - def test_memoized_is_not_affected_by_freeze - @person.freeze - assert_equal "Josh", @person.name - assert_equal "Joshua", @person.update("Joshua") - end - - def test_memoization_with_args - assert_equal 55, @calculator.fib(10) - assert_equal 11, @calculator.fib_calls - end - - def test_reloadable_with_args - assert_equal 55, @calculator.fib(10) - assert_equal 11, @calculator.fib_calls - assert_equal 55, @calculator.fib(10, :reload) - assert_equal 12, @calculator.fib_calls - assert_equal 55, @calculator.fib(10, true) - assert_equal 13, @calculator.fib_calls - end - - def test_memoization_with_boolean_arg - assert_equal 4, @calculator.add_or_subtract(2, 2, true) - assert_equal 2, @calculator.add_or_subtract(4, 2, false) - end - - def test_object_memoization - [Company.new, Company.new, Company.new].each do |company| - ActiveSupport::Deprecation.silence do - company.extend ActiveSupport::Memoizable - end - company.memoize :name - - assert_equal "37signals", company.name - assert_equal 1, company.name_calls - assert_equal "37signals", company.name - assert_equal 1, company.name_calls - end - end - - def test_memoized_module_methods - assert_equal 1.025, @calculator.sales_tax(10) - assert_equal 1, @calculator.sales_tax_calls - assert_equal 1.025, @calculator.sales_tax(10) - assert_equal 1, @calculator.sales_tax_calls - assert_equal 2.5625, @calculator.sales_tax(25) - assert_equal 2, @calculator.sales_tax_calls - end - - def test_object_memoized_module_methods - company = Company.new - company.extend(Rates) - - assert_equal 1.025, company.sales_tax(10) - assert_equal 1, company.sales_tax_calls - assert_equal 1.025, company.sales_tax(10) - assert_equal 1, company.sales_tax_calls - assert_equal 2.5625, company.sales_tax(25) - assert_equal 2, company.sales_tax_calls - end - - def test_double_memoization - assert_raise(RuntimeError) { Person.memoize :name } - person = Person.new - ActiveSupport::Deprecation.silence do - person.extend ActiveSupport::Memoizable - end - assert_raise(RuntimeError) { person.memoize :name } - - company = Company.new - ActiveSupport::Deprecation.silence do - company.extend ActiveSupport::Memoizable - end - company.memoize :name - assert_raise(RuntimeError) { company.memoize :name } - end - - def test_protected_method_memoization - person = Person.new - - assert_raise(NoMethodError) { person.memoize_protected_test } - assert_equal "protected", person.send(:memoize_protected_test) - end - - def test_private_method_memoization - person = Person.new - - assert_raise(NoMethodError) { person.is_developer? } - assert_equal "Yes", person.send(:is_developer?) - assert_equal 1, person.is_developer_calls - assert_equal "Yes", person.send(:is_developer?) - assert_equal 1, person.is_developer_calls - end - -end diff --git a/activesupport/test/message_encryptor_test.rb b/activesupport/test/message_encryptor_test.rb index 83a19f8106..11142a358f 100644 --- a/activesupport/test/message_encryptor_test.rb +++ b/activesupport/test/message_encryptor_test.rb @@ -11,70 +11,75 @@ require 'active_support/time' require 'active_support/json' class MessageEncryptorTest < ActiveSupport::TestCase - class JSONSerializer def dump(value) ActiveSupport::JSON.encode(value) end - + def load(value) ActiveSupport::JSON.decode(value) end end - + def setup - @encryptor = ActiveSupport::MessageEncryptor.new(SecureRandom.hex(64)) + @secret = SecureRandom.hex(64) + @verifier = ActiveSupport::MessageVerifier.new(@secret, :serializer => ActiveSupport::MessageEncryptor::NullSerializer) + @encryptor = ActiveSupport::MessageEncryptor.new(@secret) @data = { :some => "data", :now => Time.local(2010) } end - def test_simple_round_tripping - message = @encryptor.encrypt(@data) - assert_equal @data, @encryptor.decrypt(message) - end - def test_encrypting_twice_yields_differing_cipher_text - first_messqage = @encryptor.encrypt(@data) - second_message = @encryptor.encrypt(@data) + first_messqage = @encryptor.encrypt_and_sign(@data).split("--").first + second_message = @encryptor.encrypt_and_sign(@data).split("--").first assert_not_equal first_messqage, second_message end - def test_messing_with_either_value_causes_failure - text, iv = @encryptor.encrypt(@data).split("--") + def test_messing_with_either_encrypted_values_causes_failure + text, iv = @verifier.verify(@encryptor.encrypt_and_sign(@data)).split("--") assert_not_decrypted([iv, text] * "--") assert_not_decrypted([text, munge(iv)] * "--") assert_not_decrypted([munge(text), iv] * "--") assert_not_decrypted([munge(text), munge(iv)] * "--") end + def test_messing_with_verified_values_causes_failures + text, iv = @encryptor.encrypt_and_sign(@data).split("--") + assert_not_verified([iv, text] * "--") + assert_not_verified([text, munge(iv)] * "--") + assert_not_verified([munge(text), iv] * "--") + assert_not_verified([munge(text), munge(iv)] * "--") + end + def test_signed_round_tripping message = @encryptor.encrypt_and_sign(@data) assert_equal @data, @encryptor.decrypt_and_verify(message) end - + def test_alternative_serialization_method encryptor = ActiveSupport::MessageEncryptor.new(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" } end - def test_digest_algorithm_as_second_parameter_deprecation - assert_deprecated(/options hash/) do - ActiveSupport::MessageEncryptor.new(SecureRandom.hex(64), 'aes-256-cbc') - end - end - private - def assert_not_decrypted(value) - assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do - @encryptor.decrypt(value) - end + + def assert_not_decrypted(value) + assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do + @encryptor.decrypt_and_verify(@verifier.generate(value)) end + end - def munge(base64_string) - bits = ActiveSupport::Base64.decode64(base64_string) - bits.reverse! - ActiveSupport::Base64.encode64s(bits) + def assert_not_verified(value) + assert_raise(ActiveSupport::MessageVerifier::InvalidSignature) do + @encryptor.decrypt_and_verify(value) end -end + end + def munge(base64_string) + bits = ActiveSupport::Base64.decode64(base64_string) + bits.reverse! + ActiveSupport::Base64.strict_encode64(bits) + end end + +end
\ No newline at end of file diff --git a/activesupport/test/message_verifier_test.rb b/activesupport/test/message_verifier_test.rb index 35747abe5b..5adff41653 100644 --- a/activesupport/test/message_verifier_test.rb +++ b/activesupport/test/message_verifier_test.rb @@ -50,12 +50,6 @@ class MessageVerifierTest < ActiveSupport::TestCase assert_equal verifier.verify(message), { "foo" => 123, "bar" => "2010-01-01T00:00:00Z" } end - def test_digest_algorithm_as_second_parameter_deprecation - assert_deprecated(/options hash/) do - ActiveSupport::MessageVerifier.new("secret", "SHA1") - end - end - def assert_not_verified(message) assert_raise(ActiveSupport::MessageVerifier::InvalidSignature) do @verifier.verify(message) diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index bfff10fff2..20e56e2c81 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -101,15 +101,8 @@ class MultibyteCharsUTF8BehaviourTest < Test::Unit::TestCase def setup @chars = UNICODE_STRING.dup.mb_chars - - if RUBY_VERSION < '1.9' - # Multibyte support all kinds of whitespace (ie. NEWLINE, SPACE, EM SPACE) - @whitespace = "\n\t#{[32, 8195].pack('U*')}" - else - # Ruby 1.9 only supports basic whitespace - @whitespace = "\n\t " - end - + # Ruby 1.9 only supports basic whitespace + @whitespace = "\n\t " @byte_order_mark = [65279].pack('U') end @@ -150,10 +143,8 @@ class MultibyteCharsUTF8BehaviourTest < Test::Unit::TestCase assert_not_equal original, proxy.to_s end - if RUBY_VERSION >= '1.9' - def test_unicode_string_should_have_utf8_encoding - assert_equal Encoding::UTF_8, UNICODE_STRING.encoding - end + def test_unicode_string_should_have_utf8_encoding + assert_equal Encoding::UTF_8, UNICODE_STRING.encoding end def test_identity diff --git a/activesupport/test/multibyte_test_helpers.rb b/activesupport/test/multibyte_test_helpers.rb index 8839b75601..fdbe2f4350 100644 --- a/activesupport/test/multibyte_test_helpers.rb +++ b/activesupport/test/multibyte_test_helpers.rb @@ -3,10 +3,7 @@ module MultibyteTestHelpers UNICODE_STRING = 'こにちわ' ASCII_STRING = 'ohayo' - BYTE_STRING = "\270\236\010\210\245" - if BYTE_STRING.respond_to?(:force_encoding) - BYTE_STRING.force_encoding("ASCII-8BIT") - end + BYTE_STRING = "\270\236\010\210\245".force_encoding("ASCII-8BIT") def chars(str) ActiveSupport::Multibyte::Chars.new(str) diff --git a/activesupport/test/multibyte_utils_test.rb b/activesupport/test/multibyte_utils_test.rb index 0a2f20d282..f807492be0 100644 --- a/activesupport/test/multibyte_utils_test.rb +++ b/activesupport/test/multibyte_utils_test.rb @@ -56,37 +56,9 @@ class MultibyteUtilsTest < ActiveSupport::TestCase end end - if RUBY_VERSION < '1.9' - test "clean leaves ASCII strings intact" do - with_encoding('None') do - [ - 'word', "\270\236\010\210\245" - ].each do |string| - assert_equal string, ActiveSupport::Multibyte.clean(string) - end - end - end - - test "clean cleans invalid characters from UTF-8 encoded strings" do - with_encoding('UTF8') do - cleaned_utf8 = [8].pack('C*') - assert_equal example('valid UTF-8'), ActiveSupport::Multibyte.clean(example('valid UTF-8')) - assert_equal cleaned_utf8, ActiveSupport::Multibyte.clean(example('invalid UTF-8')) - end - end - - test "clean cleans invalid characters from Shift-JIS encoded strings" do - with_encoding('SJIS') do - cleaned_sjis = [184, 0, 136, 165].pack('C*') - assert_equal example('valid Shift-JIS'), ActiveSupport::Multibyte.clean(example('valid Shift-JIS')) - assert_equal cleaned_sjis, ActiveSupport::Multibyte.clean(example('invalid Shift-JIS')) - end - end - else - test "clean is a no-op" do - with_encoding('UTF8') do - assert_equal example('invalid Shift-JIS'), ActiveSupport::Multibyte.clean(example('invalid Shift-JIS')) - end + test "clean is a no-op" do + with_encoding('UTF8') do + assert_equal example('invalid Shift-JIS'), ActiveSupport::Multibyte.clean(example('invalid Shift-JIS')) end end @@ -101,37 +73,21 @@ class MultibyteUtilsTest < ActiveSupport::TestCase 'invalid Shift-JIS' => [184, 158, 8, 0, 255, 136, 165].pack('C*') } - if Kernel.const_defined?(:Encoding) - def example(key) - STRINGS[key].force_encoding(Encoding.default_external) - end - - def examples - STRINGS.values.map { |s| s.force_encoding(Encoding.default_external) } - end - else - def example(key) - STRINGS[key] - end - - def examples - STRINGS.values - end + def example(key) + STRINGS[key].force_encoding(Encoding.default_external) end - if 'string'.respond_to?(:encoding) - KCODE_TO_ENCODING = Hash.new(Encoding::BINARY). - update('UTF8' => Encoding::UTF_8, 'SJIS' => Encoding::Shift_JIS) - - def with_encoding(enc) - before = Encoding.default_external - silence_warnings { Encoding.default_external = KCODE_TO_ENCODING[enc] } + def examples + STRINGS.values.map { |s| s.force_encoding(Encoding.default_external) } + end - yield + KCODE_TO_ENCODING = Hash.new(Encoding::BINARY). + update('UTF8' => Encoding::UTF_8, 'SJIS' => Encoding::Shift_JIS) - silence_warnings { Encoding.default_external = before } - end - else - alias with_encoding with_kcode + def with_encoding(enc) + before = Encoding.default_external + silence_warnings { Encoding.default_external = KCODE_TO_ENCODING[enc] } + yield + silence_warnings { Encoding.default_external = before } end end diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb index 884ee61547..fc9fa90d07 100644 --- a/activesupport/test/notifications_test.rb +++ b/activesupport/test/notifications_test.rb @@ -24,6 +24,26 @@ module Notifications end end + class SubscribedTest < TestCase + def test_subscribed + name = "foo" + name2 = name * 2 + expected = [name, name] + + events = [] + callback = lambda {|*_| events << _.first} + ActiveSupport::Notifications.subscribed(callback, name) do + ActiveSupport::Notifications.instrument(name) + ActiveSupport::Notifications.instrument(name2) + ActiveSupport::Notifications.instrument(name) + end + assert_equal expected, events + + ActiveSupport::Notifications.instrument(name) + assert_equal expected, events + end + end + class UnsubscribeTest < TestCase def test_unsubscribing_removes_a_subscription @notifier.publish :foo diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index 0b5f912dc4..8119b36491 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -81,24 +81,21 @@ class OrderedHashTest < Test::Unit::TestCase keys = [] assert_equal @ordered_hash, @ordered_hash.each_key { |k| keys << k } assert_equal @keys, keys - expected_class = RUBY_VERSION < '1.9' ? Enumerable::Enumerator : Enumerator - assert_kind_of expected_class, @ordered_hash.each_key + assert_kind_of Enumerator, @ordered_hash.each_key end def test_each_value values = [] assert_equal @ordered_hash, @ordered_hash.each_value { |v| values << v } assert_equal @values, values - expected_class = RUBY_VERSION < '1.9' ? Enumerable::Enumerator : Enumerator - assert_kind_of expected_class, @ordered_hash.each_value + assert_kind_of Enumerator, @ordered_hash.each_value end def test_each values = [] assert_equal @ordered_hash, @ordered_hash.each {|key, value| values << value} assert_equal @values, values - expected_class = RUBY_VERSION < '1.9' ? Enumerable::Enumerator : Enumerator - assert_kind_of expected_class, @ordered_hash.each + assert_kind_of Enumerator, @ordered_hash.each end def test_each_with_index @@ -114,9 +111,7 @@ class OrderedHashTest < Test::Unit::TestCase end assert_equal @values, values assert_equal @keys, keys - - expected_class = RUBY_VERSION < '1.9' ? Enumerable::Enumerator : Enumerator - assert_kind_of expected_class, @ordered_hash.each_pair + assert_kind_of Enumerator, @ordered_hash.each_pair end def test_find_all diff --git a/activesupport/test/tagged_logging_test.rb b/activesupport/test/tagged_logging_test.rb new file mode 100644 index 0000000000..dd4ae319e5 --- /dev/null +++ b/activesupport/test/tagged_logging_test.rb @@ -0,0 +1,67 @@ +require 'abstract_unit' +require 'active_support/logger' +require 'active_support/tagged_logging' + +class TaggedLoggingTest < ActiveSupport::TestCase + class MyLogger < ::ActiveSupport::Logger + def flush(*) + info "[FLUSHED]" + end + end + + setup do + @output = StringIO.new + @logger = ActiveSupport::TaggedLogging.new(MyLogger.new(@output)) + end + + test "tagged once" do + @logger.tagged("BCX") { @logger.info "Funky time" } + assert_equal "[BCX] Funky time\n", @output.string + end + + test "tagged twice" do + @logger.tagged("BCX") { @logger.tagged("Jason") { @logger.info "Funky time" } } + assert_equal "[BCX] [Jason] Funky time\n", @output.string + end + + test "tagged thrice at once" do + @logger.tagged("BCX", "Jason", "New") { @logger.info "Funky time" } + assert_equal "[BCX] [Jason] [New] Funky time\n", @output.string + end + + test "tagged once with blank and nil" do + @logger.tagged(nil, "", "New") { @logger.info "Funky time" } + assert_equal "[New] Funky time\n", @output.string + end + + test "keeps each tag in their own thread" do + @logger.tagged("BCX") do + Thread.new do + @logger.tagged("OMG") { @logger.info "Cool story bro" } + end.join + @logger.info "Funky time" + end + assert_equal "[OMG] Cool story bro\n[BCX] Funky time\n", @output.string + end + + test "cleans up the taggings on flush" do + @logger.tagged("BCX") do + Thread.new do + @logger.tagged("OMG") do + @logger.flush + @logger.info "Cool story bro" + end + end.join + end + assert_equal "[FLUSHED]\nCool story bro\n", @output.string + end + + test "mixed levels of tagging" do + @logger.tagged("BCX") do + @logger.tagged("Jason") { @logger.info "Funky time" } + @logger.info "Junky time!" + end + + assert_equal "[BCX] [Jason] Funky time\n[BCX] Junky time!\n", @output.string + end +end diff --git a/activesupport/test/whiny_nil_test.rb b/activesupport/test/whiny_nil_test.rb deleted file mode 100644 index 1acaf7228f..0000000000 --- a/activesupport/test/whiny_nil_test.rb +++ /dev/null @@ -1,54 +0,0 @@ -# Stub to enable testing without Active Record -module ActiveRecord - class Base - def save! - end - end -end - -require 'abstract_unit' -require 'active_support/whiny_nil' - -NilClass.add_whiner ::ActiveRecord::Base - -class WhinyNilTest < Test::Unit::TestCase - def test_unchanged - nil.method_thats_not_in_whiners - rescue NoMethodError => nme - assert_match(/nil:NilClass/, nme.message) - end - - def test_active_record - nil.save! - rescue NoMethodError => nme - assert_no_match(/nil:NilClass/, nme.message) - assert_match(/nil\.save!/, nme.message) - end - - def test_array - nil.each - rescue NoMethodError => nme - assert_no_match(/nil:NilClass/, nme.message) - assert_match(/nil\.each/, nme.message) - end - - def test_id - nil.id - rescue RuntimeError => nme - assert_no_match(/nil:NilClass/, nme.message) - assert_match(Regexp.new(nil.object_id.to_s), nme.message) - end - - def test_no_to_ary_coercion - nil.to_ary - rescue NoMethodError => nme - assert_no_match(/nil:NilClass/, nme.message) - assert_match(/nil\.to_ary/, nme.message) - end - - def test_no_to_str_coercion - nil.to_str - rescue NoMethodError => nme - assert_match(/nil:NilClass/, nme.message) - end -end |