repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/resource/templates/functional_test.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/resource/templates/functional_test.rb
require 'test_helper' class <%= controller_class_name %>ControllerTest < ActionController::TestCase # Replace this with your real tests. test "the truth" do assert true end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/resource/templates/helper_test.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/resource/templates/helper_test.rb
require 'test_helper' class <%= controller_class_name %>HelperTest < ActionView::TestCase end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/resource/templates/controller.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/resource/templates/controller.rb
class <%= controller_class_name %>Controller < ApplicationController end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/resource/templates/helper.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/resource/templates/helper.rb
module <%= controller_class_name %>Helper end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/model/model_generator.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/model/model_generator.rb
class ModelGenerator < Rails::Generator::NamedBase default_options :skip_timestamps => false, :skip_migration => false, :skip_fixture => false def manifest record do |m| # Check for class naming collisions. m.class_collisions class_name, "#{class_name}Test" # Model, test, and fixture directories. m.directory File.join('app/models', class_path) m.directory File.join('test/unit', class_path) m.directory File.join('test/fixtures', class_path) # Model class, unit test, and fixtures. m.template 'model.rb', File.join('app/models', class_path, "#{file_name}.rb") m.template 'unit_test.rb', File.join('test/unit', class_path, "#{file_name}_test.rb") unless options[:skip_fixture] m.template 'fixtures.yml', File.join('test/fixtures', "#{table_name}.yml") end migration_file_path = file_path.gsub(/\//, '_') migration_name = class_name if ActiveRecord::Base.pluralize_table_names migration_name = migration_name.pluralize migration_file_path = migration_file_path.pluralize end unless options[:skip_migration] m.migration_template 'migration.rb', 'db/migrate', :assigns => { :migration_name => "Create#{migration_name.gsub(/::/, '')}" }, :migration_file_name => "create_#{migration_file_path}" end end end protected def banner "Usage: #{$0} #{spec.name} ModelName [field:type, field:type]" end def add_options!(opt) opt.separator '' opt.separator 'Options:' opt.on("--skip-timestamps", "Don't add timestamps to the migration file for this model") { |v| options[:skip_timestamps] = v } opt.on("--skip-migration", "Don't generate a migration file for this model") { |v| options[:skip_migration] = v } opt.on("--skip-fixture", "Don't generation a fixture file for this model") { |v| options[:skip_fixture] = v} end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/model/templates/unit_test.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/model/templates/unit_test.rb
require 'test_helper' class <%= class_name %>Test < ActiveSupport::TestCase # Replace this with your real tests. test "the truth" do assert true end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/model/templates/migration.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/model/templates/migration.rb
class <%= migration_name %> < ActiveRecord::Migration def self.up create_table :<%= table_name %> do |t| <% for attribute in attributes -%> t.<%= attribute.type %> :<%= attribute.name %> <% end -%> <% unless options[:skip_timestamps] %> t.timestamps <% end -%> end end def self.down drop_table :<%= table_name %> end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/model/templates/model.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/model/templates/model.rb
class <%= class_name %> < ActiveRecord::Base <% attributes.select(&:reference?).each do |attribute| -%> belongs_to :<%= attribute.name %> <% end -%> end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/observer/observer_generator.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/observer/observer_generator.rb
class ObserverGenerator < Rails::Generator::NamedBase def manifest record do |m| # Check for class naming collisions. m.class_collisions "#{class_name}Observer", "#{class_name}ObserverTest" # Observer, and test directories. m.directory File.join('app/models', class_path) m.directory File.join('test/unit', class_path) # Observer class and unit test fixtures. m.template 'observer.rb', File.join('app/models', class_path, "#{file_name}_observer.rb") m.template 'unit_test.rb', File.join('test/unit', class_path, "#{file_name}_observer_test.rb") end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/observer/templates/unit_test.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/observer/templates/unit_test.rb
require 'test_helper' class <%= class_name %>ObserverTest < ActiveSupport::TestCase # Replace this with your real tests. test "the truth" do assert true end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/observer/templates/observer.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/observer/templates/observer.rb
class <%= class_name %>Observer < ActiveRecord::Observer end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/integration_test/integration_test_generator.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/integration_test/integration_test_generator.rb
class IntegrationTestGenerator < Rails::Generator::NamedBase default_options :skip_migration => false def manifest record do |m| # Check for class naming collisions. m.class_collisions class_name, "#{class_name}Test" # integration test directory m.directory File.join('test/integration', class_path) # integration test stub m.template 'integration_test.rb', File.join('test/integration', class_path, "#{file_name}_test.rb") end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/integration_test/templates/integration_test.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/integration_test/templates/integration_test.rb
require 'test_helper' class <%= class_name %>Test < ActionController::IntegrationTest fixtures :all # Replace this with your real tests. test "the truth" do assert true end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/performance_test/performance_test_generator.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/performance_test/performance_test_generator.rb
class PerformanceTestGenerator < Rails::Generator::NamedBase default_options :skip_migration => false def manifest record do |m| # Check for class naming collisions. m.class_collisions class_name, "#{class_name}Test" # performance test directory m.directory File.join('test/performance', class_path) # performance test stub m.template 'performance_test.rb', File.join('test/performance', class_path, "#{file_name}_test.rb") end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/performance_test/templates/performance_test.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/performance_test/templates/performance_test.rb
require 'test_helper' require 'performance_test_help' class <%= class_name %>Test < ActionController::PerformanceTest # Replace this with your real tests. def test_homepage get '/' end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/helper/helper_generator.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/helper/helper_generator.rb
class HelperGenerator < Rails::Generator::NamedBase def manifest record do |m| # Check for class naming collisions. m.class_collisions class_path, "#{class_name}Helper", "#{class_name}HelperTest" # Helper and helper test directories. m.directory File.join('app/helpers', class_path) m.directory File.join('test/unit/helpers', class_path) # Helper and helper test class. m.template 'helper.rb', File.join('app/helpers', class_path, "#{file_name}_helper.rb") m.template 'helper_test.rb', File.join('test/unit/helpers', class_path, "#{file_name}_helper_test.rb") end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/helper/templates/helper_test.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/helper/templates/helper_test.rb
require 'test_helper' class <%= class_name %>HelperTest < ActionView::TestCase end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/helper/templates/helper.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/helper/templates/helper.rb
module <%= class_name %>Helper end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/metal/metal_generator.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/metal/metal_generator.rb
class MetalGenerator < Rails::Generator::NamedBase def manifest record do |m| m.directory 'app/metal' m.template 'metal.rb', File.join('app/metal', "#{file_name}.rb") end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/metal/templates/metal.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/metal/templates/metal.rb
# Allow the metal piece to run in isolation require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails) class <%= class_name %> def self.call(env) if env["PATH_INFO"] =~ /^\/<%= file_name %>/ [200, {"Content-Type" => "text/html"}, ["Hello, World!"]] else [404, {"Content-Type" => "text/html"}, ["Not Found"]] end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/migration/migration_generator.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/migration/migration_generator.rb
class MigrationGenerator < Rails::Generator::NamedBase def manifest record do |m| m.migration_template 'migration.rb', 'db/migrate', :assigns => get_local_assigns end end private def get_local_assigns returning(assigns = {}) do if class_name.underscore =~ /^(add|remove)_.*_(?:to|from)_(.*)/ assigns[:migration_action] = $1 assigns[:table_name] = $2.pluralize else assigns[:attributes] = [] end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/migration/templates/migration.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/migration/templates/migration.rb
class <%= class_name.underscore.camelize %> < ActiveRecord::Migration def self.up<% attributes.each do |attribute| %> <%= migration_action %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'add' %>, :<%= attribute.type %><% end -%> <%- end %> end def self.down<% attributes.reverse.each do |attribute| %> <%= migration_action == 'add' ? 'remove' : 'add' %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'remove' %>, :<%= attribute.type %><% end -%> <%- end %> end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/session_migration/session_migration_generator.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/session_migration/session_migration_generator.rb
class SessionMigrationGenerator < Rails::Generator::NamedBase def initialize(runtime_args, runtime_options = {}) runtime_args << 'add_session_table' if runtime_args.empty? super end def manifest record do |m| m.migration_template 'migration.rb', 'db/migrate', :assigns => { :session_table_name => default_session_table_name } end end protected def default_session_table_name ActiveRecord::Base.pluralize_table_names ? 'session'.pluralize : 'session' end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/session_migration/templates/migration.rb
provider/vendor/rails/railties/lib/rails_generator/generators/components/session_migration/templates/migration.rb
class <%= class_name %> < ActiveRecord::Migration def self.up create_table :<%= session_table_name %> do |t| t.string :session_id, :null => false t.text :data t.timestamps end add_index :<%= session_table_name %>, :session_id add_index :<%= session_table_name %>, :updated_at end def self.down drop_table :<%= session_table_name %> end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/applications/app/app_generator.rb
provider/vendor/rails/railties/lib/rails_generator/generators/applications/app/app_generator.rb
require 'rbconfig' require File.dirname(__FILE__) + '/template_runner' require 'digest/md5' require 'active_support/secure_random' class AppGenerator < Rails::Generator::Base DEFAULT_SHEBANG = File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name']) DATABASES = %w( mysql oracle postgresql sqlite2 sqlite3 frontbase ibm_db ) DEFAULT_DATABASE = 'sqlite3' mandatory_options :source => "#{File.dirname(__FILE__)}/../../../../.." default_options :db => (ENV["RAILS_DEFAULT_DATABASE"] || DEFAULT_DATABASE), :shebang => DEFAULT_SHEBANG, :with_dispatchers => false, :freeze => false def initialize(runtime_args, runtime_options = {}) super usage if args.empty? usage("Databases supported for preconfiguration are: #{DATABASES.join(", ")}") if (options[:db] && !DATABASES.include?(options[:db])) @destination_root = args.shift @app_name = File.basename(File.expand_path(@destination_root)) end def manifest record do |m| create_directories(m) create_root_files(m) create_app_files(m) create_config_files(m) create_script_files(m) create_test_files(m) create_public_files(m) create_documentation_file(m) create_log_files(m) end end def after_generate if options[:template] Rails::TemplateRunner.new(options[:template], @destination_root) end end protected def banner "Usage: #{$0} /path/to/your/app [options]" end def add_options!(opt) opt.separator '' opt.separator 'Options:' opt.on("-r", "--ruby=path", String, "Path to the Ruby binary of your choice (otherwise scripts use env, dispatchers current path).", "Default: #{DEFAULT_SHEBANG}") { |v| options[:shebang] = v } opt.on("-d", "--database=name", String, "Preconfigure for selected database (options: #{DATABASES.join('/')}).", "Default: #{DEFAULT_DATABASE}") { |v| options[:db] = v } opt.on("-D", "--with-dispatchers", "Add CGI/FastCGI/mod_ruby dispatches code to generated application skeleton", "Default: false") { |v| options[:with_dispatchers] = v } opt.on("-f", "--freeze", "Freeze Rails in vendor/rails from the gems generating the skeleton", "Default: false") { |v| options[:freeze] = v } opt.on("-m", "--template=path", String, "Use an application template that lives at path (can be a filesystem path or URL).", "Default: (none)") { |v| options[:template] = v } end private def create_directories(m) m.directory '' # Intermediate directories are automatically created so don't sweat their absence here. %w( app/controllers app/helpers app/models app/views/layouts config/environments config/initializers config/locales db doc lib lib/tasks log public/images public/javascripts public/stylesheets script/performance test/fixtures test/functional test/integration test/performance test/unit vendor vendor/plugins tmp/sessions tmp/sockets tmp/cache tmp/pids ).each { |path| m.directory(path) } end def create_root_files(m) m.file "fresh_rakefile", "Rakefile" m.file "README", "README" end def create_app_files(m) m.file "helpers/application_controller.rb", "app/controllers/application_controller.rb" m.file "helpers/application_helper.rb", "app/helpers/application_helper.rb" end def create_config_files(m) create_database_configuration_file(m) create_routes_file(m) create_locale_file(m) create_seeds_file(m) create_initializer_files(m) create_environment_files(m) end def create_documentation_file(m) m.file "doc/README_FOR_APP", "doc/README_FOR_APP" end def create_log_files(m) %w( server production development test ).each do |file| m.file "configs/empty.log", "log/#{file}.log", :chmod => 0666 end end def create_public_files(m) create_dispatch_files(m) create_error_files(m) create_welcome_file(m) create_browser_convention_files(m) create_rails_image(m) create_javascript_files(m) end def create_script_files(m) %w( about console dbconsole destroy generate runner server plugin performance/benchmarker performance/profiler ).each do |file| m.file "bin/#{file}", "script/#{file}", { :chmod => 0755, :shebang => options[:shebang] == DEFAULT_SHEBANG ? nil : options[:shebang] } end end def create_test_files(m) m.file "helpers/test_helper.rb", "test/test_helper.rb" m.file "helpers/performance_test.rb", "test/performance/browsing_test.rb" end def create_database_configuration_file(m) m.template "configs/databases/#{options[:db]}.yml", "config/database.yml", :assigns => { :app_name => @app_name, :socket => options[:db] == "mysql" ? mysql_socket_location : nil } end def create_routes_file(m) m.file "configs/routes.rb", "config/routes.rb" end def create_seeds_file(m) m.file "configs/seeds.rb", "db/seeds.rb" end def create_initializer_files(m) %w( backtrace_silencers inflections mime_types new_rails_defaults ).each do |initializer| m.file "configs/initializers/#{initializer}.rb", "config/initializers/#{initializer}.rb" end m.template "configs/initializers/session_store.rb", "config/initializers/session_store.rb", :assigns => { :app_name => @app_name, :app_secret => ActiveSupport::SecureRandom.hex(64) } end def create_locale_file(m) m.file "configs/locales/en.yml", "config/locales/en.yml" end def create_environment_files(m) m.template "environments/environment.rb", "config/environment.rb", :assigns => { :freeze => options[:freeze] } m.file "environments/boot.rb", "config/boot.rb" m.file "environments/production.rb", "config/environments/production.rb" m.file "environments/development.rb", "config/environments/development.rb" m.file "environments/test.rb", "config/environments/test.rb" end def create_dispatch_files(m) if options[:with_dispatchers] dispatcher_options = { :chmod => 0755, :shebang => options[:shebang] } m.file "dispatches/config.ru", "config.ru" m.file "dispatches/dispatch.rb", "public/dispatch.rb", dispatcher_options m.file "dispatches/dispatch.rb", "public/dispatch.cgi", dispatcher_options m.file "dispatches/dispatch.fcgi", "public/dispatch.fcgi", dispatcher_options end end def create_error_files(m) %w( 404 422 500 ).each do |file| m.file "html/#{file}.html", "public/#{file}.html" end end def create_welcome_file(m) m.file 'html/index.html', 'public/index.html' end def create_browser_convention_files(m) m.file "html/favicon.ico", "public/favicon.ico" m.file "html/robots.txt", "public/robots.txt" end def create_rails_image(m) m.file "html/images/rails.png", "public/images/rails.png" end def create_javascript_files(m) %w( prototype effects dragdrop controls application ).each do |javascript| m.file "html/javascripts/#{javascript}.js", "public/javascripts/#{javascript}.js" end end def mysql_socket_location [ "/tmp/mysql.sock", # default "/var/run/mysqld/mysqld.sock", # debian/gentoo "/var/tmp/mysql.sock", # freebsd "/var/lib/mysql/mysql.sock", # fedora "/opt/local/lib/mysql/mysql.sock", # fedora "/opt/local/var/run/mysqld/mysqld.sock", # mac + darwinports + mysql "/opt/local/var/run/mysql4/mysqld.sock", # mac + darwinports + mysql4 "/opt/local/var/run/mysql5/mysqld.sock", # mac + darwinports + mysql5 "/opt/lampp/var/mysql/mysql.sock" # xampp for linux ].find { |f| File.exist?(f) } unless RUBY_PLATFORM =~ /(:?mswin|mingw)/ end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/applications/app/template_runner.rb
provider/vendor/rails/railties/lib/rails_generator/generators/applications/app/template_runner.rb
require File.dirname(__FILE__) + '/scm/scm' require File.dirname(__FILE__) + '/scm/git' require File.dirname(__FILE__) + '/scm/svn' require 'open-uri' require 'fileutils' module Rails class TemplateRunner attr_reader :root attr_writer :logger def initialize(template, root = '') # :nodoc: @root = File.expand_path(File.directory?(root) ? root : File.join(Dir.pwd, root)) log 'applying', "template: #{template}" load_template(template) log 'applied', "#{template}" end def load_template(template) begin code = open(template).read in_root { self.instance_eval(code) } rescue LoadError, Errno::ENOENT => e raise "The template [#{template}] could not be loaded. Error: #{e}" end end # Create a new file in the Rails project folder. Specify the # relative path from RAILS_ROOT. Data is the return value of a block # or a data string. # # ==== Examples # # file("lib/fun_party.rb") do # hostname = ask("What is the virtual hostname I should use?") # "vhost.name = #{hostname}" # end # # file("config/apach.conf", "your apache config") # def file(filename, data = nil, log_action = true, &block) log 'file', filename if log_action dir, file = [File.dirname(filename), File.basename(filename)] inside(dir) do File.open(file, "w") do |f| if block_given? f.write(block.call) else f.write(data) end end end end # Install a plugin. You must provide either a Subversion url or Git url. # For a Git-hosted plugin, you can specify if it should be added as a submodule instead of cloned. # # ==== Examples # # plugin 'restful-authentication', :git => 'git://github.com/technoweenie/restful-authentication.git' # plugin 'restful-authentication', :git => 'git://github.com/technoweenie/restful-authentication.git', :submodule => true # plugin 'restful-authentication', :svn => 'svn://svnhub.com/technoweenie/restful-authentication/trunk' # def plugin(name, options) log 'plugin', name if options[:git] && options[:submodule] in_root do Git.run("submodule add #{options[:git]} vendor/plugins/#{name}") end elsif options[:git] || options[:svn] in_root do run_ruby_script("script/plugin install #{options[:svn] || options[:git]}", false) end else log "! no git or svn provided for #{name}. skipping..." end end # Adds an entry into config/environment.rb for the supplied gem : def gem(name, options = {}) log 'gem', name env = options.delete(:env) gems_code = "config.gem '#{name}'" if options.any? opts = options.inject([]) {|result, h| result << [":#{h[0]} => #{h[1].inspect.gsub('"',"'")}"] }.sort.join(", ") gems_code << ", #{opts}" end environment gems_code, :env => env end # Adds a line inside the Initializer block for config/environment.rb. Used by #gem # If options :env is specified, the line is appended to the corresponding # file in config/environments/#{env}.rb def environment(data = nil, options = {}, &block) sentinel = 'Rails::Initializer.run do |config|' data = block.call if !data && block_given? in_root do if options[:env].nil? gsub_file 'config/environment.rb', /(#{Regexp.escape(sentinel)})/mi do |match| "#{match}\n " << data end else Array.wrap(options[:env]).each do|env| append_file "config/environments/#{env}.rb", "\n#{data}" end end end end # Run a command in git. # # ==== Examples # # git :init # git :add => "this.file that.rb" # git :add => "onefile.rb", :rm => "badfile.cxx" # def git(command = {}) in_root do if command.is_a?(Symbol) log 'running', "git #{command}" Git.run(command.to_s) else command.each do |command, options| log 'running', "git #{command} #{options}" Git.run("#{command} #{options}") end end end end # Create a new file in the vendor/ directory. Code can be specified # in a block or a data string can be given. # # ==== Examples # # vendor("sekrit.rb") do # sekrit_salt = "#{Time.now}--#{3.years.ago}--#{rand}--" # "salt = '#{sekrit_salt}'" # end # # vendor("foreign.rb", "# Foreign code is fun") # def vendor(filename, data = nil, &block) log 'vendoring', filename file("vendor/#{filename}", data, false, &block) end # Create a new file in the lib/ directory. Code can be specified # in a block or a data string can be given. # # ==== Examples # # lib("crypto.rb") do # "crypted_special_value = '#{rand}--#{Time.now}--#{rand(1337)}--'" # end # # lib("foreign.rb", "# Foreign code is fun") # def lib(filename, data = nil, &block) log 'lib', filename file("lib/#{filename}", data, false, &block) end # Create a new Rakefile with the provided code (either in a block or a string). # # ==== Examples # # rakefile("bootstrap.rake") do # project = ask("What is the UNIX name of your project?") # # <<-TASK # namespace :#{project} do # task :bootstrap do # puts "i like boots!" # end # end # TASK # end # # rakefile("seed.rake", "puts 'im plantin ur seedz'") # def rakefile(filename, data = nil, &block) log 'rakefile', filename file("lib/tasks/#{filename}", data, false, &block) end # Create a new initializer with the provided code (either in a block or a string). # # ==== Examples # # initializer("globals.rb") do # data = "" # # ['MY_WORK', 'ADMINS', 'BEST_COMPANY_EVAR'].each do # data << "#{const} = :entp" # end # # data # end # # initializer("api.rb", "API_KEY = '123456'") # def initializer(filename, data = nil, &block) log 'initializer', filename file("config/initializers/#{filename}", data, false, &block) end # Generate something using a generator from Rails or a plugin. # The second parameter is the argument string that is passed to # the generator or an Array that is joined. # # ==== Example # # generate(:authenticated, "user session") # def generate(what, *args) log 'generating', what argument = args.map(&:to_s).flatten.join(" ") in_root { run_ruby_script("script/generate #{what} #{argument}", false) } end # Executes a command # # ==== Example # # inside('vendor') do # run('ln -s ~/edge rails') # end # def run(command, log_action = true) log 'executing', "#{command} from #{Dir.pwd}" if log_action `#{command}` end # Executes a ruby script (taking into account WIN32 platform quirks) def run_ruby_script(command, log_action = true) ruby_command = RUBY_PLATFORM=~ /win32/ ? 'ruby ' : '' run("#{ruby_command}#{command}", log_action) end # Runs the supplied rake task # # ==== Example # # rake("db:migrate") # rake("db:migrate", :env => "production") # rake("gems:install", :sudo => true) # def rake(command, options = {}) log 'rake', command env = options[:env] || 'development' sudo = options[:sudo] ? 'sudo ' : '' in_root { run("#{sudo}rake #{command} RAILS_ENV=#{env}", false) } end # Just run the capify command in root # # ==== Example # # capify! # def capify! log 'capifying' in_root { run('capify .', false) } end # Add Rails to /vendor/rails # # ==== Example # # freeze! # def freeze!(args = {}) log 'vendor', 'rails edge' in_root { run('rake rails:freeze:edge', false) } end # Make an entry in Rails routing file conifg/routes.rb # # === Example # # route "map.root :controller => :welcome" # def route(routing_code) log 'route', routing_code sentinel = 'ActionController::Routing::Routes.draw do |map|' in_root do gsub_file 'config/routes.rb', /(#{Regexp.escape(sentinel)})/mi do |match| "#{match}\n #{routing_code}\n" end end end protected # Get a user's input # # ==== Example # # answer = ask("Should I freeze the latest Rails?") # freeze! if ask("Should I freeze the latest Rails?") == "yes" # def ask(string) log '', string STDIN.gets.strip end # Do something in the root of the Rails application or # a provided subfolder; the full path is yielded to the block you provide. # The path is set back to the previous path when the method exits. def inside(dir = '', &block) folder = File.join(root, dir) FileUtils.mkdir_p(folder) unless File.exist?(folder) FileUtils.cd(folder) { block.arity == 1 ? yield(folder) : yield } end def in_root FileUtils.cd(root) { yield } end # Helper to test if the user says yes(y)? # # ==== Example # # freeze! if yes?("Should I freeze the latest Rails?") # def yes?(question) answer = ask(question).downcase answer == "y" || answer == "yes" end # Helper to test if the user does NOT say yes(y)? # # ==== Example # # capify! if no?("Will you be using vlad to deploy your application?") # def no?(question) !yes?(question) end # Run a regular expression replacement on a file # # ==== Example # # gsub_file 'app/controllers/application_controller.rb', /#\s*(filter_parameter_logging :password)/, '\1' # def gsub_file(relative_destination, regexp, *args, &block) path = destination_path(relative_destination) content = File.read(path).gsub(regexp, *args, &block) File.open(path, 'wb') { |file| file.write(content) } end # Append text to a file # # ==== Example # # append_file 'config/environments/test.rb', 'config.gem "rspec"' # def append_file(relative_destination, data) path = destination_path(relative_destination) File.open(path, 'ab') { |file| file.write(data) } end def destination_path(relative_destination) File.join(root, relative_destination) end def log(action, message = '') logger.log(action, message) end def logger @logger ||= Rails::Generator::Base.logger end def logger @logger ||= if defined?(Rails::Generator::Base) Rails::Generator::Base.logger else require 'rails_generator/simple_logger' Rails::Generator::SimpleLogger.new(STDOUT) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/applications/app/scm/scm.rb
provider/vendor/rails/railties/lib/rails_generator/generators/applications/app/scm/scm.rb
module Rails class Scm private def self.hash_to_parameters(hash) hash.collect { |key, value| "--#{key} #{(value.kind_of?(String) ? value : "")}"}.join(" ") end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/applications/app/scm/svn.rb
provider/vendor/rails/railties/lib/rails_generator/generators/applications/app/scm/svn.rb
module Rails class Svn < Scm def self.checkout(repos, branch = nil) `svn checkout #{repos}/#{branch || "trunk"}` end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/applications/app/scm/git.rb
provider/vendor/rails/railties/lib/rails_generator/generators/applications/app/scm/git.rb
STDOUT.sync = true module Rails class Git < Scm def self.clone(repos, branch=nil) system "git clone #{repos}" if branch system "cd #{repos.split('/').last}/" system "git checkout #{branch}" end end def self.run(command) system "git #{command}" end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/configs/seeds.rb
provider/vendor/rails/railties/configs/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }]) # Major.create(:name => 'Daley', :city => cities.first)
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/configs/routes.rb
provider/vendor/rails/railties/configs/routes.rb
ActionController::Routing::Routes.draw do |map| # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. # map.root :controller => "welcome" # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/configs/initializers/session_store.rb
provider/vendor/rails/railties/configs/initializers/session_store.rb
# Be sure to restart your server when you modify this file. # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. ActionController::Base.session = { :key => '_<%= app_name %>_session', :secret => '<%= app_secret %>' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # ActionController::Base.session_store = :active_record_store
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/configs/initializers/new_rails_defaults.rb
provider/vendor/rails/railties/configs/initializers/new_rails_defaults.rb
# Be sure to restart your server when you modify this file. # These settings change the behavior of Rails 2 apps and will be defaults # for Rails 3. You can remove this initializer when Rails 3 is released. if defined?(ActiveRecord) # Include Active Record class name as root for JSON serialized output. ActiveRecord::Base.include_root_in_json = true # Store the full class name (including module namespace) in STI type column. ActiveRecord::Base.store_full_sti_class = true end ActionController::Routing.generate_best_match = false # Use ISO 8601 format for JSON serialized times and dates. ActiveSupport.use_standard_json_time_format = true # Don't escape HTML entities in JSON, leave that for the #json_escape helper. # if you're including raw json in an HTML page. ActiveSupport.escape_html_entities_in_json = false
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/configs/initializers/inflections.rb
provider/vendor/rails/railties/configs/initializers/inflections.rb
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format # (all these examples are active by default): # ActiveSupport::Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/configs/initializers/backtrace_silencers.rb
provider/vendor/rails/railties/configs/initializers/backtrace_silencers.rb
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying do debug a problem that might steem from framework code. # Rails.backtrace_cleaner.remove_silencers!
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/configs/initializers/mime_types.rb
provider/vendor/rails/railties/configs/initializers/mime_types.rb
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf # Mime::Type.register_alias "text/html", :iphone
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/guides/rails_guides.rb
provider/vendor/rails/railties/guides/rails_guides.rb
pwd = File.dirname(__FILE__) $: << pwd begin as_lib = File.join(pwd, "../../activesupport/lib") ap_lib = File.join(pwd, "../../actionpack/lib") $: << as_lib if File.directory?(as_lib) $: << ap_lib if File.directory?(ap_lib) require "action_controller" require "action_view" rescue LoadError require 'rubygems' gem "actionpack", '>= 2.3' require "action_controller" require "action_view" end begin require 'rubygems' gem 'RedCloth', '>= 4.1.1' rescue Gem::LoadError $stderr.puts %(Generating Guides requires RedCloth 4.1.1+) exit 1 end require 'redcloth' module RailsGuides autoload :Generator, "rails_guides/generator" autoload :Indexer, "rails_guides/indexer" autoload :Helpers, "rails_guides/helpers" autoload :TextileExtensions, "rails_guides/textile_extensions" end RedCloth.send(:include, RailsGuides::TextileExtensions) if $0 == __FILE__ RailsGuides::Generator.new.generate end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/guides/rails_guides/textile_extensions.rb
provider/vendor/rails/railties/guides/rails_guides/textile_extensions.rb
module RailsGuides module TextileExtensions def notestuff(body) body.gsub!(/^(IMPORTANT|CAUTION|WARNING|NOTE|INFO)(?:\.|\:)(.*)$/) do |m| css_class = $1.downcase css_class = 'warning' if ['caution', 'important'].include?(css_class) result = "<div class='#{css_class}'><p>" result << $2.strip result << '</p></div>' result end end def tip(body) body.gsub!(/^(TIP)\:(.*)$/) do |m| result = "<div class='info'><p>" result << $2.strip result << '</p></div>' result end end def plusplus(body) body.gsub!(/\+(.*?)\+/) do |m| "<notextile><tt>#{$1}</tt></notextile>" end # The real plus sign body.gsub!('<plus>', '+') end def code(body) body.gsub!(%r{<(yaml|shell|ruby|erb|html|sql|plain)>(.*?)</\1>}m) do |m| es = ERB::Util.h($2) css_class = ['erb', 'shell'].include?($1) ? 'html' : $1 %{<notextile><div class="code_container"><code class="#{css_class}">#{es}</code></div></notextile>} end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/guides/rails_guides/helpers.rb
provider/vendor/rails/railties/guides/rails_guides/helpers.rb
module RailsGuides module Helpers def guide(name, url, options = {}, &block) link = content_tag(:a, :href => url) { name } result = content_tag(:dt, link) if ticket = options[:ticket] result << content_tag(:dd, lh(ticket), :class => 'ticket') end result << content_tag(:dd, capture(&block)) concat(result) end def lh(id, label = "Lighthouse Ticket") url = "http://rails.lighthouseapp.com/projects/16213/tickets/#{id}" content_tag(:a, label, :href => url) end def author(name, nick, image = 'credits_pic_blank.gif', &block) image = "images/#{image}" result = content_tag(:img, nil, :src => image, :class => 'left pic', :alt => name) result << content_tag(:h3, name) result << content_tag(:p, capture(&block)) concat content_tag(:div, result, :class => 'clearfix', :id => nick) end def code(&block) c = capture(&block) content_tag(:code, c) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/guides/rails_guides/indexer.rb
provider/vendor/rails/railties/guides/rails_guides/indexer.rb
module RailsGuides class Indexer attr_reader :body, :result, :level_hash def initialize(body) @body = body @result = @body.dup end def index @level_hash = process(body) end private def process(string, current_level= 3, counters = [1]) s = StringScanner.new(string) level_hash = ActiveSupport::OrderedHash.new while !s.eos? s.match?(/\h[0-9]\..*$/) if matched = s.matched matched =~ /\h([0-9])\.(.*)$/ level, title = $1.to_i, $2 if level < current_level # This is needed. Go figure. return level_hash elsif level == current_level index = counters.join(".") bookmark = '#' + title.strip.downcase.gsub(/\s+|_/, '-').delete('^a-z0-9-') raise "Parsing Fail" unless @result.sub!(matched, "h#{level}(#{bookmark}). #{index}#{title}") key = { :title => title, :id => bookmark } # Recurse counters << 1 level_hash[key] = process(s.post_match, current_level + 1, counters) counters.pop # Increment the current level last = counters.pop counters << last + 1 end end s.getch end level_hash end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/guides/rails_guides/generator.rb
provider/vendor/rails/railties/guides/rails_guides/generator.rb
require 'set' module RailsGuides class Generator attr_reader :output, :view_path, :view, :guides_dir def initialize(output = nil) @guides_dir = File.join(File.dirname(__FILE__), '..') @output = output || File.join(@guides_dir, "output") unless ENV["ONLY"] FileUtils.rm_r(@output) if File.directory?(@output) FileUtils.mkdir(@output) end @view_path = File.join(@guides_dir, "source") end def generate guides = Dir.entries(view_path).find_all {|g| g =~ /textile$/ } if ENV["ONLY"] only = ENV["ONLY"].split(",").map{|x| x.strip }.map {|o| "#{o}.textile" } guides = guides.find_all {|g| only.include?(g) } puts "GENERATING ONLY #{guides.inspect}" end guides.each do |guide| generate_guide(guide) end # Copy images and css files to html directory FileUtils.cp_r File.join(guides_dir, 'images'), File.join(output, 'images') FileUtils.cp_r File.join(guides_dir, 'files'), File.join(output, 'files') end def generate_guide(guide) guide =~ /(.*?)(\.erb)?\.textile/ name = $1 puts "Generating #{name}" file = File.join(output, "#{name}.html") File.open(file, 'w') do |f| @view = ActionView::Base.new(view_path) @view.extend(Helpers) if guide =~ /\.erb\.textile/ # Generate the erb pages with textile formatting - e.g. index/authors result = view.render(:layout => 'layout', :file => name) f.write textile(result) else body = File.read(File.join(view_path, guide)) body = set_header_section(body, @view) body = set_index(body, @view) result = view.render(:layout => 'layout', :text => textile(body)) f.write result end end end def set_header_section(body, view) new_body = body.gsub(/(.*?)endprologue\./m, '').strip header = $1 header =~ /h2\.(.*)/ page_title = $1.strip header = textile(header) view.content_for(:page_title) { page_title } view.content_for(:header_section) { header } new_body end def set_index(body, view) index = <<-INDEX <div id="subCol"> <h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3> <ol class="chapters"> INDEX i = Indexer.new(body) i.index # Set index for 2 levels i.level_hash.each do |key, value| link = view.content_tag(:a, :href => key[:id]) { textile(key[:title]) } children = value.keys.map do |k| l = view.content_tag(:a, :href => k[:id]) { textile(k[:title]) } view.content_tag(:li, l) end children_ul = view.content_tag(:ul, children) index << view.content_tag(:li, link + children_ul) end index << '</ol>' index << '</div>' view.content_for(:index_section) { index } i.result end def textile(body) # If the issue with notextile is fixed just remove the wrapper. with_workaround_for_notextile(body) do |body| t = RedCloth.new(body) t.hard_breaks = false t.to_html(:notestuff, :plusplus, :code, :tip) end end # For some reason the notextile tag does not always turn off textile. See # LH ticket of the security guide (#7). As a temporary workaround we deal # with code blocks by hand. def with_workaround_for_notextile(body) code_blocks = [] body.gsub!(%r{<(yaml|shell|ruby|erb|html|sql|plain)>(.*?)</\1>}m) do |m| es = ERB::Util.h($2) css_class = ['erb', 'shell'].include?($1) ? 'html' : $1 code_blocks << %{<div class="code_container"><code class="#{css_class}">#{es}</code></div>} "\ndirty_workaround_for_notextile_#{code_blocks.size - 1}\n" end body = yield body body.gsub(%r{<p>dirty_workaround_for_notextile_(\d+)</p>}) do |_| code_blocks[$1.to_i] end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/environments/test.rb
provider/vendor/rails/railties/environments/test.rb
# Settings specified here will take precedence over those in config/environment.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = true config.action_controller.perform_caching = false config.action_view.cache_template_loading = true # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/environments/development.rb
provider/vendor/rails/railties/environments/development.rb
# Settings specified here will take precedence over those in config/environment.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = true config.action_view.debug_rjs = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/environments/environment.rb
provider/vendor/rails/railties/environments/environment.rb
# Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present <%= '# ' if freeze %>RAILS_GEM_VERSION = '<%= Rails::VERSION::STRING %>' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'UTC' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/environments/production.rb
provider/vendor/rails/railties/environments/production.rb
# Settings specified here will take precedence over those in config/environment.rb # The production environment is meant for finished, "live" apps. # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.action_controller.consider_all_requests_local = false config.action_controller.perform_caching = true config.action_view.cache_template_loading = true # See everything in the log (default is :info) # config.log_level = :debug # Use a different logger for distributed setups # config.logger = SyslogLogger.new # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and javascripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe!
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/environments/boot.rb
provider/vendor/rails/railties/environments/boot.rb
# Don't change this file! # Configure your app in config/environment.rb and config/environments/*.rb RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT) module Rails class << self def boot! unless booted? preinitialize pick_boot.run end end def booted? defined? Rails::Initializer end def pick_boot (vendor_rails? ? VendorBoot : GemBoot).new end def vendor_rails? File.exist?("#{RAILS_ROOT}/vendor/rails") end def preinitialize load(preinitializer_path) if File.exist?(preinitializer_path) end def preinitializer_path "#{RAILS_ROOT}/config/preinitializer.rb" end end class Boot def run load_initializer Rails::Initializer.run(:set_load_path) end end class VendorBoot < Boot def load_initializer require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer" Rails::Initializer.run(:install_gem_spec_stubs) Rails::GemDependency.add_frozen_gem_path end end class GemBoot < Boot def load_initializer self.class.load_rubygems load_rails_gem require 'initializer' end def load_rails_gem if version = self.class.gem_version gem 'rails', version else gem 'rails' end rescue Gem::LoadError => load_error $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.) exit 1 end class << self def rubygems_version Gem::RubyGemsVersion rescue nil end def gem_version if defined? RAILS_GEM_VERSION RAILS_GEM_VERSION elsif ENV.include?('RAILS_GEM_VERSION') ENV['RAILS_GEM_VERSION'] else parse_gem_version(read_environment_rb) end end def load_rubygems min_version = '1.3.2' require 'rubygems' unless rubygems_version >= min_version $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.) exit 1 end rescue LoadError $stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org) exit 1 end def parse_gem_version(text) $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/ end private def read_environment_rb File.read("#{RAILS_ROOT}/config/environment.rb") end end end end # All that for this: Rails.boot!
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/install.rb
provider/vendor/rails/actionpack/install.rb
require 'rbconfig' require 'find' require 'ftools' include Config # this was adapted from rdoc's install.rb by way of Log4r $sitedir = CONFIG["sitelibdir"] unless $sitedir version = CONFIG["MAJOR"] + "." + CONFIG["MINOR"] $libdir = File.join(CONFIG["libdir"], "ruby", version) $sitedir = $:.find {|x| x =~ /site_ruby/ } if !$sitedir $sitedir = File.join($libdir, "site_ruby") elsif $sitedir !~ Regexp.quote(version) $sitedir = File.join($sitedir, version) end end # the actual gruntwork Dir.chdir("lib") Find.find("action_controller", "action_controller.rb", "action_view", "action_view.rb") { |f| if f[-3..-1] == ".rb" File::install(f, File.join($sitedir, *f.split(/\//)), 0644, true) else File::makedirs(File.join($sitedir, *f.split(/\//))) end }
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/active_record_unit.rb
provider/vendor/rails/actionpack/test/active_record_unit.rb
require 'abstract_unit' # Define the essentials class ActiveRecordTestConnector cattr_accessor :able_to_connect cattr_accessor :connected # Set our defaults self.connected = false self.able_to_connect = true end # Try to grab AR if defined?(ActiveRecord) && defined?(Fixtures) $stderr.puts 'Active Record is already loaded, running tests' else $stderr.print 'Attempting to load Active Record... ' begin PATH_TO_AR = "#{File.dirname(__FILE__)}/../../activerecord/lib" raise LoadError, "#{PATH_TO_AR} doesn't exist" unless File.directory?(PATH_TO_AR) $LOAD_PATH.unshift PATH_TO_AR require 'active_record' require 'active_record/fixtures' $stderr.puts 'success' rescue LoadError => e $stderr.print "failed. Skipping Active Record assertion tests: #{e}" ActiveRecordTestConnector.able_to_connect = false end end $stderr.flush # Define the rest of the connector class ActiveRecordTestConnector class << self def setup unless self.connected || !self.able_to_connect setup_connection load_schema require_fixture_models self.connected = true end rescue Exception => e # errors from ActiveRecord setup $stderr.puts "\nSkipping ActiveRecord assertion tests: #{e}" #$stderr.puts " #{e.backtrace.join("\n ")}\n" self.able_to_connect = false end private def setup_connection if Object.const_defined?(:ActiveRecord) defaults = { :database => ':memory:' } begin adapter = defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3' options = defaults.merge :adapter => adapter, :timeout => 500 ActiveRecord::Base.establish_connection(options) ActiveRecord::Base.configurations = { 'sqlite3_ar_integration' => options } ActiveRecord::Base.connection rescue Exception # errors from establishing a connection $stderr.puts 'SQLite 3 unavailable; trying SQLite 2.' options = defaults.merge :adapter => 'sqlite' ActiveRecord::Base.establish_connection(options) ActiveRecord::Base.configurations = { 'sqlite2_ar_integration' => options } ActiveRecord::Base.connection end Object.send(:const_set, :QUOTED_TYPE, ActiveRecord::Base.connection.quote_column_name('type')) unless Object.const_defined?(:QUOTED_TYPE) else raise "Can't setup connection since ActiveRecord isn't loaded." end end # Load actionpack sqlite tables def load_schema File.read(File.dirname(__FILE__) + "/fixtures/db_definitions/sqlite.sql").split(';').each do |sql| ActiveRecord::Base.connection.execute(sql) unless sql.blank? end end def require_fixture_models Dir.glob(File.dirname(__FILE__) + "/fixtures/*.rb").each {|f| require f} end end end class ActiveRecordTestCase < ActionController::TestCase include ActiveRecord::TestFixtures # Set our fixture path if ActiveRecordTestConnector.able_to_connect self.fixture_path = [FIXTURE_LOAD_PATH] self.use_transactional_fixtures = false end def self.fixtures(*args) super if ActiveRecordTestConnector.connected end def run(*args) super if ActiveRecordTestConnector.connected end end ActiveRecordTestConnector.setup
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/testing_sandbox.rb
provider/vendor/rails/actionpack/test/testing_sandbox.rb
module TestingSandbox # Temporarily replaces KCODE for the block def with_kcode(kcode) if RUBY_VERSION < '1.9' old_kcode, $KCODE = $KCODE, kcode begin yield ensure $KCODE = old_kcode end else yield end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/abstract_unit.rb
provider/vendor/rails/actionpack/test/abstract_unit.rb
$:.unshift(File.dirname(__FILE__) + '/../lib') $:.unshift(File.dirname(__FILE__) + '/../../activesupport/lib') $:.unshift(File.dirname(__FILE__) + '/fixtures/helpers') $:.unshift(File.dirname(__FILE__) + '/fixtures/alternate_helpers') require 'rubygems' require 'yaml' require 'stringio' require 'test/unit' gem 'mocha', '>= 0.9.7' require 'mocha' begin require 'ruby-debug' Debugger.settings[:autoeval] = true Debugger.start rescue LoadError # Debugging disabled. `gem install ruby-debug` to enable. end require 'action_controller' require 'action_controller/cgi_ext' require 'action_controller/test_process' require 'action_view/test_case' # Show backtraces for deprecated behavior for quicker cleanup. ActiveSupport::Deprecation.debug = true ActionController::Base.logger = nil ActionController::Routing::Routes.reload rescue nil ActionController::Base.session_store = nil # Register danish language for testing I18n.backend.store_translations 'da', {} I18n.backend.store_translations 'pt-BR', {} ORIGINAL_LOCALES = I18n.available_locales.map(&:to_s).sort FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures') ActionView::Base.cache_template_loading = true ActionController::Base.view_paths = FIXTURE_LOAD_PATH CACHED_VIEW_PATHS = ActionView::Base.cache_template_loading? ? ActionController::Base.view_paths : ActionController::Base.view_paths.map {|path| ActionView::Template::EagerPath.new(path.to_s)} class DummyMutex def lock @locked = true end def unlock @locked = false end def locked? @locked end end ActionController::Reloader.default_lock = DummyMutex.new
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/adv_attr_test.rb
provider/vendor/rails/actionpack/test/adv_attr_test.rb
require File.dirname(__FILE__) + '/abstract_unit' require 'action_mailer/adv_attr_accessor' class AdvAttrTest < Test::Unit::TestCase class Person include ActionMailer::AdvAttrAccessor adv_attr_accessor :name end def test_adv_attr bob = Person.new assert_nil bob.name bob.name 'Bob' assert_equal 'Bob', bob.name assert_raise(ArgumentError) {bob.name 'x', 'y'} end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/integration_test.rb
provider/vendor/rails/actionpack/test/controller/integration_test.rb
require 'abstract_unit' class SessionTest < Test::Unit::TestCase StubApp = lambda { |env| [200, {"Content-Type" => "text/html", "Content-Length" => "13"}, ["Hello, World!"]] } def setup @session = ActionController::Integration::Session.new(StubApp) end def test_https_bang_works_and_sets_truth_by_default assert !@session.https? @session.https! assert @session.https? @session.https! false assert !@session.https? end def test_host! assert_not_equal "glu.ttono.us", @session.host @session.host! "rubyonrails.com" assert_equal "rubyonrails.com", @session.host end def test_follow_redirect_raises_when_no_redirect @session.stubs(:redirect?).returns(false) assert_raise(RuntimeError) { @session.follow_redirect! } end def test_request_via_redirect_uses_given_method path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"} @session.expects(:put).with(path, args, headers) @session.stubs(:redirect?).returns(false) @session.request_via_redirect(:put, path, args, headers) end def test_request_via_redirect_follows_redirects path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"} @session.stubs(:redirect?).returns(true, true, false) @session.expects(:follow_redirect!).times(2) @session.request_via_redirect(:get, path, args, headers) end def test_request_via_redirect_returns_status path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"} @session.stubs(:redirect?).returns(false) @session.stubs(:status).returns(200) assert_equal 200, @session.request_via_redirect(:get, path, args, headers) end def test_get_via_redirect path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" } @session.expects(:request_via_redirect).with(:get, path, args, headers) @session.get_via_redirect(path, args, headers) end def test_post_via_redirect path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" } @session.expects(:request_via_redirect).with(:post, path, args, headers) @session.post_via_redirect(path, args, headers) end def test_put_via_redirect path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" } @session.expects(:request_via_redirect).with(:put, path, args, headers) @session.put_via_redirect(path, args, headers) end def test_delete_via_redirect path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" } @session.expects(:request_via_redirect).with(:delete, path, args, headers) @session.delete_via_redirect(path, args, headers) end def test_url_for_with_controller options = {:action => 'show'} mock_controller = mock() mock_controller.expects(:url_for).with(options).returns('/show') @session.stubs(:controller).returns(mock_controller) assert_equal '/show', @session.url_for(options) end def test_url_for_without_controller options = {:action => 'show'} mock_rewriter = mock() mock_rewriter.expects(:rewrite).with(options).returns('/show') @session.stubs(:generic_url_rewriter).returns(mock_rewriter) @session.stubs(:controller).returns(nil) assert_equal '/show', @session.url_for(options) end def test_redirect_bool_with_status_in_300s @session.stubs(:status).returns 301 assert @session.redirect? end def test_redirect_bool_with_status_in_200s @session.stubs(:status).returns 200 assert !@session.redirect? end def test_get path = "/index"; params = "blah"; headers = {:location => 'blah'} @session.expects(:process).with(:get,path,params,headers) @session.get(path,params,headers) end def test_post path = "/index"; params = "blah"; headers = {:location => 'blah'} @session.expects(:process).with(:post,path,params,headers) @session.post(path,params,headers) end def test_put path = "/index"; params = "blah"; headers = {:location => 'blah'} @session.expects(:process).with(:put,path,params,headers) @session.put(path,params,headers) end def test_delete path = "/index"; params = "blah"; headers = {:location => 'blah'} @session.expects(:process).with(:delete,path,params,headers) @session.delete(path,params,headers) end def test_head path = "/index"; params = "blah"; headers = {:location => 'blah'} @session.expects(:process).with(:head,path,params,headers) @session.head(path,params,headers) end def test_xml_http_request_get path = "/index"; params = "blah"; headers = {:location => 'blah'} headers_after_xhr = headers.merge( "X-Requested-With" => "XMLHttpRequest", "Accept" => "text/javascript, text/html, application/xml, text/xml, */*" ) @session.expects(:process).with(:get,path,params,headers_after_xhr) @session.xml_http_request(:get,path,params,headers) end def test_xml_http_request_post path = "/index"; params = "blah"; headers = {:location => 'blah'} headers_after_xhr = headers.merge( "X-Requested-With" => "XMLHttpRequest", "Accept" => "text/javascript, text/html, application/xml, text/xml, */*" ) @session.expects(:process).with(:post,path,params,headers_after_xhr) @session.xml_http_request(:post,path,params,headers) end def test_xml_http_request_put path = "/index"; params = "blah"; headers = {:location => 'blah'} headers_after_xhr = headers.merge( "X-Requested-With" => "XMLHttpRequest", "Accept" => "text/javascript, text/html, application/xml, text/xml, */*" ) @session.expects(:process).with(:put,path,params,headers_after_xhr) @session.xml_http_request(:put,path,params,headers) end def test_xml_http_request_delete path = "/index"; params = "blah"; headers = {:location => 'blah'} headers_after_xhr = headers.merge( "X-Requested-With" => "XMLHttpRequest", "Accept" => "text/javascript, text/html, application/xml, text/xml, */*" ) @session.expects(:process).with(:delete,path,params,headers_after_xhr) @session.xml_http_request(:delete,path,params,headers) end def test_xml_http_request_head path = "/index"; params = "blah"; headers = {:location => 'blah'} headers_after_xhr = headers.merge( "X-Requested-With" => "XMLHttpRequest", "Accept" => "text/javascript, text/html, application/xml, text/xml, */*" ) @session.expects(:process).with(:head,path,params,headers_after_xhr) @session.xml_http_request(:head,path,params,headers) end def test_xml_http_request_override_accept path = "/index"; params = "blah"; headers = {:location => 'blah', "Accept" => "application/xml"} headers_after_xhr = headers.merge( "X-Requested-With" => "XMLHttpRequest" ) @session.expects(:process).with(:post,path,params,headers_after_xhr) @session.xml_http_request(:post,path,params,headers) end end class IntegrationTestTest < Test::Unit::TestCase def setup @test = ::ActionController::IntegrationTest.new(:default_test) @test.class.stubs(:fixture_table_names).returns([]) @session = @test.open_session end def test_opens_new_session @test.class.expects(:fixture_table_names).times(2).returns(['foo']) session1 = @test.open_session { |sess| } session2 = @test.open_session # implicit session assert_equal ::ActionController::Integration::Session, session1.class assert_equal ::ActionController::Integration::Session, session2.class assert_not_equal session1, session2 end end # Tests that integration tests don't call Controller test methods for processing. # Integration tests have their own setup and teardown. class IntegrationTestUsesCorrectClass < ActionController::IntegrationTest def self.fixture_table_names [] end def test_integration_methods_called reset! @integration_session.stubs(:generic_url_rewriter) @integration_session.stubs(:process) %w( get post head put delete ).each do |verb| assert_nothing_raised("'#{verb}' should use integration test methods") { __send__(verb, '/') } end end end class IntegrationProcessTest < ActionController::IntegrationTest class IntegrationController < ActionController::Base def get respond_to do |format| format.html { render :text => "OK", :status => 200 } format.js { render :text => "JS OK", :status => 200 } end end def get_with_params render :text => "foo: #{params[:foo]}", :status => 200 end def post_with_multiparameter_params render :text => "foo(1i): #{params[:"foo(1i)"]}, foo(2i): #{params[:"foo(2i)"]}", :status => 200 end def multipart_post_with_multiparameter_params render :text => "foo(1i): #{params[:"foo(1i)"]}, foo(2i): #{params[:"foo(2i)"]}, filesize: #{params[:file].size}", :status => 200 end def post render :text => "Created", :status => 201 end def cookie_monster cookies["cookie_1"] = nil cookies["cookie_3"] = "chocolate" render :text => "Gone", :status => 410 end def redirect redirect_to :action => "get" end end FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart' def test_get with_test_route_set do get '/get' assert_equal 200, status assert_equal "OK", status_message assert_response 200 assert_response :success assert_response :ok assert_equal({}, cookies) assert_equal "OK", body assert_equal "OK", response.body assert_kind_of HTML::Document, html_document assert_equal 1, request_count end end def test_post with_test_route_set do post '/post' assert_equal 201, status assert_equal "Created", status_message assert_response 201 assert_response :success assert_response :created assert_equal({}, cookies) assert_equal "Created", body assert_equal "Created", response.body assert_kind_of HTML::Document, html_document assert_equal 1, request_count end end def test_cookie_monster with_test_route_set do self.cookies['cookie_1'] = "sugar" self.cookies['cookie_2'] = "oatmeal" get '/cookie_monster' assert_equal 410, status assert_equal "Gone", status_message assert_response 410 assert_response :gone assert_equal "cookie_1=; path=/\ncookie_3=chocolate; path=/", headers["Set-Cookie"] assert_equal({"cookie_1"=>"", "cookie_2"=>"oatmeal", "cookie_3"=>"chocolate"}, cookies) assert_equal "Gone", response.body end end def test_redirect with_test_route_set do get '/redirect' assert_equal 302, status assert_equal "Found", status_message assert_response 302 assert_response :redirect assert_response :found assert_equal "<html><body>You are being <a href=\"http://www.example.com/get\">redirected</a>.</body></html>", response.body assert_kind_of HTML::Document, html_document assert_equal 1, request_count follow_redirect! assert_response :success assert_equal "/get", path end end def test_xml_http_request_get with_test_route_set do xhr :get, '/get' assert_equal 200, status assert_equal "OK", status_message assert_response 200 assert_response :success assert_response :ok assert_equal "JS OK", response.body end end def test_get_with_query_string with_test_route_set do get '/get_with_params?foo=bar' assert_equal '/get_with_params?foo=bar', request.env["REQUEST_URI"] assert_equal '/get_with_params?foo=bar', request.request_uri assert_equal "", request.env["QUERY_STRING"] assert_equal 'foo=bar', request.query_string assert_equal 'bar', request.parameters['foo'] assert_equal 200, status assert_equal "foo: bar", response.body end end def test_get_with_parameters with_test_route_set do get '/get_with_params', :foo => "bar" assert_equal '/get_with_params', request.env["REQUEST_URI"] assert_equal '/get_with_params', request.request_uri assert_equal 'foo=bar', request.env["QUERY_STRING"] assert_equal 'foo=bar', request.query_string assert_equal 'bar', request.parameters['foo'] assert_equal 200, status assert_equal "foo: bar", response.body end end def test_post_with_multiparameter_attribute_parameters with_test_route_set do post '/post_with_multiparameter_params', :"foo(1i)" => "bar", :"foo(2i)" => "baz" assert_equal 200, status assert_equal "foo(1i): bar, foo(2i): baz", response.body end end def test_multipart_post_with_multiparameter_attribute_parameters with_test_route_set do post '/multipart_post_with_multiparameter_params', :"foo(1i)" => "bar", :"foo(2i)" => "baz", :file => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg") assert_equal 200, status assert_equal "foo(1i): bar, foo(2i): baz, filesize: 159528", response.body end end def test_head with_test_route_set do head '/get' assert_equal 200, status assert_equal "", body head '/post' assert_equal 201, status assert_equal "", body end end private def with_test_route_set with_routing do |set| set.draw do |map| map.with_options :controller => "IntegrationProcessTest::Integration" do |c| c.connect "/:action" end end yield end end end class MetalTest < ActionController::IntegrationTest class Poller def self.call(env) if env["PATH_INFO"] =~ /^\/success/ [200, {"Content-Type" => "text/plain", "Content-Length" => "12"}, ["Hello World!"]] else [404, {"Content-Type" => "text/plain", "Content-Length" => "0"}, []] end end end def setup @integration_session = ActionController::Integration::Session.new(Poller) end def test_successful_get get "/success" assert_response 200 assert_response :success assert_response :ok assert_equal "Hello World!", response.body end def test_failed_get get "/failure" assert_response 404 assert_response :not_found assert_equal '', response.body end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/addresses_render_test.rb
provider/vendor/rails/actionpack/test/controller/addresses_render_test.rb
require 'abstract_unit' class Address def Address.count(conditions = nil, join = nil) nil end def Address.find_all(arg1, arg2, arg3, arg4) [] end def self.find(*args) [] end end class AddressesTestController < ActionController::Base def self.controller_name; "addresses"; end def self.controller_path; "addresses"; end end class AddressesTest < ActionController::TestCase tests AddressesTestController def setup # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". @controller.logger = Logger.new(nil) @request.host = "www.nextangle.com" end def test_list get :list assert_equal "We only need to get this far!", @response.body.chomp end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/cookie_test.rb
provider/vendor/rails/actionpack/test/controller/cookie_test.rb
require 'abstract_unit' class CookieTest < ActionController::TestCase class TestController < ActionController::Base def authenticate cookies["user_name"] = "david" end def set_with_with_escapable_characters cookies["that & guy"] = "foo & bar => baz" end def authenticate_for_fourteen_days cookies["user_name"] = { "value" => "david", "expires" => Time.utc(2005, 10, 10,5) } end def authenticate_for_fourteen_days_with_symbols cookies[:user_name] = { :value => "david", :expires => Time.utc(2005, 10, 10,5) } end def set_multiple_cookies cookies["user_name"] = { "value" => "david", "expires" => Time.utc(2005, 10, 10,5) } cookies["login"] = "XJ-122" end def access_frozen_cookies cookies["will"] = "work" end def logout cookies.delete("user_name") end def delete_cookie_with_path cookies.delete("user_name", :path => '/beaten') render :text => "hello world" end def authenticate_with_http_only cookies["user_name"] = { :value => "david", :httponly => true } end def rescue_action(e) raise unless ActionView::MissingTemplate # No templates here, and we don't care about the output end end tests TestController def setup @request.host = "www.nextangle.com" end def test_setting_cookie get :authenticate assert_equal ["user_name=david; path=/"], @response.headers["Set-Cookie"] assert_equal({"user_name" => "david"}, @response.cookies) end def test_setting_with_escapable_characters get :set_with_with_escapable_characters assert_equal ["that+%26+guy=foo+%26+bar+%3D%3E+baz; path=/"], @response.headers["Set-Cookie"] assert_equal({"that & guy" => "foo & bar => baz"}, @response.cookies) end def test_setting_cookie_for_fourteen_days get :authenticate_for_fourteen_days assert_equal ["user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT"], @response.headers["Set-Cookie"] assert_equal({"user_name" => "david"}, @response.cookies) end def test_setting_cookie_for_fourteen_days_with_symbols get :authenticate_for_fourteen_days_with_symbols assert_equal ["user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT"], @response.headers["Set-Cookie"] assert_equal({"user_name" => "david"}, @response.cookies) end def test_setting_cookie_with_http_only get :authenticate_with_http_only assert_equal ["user_name=david; path=/; HttpOnly"], @response.headers["Set-Cookie"] assert_equal({"user_name" => "david"}, @response.cookies) end def test_multiple_cookies get :set_multiple_cookies assert_equal 2, @response.cookies.size assert_equal "user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT", @response.headers["Set-Cookie"][0] assert_equal "login=XJ-122; path=/", @response.headers["Set-Cookie"][1] assert_equal({"login" => "XJ-122", "user_name" => "david"}, @response.cookies) end def test_setting_test_cookie assert_nothing_raised { get :access_frozen_cookies } end def test_expiring_cookie get :logout assert_equal ["user_name=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT"], @response.headers["Set-Cookie"] assert_equal({"user_name" => nil}, @response.cookies) end def test_cookiejar_accessor @request.cookies["user_name"] = "david" @controller.request = @request jar = ActionController::CookieJar.new(@controller) assert_equal "david", jar["user_name"] assert_equal nil, jar["something_else"] end def test_cookiejar_accessor_with_array_value @request.cookies["pages"] = %w{1 2 3} @controller.request = @request jar = ActionController::CookieJar.new(@controller) assert_equal %w{1 2 3}, jar["pages"] end def test_delete_cookie_with_path get :delete_cookie_with_path assert_equal ["user_name=; path=/beaten; expires=Thu, 01-Jan-1970 00:00:00 GMT"], @response.headers["Set-Cookie"] end def test_cookies_persist_throughout_request get :authenticate cookies = @controller.send(:cookies) assert_equal 'david', cookies['user_name'] end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/rack_test.rb
provider/vendor/rails/actionpack/test/controller/rack_test.rb
require 'abstract_unit' class BaseRackTest < ActiveSupport::TestCase def setup @env = { "HTTP_MAX_FORWARDS" => "10", "SERVER_NAME" => "glu.ttono.us", "FCGI_ROLE" => "RESPONDER", "AUTH_TYPE" => "Basic", "HTTP_X_FORWARDED_HOST" => "glu.ttono.us", "HTTP_ACCEPT_CHARSET" => "UTF-8", "HTTP_ACCEPT_ENCODING" => "gzip, deflate", "HTTP_CACHE_CONTROL" => "no-cache, max-age=0", "HTTP_PRAGMA" => "no-cache", "HTTP_USER_AGENT" => "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en)", "PATH_INFO" => "/homepage/", "HTTP_ACCEPT_LANGUAGE" => "en", "HTTP_NEGOTIATE" => "trans", "HTTP_HOST" => "glu.ttono.us:8007", "HTTP_REFERER" => "http://www.google.com/search?q=glu.ttono.us", "HTTP_FROM" => "googlebot", "SERVER_PROTOCOL" => "HTTP/1.1", "REDIRECT_URI" => "/dispatch.fcgi", "SCRIPT_NAME" => "/dispatch.fcgi", "SERVER_ADDR" => "207.7.108.53", "REMOTE_ADDR" => "207.7.108.53", "REMOTE_HOST" => "google.com", "REMOTE_IDENT" => "kevin", "REMOTE_USER" => "kevin", "SERVER_SOFTWARE" => "lighttpd/1.4.5", "HTTP_COOKIE" => "_session_id=c84ace84796670c052c6ceb2451fb0f2; is_admin=yes", "HTTP_X_FORWARDED_SERVER" => "glu.ttono.us", "REQUEST_URI" => "/admin", "DOCUMENT_ROOT" => "/home/kevinc/sites/typo/public", "PATH_TRANSLATED" => "/home/kevinc/sites/typo/public/homepage/", "SERVER_PORT" => "8007", "QUERY_STRING" => "", "REMOTE_PORT" => "63137", "GATEWAY_INTERFACE" => "CGI/1.1", "HTTP_X_FORWARDED_FOR" => "65.88.180.234", "HTTP_ACCEPT" => "*/*", "SCRIPT_FILENAME" => "/home/kevinc/sites/typo/public/dispatch.fcgi", "REDIRECT_STATUS" => "200", "REQUEST_METHOD" => "GET" } @request = ActionController::Request.new(@env) # some Nokia phone browsers omit the space after the semicolon separator. # some developers have grown accustomed to using comma in cookie values. @alt_cookie_fmt_request = ActionController::Request.new(@env.merge({"HTTP_COOKIE"=>"_session_id=c84ace847,96670c052c6ceb2451fb0f2;is_admin=yes"})) end def default_test; end private def set_content_data(data) @request.env['REQUEST_METHOD'] = 'POST' @request.env['CONTENT_LENGTH'] = data.length @request.env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8' @request.env['rack.input'] = StringIO.new(data) end end class RackRequestTest < BaseRackTest def test_proxy_request assert_equal 'glu.ttono.us', @request.host_with_port end def test_http_host @env.delete "HTTP_X_FORWARDED_HOST" @env['HTTP_HOST'] = "rubyonrails.org:8080" assert_equal "rubyonrails.org", @request.host assert_equal "rubyonrails.org:8080", @request.host_with_port @env['HTTP_X_FORWARDED_HOST'] = "www.firsthost.org, www.secondhost.org" assert_equal "www.secondhost.org", @request.host end def test_http_host_with_default_port_overrides_server_port @env.delete "HTTP_X_FORWARDED_HOST" @env['HTTP_HOST'] = "rubyonrails.org" assert_equal "rubyonrails.org", @request.host_with_port end def test_host_with_port_defaults_to_server_name_if_no_host_headers @env.delete "HTTP_X_FORWARDED_HOST" @env.delete "HTTP_HOST" assert_equal "glu.ttono.us:8007", @request.host_with_port end def test_host_with_port_falls_back_to_server_addr_if_necessary @env.delete "HTTP_X_FORWARDED_HOST" @env.delete "HTTP_HOST" @env.delete "SERVER_NAME" assert_equal "207.7.108.53", @request.host assert_equal 8007, @request.port assert_equal "207.7.108.53:8007", @request.host_with_port end def test_host_with_port_if_http_standard_port_is_specified @env['HTTP_X_FORWARDED_HOST'] = "glu.ttono.us:80" assert_equal "glu.ttono.us", @request.host_with_port end def test_host_with_port_if_https_standard_port_is_specified @env['HTTP_X_FORWARDED_PROTO'] = "https" @env['HTTP_X_FORWARDED_HOST'] = "glu.ttono.us:443" assert_equal "glu.ttono.us", @request.host_with_port end def test_host_if_ipv6_reference @env.delete "HTTP_X_FORWARDED_HOST" @env['HTTP_HOST'] = "[2001:1234:5678:9abc:def0::dead:beef]" assert_equal "[2001:1234:5678:9abc:def0::dead:beef]", @request.host end def test_host_if_ipv6_reference_with_port @env.delete "HTTP_X_FORWARDED_HOST" @env['HTTP_HOST'] = "[2001:1234:5678:9abc:def0::dead:beef]:8008" assert_equal "[2001:1234:5678:9abc:def0::dead:beef]", @request.host end def test_cgi_environment_variables assert_equal "Basic", @request.auth_type assert_equal 0, @request.content_length assert_equal nil, @request.content_type assert_equal "CGI/1.1", @request.gateway_interface assert_equal "*/*", @request.accept assert_equal "UTF-8", @request.accept_charset assert_equal "gzip, deflate", @request.accept_encoding assert_equal "en", @request.accept_language assert_equal "no-cache, max-age=0", @request.cache_control assert_equal "googlebot", @request.from assert_equal "glu.ttono.us", @request.host assert_equal "trans", @request.negotiate assert_equal "no-cache", @request.pragma assert_equal "http://www.google.com/search?q=glu.ttono.us", @request.referer assert_equal "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en)", @request.user_agent assert_equal "/homepage/", @request.path_info assert_equal "/home/kevinc/sites/typo/public/homepage/", @request.path_translated assert_equal "", @request.query_string assert_equal "207.7.108.53", @request.remote_addr assert_equal "google.com", @request.remote_host assert_equal "kevin", @request.remote_ident assert_equal "kevin", @request.remote_user assert_equal :get, @request.request_method assert_equal "/dispatch.fcgi", @request.script_name assert_equal "glu.ttono.us", @request.server_name assert_equal 8007, @request.server_port assert_equal "HTTP/1.1", @request.server_protocol assert_equal "lighttpd", @request.server_software end def test_cookie_syntax_resilience cookies = @request.cookies assert_equal "c84ace84796670c052c6ceb2451fb0f2", cookies["_session_id"], cookies.inspect assert_equal "yes", cookies["is_admin"], cookies.inspect alt_cookies = @alt_cookie_fmt_request.cookies #assert_equal "c84ace847,96670c052c6ceb2451fb0f2", alt_cookies["_session_id"], alt_cookies.inspect assert_equal "yes", alt_cookies["is_admin"], alt_cookies.inspect end end class RackRequestParamsParsingTest < BaseRackTest def test_doesnt_break_when_content_type_has_charset set_content_data 'flamenco=love' assert_equal({"flamenco"=> "love"}, @request.request_parameters) end def test_doesnt_interpret_request_uri_as_query_string_when_missing @request.env['REQUEST_URI'] = 'foo' assert_equal({}, @request.query_parameters) end end class RackRequestContentTypeTest < BaseRackTest def test_html_content_type_verification @request.env['CONTENT_TYPE'] = Mime::HTML.to_s assert @request.content_type.verify_request? end def test_xml_content_type_verification @request.env['CONTENT_TYPE'] = Mime::XML.to_s assert !@request.content_type.verify_request? end end class RackRequestNeedsRewoundTest < BaseRackTest def test_body_should_be_rewound data = 'foo' @env['rack.input'] = StringIO.new(data) @env['CONTENT_LENGTH'] = data.length @env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8' # Read the request body by parsing params. request = ActionController::Request.new(@env) request.request_parameters # Should have rewound the body. assert_equal 0, request.body.pos end end class RackResponseTest < BaseRackTest def setup super @response = ActionController::Response.new end def test_simple_output @response.body = "Hello, World!" @response.prepare! status, headers, body = @response.to_a assert_equal 200, status assert_equal({ "Content-Type" => "text/html; charset=utf-8", "Cache-Control" => "private, max-age=0, must-revalidate", "ETag" => '"65a8e27d8879283831b664bd8b7f0ad4"', "Set-Cookie" => "", "Content-Length" => "13" }, headers) parts = [] body.each { |part| parts << part } assert_equal ["Hello, World!"], parts end def test_utf8_output @response.body = [1090, 1077, 1089, 1090].pack("U*") @response.prepare! status, headers, body = @response.to_a assert_equal 200, status assert_equal({ "Content-Type" => "text/html; charset=utf-8", "Cache-Control" => "private, max-age=0, must-revalidate", "ETag" => '"ebb5e89e8a94e9dd22abf5d915d112b2"', "Set-Cookie" => "", "Content-Length" => "8" }, headers) end def test_streaming_block @response.body = Proc.new do |response, output| 5.times { |n| output.write(n) } end @response.prepare! status, headers, body = @response.to_a assert_equal 200, status assert_equal({ "Content-Type" => "text/html; charset=utf-8", "Cache-Control" => "no-cache", "Set-Cookie" => "" }, headers) parts = [] body.each { |part| parts << part } assert_equal ["0", "1", "2", "3", "4"], parts end def test_streaming_block_with_flush_is_deprecated @response.body = Proc.new do |response, output| 5.times do |n| output.write(n) output.flush end end assert_deprecated(/output.flush is no longer needed/) do @response.prepare! status, headers, body = @response.to_a parts = [] body.each { |part| parts << part } end end end class RackResponseHeadersTest < BaseRackTest def setup super @response = ActionController::Response.new @response.status = "200 OK" end def test_content_type [204, 304].each do |c| @response.status = c.to_s assert !response_headers.has_key?("Content-Type"), "#{c} should not have Content-Type header" end [200, 302, 404, 500].each do |c| @response.status = c.to_s assert response_headers.has_key?("Content-Type"), "#{c} did not have Content-Type header" end end def test_status assert !response_headers.has_key?('Status') end private def response_headers @response.prepare! @response.to_a[1] end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/http_basic_authentication_test.rb
provider/vendor/rails/actionpack/test/controller/http_basic_authentication_test.rb
require 'abstract_unit' class HttpBasicAuthenticationTest < ActionController::TestCase class DummyController < ActionController::Base before_filter :authenticate, :only => :index before_filter :authenticate_with_request, :only => :display before_filter :authenticate_long_credentials, :only => :show def index render :text => "Hello Secret" end def display render :text => 'Definitely Maybe' end def show render :text => 'Only for loooooong credentials' end private def authenticate authenticate_or_request_with_http_basic do |username, password| username == 'lifo' && password == 'world' end end def authenticate_with_request if authenticate_with_http_basic { |username, password| username == 'pretty' && password == 'please' } @logged_in = true else request_http_basic_authentication("SuperSecret") end end def authenticate_long_credentials authenticate_or_request_with_http_basic do |username, password| username == '1234567890123456789012345678901234567890' && password == '1234567890123456789012345678901234567890' end end end AUTH_HEADERS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION', 'REDIRECT_X_HTTP_AUTHORIZATION'] tests DummyController AUTH_HEADERS.each do |header| test "successful authentication with #{header.downcase}" do @request.env[header] = encode_credentials('lifo', 'world') get :index assert_response :success assert_equal 'Hello Secret', @response.body, "Authentication failed for request header #{header}" end test "successful authentication with #{header.downcase} and long credentials" do @request.env[header] = encode_credentials('1234567890123456789012345678901234567890', '1234567890123456789012345678901234567890') get :show assert_response :success assert_equal 'Only for loooooong credentials', @response.body, "Authentication failed for request header #{header} and long credentials" end end AUTH_HEADERS.each do |header| test "unsuccessful authentication with #{header.downcase}" do @request.env[header] = encode_credentials('h4x0r', 'world') get :index assert_response :unauthorized assert_equal "HTTP Basic: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header}" end test "unsuccessful authentication with #{header.downcase} and long credentials" do @request.env[header] = encode_credentials('h4x0rh4x0rh4x0rh4x0rh4x0rh4x0rh4x0rh4x0r', 'worldworldworldworldworldworldworldworld') get :show assert_response :unauthorized assert_equal "HTTP Basic: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header} and long credentials" end end test "authentication request without credential" do get :display assert_response :unauthorized assert_equal "HTTP Basic: Access denied.\n", @response.body assert_equal 'Basic realm="SuperSecret"', @response.headers['WWW-Authenticate'] end test "authentication request with invalid credential" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials('pretty', 'foo') get :display assert_response :unauthorized assert_equal "HTTP Basic: Access denied.\n", @response.body assert_equal 'Basic realm="SuperSecret"', @response.headers['WWW-Authenticate'] end test "authentication request with valid credential" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials('pretty', 'please') get :display assert_response :success assert assigns(:logged_in) assert_equal 'Definitely Maybe', @response.body end private def encode_credentials(username, password) "Basic #{ActiveSupport::Base64.encode64("#{username}:#{password}")}" end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/middleware_stack_test.rb
provider/vendor/rails/actionpack/test/controller/middleware_stack_test.rb
require 'abstract_unit' class MiddlewareStackTest < ActiveSupport::TestCase class FooMiddleware; end class BarMiddleware; end class BazMiddleware; end def setup @stack = ActionController::MiddlewareStack.new @stack.use FooMiddleware @stack.use BarMiddleware end test "use should push middleware as class onto the stack" do assert_difference "@stack.size" do @stack.use BazMiddleware end assert_equal BazMiddleware, @stack.last.klass end test "use should push middleware as a string onto the stack" do assert_difference "@stack.size" do @stack.use "MiddlewareStackTest::BazMiddleware" end assert_equal BazMiddleware, @stack.last.klass end test "use should push middleware as a symbol onto the stack" do assert_difference "@stack.size" do @stack.use :"MiddlewareStackTest::BazMiddleware" end assert_equal BazMiddleware, @stack.last.klass end test "use should push middleware class with arguments onto the stack" do assert_difference "@stack.size" do @stack.use BazMiddleware, true, :foo => "bar" end assert_equal BazMiddleware, @stack.last.klass assert_equal([true, {:foo => "bar"}], @stack.last.args) end test "insert inserts middleware at the integer index" do @stack.insert(1, BazMiddleware) assert_equal BazMiddleware, @stack[1].klass end test "insert_after inserts middleware after the integer index" do @stack.insert_after(1, BazMiddleware) assert_equal BazMiddleware, @stack[2].klass end test "insert_before inserts middleware before another middleware class" do @stack.insert_before(BarMiddleware, BazMiddleware) assert_equal BazMiddleware, @stack[1].klass end test "insert_after inserts middleware after another middleware class" do @stack.insert_after(BarMiddleware, BazMiddleware) assert_equal BazMiddleware, @stack[2].klass end test "swaps one middleware out for another" do assert_equal FooMiddleware, @stack[0].klass @stack.swap(FooMiddleware, BazMiddleware) assert_equal BazMiddleware, @stack[0].klass end test "active returns all only enabled middleware" do assert_no_difference "@stack.active.size" do assert_difference "@stack.size" do @stack.use BazMiddleware, :if => lambda { false } end end end test "lazy evaluates middleware class" do assert_difference "@stack.size" do @stack.use lambda { BazMiddleware } end assert_equal BazMiddleware, @stack.last.klass end test "lazy evaluates middleware arguments" do assert_difference "@stack.size" do @stack.use BazMiddleware, lambda { :foo } end assert_equal [:foo], @stack.last.send(:build_args) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/send_file_test.rb
provider/vendor/rails/actionpack/test/controller/send_file_test.rb
# encoding: utf-8 require 'abstract_unit' module TestFileUtils def file_name() File.basename(__FILE__) end def file_path() File.expand_path(__FILE__) end def file_data() @data ||= File.open(file_path, 'rb') { |f| f.read } end end class SendFileController < ActionController::Base include TestFileUtils layout "layouts/standard" # to make sure layouts don't interfere attr_writer :options def options() @options ||= {} end def file() send_file(file_path, options) end def data() send_data(file_data, options) end def multibyte_text_data() send_data("Кирилица\n祝您好運", options) end def rescue_action(e) raise end end class SendFileTest < ActionController::TestCase tests SendFileController include TestFileUtils Mime::Type.register "image/png", :png unless defined? Mime::PNG def setup @controller = SendFileController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new end def test_file_nostream @controller.options = { :stream => false } response = nil assert_nothing_raised { response = process('file') } assert_not_nil response assert_kind_of String, response.body assert_equal file_data, response.body end def test_file_stream response = nil assert_nothing_raised { response = process('file') } assert_not_nil response assert_kind_of Proc, response.body require 'stringio' output = StringIO.new output.binmode output.string.force_encoding(file_data.encoding) if output.string.respond_to?(:force_encoding) assert_nothing_raised { response.body.call(response, output) } assert_equal file_data, output.string end def test_file_url_based_filename @controller.options = { :url_based_filename => true } response = nil assert_nothing_raised { response = process('file') } assert_not_nil response assert_equal "attachment", response.headers["Content-Disposition"] end def test_x_sendfile_header @controller.options = { :x_sendfile => true } response = nil assert_nothing_raised { response = process('file') } assert_not_nil response assert_equal @controller.file_path, response.headers['X-Sendfile'] assert response.body.blank? assert !response.etag? end def test_data response = nil assert_nothing_raised { response = process('data') } assert_not_nil response assert_kind_of String, response.body assert_equal file_data, response.body end def test_headers_after_send_shouldnt_include_charset response = process('data') assert_equal "application/octet-stream", response.content_type response = process('file') assert_equal "application/octet-stream", response.content_type end # Test that send_file_headers! is setting the correct HTTP headers. def test_send_file_headers! options = { :length => 1, :type => Mime::PNG, :disposition => 'disposition', :filename => 'filename' } # Do it a few times: the resulting headers should be identical # no matter how many times you send with the same options. # Test resolving Ticket #458. @controller.headers = {} @controller.send(:send_file_headers!, options) @controller.send(:send_file_headers!, options) @controller.send(:send_file_headers!, options) h = @controller.headers assert_equal '1', h['Content-Length'] assert_equal 'image/png', h['Content-Type'] assert_equal 'disposition; filename="filename"', h['Content-Disposition'] assert_equal 'binary', h['Content-Transfer-Encoding'] # test overriding Cache-Control: no-cache header to fix IE open/save dialog @controller.headers = { 'Cache-Control' => 'no-cache' } @controller.send(:send_file_headers!, options) h = @controller.headers assert_equal 'private', h['Cache-Control'] end def test_send_file_headers_with_mime_lookup_with_symbol options = { :length => 1, :type => :png } @controller.headers = {} @controller.send(:send_file_headers!, options) headers = @controller.headers assert_equal 'image/png', headers['Content-Type'] end def test_send_file_headers_with_bad_symbol options = { :length => 1, :type => :this_type_is_not_registered } @controller.headers = {} assert_raise(ArgumentError){ @controller.send(:send_file_headers!, options) } end %w(file data).each do |method| define_method "test_send_#{method}_status" do @controller.options = { :stream => false, :status => 500 } assert_nothing_raised { assert_not_nil process(method) } assert_equal '500 Internal Server Error', @response.status end define_method "test_default_send_#{method}_status" do @controller.options = { :stream => false } assert_nothing_raised { assert_not_nil process(method) } assert_equal ActionController::Base::DEFAULT_RENDER_STATUS_CODE, @response.status end end def test_send_data_content_length_header @controller.headers = {} @controller.options = { :type => :text, :filename => 'file_with_utf8_text' } process('multibyte_text_data') assert_equal '29', @controller.headers['Content-Length'] end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/verification_test.rb
provider/vendor/rails/actionpack/test/controller/verification_test.rb
require 'abstract_unit' class VerificationTest < ActionController::TestCase class TestController < ActionController::Base verify :only => :guarded_one, :params => "one", :add_flash => { :error => 'unguarded' }, :redirect_to => { :action => "unguarded" } verify :only => :guarded_two, :params => %w( one two ), :redirect_to => { :action => "unguarded" } verify :only => :guarded_with_flash, :params => "one", :add_flash => { :notice => "prereqs failed" }, :redirect_to => { :action => "unguarded" } verify :only => :guarded_in_session, :session => "one", :redirect_to => { :action => "unguarded" } verify :only => [:multi_one, :multi_two], :session => %w( one two ), :redirect_to => { :action => "unguarded" } verify :only => :guarded_by_method, :method => :post, :redirect_to => { :action => "unguarded" } verify :only => :guarded_by_xhr, :xhr => true, :redirect_to => { :action => "unguarded" } verify :only => :guarded_by_not_xhr, :xhr => false, :redirect_to => { :action => "unguarded" } before_filter :unconditional_redirect, :only => :two_redirects verify :only => :two_redirects, :method => :post, :redirect_to => { :action => "unguarded" } verify :only => :must_be_post, :method => :post, :render => { :status => 405, :text => "Must be post" }, :add_headers => { "Allow" => "POST" } verify :only => :guarded_one_for_named_route_test, :params => "one", :redirect_to => :foo_url verify :only => :no_default_action, :params => "santa" verify :only => :guarded_with_back, :method => :post, :redirect_to => :back def guarded_one render :text => "#{params[:one]}" end def guarded_one_for_named_route_test render :text => "#{params[:one]}" end def guarded_with_flash render :text => "#{params[:one]}" end def guarded_two render :text => "#{params[:one]}:#{params[:two]}" end def guarded_in_session render :text => "#{session["one"]}" end def multi_one render :text => "#{session["one"]}:#{session["two"]}" end def multi_two render :text => "#{session["two"]}:#{session["one"]}" end def guarded_by_method render :text => "#{request.method}" end def guarded_by_xhr render :text => "#{request.xhr?}" end def guarded_by_not_xhr render :text => "#{request.xhr?}" end def unguarded render :text => "#{params[:one]}" end def two_redirects render :nothing => true end def must_be_post render :text => "Was a post!" end def guarded_with_back render :text => "#{params[:one]}" end def no_default_action # Will never run end protected def rescue_action(e) raise end def unconditional_redirect redirect_to :action => "unguarded" end end def setup @controller = TestController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new ActionController::Routing::Routes.add_named_route :foo, '/foo', :controller => 'test', :action => 'foo' end def test_using_symbol_back_with_no_referrer assert_raise(ActionController::RedirectBackError) { get :guarded_with_back } end def test_using_symbol_back_redirects_to_referrer @request.env["HTTP_REFERER"] = "/foo" get :guarded_with_back assert_redirected_to '/foo' end def test_no_deprecation_warning_for_named_route assert_not_deprecated do get :guarded_one_for_named_route_test, :two => "not one" assert_redirected_to '/foo' end end def test_guarded_one_with_prereqs get :guarded_one, :one => "here" assert_equal "here", @response.body end def test_guarded_one_without_prereqs get :guarded_one assert_redirected_to :action => "unguarded" assert_equal 'unguarded', flash[:error] end def test_guarded_with_flash_with_prereqs get :guarded_with_flash, :one => "here" assert_equal "here", @response.body assert flash.empty? end def test_guarded_with_flash_without_prereqs get :guarded_with_flash assert_redirected_to :action => "unguarded" assert_equal "prereqs failed", flash[:notice] end def test_guarded_two_with_prereqs get :guarded_two, :one => "here", :two => "there" assert_equal "here:there", @response.body end def test_guarded_two_without_prereqs_one get :guarded_two, :two => "there" assert_redirected_to :action => "unguarded" end def test_guarded_two_without_prereqs_two get :guarded_two, :one => "here" assert_redirected_to :action => "unguarded" end def test_guarded_two_without_prereqs_both get :guarded_two assert_redirected_to :action => "unguarded" end def test_unguarded_with_params get :unguarded, :one => "here" assert_equal "here", @response.body end def test_unguarded_without_params get :unguarded assert_equal "", @response.body end def test_guarded_in_session_with_prereqs get :guarded_in_session, {}, "one" => "here" assert_equal "here", @response.body end def test_guarded_in_session_without_prereqs get :guarded_in_session assert_redirected_to :action => "unguarded" end def test_multi_one_with_prereqs get :multi_one, {}, "one" => "here", "two" => "there" assert_equal "here:there", @response.body end def test_multi_one_without_prereqs get :multi_one assert_redirected_to :action => "unguarded" end def test_multi_two_with_prereqs get :multi_two, {}, "one" => "here", "two" => "there" assert_equal "there:here", @response.body end def test_multi_two_without_prereqs get :multi_two assert_redirected_to :action => "unguarded" end def test_guarded_by_method_with_prereqs post :guarded_by_method assert_equal "post", @response.body end def test_guarded_by_method_without_prereqs get :guarded_by_method assert_redirected_to :action => "unguarded" end def test_guarded_by_xhr_with_prereqs xhr :post, :guarded_by_xhr assert_equal "true", @response.body end def test_guarded_by_xhr_without_prereqs get :guarded_by_xhr assert_redirected_to :action => "unguarded" end def test_guarded_by_not_xhr_with_prereqs get :guarded_by_not_xhr assert_equal "false", @response.body end def test_guarded_by_not_xhr_without_prereqs xhr :post, :guarded_by_not_xhr assert_redirected_to :action => "unguarded" end def test_guarded_post_and_calls_render_succeeds post :must_be_post assert_equal "Was a post!", @response.body end def test_default_failure_should_be_a_bad_request post :no_default_action assert_response :bad_request end def test_guarded_post_and_calls_render_fails_and_sets_allow_header get :must_be_post assert_response 405 assert_equal "Must be post", @response.body assert_equal "POST", @response.headers["Allow"] end def test_second_redirect assert_nothing_raised { get :two_redirects } end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/filter_params_test.rb
provider/vendor/rails/actionpack/test/controller/filter_params_test.rb
require 'abstract_unit' class FilterParamController < ActionController::Base end class FilterParamTest < Test::Unit::TestCase def setup @controller = FilterParamController.new end def test_filter_parameters assert FilterParamController.respond_to?(:filter_parameter_logging) assert !@controller.respond_to?(:filter_parameters) FilterParamController.filter_parameter_logging assert @controller.respond_to?(:filter_parameters) test_hashes = [[{},{},[]], [{'foo'=>nil},{'foo'=>nil},[]], [{'foo'=>'bar'},{'foo'=>'bar'},[]], [{'foo'=>'bar'},{'foo'=>'bar'},%w'food'], [{'foo'=>'bar'},{'foo'=>'[FILTERED]'},%w'foo'], [{'foo'=>'bar', 'bar'=>'foo'},{'foo'=>'[FILTERED]', 'bar'=>'foo'},%w'foo baz'], [{'foo'=>'bar', 'baz'=>'foo'},{'foo'=>'[FILTERED]', 'baz'=>'[FILTERED]'},%w'foo baz'], [{'bar'=>{'foo'=>'bar','bar'=>'foo'}},{'bar'=>{'foo'=>'[FILTERED]','bar'=>'foo'}},%w'fo'], [{'foo'=>{'foo'=>'bar','bar'=>'foo'}},{'foo'=>'[FILTERED]'},%w'f banana'], [{'baz'=>[{'foo'=>'baz'}]}, {'baz'=>[{'foo'=>'[FILTERED]'}]}, %w(foo)], [{'baz'=>[{'foo'=>'baz'}, 1, 2, 3]}, {'baz'=>[{'foo'=>'[FILTERED]'}, 1, 2, 3]}, %w(foo)]] test_hashes.each do |before_filter, after_filter, filter_words| FilterParamController.filter_parameter_logging(*filter_words) assert_equal after_filter, @controller.__send__(:filter_parameters, before_filter) filter_words.push('blah') FilterParamController.filter_parameter_logging(*filter_words) do |key, value| value.reverse! if key =~ /bargain/ end before_filter['barg'] = {'bargain'=>'gain', 'blah'=>'bar', 'bar'=>{'bargain'=>{'blah'=>'foo'}}} after_filter['barg'] = {'bargain'=>'niag', 'blah'=>'[FILTERED]', 'bar'=>{'bargain'=>{'blah'=>'[FILTERED]'}}} assert_equal after_filter, @controller.__send__(:filter_parameters, before_filter) end end def test_filter_parameters_is_protected FilterParamController.filter_parameter_logging(:foo) assert !FilterParamController.action_methods.include?('filter_parameters') assert_raise(NoMethodError) { @controller.filter_parameters([{'password' => '[FILTERED]'}]) } end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/layout_test.rb
provider/vendor/rails/actionpack/test/controller/layout_test.rb
require 'abstract_unit' # The view_paths array must be set on Base and not LayoutTest so that LayoutTest's inherited # method has access to the view_paths array when looking for a layout to automatically assign. old_load_paths = ActionController::Base.view_paths ActionView::Template::register_template_handler :mab, lambda { |template| template.source.inspect } ActionController::Base.view_paths = [ File.dirname(__FILE__) + '/../fixtures/layout_tests/' ] class LayoutTest < ActionController::Base def self.controller_path; 'views' end self.view_paths = ActionController::Base.view_paths.dup end # Restore view_paths to previous value ActionController::Base.view_paths = old_load_paths class ProductController < LayoutTest end class ItemController < LayoutTest end class ThirdPartyTemplateLibraryController < LayoutTest end module ControllerNameSpace end class ControllerNameSpace::NestedController < LayoutTest end class MultipleExtensions < LayoutTest end class LayoutAutoDiscoveryTest < ActionController::TestCase def setup @request.host = "www.nextangle.com" end def test_application_layout_is_default_when_no_controller_match @controller = ProductController.new get :hello assert_equal 'layout_test.rhtml hello.rhtml', @response.body end def test_controller_name_layout_name_match @controller = ItemController.new get :hello assert_equal 'item.rhtml hello.rhtml', @response.body end def test_third_party_template_library_auto_discovers_layout @controller = ThirdPartyTemplateLibraryController.new get :hello assert_equal 'layouts/third_party_template_library.mab', @controller.active_layout.to_s assert_equal 'layouts/third_party_template_library', @response.layout assert_response :success assert_equal 'Mab', @response.body end def test_namespaced_controllers_auto_detect_layouts @controller = ControllerNameSpace::NestedController.new get :hello assert_equal 'layouts/controller_name_space/nested', @controller.active_layout.to_s assert_equal 'controller_name_space/nested.rhtml hello.rhtml', @response.body end def test_namespaced_controllers_auto_detect_layouts @controller = MultipleExtensions.new get :hello assert_equal 'layouts/multiple_extensions.html.erb', @controller.active_layout.to_s assert_equal 'multiple_extensions.html.erb hello.rhtml', @response.body.strip end end class DefaultLayoutController < LayoutTest end class AbsolutePathLayoutController < LayoutTest layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test.rhtml') end class HasOwnLayoutController < LayoutTest layout 'item' end class PrependsViewPathController < LayoutTest def hello prepend_view_path File.dirname(__FILE__) + '/../fixtures/layout_tests/alt/' render :layout => 'alt' end end class SetsLayoutInRenderController < LayoutTest def hello render :layout => 'third_party_template_library' end end class RendersNoLayoutController < LayoutTest def hello render :layout => false end end class LayoutSetInResponseTest < ActionController::TestCase def test_layout_set_when_using_default_layout @controller = DefaultLayoutController.new get :hello assert_equal 'layouts/layout_test', @response.layout end def test_layout_set_when_set_in_controller @controller = HasOwnLayoutController.new get :hello assert_equal 'layouts/item', @response.layout end def test_layout_set_when_using_render @controller = SetsLayoutInRenderController.new get :hello assert_equal 'layouts/third_party_template_library', @response.layout end def test_layout_is_not_set_when_none_rendered @controller = RendersNoLayoutController.new get :hello assert_nil @response.layout end def test_exempt_from_layout_honored_by_render_template ActionController::Base.exempt_from_layout :rhtml @controller = RenderWithTemplateOptionController.new get :hello assert_equal "alt/hello.rhtml", @response.body.strip ensure ActionController::Base.exempt_from_layout.delete(/\.rhtml$/) end def test_layout_is_picked_from_the_controller_instances_view_path @controller = PrependsViewPathController.new get :hello assert_equal 'layouts/alt', @response.layout end def test_absolute_pathed_layout @controller = AbsolutePathLayoutController.new get :hello assert_equal "layout_test.rhtml hello.rhtml", @response.body.strip end end class RenderWithTemplateOptionController < LayoutTest def hello render :template => 'alt/hello' end end class SetsNonExistentLayoutFile < LayoutTest layout "nofile.rhtml" end class LayoutExceptionRaised < ActionController::TestCase def test_exception_raised_when_layout_file_not_found @controller = SetsNonExistentLayoutFile.new get :hello assert_kind_of ActionView::MissingTemplate, @response.template.instance_eval { @exception } end end class LayoutStatusIsRendered < LayoutTest def hello render :status => 401 end end class LayoutStatusIsRenderedTest < ActionController::TestCase def test_layout_status_is_rendered @controller = LayoutStatusIsRendered.new get :hello assert_response 401 end end unless RUBY_PLATFORM =~ /(:?mswin|mingw|bccwin)/ class LayoutSymlinkedTest < LayoutTest layout "symlinked/symlinked_layout" end class LayoutSymlinkedIsRenderedTest < ActionController::TestCase def test_symlinked_layout_is_rendered @controller = LayoutSymlinkedTest.new get :hello assert_response 200 assert_equal "layouts/symlinked/symlinked_layout", @response.layout end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/action_pack_assertions_test.rb
provider/vendor/rails/actionpack/test/controller/action_pack_assertions_test.rb
require 'abstract_unit' # a controller class to facilitate the tests class ActionPackAssertionsController < ActionController::Base # this does absolutely nothing def nothing() head :ok end # a standard template def hello_world() render :template => "test/hello_world"; end # a standard template def hello_xml_world() render :template => "test/hello_xml_world"; end # a standard partial def partial() render :partial => 'test/partial'; end # a redirect to an internal location def redirect_internal() redirect_to "/nothing"; end def redirect_to_action() redirect_to :action => "flash_me", :id => 1, :params => { "panda" => "fun" }; end def redirect_to_controller() redirect_to :controller => "elsewhere", :action => "flash_me"; end def redirect_to_controller_with_symbol() redirect_to :controller => :elsewhere, :action => :flash_me; end def redirect_to_path() redirect_to '/some/path' end def redirect_to_named_route() redirect_to route_one_url end # a redirect to an external location def redirect_external() redirect_to "http://www.rubyonrails.org"; end # a 404 def response404() head '404 AWOL' end # a 500 def response500() head '500 Sorry' end # a fictional 599 def response599() head '599 Whoah!' end # putting stuff in the flash def flash_me flash['hello'] = 'my name is inigo montoya...' render :text => "Inconceivable!" end # we have a flash, but nothing is in it def flash_me_naked flash.clear render :text => "wow!" end # assign some template instance variables def assign_this @howdy = "ho" render :inline => "Mr. Henke" end def render_based_on_parameters render :text => "Mr. #{params[:name]}" end def render_url render :text => "<div>#{url_for(:action => 'flash_me', :only_path => true)}</div>" end def render_text_with_custom_content_type render :text => "Hello!", :content_type => Mime::RSS end # puts something in the session def session_stuffing session['xmas'] = 'turkey' render :text => "ho ho ho" end # raises exception on get requests def raise_on_get raise "get" if request.get? render :text => "request method: #{request.env['REQUEST_METHOD']}" end # raises exception on post requests def raise_on_post raise "post" if request.post? render :text => "request method: #{request.env['REQUEST_METHOD']}" end def get_valid_record @record = Class.new do def valid? true end def errors Class.new do def full_messages; []; end end.new end end.new render :nothing => true end def get_invalid_record @record = Class.new do def valid? false end def errors Class.new do def full_messages; ['...stuff...']; end end.new end end.new render :nothing => true end # 911 def rescue_action(e) raise; end end # Used to test that assert_response includes the exception message # in the failure message when an action raises and assert_response # is expecting something other than an error. class AssertResponseWithUnexpectedErrorController < ActionController::Base def index raise 'FAIL' end def show render :text => "Boom", :status => 500 end end class UserController < ActionController::Base end module Admin class InnerModuleController < ActionController::Base def index render :nothing => true end def redirect_to_index redirect_to admin_inner_module_path end def redirect_to_absolute_controller redirect_to :controller => '/content' end def redirect_to_fellow_controller redirect_to :controller => 'user' end def redirect_to_top_level_named_route redirect_to top_level_url(:id => "foo") end end end # a test case to exercise the new capabilities TestRequest & TestResponse class ActionPackAssertionsControllerTest < ActionController::TestCase # let's get this party started def setup ActionController::Routing::Routes.reload ActionController::Routing.use_controllers!(%w(action_pack_assertions admin/inner_module user content admin/user)) end def teardown ActionController::Routing::Routes.reload end # -- assertion-based testing ------------------------------------------------ def test_assert_tag_and_url_for get :render_url assert_tag :content => "/action_pack_assertions/flash_me" end # test the get method, make sure the request really was a get def test_get assert_raise(RuntimeError) { get :raise_on_get } get :raise_on_post assert_equal @response.body, 'request method: GET' end # test the get method, make sure the request really was a get def test_post assert_raise(RuntimeError) { post :raise_on_post } post :raise_on_get assert_equal @response.body, 'request method: POST' end # the following test fails because the request_method is now cached on the request instance # test the get/post switch within one test action # def test_get_post_switch # post :raise_on_get # assert_equal @response.body, 'request method: POST' # get :raise_on_post # assert_equal @response.body, 'request method: GET' # post :raise_on_get # assert_equal @response.body, 'request method: POST' # get :raise_on_post # assert_equal @response.body, 'request method: GET' # end # test the redirection to a named route def test_assert_redirect_to_named_route with_routing do |set| set.draw do |map| map.route_one 'route_one', :controller => 'action_pack_assertions', :action => 'nothing' map.connect ':controller/:action/:id' end set.install_helpers process :redirect_to_named_route assert_redirected_to 'http://test.host/route_one' assert_redirected_to route_one_url end end def test_assert_redirect_to_named_route_failure with_routing do |set| set.draw do |map| map.route_one 'route_one', :controller => 'action_pack_assertions', :action => 'nothing', :id => 'one' map.route_two 'route_two', :controller => 'action_pack_assertions', :action => 'nothing', :id => 'two' map.connect ':controller/:action/:id' end process :redirect_to_named_route assert_raise(ActiveSupport::TestCase::Assertion) do assert_redirected_to 'http://test.host/route_two' end assert_raise(ActiveSupport::TestCase::Assertion) do assert_redirected_to :controller => 'action_pack_assertions', :action => 'nothing', :id => 'two' end assert_raise(ActiveSupport::TestCase::Assertion) do assert_redirected_to route_two_url end end end def test_assert_redirect_to_nested_named_route with_routing do |set| set.draw do |map| map.admin_inner_module 'admin/inner_module', :controller => 'admin/inner_module', :action => 'index' map.connect ':controller/:action/:id' end @controller = Admin::InnerModuleController.new process :redirect_to_index # redirection is <{"action"=>"index", "controller"=>"admin/admin/inner_module"}> assert_redirected_to admin_inner_module_path end end def test_assert_redirected_to_top_level_named_route_from_nested_controller with_routing do |set| set.draw do |map| map.top_level '/action_pack_assertions/:id', :controller => 'action_pack_assertions', :action => 'index' map.connect ':controller/:action/:id' end @controller = Admin::InnerModuleController.new process :redirect_to_top_level_named_route # assert_redirected_to "http://test.host/action_pack_assertions/foo" would pass because of exact match early return assert_redirected_to "/action_pack_assertions/foo" end end def test_assert_redirected_to_top_level_named_route_with_same_controller_name_in_both_namespaces with_routing do |set| set.draw do |map| # this controller exists in the admin namespace as well which is the only difference from previous test map.top_level '/user/:id', :controller => 'user', :action => 'index' map.connect ':controller/:action/:id' end @controller = Admin::InnerModuleController.new process :redirect_to_top_level_named_route # assert_redirected_to top_level_url('foo') would pass because of exact match early return assert_redirected_to top_level_path('foo') end end # -- standard request/response object testing -------------------------------- # make sure that the template objects exist def test_template_objects_alive process :assign_this assert !@response.has_template_object?('hi') assert @response.has_template_object?('howdy') end # make sure we don't have template objects when we shouldn't def test_template_object_missing process :nothing assert_nil @response.template_objects['howdy'] end # check the empty flashing def test_flash_me_naked process :flash_me_naked assert !@response.has_flash? assert !@response.has_flash_with_contents? end # check if we have flash objects def test_flash_haves process :flash_me assert @response.has_flash? assert @response.has_flash_with_contents? assert @response.has_flash_object?('hello') end # ensure we don't have flash objects def test_flash_have_nots process :nothing assert !@response.has_flash? assert !@response.has_flash_with_contents? assert_nil @response.flash['hello'] end # check if we were rendered by a file-based template? def test_rendered_action process :nothing assert_nil @response.rendered[:template] process :hello_world assert @response.rendered[:template] assert 'hello_world', @response.rendered[:template].to_s end def test_assert_template_with_partial get :partial assert_template :partial => '_partial' end def test_assert_template_with_nil get :nothing assert_template nil end def test_assert_template_with_string get :hello_world assert_template 'hello_world' end def test_assert_template_with_symbol get :hello_world assert_template :hello_world end def test_assert_template_with_bad_argument assert_raise(ArgumentError) { assert_template 1 } end # check the redirection location def test_redirection_location process :redirect_internal assert_equal 'http://test.host/nothing', @response.redirect_url process :redirect_external assert_equal 'http://www.rubyonrails.org', @response.redirect_url end def test_no_redirect_url process :nothing assert_nil @response.redirect_url end # check server errors def test_server_error_response_code process :response500 assert @response.server_error? process :response599 assert @response.server_error? process :response404 assert !@response.server_error? end # check a 404 response code def test_missing_response_code process :response404 assert @response.missing? end # check client errors def test_client_error_response_code process :response404 assert @response.client_error? end # check to see if our redirection matches a pattern def test_redirect_url_match process :redirect_external assert @response.redirect? assert @response.redirect_url_match?("rubyonrails") assert @response.redirect_url_match?(/rubyonrails/) assert !@response.redirect_url_match?("phpoffrails") assert !@response.redirect_url_match?(/perloffrails/) end # check for a redirection def test_redirection process :redirect_internal assert @response.redirect? process :redirect_external assert @response.redirect? process :nothing assert !@response.redirect? end # check a successful response code def test_successful_response_code process :nothing assert @response.success? end # a basic check to make sure we have a TestResponse object def test_has_response process :nothing assert_kind_of ActionController::TestResponse, @response end def test_render_based_on_parameters process :render_based_on_parameters, "name" => "David" assert_equal "Mr. David", @response.body end def test_assert_redirection_fails_with_incorrect_controller process :redirect_to_controller assert_raise(ActiveSupport::TestCase::Assertion) do assert_redirected_to :controller => "action_pack_assertions", :action => "flash_me" end end def test_assert_redirection_with_extra_controller_option get :redirect_to_action assert_redirected_to :controller => 'action_pack_assertions', :action => "flash_me", :id => 1, :params => { :panda => 'fun' } end def test_redirected_to_url_leading_slash process :redirect_to_path assert_redirected_to '/some/path' end def test_redirected_to_url_no_leadling_slash process :redirect_to_path assert_redirected_to 'some/path' end def test_redirected_to_url_full_url process :redirect_to_path assert_redirected_to 'http://test.host/some/path' end def test_assert_redirection_with_symbol process :redirect_to_controller_with_symbol assert_nothing_raised { assert_redirected_to :controller => "elsewhere", :action => "flash_me" } process :redirect_to_controller_with_symbol assert_nothing_raised { assert_redirected_to :controller => :elsewhere, :action => :flash_me } end def test_redirected_to_with_nested_controller @controller = Admin::InnerModuleController.new get :redirect_to_absolute_controller assert_redirected_to :controller => '/content' get :redirect_to_fellow_controller assert_redirected_to :controller => 'admin/user' end def test_assert_valid get :get_valid_record assert_deprecated { assert_valid assigns('record') } end def test_assert_valid_failing get :get_invalid_record begin assert_deprecated { assert_valid assigns('record') } assert false rescue ActiveSupport::TestCase::Assertion => e end end def test_assert_response_uses_exception_message @controller = AssertResponseWithUnexpectedErrorController.new get :index assert_response :success flunk 'Expected non-success response' rescue ActiveSupport::TestCase::Assertion => e assert e.message.include?('FAIL') end def test_assert_response_failure_response_with_no_exception @controller = AssertResponseWithUnexpectedErrorController.new get :show assert_response :success flunk 'Expected non-success response' rescue ActiveSupport::TestCase::Assertion # success rescue flunk "assert_response failed to handle failure response with missing, but optional, exception." end end class ActionPackHeaderTest < ActionController::TestCase tests ActionPackAssertionsController def test_rendering_xml_sets_content_type process :hello_xml_world assert_equal('application/xml; charset=utf-8', @response.headers['Content-Type']) end def test_rendering_xml_respects_content_type @response.headers['type'] = 'application/pdf' process :hello_xml_world assert_equal('application/pdf; charset=utf-8', @response.headers['Content-Type']) end def test_render_text_with_custom_content_type get :render_text_with_custom_content_type assert_equal 'application/rss+xml; charset=utf-8', @response.headers['Content-Type'] end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/redirect_test.rb
provider/vendor/rails/actionpack/test/controller/redirect_test.rb
require 'abstract_unit' class WorkshopsController < ActionController::Base end class Workshop attr_accessor :id, :new_record def initialize(id, new_record) @id, @new_record = id, new_record end def new_record? @new_record end def to_s id.to_s end end class RedirectController < ActionController::Base def simple_redirect redirect_to :action => "hello_world" end def redirect_with_status redirect_to({:action => "hello_world", :status => 301}) end def redirect_with_status_hash redirect_to({:action => "hello_world"}, {:status => 301}) end def url_redirect_with_status redirect_to("http://www.example.com", :status => :moved_permanently) end def url_redirect_with_status_hash redirect_to("http://www.example.com", {:status => 301}) end def relative_url_redirect_with_status redirect_to("/things/stuff", :status => :found) end def relative_url_redirect_with_status_hash redirect_to("/things/stuff", {:status => 301}) end def redirect_to_back_with_status redirect_to :back, :status => 307 end def host_redirect redirect_to :action => "other_host", :only_path => false, :host => 'other.test.host' end def module_redirect redirect_to :controller => 'module_test/module_redirect', :action => "hello_world" end def redirect_with_assigns @hello = "world" redirect_to :action => "hello_world" end def redirect_to_url redirect_to "http://www.rubyonrails.org/" end def redirect_to_url_with_unescaped_query_string redirect_to "http://dev.rubyonrails.org/query?status=new" end def redirect_to_url_with_complex_scheme redirect_to "x-test+scheme.complex:redirect" end def redirect_to_back redirect_to :back end def redirect_to_existing_record redirect_to Workshop.new(5, false) end def redirect_to_new_record redirect_to Workshop.new(5, true) end def redirect_to_nil redirect_to nil end def rescue_errors(e) raise e end def rescue_action(e) raise end protected def dashbord_url(id, message) url_for :action => "dashboard", :params => { "id" => id, "message" => message } end end class RedirectTest < ActionController::TestCase tests RedirectController def test_simple_redirect get :simple_redirect assert_response :redirect assert_equal "http://test.host/redirect/hello_world", redirect_to_url end def test_redirect_with_no_status get :simple_redirect assert_response 302 assert_equal "http://test.host/redirect/hello_world", redirect_to_url end def test_redirect_with_status get :redirect_with_status assert_response 301 assert_equal "http://test.host/redirect/hello_world", redirect_to_url end def test_redirect_with_status_hash get :redirect_with_status_hash assert_response 301 assert_equal "http://test.host/redirect/hello_world", redirect_to_url end def test_url_redirect_with_status get :url_redirect_with_status assert_response 301 assert_equal "http://www.example.com", redirect_to_url end def test_url_redirect_with_status_hash get :url_redirect_with_status_hash assert_response 301 assert_equal "http://www.example.com", redirect_to_url end def test_relative_url_redirect_with_status get :relative_url_redirect_with_status assert_response 302 assert_equal "http://test.host/things/stuff", redirect_to_url end def test_relative_url_redirect_with_status_hash get :relative_url_redirect_with_status_hash assert_response 301 assert_equal "http://test.host/things/stuff", redirect_to_url end def test_redirect_to_back_with_status @request.env["HTTP_REFERER"] = "http://www.example.com/coming/from" get :redirect_to_back_with_status assert_response 307 assert_equal "http://www.example.com/coming/from", redirect_to_url end def test_simple_redirect_using_options get :host_redirect assert_response :redirect assert_redirected_to :action => "other_host", :only_path => false, :host => 'other.test.host' end def test_module_redirect get :module_redirect assert_response :redirect assert_redirected_to "http://test.host/module_test/module_redirect/hello_world" end def test_module_redirect_using_options get :module_redirect assert_response :redirect assert_redirected_to :controller => 'module_test/module_redirect', :action => 'hello_world' end def test_redirect_with_assigns get :redirect_with_assigns assert_response :redirect assert_equal "world", assigns["hello"] end def test_redirect_to_url get :redirect_to_url assert_response :redirect assert_redirected_to "http://www.rubyonrails.org/" end def test_redirect_to_url_with_unescaped_query_string get :redirect_to_url_with_unescaped_query_string assert_response :redirect assert_redirected_to "http://dev.rubyonrails.org/query?status=new" end def test_redirect_to_url_with_complex_scheme get :redirect_to_url_with_complex_scheme assert_response :redirect assert_equal "x-test+scheme.complex:redirect", redirect_to_url end def test_redirect_to_back @request.env["HTTP_REFERER"] = "http://www.example.com/coming/from" get :redirect_to_back assert_response :redirect assert_equal "http://www.example.com/coming/from", redirect_to_url end def test_redirect_to_back_with_no_referer assert_raise(ActionController::RedirectBackError) { @request.env["HTTP_REFERER"] = nil get :redirect_to_back } end def test_redirect_to_record ActionController::Routing::Routes.draw do |map| map.resources :workshops map.connect ':controller/:action/:id' end get :redirect_to_existing_record assert_equal "http://test.host/workshops/5", redirect_to_url assert_redirected_to Workshop.new(5, false) get :redirect_to_new_record assert_equal "http://test.host/workshops", redirect_to_url assert_redirected_to Workshop.new(5, true) end def test_redirect_with_partial_params get :module_redirect assert_deprecated(/test_redirect_with_partial_params/) do assert_redirected_to :action => 'hello_world' end end def test_redirect_to_nil assert_raise(ActionController::ActionControllerError) do get :redirect_to_nil end end end module ModuleTest class ModuleRedirectController < ::RedirectController def module_redirect redirect_to :controller => '/redirect', :action => "hello_world" end end class ModuleRedirectTest < ActionController::TestCase tests ModuleRedirectController def test_simple_redirect get :simple_redirect assert_response :redirect assert_equal "http://test.host/module_test/module_redirect/hello_world", redirect_to_url end def test_simple_redirect_using_options get :host_redirect assert_response :redirect assert_redirected_to :action => "other_host", :only_path => false, :host => 'other.test.host' end def test_module_redirect get :module_redirect assert_response :redirect assert_equal "http://test.host/redirect/hello_world", redirect_to_url end def test_module_redirect_using_options get :module_redirect assert_response :redirect assert_redirected_to :controller => '/redirect', :action => "hello_world" end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/record_identifier_test.rb
provider/vendor/rails/actionpack/test/controller/record_identifier_test.rb
require 'abstract_unit' class Comment attr_reader :id def save; @id = 1 end def new_record?; @id.nil? end def name @id.nil? ? 'new comment' : "comment ##{@id}" end end class Comment::Nested < Comment; end class Test::Unit::TestCase protected def comments_url 'http://www.example.com/comments' end def comment_url(comment) "http://www.example.com/comments/#{comment.id}" end end class RecordIdentifierTest < Test::Unit::TestCase include ActionController::RecordIdentifier def setup @klass = Comment @record = @klass.new @singular = 'comment' @plural = 'comments' end def test_dom_id_with_new_record assert_equal "new_#{@singular}", dom_id(@record) end def test_dom_id_with_new_record_and_prefix assert_equal "custom_prefix_#{@singular}", dom_id(@record, :custom_prefix) end def test_dom_id_with_saved_record @record.save assert_equal "#{@singular}_1", dom_id(@record) end def test_dom_id_with_prefix @record.save assert_equal "edit_#{@singular}_1", dom_id(@record, :edit) end def test_partial_path expected = "#{@plural}/#{@singular}" assert_equal expected, partial_path(@record) assert_equal expected, partial_path(Comment) end def test_partial_path_with_namespaced_controller_path expected = "admin/#{@plural}/#{@singular}" assert_equal expected, partial_path(@record, "admin/posts") assert_equal expected, partial_path(@klass, "admin/posts") end def test_partial_path_with_not_namespaced_controller_path expected = "#{@plural}/#{@singular}" assert_equal expected, partial_path(@record, "posts") assert_equal expected, partial_path(@klass, "posts") end def test_dom_class assert_equal @singular, dom_class(@record) end def test_dom_class_with_prefix assert_equal "custom_prefix_#{@singular}", dom_class(@record, :custom_prefix) end def test_singular_class_name assert_equal @singular, singular_class_name(@record) end def test_singular_class_name_for_class assert_equal @singular, singular_class_name(@klass) end def test_plural_class_name assert_equal @plural, plural_class_name(@record) end def test_plural_class_name_for_class assert_equal @plural, plural_class_name(@klass) end private def method_missing(method, *args) RecordIdentifier.send(method, *args) end end class NestedRecordIdentifierTest < RecordIdentifierTest def setup @klass = Comment::Nested @record = @klass.new @singular = 'comment_nested' @plural = 'comment_nesteds' end def test_partial_path expected = "comment/nesteds/nested" assert_equal expected, partial_path(@record) assert_equal expected, partial_path(Comment::Nested) end def test_partial_path_with_namespaced_controller_path expected = "admin/comment/nesteds/nested" assert_equal expected, partial_path(@record, "admin/posts") assert_equal expected, partial_path(@klass, "admin/posts") end def test_partial_path_with_deeper_namespaced_controller_path expected = "deeper/admin/comment/nesteds/nested" assert_equal expected, partial_path(@record, "deeper/admin/posts") assert_equal expected, partial_path(@klass, "deeper/admin/posts") end def test_partial_path_with_even_deeper_namespaced_controller_path expected = "even/more/deeper/admin/comment/nesteds/nested" assert_equal expected, partial_path(@record, "even/more/deeper/admin/posts") assert_equal expected, partial_path(@klass, "even/more/deeper/admin/posts") end def test_partial_path_with_not_namespaced_controller_path expected = "comment/nesteds/nested" assert_equal expected, partial_path(@record, "posts") assert_equal expected, partial_path(@klass, "posts") end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/rescue_test.rb
provider/vendor/rails/actionpack/test/controller/rescue_test.rb
require 'abstract_unit' class RescueController < ActionController::Base class NotAuthorized < StandardError end class NotAuthorizedToRescueAsString < StandardError end class RecordInvalid < StandardError end class RecordInvalidToRescueAsString < StandardError end class NotAllowed < StandardError end class NotAllowedToRescueAsString < StandardError end class InvalidRequest < StandardError end class InvalidRequestToRescueAsString < StandardError end class BadGateway < StandardError end class BadGatewayToRescueAsString < StandardError end class ResourceUnavailable < StandardError end class ResourceUnavailableToRescueAsString < StandardError end # We use a fully-qualified name in some strings, and a relative constant # name in some other to test correct handling of both cases. rescue_from NotAuthorized, :with => :deny_access rescue_from 'RescueController::NotAuthorizedToRescueAsString', :with => :deny_access rescue_from RecordInvalid, :with => :show_errors rescue_from 'RescueController::RecordInvalidToRescueAsString', :with => :show_errors rescue_from NotAllowed, :with => proc { head :forbidden } rescue_from 'RescueController::NotAllowedToRescueAsString', :with => proc { head :forbidden } rescue_from InvalidRequest, :with => proc { |exception| render :text => exception.message } rescue_from 'InvalidRequestToRescueAsString', :with => proc { |exception| render :text => exception.message } rescue_from BadGateway do head :status => 502 end rescue_from 'BadGatewayToRescueAsString' do head :status => 502 end rescue_from ResourceUnavailable do |exception| render :text => exception.message end rescue_from 'ResourceUnavailableToRescueAsString' do |exception| render :text => exception.message end # This is a Dispatcher exception and should be in ApplicationController. rescue_from ActionController::RoutingError do render :text => 'no way' end before_filter(:only => :before_filter_raises) { raise 'umm nice' } def before_filter_raises end def raises render :text => 'already rendered' raise "don't panic!" end def method_not_allowed raise ActionController::MethodNotAllowed.new(:get, :head, :put) end def not_implemented raise ActionController::NotImplemented.new(:get, :put) end def not_authorized raise NotAuthorized end def not_authorized_raise_as_string raise NotAuthorizedToRescueAsString end def not_allowed raise NotAllowed end def not_allowed_raise_as_string raise NotAllowedToRescueAsString end def invalid_request raise InvalidRequest end def invalid_request_raise_as_string raise InvalidRequestToRescueAsString end def record_invalid raise RecordInvalid end def record_invalid_raise_as_string raise RecordInvalidToRescueAsString end def bad_gateway raise BadGateway end def bad_gateway_raise_as_string raise BadGatewayToRescueAsString end def resource_unavailable raise ResourceUnavailable end def resource_unavailable_raise_as_string raise ResourceUnavailableToRescueAsString end def missing_template end protected def deny_access head :forbidden end def show_errors(exception) head :unprocessable_entity end end class RescueControllerTest < ActionController::TestCase FIXTURE_PUBLIC = "#{File.dirname(__FILE__)}/../fixtures".freeze setup :set_all_requests_local setup :populate_exception_object def set_all_requests_local RescueController.consider_all_requests_local = true @request.remote_addr = '1.2.3.4' @request.host = 'example.com' end def populate_exception_object begin raise 'foo' rescue => @exception end end def test_rescue_exceptions_raised_by_filters with_rails_root FIXTURE_PUBLIC do with_all_requests_local false do get :before_filter_raises end end assert_response :internal_server_error end def test_rescue_action_locally_if_all_requests_local @controller.expects(:local_request?).never @controller.expects(:rescue_action_locally).with(@exception) @controller.expects(:rescue_action_in_public).never with_all_requests_local do @controller.send :rescue_action, @exception end end def test_rescue_action_locally_if_remote_addr_is_localhost @controller.expects(:local_request?).returns(true) @controller.expects(:rescue_action_locally).with(@exception) @controller.expects(:rescue_action_in_public).never with_all_requests_local false do @controller.send :rescue_action, @exception end end def test_rescue_action_in_public_otherwise @controller.expects(:local_request?).returns(false) @controller.expects(:rescue_action_locally).never @controller.expects(:rescue_action_in_public).with(@exception) with_all_requests_local false do @controller.send :rescue_action, @exception end end def test_rescue_action_in_public_with_localized_error_file # Change locale old_locale = I18n.locale I18n.locale = :da with_rails_root FIXTURE_PUBLIC do with_all_requests_local false do get :raises end end assert_response :internal_server_error body = File.read("#{FIXTURE_PUBLIC}/public/500.da.html") assert_equal body, @response.body ensure I18n.locale = old_locale end def test_rescue_action_in_public_with_error_file with_rails_root FIXTURE_PUBLIC do with_all_requests_local false do get :raises end end assert_response :internal_server_error body = File.read("#{FIXTURE_PUBLIC}/public/500.html") assert_equal body, @response.body end def test_rescue_action_in_public_without_error_file with_rails_root '/tmp' do with_all_requests_local false do get :raises end end assert_response :internal_server_error assert_equal ' ', @response.body end def test_rescue_unknown_action_in_public_with_error_file with_rails_root FIXTURE_PUBLIC do with_all_requests_local false do get :foobar_doesnt_exist end end assert_response :not_found body = File.read("#{FIXTURE_PUBLIC}/public/404.html") assert_equal body, @response.body end def test_rescue_unknown_action_in_public_without_error_file with_rails_root '/tmp' do with_all_requests_local false do get :foobar_doesnt_exist end end assert_response :not_found assert_equal ' ', @response.body end def test_rescue_missing_template_in_public with_rails_root FIXTURE_PUBLIC do with_all_requests_local true do get :missing_template end end assert_response :internal_server_error assert @response.body.include?('missing_template'), "Response should include the template name." end def test_rescue_action_locally get :raises assert_response :internal_server_error assert_template 'diagnostics.erb' assert @response.body.include?('RescueController#raises'), "Response should include controller and action." assert @response.body.include?("don't panic"), "Response should include exception message." end def test_local_request_when_remote_addr_is_localhost @controller.expects(:request).returns(@request).at_least_once with_remote_addr '127.0.0.1' do assert @controller.send(:local_request?) end end def test_local_request_when_remote_addr_isnt_locahost @controller.expects(:request).returns(@request) with_remote_addr '1.2.3.4' do assert !@controller.send(:local_request?) end end def test_rescue_responses responses = ActionController::Base.rescue_responses assert_equal ActionController::Rescue::DEFAULT_RESCUE_RESPONSE, responses.default assert_equal ActionController::Rescue::DEFAULT_RESCUE_RESPONSE, responses[Exception.new] assert_equal :not_found, responses[ActionController::RoutingError.name] assert_equal :not_found, responses[ActionController::UnknownAction.name] assert_equal :not_found, responses['ActiveRecord::RecordNotFound'] assert_equal :conflict, responses['ActiveRecord::StaleObjectError'] assert_equal :unprocessable_entity, responses['ActiveRecord::RecordInvalid'] assert_equal :unprocessable_entity, responses['ActiveRecord::RecordNotSaved'] assert_equal :method_not_allowed, responses['ActionController::MethodNotAllowed'] assert_equal :not_implemented, responses['ActionController::NotImplemented'] end def test_rescue_templates templates = ActionController::Base.rescue_templates assert_equal ActionController::Rescue::DEFAULT_RESCUE_TEMPLATE, templates.default assert_equal ActionController::Rescue::DEFAULT_RESCUE_TEMPLATE, templates[Exception.new] assert_equal 'missing_template', templates[ActionView::MissingTemplate.name] assert_equal 'routing_error', templates[ActionController::RoutingError.name] assert_equal 'unknown_action', templates[ActionController::UnknownAction.name] assert_equal 'template_error', templates[ActionView::TemplateError.name] end def test_not_implemented with_all_requests_local false do with_rails_public_path(".") do head :not_implemented end end assert_response :not_implemented assert_equal "GET, PUT", @response.headers['Allow'] end def test_method_not_allowed with_all_requests_local false do with_rails_public_path(".") do get :method_not_allowed end end assert_response :method_not_allowed assert_equal "GET, HEAD, PUT", @response.headers['Allow'] end def test_rescue_handler get :not_authorized assert_response :forbidden end def test_rescue_handler_string get :not_authorized_raise_as_string assert_response :forbidden end def test_rescue_handler_with_argument @controller.expects(:show_errors).once.with { |e| e.is_a?(Exception) } get :record_invalid end def test_rescue_handler_with_argument_as_string @controller.expects(:show_errors).once.with { |e| e.is_a?(Exception) } get :record_invalid_raise_as_string end def test_proc_rescue_handler get :not_allowed assert_response :forbidden end def test_proc_rescue_handler_as_string get :not_allowed_raise_as_string assert_response :forbidden end def test_proc_rescue_handle_with_argument get :invalid_request assert_equal "RescueController::InvalidRequest", @response.body end def test_proc_rescue_handle_with_argument_as_string get :invalid_request_raise_as_string assert_equal "RescueController::InvalidRequestToRescueAsString", @response.body end def test_block_rescue_handler get :bad_gateway assert_response 502 end def test_block_rescue_handler_as_string get :bad_gateway_raise_as_string assert_response 502 end def test_block_rescue_handler_with_argument get :resource_unavailable assert_equal "RescueController::ResourceUnavailable", @response.body end def test_block_rescue_handler_with_argument_as_string get :resource_unavailable_raise_as_string assert_equal "RescueController::ResourceUnavailableToRescueAsString", @response.body end def test_rescue_dispatcher_exceptions env = @request.env env["action_controller.rescue.request"] = @request env["action_controller.rescue.response"] = @response RescueController.call_with_exception(env, ActionController::RoutingError.new("Route not found")) assert_equal "no way", @response.body end def test_rescue_dispatcher_exceptions_without_request_set @request.env['REQUEST_URI'] = '/no_way' response = RescueController.call_with_exception(@request.env, ActionController::RoutingError.new("Route not found")) assert_kind_of ActionController::Response, response assert_equal "no way", response.body end protected def with_all_requests_local(local = true) old_local, ActionController::Base.consider_all_requests_local = ActionController::Base.consider_all_requests_local, local yield ensure ActionController::Base.consider_all_requests_local = old_local end def with_remote_addr(addr) old_remote_addr, @request.remote_addr = @request.remote_addr, addr yield ensure @request.remote_addr = old_remote_addr end def with_rails_public_path(rails_root) old_rails = Object.const_get(:Rails) rescue nil mod = Object.const_set(:Rails, Module.new) (class << mod; self; end).instance_eval do define_method(:public_path) { "#{rails_root}/public" } end yield ensure Object.module_eval { remove_const(:Rails) } if defined?(Rails) Object.const_set(:Rails, old_rails) if old_rails end def with_rails_root(path = nil,&block) old_rails_root = RAILS_ROOT if defined?(RAILS_ROOT) if path silence_warnings { Object.const_set(:RAILS_ROOT, path) } else Object.remove_const(:RAILS_ROOT) rescue nil end with_rails_public_path(path, &block) ensure if old_rails_root silence_warnings { Object.const_set(:RAILS_ROOT, old_rails_root) } else Object.remove_const(:RAILS_ROOT) rescue nil end end end class ExceptionInheritanceRescueController < ActionController::Base class ParentException < StandardError end class ChildException < ParentException end class GrandchildException < ChildException end rescue_from ChildException, :with => lambda { head :ok } rescue_from ParentException, :with => lambda { head :created } rescue_from GrandchildException, :with => lambda { head :no_content } def raise_parent_exception raise ParentException end def raise_child_exception raise ChildException end def raise_grandchild_exception raise GrandchildException end end class ExceptionInheritanceRescueControllerTest < ActionController::TestCase def test_bottom_first get :raise_grandchild_exception assert_response :no_content end def test_inheritance_works get :raise_child_exception assert_response :created end end class ControllerInheritanceRescueController < ExceptionInheritanceRescueController class FirstExceptionInChildController < StandardError end class SecondExceptionInChildController < StandardError end rescue_from FirstExceptionInChildController, 'SecondExceptionInChildController', :with => lambda { head :gone } def raise_first_exception_in_child_controller raise FirstExceptionInChildController end def raise_second_exception_in_child_controller raise SecondExceptionInChildController end end class ControllerInheritanceRescueControllerTest < ActionController::TestCase def test_first_exception_in_child_controller get :raise_first_exception_in_child_controller assert_response :gone end def test_second_exception_in_child_controller get :raise_second_exception_in_child_controller assert_response :gone end def test_exception_in_parent_controller get :raise_parent_exception assert_response :created end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/caching_test.rb
provider/vendor/rails/actionpack/test/controller/caching_test.rb
require 'fileutils' require 'abstract_unit' require 'active_record_unit' CACHE_DIR = 'test_cache' # Don't change '/../temp/' cavalierly or you might hose something you don't want hosed FILE_STORE_PATH = File.join(File.dirname(__FILE__), '/../temp/', CACHE_DIR) ActionController::Base.page_cache_directory = FILE_STORE_PATH ActionController::Base.cache_store = :file_store, FILE_STORE_PATH # Force sweeper classes to load ActionController::Caching::Sweeper ActionController::Caching::Sweeping class PageCachingTestController < ActionController::Base caches_page :ok, :no_content, :if => Proc.new { |c| !c.request.format.json? } caches_page :found, :not_found def ok head :ok end def no_content head :no_content end def found redirect_to :action => 'ok' end def not_found head :not_found end def custom_path render :text => "Super soaker" cache_page("Super soaker", "/index.html") end def expire_custom_path expire_page("/index.html") head :ok end def trailing_slash render :text => "Sneak attack" end end class PageCachingTest < ActionController::TestCase def setup ActionController::Base.perform_caching = true ActionController::Routing::Routes.draw do |map| map.main '', :controller => 'posts', :format => nil map.formatted_posts 'posts.:format', :controller => 'posts' map.resources :posts map.connect ':controller/:action/:id' end @request = ActionController::TestRequest.new @request.host = 'hostname.com' @response = ActionController::TestResponse.new @controller = PageCachingTestController.new @params = {:controller => 'posts', :action => 'index', :only_path => true, :skip_relative_url_root => true} @rewriter = ActionController::UrlRewriter.new(@request, @params) FileUtils.rm_rf(File.dirname(FILE_STORE_PATH)) FileUtils.mkdir_p(FILE_STORE_PATH) end def teardown FileUtils.rm_rf(File.dirname(FILE_STORE_PATH)) ActionController::Routing::Routes.clear! ActionController::Base.perform_caching = false end def test_page_caching_resources_saves_to_correct_path_with_extension_even_if_default_route @params[:format] = 'rss' assert_equal '/posts.rss', @rewriter.rewrite(@params) @params[:format] = nil assert_equal '/', @rewriter.rewrite(@params) end def test_should_cache_get_with_ok_status get :ok assert_response :ok assert_page_cached :ok, "get with ok status should have been cached" end def test_should_cache_with_custom_path get :custom_path assert File.exist?("#{FILE_STORE_PATH}/index.html") end def test_should_expire_cache_with_custom_path get :custom_path assert File.exist?("#{FILE_STORE_PATH}/index.html") get :expire_custom_path assert !File.exist?("#{FILE_STORE_PATH}/index.html") end def test_should_cache_without_trailing_slash_on_url @controller.class.cache_page 'cached content', '/page_caching_test/trailing_slash' assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/trailing_slash.html") end def test_should_cache_with_trailing_slash_on_url @controller.class.cache_page 'cached content', '/page_caching_test/trailing_slash/' assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/trailing_slash.html") end def test_should_cache_ok_at_custom_path @request.stubs(:path).returns("/index.html") get :ok assert_response :ok assert File.exist?("#{FILE_STORE_PATH}/index.html") end [:ok, :no_content, :found, :not_found].each do |status| [:get, :post, :put, :delete].each do |method| unless method == :get and status == :ok define_method "test_shouldnt_cache_#{method}_with_#{status}_status" do send(method, status) assert_response status assert_page_not_cached status, "#{method} with #{status} status shouldn't have been cached" end end end end def test_page_caching_conditional_options get :ok, :format=>'json' assert_page_not_cached :ok end private def assert_page_cached(action, message = "#{action} should have been cached") assert page_cached?(action), message end def assert_page_not_cached(action, message = "#{action} shouldn't have been cached") assert !page_cached?(action), message end def page_cached?(action) File.exist? "#{FILE_STORE_PATH}/page_caching_test/#{action}.html" end end class ActionCachingTestController < ActionController::Base caches_action :index, :redirected, :forbidden, :if => Proc.new { |c| !c.request.format.json? }, :expires_in => 1.hour caches_action :show, :cache_path => 'http://test.host/custom/show' caches_action :edit, :cache_path => Proc.new { |c| c.params[:id] ? "http://test.host/#{c.params[:id]};edit" : "http://test.host/edit" } caches_action :with_layout caches_action :layout_false, :layout => false caches_action :record_not_found, :four_oh_four, :simple_runtime_error layout 'talk_from_action.erb' def index @cache_this = MockTime.now.to_f.to_s render :text => @cache_this end def redirected redirect_to :action => 'index' end def forbidden render :text => "Forbidden" response.status = "403 Forbidden" end def with_layout @cache_this = MockTime.now.to_f.to_s render :text => @cache_this, :layout => true end def record_not_found raise ActiveRecord::RecordNotFound, "oops!" end def four_oh_four render :text => "404'd!", :status => 404 end def simple_runtime_error raise "oops!" end alias_method :show, :index alias_method :edit, :index alias_method :destroy, :index alias_method :layout_false, :with_layout def expire expire_action :controller => 'action_caching_test', :action => 'index' render :nothing => true end def expire_xml expire_action :controller => 'action_caching_test', :action => 'index', :format => 'xml' render :nothing => true end end class MockTime < Time # Let Time spicy to assure that Time.now != Time.now def to_f super+rand end end class ActionCachingMockController attr_accessor :mock_url_for attr_accessor :mock_path def initialize yield self if block_given? end def url_for(*args) @mock_url_for end def request mocked_path = @mock_path Object.new.instance_eval(<<-EVAL) def path; '#{@mock_path}' end def format; 'all' end def cache_format; nil end self EVAL end end class ActionCacheTest < ActionController::TestCase def setup reset! FileUtils.mkdir_p(FILE_STORE_PATH) @path_class = ActionController::Caching::Actions::ActionCachePath @mock_controller = ActionCachingMockController.new end def teardown FileUtils.rm_rf(File.dirname(FILE_STORE_PATH)) end def test_simple_action_cache get :index cached_time = content_to_cache assert_equal cached_time, @response.body assert fragment_exist?('hostname.com/action_caching_test') reset! get :index assert_equal cached_time, @response.body end def test_simple_action_not_cached get :destroy cached_time = content_to_cache assert_equal cached_time, @response.body assert !fragment_exist?('hostname.com/action_caching_test/destroy') reset! get :destroy assert_not_equal cached_time, @response.body end def test_action_cache_with_layout get :with_layout cached_time = content_to_cache assert_not_equal cached_time, @response.body assert fragment_exist?('hostname.com/action_caching_test/with_layout') reset! get :with_layout assert_not_equal cached_time, @response.body assert_equal @response.body, read_fragment('hostname.com/action_caching_test/with_layout') end def test_action_cache_with_layout_and_layout_cache_false get :layout_false cached_time = content_to_cache assert_not_equal cached_time, @response.body assert fragment_exist?('hostname.com/action_caching_test/layout_false') reset! get :layout_false assert_not_equal cached_time, @response.body assert_equal cached_time, read_fragment('hostname.com/action_caching_test/layout_false') end def test_action_cache_conditional_options old_use_accept_header = ActionController::Base.use_accept_header ActionController::Base.use_accept_header = true @request.env['HTTP_ACCEPT'] = 'application/json' get :index assert !fragment_exist?('hostname.com/action_caching_test') ActionController::Base.use_accept_header = old_use_accept_header end def test_action_cache_with_store_options MockTime.expects(:now).returns(12345).once @controller.expects(:read_fragment).with('hostname.com/action_caching_test', :expires_in => 1.hour).once @controller.expects(:write_fragment).with('hostname.com/action_caching_test', '12345.0', :expires_in => 1.hour).once get :index end def test_action_cache_with_custom_cache_path get :show cached_time = content_to_cache assert_equal cached_time, @response.body assert fragment_exist?('test.host/custom/show') reset! get :show assert_equal cached_time, @response.body end def test_action_cache_with_custom_cache_path_in_block get :edit assert fragment_exist?('test.host/edit') reset! get :edit, :id => 1 assert fragment_exist?('test.host/1;edit') end def test_cache_expiration get :index cached_time = content_to_cache reset! get :index assert_equal cached_time, @response.body reset! get :expire reset! get :index new_cached_time = content_to_cache assert_not_equal cached_time, @response.body reset! get :index assert_response :success assert_equal new_cached_time, @response.body end def test_cache_expiration_isnt_affected_by_request_format get :index cached_time = content_to_cache reset! @request.set_REQUEST_URI "/action_caching_test/expire.xml" get :expire, :format => :xml reset! get :index new_cached_time = content_to_cache assert_not_equal cached_time, @response.body end def test_cache_is_scoped_by_subdomain @request.host = 'jamis.hostname.com' get :index jamis_cache = content_to_cache reset! @request.host = 'david.hostname.com' get :index david_cache = content_to_cache assert_not_equal jamis_cache, @response.body reset! @request.host = 'jamis.hostname.com' get :index assert_equal jamis_cache, @response.body reset! @request.host = 'david.hostname.com' get :index assert_equal david_cache, @response.body end def test_redirect_is_not_cached get :redirected assert_response :redirect reset! get :redirected assert_response :redirect end def test_forbidden_is_not_cached get :forbidden assert_response :forbidden reset! get :forbidden assert_response :forbidden end def test_xml_version_of_resource_is_treated_as_different_cache with_routing do |set| set.draw do |map| map.connect ':controller/:action.:format' map.connect ':controller/:action' end get :index, :format => 'xml' cached_time = content_to_cache assert_equal cached_time, @response.body assert fragment_exist?('hostname.com/action_caching_test/index.xml') reset! get :index, :format => 'xml' assert_equal cached_time, @response.body assert_equal 'application/xml', @response.content_type reset! get :expire_xml reset! get :index, :format => 'xml' assert_not_equal cached_time, @response.body end end def test_correct_content_type_is_returned_for_cache_hit # run it twice to cache it the first time get :index, :id => 'content-type.xml' get :index, :id => 'content-type.xml' assert_equal 'application/xml', @response.content_type end def test_correct_content_type_is_returned_for_cache_hit_on_action_with_string_key # run it twice to cache it the first time get :show, :format => 'xml' get :show, :format => 'xml' assert_equal 'application/xml', @response.content_type end def test_correct_content_type_is_returned_for_cache_hit_on_action_with_string_key_from_proc # run it twice to cache it the first time get :edit, :id => 1, :format => 'xml' get :edit, :id => 1, :format => 'xml' assert_equal 'application/xml', @response.content_type end def test_empty_path_is_normalized @mock_controller.mock_url_for = 'http://example.org/' @mock_controller.mock_path = '/' assert_equal 'example.org/index', @path_class.path_for(@mock_controller, {}) end def test_file_extensions get :index, :id => 'kitten.jpg' get :index, :id => 'kitten.jpg' assert_response :success end def test_record_not_found_returns_404_for_multiple_requests get :record_not_found assert_response 404 get :record_not_found assert_response 404 end def test_four_oh_four_returns_404_for_multiple_requests get :four_oh_four assert_response 404 get :four_oh_four assert_response 404 end def test_simple_runtime_error_returns_500_for_multiple_requests get :simple_runtime_error assert_response 500 get :simple_runtime_error assert_response 500 end private def content_to_cache assigns(:cache_this) end def reset! @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @controller = ActionCachingTestController.new @request.host = 'hostname.com' end def fragment_exist?(path) @controller.fragment_exist?(path) end def read_fragment(path) @controller.read_fragment(path) end end class FragmentCachingTestController < ActionController::Base def some_action; end; end class FragmentCachingTest < ActionController::TestCase def setup ActionController::Base.perform_caching = true @store = ActiveSupport::Cache::MemoryStore.new ActionController::Base.cache_store = @store @controller = FragmentCachingTestController.new @params = {:controller => 'posts', :action => 'index'} @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @controller.params = @params @controller.request = @request @controller.response = @response @controller.send(:initialize_current_url) @controller.send(:initialize_template_class, @response) @controller.send(:assign_shortcuts, @request, @response) end def test_fragment_cache_key assert_equal 'views/what a key', @controller.fragment_cache_key('what a key') assert_equal "views/test.host/fragment_caching_test/some_action", @controller.fragment_cache_key(:controller => 'fragment_caching_test',:action => 'some_action') end def test_read_fragment_with_caching_enabled @store.write('views/name', 'value') assert_equal 'value', @controller.read_fragment('name') end def test_read_fragment_with_caching_disabled ActionController::Base.perform_caching = false @store.write('views/name', 'value') assert_nil @controller.read_fragment('name') end def test_fragment_exist_with_caching_enabled @store.write('views/name', 'value') assert @controller.fragment_exist?('name') assert !@controller.fragment_exist?('other_name') end def test_fragment_exist_with_caching_disabled ActionController::Base.perform_caching = false @store.write('views/name', 'value') assert !@controller.fragment_exist?('name') assert !@controller.fragment_exist?('other_name') end def test_write_fragment_with_caching_enabled assert_nil @store.read('views/name') assert_equal 'value', @controller.write_fragment('name', 'value') assert_equal 'value', @store.read('views/name') end def test_write_fragment_with_caching_disabled assert_nil @store.read('views/name') ActionController::Base.perform_caching = false assert_equal 'value', @controller.write_fragment('name', 'value') assert_nil @store.read('views/name') end def test_expire_fragment_with_simple_key @store.write('views/name', 'value') @controller.expire_fragment 'name' assert_nil @store.read('views/name') end def test_expire_fragment_with_regexp @store.write('views/name', 'value') @store.write('views/another_name', 'another_value') @store.write('views/primalgrasp', 'will not expire ;-)') @controller.expire_fragment /name/ assert_nil @store.read('views/name') assert_nil @store.read('views/another_name') assert_equal 'will not expire ;-)', @store.read('views/primalgrasp') end def test_fragment_for_with_disabled_caching ActionController::Base.perform_caching = false @store.write('views/expensive', 'fragment content') fragment_computed = false buffer = 'generated till now -> ' @controller.fragment_for(buffer, 'expensive') { fragment_computed = true } assert fragment_computed assert_equal 'generated till now -> ', buffer end def test_fragment_for @store.write('views/expensive', 'fragment content') fragment_computed = false buffer = 'generated till now -> ' @controller.fragment_for(buffer, 'expensive') { fragment_computed = true } assert !fragment_computed assert_equal 'generated till now -> fragment content', buffer end end class FunctionalCachingController < ActionController::Base def fragment_cached end def html_fragment_cached_with_partial respond_to do |format| format.html end end def js_fragment_cached_with_partial respond_to do |format| format.js end end def formatted_fragment_cached respond_to do |format| format.html format.xml format.js end end def rescue_action(e) raise e end end class FunctionalFragmentCachingTest < ActionController::TestCase def setup ActionController::Base.perform_caching = true @store = ActiveSupport::Cache::MemoryStore.new ActionController::Base.cache_store = @store @controller = FunctionalCachingController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new end def test_fragment_caching get :fragment_cached assert_response :success expected_body = <<-CACHED Hello This bit's fragment cached CACHED assert_equal expected_body, @response.body assert_equal "This bit's fragment cached", @store.read('views/test.host/functional_caching/fragment_cached') end def test_fragment_caching_in_partials get :html_fragment_cached_with_partial assert_response :success assert_match /Fragment caching in a partial/, @response.body assert_match "Fragment caching in a partial", @store.read('views/test.host/functional_caching/html_fragment_cached_with_partial') end def test_render_inline_before_fragment_caching get :inline_fragment_cached assert_response :success assert_match /Some inline content/, @response.body assert_match /Some cached content/, @response.body assert_match "Some cached content", @store.read('views/test.host/functional_caching/inline_fragment_cached') end def test_fragment_caching_in_rjs_partials xhr :get, :js_fragment_cached_with_partial assert_response :success assert_match /Fragment caching in a partial/, @response.body assert_match "Fragment caching in a partial", @store.read('views/test.host/functional_caching/js_fragment_cached_with_partial') end def test_html_formatted_fragment_caching get :formatted_fragment_cached, :format => "html" assert_response :success expected_body = "<body>\n<p>ERB</p>\n</body>" assert_equal expected_body, @response.body assert_equal "<p>ERB</p>", @store.read('views/test.host/functional_caching/formatted_fragment_cached') end def test_xml_formatted_fragment_caching get :formatted_fragment_cached, :format => "xml" assert_response :success expected_body = "<body>\n <p>Builder</p>\n</body>\n" assert_equal expected_body, @response.body assert_equal " <p>Builder</p>\n", @store.read('views/test.host/functional_caching/formatted_fragment_cached') end def test_js_formatted_fragment_caching get :formatted_fragment_cached, :format => "js" assert_response :success expected_body = %(title = "Hey";\n$("element_1").visualEffect("highlight");\n) + %($("element_2").visualEffect("highlight");\nfooter = "Bye";) assert_equal expected_body, @response.body assert_equal ['$("element_1").visualEffect("highlight");', '$("element_2").visualEffect("highlight");'], @store.read('views/test.host/functional_caching/formatted_fragment_cached') end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/benchmark_test.rb
provider/vendor/rails/actionpack/test/controller/benchmark_test.rb
require 'abstract_unit' # Provide some static controllers. class BenchmarkedController < ActionController::Base def public_action render :nothing => true end def rescue_action(e) raise e end end class BenchmarkTest < ActionController::TestCase tests BenchmarkedController class MockLogger def method_missing(*args) end end def setup # benchmark doesn't do anything unless a logger is set @controller.logger = MockLogger.new @request.host = "test.actioncontroller.i" end def test_with_http_1_0_request @request.host = nil assert_nothing_raised { get :public_action } end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/webservice_test.rb
provider/vendor/rails/actionpack/test/controller/webservice_test.rb
require 'abstract_unit' class WebServiceTest < ActionController::IntegrationTest class TestController < ActionController::Base def assign_parameters if params[:full] render :text => dump_params_keys else render :text => (params.keys - ['controller', 'action']).sort.join(", ") end end def dump_params_keys(hash = params) hash.keys.sort.inject("") do |s, k| value = hash[k] value = Hash === value ? "(#{dump_params_keys(value)})" : "" s << ", " unless s.empty? s << "#{k}#{value}" end end def rescue_action(e) raise end end def setup @controller = TestController.new @default_param_parsers = ActionController::Base.param_parsers.dup end def teardown ActionController::Base.param_parsers = @default_param_parsers end def test_check_parameters with_test_route_set do get "/" assert_equal '', @controller.response.body end end def test_post_xml with_test_route_set do post "/", '<entry attributed="true"><summary>content...</summary></entry>', {'CONTENT_TYPE' => 'application/xml'} assert_equal 'entry', @controller.response.body assert @controller.params.has_key?(:entry) assert_equal 'content...', @controller.params["entry"]['summary'] assert_equal 'true', @controller.params["entry"]['attributed'] end end def test_put_xml with_test_route_set do put "/", '<entry attributed="true"><summary>content...</summary></entry>', {'CONTENT_TYPE' => 'application/xml'} assert_equal 'entry', @controller.response.body assert @controller.params.has_key?(:entry) assert_equal 'content...', @controller.params["entry"]['summary'] assert_equal 'true', @controller.params["entry"]['attributed'] end end def test_put_xml_using_a_type_node with_test_route_set do put "/", '<type attributed="true"><summary>content...</summary></type>', {'CONTENT_TYPE' => 'application/xml'} assert_equal 'type', @controller.response.body assert @controller.params.has_key?(:type) assert_equal 'content...', @controller.params["type"]['summary'] assert_equal 'true', @controller.params["type"]['attributed'] end end def test_put_xml_using_a_type_node_and_attribute with_test_route_set do put "/", '<type attributed="true"><summary type="boolean">false</summary></type>', {'CONTENT_TYPE' => 'application/xml'} assert_equal 'type', @controller.response.body assert @controller.params.has_key?(:type) assert_equal false, @controller.params["type"]['summary'] assert_equal 'true', @controller.params["type"]['attributed'] end end def test_post_xml_using_a_type_node with_test_route_set do post "/", '<font attributed="true"><type>arial</type></font>', {'CONTENT_TYPE' => 'application/xml'} assert_equal 'font', @controller.response.body assert @controller.params.has_key?(:font) assert_equal 'arial', @controller.params['font']['type'] assert_equal 'true', @controller.params["font"]['attributed'] end end def test_post_xml_using_a_root_node_named_type with_test_route_set do post "/", '<type type="integer">33</type>', {'CONTENT_TYPE' => 'application/xml'} assert @controller.params.has_key?(:type) assert_equal 33, @controller.params['type'] end end def test_post_xml_using_an_attributted_node_named_type with_test_route_set do ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } post "/", '<request><type type="string">Arial,12</type><z>3</z></request>', {'CONTENT_TYPE' => 'application/xml'} assert_equal 'type, z', @controller.response.body assert @controller.params.has_key?(:type) assert_equal 'Arial,12', @controller.params['type'], @controller.params.inspect assert_equal '3', @controller.params['z'], @controller.params.inspect end end def test_register_and_use_yaml with_test_route_set do ActionController::Base.param_parsers[Mime::YAML] = Proc.new { |d| YAML.load(d) } post "/", {"entry" => "loaded from yaml"}.to_yaml, {'CONTENT_TYPE' => 'application/x-yaml'} assert_equal 'entry', @controller.response.body assert @controller.params.has_key?(:entry) assert_equal 'loaded from yaml', @controller.params["entry"] end end def test_register_and_use_yaml_as_symbol with_test_route_set do ActionController::Base.param_parsers[Mime::YAML] = :yaml post "/", {"entry" => "loaded from yaml"}.to_yaml, {'CONTENT_TYPE' => 'application/x-yaml'} assert_equal 'entry', @controller.response.body assert @controller.params.has_key?(:entry) assert_equal 'loaded from yaml', @controller.params["entry"] end end def test_register_and_use_xml_simple with_test_route_set do ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } post "/", '<request><summary>content...</summary><title>SimpleXml</title></request>', {'CONTENT_TYPE' => 'application/xml'} assert_equal 'summary, title', @controller.response.body assert @controller.params.has_key?(:summary) assert @controller.params.has_key?(:title) assert_equal 'content...', @controller.params["summary"] assert_equal 'SimpleXml', @controller.params["title"] end end def test_use_xml_ximple_with_empty_request with_test_route_set do ActionController::Base.param_parsers[Mime::XML] = :xml_simple assert_nothing_raised { post "/", "", {'CONTENT_TYPE' => 'application/xml'} } assert_equal "", @controller.response.body end end def test_dasherized_keys_as_xml with_test_route_set do ActionController::Base.param_parsers[Mime::XML] = :xml_simple post "/?full=1", "<first-key>\n<sub-key>...</sub-key>\n</first-key>", {'CONTENT_TYPE' => 'application/xml'} assert_equal 'action, controller, first_key(sub_key), full', @controller.response.body assert_equal "...", @controller.params[:first_key][:sub_key] end end def test_typecast_as_xml with_test_route_set do ActionController::Base.param_parsers[Mime::XML] = :xml_simple xml = <<-XML <data> <a type="integer">15</a> <b type="boolean">false</b> <c type="boolean">true</c> <d type="date">2005-03-17</d> <e type="datetime">2005-03-17T21:41:07Z</e> <f>unparsed</f> <g type="integer">1</g> <g>hello</g> <g type="date">1974-07-25</g> </data> XML post "/", xml, {'CONTENT_TYPE' => 'application/xml'} params = @controller.params assert_equal 15, params[:data][:a] assert_equal false, params[:data][:b] assert_equal true, params[:data][:c] assert_equal Date.new(2005,3,17), params[:data][:d] assert_equal Time.utc(2005,3,17,21,41,7), params[:data][:e] assert_equal "unparsed", params[:data][:f] assert_equal [1, "hello", Date.new(1974,7,25)], params[:data][:g] end end def test_entities_unescaped_as_xml_simple with_test_route_set do ActionController::Base.param_parsers[Mime::XML] = :xml_simple xml = <<-XML <data>&lt;foo &quot;bar&apos;s&quot; &amp; friends&gt;</data> XML post "/", xml, {'CONTENT_TYPE' => 'application/xml'} assert_equal %(<foo "bar's" & friends>), @controller.params[:data] end end def test_typecast_as_yaml with_test_route_set do ActionController::Base.param_parsers[Mime::YAML] = :yaml yaml = <<-YAML --- data: a: 15 b: false c: true d: 2005-03-17 e: 2005-03-17T21:41:07Z f: unparsed g: - 1 - hello - 1974-07-25 YAML post "/", yaml, {'CONTENT_TYPE' => 'application/x-yaml'} params = @controller.params assert_equal 15, params[:data][:a] assert_equal false, params[:data][:b] assert_equal true, params[:data][:c] assert_equal Date.new(2005,3,17), params[:data][:d] assert_equal Time.utc(2005,3,17,21,41,7), params[:data][:e] assert_equal "unparsed", params[:data][:f] assert_equal [1, "hello", Date.new(1974,7,25)], params[:data][:g] end end private def with_test_route_set with_routing do |set| set.draw do |map| map.with_options :controller => "web_service_test/test" do |c| c.connect "/", :action => "assign_parameters" end end yield end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/logging_test.rb
provider/vendor/rails/actionpack/test/controller/logging_test.rb
require 'abstract_unit' class LoggingController < ActionController::Base def show render :nothing => true end end class LoggingTest < ActionController::TestCase tests LoggingController class MockLogger attr_reader :logged def method_missing(method, *args) @logged ||= [] @logged << args.first end end setup :set_logger def test_logging_without_parameters get :show assert_equal 2, logs.size assert_nil logs.detect {|l| l =~ /Parameters/ } end def test_logging_with_parameters get :show, :id => 10 assert_equal 3, logs.size params = logs.detect {|l| l =~ /Parameters/ } assert_equal 'Parameters: {"id"=>"10"}', params end private def set_logger @controller.logger = MockLogger.new end def logs @logs ||= @controller.logger.logged.compact.map {|l| l.strip} end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/test_test.rb
provider/vendor/rails/actionpack/test/controller/test_test.rb
require 'abstract_unit' require 'controller/fake_controllers' class TestTest < ActionController::TestCase class TestController < ActionController::Base def no_op render :text => 'dummy' end def set_flash flash["test"] = ">#{flash["test"]}<" render :text => 'ignore me' end def set_flash_now flash.now["test_now"] = ">#{flash["test_now"]}<" render :text => 'ignore me' end def set_session session['string'] = 'A wonder' session[:symbol] = 'it works' render :text => 'Success' end def reset_the_session reset_session render :text => 'ignore me' end def render_raw_post raise ActiveSupport::TestCase::Assertion, "#raw_post is blank" if request.raw_post.blank? render :text => request.raw_post end def render_body render :text => request.body.read end def test_params render :text => params.inspect end def test_uri render :text => request.request_uri end def test_query_string render :text => request.query_string end def test_html_output render :text => <<HTML <html> <body> <a href="/"><img src="/images/button.png" /></a> <div id="foo"> <ul> <li class="item">hello</li> <li class="item">goodbye</li> </ul> </div> <div id="bar"> <form action="/somewhere"> Name: <input type="text" name="person[name]" id="person_name" /> </form> </div> </body> </html> HTML end def test_xml_output response.content_type = "application/xml" render :text => <<XML <?xml version="1.0" encoding="UTF-8"?> <root> <area>area is an empty tag in HTML, raising an error if not in xml mode</area> </root> XML end def test_only_one_param render :text => (params[:left] && params[:right]) ? "EEP, Both here!" : "OK" end def test_remote_addr render :text => (request.remote_addr || "not specified") end def test_file_upload render :text => params[:file].size end def test_send_file send_file(File.expand_path(__FILE__)) end def redirect_to_same_controller redirect_to :controller => 'test', :action => 'test_uri', :id => 5 end def redirect_to_different_controller redirect_to :controller => 'fail', :id => 5 end def create head :created, :location => 'created resource' end private def rescue_action(e) raise e end def generate_url(opts) url_for(opts.merge(:action => "test_uri")) end end def setup @controller = TestController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new ActionController::Routing.use_controllers! %w(content admin/user test_test/test) ActionController::Routing::Routes.load_routes! end def teardown ActionController::Routing::Routes.reload end def test_raw_post_handling params = {:page => {:name => 'page name'}, 'some key' => 123} post :render_raw_post, params.dup assert_equal params.to_query, @response.body end def test_body_stream params = { :page => { :name => 'page name' }, 'some key' => 123 } post :render_body, params.dup assert_equal params.to_query, @response.body end def test_process_without_flash process :set_flash assert_equal '><', flash['test'] end def test_process_with_flash process :set_flash, nil, nil, { "test" => "value" } assert_equal '>value<', flash['test'] end def test_process_with_flash_now process :set_flash_now, nil, nil, { "test_now" => "value_now" } assert_equal '>value_now<', flash['test_now'] end def test_process_with_session process :set_session assert_equal 'A wonder', session['string'], "A value stored in the session should be available by string key" assert_equal 'A wonder', session[:string], "Test session hash should allow indifferent access" assert_equal 'it works', session['symbol'], "Test session hash should allow indifferent access" assert_equal 'it works', session[:symbol], "Test session hash should allow indifferent access" end def test_process_with_session_arg process :no_op, nil, { 'string' => 'value1', :symbol => 'value2' } assert_equal 'value1', session['string'] assert_equal 'value1', session[:string] assert_equal 'value2', session['symbol'] assert_equal 'value2', session[:symbol] end def test_session_is_cleared_from_controller_after_reset_session process :set_session process :reset_the_session assert_equal Hash.new, @controller.session.to_hash end def test_session_is_cleared_from_response_after_reset_session process :set_session process :reset_the_session assert_equal Hash.new, @response.session.to_hash end def test_session_is_cleared_from_request_after_reset_session process :set_session process :reset_the_session assert_equal Hash.new, @request.session.to_hash end def test_process_with_request_uri_with_no_params process :test_uri assert_equal "/test_test/test/test_uri", @response.body end def test_process_with_request_uri_with_params process :test_uri, :id => 7 assert_equal "/test_test/test/test_uri/7", @response.body end def test_process_with_request_uri_with_params_with_explicit_uri @request.set_REQUEST_URI "/explicit/uri" process :test_uri, :id => 7 assert_equal "/explicit/uri", @response.body end def test_process_with_query_string process :test_query_string, :q => 'test' assert_equal "q=test", @response.body end def test_process_with_query_string_with_explicit_uri @request.set_REQUEST_URI "/explicit/uri?q=test?extra=question" process :test_query_string assert_equal "q=test?extra=question", @response.body end def test_multiple_calls process :test_only_one_param, :left => true assert_equal "OK", @response.body process :test_only_one_param, :right => true assert_equal "OK", @response.body end def test_assert_tag_tag process :test_html_output # there is a 'form' tag assert_tag :tag => 'form' # there is not an 'hr' tag assert_no_tag :tag => 'hr' end def test_assert_tag_attributes process :test_html_output # there is a tag with an 'id' of 'bar' assert_tag :attributes => { :id => "bar" } # there is no tag with a 'name' of 'baz' assert_no_tag :attributes => { :name => "baz" } end def test_assert_tag_parent process :test_html_output # there is a tag with a parent 'form' tag assert_tag :parent => { :tag => "form" } # there is no tag with a parent of 'input' assert_no_tag :parent => { :tag => "input" } end def test_assert_tag_child process :test_html_output # there is a tag with a child 'input' tag assert_tag :child => { :tag => "input" } # there is no tag with a child 'strong' tag assert_no_tag :child => { :tag => "strong" } end def test_assert_tag_ancestor process :test_html_output # there is a 'li' tag with an ancestor having an id of 'foo' assert_tag :ancestor => { :attributes => { :id => "foo" } }, :tag => "li" # there is no tag of any kind with an ancestor having an href matching 'foo' assert_no_tag :ancestor => { :attributes => { :href => /foo/ } } end def test_assert_tag_descendant process :test_html_output # there is a tag with a descendant 'li' tag assert_tag :descendant => { :tag => "li" } # there is no tag with a descendant 'html' tag assert_no_tag :descendant => { :tag => "html" } end def test_assert_tag_sibling process :test_html_output # there is a tag with a sibling of class 'item' assert_tag :sibling => { :attributes => { :class => "item" } } # there is no tag with a sibling 'ul' tag assert_no_tag :sibling => { :tag => "ul" } end def test_assert_tag_after process :test_html_output # there is a tag following a sibling 'div' tag assert_tag :after => { :tag => "div" } # there is no tag following a sibling tag with id 'bar' assert_no_tag :after => { :attributes => { :id => "bar" } } end def test_assert_tag_before process :test_html_output # there is a tag preceding a tag with id 'bar' assert_tag :before => { :attributes => { :id => "bar" } } # there is no tag preceding a 'form' tag assert_no_tag :before => { :tag => "form" } end def test_assert_tag_children_count process :test_html_output # there is a tag with 2 children assert_tag :children => { :count => 2 } # in particular, there is a <ul> tag with two children (a nameless pair of <li>s) assert_tag :tag => 'ul', :children => { :count => 2 } # there is no tag with 4 children assert_no_tag :children => { :count => 4 } end def test_assert_tag_children_less_than process :test_html_output # there is a tag with less than 5 children assert_tag :children => { :less_than => 5 } # there is no 'ul' tag with less than 2 children assert_no_tag :children => { :less_than => 2 }, :tag => "ul" end def test_assert_tag_children_greater_than process :test_html_output # there is a 'body' tag with more than 1 children assert_tag :children => { :greater_than => 1 }, :tag => "body" # there is no tag with more than 10 children assert_no_tag :children => { :greater_than => 10 } end def test_assert_tag_children_only process :test_html_output # there is a tag containing only one child with an id of 'foo' assert_tag :children => { :count => 1, :only => { :attributes => { :id => "foo" } } } # there is no tag containing only one 'li' child assert_no_tag :children => { :count => 1, :only => { :tag => "li" } } end def test_assert_tag_content process :test_html_output # the output contains the string "Name" assert_tag :content => /Name/ # the output does not contain the string "test" assert_no_tag :content => /test/ end def test_assert_tag_multiple process :test_html_output # there is a 'div', id='bar', with an immediate child whose 'action' # attribute matches the regexp /somewhere/. assert_tag :tag => "div", :attributes => { :id => "bar" }, :child => { :attributes => { :action => /somewhere/ } } # there is no 'div', id='foo', with a 'ul' child with more than # 2 "li" children. assert_no_tag :tag => "div", :attributes => { :id => "foo" }, :child => { :tag => "ul", :children => { :greater_than => 2, :only => { :tag => "li" } } } end def test_assert_tag_children_without_content process :test_html_output # there is a form tag with an 'input' child which is a self closing tag assert_tag :tag => "form", :children => { :count => 1, :only => { :tag => "input" } } # the body tag has an 'a' child which in turn has an 'img' child assert_tag :tag => "body", :children => { :count => 1, :only => { :tag => "a", :children => { :count => 1, :only => { :tag => "img" } } } } end def test_should_not_impose_childless_html_tags_in_xml process :test_xml_output begin $stderr = StringIO.new assert_select 'area' #This will cause a warning if content is processed as HTML $stderr.rewind && err = $stderr.read ensure $stderr = STDERR end assert err.empty? end def test_assert_tag_attribute_matching @response.body = '<input type="text" name="my_name">' assert_tag :tag => 'input', :attributes => { :name => /my/, :type => 'text' } assert_no_tag :tag => 'input', :attributes => { :name => 'my', :type => 'text' } assert_no_tag :tag => 'input', :attributes => { :name => /^my$/, :type => 'text' } end def test_assert_tag_content_matching @response.body = "<p>hello world</p>" assert_tag :tag => "p", :content => "hello world" assert_tag :tag => "p", :content => /hello/ assert_no_tag :tag => "p", :content => "hello" end def test_assert_generates assert_generates 'controller/action/5', :controller => 'controller', :action => 'action', :id => '5' assert_generates 'controller/action/7', {:id => "7"}, {:controller => "controller", :action => "action"} assert_generates 'controller/action/5', {:controller => "controller", :action => "action", :id => "5", :name => "bob"}, {}, {:name => "bob"} assert_generates 'controller/action/7', {:id => "7", :name => "bob"}, {:controller => "controller", :action => "action"}, {:name => "bob"} assert_generates 'controller/action/7', {:id => "7"}, {:controller => "controller", :action => "action", :name => "bob"}, {} end def test_assert_routing assert_routing 'content', :controller => 'content', :action => 'index' end def test_assert_routing_with_method with_routing do |set| set.draw { |map| map.resources(:content) } assert_routing({ :method => 'post', :path => 'content' }, { :controller => 'content', :action => 'create' }) end end def test_assert_routing_in_module assert_routing 'admin/user', :controller => 'admin/user', :action => 'index' end def test_params_passing get :test_params, :page => {:name => "Page name", :month => '4', :year => '2004', :day => '6'} parsed_params = eval(@response.body) assert_equal( {'controller' => 'test_test/test', 'action' => 'test_params', 'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}}, parsed_params ) end def test_id_converted_to_string get :test_params, :id => 20, :foo => Object.new assert_kind_of String, @request.path_parameters['id'] end def test_array_path_parameter_handled_properly with_routing do |set| set.draw do |map| map.connect 'file/*path', :controller => 'test_test/test', :action => 'test_params' map.connect ':controller/:action/:id' end get :test_params, :path => ['hello', 'world'] assert_equal ['hello', 'world'], @request.path_parameters['path'] assert_equal 'hello/world', @request.path_parameters['path'].to_s end end def test_assert_realistic_path_parameters get :test_params, :id => 20, :foo => Object.new # All elements of path_parameters should use string keys @request.path_parameters.keys.each do |key| assert_kind_of String, key end end def test_with_routing_places_routes_back assert ActionController::Routing::Routes routes_id = ActionController::Routing::Routes.object_id begin with_routing { raise 'fail' } fail 'Should not be here.' rescue RuntimeError end assert ActionController::Routing::Routes assert_equal routes_id, ActionController::Routing::Routes.object_id end def test_remote_addr get :test_remote_addr assert_equal "0.0.0.0", @response.body @request.remote_addr = "192.0.0.1" get :test_remote_addr assert_equal "192.0.0.1", @response.body end def test_header_properly_reset_after_remote_http_request xhr :get, :test_params assert_nil @request.env['HTTP_X_REQUESTED_WITH'] end def test_header_properly_reset_after_get_request get :test_params @request.recycle! assert_nil @request.instance_variable_get("@request_method") end def test_params_reset_after_post_request post :no_op, :foo => "bar" assert_equal "bar", @request.params[:foo] @request.recycle! post :no_op assert @request.params[:foo].blank? end %w(controller response request).each do |variable| %w(get post put delete head process).each do |method| define_method("test_#{variable}_missing_for_#{method}_raises_error") do remove_instance_variable "@#{variable}" begin send(method, :test_remote_addr) assert false, "expected RuntimeError, got nothing" rescue RuntimeError => error assert true assert_match %r{@#{variable} is nil}, error.message rescue => error assert false, "expected RuntimeError, got #{error.class}" end end end end FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart' if RUBY_VERSION < '1.9' READ_BINARY = 'rb' READ_PLAIN = 'r' else READ_BINARY = 'rb:binary' READ_PLAIN = 'r:binary' end def test_test_uploaded_file filename = 'mona_lisa.jpg' path = "#{FILES_DIR}/#{filename}" content_type = 'image/png' expected = File.read(path) expected.force_encoding(Encoding::BINARY) if expected.respond_to?(:force_encoding) file = ActionController::TestUploadedFile.new(path, content_type) assert_equal filename, file.original_filename assert_equal content_type, file.content_type assert_equal file.path, file.local_path assert_equal expected, file.read new_content_type = "new content_type" file.content_type = new_content_type assert_equal new_content_type, file.content_type end def test_test_uploaded_file_with_binary filename = 'mona_lisa.jpg' path = "#{FILES_DIR}/#{filename}" content_type = 'image/png' binary_uploaded_file = ActionController::TestUploadedFile.new(path, content_type, :binary) assert_equal File.open(path, READ_BINARY).read, binary_uploaded_file.read plain_uploaded_file = ActionController::TestUploadedFile.new(path, content_type) assert_equal File.open(path, READ_PLAIN).read, plain_uploaded_file.read end def test_fixture_file_upload_with_binary filename = 'mona_lisa.jpg' path = "#{FILES_DIR}/#{filename}" content_type = 'image/jpg' binary_file_upload = fixture_file_upload(path, content_type, :binary) assert_equal File.open(path, READ_BINARY).read, binary_file_upload.read plain_file_upload = fixture_file_upload(path, content_type) assert_equal File.open(path, READ_PLAIN).read, plain_file_upload.read end def test_fixture_file_upload post :test_file_upload, :file => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg") assert_equal '159528', @response.body end def test_test_uploaded_file_exception_when_file_doesnt_exist assert_raise(RuntimeError) { ActionController::TestUploadedFile.new('non_existent_file') } end def test_redirect_url_only_cares_about_location_header get :create assert_response :created # Redirect url doesn't care that it wasn't a :redirect response. assert_equal 'created resource', @response.redirect_url assert_equal @response.redirect_url, redirect_to_url # Must be a :redirect response. assert_raise(ActiveSupport::TestCase::Assertion) do assert_redirected_to 'created resource' end end def test_binary_content_works_with_send_file get :test_send_file assert_nothing_raised(NoMethodError) { @response.binary_content } end protected def with_foo_routing with_routing do |set| set.draw do |map| map.generate_url 'foo', :controller => 'test' map.connect ':controller/:action/:id' end yield set end end end class CleanBacktraceTest < ActionController::TestCase def test_should_reraise_the_same_object exception = ActiveSupport::TestCase::Assertion.new('message') clean_backtrace { raise exception } rescue Exception => caught assert_equal exception.object_id, caught.object_id assert_equal exception.message, caught.message end def test_should_clean_assertion_lines_from_backtrace path = File.expand_path("#{File.dirname(__FILE__)}/../../lib/action_controller") exception = ActiveSupport::TestCase::Assertion.new('message') exception.set_backtrace ["#{path}/abc", "#{path}/assertions/def"] clean_backtrace { raise exception } rescue Exception => caught assert_equal ["#{path}/abc"], caught.backtrace end def test_should_only_clean_assertion_failure_errors clean_backtrace do raise "can't touch this", [File.expand_path("#{File.dirname(__FILE__)}/../../lib/action_controller/assertions/abc")] end rescue => caught assert !caught.backtrace.empty? end end class InferringClassNameTest < ActionController::TestCase def test_determine_controller_class assert_equal ContentController, determine_class("ContentControllerTest") end def test_determine_controller_class_with_nonsense_name assert_nil determine_class("HelloGoodBye") end def test_determine_controller_class_with_sensible_name_where_no_controller_exists assert_nil determine_class("NoControllerWithThisNameTest") end private def determine_class(name) ActionController::TestCase.determine_default_controller_class(name) end end class CrazyNameTest < ActionController::TestCase tests ContentController def test_controller_class_can_be_set_manually_not_just_inferred assert_equal ContentController, self.class.controller_class end end class NamedRoutesControllerTest < ActionController::TestCase tests ContentController def test_should_be_able_to_use_named_routes_before_a_request_is_done with_routing do |set| set.draw { |map| map.resources :contents } assert_equal 'http://test.host/contents/new', new_content_url assert_equal 'http://test.host/contents/1', content_url(:id => 1) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/capture_test.rb
provider/vendor/rails/actionpack/test/controller/capture_test.rb
require 'abstract_unit' class CaptureController < ActionController::Base def self.controller_name; "test"; end def self.controller_path; "test"; end def content_for render :layout => "talk_from_action" end def content_for_with_parameter render :layout => "talk_from_action" end def content_for_concatenated render :layout => "talk_from_action" end def non_erb_block_content_for render :layout => "talk_from_action" end def rescue_action(e) raise end end class CaptureTest < ActionController::TestCase tests CaptureController def setup # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". @controller.logger = Logger.new(nil) @request.host = "www.nextangle.com" end def test_simple_capture get :capturing assert_equal "Dreamy days", @response.body.strip end def test_content_for get :content_for assert_equal expected_content_for_output, @response.body end def test_should_concatentate_content_for get :content_for_concatenated assert_equal expected_content_for_output, @response.body end def test_should_set_content_for_with_parameter get :content_for_with_parameter assert_equal expected_content_for_output, @response.body end def test_non_erb_block_content_for get :non_erb_block_content_for assert_equal expected_content_for_output, @response.body end private def expected_content_for_output "<title>Putting stuff in the title!</title>\n\nGreat stuff!" end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/flash_test.rb
provider/vendor/rails/actionpack/test/controller/flash_test.rb
require 'abstract_unit' class FlashTest < ActionController::TestCase class TestController < ActionController::Base def set_flash flash["that"] = "hello" render :inline => "hello" end def set_flash_now flash.now["that"] = "hello" flash.now["foo"] ||= "bar" flash.now["foo"] ||= "err" @flashy = flash.now["that"] @flash_copy = {}.update flash render :inline => "hello" end def attempt_to_use_flash_now @flash_copy = {}.update flash @flashy = flash["that"] render :inline => "hello" end def use_flash @flash_copy = {}.update flash @flashy = flash["that"] render :inline => "hello" end def use_flash_and_keep_it @flash_copy = {}.update flash @flashy = flash["that"] flash.keep render :inline => "hello" end def use_flash_and_update_it flash.update("this" => "hello again") @flash_copy = {}.update flash render :inline => "hello" end def use_flash_after_reset_session flash["that"] = "hello" @flashy_that = flash["that"] reset_session @flashy_that_reset = flash["that"] flash["this"] = "good-bye" @flashy_this = flash["this"] render :inline => "hello" end def rescue_action(e) raise unless ActionView::MissingTemplate === e end # methods for test_sweep_after_halted_filter_chain before_filter :halt_and_redir, :only => "filter_halting_action" def std_action @flash_copy = {}.update(flash) end def filter_halting_action @flash_copy = {}.update(flash) end def halt_and_redir flash["foo"] = "bar" redirect_to :action => "std_action" @flash_copy = {}.update(flash) end end tests TestController def test_flash get :set_flash get :use_flash assert_equal "hello", @response.template.assigns["flash_copy"]["that"] assert_equal "hello", @response.template.assigns["flashy"] get :use_flash assert_nil @response.template.assigns["flash_copy"]["that"], "On second flash" end def test_keep_flash get :set_flash get :use_flash_and_keep_it assert_equal "hello", @response.template.assigns["flash_copy"]["that"] assert_equal "hello", @response.template.assigns["flashy"] get :use_flash assert_equal "hello", @response.template.assigns["flash_copy"]["that"], "On second flash" get :use_flash assert_nil @response.template.assigns["flash_copy"]["that"], "On third flash" end def test_flash_now get :set_flash_now assert_equal "hello", @response.template.assigns["flash_copy"]["that"] assert_equal "bar" , @response.template.assigns["flash_copy"]["foo"] assert_equal "hello", @response.template.assigns["flashy"] get :attempt_to_use_flash_now assert_nil @response.template.assigns["flash_copy"]["that"] assert_nil @response.template.assigns["flash_copy"]["foo"] assert_nil @response.template.assigns["flashy"] end def test_update_flash get :set_flash get :use_flash_and_update_it assert_equal "hello", @response.template.assigns["flash_copy"]["that"] assert_equal "hello again", @response.template.assigns["flash_copy"]["this"] get :use_flash assert_nil @response.template.assigns["flash_copy"]["that"], "On second flash" assert_equal "hello again", @response.template.assigns["flash_copy"]["this"], "On second flash" end def test_flash_after_reset_session get :use_flash_after_reset_session assert_equal "hello", @response.template.assigns["flashy_that"] assert_equal "good-bye", @response.template.assigns["flashy_this"] assert_nil @response.template.assigns["flashy_that_reset"] end def test_sweep_after_halted_filter_chain get :std_action assert_nil @response.template.assigns["flash_copy"]["foo"] get :filter_halting_action assert_equal "bar", @response.template.assigns["flash_copy"]["foo"] get :std_action # follow redirection assert_equal "bar", @response.template.assigns["flash_copy"]["foo"] get :std_action assert_nil @response.template.assigns["flash_copy"]["foo"] end def test_does_not_set_the_session_if_the_flash_is_empty get :std_action assert_nil session["flash"] end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/resources_test.rb
provider/vendor/rails/actionpack/test/controller/resources_test.rb
require 'abstract_unit' class ResourcesController < ActionController::Base def index() render :nothing => true end alias_method :show, :index def rescue_action(e) raise e end end class ThreadsController < ResourcesController; end class MessagesController < ResourcesController; end class CommentsController < ResourcesController; end class AuthorsController < ResourcesController; end class LogosController < ResourcesController; end class AccountsController < ResourcesController; end class AdminController < ResourcesController; end class ProductsController < ResourcesController; end class ImagesController < ResourcesController; end module Backoffice class ProductsController < ResourcesController; end class TagsController < ResourcesController; end class ManufacturersController < ResourcesController; end class ImagesController < ResourcesController; end module Admin class ProductsController < ResourcesController; end class ImagesController < ResourcesController; end end end class ResourcesTest < ActionController::TestCase # The assertions in these tests are incompatible with the hash method # optimisation. This could indicate user level problems def setup ActionController::Base.optimise_named_routes = false end def teardown ActionController::Base.optimise_named_routes = true end def test_should_arrange_actions resource = ActionController::Resources::Resource.new(:messages, :collection => { :rss => :get, :reorder => :post, :csv => :post }, :member => { :rss => :get, :atom => :get, :upload => :post, :fix => :post }, :new => { :preview => :get, :draft => :get }) assert_resource_methods [:rss], resource, :collection, :get assert_resource_methods [:csv, :reorder], resource, :collection, :post assert_resource_methods [:edit, :rss, :atom], resource, :member, :get assert_resource_methods [:upload, :fix], resource, :member, :post assert_resource_methods [:new, :preview, :draft], resource, :new, :get end def test_should_resource_controller_name_equal_resource_name_by_default resource = ActionController::Resources::Resource.new(:messages, {}) assert_equal 'messages', resource.controller end def test_should_resource_controller_name_equal_controller_option resource = ActionController::Resources::Resource.new(:messages, :controller => 'posts') assert_equal 'posts', resource.controller end def test_should_all_singleton_paths_be_the_same [ :path, :nesting_path_prefix, :member_path ].each do |method| resource = ActionController::Resources::SingletonResource.new(:messages, :path_prefix => 'admin') assert_equal 'admin/messages', resource.send(method) end end def test_default_restful_routes with_restful_routing :messages do assert_simply_restful_for :messages end end def test_override_paths_for_member_and_collection_methods collection_methods = { 'rss' => :get, 'reorder' => :post, 'csv' => :post } member_methods = { 'rss' => :get, :atom => :get, :upload => :post, :fix => :post } path_names = {:new => 'nuevo', 'rss' => 'canal', :fix => 'corrigir' } with_restful_routing :messages, :collection => collection_methods, :member => member_methods, :path_names => path_names do assert_restful_routes_for :messages, :collection => collection_methods, :member => member_methods, :path_names => path_names do |options| member_methods.each do |action, method| assert_recognizes(options.merge(:action => action.to_s, :id => '1'), :path => "/messages/1/#{path_names[action] || action}", :method => method) end collection_methods.each do |action, method| assert_recognizes(options.merge(:action => action), :path => "/messages/#{path_names[action] || action}", :method => method) end end assert_restful_named_routes_for :messages, :collection => collection_methods, :member => member_methods, :path_names => path_names do |options| collection_methods.keys.each do |action| assert_named_route "/messages/#{path_names[action] || action}", "#{action}_messages_path", :action => action end member_methods.keys.each do |action| assert_named_route "/messages/1/#{path_names[action] || action}", "#{action}_message_path", :action => action, :id => "1" end end end end def test_override_paths_for_default_restful_actions resource = ActionController::Resources::Resource.new(:messages, :path_names => {:new => 'nuevo', :edit => 'editar'}) assert_equal resource.new_path, "#{resource.path}/nuevo" end def test_multiple_default_restful_routes with_restful_routing :messages, :comments do assert_simply_restful_for :messages assert_simply_restful_for :comments end end def test_with_custom_conditions with_restful_routing :messages, :conditions => { :subdomain => 'app' } do assert_equal 'app', ActionController::Routing::Routes.named_routes.routes[:messages].conditions[:subdomain] end end def test_irregular_id_with_no_requirements_should_raise_error expected_options = {:controller => 'messages', :action => 'show', :id => '1.1.1'} with_restful_routing :messages do assert_raise(ActionController::RoutingError) do assert_recognizes(expected_options, :path => 'messages/1.1.1', :method => :get) end end end def test_irregular_id_with_requirements_should_pass expected_options = {:controller => 'messages', :action => 'show', :id => '1.1.1'} with_restful_routing(:messages, :requirements => {:id => /[0-9]\.[0-9]\.[0-9]/}) do assert_recognizes(expected_options, :path => 'messages/1.1.1', :method => :get) end end def test_with_path_prefix_requirements expected_options = {:controller => 'messages', :action => 'show', :thread_id => '1.1.1', :id => '1'} with_restful_routing :messages, :path_prefix => '/thread/:thread_id', :requirements => {:thread_id => /[0-9]\.[0-9]\.[0-9]/} do assert_recognizes(expected_options, :path => 'thread/1.1.1/messages/1', :method => :get) end end def test_irregular_id_requirements_should_get_passed_to_member_actions expected_options = {:controller => 'messages', :action => 'custom', :id => '1.1.1'} with_restful_routing(:messages, :member => {:custom => :get}, :requirements => {:id => /[0-9]\.[0-9]\.[0-9]/}) do assert_recognizes(expected_options, :path => 'messages/1.1.1/custom', :method => :get) end end def test_with_path_prefix with_restful_routing :messages, :path_prefix => '/thread/:thread_id' do assert_simply_restful_for :messages, :path_prefix => 'thread/5/', :options => { :thread_id => '5' } end end def test_multiple_with_path_prefix with_restful_routing :messages, :comments, :path_prefix => '/thread/:thread_id' do assert_simply_restful_for :messages, :path_prefix => 'thread/5/', :options => { :thread_id => '5' } assert_simply_restful_for :comments, :path_prefix => 'thread/5/', :options => { :thread_id => '5' } end end def test_with_name_prefix with_restful_routing :messages, :name_prefix => 'post_' do assert_simply_restful_for :messages, :name_prefix => 'post_' end end def test_with_collection_actions actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete } with_restful_routing :messages, :collection => actions do assert_restful_routes_for :messages do |options| actions.each do |action, method| assert_recognizes(options.merge(:action => action), :path => "/messages/#{action}", :method => method) end end assert_restful_named_routes_for :messages do |options| actions.keys.each do |action| assert_named_route "/messages/#{action}", "#{action}_messages_path", :action => action end end end end def test_with_collection_actions_and_name_prefix actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete } with_restful_routing :messages, :path_prefix => '/threads/:thread_id', :name_prefix => "thread_", :collection => actions do assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| actions.each do |action, method| assert_recognizes(options.merge(:action => action), :path => "/threads/1/messages/#{action}", :method => method) end end assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| actions.keys.each do |action| assert_named_route "/threads/1/messages/#{action}", "#{action}_thread_messages_path", :action => action end end end end def test_with_collection_actions_and_name_prefix_and_member_action_with_same_name actions = { 'a' => :get } with_restful_routing :messages, :path_prefix => '/threads/:thread_id', :name_prefix => "thread_", :collection => actions, :member => actions do assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| actions.each do |action, method| assert_recognizes(options.merge(:action => action), :path => "/threads/1/messages/#{action}", :method => method) end end assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| actions.keys.each do |action| assert_named_route "/threads/1/messages/#{action}", "#{action}_thread_messages_path", :action => action end end end end def test_with_collection_action_and_name_prefix_and_formatted actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete } with_restful_routing :messages, :path_prefix => '/threads/:thread_id', :name_prefix => "thread_", :collection => actions do assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| actions.each do |action, method| assert_recognizes(options.merge(:action => action, :format => 'xml'), :path => "/threads/1/messages/#{action}.xml", :method => method) end end assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| actions.keys.each do |action| assert_named_route "/threads/1/messages/#{action}.xml", "#{action}_thread_messages_path", :action => action, :format => 'xml' end end end end def test_with_member_action [:put, :post].each do |method| with_restful_routing :messages, :member => { :mark => method } do mark_options = {:action => 'mark', :id => '1'} mark_path = "/messages/1/mark" assert_restful_routes_for :messages do |options| assert_recognizes(options.merge(mark_options), :path => mark_path, :method => method) end assert_restful_named_routes_for :messages do |options| assert_named_route mark_path, :mark_message_path, mark_options end end end end def test_with_member_action_and_requirement expected_options = {:controller => 'messages', :action => 'mark', :id => '1.1.1'} with_restful_routing(:messages, :requirements => {:id => /[0-9]\.[0-9]\.[0-9]/}, :member => { :mark => :get }) do assert_recognizes(expected_options, :path => 'messages/1.1.1/mark', :method => :get) end end def test_member_when_override_paths_for_default_restful_actions_with [:put, :post].each do |method| with_restful_routing :messages, :member => { :mark => method }, :path_names => {:new => 'nuevo'} do mark_options = {:action => 'mark', :id => '1', :controller => "messages"} mark_path = "/messages/1/mark" assert_restful_routes_for :messages, :path_names => {:new => 'nuevo'} do |options| assert_recognizes(options.merge(mark_options), :path => mark_path, :method => method) end assert_restful_named_routes_for :messages, :path_names => {:new => 'nuevo'} do |options| assert_named_route mark_path, :mark_message_path, mark_options end end end end def test_member_when_changed_default_restful_actions_and_path_names_not_specified default_path_names = ActionController::Base.resources_path_names ActionController::Base.resources_path_names = {:new => 'nuevo', :edit => 'editar'} with_restful_routing :messages do new_options = { :action => 'new', :controller => 'messages' } new_path = "/messages/nuevo" edit_options = { :action => 'edit', :id => '1', :controller => 'messages' } edit_path = "/messages/1/editar" assert_restful_routes_for :messages do |options| assert_recognizes(options.merge(new_options), :path => new_path, :method => :get) end assert_restful_routes_for :messages do |options| assert_recognizes(options.merge(edit_options), :path => edit_path, :method => :get) end end ensure ActionController::Base.resources_path_names = default_path_names end def test_with_two_member_actions_with_same_method [:put, :post].each do |method| with_restful_routing :messages, :member => { :mark => method, :unmark => method } do %w(mark unmark).each do |action| action_options = {:action => action, :id => '1'} action_path = "/messages/1/#{action}" assert_restful_routes_for :messages do |options| assert_recognizes(options.merge(action_options), :path => action_path, :method => method) end assert_restful_named_routes_for :messages do |options| assert_named_route action_path, "#{action}_message_path".to_sym, action_options end end end end end def test_array_as_collection_or_member_method_value with_restful_routing :messages, :collection => { :search => [:get, :post] }, :member => { :toggle => [:get, :post] } do assert_restful_routes_for :messages do |options| [:get, :post].each do |method| assert_recognizes(options.merge(:action => 'search'), :path => "/messages/search", :method => method) end [:get, :post].each do |method| assert_recognizes(options.merge(:action => 'toggle', :id => '1'), :path => '/messages/1/toggle', :method => method) end end end end def test_with_new_action with_restful_routing :messages, :new => { :preview => :post } do preview_options = {:action => 'preview'} preview_path = "/messages/new/preview" assert_restful_routes_for :messages do |options| assert_recognizes(options.merge(preview_options), :path => preview_path, :method => :post) end assert_restful_named_routes_for :messages do |options| assert_named_route preview_path, :preview_new_message_path, preview_options end end end def test_with_new_action_with_name_prefix with_restful_routing :messages, :new => { :preview => :post }, :path_prefix => '/threads/:thread_id', :name_prefix => 'thread_' do preview_options = {:action => 'preview', :thread_id => '1'} preview_path = "/threads/1/messages/new/preview" assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| assert_recognizes(options.merge(preview_options), :path => preview_path, :method => :post) end assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| assert_named_route preview_path, :preview_new_thread_message_path, preview_options end end end def test_with_formatted_new_action_with_name_prefix with_restful_routing :messages, :new => { :preview => :post }, :path_prefix => '/threads/:thread_id', :name_prefix => 'thread_' do preview_options = {:action => 'preview', :thread_id => '1', :format => 'xml'} preview_path = "/threads/1/messages/new/preview.xml" assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| assert_recognizes(options.merge(preview_options), :path => preview_path, :method => :post) end assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| assert_named_route preview_path, :preview_new_thread_message_path, preview_options end end end def test_override_new_method with_restful_routing :messages do assert_restful_routes_for :messages do |options| assert_recognizes(options.merge(:action => "new"), :path => "/messages/new", :method => :get) assert_raise(ActionController::MethodNotAllowed) do ActionController::Routing::Routes.recognize_path("/messages/new", :method => :post) end end end with_restful_routing :messages, :new => { :new => :any } do assert_restful_routes_for :messages do |options| assert_recognizes(options.merge(:action => "new"), :path => "/messages/new", :method => :post) assert_recognizes(options.merge(:action => "new"), :path => "/messages/new", :method => :get) end end end def test_nested_restful_routes with_routing do |set| set.draw do |map| map.resources :threads do |map| map.resources :messages do |map| map.resources :comments end end end assert_simply_restful_for :threads assert_simply_restful_for :messages, :name_prefix => 'thread_', :path_prefix => 'threads/1/', :options => { :thread_id => '1' } assert_simply_restful_for :comments, :name_prefix => 'thread_message_', :path_prefix => 'threads/1/messages/2/', :options => { :thread_id => '1', :message_id => '2' } end end def test_nested_restful_routes_with_overwritten_defaults with_routing do |set| set.draw do |map| map.resources :threads do |map| map.resources :messages, :name_prefix => nil do |map| map.resources :comments, :name_prefix => nil end end end assert_simply_restful_for :threads assert_simply_restful_for :messages, :path_prefix => 'threads/1/', :options => { :thread_id => '1' } assert_simply_restful_for :comments, :path_prefix => 'threads/1/messages/2/', :options => { :thread_id => '1', :message_id => '2' } end end def test_shallow_nested_restful_routes with_routing do |set| set.draw do |map| map.resources :threads, :shallow => true do |map| map.resources :messages do |map| map.resources :comments end end end assert_simply_restful_for :threads, :shallow => true assert_simply_restful_for :messages, :name_prefix => 'thread_', :path_prefix => 'threads/1/', :shallow => true, :options => { :thread_id => '1' } assert_simply_restful_for :comments, :name_prefix => 'message_', :path_prefix => 'messages/2/', :shallow => true, :options => { :message_id => '2' } end end def test_shallow_nested_restful_routes_with_namespaces with_routing do |set| set.draw do |map| map.namespace :backoffice do |map| map.namespace :admin do |map| map.resources :products, :shallow => true do |map| map.resources :images end end end end assert_simply_restful_for :products, :controller => 'backoffice/admin/products', :namespace => 'backoffice/admin/', :name_prefix => 'backoffice_admin_', :path_prefix => 'backoffice/admin/', :shallow => true assert_simply_restful_for :images, :controller => 'backoffice/admin/images', :namespace => 'backoffice/admin/', :name_prefix => 'backoffice_admin_product_', :path_prefix => 'backoffice/admin/products/1/', :shallow => true, :options => { :product_id => '1' } end end def test_restful_routes_dont_generate_duplicates with_restful_routing :messages do routes = ActionController::Routing::Routes.routes routes.each do |route| routes.each do |r| next if route === r # skip the comparison instance assert distinct_routes?(route, r), "Duplicate Route: #{route}" end end end end def test_should_create_singleton_resource_routes with_singleton_resources :account do assert_singleton_restful_for :account end end def test_should_create_multiple_singleton_resource_routes with_singleton_resources :account, :logo do assert_singleton_restful_for :account assert_singleton_restful_for :logo end end def test_should_create_nested_singleton_resource_routes with_routing do |set| set.draw do |map| map.resource :admin, :controller => 'admin' do |admin| admin.resource :account end end assert_singleton_restful_for :admin, :controller => 'admin' assert_singleton_restful_for :account, :name_prefix => "admin_", :path_prefix => 'admin/' end end def test_resource_has_many_should_become_nested_resources with_routing do |set| set.draw do |map| map.resources :messages, :has_many => [ :comments, :authors ] end assert_simply_restful_for :messages assert_simply_restful_for :comments, :name_prefix => "message_", :path_prefix => 'messages/1/', :options => { :message_id => '1' } assert_simply_restful_for :authors, :name_prefix => "message_", :path_prefix => 'messages/1/', :options => { :message_id => '1' } end end def test_resources_has_many_hash_should_become_nested_resources with_routing do |set| set.draw do |map| map.resources :threads, :has_many => { :messages => [ :comments, { :authors => :threads } ] } end assert_simply_restful_for :threads assert_simply_restful_for :messages, :name_prefix => "thread_", :path_prefix => 'threads/1/', :options => { :thread_id => '1' } assert_simply_restful_for :comments, :name_prefix => "thread_message_", :path_prefix => 'threads/1/messages/1/', :options => { :thread_id => '1', :message_id => '1' } assert_simply_restful_for :authors, :name_prefix => "thread_message_", :path_prefix => 'threads/1/messages/1/', :options => { :thread_id => '1', :message_id => '1' } assert_simply_restful_for :threads, :name_prefix => "thread_message_author_", :path_prefix => 'threads/1/messages/1/authors/1/', :options => { :thread_id => '1', :message_id => '1', :author_id => '1' } end end def test_shallow_resource_has_many_should_become_shallow_nested_resources with_routing do |set| set.draw do |map| map.resources :messages, :has_many => [ :comments, :authors ], :shallow => true end assert_simply_restful_for :messages, :shallow => true assert_simply_restful_for :comments, :name_prefix => "message_", :path_prefix => 'messages/1/', :shallow => true, :options => { :message_id => '1' } assert_simply_restful_for :authors, :name_prefix => "message_", :path_prefix => 'messages/1/', :shallow => true, :options => { :message_id => '1' } end end def test_resource_has_one_should_become_nested_resources with_routing do |set| set.draw do |map| map.resources :messages, :has_one => :logo end assert_simply_restful_for :messages assert_singleton_restful_for :logo, :name_prefix => 'message_', :path_prefix => 'messages/1/', :options => { :message_id => '1' } end end def test_shallow_resource_has_one_should_become_shallow_nested_resources with_routing do |set| set.draw do |map| map.resources :messages, :has_one => :logo, :shallow => true end assert_simply_restful_for :messages, :shallow => true assert_singleton_restful_for :logo, :name_prefix => 'message_', :path_prefix => 'messages/1/', :shallow => true, :options => { :message_id => '1' } end end def test_singleton_resource_with_member_action [:put, :post].each do |method| with_singleton_resources :account, :member => { :reset => method } do reset_options = {:action => 'reset'} reset_path = "/account/reset" assert_singleton_routes_for :account do |options| assert_recognizes(options.merge(reset_options), :path => reset_path, :method => method) end assert_singleton_named_routes_for :account do |options| assert_named_route reset_path, :reset_account_path, reset_options end end end end def test_singleton_resource_with_two_member_actions_with_same_method [:put, :post].each do |method| with_singleton_resources :account, :member => { :reset => method, :disable => method } do %w(reset disable).each do |action| action_options = {:action => action} action_path = "/account/#{action}" assert_singleton_routes_for :account do |options| assert_recognizes(options.merge(action_options), :path => action_path, :method => method) end assert_singleton_named_routes_for :account do |options| assert_named_route action_path, "#{action}_account_path".to_sym, action_options end end end end end def test_should_nest_resources_in_singleton_resource with_routing do |set| set.draw do |map| map.resource :account do |account| account.resources :messages end end assert_singleton_restful_for :account assert_simply_restful_for :messages, :name_prefix => "account_", :path_prefix => 'account/' end end def test_should_nest_resources_in_singleton_resource_with_path_prefix with_routing do |set| set.draw do |map| map.resource(:account, :path_prefix => ':site_id') do |account| account.resources :messages end end assert_singleton_restful_for :account, :path_prefix => '7/', :options => { :site_id => '7' } assert_simply_restful_for :messages, :name_prefix => "account_", :path_prefix => '7/account/', :options => { :site_id => '7' } end end def test_should_nest_singleton_resource_in_resources with_routing do |set| set.draw do |map| map.resources :threads do |thread| thread.resource :admin, :controller => 'admin' end end assert_simply_restful_for :threads assert_singleton_restful_for :admin, :controller => 'admin', :name_prefix => 'thread_', :path_prefix => 'threads/5/', :options => { :thread_id => '5' } end end def test_should_not_allow_delete_or_put_on_collection_path controller_name = :messages with_restful_routing controller_name do options = { :controller => controller_name.to_s } collection_path = "/#{controller_name}" assert_raise(ActionController::MethodNotAllowed) do assert_recognizes(options.merge(:action => 'update'), :path => collection_path, :method => :put) end assert_raise(ActionController::MethodNotAllowed) do assert_recognizes(options.merge(:action => 'destroy'), :path => collection_path, :method => :delete) end end end def test_should_not_allow_invalid_head_method_for_member_routes with_routing do |set| set.draw do |map| assert_raise(ArgumentError) do map.resources :messages, :member => {:something => :head} end end end end def test_should_not_allow_invalid_http_methods_for_member_routes with_routing do |set| set.draw do |map| assert_raise(ArgumentError) do map.resources :messages, :member => {:something => :invalid} end end end end def test_resource_action_separator with_routing do |set| set.draw do |map| map.resources :messages, :collection => {:search => :get}, :new => {:preview => :any}, :name_prefix => 'thread_', :path_prefix => '/threads/:thread_id' map.resource :account, :member => {:login => :get}, :new => {:preview => :any}, :name_prefix => 'admin_', :path_prefix => '/admin' end action_separator = ActionController::Base.resource_action_separator assert_simply_restful_for :messages, :name_prefix => 'thread_', :path_prefix => 'threads/1/', :options => { :thread_id => '1' } assert_named_route "/threads/1/messages#{action_separator}search", "search_thread_messages_path", {} assert_named_route "/threads/1/messages/new", "new_thread_message_path", {} assert_named_route "/threads/1/messages/new#{action_separator}preview", "preview_new_thread_message_path", {} assert_singleton_restful_for :account, :name_prefix => 'admin_', :path_prefix => 'admin/' assert_named_route "/admin/account#{action_separator}login", "login_admin_account_path", {} assert_named_route "/admin/account/new", "new_admin_account_path", {} assert_named_route "/admin/account/new#{action_separator}preview", "preview_new_admin_account_path", {} end end def test_new_style_named_routes_for_resource with_routing do |set| set.draw do |map| map.resources :messages, :collection => {:search => :get}, :new => {:preview => :any}, :name_prefix => 'thread_', :path_prefix => '/threads/:thread_id' end assert_simply_restful_for :messages, :name_prefix => 'thread_', :path_prefix => 'threads/1/', :options => { :thread_id => '1' } assert_named_route "/threads/1/messages/search", "search_thread_messages_path", {} assert_named_route "/threads/1/messages/new", "new_thread_message_path", {} assert_named_route "/threads/1/messages/new/preview", "preview_new_thread_message_path", {} end end def test_new_style_named_routes_for_singleton_resource with_routing do |set| set.draw do |map| map.resource :account, :member => {:login => :get}, :new => {:preview => :any}, :name_prefix => 'admin_', :path_prefix => '/admin' end assert_singleton_restful_for :account, :name_prefix => 'admin_', :path_prefix => 'admin/' assert_named_route "/admin/account/login", "login_admin_account_path", {} assert_named_route "/admin/account/new", "new_admin_account_path", {} assert_named_route "/admin/account/new/preview", "preview_new_admin_account_path", {} end end def test_resources_in_namespace with_routing do |set| set.draw do |map| map.namespace :backoffice do |backoffice| backoffice.resources :products end end assert_simply_restful_for :products, :controller => "backoffice/products", :name_prefix => 'backoffice_', :path_prefix => 'backoffice/' end end def test_resource_has_many_in_namespace with_routing do |set| set.draw do |map| map.namespace :backoffice do |backoffice| backoffice.resources :products, :has_many => :tags end end assert_simply_restful_for :products, :controller => "backoffice/products", :name_prefix => 'backoffice_', :path_prefix => 'backoffice/' assert_simply_restful_for :tags, :controller => "backoffice/tags", :name_prefix => "backoffice_product_", :path_prefix => 'backoffice/products/1/', :options => { :product_id => '1' } end end def test_resource_has_one_in_namespace with_routing do |set| set.draw do |map| map.namespace :backoffice do |backoffice| backoffice.resources :products, :has_one => :manufacturer end end assert_simply_restful_for :products, :controller => "backoffice/products", :name_prefix => 'backoffice_', :path_prefix => 'backoffice/' assert_singleton_restful_for :manufacturer, :controller => "backoffice/manufacturers", :name_prefix => 'backoffice_product_', :path_prefix => 'backoffice/products/1/', :options => { :product_id => '1' } end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/fake_controllers.rb
provider/vendor/rails/actionpack/test/controller/fake_controllers.rb
class << Object; alias_method :const_available?, :const_defined?; end class ContentController < Class.new(ActionController::Base) end class NotAController end module Admin class << self; alias_method :const_available?, :const_defined?; end class UserController < Class.new(ActionController::Base); end class NewsFeedController < Class.new(ActionController::Base); end end # For speed test class SpeedController < ActionController::Base; end class SearchController < SpeedController; end class VideosController < SpeedController; end class VideoFileController < SpeedController; end class VideoSharesController < SpeedController; end class VideoAbusesController < SpeedController; end class VideoUploadsController < SpeedController; end class VideoVisitsController < SpeedController; end class UsersController < SpeedController; end class SettingsController < SpeedController; end class ChannelsController < SpeedController; end class ChannelVideosController < SpeedController; end class SessionsController < SpeedController; end class LostPasswordsController < SpeedController; end class PagesController < SpeedController; end ActionController::Routing::Routes.draw do |map| map.route_one 'route_one', :controller => 'elsewhere', :action => 'flash_me' map.connect ':controller/:action/:id' end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/url_rewriter_test.rb
provider/vendor/rails/actionpack/test/controller/url_rewriter_test.rb
require 'abstract_unit' ActionController::UrlRewriter class UrlRewriterTests < ActionController::TestCase def setup @request = ActionController::TestRequest.new @params = {} @rewriter = ActionController::UrlRewriter.new(@request, @params) end def test_port assert_equal('http://test.host:1271/c/a/i', @rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :port => 1271) ) end def test_protocol_with_and_without_separator assert_equal('https://test.host/c/a/i', @rewriter.rewrite(:protocol => 'https', :controller => 'c', :action => 'a', :id => 'i') ) assert_equal('https://test.host/c/a/i', @rewriter.rewrite(:protocol => 'https://', :controller => 'c', :action => 'a', :id => 'i') ) end def test_user_name_and_password assert_equal( 'http://david:secret@test.host/c/a/i', @rewriter.rewrite(:user => "david", :password => "secret", :controller => 'c', :action => 'a', :id => 'i') ) end def test_user_name_and_password_with_escape_codes assert_equal( 'http://openid.aol.com%2Fnextangler:one+two%3F@test.host/c/a/i', @rewriter.rewrite(:user => "openid.aol.com/nextangler", :password => "one two?", :controller => 'c', :action => 'a', :id => 'i') ) end def test_anchor assert_equal( 'http://test.host/c/a/i#anchor', @rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :anchor => 'anchor') ) end def test_anchor_should_call_to_param assert_equal( 'http://test.host/c/a/i#anchor', @rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anchor')) ) end def test_anchor_should_be_cgi_escaped assert_equal( 'http://test.host/c/a/i#anc%2Fhor', @rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anc/hor')) ) end def test_overwrite_params @params[:controller] = 'hi' @params[:action] = 'bye' @params[:id] = '2' assert_equal '/hi/hi/2', @rewriter.rewrite(:only_path => true, :overwrite_params => {:action => 'hi'}) u = @rewriter.rewrite(:only_path => false, :overwrite_params => {:action => 'hi'}) assert_match %r(/hi/hi/2$), u end def test_overwrite_removes_original @params[:controller] = 'search' @params[:action] = 'list' @params[:list_page] = 1 assert_equal '/search/list?list_page=2', @rewriter.rewrite(:only_path => true, :overwrite_params => {"list_page" => 2}) u = @rewriter.rewrite(:only_path => false, :overwrite_params => {:list_page => 2}) assert_equal 'http://test.host/search/list?list_page=2', u end def test_to_str @params[:controller] = 'hi' @params[:action] = 'bye' @request.parameters[:id] = '2' assert_equal 'http://, test.host, /, hi, bye, {"id"=>"2"}', @rewriter.to_str end def test_trailing_slash options = {:controller => 'foo', :action => 'bar', :id => '3', :only_path => true} assert_equal '/foo/bar/3', @rewriter.rewrite(options) assert_equal '/foo/bar/3?query=string', @rewriter.rewrite(options.merge({:query => 'string'})) options.update({:trailing_slash => true}) assert_equal '/foo/bar/3/', @rewriter.rewrite(options) options.update({:query => 'string'}) assert_equal '/foo/bar/3/?query=string', @rewriter.rewrite(options) end end class UrlWriterTests < ActionController::TestCase class W include ActionController::UrlWriter end def teardown W.default_url_options.clear end def add_host! W.default_url_options[:host] = 'www.basecamphq.com' end def test_exception_is_thrown_without_host assert_raise RuntimeError do W.new.url_for :controller => 'c', :action => 'a', :id => 'i' end end def test_anchor assert_equal('/c/a#anchor', W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => 'anchor') ) end def test_anchor_should_call_to_param assert_equal('/c/a#anchor', W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => Struct.new(:to_param).new('anchor')) ) end def test_anchor_should_be_cgi_escaped assert_equal('/c/a#anc%2Fhor', W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => Struct.new(:to_param).new('anc/hor')) ) end def test_default_host add_host! assert_equal('http://www.basecamphq.com/c/a/i', W.new.url_for(:controller => 'c', :action => 'a', :id => 'i') ) end def test_host_may_be_overridden add_host! assert_equal('http://37signals.basecamphq.com/c/a/i', W.new.url_for(:host => '37signals.basecamphq.com', :controller => 'c', :action => 'a', :id => 'i') ) end def test_port add_host! assert_equal('http://www.basecamphq.com:3000/c/a/i', W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :port => 3000) ) end def test_protocol add_host! assert_equal('https://www.basecamphq.com/c/a/i', W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https') ) end def test_protocol_with_and_without_separator add_host! assert_equal('https://www.basecamphq.com/c/a/i', W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https') ) assert_equal('https://www.basecamphq.com/c/a/i', W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https://') ) end def test_trailing_slash add_host! options = {:controller => 'foo', :trailing_slash => true, :action => 'bar', :id => '33'} assert_equal('http://www.basecamphq.com/foo/bar/33/', W.new.url_for(options) ) end def test_trailing_slash_with_protocol add_host! options = { :trailing_slash => true,:protocol => 'https', :controller => 'foo', :action => 'bar', :id => '33'} assert_equal('https://www.basecamphq.com/foo/bar/33/', W.new.url_for(options) ) assert_equal 'https://www.basecamphq.com/foo/bar/33/?query=string', W.new.url_for(options.merge({:query => 'string'})) end def test_trailing_slash_with_only_path options = {:controller => 'foo', :trailing_slash => true} assert_equal '/foo/', W.new.url_for(options.merge({:only_path => true})) options.update({:action => 'bar', :id => '33'}) assert_equal '/foo/bar/33/', W.new.url_for(options.merge({:only_path => true})) assert_equal '/foo/bar/33/?query=string', W.new.url_for(options.merge({:query => 'string',:only_path => true})) end def test_trailing_slash_with_anchor options = {:trailing_slash => true, :controller => 'foo', :action => 'bar', :id => '33', :only_path => true, :anchor=> 'chapter7'} assert_equal '/foo/bar/33/#chapter7', W.new.url_for(options) assert_equal '/foo/bar/33/?query=string#chapter7', W.new.url_for(options.merge({:query => 'string'})) end def test_trailing_slash_with_params url = W.new.url_for(:trailing_slash => true, :only_path => true, :controller => 'cont', :action => 'act', :p1 => 'cafe', :p2 => 'link') params = extract_params(url) assert_equal params[0], { :p1 => 'cafe' }.to_query assert_equal params[1], { :p2 => 'link' }.to_query end def test_relative_url_root_is_respected orig_relative_url_root = ActionController::Base.relative_url_root ActionController::Base.relative_url_root = '/subdir' add_host! assert_equal('https://www.basecamphq.com/subdir/c/a/i', W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https') ) ensure ActionController::Base.relative_url_root = orig_relative_url_root end def test_named_routes ActionController::Routing::Routes.draw do |map| map.no_args '/this/is/verbose', :controller => 'home', :action => 'index' map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index' map.connect ':controller/:action/:id' end # We need to create a new class in order to install the new named route. kls = Class.new { include ActionController::UrlWriter } controller = kls.new assert controller.respond_to?(:home_url) assert_equal 'http://www.basecamphq.com/home/sweet/home/again', controller.send(:home_url, :host => 'www.basecamphq.com', :user => 'again') assert_equal("/home/sweet/home/alabama", controller.send(:home_path, :user => 'alabama', :host => 'unused')) assert_equal("http://www.basecamphq.com/home/sweet/home/alabama", controller.send(:home_url, :user => 'alabama', :host => 'www.basecamphq.com')) assert_equal("http://www.basecamphq.com/this/is/verbose", controller.send(:no_args_url, :host=>'www.basecamphq.com')) ensure ActionController::Routing::Routes.load! end def test_relative_url_root_is_respected_for_named_routes orig_relative_url_root = ActionController::Base.relative_url_root ActionController::Base.relative_url_root = '/subdir' ActionController::Routing::Routes.draw do |map| map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index' end kls = Class.new { include ActionController::UrlWriter } controller = kls.new assert_equal 'http://www.basecamphq.com/subdir/home/sweet/home/again', controller.send(:home_url, :host => 'www.basecamphq.com', :user => 'again') ensure ActionController::Routing::Routes.load! ActionController::Base.relative_url_root = orig_relative_url_root end def test_only_path ActionController::Routing::Routes.draw do |map| map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index' map.connect ':controller/:action/:id' end # We need to create a new class in order to install the new named route. kls = Class.new { include ActionController::UrlWriter } controller = kls.new assert controller.respond_to?(:home_url) assert_equal '/brave/new/world', controller.send(:url_for, :controller => 'brave', :action => 'new', :id => 'world', :only_path => true) assert_equal("/home/sweet/home/alabama", controller.send(:home_url, :user => 'alabama', :host => 'unused', :only_path => true)) assert_equal("/home/sweet/home/alabama", controller.send(:home_path, 'alabama')) ensure ActionController::Routing::Routes.load! end def test_one_parameter assert_equal('/c/a?param=val', W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :param => 'val') ) end def test_two_parameters url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :p1 => 'X1', :p2 => 'Y2') params = extract_params(url) assert_equal params[0], { :p1 => 'X1' }.to_query assert_equal params[1], { :p2 => 'Y2' }.to_query end def test_hash_parameter url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :query => {:name => 'Bob', :category => 'prof'}) params = extract_params(url) assert_equal params[0], { 'query[category]' => 'prof' }.to_query assert_equal params[1], { 'query[name]' => 'Bob' }.to_query end def test_array_parameter url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :query => ['Bob', 'prof']) params = extract_params(url) assert_equal params[0], { 'query[]' => 'Bob' }.to_query assert_equal params[1], { 'query[]' => 'prof' }.to_query end def test_hash_recursive_parameters url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :query => {:person => {:name => 'Bob', :position => 'prof'}, :hobby => 'piercing'}) params = extract_params(url) assert_equal params[0], { 'query[hobby]' => 'piercing' }.to_query assert_equal params[1], { 'query[person][name]' => 'Bob' }.to_query assert_equal params[2], { 'query[person][position]' => 'prof' }.to_query end def test_hash_recursive_and_array_parameters url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :id => 101, :query => {:person => {:name => 'Bob', :position => ['prof', 'art director']}, :hobby => 'piercing'}) assert_match %r(^/c/a/101), url params = extract_params(url) assert_equal params[0], { 'query[hobby]' => 'piercing' }.to_query assert_equal params[1], { 'query[person][name]' => 'Bob' }.to_query assert_equal params[2], { 'query[person][position][]' => 'prof' }.to_query assert_equal params[3], { 'query[person][position][]' => 'art director' }.to_query end def test_path_generation_for_symbol_parameter_keys assert_generates("/image", :controller=> :image) end def test_named_routes_with_nil_keys ActionController::Routing::Routes.clear! ActionController::Routing::Routes.draw do |map| map.main '', :controller => 'posts', :format => nil map.resources :posts map.connect ':controller/:action/:id' end # We need to create a new class in order to install the new named route. kls = Class.new { include ActionController::UrlWriter } kls.default_url_options[:host] = 'www.basecamphq.com' controller = kls.new params = {:action => :index, :controller => :posts, :format => :xml} assert_equal("http://www.basecamphq.com/posts.xml", controller.send(:url_for, params)) params[:format] = nil assert_equal("http://www.basecamphq.com/", controller.send(:url_for, params)) ensure ActionController::Routing::Routes.load! end def test_formatted_url_methods_are_deprecated ActionController::Routing::Routes.draw do |map| map.resources :posts end # We need to create a new class in order to install the new named route. kls = Class.new { include ActionController::UrlWriter } controller = kls.new params = {:id => 1, :format => :xml} assert_deprecated do assert_equal("/posts/1.xml", controller.send(:formatted_post_path, params)) end assert_deprecated do assert_equal("/posts/1.xml", controller.send(:formatted_post_path, 1, :xml)) end ensure ActionController::Routing::Routes.load! end def test_multiple_includes_maintain_distinct_options first_class = Class.new { include ActionController::UrlWriter } second_class = Class.new { include ActionController::UrlWriter } first_host, second_host = 'firsthost.com', 'secondhost.com' first_class.default_url_options[:host] = first_host second_class.default_url_options[:host] = second_host assert_equal first_class.default_url_options[:host], first_host assert_equal second_class.default_url_options[:host], second_host end private def extract_params(url) url.split('?', 2).last.split('&') end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/request_forgery_protection_test.rb
provider/vendor/rails/actionpack/test/controller/request_forgery_protection_test.rb
require 'abstract_unit' require 'digest/sha1' ActionController::Routing::Routes.draw do |map| map.connect ':controller/:action/:id' end # common controller actions module RequestForgeryProtectionActions def index render :inline => "<%= form_tag('/') {} %>" end def show_button render :inline => "<%= button_to('New', '/') {} %>" end def remote_form render :inline => "<% form_remote_tag(:url => '/') {} %>" end def unsafe render :text => 'pwn' end def rescue_action(e) raise e end end # sample controllers class RequestForgeryProtectionController < ActionController::Base include RequestForgeryProtectionActions protect_from_forgery :only => :index end class FreeCookieController < RequestForgeryProtectionController self.allow_forgery_protection = false def index render :inline => "<%= form_tag('/') {} %>" end def show_button render :inline => "<%= button_to('New', '/') {} %>" end end # common test methods module RequestForgeryProtectionTests def teardown ActionController::Base.request_forgery_protection_token = nil end def test_should_render_form_with_token_tag get :index assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token end def test_should_render_button_to_with_token_tag get :show_button assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token end def test_should_render_remote_form_with_only_one_token_parameter get :remote_form assert_equal 1, @response.body.scan(@token).size end def test_should_allow_get get :index assert_response :success end def test_should_allow_post_without_token_on_unsafe_action post :unsafe assert_response :success end def test_should_not_allow_html_post_without_token @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s assert_raise(ActionController::InvalidAuthenticityToken) { post :index, :format => :html } end def test_should_not_allow_html_put_without_token @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s assert_raise(ActionController::InvalidAuthenticityToken) { put :index, :format => :html } end def test_should_not_allow_html_delete_without_token @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s assert_raise(ActionController::InvalidAuthenticityToken) { delete :index, :format => :html } end def test_should_allow_api_formatted_post_without_token assert_nothing_raised do post :index, :format => 'xml' end end def test_should_not_allow_api_formatted_put_without_token assert_nothing_raised do put :index, :format => 'xml' end end def test_should_allow_api_formatted_delete_without_token assert_nothing_raised do delete :index, :format => 'xml' end end def test_should_not_allow_api_formatted_post_sent_as_url_encoded_form_without_token assert_raise(ActionController::InvalidAuthenticityToken) do @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s post :index, :format => 'xml' end end def test_should_not_allow_api_formatted_put_sent_as_url_encoded_form_without_token assert_raise(ActionController::InvalidAuthenticityToken) do @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s put :index, :format => 'xml' end end def test_should_not_allow_api_formatted_delete_sent_as_url_encoded_form_without_token assert_raise(ActionController::InvalidAuthenticityToken) do @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s delete :index, :format => 'xml' end end def test_should_not_allow_api_formatted_post_sent_as_multipart_form_without_token assert_raise(ActionController::InvalidAuthenticityToken) do @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s post :index, :format => 'xml' end end def test_should_not_allow_api_formatted_put_sent_as_multipart_form_without_token assert_raise(ActionController::InvalidAuthenticityToken) do @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s put :index, :format => 'xml' end end def test_should_not_allow_api_formatted_delete_sent_as_multipart_form_without_token assert_raise(ActionController::InvalidAuthenticityToken) do @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s delete :index, :format => 'xml' end end def test_should_allow_xhr_post_without_token assert_nothing_raised { xhr :post, :index } end def test_should_allow_xhr_put_without_token assert_nothing_raised { xhr :put, :index } end def test_should_allow_xhr_delete_without_token assert_nothing_raised { xhr :delete, :index } end def test_should_allow_xhr_post_with_encoded_form_content_type_without_token @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s assert_nothing_raised { xhr :post, :index } end def test_should_allow_post_with_token post :index, :authenticity_token => @token assert_response :success end def test_should_allow_put_with_token put :index, :authenticity_token => @token assert_response :success end def test_should_allow_delete_with_token delete :index, :authenticity_token => @token assert_response :success end def test_should_allow_post_with_xml @request.env['CONTENT_TYPE'] = Mime::XML.to_s post :index, :format => 'xml' assert_response :success end def test_should_allow_put_with_xml @request.env['CONTENT_TYPE'] = Mime::XML.to_s put :index, :format => 'xml' assert_response :success end def test_should_allow_delete_with_xml @request.env['CONTENT_TYPE'] = Mime::XML.to_s delete :index, :format => 'xml' assert_response :success end end # OK let's get our test on class RequestForgeryProtectionControllerTest < ActionController::TestCase include RequestForgeryProtectionTests def setup @controller = RequestForgeryProtectionController.new @request = ActionController::TestRequest.new @request.format = :html @response = ActionController::TestResponse.new @token = "cf50faa3fe97702ca1ae" ActiveSupport::SecureRandom.stubs(:base64).returns(@token) ActionController::Base.request_forgery_protection_token = :authenticity_token end end class FreeCookieControllerTest < ActionController::TestCase def setup @controller = FreeCookieController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @token = "cf50faa3fe97702ca1ae" ActiveSupport::SecureRandom.stubs(:base64).returns(@token) end def test_should_not_render_form_with_token_tag get :index assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false end def test_should_not_render_button_to_with_token_tag get :show_button assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false end def test_should_allow_all_methods_without_token [:post, :put, :delete].each do |method| assert_nothing_raised { send(method, :index)} end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/fake_models.rb
provider/vendor/rails/actionpack/test/controller/fake_models.rb
class Customer < Struct.new(:name, :id) def to_param id.to_s end end class BadCustomer < Customer end class GoodCustomer < Customer end module Quiz class Question < Struct.new(:name, :id) def to_param id.to_s end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/http_digest_authentication_test.rb
provider/vendor/rails/actionpack/test/controller/http_digest_authentication_test.rb
require 'abstract_unit' class HttpDigestAuthenticationTest < ActionController::TestCase class DummyDigestController < ActionController::Base before_filter :authenticate, :only => :index before_filter :authenticate_with_request, :only => :display USERS = { 'lifo' => 'world', 'pretty' => 'please', 'dhh' => ::Digest::MD5::hexdigest(["dhh","SuperSecret","secret"].join(":"))} def index render :text => "Hello Secret" end def display render :text => 'Definitely Maybe' end private def authenticate authenticate_or_request_with_http_digest("SuperSecret") do |username| # Return the password USERS[username] end end def authenticate_with_request if authenticate_with_http_digest("SuperSecret") { |username| USERS[username] } @logged_in = true else request_http_digest_authentication("SuperSecret", "Authentication Failed") end end end AUTH_HEADERS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION', 'REDIRECT_X_HTTP_AUTHORIZATION'] tests DummyDigestController AUTH_HEADERS.each do |header| test "successful authentication with #{header.downcase}" do @request.env[header] = encode_credentials(:username => 'lifo', :password => 'world') get :index assert_response :success assert_equal 'Hello Secret', @response.body, "Authentication failed for request header #{header}" end end AUTH_HEADERS.each do |header| test "unsuccessful authentication with #{header.downcase}" do @request.env[header] = encode_credentials(:username => 'h4x0r', :password => 'world') get :index assert_response :unauthorized assert_equal "HTTP Digest: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header}" end end test "authentication request without credential" do get :display assert_response :unauthorized assert_equal "Authentication Failed", @response.body credentials = decode_credentials(@response.headers['WWW-Authenticate']) assert_equal 'SuperSecret', credentials[:realm] end test "authentication request with nil credentials" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => nil, :password => nil) get :index assert_response :unauthorized assert_equal "HTTP Digest: Access denied.\n", @response.body, "Authentication didn't fail for request" assert_not_equal 'Hello Secret', @response.body, "Authentication didn't fail for request" end test "authentication request with invalid password" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'foo') get :display assert_response :unauthorized assert_equal "Authentication Failed", @response.body end test "authentication request with invalid nonce" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please', :nonce => "xxyyzz") get :display assert_response :unauthorized assert_equal "Authentication Failed", @response.body end test "authentication request with invalid opaque" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'foo', :opaque => "xxyyzz") get :display assert_response :unauthorized assert_equal "Authentication Failed", @response.body end test "authentication request with invalid realm" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'foo', :realm => "NotSecret") get :display assert_response :unauthorized assert_equal "Authentication Failed", @response.body end test "authentication request with valid credential" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please') get :display assert_response :success assert assigns(:logged_in) assert_equal 'Definitely Maybe', @response.body end test "authentication request with valid credential and nil session" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please') # session_id = "" in functional test, but is +nil+ in real life @request.session.session_id = nil get :display assert_response :success assert assigns(:logged_in) assert_equal 'Definitely Maybe', @response.body end test "authentication request with request-uri that doesn't match credentials digest-uri" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please') @request.env['REQUEST_URI'] = "/http_digest_authentication_test/dummy_digest/altered/uri" get :display assert_response :unauthorized assert_equal "Authentication Failed", @response.body end test "authentication request with absolute request uri (as in webrick)" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please') @request.env['REQUEST_URI'] = "http://test.host/http_digest_authentication_test/dummy_digest" get :display assert_response :success assert assigns(:logged_in) assert_equal 'Definitely Maybe', @response.body end test "authentication request with absolute uri in credentials (as in IE)" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:url => "http://test.host/http_digest_authentication_test/dummy_digest", :username => 'pretty', :password => 'please') get :display assert_response :success assert assigns(:logged_in) assert_equal 'Definitely Maybe', @response.body end test "authentication request with absolute uri in both request and credentials (as in Webrick with IE)" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:url => "http://test.host/http_digest_authentication_test/dummy_digest", :username => 'pretty', :password => 'please') @request.env['REQUEST_URI'] = "http://test.host/http_digest_authentication_test/dummy_digest" get :display assert_response :success assert assigns(:logged_in) assert_equal 'Definitely Maybe', @response.body end test "authentication request with password stored as ha1 digest hash" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'dhh', :password => ::Digest::MD5::hexdigest(["dhh","SuperSecret","secret"].join(":")), :password_is_ha1 => true) get :display assert_response :success assert assigns(:logged_in) assert_equal 'Definitely Maybe', @response.body end test "authentication request with _method" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please', :method => :post) @request.env['rack.methodoverride.original_method'] = 'POST' put :display assert_response :success assert assigns(:logged_in) assert_equal 'Definitely Maybe', @response.body end test "validate_digest_response should fail with nil returning password_procedure" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => nil, :password => nil) assert !ActionController::HttpAuthentication::Digest.validate_digest_response(@request, "SuperSecret"){nil} end private def encode_credentials(options) options.reverse_merge!(:nc => "00000001", :cnonce => "0a4f113b", :password_is_ha1 => false) password = options.delete(:password) # Set in /initializers/session_store.rb. Used as secret in generating nonce # to prevent tampering of timestamp ActionController::Base.session_options[:secret] = "session_options_secret" # Perform unauthenticated request to retrieve digest parameters to use on subsequent request method = options.delete(:method) || 'GET' case method.to_s.upcase when 'GET' get :index when 'POST' post :index end assert_response :unauthorized credentials = decode_credentials(@response.headers['WWW-Authenticate']) credentials.merge!(options) credentials.merge!(:uri => @request.env['REQUEST_URI'].to_s) ActionController::HttpAuthentication::Digest.encode_credentials(method, credentials, password, options[:password_is_ha1]) end def decode_credentials(header) ActionController::HttpAuthentication::Digest.decode_credentials(@response.headers['WWW-Authenticate']) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/mime_responds_test.rb
provider/vendor/rails/actionpack/test/controller/mime_responds_test.rb
require 'abstract_unit' class RespondToController < ActionController::Base layout :set_layout def html_xml_or_rss respond_to do |type| type.html { render :text => "HTML" } type.xml { render :text => "XML" } type.rss { render :text => "RSS" } type.all { render :text => "Nothing" } end end def js_or_html respond_to do |type| type.html { render :text => "HTML" } type.js { render :text => "JS" } type.all { render :text => "Nothing" } end end def json_or_yaml respond_to do |type| type.json { render :text => "JSON" } type.yaml { render :text => "YAML" } end end def html_or_xml respond_to do |type| type.html { render :text => "HTML" } type.xml { render :text => "XML" } type.all { render :text => "Nothing" } end end def forced_xml request.format = :xml respond_to do |type| type.html { render :text => "HTML" } type.xml { render :text => "XML" } end end def just_xml respond_to do |type| type.xml { render :text => "XML" } end end def using_defaults respond_to do |type| type.html type.js type.xml end end def using_defaults_with_type_list respond_to(:html, :js, :xml) end def made_for_content_type respond_to do |type| type.rss { render :text => "RSS" } type.atom { render :text => "ATOM" } type.all { render :text => "Nothing" } end end def custom_type_handling respond_to do |type| type.html { render :text => "HTML" } type.custom("application/crazy-xml") { render :text => "Crazy XML" } type.all { render :text => "Nothing" } end end def custom_constant_handling Mime::Type.register("text/x-mobile", :mobile) respond_to do |type| type.html { render :text => "HTML" } type.mobile { render :text => "Mobile" } end ensure Mime.module_eval { remove_const :MOBILE if const_defined?(:MOBILE) } end def custom_constant_handling_without_block Mime::Type.register("text/x-mobile", :mobile) respond_to do |type| type.html { render :text => "HTML" } type.mobile end ensure Mime.module_eval { remove_const :MOBILE if const_defined?(:MOBILE) } end def handle_any respond_to do |type| type.html { render :text => "HTML" } type.any(:js, :xml) { render :text => "Either JS or XML" } end end def handle_any_any respond_to do |type| type.html { render :text => 'HTML' } type.any { render :text => 'Whatever you ask for, I got it' } end end def all_types_with_layout respond_to do |type| type.html type.js end end def iphone_with_html_response_type Mime::Type.register_alias("text/html", :iphone) request.format = :iphone if request.env["HTTP_ACCEPT"] == "text/iphone" respond_to do |type| type.html { @type = "Firefox" } type.iphone { @type = "iPhone" } end ensure Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) } end def iphone_with_html_response_type_without_layout Mime::Type.register_alias("text/html", :iphone) request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone" respond_to do |type| type.html { @type = "Firefox"; render :action => "iphone_with_html_response_type" } type.iphone { @type = "iPhone" ; render :action => "iphone_with_html_response_type" } end ensure Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) } end def rescue_action(e) raise end protected def set_layout if ["all_types_with_layout", "iphone_with_html_response_type"].include?(action_name) "respond_to/layouts/standard" elsif action_name == "iphone_with_html_response_type_without_layout" "respond_to/layouts/missing" end end end class MimeControllerTest < ActionController::TestCase tests RespondToController def setup ActionController::Base.use_accept_header = true @request.host = "www.example.com" end def teardown ActionController::Base.use_accept_header = false end def test_html @request.accept = "text/html" get :js_or_html assert_equal 'HTML', @response.body get :html_or_xml assert_equal 'HTML', @response.body get :just_xml assert_response 406 end def test_all @request.accept = "*/*" get :js_or_html assert_equal 'HTML', @response.body # js is not part of all get :html_or_xml assert_equal 'HTML', @response.body get :just_xml assert_equal 'XML', @response.body end def test_xml @request.accept = "application/xml" get :html_xml_or_rss assert_equal 'XML', @response.body end def test_js_or_html @request.accept = "text/javascript, text/html" get :js_or_html assert_equal 'JS', @response.body get :html_or_xml assert_equal 'HTML', @response.body get :just_xml assert_response 406 end def test_json_or_yaml get :json_or_yaml assert_equal 'JSON', @response.body get :json_or_yaml, :format => 'json' assert_equal 'JSON', @response.body get :json_or_yaml, :format => 'yaml' assert_equal 'YAML', @response.body { 'YAML' => %w(text/yaml), 'JSON' => %w(application/json text/x-json) }.each do |body, content_types| content_types.each do |content_type| @request.accept = content_type get :json_or_yaml assert_equal body, @response.body end end end def test_js_or_anything @request.accept = "text/javascript, */*" get :js_or_html assert_equal 'JS', @response.body get :html_or_xml assert_equal 'HTML', @response.body get :just_xml assert_equal 'XML', @response.body end def test_using_defaults @request.accept = "*/*" get :using_defaults assert_equal "text/html", @response.content_type assert_equal 'Hello world!', @response.body @request.accept = "text/javascript" get :using_defaults assert_equal "text/javascript", @response.content_type assert_equal '$("body").visualEffect("highlight");', @response.body @request.accept = "application/xml" get :using_defaults assert_equal "application/xml", @response.content_type assert_equal "<p>Hello world!</p>\n", @response.body end def test_using_defaults_with_type_list @request.accept = "*/*" get :using_defaults_with_type_list assert_equal "text/html", @response.content_type assert_equal 'Hello world!', @response.body @request.accept = "text/javascript" get :using_defaults_with_type_list assert_equal "text/javascript", @response.content_type assert_equal '$("body").visualEffect("highlight");', @response.body @request.accept = "application/xml" get :using_defaults_with_type_list assert_equal "application/xml", @response.content_type assert_equal "<p>Hello world!</p>\n", @response.body end def test_with_atom_content_type @request.env["CONTENT_TYPE"] = "application/atom+xml" get :made_for_content_type assert_equal "ATOM", @response.body end def test_with_rss_content_type @request.env["CONTENT_TYPE"] = "application/rss+xml" get :made_for_content_type assert_equal "RSS", @response.body end def test_synonyms @request.accept = "application/javascript" get :js_or_html assert_equal 'JS', @response.body @request.accept = "application/x-xml" get :html_xml_or_rss assert_equal "XML", @response.body end def test_custom_types @request.accept = "application/crazy-xml" get :custom_type_handling assert_equal "application/crazy-xml", @response.content_type assert_equal 'Crazy XML', @response.body @request.accept = "text/html" get :custom_type_handling assert_equal "text/html", @response.content_type assert_equal 'HTML', @response.body end def test_xhtml_alias @request.accept = "application/xhtml+xml,application/xml" get :html_or_xml assert_equal 'HTML', @response.body end def test_firefox_simulation @request.accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" get :html_or_xml assert_equal 'HTML', @response.body end def test_handle_any @request.accept = "*/*" get :handle_any assert_equal 'HTML', @response.body @request.accept = "text/javascript" get :handle_any assert_equal 'Either JS or XML', @response.body @request.accept = "text/xml" get :handle_any assert_equal 'Either JS or XML', @response.body end def test_handle_any_any @request.accept = "*/*" get :handle_any_any assert_equal 'HTML', @response.body end def test_handle_any_any_parameter_format get :handle_any_any, {:format=>'html'} assert_equal 'HTML', @response.body end def test_handle_any_any_explicit_html @request.accept = "text/html" get :handle_any_any assert_equal 'HTML', @response.body end def test_handle_any_any_javascript @request.accept = "text/javascript" get :handle_any_any assert_equal 'Whatever you ask for, I got it', @response.body end def test_handle_any_any_xml @request.accept = "text/xml" get :handle_any_any assert_equal 'Whatever you ask for, I got it', @response.body end def test_rjs_type_skips_layout @request.accept = "text/javascript" get :all_types_with_layout assert_equal 'RJS for all_types_with_layout', @response.body end def test_html_type_with_layout @request.accept = "text/html" get :all_types_with_layout assert_equal '<html><div id="html">HTML for all_types_with_layout</div></html>', @response.body end def test_xhr xhr :get, :js_or_html assert_equal 'JS', @response.body xhr :get, :using_defaults assert_equal '$("body").visualEffect("highlight");', @response.body end def test_custom_constant get :custom_constant_handling, :format => "mobile" assert_equal "text/x-mobile", @response.content_type assert_equal "Mobile", @response.body end def test_custom_constant_handling_without_block get :custom_constant_handling_without_block, :format => "mobile" assert_equal "text/x-mobile", @response.content_type assert_equal "Mobile", @response.body end def test_forced_format get :html_xml_or_rss assert_equal "HTML", @response.body get :html_xml_or_rss, :format => "html" assert_equal "HTML", @response.body get :html_xml_or_rss, :format => "xml" assert_equal "XML", @response.body get :html_xml_or_rss, :format => "rss" assert_equal "RSS", @response.body end def test_internally_forced_format get :forced_xml assert_equal "XML", @response.body get :forced_xml, :format => "html" assert_equal "XML", @response.body end def test_extension_synonyms get :html_xml_or_rss, :format => "xhtml" assert_equal "HTML", @response.body end def test_render_action_for_html @controller.instance_eval do def render(*args) unless args.empty? @action = args.first[:action] end response.body = "#{@action} - #{@template.template_format}" end end get :using_defaults assert_equal "using_defaults - html", @response.body get :using_defaults, :format => "xml" assert_equal "using_defaults - xml", @response.body end def test_format_with_custom_response_type get :iphone_with_html_response_type assert_equal '<html><div id="html">Hello future from Firefox!</div></html>', @response.body get :iphone_with_html_response_type, :format => "iphone" assert_equal "text/html", @response.content_type assert_equal '<html><div id="iphone">Hello iPhone future from iPhone!</div></html>', @response.body end def test_format_with_custom_response_type_and_request_headers @request.accept = "text/iphone" get :iphone_with_html_response_type assert_equal '<html><div id="iphone">Hello iPhone future from iPhone!</div></html>', @response.body assert_equal "text/html", @response.content_type end def test_format_with_custom_response_type_and_request_headers_with_only_one_layout_present get :iphone_with_html_response_type_without_layout assert_equal '<html><div id="html_missing">Hello future from Firefox!</div></html>', @response.body @request.accept = "text/iphone" assert_raise(ActionView::MissingTemplate) { get :iphone_with_html_response_type_without_layout } end end class AbstractPostController < ActionController::Base self.view_paths = File.dirname(__FILE__) + "/../fixtures/post_test/" end # For testing layouts which are set automatically class PostController < AbstractPostController around_filter :with_iphone def index respond_to do |type| type.html type.iphone end end protected def with_iphone Mime::Type.register_alias("text/html", :iphone) request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone" yield ensure Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) } end end class SuperPostController < PostController def index respond_to do |type| type.html type.iphone end end end class MimeControllerLayoutsTest < ActionController::TestCase tests PostController def setup @request.host = "www.example.com" end def test_missing_layout_renders_properly get :index assert_equal '<html><div id="html">Hello Firefox</div></html>', @response.body @request.accept = "text/iphone" get :index assert_equal 'Hello iPhone', @response.body end def test_format_with_inherited_layouts @controller = SuperPostController.new get :index assert_equal 'Super Firefox', @response.body @request.accept = "text/iphone" get :index assert_equal '<html><div id="super_iphone">Super iPhone</div></html>', @response.body end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/routing_test.rb
provider/vendor/rails/actionpack/test/controller/routing_test.rb
require 'abstract_unit' require 'controller/fake_controllers' require 'action_controller/routing/route_set' class MilestonesController < ActionController::Base def index() head :ok end alias_method :show, :index def rescue_action(e) raise e end end RunTimeTests = ARGV.include? 'time' ROUTING = ActionController::Routing class ROUTING::RouteBuilder attr_reader :warn_output def warn(msg) (@warn_output ||= []) << msg end end # See RFC 3986, section 3.3 for allowed path characters. class UriReservedCharactersRoutingTest < Test::Unit::TestCase def setup ActionController::Routing.use_controllers! ['controller'] @set = ActionController::Routing::RouteSet.new @set.draw do |map| map.connect ':controller/:action/:variable/*additional' end safe, unsafe = %w(: @ & = + $ , ;), %w(^ / ? # [ ]) hex = unsafe.map { |char| '%' + char.unpack('H2').first.upcase } @segment = "#{safe.join}#{unsafe.join}".freeze @escaped = "#{safe.join}#{hex.join}".freeze end def test_route_generation_escapes_unsafe_path_characters assert_equal "/contr#{@segment}oller/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2", @set.generate(:controller => "contr#{@segment}oller", :action => "act#{@segment}ion", :variable => "var#{@segment}iable", :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"]) end def test_route_recognition_unescapes_path_components options = { :controller => "controller", :action => "act#{@segment}ion", :variable => "var#{@segment}iable", :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"] } assert_equal options, @set.recognize_path("/controller/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2") end def test_route_generation_allows_passing_non_string_values_to_generated_helper assert_equal "/controller/action/variable/1/2", @set.generate(:controller => "controller", :action => "action", :variable => "variable", :additional => [1, 2]) end end class SegmentTest < Test::Unit::TestCase def test_first_segment_should_interpolate_for_structure s = ROUTING::Segment.new def s.interpolation_statement(array) 'hello' end assert_equal 'hello', s.continue_string_structure([]) end def test_interpolation_statement s = ROUTING::StaticSegment.new("Hello") assert_equal "Hello", eval(s.interpolation_statement([])) assert_equal "HelloHello", eval(s.interpolation_statement([s])) s2 = ROUTING::StaticSegment.new("-") assert_equal "Hello-Hello", eval(s.interpolation_statement([s, s2])) s3 = ROUTING::StaticSegment.new("World") assert_equal "Hello-World", eval(s3.interpolation_statement([s, s2])) end end class StaticSegmentTest < Test::Unit::TestCase def test_interpolation_chunk_should_respect_raw s = ROUTING::StaticSegment.new('Hello World') assert !s.raw? assert_equal 'Hello%20World', s.interpolation_chunk s = ROUTING::StaticSegment.new('Hello World', :raw => true) assert s.raw? assert_equal 'Hello World', s.interpolation_chunk end def test_regexp_chunk_should_escape_specials s = ROUTING::StaticSegment.new('Hello*World') assert_equal 'Hello\*World', s.regexp_chunk s = ROUTING::StaticSegment.new('HelloWorld') assert_equal 'HelloWorld', s.regexp_chunk end def test_regexp_chunk_should_add_question_mark_for_optionals s = ROUTING::StaticSegment.new("/", :optional => true) assert_equal "/?", s.regexp_chunk s = ROUTING::StaticSegment.new("hello", :optional => true) assert_equal "(?:hello)?", s.regexp_chunk end end class DynamicSegmentTest < Test::Unit::TestCase def segment(options = {}) unless @segment @segment = ROUTING::DynamicSegment.new(:a, options) end @segment end def test_extract_value s = ROUTING::DynamicSegment.new(:a) hash = {:a => '10', :b => '20'} assert_equal '10', eval(s.extract_value) hash = {:b => '20'} assert_equal nil, eval(s.extract_value) s.default = '20' assert_equal '20', eval(s.extract_value) end def test_default_local_name assert_equal 'a_value', segment.local_name, "Unexpected name -- all value_check tests will fail!" end def test_presence_value_check a_value = 10 assert eval(segment.value_check) end def test_regexp_value_check_rejects_nil segment = segment(:regexp => /\d+/) a_value = nil assert !eval(segment.value_check) end def test_optional_regexp_value_check_should_accept_nil segment = segment(:regexp => /\d+/, :optional => true) a_value = nil assert eval(segment.value_check) end def test_regexp_value_check_rejects_no_match segment = segment(:regexp => /\d+/) a_value = "Hello20World" assert !eval(segment.value_check) a_value = "20Hi" assert !eval(segment.value_check) end def test_regexp_value_check_accepts_match segment = segment(:regexp => /\d+/) a_value = "30" assert eval(segment.value_check) end def test_value_check_fails_on_nil a_value = nil assert ! eval(segment.value_check) end def test_optional_value_needs_no_check segment = segment(:optional => true) a_value = nil assert_equal nil, segment.value_check end def test_regexp_value_check_should_accept_match_with_default segment = segment(:regexp => /\d+/, :default => '200') a_value = '100' assert eval(segment.value_check) end def test_expiry_should_not_trigger_once_expired expired = true hash = merged = {:a => 2, :b => 3} options = {:b => 3} expire_on = Hash.new { raise 'No!!!' } eval(segment.expiry_statement) rescue RuntimeError flunk "Expiry check should not have occurred!" end def test_expiry_should_occur_according_to_expire_on expired = false hash = merged = {:a => 2, :b => 3} options = {:b => 3} expire_on = {:b => true, :a => false} eval(segment.expiry_statement) assert !expired assert_equal({:a => 2, :b => 3}, hash) expire_on = {:b => true, :a => true} eval(segment.expiry_statement) assert expired assert_equal({:b => 3}, hash) end def test_extraction_code_should_return_on_nil hash = merged = {:b => 3} options = {:b => 3} a_value = nil # Local jump because of return inside eval. assert_raise(LocalJumpError) { eval(segment.extraction_code) } end def test_extraction_code_should_return_on_mismatch segment = segment(:regexp => /\d+/) hash = merged = {:a => 'Hi', :b => '3'} options = {:b => '3'} a_value = nil # Local jump because of return inside eval. assert_raise(LocalJumpError) { eval(segment.extraction_code) } end def test_extraction_code_should_accept_value_and_set_local hash = merged = {:a => 'Hi', :b => '3'} options = {:b => '3'} a_value = nil expired = true eval(segment.extraction_code) assert_equal 'Hi', a_value end def test_extraction_should_work_without_value_check segment.default = 'hi' hash = merged = {:b => '3'} options = {:b => '3'} a_value = nil expired = true eval(segment.extraction_code) assert_equal 'hi', a_value end def test_extraction_code_should_perform_expiry expired = false hash = merged = {:a => 'Hi', :b => '3'} options = {:b => '3'} expire_on = {:a => true} a_value = nil eval(segment.extraction_code) assert_equal 'Hi', a_value assert expired assert_equal options, hash end def test_interpolation_chunk_should_replace_value a_value = 'Hi' assert_equal a_value, eval(%("#{segment.interpolation_chunk}")) end def test_interpolation_chunk_should_accept_nil a_value = nil assert_equal '', eval(%("#{segment.interpolation_chunk('a_value')}")) end def test_value_regexp_should_be_nil_without_regexp assert_equal nil, segment.value_regexp end def test_value_regexp_should_match_exacly segment = segment(:regexp => /\d+/) assert_no_match segment.value_regexp, "Hello 10 World" assert_no_match segment.value_regexp, "Hello 10" assert_no_match segment.value_regexp, "10 World" assert_match segment.value_regexp, "10" end def test_regexp_chunk_should_return_string segment = segment(:regexp => /\d+/) assert_kind_of String, segment.regexp_chunk end def test_build_pattern_non_optional_with_no_captures # Non optional a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /\d+/) assert_equal "(\\d+)stuff", a_segment.build_pattern('stuff') end def test_build_pattern_non_optional_with_captures # Non optional a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /(\d+)(.*?)/) assert_equal "((\\d+)(.*?))stuff", a_segment.build_pattern('stuff') end def test_optionality_implied a_segment = ROUTING::DynamicSegment.new(:id) assert a_segment.optionality_implied? a_segment = ROUTING::DynamicSegment.new(:action) assert a_segment.optionality_implied? end def test_modifiers_must_be_handled_sensibly a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/i) assert_equal "((?i-mx:david|jamis))stuff", a_segment.build_pattern('stuff') a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/x) assert_equal "((?x-mi:david|jamis))stuff", a_segment.build_pattern('stuff') a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/) assert_equal "(david|jamis)stuff", a_segment.build_pattern('stuff') end end class ControllerSegmentTest < Test::Unit::TestCase def test_regexp_should_only_match_possible_controllers ActionController::Routing.with_controllers %w(admin/accounts admin/users account pages) do cs = ROUTING::ControllerSegment.new :controller regexp = %r{\A#{cs.regexp_chunk}\Z} ActionController::Routing.possible_controllers.each do |name| assert_match regexp, name assert_no_match regexp, "#{name}_fake" match = regexp.match name assert_equal name, match[1] end end end end class PathSegmentTest < Test::Unit::TestCase def segment(options = {}) unless @segment @segment = ROUTING::PathSegment.new(:path, options) end @segment end def test_regexp_chunk_should_return_string segment = segment(:regexp => /[a-z]+/) assert_kind_of String, segment.regexp_chunk end def test_regexp_chunk_should_be_wrapped_with_parenthesis segment = segment(:regexp => /[a-z]+/) assert_equal "([a-z]+)", segment.regexp_chunk end def test_regexp_chunk_should_respect_options segment = segment(:regexp => /[a-z]+/i) assert_equal "((?i-mx:[a-z]+))", segment.regexp_chunk end end class RouteBuilderTest < Test::Unit::TestCase def builder @builder ||= ROUTING::RouteBuilder.new end def build(path, options) builder.build(path, options) end def test_options_should_not_be_modified requirements1 = { :id => /\w+/, :controller => /(?:[a-z](?:-?[a-z]+)*)/ } requirements2 = requirements1.dup assert_equal requirements1, requirements2 with_options(:controller => 'folder', :requirements => requirements2) do |m| m.build 'folders/new', :action => 'new' end assert_equal requirements1, requirements2 end def test_segment_for_static segment, rest = builder.segment_for 'ulysses' assert_equal '', rest assert_kind_of ROUTING::StaticSegment, segment assert_equal 'ulysses', segment.value end def test_segment_for_action segment, rest = builder.segment_for ':action' assert_equal '', rest assert_kind_of ROUTING::DynamicSegment, segment assert_equal :action, segment.key assert_equal 'index', segment.default end def test_segment_for_dynamic segment, rest = builder.segment_for ':login' assert_equal '', rest assert_kind_of ROUTING::DynamicSegment, segment assert_equal :login, segment.key assert_equal nil, segment.default assert ! segment.optional? end def test_segment_for_with_rest segment, rest = builder.segment_for ':login/:action' assert_equal :login, segment.key assert_equal '/:action', rest segment, rest = builder.segment_for rest assert_equal '/', segment.value assert_equal ':action', rest segment, rest = builder.segment_for rest assert_equal :action, segment.key assert_equal '', rest end def test_segments_for segments = builder.segments_for_route_path '/:controller/:action/:id' assert_kind_of ROUTING::DividerSegment, segments[0] assert_equal '/', segments[2].value assert_kind_of ROUTING::DynamicSegment, segments[1] assert_equal :controller, segments[1].key assert_kind_of ROUTING::DividerSegment, segments[2] assert_equal '/', segments[2].value assert_kind_of ROUTING::DynamicSegment, segments[3] assert_equal :action, segments[3].key assert_kind_of ROUTING::DividerSegment, segments[4] assert_equal '/', segments[4].value assert_kind_of ROUTING::DynamicSegment, segments[5] assert_equal :id, segments[5].key end def test_segment_for_action s, r = builder.segment_for(':action/something/else') assert_equal '/something/else', r assert_equal :action, s.key end def test_action_default_should_not_trigger_on_prefix s, r = builder.segment_for ':action_name/something/else' assert_equal '/something/else', r assert_equal :action_name, s.key assert_equal nil, s.default end def test_divide_route_options segments = builder.segments_for_route_path '/cars/:action/:person/:car/' defaults, requirements = builder.divide_route_options(segments, :action => 'buy', :person => /\w+/, :car => /\w+/, :defaults => {:person => nil, :car => nil} ) assert_equal({:action => 'buy', :person => nil, :car => nil}, defaults) assert_equal({:person => /\w+/, :car => /\w+/}, requirements) end def test_assign_route_options segments = builder.segments_for_route_path '/cars/:action/:person/:car/' defaults = {:action => 'buy', :person => nil, :car => nil} requirements = {:person => /\w+/, :car => /\w+/} route_requirements = builder.assign_route_options(segments, defaults, requirements) assert_equal({}, route_requirements) assert_equal :action, segments[3].key assert_equal 'buy', segments[3].default assert_equal :person, segments[5].key assert_equal %r/\w+/, segments[5].regexp assert segments[5].optional? assert_equal :car, segments[7].key assert_equal %r/\w+/, segments[7].regexp assert segments[7].optional? end def test_assign_route_options_with_anchor_chars segments = builder.segments_for_route_path '/cars/:action/:person/:car/' defaults = {:action => 'buy', :person => nil, :car => nil} requirements = {:person => /\w+/, :car => /^\w+$/} assert_raise ArgumentError do route_requirements = builder.assign_route_options(segments, defaults, requirements) end requirements[:car] = /[^\/]+/ route_requirements = builder.assign_route_options(segments, defaults, requirements) end def test_optional_segments_preceding_required_segments segments = builder.segments_for_route_path '/cars/:action/:person/:car/' defaults = {:action => 'buy', :person => nil, :car => "model-t"} assert builder.assign_route_options(segments, defaults, {}).empty? 0.upto(1) { |i| assert !segments[i].optional?, "segment #{i} is optional and it shouldn't be" } assert segments[2].optional? assert_equal nil, builder.warn_output # should only warn on the :person segment end def test_segmentation_of_dot_path segments = builder.segments_for_route_path '/books/:action.rss' assert builder.assign_route_options(segments, {}, {}).empty? assert_equal 6, segments.length # "/", "books", "/", ":action", ".", "rss" assert !segments.any? { |seg| seg.optional? } end def test_segmentation_of_dynamic_dot_path segments = builder.segments_for_route_path '/books/:action.:format' assert builder.assign_route_options(segments, {}, {}).empty? assert_equal 6, segments.length # "/", "books", "/", ":action", ".", ":format" assert !segments.any? { |seg| seg.optional? } assert_kind_of ROUTING::DynamicSegment, segments.last end def test_assignment_of_default_options segments = builder.segments_for_route_path '/:controller/:action/:id/' action, id = segments[-4], segments[-2] assert_equal :action, action.key assert_equal :id, id.key assert ! action.optional? assert ! id.optional? builder.assign_default_route_options(segments) assert_equal 'index', action.default assert action.optional? assert id.optional? end def test_assignment_of_default_options_respects_existing_defaults segments = builder.segments_for_route_path '/:controller/:action/:id/' action, id = segments[-4], segments[-2] assert_equal :action, action.key assert_equal :id, id.key action.default = 'show' action.is_optional = true id.default = 'Welcome' id.is_optional = true builder.assign_default_route_options(segments) assert_equal 'show', action.default assert action.optional? assert_equal 'Welcome', id.default assert id.optional? end def test_assignment_of_default_options_respects_regexps segments = builder.segments_for_route_path '/:controller/:action/:id/' action = segments[-4] assert_equal :action, action.key segments[-4] = ROUTING::DynamicSegment.new(:action, :regexp => /show|in/) builder.assign_default_route_options(segments) assert_equal nil, action.default assert ! action.optional? end def test_assignment_of_is_optional_when_default segments = builder.segments_for_route_path '/books/:action.rss' assert_equal segments[3].key, :action segments[3].default = 'changes' builder.ensure_required_segments(segments) assert ! segments[3].optional? end def test_is_optional_is_assigned_to_default_segments segments = builder.segments_for_route_path '/books/:action' builder.assign_route_options(segments, {:action => 'index'}, {}) assert_equal segments[3].key, :action assert segments[3].optional? assert_kind_of ROUTING::DividerSegment, segments[2] assert segments[2].optional? end # XXX is optional not being set right? # /blah/:defaulted_segment <-- is the second slash optional? it should be. def test_route_build ActionController::Routing.with_controllers %w(users pages) do r = builder.build '/:controller/:action/:id/', :action => nil [0, 2, 4].each do |i| assert_kind_of ROUTING::DividerSegment, r.segments[i] assert_equal '/', r.segments[i].value assert r.segments[i].optional? if i > 1 end assert_kind_of ROUTING::DynamicSegment, r.segments[1] assert_equal :controller, r.segments[1].key assert_equal nil, r.segments[1].default assert_kind_of ROUTING::DynamicSegment, r.segments[3] assert_equal :action, r.segments[3].key assert_equal 'index', r.segments[3].default assert_kind_of ROUTING::DynamicSegment, r.segments[5] assert_equal :id, r.segments[5].key assert r.segments[5].optional? end end def test_slashes_are_implied routes = [ builder.build('/:controller/:action/:id/', :action => nil), builder.build('/:controller/:action/:id', :action => nil), builder.build(':controller/:action/:id', :action => nil), builder.build('/:controller/:action/:id/', :action => nil) ] expected = routes.first.segments.length routes.each_with_index do |route, i| found = route.segments.length assert_equal expected, found, "Route #{i + 1} has #{found} segments, expected #{expected}" end end end class RoutingTest < Test::Unit::TestCase def test_possible_controllers true_controller_paths = ActionController::Routing.controller_paths ActionController::Routing.use_controllers! nil silence_warnings do Object.send(:const_set, :RAILS_ROOT, File.dirname(__FILE__) + '/controller_fixtures') end ActionController::Routing.controller_paths = [ RAILS_ROOT, RAILS_ROOT + '/app/controllers', RAILS_ROOT + '/vendor/plugins/bad_plugin/lib' ] assert_equal ["admin/user", "plugin", "user"], ActionController::Routing.possible_controllers.sort ensure if true_controller_paths ActionController::Routing.controller_paths = true_controller_paths end ActionController::Routing.use_controllers! nil Object.send(:remove_const, :RAILS_ROOT) rescue nil end def test_possible_controllers_are_reset_on_each_load true_possible_controllers = ActionController::Routing.possible_controllers true_controller_paths = ActionController::Routing.controller_paths ActionController::Routing.use_controllers! nil root = File.dirname(__FILE__) + '/controller_fixtures' ActionController::Routing.controller_paths = [] assert_equal [], ActionController::Routing.possible_controllers ActionController::Routing.controller_paths = [ root, root + '/app/controllers', root + '/vendor/plugins/bad_plugin/lib' ] ActionController::Routing::Routes.load! assert_equal ["admin/user", "plugin", "user"], ActionController::Routing.possible_controllers.sort ensure ActionController::Routing.controller_paths = true_controller_paths ActionController::Routing.use_controllers! true_possible_controllers Object.send(:remove_const, :RAILS_ROOT) rescue nil ActionController::Routing::Routes.clear! ActionController::Routing::Routes.load_routes! end def test_with_controllers c = %w(admin/accounts admin/users account pages) ActionController::Routing.with_controllers c do assert_equal c, ActionController::Routing.possible_controllers end end def test_normalize_unix_paths load_paths = %w(. config/../app/controllers config/../app//helpers script/../config/../vendor/rails/actionpack/lib vendor/rails/railties/builtin/rails_info app/models lib script/../config/../foo/bar/../../app/models .foo/../.bar foo.bar/../config) paths = ActionController::Routing.normalize_paths(load_paths) assert_equal %w(vendor/rails/railties/builtin/rails_info vendor/rails/actionpack/lib app/controllers app/helpers app/models config .bar lib .), paths end def test_normalize_windows_paths load_paths = %w(. config\\..\\app\\controllers config\\..\\app\\\\helpers script\\..\\config\\..\\vendor\\rails\\actionpack\\lib vendor\\rails\\railties\\builtin\\rails_info app\\models lib script\\..\\config\\..\\foo\\bar\\..\\..\\app\\models .foo\\..\\.bar foo.bar\\..\\config) paths = ActionController::Routing.normalize_paths(load_paths) assert_equal %w(vendor\\rails\\railties\\builtin\\rails_info vendor\\rails\\actionpack\\lib app\\controllers app\\helpers app\\models config .bar lib .), paths end def test_routing_helper_module assert_kind_of Module, ActionController::Routing::Helpers h = ActionController::Routing::Helpers c = Class.new assert ! c.ancestors.include?(h) ActionController::Routing::Routes.install_helpers c assert c.ancestors.include?(h) end end class MockController attr_accessor :routes def initialize(routes) self.routes = routes end def url_for(options) only_path = options.delete(:only_path) port = options.delete(:port) || 80 port_string = port == 80 ? '' : ":#{port}" protocol = options.delete(:protocol) || "http" host = options.delete(:host) || "test.host" anchor = "##{options.delete(:anchor)}" if options.key?(:anchor) path = routes.generate(options) only_path ? "#{path}#{anchor}" : "#{protocol}://#{host}#{port_string}#{path}#{anchor}" end def request @request ||= ActionController::TestRequest.new end end class LegacyRouteSetTests < ActiveSupport::TestCase attr_reader :rs def setup # These tests assume optimisation is on, so re-enable it. ActionController::Base.optimise_named_routes = true @rs = ::ActionController::Routing::RouteSet.new ActionController::Routing.use_controllers! %w(content admin/user admin/news_feed) end def teardown @rs.clear! end def test_routes_for_controller_and_action_deprecated assert_deprecated { @rs.routes_for_controller_and_action("controller", "action") } end def test_default_setup @rs.draw {|m| m.connect ':controller/:action/:id' } assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/content")) assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/content/list")) assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/content/show/10")) assert_equal({:controller => "admin/user", :action => 'show', :id => '10'}, rs.recognize_path("/admin/user/show/10")) assert_equal '/admin/user/show/10', rs.generate(:controller => 'admin/user', :action => 'show', :id => 10) assert_equal '/admin/user/show', rs.generate({:action => 'show'}, {:controller => 'admin/user', :action => 'list', :id => '10'}) assert_equal '/admin/user/list/10', rs.generate({}, {:controller => 'admin/user', :action => 'list', :id => '10'}) assert_equal '/admin/stuff', rs.generate({:controller => 'stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'}) assert_equal '/stuff', rs.generate({:controller => '/stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'}) end def test_ignores_leading_slash @rs.clear! @rs.draw {|m| m.connect '/:controller/:action/:id'} test_default_setup end def test_time_recognition # We create many routes to make situation more realistic @rs = ::ActionController::Routing::RouteSet.new @rs.draw { |map| map.frontpage '', :controller => 'search', :action => 'new' map.resources :videos do |video| video.resources :comments video.resource :file, :controller => 'video_file' video.resource :share, :controller => 'video_shares' video.resource :abuse, :controller => 'video_abuses' end map.resources :abuses, :controller => 'video_abuses' map.resources :video_uploads map.resources :video_visits map.resources :users do |user| user.resource :settings user.resources :videos end map.resources :channels do |channel| channel.resources :videos, :controller => 'channel_videos' end map.resource :session map.resource :lost_password map.search 'search', :controller => 'search' map.resources :pages map.connect ':controller/:action/:id' } n = 1000 if RunTimeTests GC.start rectime = Benchmark.realtime do n.times do rs.recognize_path("/videos/1234567", {:method => :get}) rs.recognize_path("/videos/1234567/abuse", {:method => :get}) rs.recognize_path("/users/1234567/settings", {:method => :get}) rs.recognize_path("/channels/1234567", {:method => :get}) rs.recognize_path("/session/new", {:method => :get}) rs.recognize_path("/admin/user/show/10", {:method => :get}) end end puts "\n\nRecognition (#{rs.routes.size} routes):" per_url = rectime / (n * 6) puts "#{per_url * 1000} ms/url" puts "#{1 / per_url} url/s\n\n" end end def test_time_generation n = 5000 if RunTimeTests GC.start pairs = [ [{:controller => 'content', :action => 'index'}, {:controller => 'content', :action => 'show'}], [{:controller => 'content'}, {:controller => 'content', :action => 'index'}], [{:controller => 'content', :action => 'list'}, {:controller => 'content', :action => 'index'}], [{:controller => 'content', :action => 'show', :id => '10'}, {:controller => 'content', :action => 'list'}], [{:controller => 'admin/user', :action => 'index'}, {:controller => 'admin/user', :action => 'show'}], [{:controller => 'admin/user'}, {:controller => 'admin/user', :action => 'index'}], [{:controller => 'admin/user', :action => 'list'}, {:controller => 'admin/user', :action => 'index'}], [{:controller => 'admin/user', :action => 'show', :id => '10'}, {:controller => 'admin/user', :action => 'list'}], ] p = nil gentime = Benchmark.realtime do n.times do pairs.each {|(a, b)| rs.generate(a, b)} end end puts "\n\nGeneration (RouteSet): (#{(n * 8)} urls)" per_url = gentime / (n * 8) puts "#{per_url * 1000} ms/url" puts "#{1 / per_url} url/s\n\n" end end def test_route_with_colon_first rs.draw do |map| map.connect '/:controller/:action/:id', :action => 'index', :id => nil map.connect ':url', :controller => 'tiny_url', :action => 'translate' end end def test_route_with_regexp_for_controller rs.draw do |map| map.connect ':controller/:admintoken/:action/:id', :controller => /admin\/.+/ map.connect ':controller/:action/:id' end assert_equal({:controller => "admin/user", :admintoken => "foo", :action => "index"}, rs.recognize_path("/admin/user/foo")) assert_equal({:controller => "content", :action => "foo"}, rs.recognize_path("/content/foo")) assert_equal '/admin/user/foo', rs.generate(:controller => "admin/user", :admintoken => "foo", :action => "index") assert_equal '/content/foo', rs.generate(:controller => "content", :action => "foo") end def test_route_with_regexp_and_captures_for_controller rs.draw do |map| map.connect ':controller/:action/:id', :controller => /admin\/(accounts|users)/ end assert_equal({:controller => "admin/accounts", :action => "index"}, rs.recognize_path("/admin/accounts")) assert_equal({:controller => "admin/users", :action => "index"}, rs.recognize_path("/admin/users")) assert_raise(ActionController::RoutingError) { rs.recognize_path("/admin/products") } end def test_route_with_regexp_and_dot rs.draw do |map| map.connect ':controller/:action/:file', :controller => /admin|user/, :action => /upload|download/, :defaults => {:file => nil}, :requirements => {:file => %r{[^/]+(\.[^/]+)?}} end # Without a file extension assert_equal '/user/download/file', rs.generate(:controller => "user", :action => "download", :file => "file") assert_equal( {:controller => "user", :action => "download", :file => "file"}, rs.recognize_path("/user/download/file")) # Now, let's try a file with an extension, really a dot (.) assert_equal '/user/download/file.jpg', rs.generate( :controller => "user", :action => "download", :file => "file.jpg") assert_equal( {:controller => "user", :action => "download", :file => "file.jpg"}, rs.recognize_path("/user/download/file.jpg")) end def test_basic_named_route rs.add_named_route :home, '', :controller => 'content', :action => 'list' x = setup_for_named_route assert_equal("http://test.host/", x.send(:home_url)) end def test_basic_named_route_with_relative_url_root rs.add_named_route :home, '', :controller => 'content', :action => 'list' x = setup_for_named_route ActionController::Base.relative_url_root = "/foo" assert_equal("http://test.host/foo/", x.send(:home_url)) assert_equal "/foo/", x.send(:home_path) ActionController::Base.relative_url_root = nil end def test_named_route_with_option rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page' x = setup_for_named_route assert_equal("http://test.host/page/new%20stuff", x.send(:page_url, :title => 'new stuff')) end def test_named_route_with_default rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page', :title => 'AboutPage' x = setup_for_named_route assert_equal("http://test.host/page/AboutRails", x.send(:page_url, :title => "AboutRails")) end def test_named_route_with_name_prefix
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/selector_test.rb
provider/vendor/rails/actionpack/test/controller/selector_test.rb
#-- # Copyright (c) 2006 Assaf Arkin (http://labnotes.org) # Under MIT and/or CC By license. #++ require 'abstract_unit' require 'controller/fake_controllers' class SelectorTest < Test::Unit::TestCase # # Basic selector: element, id, class, attributes. # def test_element parse(%Q{<div id="1"></div><p></p><div id="2"></div>}) # Match element by name. select("div") assert_equal 2, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "2", @matches[1].attributes["id"] # Not case sensitive. select("DIV") assert_equal 2, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "2", @matches[1].attributes["id"] # Universal match (all elements). select("*") assert_equal 3, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal nil, @matches[1].attributes["id"] assert_equal "2", @matches[2].attributes["id"] end def test_identifier parse(%Q{<div id="1"></div><p></p><div id="2"></div>}) # Match element by ID. select("div#1") assert_equal 1, @matches.size assert_equal "1", @matches[0].attributes["id"] # Match element by ID, substitute value. select("div#?", 2) assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] # Element name does not match ID. select("p#?", 2) assert_equal 0, @matches.size # Use regular expression. select("#?", /\d/) assert_equal 2, @matches.size end def test_class_name parse(%Q{<div id="1" class=" foo "></div><p id="2" class=" foo bar "></p><div id="3" class="bar"></div>}) # Match element with specified class. select("div.foo") assert_equal 1, @matches.size assert_equal "1", @matches[0].attributes["id"] # Match any element with specified class. select("*.foo") assert_equal 2, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "2", @matches[1].attributes["id"] # Match elements with other class. select("*.bar") assert_equal 2, @matches.size assert_equal "2", @matches[0].attributes["id"] assert_equal "3", @matches[1].attributes["id"] # Match only element with both class names. select("*.bar.foo") assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] end def test_attribute parse(%Q{<div id="1"></div><p id="2" title="" bar="foo"></p><div id="3" title="foo"></div>}) # Match element with attribute. select("div[title]") assert_equal 1, @matches.size assert_equal "3", @matches[0].attributes["id"] # Match any element with attribute. select("*[title]") assert_equal 2, @matches.size assert_equal "2", @matches[0].attributes["id"] assert_equal "3", @matches[1].attributes["id"] # Match element with attribute value. select("*[title=foo]") assert_equal 1, @matches.size assert_equal "3", @matches[0].attributes["id"] # Match element with attribute and attribute value. select("[bar=foo][title]") assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] # Not case sensitive. select("[BAR=foo][TiTle]") assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] end def test_attribute_quoted parse(%Q{<div id="1" title="foo"></div><div id="2" title="bar"></div><div id="3" title=" bar "></div>}) # Match without quotes. select("[title = bar]") assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] # Match with single quotes. select("[title = 'bar' ]") assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] # Match with double quotes. select("[title = \"bar\" ]") assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] # Match with spaces. select("[title = \" bar \" ]") assert_equal 1, @matches.size assert_equal "3", @matches[0].attributes["id"] end def test_attribute_equality parse(%Q{<div id="1" title="foo bar"></div><div id="2" title="barbaz"></div>}) # Match (fail) complete value. select("[title=bar]") assert_equal 0, @matches.size # Match space-separate word. select("[title~=foo]") assert_equal 1, @matches.size assert_equal "1", @matches[0].attributes["id"] select("[title~=bar]") assert_equal 1, @matches.size assert_equal "1", @matches[0].attributes["id"] # Match beginning of value. select("[title^=ba]") assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] # Match end of value. select("[title$=ar]") assert_equal 1, @matches.size assert_equal "1", @matches[0].attributes["id"] # Match text in value. select("[title*=bar]") assert_equal 2, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "2", @matches[1].attributes["id"] # Match first space separated word. select("[title|=foo]") assert_equal 1, @matches.size assert_equal "1", @matches[0].attributes["id"] select("[title|=bar]") assert_equal 0, @matches.size end # # Selector composition: groups, sibling, children # def test_selector_group parse(%Q{<h1 id="1"></h1><h2 id="2"></h2><h3 id="3"></h3>}) # Simple group selector. select("h1,h3") assert_equal 2, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "3", @matches[1].attributes["id"] select("h1 , h3") assert_equal 2, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "3", @matches[1].attributes["id"] # Complex group selector. parse(%Q{<h1 id="1"><a href="foo"></a></h1><h2 id="2"><a href="bar"></a></h2><h3 id="2"><a href="baz"></a></h3>}) select("h1 a, h3 a") assert_equal 2, @matches.size assert_equal "foo", @matches[0].attributes["href"] assert_equal "baz", @matches[1].attributes["href"] # And now for the three selector challenge. parse(%Q{<h1 id="1"><a href="foo"></a></h1><h2 id="2"><a href="bar"></a></h2><h3 id="2"><a href="baz"></a></h3>}) select("h1 a, h2 a, h3 a") assert_equal 3, @matches.size assert_equal "foo", @matches[0].attributes["href"] assert_equal "bar", @matches[1].attributes["href"] assert_equal "baz", @matches[2].attributes["href"] end def test_sibling_selector parse(%Q{<h1 id="1"></h1><h2 id="2"></h2><h3 id="3"></h3>}) # Test next sibling. select("h1+*") assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] select("h1+h2") assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] select("h1+h3") assert_equal 0, @matches.size select("*+h3") assert_equal 1, @matches.size assert_equal "3", @matches[0].attributes["id"] # Test any sibling. select("h1~*") assert_equal 2, @matches.size assert_equal "2", @matches[0].attributes["id"] assert_equal "3", @matches[1].attributes["id"] select("h2~*") assert_equal 1, @matches.size assert_equal "3", @matches[0].attributes["id"] end def test_children_selector parse(%Q{<div><p id="1"><span id="2"></span></p></div><div><p id="3"><span id="4" class="foo"></span></p></div>}) # Test child selector. select("div>p") assert_equal 2, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "3", @matches[1].attributes["id"] select("div>span") assert_equal 0, @matches.size select("div>p#3") assert_equal 1, @matches.size assert_equal "3", @matches[0].attributes["id"] select("div>p>span") assert_equal 2, @matches.size assert_equal "2", @matches[0].attributes["id"] assert_equal "4", @matches[1].attributes["id"] # Test descendant selector. select("div p") assert_equal 2, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "3", @matches[1].attributes["id"] select("div span") assert_equal 2, @matches.size assert_equal "2", @matches[0].attributes["id"] assert_equal "4", @matches[1].attributes["id"] select("div *#3") assert_equal 1, @matches.size assert_equal "3", @matches[0].attributes["id"] select("div *#4") assert_equal 1, @matches.size assert_equal "4", @matches[0].attributes["id"] # This is here because it failed before when whitespaces # were not properly stripped. select("div .foo") assert_equal 1, @matches.size assert_equal "4", @matches[0].attributes["id"] end # # Pseudo selectors: root, nth-child, empty, content, etc # def test_root_selector parse(%Q{<div id="1"><div id="2"></div></div>}) # Can only find element if it's root. select(":root") assert_equal 1, @matches.size assert_equal "1", @matches[0].attributes["id"] select("#1:root") assert_equal 1, @matches.size assert_equal "1", @matches[0].attributes["id"] select("#2:root") assert_equal 0, @matches.size # Opposite for nth-child. select("#1:nth-child(1)") assert_equal 0, @matches.size end def test_nth_child_odd_even parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>}) # Test odd nth children. select("tr:nth-child(odd)") assert_equal 2, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "3", @matches[1].attributes["id"] # Test even nth children. select("tr:nth-child(even)") assert_equal 2, @matches.size assert_equal "2", @matches[0].attributes["id"] assert_equal "4", @matches[1].attributes["id"] end def test_nth_child_a_is_zero parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>}) # Test the third child. select("tr:nth-child(0n+3)") assert_equal 1, @matches.size assert_equal "3", @matches[0].attributes["id"] # Same but an can be omitted when zero. select("tr:nth-child(3)") assert_equal 1, @matches.size assert_equal "3", @matches[0].attributes["id"] # Second element (but not every second element). select("tr:nth-child(0n+2)") assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] # Before first and past last returns nothing.: assert_raise(ArgumentError) { select("tr:nth-child(-1)") } select("tr:nth-child(0)") assert_equal 0, @matches.size select("tr:nth-child(5)") assert_equal 0, @matches.size end def test_nth_child_a_is_one parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>}) # a is group of one, pick every element in group. select("tr:nth-child(1n+0)") assert_equal 4, @matches.size # Same but a can be omitted when one. select("tr:nth-child(n+0)") assert_equal 4, @matches.size # Same but b can be omitted when zero. select("tr:nth-child(n)") assert_equal 4, @matches.size end def test_nth_child_b_is_zero parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>}) # If b is zero, pick the n-th element (here each one). select("tr:nth-child(n+0)") assert_equal 4, @matches.size # If b is zero, pick the n-th element (here every second). select("tr:nth-child(2n+0)") assert_equal 2, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "3", @matches[1].attributes["id"] # If a and b are both zero, no element selected. select("tr:nth-child(0n+0)") assert_equal 0, @matches.size select("tr:nth-child(0)") assert_equal 0, @matches.size end def test_nth_child_a_is_negative parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>}) # Since a is -1, picks the first three elements. select("tr:nth-child(-n+3)") assert_equal 3, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "2", @matches[1].attributes["id"] assert_equal "3", @matches[2].attributes["id"] # Since a is -2, picks the first in every second of first four elements. select("tr:nth-child(-2n+3)") assert_equal 2, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "3", @matches[1].attributes["id"] # Since a is -2, picks the first in every second of first three elements. select("tr:nth-child(-2n+2)") assert_equal 1, @matches.size assert_equal "1", @matches[0].attributes["id"] end def test_nth_child_b_is_negative parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>}) # Select last of four. select("tr:nth-child(4n-1)") assert_equal 1, @matches.size assert_equal "4", @matches[0].attributes["id"] # Select first of four. select("tr:nth-child(4n-4)") assert_equal 1, @matches.size assert_equal "1", @matches[0].attributes["id"] # Select last of every second. select("tr:nth-child(2n-1)") assert_equal 2, @matches.size assert_equal "2", @matches[0].attributes["id"] assert_equal "4", @matches[1].attributes["id"] # Select nothing since an+b always < 0 select("tr:nth-child(-1n-1)") assert_equal 0, @matches.size end def test_nth_child_substitution_values parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>}) # Test with ?n?. select("tr:nth-child(?n?)", 2, 1) assert_equal 2, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "3", @matches[1].attributes["id"] select("tr:nth-child(?n?)", 2, 2) assert_equal 2, @matches.size assert_equal "2", @matches[0].attributes["id"] assert_equal "4", @matches[1].attributes["id"] select("tr:nth-child(?n?)", 4, 2) assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] # Test with ? (b only). select("tr:nth-child(?)", 3) assert_equal 1, @matches.size assert_equal "3", @matches[0].attributes["id"] select("tr:nth-child(?)", 5) assert_equal 0, @matches.size end def test_nth_last_child parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>}) # Last two elements. select("tr:nth-last-child(-n+2)") assert_equal 2, @matches.size assert_equal "3", @matches[0].attributes["id"] assert_equal "4", @matches[1].attributes["id"] # All old elements counting from last one. select("tr:nth-last-child(odd)") assert_equal 2, @matches.size assert_equal "2", @matches[0].attributes["id"] assert_equal "4", @matches[1].attributes["id"] end def test_nth_of_type parse(%Q{<table><thead></thead><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>}) # First two elements. select("tr:nth-of-type(-n+2)") assert_equal 2, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "2", @matches[1].attributes["id"] # All old elements counting from last one. select("tr:nth-last-of-type(odd)") assert_equal 2, @matches.size assert_equal "2", @matches[0].attributes["id"] assert_equal "4", @matches[1].attributes["id"] end def test_first_and_last parse(%Q{<table><thead></thead><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>}) # First child. select("tr:first-child") assert_equal 0, @matches.size select(":first-child") assert_equal 1, @matches.size assert_equal "thead", @matches[0].name # First of type. select("tr:first-of-type") assert_equal 1, @matches.size assert_equal "1", @matches[0].attributes["id"] select("thead:first-of-type") assert_equal 1, @matches.size assert_equal "thead", @matches[0].name select("div:first-of-type") assert_equal 0, @matches.size # Last child. select("tr:last-child") assert_equal 1, @matches.size assert_equal "4", @matches[0].attributes["id"] # Last of type. select("tr:last-of-type") assert_equal 1, @matches.size assert_equal "4", @matches[0].attributes["id"] select("thead:last-of-type") assert_equal 1, @matches.size assert_equal "thead", @matches[0].name select("div:last-of-type") assert_equal 0, @matches.size end def test_first_and_last # Only child. parse(%Q{<table><tr></tr></table>}) select("table:only-child") assert_equal 0, @matches.size select("tr:only-child") assert_equal 1, @matches.size assert_equal "tr", @matches[0].name parse(%Q{<table><tr></tr><tr></tr></table>}) select("tr:only-child") assert_equal 0, @matches.size # Only of type. parse(%Q{<table><thead></thead><tr></tr><tr></tr></table>}) select("thead:only-of-type") assert_equal 1, @matches.size assert_equal "thead", @matches[0].name select("td:only-of-type") assert_equal 0, @matches.size end def test_empty parse(%Q{<table><tr></tr></table>}) select("table:empty") assert_equal 0, @matches.size select("tr:empty") assert_equal 1, @matches.size parse(%Q{<div> </div>}) select("div:empty") assert_equal 1, @matches.size end def test_content parse(%Q{<div> </div>}) select("div:content()") assert_equal 1, @matches.size parse(%Q{<div>something </div>}) select("div:content()") assert_equal 0, @matches.size select("div:content(something)") assert_equal 1, @matches.size select("div:content( 'something' )") assert_equal 1, @matches.size select("div:content( \"something\" )") assert_equal 1, @matches.size select("div:content(?)", "something") assert_equal 1, @matches.size select("div:content(?)", /something/) assert_equal 1, @matches.size end # # Test negation. # def test_element_negation parse(%Q{<p></p><div></div>}) select("*") assert_equal 2, @matches.size select("*:not(p)") assert_equal 1, @matches.size assert_equal "div", @matches[0].name select("*:not(div)") assert_equal 1, @matches.size assert_equal "p", @matches[0].name select("*:not(span)") assert_equal 2, @matches.size end def test_id_negation parse(%Q{<p id="1"></p><p id="2"></p>}) select("p") assert_equal 2, @matches.size select(":not(#1)") assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] select(":not(#2)") assert_equal 1, @matches.size assert_equal "1", @matches[0].attributes["id"] end def test_class_name_negation parse(%Q{<p class="foo"></p><p class="bar"></p>}) select("p") assert_equal 2, @matches.size select(":not(.foo)") assert_equal 1, @matches.size assert_equal "bar", @matches[0].attributes["class"] select(":not(.bar)") assert_equal 1, @matches.size assert_equal "foo", @matches[0].attributes["class"] end def test_attribute_negation parse(%Q{<p title="foo"></p><p title="bar"></p>}) select("p") assert_equal 2, @matches.size select(":not([title=foo])") assert_equal 1, @matches.size assert_equal "bar", @matches[0].attributes["title"] select(":not([title=bar])") assert_equal 1, @matches.size assert_equal "foo", @matches[0].attributes["title"] end def test_pseudo_class_negation parse(%Q{<div><p id="1"></p><p id="2"></p></div>}) select("p") assert_equal 2, @matches.size select("p:not(:first-child)") assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] select("p:not(:nth-child(2))") assert_equal 1, @matches.size assert_equal "1", @matches[0].attributes["id"] end def test_negation_details parse(%Q{<p id="1"></p><p id="2"></p><p id="3"></p>}) assert_raise(ArgumentError) { select(":not(") } assert_raise(ArgumentError) { select(":not(:not())") } select("p:not(#1):not(#3)") assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] end def test_select_from_element parse(%Q{<div><p id="1"></p><p id="2"></p></div>}) select("div") @matches = @matches[0].select("p") assert_equal 2, @matches.size assert_equal "1", @matches[0].attributes["id"] assert_equal "2", @matches[1].attributes["id"] end protected def parse(html) @html = HTML::Document.new(html).root end def select(*selector) @matches = HTML.selector(*selector).select(@html) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/filters_test.rb
provider/vendor/rails/actionpack/test/controller/filters_test.rb
require 'abstract_unit' # FIXME: crashes Ruby 1.9 class FilterTest < Test::Unit::TestCase class TestController < ActionController::Base before_filter :ensure_login after_filter :clean_up def show render :inline => "ran action" end private def ensure_login @ran_filter ||= [] @ran_filter << "ensure_login" end def clean_up @ran_after_filter ||= [] @ran_after_filter << "clean_up" end end class ChangingTheRequirementsController < TestController before_filter :ensure_login, :except => [:go_wild] def go_wild render :text => "gobble" end end class TestMultipleFiltersController < ActionController::Base before_filter :try_1 before_filter :try_2 before_filter :try_3 (1..3).each do |i| define_method "fail_#{i}" do render :text => i.to_s end end protected (1..3).each do |i| define_method "try_#{i}" do instance_variable_set :@try, i if action_name == "fail_#{i}" head(404) end end end end class RenderingController < ActionController::Base before_filter :render_something_else def show @ran_action = true render :inline => "ran action" end private def render_something_else render :inline => "something else" end end class ConditionalFilterController < ActionController::Base def show render :inline => "ran action" end def another_action render :inline => "ran action" end def show_without_filter render :inline => "ran action without filter" end private def ensure_login @ran_filter ||= [] @ran_filter << "ensure_login" end def clean_up_tmp @ran_filter ||= [] @ran_filter << "clean_up_tmp" end def rescue_action(e) raise(e) end end class ConditionalCollectionFilterController < ConditionalFilterController before_filter :ensure_login, :except => [ :show_without_filter, :another_action ] end class OnlyConditionSymController < ConditionalFilterController before_filter :ensure_login, :only => :show end class ExceptConditionSymController < ConditionalFilterController before_filter :ensure_login, :except => :show_without_filter end class BeforeAndAfterConditionController < ConditionalFilterController before_filter :ensure_login, :only => :show after_filter :clean_up_tmp, :only => :show end class OnlyConditionProcController < ConditionalFilterController before_filter(:only => :show) {|c| c.instance_variable_set(:"@ran_proc_filter", true) } end class ExceptConditionProcController < ConditionalFilterController before_filter(:except => :show_without_filter) {|c| c.instance_variable_set(:"@ran_proc_filter", true) } end class ConditionalClassFilter def self.filter(controller) controller.instance_variable_set(:"@ran_class_filter", true) end end class OnlyConditionClassController < ConditionalFilterController before_filter ConditionalClassFilter, :only => :show end class ExceptConditionClassController < ConditionalFilterController before_filter ConditionalClassFilter, :except => :show_without_filter end class AnomolousYetValidConditionController < ConditionalFilterController before_filter(ConditionalClassFilter, :ensure_login, Proc.new {|c| c.instance_variable_set(:"@ran_proc_filter1", true)}, :except => :show_without_filter) { |c| c.instance_variable_set(:"@ran_proc_filter2", true)} end class ConditionalOptionsFilter < ConditionalFilterController before_filter :ensure_login, :if => Proc.new { |c| true } before_filter :clean_up_tmp, :if => Proc.new { |c| false } end class EmptyFilterChainController < TestController self.filter_chain.clear def show @action_executed = true render :text => "yawp!" end end class PrependingController < TestController prepend_before_filter :wonderful_life # skip_before_filter :fire_flash private def wonderful_life @ran_filter ||= [] @ran_filter << "wonderful_life" end end class SkippingAndLimitedController < TestController skip_before_filter :ensure_login before_filter :ensure_login, :only => :index def index render :text => 'ok' end def public end end class SkippingAndReorderingController < TestController skip_before_filter :ensure_login before_filter :find_record before_filter :ensure_login private def find_record @ran_filter ||= [] @ran_filter << "find_record" end end class ConditionalSkippingController < TestController skip_before_filter :ensure_login, :only => [ :login ] skip_after_filter :clean_up, :only => [ :login ] before_filter :find_user, :only => [ :change_password ] def login render :inline => "ran action" end def change_password render :inline => "ran action" end protected def find_user @ran_filter ||= [] @ran_filter << "find_user" end end class ConditionalParentOfConditionalSkippingController < ConditionalFilterController before_filter :conditional_in_parent, :only => [:show, :another_action] after_filter :conditional_in_parent, :only => [:show, :another_action] private def conditional_in_parent @ran_filter ||= [] @ran_filter << 'conditional_in_parent' end end class ChildOfConditionalParentController < ConditionalParentOfConditionalSkippingController skip_before_filter :conditional_in_parent, :only => :another_action skip_after_filter :conditional_in_parent, :only => :another_action end class AnotherChildOfConditionalParentController < ConditionalParentOfConditionalSkippingController skip_before_filter :conditional_in_parent, :only => :show end class ProcController < PrependingController before_filter(proc { |c| c.instance_variable_set(:"@ran_proc_filter", true) }) end class ImplicitProcController < PrependingController before_filter { |c| c.instance_variable_set(:"@ran_proc_filter", true) } end class AuditFilter def self.filter(controller) controller.instance_variable_set(:"@was_audited", true) end end class AroundFilter def before(controller) @execution_log = "before" controller.class.execution_log << " before aroundfilter " if controller.respond_to? :execution_log controller.instance_variable_set(:"@before_ran", true) end def after(controller) controller.instance_variable_set(:"@execution_log", @execution_log + " and after") controller.instance_variable_set(:"@after_ran", true) controller.class.execution_log << " after aroundfilter " if controller.respond_to? :execution_log end end class AppendedAroundFilter def before(controller) controller.class.execution_log << " before appended aroundfilter " end def after(controller) controller.class.execution_log << " after appended aroundfilter " end end class AuditController < ActionController::Base before_filter(AuditFilter) def show render :text => "hello" end end class AroundFilterController < PrependingController around_filter AroundFilter.new end class BeforeAfterClassFilterController < PrependingController begin filter = AroundFilter.new before_filter filter after_filter filter end end class MixedFilterController < PrependingController cattr_accessor :execution_log def initialize @@execution_log = "" end before_filter { |c| c.class.execution_log << " before procfilter " } prepend_around_filter AroundFilter.new after_filter { |c| c.class.execution_log << " after procfilter " } append_around_filter AppendedAroundFilter.new end class MixedSpecializationController < ActionController::Base class OutOfOrder < StandardError; end before_filter :first before_filter :second, :only => :foo def foo render :text => 'foo' end def bar render :text => 'bar' end protected def first @first = true end def second raise OutOfOrder unless @first end end class DynamicDispatchController < ActionController::Base before_filter :choose %w(foo bar baz).each do |action| define_method(action) { render :text => action } end private def choose self.action_name = params[:choose] end end class PrependingBeforeAndAfterController < ActionController::Base prepend_before_filter :before_all prepend_after_filter :after_all before_filter :between_before_all_and_after_all def before_all @ran_filter ||= [] @ran_filter << 'before_all' end def after_all @ran_filter ||= [] @ran_filter << 'after_all' end def between_before_all_and_after_all @ran_filter ||= [] @ran_filter << 'between_before_all_and_after_all' end def show render :text => 'hello' end end class ErrorToRescue < Exception; end class RescuingAroundFilterWithBlock def filter(controller) begin yield rescue ErrorToRescue => ex controller.__send__ :render, :text => "I rescued this: #{ex.inspect}" end end end class RescuedController < ActionController::Base around_filter RescuingAroundFilterWithBlock.new def show raise ErrorToRescue.new("Something made the bad noise.") end private def rescue_action(exception) raise exception end end class NonYieldingAroundFilterController < ActionController::Base before_filter :filter_one around_filter :non_yielding_filter before_filter :filter_two after_filter :filter_three def index render :inline => "index" end #make sure the controller complains def rescue_action(e); raise e; end private def filter_one @filters ||= [] @filters << "filter_one" end def filter_two @filters << "filter_two" end def non_yielding_filter @filters << "zomg it didn't yield" @filter_return_value end def filter_three @filters << "filter_three" end end def test_non_yielding_around_filters_not_returning_false_do_not_raise controller = NonYieldingAroundFilterController.new controller.instance_variable_set "@filter_return_value", true assert_nothing_raised do test_process(controller, "index") end end def test_non_yielding_around_filters_returning_false_do_not_raise controller = NonYieldingAroundFilterController.new controller.instance_variable_set "@filter_return_value", false assert_nothing_raised do test_process(controller, "index") end end def test_after_filters_are_not_run_if_around_filter_returns_false controller = NonYieldingAroundFilterController.new controller.instance_variable_set "@filter_return_value", false test_process(controller, "index") assert_equal ["filter_one", "zomg it didn't yield"], controller.assigns['filters'] end def test_after_filters_are_not_run_if_around_filter_does_not_yield controller = NonYieldingAroundFilterController.new controller.instance_variable_set "@filter_return_value", true test_process(controller, "index") assert_equal ["filter_one", "zomg it didn't yield"], controller.assigns['filters'] end def test_empty_filter_chain assert_equal 0, EmptyFilterChainController.filter_chain.size assert test_process(EmptyFilterChainController).template.assigns['action_executed'] end def test_added_filter_to_inheritance_graph assert_equal [ :ensure_login ], TestController.before_filters end def test_base_class_in_isolation assert_equal [ ], ActionController::Base.before_filters end def test_prepending_filter assert_equal [ :wonderful_life, :ensure_login ], PrependingController.before_filters end def test_running_filters assert_equal %w( wonderful_life ensure_login ), test_process(PrependingController).template.assigns["ran_filter"] end def test_running_filters_with_proc assert test_process(ProcController).template.assigns["ran_proc_filter"] end def test_running_filters_with_implicit_proc assert test_process(ImplicitProcController).template.assigns["ran_proc_filter"] end def test_running_filters_with_class assert test_process(AuditController).template.assigns["was_audited"] end def test_running_anomolous_yet_valid_condition_filters response = test_process(AnomolousYetValidConditionController) assert_equal %w( ensure_login ), response.template.assigns["ran_filter"] assert response.template.assigns["ran_class_filter"] assert response.template.assigns["ran_proc_filter1"] assert response.template.assigns["ran_proc_filter2"] response = test_process(AnomolousYetValidConditionController, "show_without_filter") assert_equal nil, response.template.assigns["ran_filter"] assert !response.template.assigns["ran_class_filter"] assert !response.template.assigns["ran_proc_filter1"] assert !response.template.assigns["ran_proc_filter2"] end def test_running_conditional_options response = test_process(ConditionalOptionsFilter) assert_equal %w( ensure_login ), response.template.assigns["ran_filter"] end def test_running_collection_condition_filters assert_equal %w( ensure_login ), test_process(ConditionalCollectionFilterController).template.assigns["ran_filter"] assert_equal nil, test_process(ConditionalCollectionFilterController, "show_without_filter").template.assigns["ran_filter"] assert_equal nil, test_process(ConditionalCollectionFilterController, "another_action").template.assigns["ran_filter"] end def test_running_only_condition_filters assert_equal %w( ensure_login ), test_process(OnlyConditionSymController).template.assigns["ran_filter"] assert_equal nil, test_process(OnlyConditionSymController, "show_without_filter").template.assigns["ran_filter"] assert test_process(OnlyConditionProcController).template.assigns["ran_proc_filter"] assert !test_process(OnlyConditionProcController, "show_without_filter").template.assigns["ran_proc_filter"] assert test_process(OnlyConditionClassController).template.assigns["ran_class_filter"] assert !test_process(OnlyConditionClassController, "show_without_filter").template.assigns["ran_class_filter"] end def test_running_except_condition_filters assert_equal %w( ensure_login ), test_process(ExceptConditionSymController).template.assigns["ran_filter"] assert_equal nil, test_process(ExceptConditionSymController, "show_without_filter").template.assigns["ran_filter"] assert test_process(ExceptConditionProcController).template.assigns["ran_proc_filter"] assert !test_process(ExceptConditionProcController, "show_without_filter").template.assigns["ran_proc_filter"] assert test_process(ExceptConditionClassController).template.assigns["ran_class_filter"] assert !test_process(ExceptConditionClassController, "show_without_filter").template.assigns["ran_class_filter"] end def test_running_before_and_after_condition_filters assert_equal %w( ensure_login clean_up_tmp), test_process(BeforeAndAfterConditionController).template.assigns["ran_filter"] assert_equal nil, test_process(BeforeAndAfterConditionController, "show_without_filter").template.assigns["ran_filter"] end def test_around_filter controller = test_process(AroundFilterController) assert controller.template.assigns["before_ran"] assert controller.template.assigns["after_ran"] end def test_before_after_class_filter controller = test_process(BeforeAfterClassFilterController) assert controller.template.assigns["before_ran"] assert controller.template.assigns["after_ran"] end def test_having_properties_in_around_filter controller = test_process(AroundFilterController) assert_equal "before and after", controller.template.assigns["execution_log"] end def test_prepending_and_appending_around_filter controller = test_process(MixedFilterController) assert_equal " before aroundfilter before procfilter before appended aroundfilter " + " after appended aroundfilter after aroundfilter after procfilter ", MixedFilterController.execution_log end def test_rendering_breaks_filtering_chain response = test_process(RenderingController) assert_equal "something else", response.body assert !response.template.assigns["ran_action"] end def test_filters_with_mixed_specialization_run_in_order assert_nothing_raised do response = test_process(MixedSpecializationController, 'bar') assert_equal 'bar', response.body end assert_nothing_raised do response = test_process(MixedSpecializationController, 'foo') assert_equal 'foo', response.body end end def test_dynamic_dispatch %w(foo bar baz).each do |action| request = ActionController::TestRequest.new request.query_parameters[:choose] = action response = DynamicDispatchController.process(request, ActionController::TestResponse.new) assert_equal action, response.body end end def test_running_prepended_before_and_after_filter assert_equal 3, PrependingBeforeAndAfterController.filter_chain.length response = test_process(PrependingBeforeAndAfterController) assert_equal %w( before_all between_before_all_and_after_all after_all ), response.template.assigns["ran_filter"] end def test_skipping_and_limiting_controller assert_equal %w( ensure_login ), test_process(SkippingAndLimitedController, "index").template.assigns["ran_filter"] assert_nil test_process(SkippingAndLimitedController, "public").template.assigns["ran_filter"] end def test_skipping_and_reordering_controller assert_equal %w( find_record ensure_login ), test_process(SkippingAndReorderingController, "index").template.assigns["ran_filter"] end def test_conditional_skipping_of_filters assert_nil test_process(ConditionalSkippingController, "login").template.assigns["ran_filter"] assert_equal %w( ensure_login find_user ), test_process(ConditionalSkippingController, "change_password").template.assigns["ran_filter"] assert_nil test_process(ConditionalSkippingController, "login").template.controller.instance_variable_get("@ran_after_filter") assert_equal %w( clean_up ), test_process(ConditionalSkippingController, "change_password").template.controller.instance_variable_get("@ran_after_filter") end def test_conditional_skipping_of_filters_when_parent_filter_is_also_conditional assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter'] assert_nil test_process(ChildOfConditionalParentController, 'another_action').template.assigns['ran_filter'] end def test_condition_skipping_of_filters_when_siblings_also_have_conditions assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter'], "1" assert_equal nil, test_process(AnotherChildOfConditionalParentController).template.assigns['ran_filter'] assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter'] end def test_changing_the_requirements assert_equal nil, test_process(ChangingTheRequirementsController, "go_wild").template.assigns['ran_filter'] end def test_a_rescuing_around_filter response = nil assert_nothing_raised do response = test_process(RescuedController) end assert response.success? assert_equal("I rescued this: #<FilterTest::ErrorToRescue: Something made the bad noise.>", response.body) end private def test_process(controller, action = "show") ActionController::Base.class_eval { include ActionController::ProcessWithTest } unless ActionController::Base < ActionController::ProcessWithTest request = ActionController::TestRequest.new request.action = action controller = controller.new if controller.is_a?(Class) controller.process_with_test(request, ActionController::TestResponse.new) end end class PostsController < ActionController::Base def rescue_action(e); raise e; end module AroundExceptions class Error < StandardError ; end class Before < Error ; end class After < Error ; end end include AroundExceptions class DefaultFilter include AroundExceptions end module_eval %w(raises_before raises_after raises_both no_raise no_filter).map { |action| "def #{action}; default_action end" }.join("\n") private def default_action render :inline => "#{action_name} called" end end class ControllerWithSymbolAsFilter < PostsController around_filter :raise_before, :only => :raises_before around_filter :raise_after, :only => :raises_after around_filter :without_exception, :only => :no_raise private def raise_before raise Before yield end def raise_after yield raise After end def without_exception # Do stuff... 1 + 1 yield # Do stuff... 1 + 1 end end class ControllerWithFilterClass < PostsController class YieldingFilter < DefaultFilter def self.filter(controller) yield raise After end end around_filter YieldingFilter, :only => :raises_after end class ControllerWithFilterInstance < PostsController class YieldingFilter < DefaultFilter def filter(controller) yield raise After end end around_filter YieldingFilter.new, :only => :raises_after end class ControllerWithFilterMethod < PostsController class YieldingFilter < DefaultFilter def filter(controller) yield raise After end end around_filter YieldingFilter.new.method(:filter), :only => :raises_after end class ControllerWithProcFilter < PostsController around_filter(:only => :no_raise) do |c,b| c.instance_variable_set(:"@before", true) b.call c.instance_variable_set(:"@after", true) end end class ControllerWithNestedFilters < ControllerWithSymbolAsFilter around_filter :raise_before, :raise_after, :without_exception, :only => :raises_both end class ControllerWithAllTypesOfFilters < PostsController before_filter :before around_filter :around after_filter :after around_filter :around_again private def before @ran_filter ||= [] @ran_filter << 'before' end def around @ran_filter << 'around (before yield)' yield @ran_filter << 'around (after yield)' end def after @ran_filter << 'after' end def around_again @ran_filter << 'around_again (before yield)' yield @ran_filter << 'around_again (after yield)' end end class ControllerWithTwoLessFilters < ControllerWithAllTypesOfFilters skip_filter :around_again skip_filter :after end class YieldingAroundFiltersTest < Test::Unit::TestCase include PostsController::AroundExceptions def test_filters_registering assert_equal 1, ControllerWithFilterMethod.filter_chain.size assert_equal 1, ControllerWithFilterClass.filter_chain.size assert_equal 1, ControllerWithFilterInstance.filter_chain.size assert_equal 3, ControllerWithSymbolAsFilter.filter_chain.size assert_equal 6, ControllerWithNestedFilters.filter_chain.size assert_equal 4, ControllerWithAllTypesOfFilters.filter_chain.size end def test_base controller = PostsController assert_nothing_raised { test_process(controller,'no_raise') } assert_nothing_raised { test_process(controller,'raises_before') } assert_nothing_raised { test_process(controller,'raises_after') } assert_nothing_raised { test_process(controller,'no_filter') } end def test_with_symbol controller = ControllerWithSymbolAsFilter assert_nothing_raised { test_process(controller,'no_raise') } assert_raise(Before) { test_process(controller,'raises_before') } assert_raise(After) { test_process(controller,'raises_after') } assert_nothing_raised { test_process(controller,'no_raise') } end def test_with_class controller = ControllerWithFilterClass assert_nothing_raised { test_process(controller,'no_raise') } assert_raise(After) { test_process(controller,'raises_after') } end def test_with_instance controller = ControllerWithFilterInstance assert_nothing_raised { test_process(controller,'no_raise') } assert_raise(After) { test_process(controller,'raises_after') } end def test_with_method controller = ControllerWithFilterMethod assert_nothing_raised { test_process(controller,'no_raise') } assert_raise(After) { test_process(controller,'raises_after') } end def test_with_proc controller = test_process(ControllerWithProcFilter,'no_raise') assert controller.template.assigns['before'] assert controller.template.assigns['after'] end def test_nested_filters controller = ControllerWithNestedFilters assert_nothing_raised do begin test_process(controller,'raises_both') rescue Before, After end end assert_raise Before do begin test_process(controller,'raises_both') rescue After end end end def test_filter_order_with_all_filter_types controller = test_process(ControllerWithAllTypesOfFilters,'no_raise') assert_equal 'before around (before yield) around_again (before yield) around_again (after yield) around (after yield) after',controller.template.assigns['ran_filter'].join(' ') end def test_filter_order_with_skip_filter_method controller = test_process(ControllerWithTwoLessFilters,'no_raise') assert_equal 'before around (before yield) around (after yield)',controller.template.assigns['ran_filter'].join(' ') end def test_first_filter_in_multiple_before_filter_chain_halts controller = ::FilterTest::TestMultipleFiltersController.new response = test_process(controller, 'fail_1') assert_equal ' ', response.body assert_equal 1, controller.instance_variable_get(:@try) assert controller.instance_variable_get(:@before_filter_chain_aborted) end def test_second_filter_in_multiple_before_filter_chain_halts controller = ::FilterTest::TestMultipleFiltersController.new response = test_process(controller, 'fail_2') assert_equal ' ', response.body assert_equal 2, controller.instance_variable_get(:@try) assert controller.instance_variable_get(:@before_filter_chain_aborted) end def test_last_filter_in_multiple_before_filter_chain_halts controller = ::FilterTest::TestMultipleFiltersController.new response = test_process(controller, 'fail_3') assert_equal ' ', response.body assert_equal 3, controller.instance_variable_get(:@try) assert controller.instance_variable_get(:@before_filter_chain_aborted) end protected def test_process(controller, action = "show") ActionController::Base.class_eval { include ActionController::ProcessWithTest } unless ActionController::Base < ActionController::ProcessWithTest request = ActionController::TestRequest.new request.action = action controller = controller.new if controller.is_a?(Class) controller.process_with_test(request, ActionController::TestResponse.new) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/request_test.rb
provider/vendor/rails/actionpack/test/controller/request_test.rb
require 'abstract_unit' class RequestTest < ActiveSupport::TestCase def setup ActionController::Base.relative_url_root = nil end def teardown ActionController::Base.relative_url_root = nil end def test_remote_ip request = stub_request 'REMOTE_ADDR' => '1.2.3.4' assert_equal '1.2.3.4', request.remote_ip request = stub_request 'REMOTE_ADDR' => '1.2.3.4,3.4.5.6' assert_equal '1.2.3.4', request.remote_ip request = stub_request 'REMOTE_ADDR' => '1.2.3.4', 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' assert_equal '1.2.3.4', request.remote_ip request = stub_request 'REMOTE_ADDR' => '127.0.0.1', 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' assert_equal '3.4.5.6', request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,3.4.5.6' assert_equal '3.4.5.6', request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '172.16.0.1,3.4.5.6' assert_equal '3.4.5.6', request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '192.168.0.1,3.4.5.6' assert_equal '3.4.5.6', request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '10.0.0.1,3.4.5.6' assert_equal '3.4.5.6', request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '10.0.0.1, 10.0.0.1, 3.4.5.6' assert_equal '3.4.5.6', request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '127.0.0.1,3.4.5.6' assert_equal '3.4.5.6', request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,192.168.0.1' assert_equal 'unknown', request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4' assert_equal '3.4.5.6', request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1', 'HTTP_CLIENT_IP' => '2.2.2.2' e = assert_raise(ActionController::ActionControllerError) { request.remote_ip } assert_match /IP spoofing attack/, e.message assert_match /HTTP_X_FORWARDED_FOR="1.1.1.1"/, e.message assert_match /HTTP_CLIENT_IP="2.2.2.2"/, e.message # turn IP Spoofing detection off. # This is useful for sites that are aimed at non-IP clients. The typical # example is WAP. Since the cellular network is not IP based, it's a # leap of faith to assume that their proxies are ever going to set the # HTTP_CLIENT_IP/HTTP_X_FORWARDED_FOR headers properly. ActionController::Base.ip_spoofing_check = false request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1', 'HTTP_CLIENT_IP' => '2.2.2.2' assert_equal '2.2.2.2', request.remote_ip ActionController::Base.ip_spoofing_check = true request = stub_request 'HTTP_X_FORWARDED_FOR' => '8.8.8.8, 9.9.9.9' assert_equal '9.9.9.9', request.remote_ip end def test_domains request = stub_request 'HTTP_HOST' => 'www.rubyonrails.org' assert_equal "rubyonrails.org", request.domain request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk" assert_equal "rubyonrails.co.uk", request.domain(2) request = stub_request 'HTTP_HOST' => "192.168.1.200" assert_nil request.domain request = stub_request 'HTTP_HOST' => "foo.192.168.1.200" assert_nil request.domain request = stub_request 'HTTP_HOST' => "192.168.1.200.com" assert_equal "200.com", request.domain end def test_subdomains request = stub_request 'HTTP_HOST' => "www.rubyonrails.org" assert_equal %w( www ), request.subdomains request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk" assert_equal %w( www ), request.subdomains(2) request = stub_request 'HTTP_HOST' => "dev.www.rubyonrails.co.uk" assert_equal %w( dev www ), request.subdomains(2) request = stub_request 'HTTP_HOST' => "foobar.foobar.com" assert_equal %w( foobar ), request.subdomains request = stub_request 'HTTP_HOST' => "192.168.1.200" assert_equal [], request.subdomains request = stub_request 'HTTP_HOST' => "foo.192.168.1.200" assert_equal [], request.subdomains request = stub_request 'HTTP_HOST' => "192.168.1.200.com" assert_equal %w( 192 168 1 ), request.subdomains request = stub_request 'HTTP_HOST' => nil assert_equal [], request.subdomains end def test_port_string request = stub_request 'HTTP_HOST' => 'www.example.org:80' assert_equal "", request.port_string request = stub_request 'HTTP_HOST' => 'www.example.org:8080' assert_equal ":8080", request.port_string end def test_request_uri request = stub_request 'REQUEST_URI' => "http://www.rubyonrails.org/path/of/some/uri?mapped=1" assert_equal "/path/of/some/uri?mapped=1", request.request_uri assert_equal "/path/of/some/uri", request.path request = stub_request 'REQUEST_URI' => "http://www.rubyonrails.org/path/of/some/uri" assert_equal "/path/of/some/uri", request.request_uri assert_equal "/path/of/some/uri", request.path request = stub_request 'REQUEST_URI' => "/path/of/some/uri" assert_equal "/path/of/some/uri", request.request_uri assert_equal "/path/of/some/uri", request.path request = stub_request 'REQUEST_URI' => "/" assert_equal "/", request.request_uri assert_equal "/", request.path request = stub_request 'REQUEST_URI' => "/?m=b" assert_equal "/?m=b", request.request_uri assert_equal "/", request.path request = stub_request 'REQUEST_URI' => "/", 'SCRIPT_NAME' => '/dispatch.cgi' assert_equal "/", request.request_uri assert_equal "/", request.path ActionController::Base.relative_url_root = "/hieraki" request = stub_request 'REQUEST_URI' => "/hieraki/", 'SCRIPT_NAME' => "/hieraki/dispatch.cgi" assert_equal "/hieraki/", request.request_uri assert_equal "/", request.path ActionController::Base.relative_url_root = nil ActionController::Base.relative_url_root = "/collaboration/hieraki" request = stub_request 'REQUEST_URI' => "/collaboration/hieraki/books/edit/2", 'SCRIPT_NAME' => "/collaboration/hieraki/dispatch.cgi" assert_equal "/collaboration/hieraki/books/edit/2", request.request_uri assert_equal "/books/edit/2", request.path ActionController::Base.relative_url_root = nil # The following tests are for when REQUEST_URI is not supplied (as in IIS) request = stub_request 'PATH_INFO' => "/path/of/some/uri?mapped=1", 'SCRIPT_NAME' => nil, 'REQUEST_URI' => nil assert_equal "/path/of/some/uri?mapped=1", request.request_uri assert_equal "/path/of/some/uri", request.path ActionController::Base.relative_url_root = '/path' request = stub_request 'PATH_INFO' => "/path/of/some/uri?mapped=1", 'SCRIPT_NAME' => "/path/dispatch.rb", 'REQUEST_URI' => nil assert_equal "/path/of/some/uri?mapped=1", request.request_uri assert_equal "/of/some/uri", request.path ActionController::Base.relative_url_root = nil request = stub_request 'PATH_INFO' => "/path/of/some/uri", 'SCRIPT_NAME' => nil, 'REQUEST_URI' => nil assert_equal "/path/of/some/uri", request.request_uri assert_equal "/path/of/some/uri", request.path request = stub_request 'PATH_INFO' => '/', 'REQUEST_URI' => nil assert_equal "/", request.request_uri assert_equal "/", request.path request = stub_request 'PATH_INFO' => '/?m=b', 'REQUEST_URI' => nil assert_equal "/?m=b", request.request_uri assert_equal "/", request.path request = stub_request 'PATH_INFO' => "/", 'SCRIPT_NAME' => "/dispatch.cgi", 'REQUEST_URI' => nil assert_equal "/", request.request_uri assert_equal "/", request.path ActionController::Base.relative_url_root = '/hieraki' request = stub_request 'PATH_INFO' => "/hieraki/", 'SCRIPT_NAME' => "/hieraki/dispatch.cgi", 'REQUEST_URI' => nil assert_equal "/hieraki/", request.request_uri assert_equal "/", request.path ActionController::Base.relative_url_root = nil request = stub_request 'REQUEST_URI' => '/hieraki/dispatch.cgi' ActionController::Base.relative_url_root = '/hieraki' assert_equal "/dispatch.cgi", request.path ActionController::Base.relative_url_root = nil request = stub_request 'REQUEST_URI' => '/hieraki/dispatch.cgi' ActionController::Base.relative_url_root = '/foo' assert_equal "/hieraki/dispatch.cgi", request.path ActionController::Base.relative_url_root = nil # This test ensures that Rails uses REQUEST_URI over PATH_INFO ActionController::Base.relative_url_root = nil request = stub_request 'REQUEST_URI' => "/some/path", 'PATH_INFO' => "/another/path", 'SCRIPT_NAME' => "/dispatch.cgi" assert_equal "/some/path", request.request_uri assert_equal "/some/path", request.path end def test_host_with_default_port request = stub_request 'HTTP_HOST' => 'rubyonrails.org:80' assert_equal "rubyonrails.org", request.host_with_port end def test_host_with_non_default_port request = stub_request 'HTTP_HOST' => 'rubyonrails.org:81' assert_equal "rubyonrails.org:81", request.host_with_port end def test_server_software request = stub_request assert_equal nil, request.server_software request = stub_request 'SERVER_SOFTWARE' => 'Apache3.422' assert_equal 'apache', request.server_software request = stub_request 'SERVER_SOFTWARE' => 'lighttpd(1.1.4)' assert_equal 'lighttpd', request.server_software end def test_xml_http_request request = stub_request assert !request.xml_http_request? assert !request.xhr? request = stub_request 'HTTP_X_REQUESTED_WITH' => 'DefinitelyNotAjax1.0' assert !request.xml_http_request? assert !request.xhr? request = stub_request 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest' assert request.xml_http_request? assert request.xhr? end def test_reports_ssl request = stub_request assert !request.ssl? request = stub_request 'HTTPS' => 'on' assert request.ssl? end def test_reports_ssl_when_proxied_via_lighttpd request = stub_request assert !request.ssl? request = stub_request 'HTTP_X_FORWARDED_PROTO' => 'https' assert request.ssl? end def test_symbolized_request_methods [:get, :post, :put, :delete].each do |method| request = stub_request 'REQUEST_METHOD' => method.to_s.upcase assert_equal method, request.method end end def test_invalid_http_method_raises_exception assert_raise(ActionController::UnknownHttpMethod) do request = stub_request 'REQUEST_METHOD' => 'RANDOM_METHOD' request.request_method end end def test_allow_method_hacking_on_post [:get, :head, :options, :put, :post, :delete].each do |method| request = stub_request 'REQUEST_METHOD' => method.to_s.upcase assert_equal(method == :head ? :get : method, request.method) end end def test_restrict_method_hacking [:get, :put, :delete].each do |method| request = stub_request 'REQUEST_METHOD' => method.to_s.upcase, 'action_controller.request.request_parameters' => { :_method => 'put' } assert_equal method, request.method end end def test_head_masquerading_as_get request = stub_request 'REQUEST_METHOD' => 'HEAD' assert_equal :get, request.method assert request.get? assert request.head? end def test_xml_format request = stub_request request.expects(:parameters).at_least_once.returns({ :format => 'xml' }) assert_equal Mime::XML, request.format end def test_xhtml_format request = stub_request request.expects(:parameters).at_least_once.returns({ :format => 'xhtml' }) assert_equal Mime::HTML, request.format end def test_txt_format request = stub_request request.expects(:parameters).at_least_once.returns({ :format => 'txt' }) assert_equal Mime::TEXT, request.format end def test_xml_http_request ActionController::Base.use_accept_header, old = false, ActionController::Base.use_accept_header request = stub_request 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest' request.expects(:parameters).at_least_once.returns({}) assert request.xhr? assert_equal Mime::JS, request.format ensure ActionController::Base.use_accept_header = old end def test_content_type request = stub_request 'CONTENT_TYPE' => 'text/html' assert_equal Mime::HTML, request.content_type end def test_can_override_format_with_parameter request = stub_request request.expects(:parameters).at_least_once.returns({ :format => :txt }) assert !request.format.xml? request = stub_request request.expects(:parameters).at_least_once.returns({ :format => :xml }) assert request.format.xml? end def test_content_no_type request = stub_request assert_equal nil, request.content_type end def test_content_type_xml request = stub_request 'CONTENT_TYPE' => 'application/xml' assert_equal Mime::XML, request.content_type end def test_content_type_with_charset request = stub_request 'CONTENT_TYPE' => 'application/xml; charset=UTF-8' assert_equal Mime::XML, request.content_type end def test_user_agent request = stub_request 'HTTP_USER_AGENT' => 'TestAgent' assert_equal 'TestAgent', request.user_agent end def test_parameters request = stub_request request.stubs(:request_parameters).returns({ "foo" => 1 }) request.stubs(:query_parameters).returns({ "bar" => 2 }) assert_equal({"foo" => 1, "bar" => 2}, request.parameters) assert_equal({"foo" => 1}, request.request_parameters) assert_equal({"bar" => 2}, request.query_parameters) end protected def stub_request(env={}) ActionController::Request.new(env) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/dispatcher_test.rb
provider/vendor/rails/actionpack/test/controller/dispatcher_test.rb
require 'abstract_unit' class DispatcherTest < Test::Unit::TestCase Dispatcher = ActionController::Dispatcher Reloader = ActionController::Reloader def setup ENV['REQUEST_METHOD'] = 'GET' reset_dispatcher Dispatcher.stubs(:require_dependency) end def teardown ENV.delete 'REQUEST_METHOD' reset_dispatcher end def test_clears_dependencies_after_dispatch_if_in_loading_mode ActiveSupport::Dependencies.expects(:clear).once # Close the response so dependencies kicks in dispatch(false).last.close end def test_reloads_routes_before_dispatch_if_in_loading_mode ActionController::Routing::Routes.expects(:reload).once dispatch(false) end def test_leaves_dependencies_after_dispatch_if_not_in_loading_mode ActionController::Routing::Routes.expects(:reload).never ActiveSupport::Dependencies.expects(:clear).never dispatch end def test_builds_middleware_stack_only_during_initialization_if_not_in_loading_mode dispatcher = create_dispatcher assert_not_nil dispatcher.instance_variable_get(:"@app") dispatcher.instance_variable_set(:"@app", lambda { |env| }) dispatcher.expects(:build_middleware_stack).never dispatcher.call(nil) dispatcher.call(nil) end def test_rebuilds_middleware_stack_on_every_request_if_in_loading_mode dispatcher = create_dispatcher(false) dispatcher.instance_variable_set(:"@app", lambda { |env| }) dispatcher.expects(:build_middleware_stack).twice dispatcher.call(nil) Reloader.default_lock.unlock dispatcher.call(nil) end def test_doesnt_wrap_call_in_reloader_if_not_in_loading_mode Reloader.expects(:run).never dispatch end def test_wraps_call_in_reloader_if_in_loading_mode Reloader.expects(:run).once dispatch(false) end # Stub out dispatch error logger class << Dispatcher def log_failsafe_exception(status, exception); end end def test_failsafe_response Dispatcher.any_instance.expects(:dispatch).raises('b00m') ActionController::Failsafe.any_instance.expects(:log_failsafe_exception) response = nil assert_nothing_raised do response = dispatch end assert_equal 3, response.size assert_equal 500, response[0] assert_equal({"Content-Type" => "text/html"}, response[1]) assert_match /500 Internal Server Error/, response[2].join end def test_prepare_callbacks a = b = c = nil Dispatcher.to_prepare { |*args| a = b = c = 1 } Dispatcher.to_prepare { |*args| b = c = 2 } Dispatcher.to_prepare { |*args| c = 3 } # Ensure to_prepare callbacks are not run when defined assert_nil a || b || c # Run callbacks Dispatcher.run_prepare_callbacks assert_equal 1, a assert_equal 2, b assert_equal 3, c # Make sure they are only run once a = b = c = nil dispatch assert_nil a || b || c end def test_to_prepare_with_identifier_replaces a = b = nil Dispatcher.to_prepare(:unique_id) { |*args| a = b = 1 } Dispatcher.to_prepare(:unique_id) { |*args| a = 2 } Dispatcher.run_prepare_callbacks assert_equal 2, a assert_equal nil, b end private def dispatch(cache_classes = true) ActionController::Routing::RouteSet.any_instance.stubs(:call).returns([200, {}, 'response']) Dispatcher.define_dispatcher_callbacks(cache_classes) Dispatcher.new.call({'rack.input' => StringIO.new('')}) end def create_dispatcher(cache_classes = true) Dispatcher.define_dispatcher_callbacks(cache_classes) Dispatcher.new end def reset_dispatcher Dispatcher.middleware = ActionController::MiddlewareStack.new do |middleware| middlewares = File.expand_path(File.join(File.dirname(__FILE__), "../../lib/action_controller/middlewares.rb")) middleware.instance_eval(File.read(middlewares)) end # Clear callbacks as they are redefined by Dispatcher#define_dispatcher_callbacks Dispatcher.instance_variable_set("@prepare_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new) Dispatcher.instance_variable_set("@before_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new) Dispatcher.instance_variable_set("@after_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new) Dispatcher.define_dispatcher_callbacks(true) end def assert_subclasses(howmany, klass, message = klass.subclasses.inspect) assert_equal howmany, klass.subclasses.size, message end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/helper_test.rb
provider/vendor/rails/actionpack/test/controller/helper_test.rb
require 'abstract_unit' ActionController::Base.helpers_dir = File.dirname(__FILE__) + '/../fixtures/helpers' class TestController < ActionController::Base attr_accessor :delegate_attr def delegate_method() end def rescue_action(e) raise end end module Fun class GamesController < ActionController::Base def render_hello_world render :inline => "hello: <%= stratego %>" end def rescue_action(e) raise end end class PdfController < ActionController::Base def test render :inline => "test: <%= foobar %>" end def rescue_action(e) raise end end end class ApplicationController < ActionController::Base helper :all end module LocalAbcHelper def a() end def b() end def c() end end class HelperTest < Test::Unit::TestCase def setup # Increment symbol counter. @symbol = (@@counter ||= 'A0').succ!.dup # Generate new controller class. controller_class_name = "Helper#{@symbol}Controller" eval("class #{controller_class_name} < TestController; end") @controller_class = self.class.const_get(controller_class_name) # Set default test helper. self.test_helper = LocalAbcHelper end def test_deprecated_helper assert_equal expected_helper_methods, missing_methods assert_nothing_raised { @controller_class.helper TestHelper } assert_equal [], missing_methods end def test_declare_helper require 'abc_helper' self.test_helper = AbcHelper assert_equal expected_helper_methods, missing_methods assert_nothing_raised { @controller_class.helper :abc } assert_equal [], missing_methods end def test_declare_missing_helper assert_equal expected_helper_methods, missing_methods assert_raise(MissingSourceFile) { @controller_class.helper :missing } end def test_declare_missing_file_from_helper require 'broken_helper' rescue LoadError => e assert_nil(/\bbroken_helper\b/.match(e.to_s)[1]) end def test_helper_block assert_nothing_raised { @controller_class.helper { def block_helper_method; end } } assert master_helper_methods.include?('block_helper_method') end def test_helper_block_include assert_equal expected_helper_methods, missing_methods assert_nothing_raised { @controller_class.helper { include HelperTest::TestHelper } } assert [], missing_methods end def test_helper_method assert_nothing_raised { @controller_class.helper_method :delegate_method } assert master_helper_methods.include?('delegate_method') end def test_helper_attr assert_nothing_raised { @controller_class.helper_attr :delegate_attr } assert master_helper_methods.include?('delegate_attr') assert master_helper_methods.include?('delegate_attr=') end def test_helper_for_nested_controller request = ActionController::TestRequest.new response = ActionController::TestResponse.new request.action = 'render_hello_world' assert_equal 'hello: Iz guuut!', Fun::GamesController.process(request, response).body end def test_helper_for_acronym_controller request = ActionController::TestRequest.new response = ActionController::TestResponse.new request.action = 'test' assert_equal 'test: baz', Fun::PdfController.process(request, response).body end def test_all_helpers methods = ApplicationController.master_helper_module.instance_methods.map(&:to_s) # abc_helper.rb assert methods.include?('bare_a') # fun/games_helper.rb assert methods.include?('stratego') # fun/pdf_helper.rb assert methods.include?('foobar') end def test_all_helpers_with_alternate_helper_dir @controller_class.helpers_dir = File.dirname(__FILE__) + '/../fixtures/alternate_helpers' # Reload helpers @controller_class.master_helper_module = Module.new @controller_class.helper :all # helpers/abc_helper.rb should not be included assert !master_helper_methods.include?('bare_a') # alternate_helpers/foo_helper.rb assert master_helper_methods.include?('baz') end def test_helper_proxy methods = ApplicationController.helpers.methods.map(&:to_s) # ActionView assert methods.include?('pluralize') # abc_helper.rb assert methods.include?('bare_a') # fun/games_helper.rb assert methods.include?('stratego') # fun/pdf_helper.rb assert methods.include?('foobar') end private def expected_helper_methods TestHelper.instance_methods.map(&:to_s) end def master_helper_methods @controller_class.master_helper_module.instance_methods.map(&:to_s) end def missing_methods expected_helper_methods - master_helper_methods end def test_helper=(helper_module) silence_warnings { self.class.const_set('TestHelper', helper_module) } end end class IsolatedHelpersTest < Test::Unit::TestCase class A < ActionController::Base def index render :inline => '<%= shout %>' end def rescue_action(e) raise end end class B < A helper { def shout; 'B' end } def index render :inline => '<%= shout %>' end end class C < A helper { def shout; 'C' end } def index render :inline => '<%= shout %>' end end def setup @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @request.action = 'index' end def test_helper_in_a assert_raise(NameError) { A.process(@request, @response) } end def test_helper_in_b assert_equal 'B', B.process(@request, @response).body end def test_helper_in_c assert_equal 'C', C.process(@request, @response).body end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/render_test.rb
provider/vendor/rails/actionpack/test/controller/render_test.rb
require 'abstract_unit' require 'controller/fake_models' module Fun class GamesController < ActionController::Base def hello_world end end end class MockLogger attr_reader :logged def initialize @logged = [] end def method_missing(method, *args) @logged << args.first end end class TestController < ActionController::Base protect_from_forgery class LabellingFormBuilder < ActionView::Helpers::FormBuilder end layout :determine_layout def hello_world end def conditional_hello if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123]) render :action => 'hello_world' end end def conditional_hello_with_public_header if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true) render :action => 'hello_world' end end def conditional_hello_with_public_header_and_expires_at expires_in 1.minute if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true) render :action => 'hello_world' end end def conditional_hello_with_expires_in expires_in 1.minute render :action => 'hello_world' end def conditional_hello_with_expires_in_with_public expires_in 1.minute, :public => true render :action => 'hello_world' end def conditional_hello_with_expires_in_with_public_with_more_keys expires_in 1.minute, :public => true, 'max-stale' => 5.hours render :action => 'hello_world' end def conditional_hello_with_expires_in_with_public_with_more_keys_old_syntax expires_in 1.minute, :public => true, :private => nil, 'max-stale' => 5.hours render :action => 'hello_world' end def conditional_hello_with_bangs render :action => 'hello_world' end before_filter :handle_last_modified_and_etags, :only=>:conditional_hello_with_bangs def handle_last_modified_and_etags fresh_when(:last_modified => Time.now.utc.beginning_of_day, :etag => [ :foo, 123 ]) end def render_hello_world render :template => "test/hello_world" end def render_hello_world_with_last_modified_set response.last_modified = Date.new(2008, 10, 10).to_time render :template => "test/hello_world" end def render_hello_world_with_etag_set response.etag = "hello_world" render :template => "test/hello_world" end def render_hello_world_with_forward_slash render :template => "/test/hello_world" end def render_template_in_top_directory render :template => 'shared' end def render_template_in_top_directory_with_slash render :template => '/shared' end def render_hello_world_from_variable @person = "david" render :text => "hello #{@person}" end def render_action_hello_world render :action => "hello_world" end def render_action_hello_world_as_string render "hello_world" end def render_action_hello_world_with_symbol render :action => :hello_world end def render_text_hello_world render :text => "hello world" end def render_text_hello_world_with_layout @variable_for_layout = ", I'm here!" render :text => "hello world", :layout => true end def hello_world_with_layout_false render :layout => false end def render_file_with_instance_variables @secret = 'in the sauce' path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb') render :file => path end def render_file_as_string_with_instance_variables @secret = 'in the sauce' path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')) render path end def render_file_not_using_full_path @secret = 'in the sauce' render :file => 'test/render_file_with_ivar' end def render_file_not_using_full_path_with_dot_in_path @secret = 'in the sauce' render :file => 'test/dot.directory/render_file_with_ivar' end def render_file_using_pathname @secret = 'in the sauce' render :file => Pathname.new(File.dirname(__FILE__)).join('..', 'fixtures', 'test', 'dot.directory', 'render_file_with_ivar.erb') end def render_file_from_template @secret = 'in the sauce' @path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')) end def render_file_with_locals path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb') render :file => path, :locals => {:secret => 'in the sauce'} end def render_file_as_string_with_locals path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb')) render path, :locals => {:secret => 'in the sauce'} end def accessing_request_in_template render :inline => "Hello: <%= request.host %>" end def accessing_logger_in_template render :inline => "<%= logger.class %>" end def accessing_action_name_in_template render :inline => "<%= action_name %>" end def accessing_controller_name_in_template render :inline => "<%= controller_name %>" end def render_json_nil render :json => nil end def render_json_hello_world render :json => ActiveSupport::JSON.encode(:hello => 'world') end def render_json_hello_world_with_callback render :json => ActiveSupport::JSON.encode(:hello => 'world'), :callback => 'alert' end def render_json_with_custom_content_type render :json => ActiveSupport::JSON.encode(:hello => 'world'), :content_type => 'text/javascript' end def render_symbol_json render :json => ActiveSupport::JSON.encode(:hello => 'world') end def render_json_with_render_to_string render :json => {:hello => render_to_string(:partial => 'partial')} end def render_custom_code render :text => "hello world", :status => 404 end def render_custom_code_rjs render :update, :status => 404 do |page| page.replace :foo, :partial => 'partial' end end def render_text_with_nil render :text => nil end def render_text_with_false render :text => false end def render_nothing_with_appendix render :text => "appended" end def render_vanilla_js_hello render :js => "alert('hello')" end def render_xml_hello @name = "David" render :template => "test/hello" end def render_xml_hello_as_string_template @name = "David" render "test/hello" end def render_xml_with_custom_content_type render :xml => "<blah/>", :content_type => "application/atomsvc+xml" end def render_line_offset render :inline => '<% raise %>', :locals => {:foo => 'bar'} end def heading head :ok end def greeting # let's just rely on the template end def blank_response render :text => ' ' end def layout_test render :action => "hello_world" end def builder_layout_test render :action => "hello", :layout => "layouts/builder" end def builder_partial_test render :action => "hello_world_container" end def partials_list @test_unchanged = 'hello' @customers = [ Customer.new("david"), Customer.new("mary") ] render :action => "list" end def partial_only render :partial => true end def hello_in_a_string @customers = [ Customer.new("david"), Customer.new("mary") ] render :text => "How's there? " + render_to_string(:template => "test/list") end def accessing_params_in_template render :inline => "Hello: <%= params[:name] %>" end def accessing_local_assigns_in_inline_template name = params[:local_name] render :inline => "<%= 'Goodbye, ' + local_name %>", :locals => { :local_name => name } end def render_implicit_html_template end def render_explicit_html_template end def render_implicit_html_template_from_xhr_request end def render_implicit_js_template_without_layout end def render_html_explicit_template_and_layout render :template => 'test/render_implicit_html_template_from_xhr_request', :layout => 'layouts/default_html' end def formatted_html_erb end def formatted_xml_erb end def render_to_string_test @foo = render_to_string :inline => "this is a test" end def default_render if @alternate_default_render @alternate_default_render.call else super end end def render_action_hello_world_as_symbol render :action => :hello_world end def layout_test_with_different_layout render :action => "hello_world", :layout => "standard" end def layout_test_with_different_layout_and_string_action render "hello_world", :layout => "standard" end def layout_test_with_different_layout_and_symbol_action render :hello_world, :layout => "standard" end def rendering_without_layout render :action => "hello_world", :layout => false end def layout_overriding_layout render :action => "hello_world", :layout => "standard" end def rendering_nothing_on_layout render :nothing => true end def render_to_string_with_assigns @before = "i'm before the render" render_to_string :text => "foo" @after = "i'm after the render" render :action => "test/hello_world" end def render_to_string_with_exception render_to_string :file => "exception that will not be caught - this will certainly not work" end def render_to_string_with_caught_exception @before = "i'm before the render" begin render_to_string :file => "exception that will be caught- hope my future instance vars still work!" rescue end @after = "i'm after the render" render :action => "test/hello_world" end def accessing_params_in_template_with_layout render :layout => nil, :inline => "Hello: <%= params[:name] %>" end def render_with_explicit_template render :template => "test/hello_world" end def render_with_explicit_string_template render "test/hello_world" end def render_with_explicit_template_with_locals render :template => "test/render_file_with_locals", :locals => { :secret => 'area51' } end def double_render render :text => "hello" render :text => "world" end def double_redirect redirect_to :action => "double_render" redirect_to :action => "double_render" end def render_and_redirect render :text => "hello" redirect_to :action => "double_render" end def render_to_string_and_render @stuff = render_to_string :text => "here is some cached stuff" render :text => "Hi web users! #{@stuff}" end def render_to_string_with_inline_and_render render_to_string :inline => "<%= 'dlrow olleh'.reverse %>" render :template => "test/hello_world" end def rendering_with_conflicting_local_vars @name = "David" def @template.name() nil end render :action => "potential_conflicts" end def hello_world_from_rxml_using_action render :action => "hello_world_from_rxml.builder" end def hello_world_from_rxml_using_template render :template => "test/hello_world_from_rxml.builder" end module RenderTestHelper def rjs_helper_method_from_module page.visual_effect :highlight end end helper RenderTestHelper helper do def rjs_helper_method(value) page.visual_effect :highlight, value end end def enum_rjs_test render :update do |page| page.select('.product').each do |value| page.rjs_helper_method_from_module page.rjs_helper_method(value) page.sortable(value, :url => { :action => "order" }) page.draggable(value) end end end def delete_with_js @project_id = 4 end def render_js_with_explicit_template @project_id = 4 render :template => 'test/delete_with_js' end def render_js_with_explicit_action_template @project_id = 4 render :action => 'delete_with_js' end def update_page render :update do |page| page.replace_html 'balance', '$37,000,000.00' page.visual_effect :highlight, 'balance' end end def update_page_with_instance_variables @money = '$37,000,000.00' @div_id = 'balance' render :update do |page| page.replace_html @div_id, @money page.visual_effect :highlight, @div_id end end def update_page_with_view_method render :update do |page| page.replace_html 'person', pluralize(2, 'person') end end def action_talk_to_layout # Action template sets variable that's picked up by layout end def render_text_with_assigns @hello = "world" render :text => "foo" end def yield_content_for render :action => "content_for", :layout => "yield" end def render_content_type_from_body response.content_type = Mime::RSS render :text => "hello world!" end def head_with_location_header head :location => "/foo" end def head_with_symbolic_status head :status => params[:status].intern end def head_with_integer_status head :status => params[:status].to_i end def head_with_string_status head :status => params[:status] end def head_with_custom_header head :x_custom_header => "something" end def head_with_status_code_first head :forbidden, :x_custom_header => "something" end def render_with_location render :xml => "<hello/>", :location => "http://example.com", :status => 201 end def render_with_object_location customer = Customer.new("Some guy", 1) render :xml => "<customer/>", :location => customer_url(customer), :status => :created end def render_with_to_xml to_xmlable = Class.new do def to_xml "<i-am-xml/>" end end.new render :xml => to_xmlable end def render_using_layout_around_block render :action => "using_layout_around_block" end def render_using_layout_around_block_with_args render :action => "using_layout_around_block_with_args" end def render_using_layout_around_block_in_main_layout_and_within_content_for_layout render :action => "using_layout_around_block", :layout => "layouts/block_with_layout" end def partial_dot_html render :partial => 'partial.html.erb' end def partial_as_rjs render :update do |page| page.replace :foo, :partial => 'partial' end end def respond_to_partial_as_rjs respond_to do |format| format.js do render :update do |page| page.replace :foo, :partial => 'partial' end end end end def partial render :partial => 'partial' end def render_alternate_default # For this test, the method "default_render" is overridden: @alternate_default_render = lambda do render :update do |page| page.replace :foo, :partial => 'partial' end end end def partial_only_with_layout render :partial => "partial_only", :layout => true end def render_to_string_with_partial @partial_only = render_to_string :partial => "partial_only" @partial_with_locals = render_to_string :partial => "customer", :locals => { :customer => Customer.new("david") } render :action => "test/hello_world" end def partial_with_counter render :partial => "counter", :locals => { :counter_counter => 5 } end def partial_with_locals render :partial => "customer", :locals => { :customer => Customer.new("david") } end def partial_with_form_builder render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, @template, {}, Proc.new {}) end def partial_with_form_builder_subclass render :partial => LabellingFormBuilder.new(:post, nil, @template, {}, Proc.new {}) end def partial_collection render :partial => "customer", :collection => [ Customer.new("david"), Customer.new("mary") ] end def partial_collection_with_as render :partial => "customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => :customer end def partial_collection_with_counter render :partial => "customer_counter", :collection => [ Customer.new("david"), Customer.new("mary") ] end def partial_collection_with_locals render :partial => "customer_greeting", :collection => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" } end def partial_collection_with_spacer render :partial => "customer", :spacer_template => "partial_only", :collection => [ Customer.new("david"), Customer.new("mary") ] end def partial_collection_shorthand_with_locals render :partial => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" } end def partial_collection_shorthand_with_different_types_of_records render :partial => [ BadCustomer.new("mark"), GoodCustomer.new("craig"), BadCustomer.new("john"), GoodCustomer.new("zach"), GoodCustomer.new("brandon"), BadCustomer.new("dan") ], :locals => { :greeting => "Bonjour" } end def empty_partial_collection render :partial => "customer", :collection => [] end def partial_collection_shorthand_with_different_types_of_records_with_counter partial_collection_shorthand_with_different_types_of_records end def missing_partial render :partial => 'thisFileIsntHere' end def partial_with_hash_object render :partial => "hash_object", :object => {:first_name => "Sam"} end def partial_with_nested_object render :partial => "quiz/questions/question", :object => Quiz::Question.new("first") end def partial_with_nested_object_shorthand render Quiz::Question.new("first") end def partial_hash_collection render :partial => "hash_object", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ] end def partial_hash_collection_with_locals render :partial => "hash_greeting", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ], :locals => { :greeting => "Hola" } end def partial_with_implicit_local_assignment @customer = Customer.new("Marcel") render :partial => "customer" end def render_call_to_partial_with_layout render :action => "calling_partial_with_layout" end def render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout render :action => "calling_partial_with_layout", :layout => "layouts/partial_with_layout" end def rescue_action(e) raise end private def determine_layout case action_name when "hello_world", "layout_test", "rendering_without_layout", "rendering_nothing_on_layout", "render_text_hello_world", "render_text_hello_world_with_layout", "hello_world_with_layout_false", "partial_only", "partial_only_with_layout", "accessing_params_in_template", "accessing_params_in_template_with_layout", "render_with_explicit_template", "render_with_explicit_string_template", "render_js_with_explicit_template", "render_js_with_explicit_action_template", "delete_with_js", "update_page", "update_page_with_instance_variables" "layouts/standard" when "render_implicit_js_template_without_layout" "layouts/default_html" when "action_talk_to_layout", "layout_overriding_layout" "layouts/talk_from_action" when "render_implicit_html_template_from_xhr_request" (request.xhr? ? 'layouts/xhr' : 'layouts/standard') end end end class RenderTest < ActionController::TestCase tests TestController def setup # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". @controller.logger = Logger.new(nil) @request.host = "www.nextangle.com" end def test_simple_show get :hello_world assert_response 200 assert_response :success assert_template "test/hello_world" assert_equal "<html>Hello world!</html>", @response.body end def test_renders_default_template_for_missing_action get :'hyphen-ated' assert_template 'test/hyphen-ated' end def test_render get :render_hello_world assert_template "test/hello_world" end def test_line_offset begin get :render_line_offset flunk "the action should have raised an exception" rescue RuntimeError => exc line = exc.backtrace.first assert(line =~ %r{:(\d+):}) assert_equal "1", $1, "The line offset is wrong, perhaps the wrong exception has been raised, exception was: #{exc.inspect}" end end def test_render_with_forward_slash get :render_hello_world_with_forward_slash assert_template "test/hello_world" end def test_render_in_top_directory get :render_template_in_top_directory assert_template "shared" assert_equal "Elastica", @response.body end def test_render_in_top_directory_with_slash get :render_template_in_top_directory_with_slash assert_template "shared" assert_equal "Elastica", @response.body end def test_render_from_variable get :render_hello_world_from_variable assert_equal "hello david", @response.body end def test_render_action get :render_action_hello_world assert_template "test/hello_world" end def test_render_action_hello_world_as_string get :render_action_hello_world_as_string assert_equal "Hello world!", @response.body assert_template "test/hello_world" end def test_render_action_with_symbol get :render_action_hello_world_with_symbol assert_template "test/hello_world" end def test_render_text get :render_text_hello_world assert_equal "hello world", @response.body end def test_do_with_render_text_and_layout get :render_text_hello_world_with_layout assert_equal "<html>hello world, I'm here!</html>", @response.body end def test_xhr_with_render_text_and_layout xhr :get, :render_text_hello_world_with_layout assert_equal "<html>hello world, I'm here!</html>", @response.body end def test_do_with_render_action_and_layout_false get :hello_world_with_layout_false assert_equal 'Hello world!', @response.body end def test_render_file_with_instance_variables get :render_file_with_instance_variables assert_equal "The secret is in the sauce\n", @response.body end def test_render_file_as_string_with_instance_variables get :render_file_as_string_with_instance_variables assert_equal "The secret is in the sauce\n", @response.body end def test_render_file_not_using_full_path get :render_file_not_using_full_path assert_equal "The secret is in the sauce\n", @response.body end def test_render_file_not_using_full_path_with_dot_in_path get :render_file_not_using_full_path_with_dot_in_path assert_equal "The secret is in the sauce\n", @response.body end def test_render_file_using_pathname get :render_file_using_pathname assert_equal "The secret is in the sauce\n", @response.body end def test_render_file_with_locals get :render_file_with_locals assert_equal "The secret is in the sauce\n", @response.body end def test_render_file_as_string_with_locals get :render_file_as_string_with_locals assert_equal "The secret is in the sauce\n", @response.body end def test_render_file_from_template get :render_file_from_template assert_equal "The secret is in the sauce\n", @response.body end def test_render_json_nil get :render_json_nil assert_equal 'null', @response.body assert_equal 'application/json', @response.content_type end def test_render_json get :render_json_hello_world assert_equal '{"hello":"world"}', @response.body assert_equal 'application/json', @response.content_type end def test_render_json_with_callback get :render_json_hello_world_with_callback assert_equal 'alert({"hello":"world"})', @response.body assert_equal 'application/json', @response.content_type end def test_render_json_with_custom_content_type get :render_json_with_custom_content_type assert_equal '{"hello":"world"}', @response.body assert_equal 'text/javascript', @response.content_type end def test_render_symbol_json get :render_symbol_json assert_equal '{"hello":"world"}', @response.body assert_equal 'application/json', @response.content_type end def test_render_json_with_render_to_string get :render_json_with_render_to_string assert_equal '{"hello":"partial html"}', @response.body assert_equal 'application/json', @response.content_type end def test_render_custom_code get :render_custom_code assert_response 404 assert_response :missing assert_equal 'hello world', @response.body end def test_render_custom_code_rjs get :render_custom_code_rjs assert_response 404 assert_equal %(Element.replace("foo", "partial html");), @response.body end def test_render_text_with_nil get :render_text_with_nil assert_response 200 assert_equal ' ', @response.body end def test_render_text_with_false get :render_text_with_false assert_equal 'false', @response.body end def test_render_nothing_with_appendix get :render_nothing_with_appendix assert_response 200 assert_equal 'appended', @response.body end def test_attempt_to_access_object_method assert_raise(ActionController::UnknownAction, "No action responded to [clone]") { get :clone } end def test_private_methods assert_raise(ActionController::UnknownAction, "No action responded to [determine_layout]") { get :determine_layout } end def test_access_to_request_in_view get :accessing_request_in_template assert_equal "Hello: www.nextangle.com", @response.body end def test_access_to_logger_in_view get :accessing_logger_in_template assert_equal "Logger", @response.body end def test_access_to_action_name_in_view get :accessing_action_name_in_template assert_equal "accessing_action_name_in_template", @response.body end def test_access_to_controller_name_in_view get :accessing_controller_name_in_template assert_equal "test", @response.body # name is explicitly set to 'test' inside the controller. end def test_render_vanilla_js get :render_vanilla_js_hello assert_equal "alert('hello')", @response.body assert_equal "text/javascript", @response.content_type end def test_render_xml get :render_xml_hello assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body assert_equal "application/xml", @response.content_type end def test_render_xml_as_string_template get :render_xml_hello_as_string_template assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body assert_equal "application/xml", @response.content_type end def test_render_xml_with_default get :greeting assert_equal "<p>This is grand!</p>\n", @response.body end def test_render_xml_with_partial get :builder_partial_test assert_equal "<test>\n <hello/>\n</test>\n", @response.body end def test_enum_rjs_test ActiveSupport::SecureRandom.stubs(:base64).returns("asdf") get :enum_rjs_test body = %{ $$(".product").each(function(value, index) { new Effect.Highlight(element,{}); new Effect.Highlight(value,{}); Sortable.create(value, {onUpdate:function(){new Ajax.Request('/test/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize(value) + '&authenticity_token=' + encodeURIComponent('asdf')})}}); new Draggable(value, {}); }); }.gsub(/^ /, '').strip assert_equal body, @response.body end def test_layout_rendering get :layout_test assert_equal "<html>Hello world!</html>", @response.body end def test_render_xml_with_layouts get :builder_layout_test assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body end def test_partials_list get :partials_list assert_equal "goodbyeHello: davidHello: marygoodbye\n", @response.body end def test_render_to_string get :hello_in_a_string assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body end def test_render_to_string_resets_assigns get :render_to_string_test assert_equal "The value of foo is: ::this is a test::\n", @response.body end def test_render_to_string_inline get :render_to_string_with_inline_and_render assert_template "test/hello_world" end def test_nested_rendering @controller = Fun::GamesController.new get :hello_world assert_equal "Living in a nested world", @response.body end def test_accessing_params_in_template get :accessing_params_in_template, :name => "David" assert_equal "Hello: David", @response.body end def test_accessing_local_assigns_in_inline_template get :accessing_local_assigns_in_inline_template, :local_name => "Local David" assert_equal "Goodbye, Local David", @response.body end def test_render_in_an_rjs_template_should_pick_html_templates_when_available [:js, "js"].each do |format| assert_nothing_raised do get :render_implicit_html_template, :format => format assert_equal %(document.write("Hello world\\n");), @response.body end end end def test_explicitly_rendering_an_html_template_with_implicit_html_template_renders_should_be_possible_from_an_rjs_template [:js, "js"].each do |format| assert_nothing_raised do get :render_explicit_html_template, :format => format assert_equal %(document.write("Hello world\\n");), @response.body end end end def test_should_implicitly_render_html_template_from_xhr_request xhr :get, :render_implicit_html_template_from_xhr_request assert_equal "XHR!\nHello HTML!", @response.body end def test_should_render_explicit_html_template_with_html_layout xhr :get, :render_html_explicit_template_and_layout assert_equal "<html>Hello HTML!</html>\n", @response.body end def test_should_implicitly_render_js_template_without_layout get :render_implicit_js_template_without_layout, :format => :js assert_no_match /<html>/, @response.body end def test_should_render_formatted_template get :formatted_html_erb assert_equal 'formatted html erb', @response.body end def test_should_render_formatted_xml_erb_template get :formatted_xml_erb, :format => :xml assert_equal '<test>passed formatted xml erb</test>', @response.body end def test_should_render_formatted_html_erb_template get :formatted_xml_erb assert_equal '<test>passed formatted html erb</test>', @response.body end def test_should_render_formatted_html_erb_template_with_faulty_accepts_header @request.accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, appliction/x-shockwave-flash, */*" get :formatted_xml_erb assert_equal '<test>passed formatted html erb</test>', @response.body end def test_should_render_xml_but_keep_custom_content_type get :render_xml_with_custom_content_type assert_equal "application/atomsvc+xml", @response.content_type end def test_render_with_default_from_accept_header xhr :get, :greeting assert_equal "$(\"body\").visualEffect(\"highlight\");", @response.body end def test_render_rjs_with_default get :delete_with_js assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body end def test_render_rjs_template_explicitly get :render_js_with_explicit_template assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body end def test_rendering_rjs_action_explicitly get :render_js_with_explicit_action_template assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body end def test_layout_test_with_different_layout get :layout_test_with_different_layout assert_equal "<html>Hello world!</html>", @response.body end def test_layout_test_with_different_layout_and_string_action get :layout_test_with_different_layout_and_string_action assert_equal "<html>Hello world!</html>", @response.body end def test_layout_test_with_different_layout_and_symbol_action get :layout_test_with_different_layout_and_symbol_action assert_equal "<html>Hello world!</html>", @response.body end def test_rendering_without_layout get :rendering_without_layout assert_equal "Hello world!", @response.body end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/header_test.rb
provider/vendor/rails/actionpack/test/controller/header_test.rb
require 'abstract_unit' class HeaderTest < Test::Unit::TestCase def setup @headers = ActionController::Http::Headers.new("HTTP_CONTENT_TYPE"=>"text/plain") end def test_content_type_works assert_equal "text/plain", @headers["Content-Type"] assert_equal "text/plain", @headers["content-type"] assert_equal "text/plain", @headers["CONTENT_TYPE"] assert_equal "text/plain", @headers["HTTP_CONTENT_TYPE"] end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/polymorphic_routes_test.rb
provider/vendor/rails/actionpack/test/controller/polymorphic_routes_test.rb
require 'abstract_unit' class Article attr_reader :id def save; @id = 1 end def new_record?; @id.nil? end def name model = self.class.name.downcase @id.nil? ? "new #{model}" : "#{model} ##{@id}" end end class Response < Article def post_id; 1 end end class Tag < Article def response_id; 1 end end class Tax attr_reader :id def save; @id = 1 end def new_record?; @id.nil? end def name model = self.class.name.downcase @id.nil? ? "new #{model}" : "#{model} ##{@id}" end end class Fax < Tax def store_id; 1 end end # TODO: test nested models class Response::Nested < Response; end class PolymorphicRoutesTest < ActiveSupport::TestCase include ActionController::PolymorphicRoutes def setup @article = Article.new @response = Response.new @tax = Tax.new @fax = Fax.new end def test_with_record @article.save expects(:article_url).with(@article) polymorphic_url(@article) end def test_with_new_record expects(:articles_url).with() @article.expects(:new_record?).returns(true) polymorphic_url(@article) end def test_with_record_and_action expects(:new_article_url).with() @article.expects(:new_record?).never polymorphic_url(@article, :action => 'new') end def test_url_helper_prefixed_with_new expects(:new_article_url).with() new_polymorphic_url(@article) end def test_url_helper_prefixed_with_edit @article.save expects(:edit_article_url).with(@article) edit_polymorphic_url(@article) end def test_url_helper_prefixed_with_edit_with_url_options @article.save expects(:edit_article_url).with(@article, :param1 => '10') edit_polymorphic_url(@article, :param1 => '10') end def test_url_helper_with_url_options @article.save expects(:article_url).with(@article, :param1 => '10') polymorphic_url(@article, :param1 => '10') end def test_formatted_url_helper_is_deprecated expects(:articles_url).with(:format => :pdf) assert_deprecated do formatted_polymorphic_url([@article, :pdf]) end end def test_format_option @article.save expects(:article_url).with(@article, :format => :pdf) polymorphic_url(@article, :format => :pdf) end def test_format_option_with_url_options @article.save expects(:article_url).with(@article, :format => :pdf, :param1 => '10') polymorphic_url(@article, :format => :pdf, :param1 => '10') end def test_id_and_format_option @article.save expects(:article_url).with(:id => @article, :format => :pdf) polymorphic_url(:id => @article, :format => :pdf) end def test_with_nested @response.save expects(:article_response_url).with(@article, @response) polymorphic_url([@article, @response]) end def test_with_nested_unsaved expects(:article_responses_url).with(@article) polymorphic_url([@article, @response]) end def test_new_with_array_and_namespace expects(:new_admin_article_url).with() polymorphic_url([:admin, @article], :action => 'new') end def test_unsaved_with_array_and_namespace expects(:admin_articles_url).with() polymorphic_url([:admin, @article]) end def test_nested_unsaved_with_array_and_namespace @article.save expects(:admin_article_url).with(@article) polymorphic_url([:admin, @article]) expects(:admin_article_responses_url).with(@article) polymorphic_url([:admin, @article, @response]) end def test_nested_with_array_and_namespace @response.save expects(:admin_article_response_url).with(@article, @response) polymorphic_url([:admin, @article, @response]) # a ridiculously long named route tests correct ordering of namespaces and nesting: @tag = Tag.new @tag.save expects(:site_admin_article_response_tag_url).with(@article, @response, @tag) polymorphic_url([:site, :admin, @article, @response, @tag]) end def test_nesting_with_array_ending_in_singleton_resource expects(:article_response_url).with(@article) polymorphic_url([@article, :response]) end def test_nesting_with_array_containing_singleton_resource @tag = Tag.new @tag.save expects(:article_response_tag_url).with(@article, @tag) polymorphic_url([@article, :response, @tag]) end def test_nesting_with_array_containing_namespace_and_singleton_resource @tag = Tag.new @tag.save expects(:admin_article_response_tag_url).with(@article, @tag) polymorphic_url([:admin, @article, :response, @tag]) end def test_nesting_with_array_containing_singleton_resource_and_format @tag = Tag.new @tag.save expects(:article_response_tag_url).with(@article, @tag, :format => :pdf) polymorphic_url([@article, :response, @tag], :format => :pdf) end def test_nesting_with_array_containing_singleton_resource_and_format_option @tag = Tag.new @tag.save expects(:article_response_tag_url).with(@article, @tag, :format => :pdf) polymorphic_url([@article, :response, @tag], :format => :pdf) end def test_nesting_with_array_containing_nil expects(:article_response_url).with(@article) polymorphic_url([@article, nil, :response]) end def test_with_array_containing_single_object @article.save expects(:article_url).with(@article) polymorphic_url([nil, @article]) end def test_with_array_containing_single_name @article.save expects(:articles_url) polymorphic_url([:articles]) end # TODO: Needs to be updated to correctly know about whether the object is in a hash or not def xtest_with_hash expects(:article_url).with(@article) @article.save polymorphic_url(:id => @article) end def test_polymorphic_path_accepts_options expects(:new_article_path).with() polymorphic_path(@article, :action => :new) end def test_polymorphic_path_does_not_modify_arguments expects(:admin_article_responses_url).with(@article) path = [:admin, @article, @response] assert_no_difference 'path.size' do polymorphic_url(path) end end # Tests for names where .plural.singular doesn't round-trip def test_with_irregular_plural_record @tax.save expects(:taxis_url).with(@tax) polymorphic_url(@tax) end def test_with_irregular_plural_new_record expects(:taxes_url).with() @tax.expects(:new_record?).returns(true) polymorphic_url(@tax) end def test_with_irregular_plural_record_and_action expects(:new_taxis_url).with() @tax.expects(:new_record?).never polymorphic_url(@tax, :action => 'new') end def test_irregular_plural_url_helper_prefixed_with_new expects(:new_taxis_url).with() new_polymorphic_url(@tax) end def test_irregular_plural_url_helper_prefixed_with_edit @tax.save expects(:edit_taxis_url).with(@tax) edit_polymorphic_url(@tax) end def test_with_nested_irregular_plurals @fax.save expects(:taxis_faxis_url).with(@tax, @fax) polymorphic_url([@tax, @fax]) end def test_with_nested_unsaved_irregular_plurals expects(:taxis_faxes_url).with(@tax) polymorphic_url([@tax, @fax]) end def test_new_with_irregular_plural_array_and_namespace expects(:new_admin_taxis_url).with() polymorphic_url([:admin, @tax], :action => 'new') end def test_unsaved_with_irregular_plural_array_and_namespace expects(:admin_taxes_url).with() polymorphic_url([:admin, @tax]) end def test_nesting_with_irregular_plurals_and_array_ending_in_singleton_resource expects(:taxis_faxis_url).with(@tax) polymorphic_url([@tax, :faxis]) end def test_with_array_containing_single_irregular_plural_object @tax.save expects(:taxis_url).with(@tax) polymorphic_url([nil, @tax]) end def test_with_array_containing_single_name_irregular_plural @tax.save expects(:taxes_url) polymorphic_url([:taxes]) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/content_type_test.rb
provider/vendor/rails/actionpack/test/controller/content_type_test.rb
require 'abstract_unit' class ContentTypeController < ActionController::Base def render_content_type_from_body response.content_type = Mime::RSS render :text => "hello world!" end def render_defaults render :text => "hello world!" end def render_content_type_from_render render :text => "hello world!", :content_type => Mime::RSS end def render_charset_from_body response.charset = "utf-16" render :text => "hello world!" end def render_nil_charset_from_body response.charset = nil render :text => "hello world!" end def render_default_for_rhtml end def render_default_for_rxml end def render_default_for_rjs end def render_change_for_rxml response.content_type = Mime::HTML render :action => "render_default_for_rxml" end def render_default_content_types_for_respond_to respond_to do |format| format.html { render :text => "hello world!" } format.xml { render :action => "render_default_content_types_for_respond_to.rhtml" } format.js { render :text => "hello world!" } format.rss { render :text => "hello world!", :content_type => Mime::XML } end end def rescue_action(e) raise end end class ContentTypeTest < ActionController::TestCase tests ContentTypeController def setup # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". @controller.logger = Logger.new(nil) end def test_render_defaults get :render_defaults assert_equal "utf-8", @response.charset assert_equal Mime::HTML, @response.content_type end def test_render_changed_charset_default ContentTypeController.default_charset = "utf-16" get :render_defaults assert_equal "utf-16", @response.charset assert_equal Mime::HTML, @response.content_type ContentTypeController.default_charset = "utf-8" end def test_content_type_from_body get :render_content_type_from_body assert_equal "application/rss+xml", @response.content_type assert_equal "utf-8", @response.charset end def test_content_type_from_render get :render_content_type_from_render assert_equal "application/rss+xml", @response.content_type assert_equal "utf-8", @response.charset end def test_charset_from_body get :render_charset_from_body assert_equal Mime::HTML, @response.content_type assert_equal "utf-16", @response.charset end def test_nil_charset_from_body get :render_nil_charset_from_body assert_equal Mime::HTML, @response.content_type assert_equal "utf-8", @response.charset, @response.headers.inspect end def test_nil_default_for_rhtml ContentTypeController.default_charset = nil get :render_default_for_rhtml assert_equal Mime::HTML, @response.content_type assert_nil @response.charset, @response.headers.inspect ensure ContentTypeController.default_charset = "utf-8" end def test_default_for_rhtml get :render_default_for_rhtml assert_equal Mime::HTML, @response.content_type assert_equal "utf-8", @response.charset end def test_default_for_rxml get :render_default_for_rxml assert_equal Mime::XML, @response.content_type assert_equal "utf-8", @response.charset end def test_default_for_rjs xhr :post, :render_default_for_rjs assert_equal Mime::JS, @response.content_type assert_equal "utf-8", @response.charset end def test_change_for_rxml get :render_change_for_rxml assert_equal Mime::HTML, @response.content_type assert_equal "utf-8", @response.charset end end class AcceptBasedContentTypeTest < ActionController::TestCase tests ContentTypeController def setup ActionController::Base.use_accept_header = true end def teardown ActionController::Base.use_accept_header = false end def test_render_default_content_types_for_respond_to @request.accept = Mime::HTML.to_s get :render_default_content_types_for_respond_to assert_equal Mime::HTML, @response.content_type @request.accept = Mime::JS.to_s get :render_default_content_types_for_respond_to assert_equal Mime::JS, @response.content_type end def test_render_default_content_types_for_respond_to_with_template @request.accept = Mime::XML.to_s get :render_default_content_types_for_respond_to assert_equal Mime::XML, @response.content_type end def test_render_default_content_types_for_respond_to_with_overwrite @request.accept = Mime::RSS.to_s get :render_default_content_types_for_respond_to assert_equal Mime::XML, @response.content_type end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/reloader_test.rb
provider/vendor/rails/actionpack/test/controller/reloader_test.rb
require 'abstract_unit' class ReloaderTests < ActiveSupport::TestCase Reloader = ActionController::Reloader Dispatcher = ActionController::Dispatcher class MyBody < Array def initialize(&block) @on_close = block end def foo "foo" end def bar "bar" end def close @on_close.call if @on_close end end def setup @lock = Mutex.new end def test_it_reloads_the_application_before_yielding Dispatcher.expects(:reload_application) Reloader.run(@lock) do [200, { "Content-Type" => "text/html" }, [""]] end end def test_it_locks_before_yielding lock = DummyMutex.new Dispatcher.expects(:reload_application) Reloader.run(lock) do assert lock.locked? [200, { "Content-Type" => "text/html" }, [""]] end assert lock.locked? end def test_it_unlocks_upon_calling_close_on_body lock = DummyMutex.new Dispatcher.expects(:reload_application) headers, status, body = Reloader.run(lock) do [200, { "Content-Type" => "text/html" }, [""]] end body.close assert !lock.locked? end def test_it_unlocks_if_app_object_raises_exception lock = DummyMutex.new Dispatcher.expects(:reload_application) assert_raise(RuntimeError) do Reloader.run(lock) do raise "oh no!" end end assert !lock.locked? end def test_returned_body_object_always_responds_to_close status, headers, body = Reloader.run(@lock) do [200, { "Content-Type" => "text/html" }, [""]] end assert body.respond_to?(:close) end def test_returned_body_object_behaves_like_underlying_object status, headers, body = Reloader.run(@lock) do b = MyBody.new b << "hello" b << "world" [200, { "Content-Type" => "text/html" }, b] end assert_equal 2, body.size assert_equal "hello", body[0] assert_equal "world", body[1] assert_equal "foo", body.foo assert_equal "bar", body.bar end def test_it_calls_close_on_underlying_object_when_close_is_called_on_body close_called = false status, headers, body = Reloader.run(@lock) do b = MyBody.new do close_called = true end [200, { "Content-Type" => "text/html" }, b] end body.close assert close_called end def test_returned_body_object_responds_to_all_methods_supported_by_underlying_object status, headers, body = Reloader.run(@lock) do [200, { "Content-Type" => "text/html" }, MyBody.new] end assert body.respond_to?(:size) assert body.respond_to?(:each) assert body.respond_to?(:foo) assert body.respond_to?(:bar) end def test_it_doesnt_clean_up_the_application_after_call Dispatcher.expects(:cleanup_application).never status, headers, body = Reloader.run(@lock) do [200, { "Content-Type" => "text/html" }, MyBody.new] end end def test_it_cleans_up_the_application_when_close_is_called_on_body Dispatcher.expects(:cleanup_application) status, headers, body = Reloader.run(@lock) do [200, { "Content-Type" => "text/html" }, MyBody.new] end body.close end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/assert_select_test.rb
provider/vendor/rails/actionpack/test/controller/assert_select_test.rb
#-- # Copyright (c) 2006 Assaf Arkin (http://labnotes.org) # Under MIT and/or CC By license. #++ require 'abstract_unit' require 'controller/fake_controllers' unless defined?(ActionMailer) begin $:.unshift("#{File.dirname(__FILE__)}/../../../actionmailer/lib") require 'action_mailer' rescue LoadError => e raise unless e.message =~ /action_mailer/ require 'rubygems' gem 'actionmailer' end end ActionMailer::Base.template_root = FIXTURE_LOAD_PATH class AssertSelectTest < ActionController::TestCase Assertion = ActiveSupport::TestCase::Assertion class AssertSelectMailer < ActionMailer::Base def test(html) recipients "test <test@test.host>" from "test@test.host" subject "Test e-mail" part :content_type=>"text/html", :body=>html end end class AssertSelectController < ActionController::Base def response_with=(content) @content = content end def response_with(&block) @update = block end def html() render :text=>@content, :layout=>false, :content_type=>Mime::HTML @content = nil end def rjs() render :update do |page| @update.call page end @update = nil end def xml() render :text=>@content, :layout=>false, :content_type=>Mime::XML @content = nil end def rescue_action(e) raise e end end tests AssertSelectController def setup ActionMailer::Base.delivery_method = :test ActionMailer::Base.perform_deliveries = true ActionMailer::Base.deliveries = [] end def teardown ActionMailer::Base.deliveries.clear end def assert_failure(message, &block) e = assert_raise(Assertion, &block) assert_match(message, e.message) if Regexp === message assert_equal(message, e.message) if String === message end # # Test assert select. # def test_assert_select render_html %Q{<div id="1"></div><div id="2"></div>} assert_select "div", 2 assert_failure(/Expected at least 3 elements matching \"div\", found 2/) { assert_select "div", 3 } assert_failure(/Expected at least 1 element matching \"p\", found 0/) { assert_select "p" } end def test_equality_true_false render_html %Q{<div id="1"></div><div id="2"></div>} assert_nothing_raised { assert_select "div" } assert_raise(Assertion) { assert_select "p" } assert_nothing_raised { assert_select "div", true } assert_raise(Assertion) { assert_select "p", true } assert_raise(Assertion) { assert_select "div", false } assert_nothing_raised { assert_select "p", false } end def test_equality_string_and_regexp render_html %Q{<div id="1">foo</div><div id="2">foo</div>} assert_nothing_raised { assert_select "div", "foo" } assert_raise(Assertion) { assert_select "div", "bar" } assert_nothing_raised { assert_select "div", :text=>"foo" } assert_raise(Assertion) { assert_select "div", :text=>"bar" } assert_nothing_raised { assert_select "div", /(foo|bar)/ } assert_raise(Assertion) { assert_select "div", /foobar/ } assert_nothing_raised { assert_select "div", :text=>/(foo|bar)/ } assert_raise(Assertion) { assert_select "div", :text=>/foobar/ } assert_raise(Assertion) { assert_select "p", :text=>/foobar/ } end def test_equality_of_html render_html %Q{<p>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</p>} text = "\"This is not a big problem,\" he said." html = "<em>\"This is <strong>not</strong> a big problem,\"</em> he said." assert_nothing_raised { assert_select "p", text } assert_raise(Assertion) { assert_select "p", html } assert_nothing_raised { assert_select "p", :html=>html } assert_raise(Assertion) { assert_select "p", :html=>text } # No stripping for pre. render_html %Q{<pre>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</pre>} text = "\n\"This is not a big problem,\" he said.\n" html = "\n<em>\"This is <strong>not</strong> a big problem,\"</em> he said.\n" assert_nothing_raised { assert_select "pre", text } assert_raise(Assertion) { assert_select "pre", html } assert_nothing_raised { assert_select "pre", :html=>html } assert_raise(Assertion) { assert_select "pre", :html=>text } end def test_counts render_html %Q{<div id="1">foo</div><div id="2">foo</div>} assert_nothing_raised { assert_select "div", 2 } assert_failure(/Expected at least 3 elements matching \"div\", found 2/) do assert_select "div", 3 end assert_nothing_raised { assert_select "div", 1..2 } assert_failure(/Expected between 3 and 4 elements matching \"div\", found 2/) do assert_select "div", 3..4 end assert_nothing_raised { assert_select "div", :count=>2 } assert_failure(/Expected at least 3 elements matching \"div\", found 2/) do assert_select "div", :count=>3 end assert_nothing_raised { assert_select "div", :minimum=>1 } assert_nothing_raised { assert_select "div", :minimum=>2 } assert_failure(/Expected at least 3 elements matching \"div\", found 2/) do assert_select "div", :minimum=>3 end assert_nothing_raised { assert_select "div", :maximum=>2 } assert_nothing_raised { assert_select "div", :maximum=>3 } assert_failure(/Expected at most 1 element matching \"div\", found 2/) do assert_select "div", :maximum=>1 end assert_nothing_raised { assert_select "div", :minimum=>1, :maximum=>2 } assert_failure(/Expected between 3 and 4 elements matching \"div\", found 2/) do assert_select "div", :minimum=>3, :maximum=>4 end end def test_substitution_values render_html %Q{<div id="1">foo</div><div id="2">foo</div>} assert_select "div#?", /\d+/ do |elements| assert_equal 2, elements.size end assert_select "div" do assert_select "div#?", /\d+/ do |elements| assert_equal 2, elements.size assert_select "#1" assert_select "#2" end end end def test_nested_assert_select render_html %Q{<div id="1">foo</div><div id="2">foo</div>} assert_select "div" do |elements| assert_equal 2, elements.size assert_select elements[0], "#1" assert_select elements[1], "#2" end assert_select "div" do assert_select "div" do |elements| assert_equal 2, elements.size # Testing in a group is one thing assert_select "#1,#2" # Testing individually is another. assert_select "#1" assert_select "#2" assert_select "#3", false end end assert_failure(/Expected at least 1 element matching \"#4\", found 0\./) do assert_select "div" do assert_select "#4" end end end def test_assert_select_text_match render_html %Q{<div id="1"><span>foo</span></div><div id="2"><span>bar</span></div>} assert_select "div" do assert_nothing_raised { assert_select "div", "foo" } assert_nothing_raised { assert_select "div", "bar" } assert_nothing_raised { assert_select "div", /\w*/ } assert_nothing_raised { assert_select "div", /\w*/, :count=>2 } assert_raise(Assertion) { assert_select "div", :text=>"foo", :count=>2 } assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" } assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" } assert_nothing_raised { assert_select "div", :html=>/\w*/ } assert_nothing_raised { assert_select "div", :html=>/\w*/, :count=>2 } assert_raise(Assertion) { assert_select "div", :html=>"<span>foo</span>", :count=>2 } end end # With single result. def test_assert_select_from_rjs_with_single_result render_rjs do |page| page.replace_html "test", "<div id=\"1\">foo</div>\n<div id=\"2\">foo</div>" end assert_select "div" do |elements| assert elements.size == 2 assert_select "#1" assert_select "#2" end assert_select "div#?", /\d+/ do |elements| assert_select "#1" assert_select "#2" end end # With multiple results. def test_assert_select_from_rjs_with_multiple_results render_rjs do |page| page.replace_html "test", "<div id=\"1\">foo</div>" page.replace_html "test2", "<div id=\"2\">foo</div>" end assert_select "div" do |elements| assert elements.size == 2 assert_select "#1" assert_select "#2" end end def test_assert_select_rjs_for_positioned_insert_should_fail_when_mixing_arguments render_rjs do |page| page.insert_html :top, "test1", "<div id=\"1\">foo</div>" page.insert_html :bottom, "test2", "<div id=\"2\">foo</div>" end assert_raise(Assertion) {assert_select_rjs :insert, :top, "test2"} end def test_elect_with_xml_namespace_attributes render_html %Q{<link xlink:href="http://nowhere.com"></link>} assert_nothing_raised { assert_select "link[xlink:href=http://nowhere.com]" } end # # Test css_select. # def test_css_select render_html %Q{<div id="1"></div><div id="2"></div>} assert 2, css_select("div").size assert 0, css_select("p").size end def test_nested_css_select render_html %Q{<div id="1">foo</div><div id="2">foo</div>} assert_select "div#?", /\d+/ do |elements| assert_equal 1, css_select(elements[0], "div").size assert_equal 1, css_select(elements[1], "div").size end assert_select "div" do assert_equal 2, css_select("div").size css_select("div").each do |element| # Testing as a group is one thing assert !css_select("#1,#2").empty? # Testing individually is another assert !css_select("#1").empty? assert !css_select("#2").empty? end end end # With one result. def test_css_select_from_rjs_with_single_result render_rjs do |page| page.replace_html "test", "<div id=\"1\">foo</div>\n<div id=\"2\">foo</div>" end assert_equal 2, css_select("div").size assert_equal 1, css_select("#1").size assert_equal 1, css_select("#2").size end # With multiple results. def test_css_select_from_rjs_with_multiple_results render_rjs do |page| page.replace_html "test", "<div id=\"1\">foo</div>" page.replace_html "test2", "<div id=\"2\">foo</div>" end assert_equal 2, css_select("div").size assert_equal 1, css_select("#1").size assert_equal 1, css_select("#2").size end # # Test assert_select_rjs. # # Test that we can pick up all statements in the result. def test_assert_select_rjs_picks_up_all_statements render_rjs do |page| page.replace "test", "<div id=\"1\">foo</div>" page.replace_html "test2", "<div id=\"2\">foo</div>" page.insert_html :top, "test3", "<div id=\"3\">foo</div>" end found = false assert_select_rjs do assert_select "#1" assert_select "#2" assert_select "#3" found = true end assert found end # Test that we fail if there is nothing to pick. def test_assert_select_rjs_fails_if_nothing_to_pick render_rjs { } assert_raise(Assertion) { assert_select_rjs } end def test_assert_select_rjs_with_unicode # Test that non-ascii characters (which are converted into \uXXXX in RJS) are decoded correctly. render_rjs do |page| page.replace "test", "<div id=\"1\">\343\203\201\343\202\261\343\203\203\343\203\210</div>" end assert_select_rjs do str = "#1" assert_select str, :text => "\343\203\201\343\202\261\343\203\203\343\203\210" assert_select str, "\343\203\201\343\202\261\343\203\203\343\203\210" if str.respond_to?(:force_encoding) str.force_encoding(Encoding::UTF_8) assert_select str, /\343\203\201..\343\203\210/u assert_raise(Assertion) { assert_select str, /\343\203\201.\343\203\210/u } else assert_select str, Regexp.new("\343\203\201..\343\203\210",0,'U') assert_raise(Assertion) { assert_select str, Regexp.new("\343\203\201.\343\203\210",0,'U') } end end end def test_assert_select_rjs_with_id # Test that we can pick up all statements in the result. render_rjs do |page| page.replace "test1", "<div id=\"1\">foo</div>" page.replace_html "test2", "<div id=\"2\">foo</div>" page.insert_html :top, "test3", "<div id=\"3\">foo</div>" end assert_select_rjs "test1" do assert_select "div", 1 assert_select "#1" end assert_select_rjs "test2" do assert_select "div", 1 assert_select "#2" end assert_select_rjs "test3" do assert_select "div", 1 assert_select "#3" end assert_raise(Assertion) { assert_select_rjs "test4" } end def test_assert_select_rjs_for_replace render_rjs do |page| page.replace "test1", "<div id=\"1\">foo</div>" page.replace_html "test2", "<div id=\"2\">foo</div>" page.insert_html :top, "test3", "<div id=\"3\">foo</div>" end # Replace. assert_select_rjs :replace do assert_select "div", 1 assert_select "#1" end assert_select_rjs :replace, "test1" do assert_select "div", 1 assert_select "#1" end assert_raise(Assertion) { assert_select_rjs :replace, "test2" } # Replace HTML. assert_select_rjs :replace_html do assert_select "div", 1 assert_select "#2" end assert_select_rjs :replace_html, "test2" do assert_select "div", 1 assert_select "#2" end assert_raise(Assertion) { assert_select_rjs :replace_html, "test1" } end def test_assert_select_rjs_for_chained_replace render_rjs do |page| page['test1'].replace "<div id=\"1\">foo</div>" page['test2'].replace_html "<div id=\"2\">foo</div>" page.insert_html :top, "test3", "<div id=\"3\">foo</div>" end # Replace. assert_select_rjs :chained_replace do assert_select "div", 1 assert_select "#1" end assert_select_rjs :chained_replace, "test1" do assert_select "div", 1 assert_select "#1" end assert_raise(Assertion) { assert_select_rjs :chained_replace, "test2" } # Replace HTML. assert_select_rjs :chained_replace_html do assert_select "div", 1 assert_select "#2" end assert_select_rjs :chained_replace_html, "test2" do assert_select "div", 1 assert_select "#2" end assert_raise(Assertion) { assert_select_rjs :replace_html, "test1" } end # Simple remove def test_assert_select_rjs_for_remove render_rjs do |page| page.remove "test1" end assert_select_rjs :remove, "test1" end def test_assert_select_rjs_for_remove_offers_useful_error_when_assertion_fails render_rjs do |page| page.remove "test_with_typo" end assert_select_rjs :remove, "test1" rescue Assertion assert_equal "No RJS statement that removes 'test1' was rendered.", $!.message end def test_assert_select_rjs_for_remove_ignores_block render_rjs do |page| page.remove "test1" end assert_nothing_raised do assert_select_rjs :remove, "test1" do assert_select "p" end end end # Simple show def test_assert_select_rjs_for_show render_rjs do |page| page.show "test1" end assert_select_rjs :show, "test1" end def test_assert_select_rjs_for_show_offers_useful_error_when_assertion_fails render_rjs do |page| page.show "test_with_typo" end assert_select_rjs :show, "test1" rescue Assertion assert_equal "No RJS statement that shows 'test1' was rendered.", $!.message end def test_assert_select_rjs_for_show_ignores_block render_rjs do |page| page.show "test1" end assert_nothing_raised do assert_select_rjs :show, "test1" do assert_select "p" end end end # Simple hide def test_assert_select_rjs_for_hide render_rjs do |page| page.hide "test1" end assert_select_rjs :hide, "test1" end def test_assert_select_rjs_for_hide_offers_useful_error_when_assertion_fails render_rjs do |page| page.hide "test_with_typo" end assert_select_rjs :hide, "test1" rescue Assertion assert_equal "No RJS statement that hides 'test1' was rendered.", $!.message end def test_assert_select_rjs_for_hide_ignores_block render_rjs do |page| page.hide "test1" end assert_nothing_raised do assert_select_rjs :hide, "test1" do assert_select "p" end end end # Simple toggle def test_assert_select_rjs_for_toggle render_rjs do |page| page.toggle "test1" end assert_select_rjs :toggle, "test1" end def test_assert_select_rjs_for_toggle_offers_useful_error_when_assertion_fails render_rjs do |page| page.toggle "test_with_typo" end assert_select_rjs :toggle, "test1" rescue Assertion assert_equal "No RJS statement that toggles 'test1' was rendered.", $!.message end def test_assert_select_rjs_for_toggle_ignores_block render_rjs do |page| page.toggle "test1" end assert_nothing_raised do assert_select_rjs :toggle, "test1" do assert_select "p" end end end # Non-positioned insert. def test_assert_select_rjs_for_nonpositioned_insert render_rjs do |page| page.replace "test1", "<div id=\"1\">foo</div>" page.replace_html "test2", "<div id=\"2\">foo</div>" page.insert_html :top, "test3", "<div id=\"3\">foo</div>" end assert_select_rjs :insert_html do assert_select "div", 1 assert_select "#3" end assert_select_rjs :insert_html, "test3" do assert_select "div", 1 assert_select "#3" end assert_raise(Assertion) { assert_select_rjs :insert_html, "test1" } end # Positioned insert. def test_assert_select_rjs_for_positioned_insert render_rjs do |page| page.insert_html :top, "test1", "<div id=\"1\">foo</div>" page.insert_html :bottom, "test2", "<div id=\"2\">foo</div>" page.insert_html :before, "test3", "<div id=\"3\">foo</div>" page.insert_html :after, "test4", "<div id=\"4\">foo</div>" end assert_select_rjs :insert, :top do assert_select "div", 1 assert_select "#1" end assert_select_rjs :insert, :bottom do assert_select "div", 1 assert_select "#2" end assert_select_rjs :insert, :before do assert_select "div", 1 assert_select "#3" end assert_select_rjs :insert, :after do assert_select "div", 1 assert_select "#4" end assert_select_rjs :insert_html do assert_select "div", 4 end end def test_assert_select_rjs_raise_errors assert_raise(ArgumentError) { assert_select_rjs(:destroy) } assert_raise(ArgumentError) { assert_select_rjs(:insert, :left) } end # Simple selection from a single result. def test_nested_assert_select_rjs_with_single_result render_rjs do |page| page.replace_html "test", "<div id=\"1\">foo</div>\n<div id=\"2\">foo</div>" end assert_select_rjs "test" do |elements| assert_equal 2, elements.size assert_select "#1" assert_select "#2" end end # Deal with two results. def test_nested_assert_select_rjs_with_two_results render_rjs do |page| page.replace_html "test", "<div id=\"1\">foo</div>" page.replace_html "test2", "<div id=\"2\">foo</div>" end assert_select_rjs "test" do |elements| assert_equal 1, elements.size assert_select "#1" end assert_select_rjs "test2" do |elements| assert_equal 1, elements.size assert_select "#2" end end def test_feed_item_encoded render_xml <<-EOF <rss version="2.0"> <channel> <item> <description> <![CDATA[ <p>Test 1</p> ]]> </description> </item> <item> <description> <![CDATA[ <p>Test 2</p> ]]> </description> </item> </channel> </rss> EOF assert_select "channel item description" do # Test element regardless of wrapper. assert_select_encoded do assert_select "p", :count=>2, :text=>/Test/ end # Test through encoded wrapper. assert_select_encoded do assert_select "encoded p", :count=>2, :text=>/Test/ end # Use :root instead (recommended) assert_select_encoded do assert_select ":root p", :count=>2, :text=>/Test/ end # Test individually. assert_select "description" do |elements| assert_select_encoded elements[0] do assert_select "p", "Test 1" end assert_select_encoded elements[1] do assert_select "p", "Test 2" end end end # Test that we only un-encode element itself. assert_select "channel item" do assert_select_encoded do assert_select "p", 0 end end end # # Test assert_select_email # def test_assert_select_email assert_raise(Assertion) { assert_select_email {} } AssertSelectMailer.deliver_test "<div><p>foo</p><p>bar</p></div>" assert_select_email do assert_select "div:root" do assert_select "p:first-child", "foo" assert_select "p:last-child", "bar" end end end protected def render_html(html) @controller.response_with = html get :html end def render_rjs(&block) @controller.response_with &block get :rjs end def render_xml(xml) @controller.response_with = xml get :xml end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/view_paths_test.rb
provider/vendor/rails/actionpack/test/controller/view_paths_test.rb
require 'abstract_unit' class ViewLoadPathsTest < ActionController::TestCase class TestController < ActionController::Base def self.controller_path() "test" end def rescue_action(e) raise end before_filter :add_view_path, :only => :hello_world_at_request_time def hello_world() end def hello_world_at_request_time() render(:action => 'hello_world') end private def add_view_path prepend_view_path "#{FIXTURE_LOAD_PATH}/override" end end class Test::SubController < ActionController::Base layout 'test/sub' def hello_world; render(:template => 'test/hello_world'); end end def setup TestController.view_paths = nil @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @controller = TestController.new # Following is needed in order to setup @controller.template object properly @controller.send :initialize_template_class, @response @controller.send :assign_shortcuts, @request, @response # Track the last warning. @old_behavior = ActiveSupport::Deprecation.behavior @last_message = nil ActiveSupport::Deprecation.behavior = Proc.new { |message, callback| @last_message = message } end def teardown ActiveSupport::Deprecation.behavior = @old_behavior end def test_template_load_path_was_set_correctly assert_equal [FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s) end def test_controller_appends_view_path_correctly @controller.append_view_path 'foo' assert_equal [FIXTURE_LOAD_PATH, 'foo'], @controller.view_paths.map(&:to_s) @controller.append_view_path(%w(bar baz)) assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths.map(&:to_s) @controller.append_view_path(FIXTURE_LOAD_PATH) assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s) end def test_controller_prepends_view_path_correctly @controller.prepend_view_path 'baz' assert_equal ['baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s) @controller.prepend_view_path(%w(foo bar)) assert_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s) @controller.prepend_view_path(FIXTURE_LOAD_PATH) assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s) end def test_template_appends_view_path_correctly @controller.instance_variable_set :@template, ActionView::Base.new(TestController.view_paths, {}, @controller) class_view_paths = TestController.view_paths @controller.append_view_path 'foo' assert_equal [FIXTURE_LOAD_PATH, 'foo'], @controller.view_paths.map(&:to_s) @controller.append_view_path(%w(bar baz)) assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths.map(&:to_s) assert_equal class_view_paths, TestController.view_paths end def test_template_prepends_view_path_correctly @controller.instance_variable_set :@template, ActionView::Base.new(TestController.view_paths, {}, @controller) class_view_paths = TestController.view_paths @controller.prepend_view_path 'baz' assert_equal ['baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s) @controller.prepend_view_path(%w(foo bar)) assert_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s) assert_equal class_view_paths, TestController.view_paths end def test_view_paths get :hello_world assert_response :success assert_equal "Hello world!", @response.body end def test_view_paths_override TestController.prepend_view_path "#{FIXTURE_LOAD_PATH}/override" get :hello_world assert_response :success assert_equal "Hello overridden world!", @response.body end def test_view_paths_override_for_layouts_in_controllers_with_a_module @controller = Test::SubController.new Test::SubController.view_paths = [ "#{FIXTURE_LOAD_PATH}/override", FIXTURE_LOAD_PATH, "#{FIXTURE_LOAD_PATH}/override2" ] get :hello_world assert_response :success assert_equal "layout: Hello overridden world!", @response.body end def test_view_paths_override_at_request_time get :hello_world_at_request_time assert_response :success assert_equal "Hello overridden world!", @response.body end def test_inheritance original_load_paths = ActionController::Base.view_paths self.class.class_eval %{ class A < ActionController::Base; end class B < A; end class C < ActionController::Base; end } A.view_paths = ['a/path'] assert_equal ['a/path'], A.view_paths.map(&:to_s) assert_equal A.view_paths, B.view_paths assert_equal original_load_paths, C.view_paths C.view_paths = [] assert_nothing_raised { C.view_paths << 'c/path' } assert_equal ['c/path'], C.view_paths.map(&:to_s) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/mime_type_test.rb
provider/vendor/rails/actionpack/test/controller/mime_type_test.rb
require 'abstract_unit' class MimeTypeTest < Test::Unit::TestCase Mime::Type.register "image/png", :png Mime::Type.register "application/pdf", :pdf def test_parse_single Mime::LOOKUP.keys.each do |mime_type| assert_equal [Mime::Type.lookup(mime_type)], Mime::Type.parse(mime_type) end end def test_parse_without_q accept = "text/xml,application/xhtml+xml,text/yaml,application/xml,text/html,image/png,text/plain,application/pdf,*/*" expect = [Mime::HTML, Mime::XML, Mime::YAML, Mime::PNG, Mime::TEXT, Mime::PDF, Mime::ALL] assert_equal expect, Mime::Type.parse(accept) end def test_parse_with_q accept = "text/xml,application/xhtml+xml,text/yaml; q=0.3,application/xml,text/html; q=0.8,image/png,text/plain; q=0.5,application/pdf,*/*; q=0.2" expect = [Mime::HTML, Mime::XML, Mime::PNG, Mime::PDF, Mime::TEXT, Mime::YAML, Mime::ALL] assert_equal expect, Mime::Type.parse(accept) end # Accept header send with user HTTP_USER_AGENT: Sunrise/0.42j (Windows XP) def test_parse_crappy_broken_acceptlines accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/*,,*/*;q=0.5" expect = [Mime::HTML, Mime::XML, "image/*", Mime::TEXT, Mime::ALL] assert_equal expect, Mime::Type.parse(accept).collect { |c| c.to_s } end # Accept header send with user HTTP_USER_AGENT: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1) def test_parse_crappy_broken_acceptlines2 accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, , pronto/1.00.00, sslvpn/1.00.00.00, */*" expect = ['image/gif', 'image/x-xbitmap', 'image/jpeg','image/pjpeg', 'application/x-shockwave-flash', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/msword', 'pronto/1.00.00', 'sslvpn/1.00.00.00', Mime::ALL ] assert_equal expect, Mime::Type.parse(accept).collect { |c| c.to_s } end def test_custom_type Mime::Type.register("image/gif", :gif) assert_nothing_raised do Mime::GIF assert_equal Mime::GIF, Mime::SET.last end ensure Mime.module_eval { remove_const :GIF if const_defined?(:GIF) } end def test_type_should_be_equal_to_symbol assert_equal Mime::HTML, 'application/xhtml+xml' assert_equal Mime::HTML, :html end def test_type_convenience_methods # Don't test Mime::ALL, since it Mime::ALL#html? == true types = Mime::SET.to_a.map(&:to_sym).uniq - [:all] # Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE types.delete_if { |type| !Mime.const_defined?(type.to_s.upcase) } types.each do |type| mime = Mime.const_get(type.to_s.upcase) assert mime.send("#{type}?"), "#{mime.inspect} is not #{type}?" invalid_types = types - [type] invalid_types.delete(:html) if Mime::Type.html_types.include?(type) invalid_types.each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" } end end def test_mime_all_is_html assert Mime::ALL.all?, "Mime::ALL is not all?" assert Mime::ALL.html?, "Mime::ALL is not html?" end def test_verifiable_mime_types all_types = Mime::SET.to_a.map(&:to_sym) all_types.uniq! # Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE all_types.delete_if { |type| !Mime.const_defined?(type.to_s.upcase) } verified, unverified = all_types.partition { |type| Mime::Type.browser_generated_types.include? type } assert verified.each { |type| assert Mime.const_get(type.to_s.upcase).verify_request?, "Verifiable Mime Type is not verified: #{type.inspect}" } assert unverified.each { |type| assert !Mime.const_get(type.to_s.upcase).verify_request?, "Nonverifiable Mime Type is verified: #{type.inspect}" } end def test_regexp_matcher assert Mime::JS =~ "text/javascript" assert Mime::JS =~ "application/javascript" assert Mime::JS !~ "text/html" assert !(Mime::JS !~ "text/javascript") assert !(Mime::JS !~ "application/javascript") assert Mime::HTML =~ 'application/xhtml+xml' end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/translation_test.rb
provider/vendor/rails/actionpack/test/controller/translation_test.rb
require 'abstract_unit' # class TranslatingController < ActionController::Base # end class TranslationControllerTest < Test::Unit::TestCase def setup @controller = ActionController::Base.new end def test_action_controller_base_responds_to_translate assert @controller.respond_to?(:translate) end def test_action_controller_base_responds_to_t assert @controller.respond_to?(:t) end def test_action_controller_base_responds_to_localize assert @controller.respond_to?(:localize) end def test_action_controller_base_responds_to_l assert @controller.respond_to?(:l) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/base_test.rb
provider/vendor/rails/actionpack/test/controller/base_test.rb
require 'abstract_unit' require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late # Provide some controller to run the tests on. module Submodule class ContainedEmptyController < ActionController::Base end class ContainedNonEmptyController < ActionController::Base def public_action render :nothing => true end hide_action :hidden_action def hidden_action raise "Noooo!" end def another_hidden_action end hide_action :another_hidden_action end class SubclassedController < ContainedNonEmptyController hide_action :public_action # Hiding it here should not affect the superclass. end end class EmptyController < ActionController::Base end class NonEmptyController < ActionController::Base def public_action end hide_action :hidden_action def hidden_action end end class MethodMissingController < ActionController::Base hide_action :shouldnt_be_called def shouldnt_be_called raise "NO WAY!" end protected def method_missing(selector) render :text => selector.to_s end end class DefaultUrlOptionsController < ActionController::Base def default_url_options_action end def default_url_options(options = nil) { :host => 'www.override.com', :action => 'new', :bacon => 'chunky' } end end class ControllerClassTests < Test::Unit::TestCase def test_controller_path assert_equal 'empty', EmptyController.controller_path assert_equal EmptyController.controller_path, EmptyController.new.controller_path assert_equal 'submodule/contained_empty', Submodule::ContainedEmptyController.controller_path assert_equal Submodule::ContainedEmptyController.controller_path, Submodule::ContainedEmptyController.new.controller_path end def test_controller_name assert_equal 'empty', EmptyController.controller_name assert_equal 'contained_empty', Submodule::ContainedEmptyController.controller_name end end class ControllerInstanceTests < Test::Unit::TestCase def setup @empty = EmptyController.new @contained = Submodule::ContainedEmptyController.new @empty_controllers = [@empty, @contained, Submodule::SubclassedController.new] @non_empty_controllers = [NonEmptyController.new, Submodule::ContainedNonEmptyController.new] end def test_action_methods @empty_controllers.each do |c| hide_mocha_methods_from_controller(c) assert_equal Set.new, c.__send__(:action_methods), "#{c.controller_path} should be empty!" end @non_empty_controllers.each do |c| hide_mocha_methods_from_controller(c) assert_equal Set.new(%w(public_action)), c.__send__(:action_methods), "#{c.controller_path} should not be empty!" end end protected # Mocha adds some public instance methods to Object that would be # considered actions, so explicitly hide_action them. def hide_mocha_methods_from_controller(controller) mocha_methods = [ :expects, :mocha, :mocha_inspect, :reset_mocha, :stubba_object, :stubba_method, :stubs, :verify, :__metaclass__, :__is_a__, :to_matcher, ] controller.class.__send__(:hide_action, *mocha_methods) end end class PerformActionTest < ActionController::TestCase class MockLogger attr_reader :logged def initialize @logged = [] end def method_missing(method, *args) @logged << args.first end end def use_controller(controller_class) @controller = controller_class.new # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". @controller.logger = Logger.new(nil) @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @request.host = "www.nextangle.com" rescue_action_in_public! end def test_get_on_priv_should_show_selector use_controller MethodMissingController get :shouldnt_be_called assert_response :success assert_equal 'shouldnt_be_called', @response.body end def test_method_missing_is_not_an_action_name use_controller MethodMissingController assert ! @controller.__send__(:action_methods).include?('method_missing') get :method_missing assert_response :success assert_equal 'method_missing', @response.body end def test_get_on_hidden_should_fail use_controller NonEmptyController get :hidden_action assert_response 404 get :another_hidden_action assert_response 404 end def test_namespaced_action_should_log_module_name use_controller Submodule::ContainedNonEmptyController @controller.logger = MockLogger.new get :public_action assert_match /Processing\sSubmodule::ContainedNonEmptyController#public_action/, @controller.logger.logged[1] end end class DefaultUrlOptionsTest < ActionController::TestCase tests DefaultUrlOptionsController def setup @request.host = 'www.example.com' rescue_action_in_public! end def test_default_url_options_are_used_if_set ActionController::Routing::Routes.draw do |map| map.default_url_options 'default_url_options', :controller => 'default_url_options' map.connect ':controller/:action/:id' end get :default_url_options_action # Make a dummy request so that the controller is initialized properly. assert_equal 'http://www.override.com/default_url_options/new?bacon=chunky', @controller.url_for(:controller => 'default_url_options') assert_equal 'http://www.override.com/default_url_options?bacon=chunky', @controller.send(:default_url_options_url) ensure ActionController::Routing::Routes.load! end end class EmptyUrlOptionsTest < ActionController::TestCase tests NonEmptyController def setup @request.host = 'www.example.com' rescue_action_in_public! end def test_ensure_url_for_works_as_expected_when_called_with_no_options_if_default_url_options_is_not_set get :public_action assert_equal "http://www.example.com/non_empty/public_action", @controller.url_for end end class EnsureNamedRoutesWorksTicket22BugTest < Test::Unit::TestCase def test_named_routes_still_work ActionController::Routing::Routes.draw do |map| map.resources :things end EmptyController.send :include, ActionController::UrlWriter assert_equal '/things', EmptyController.new.send(:things_path) ensure ActionController::Routing::Routes.load! end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/failsafe_test.rb
provider/vendor/rails/actionpack/test/controller/failsafe_test.rb
require 'abstract_unit' require 'stringio' require 'logger' class FailsafeTest < ActionController::TestCase FIXTURE_PUBLIC = "#{File.dirname(__FILE__)}/../fixtures/failsafe".freeze def setup @old_error_file_path = ActionController::Failsafe.error_file_path ActionController::Failsafe.error_file_path = FIXTURE_PUBLIC @app = mock @log_io = StringIO.new @logger = Logger.new(@log_io) @failsafe = ActionController::Failsafe.new(@app) @failsafe.stubs(:failsafe_logger).returns(@logger) end def teardown ActionController::Failsafe.error_file_path = @old_error_file_path end def app_will_raise_error! @app.expects(:call).then.raises(RuntimeError.new("Printer on fire")) end def test_calls_app_and_returns_its_return_value @app.expects(:call).returns([200, { "Content-Type" => "text/html" }, "ok"]) assert_equal [200, { "Content-Type" => "text/html" }, "ok"], @failsafe.call({}) end def test_writes_to_log_file_on_exception app_will_raise_error! @failsafe.call({}) assert_match /Printer on fire/, @log_io.string # Logs exception message. assert_match /failsafe_test\.rb/, @log_io.string # Logs backtrace. end def test_returns_500_internal_server_error_on_exception app_will_raise_error! response = @failsafe.call({}) assert_equal 3, response.size # It is a valid Rack response. assert_equal 500, response[0] # Status is 500. end def test_renders_error_page_file_with_erb app_will_raise_error! response = @failsafe.call({}) assert_equal 500, response[0] assert_equal "hello my world", response[2].join end def test_returns_a_default_message_if_erb_rendering_failed app_will_raise_error! @failsafe.expects(:render_template).raises(RuntimeError.new("Harddisk is crashing")) response = @failsafe.call({}) assert_equal 500, response[0] assert_match /500 Internal Server Error/, response[2].join assert_match %r(please read this web application's log file), response[2].join end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/html-scanner/text_node_test.rb
provider/vendor/rails/actionpack/test/controller/html-scanner/text_node_test.rb
require 'abstract_unit' class TextNodeTest < Test::Unit::TestCase def setup @node = HTML::Text.new(nil, 0, 0, "hello, howdy, aloha, annyeong") end def test_to_s assert_equal "hello, howdy, aloha, annyeong", @node.to_s end def test_find_string assert_equal @node, @node.find("hello, howdy, aloha, annyeong") assert_equal false, @node.find("bogus") end def test_find_regexp assert_equal @node, @node.find(/an+y/) assert_nil @node.find(/b/) end def test_find_hash assert_equal @node, @node.find(:content => /howdy/) assert_nil @node.find(:content => /^howdy$/) assert_equal false, @node.find(:content => "howdy") end def test_find_other assert_nil @node.find(:hello) end def test_match_string assert @node.match("hello, howdy, aloha, annyeong") assert_equal false, @node.match("bogus") end def test_match_regexp assert_not_nil @node, @node.match(/an+y/) assert_nil @node.match(/b/) end def test_match_hash assert_not_nil @node, @node.match(:content => "howdy") assert_nil @node.match(:content => /^howdy$/) end def test_match_other assert_nil @node.match(:hello) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/html-scanner/tokenizer_test.rb
provider/vendor/rails/actionpack/test/controller/html-scanner/tokenizer_test.rb
require 'abstract_unit' class TokenizerTest < Test::Unit::TestCase def test_blank tokenize "" assert_end end def test_space tokenize " " assert_next " " assert_end end def test_tag_simple_open tokenize "<tag>" assert_next "<tag>" assert_end end def test_tag_simple_self_closing tokenize "<tag />" assert_next "<tag />" assert_end end def test_tag_simple_closing tokenize "</tag>" assert_next "</tag>" end def test_tag_with_single_quoted_attribute tokenize %{<tag a='hello'>x} assert_next %{<tag a='hello'>} end def test_tag_with_single_quoted_attribute_with_escape tokenize %{<tag a='hello\\''>x} assert_next %{<tag a='hello\\''>} end def test_tag_with_double_quoted_attribute tokenize %{<tag a="hello">x} assert_next %{<tag a="hello">} end def test_tag_with_double_quoted_attribute_with_escape tokenize %{<tag a="hello\\"">x} assert_next %{<tag a="hello\\"">} end def test_tag_with_unquoted_attribute tokenize %{<tag a=hello>x} assert_next %{<tag a=hello>} end def test_tag_with_lt_char_in_attribute tokenize %{<tag a="x < y">x} assert_next %{<tag a="x < y">} end def test_tag_with_gt_char_in_attribute tokenize %{<tag a="x > y">x} assert_next %{<tag a="x > y">} end def test_doctype_tag tokenize %{<!DOCTYPE "blah" "blah" "blah">\n <html>} assert_next %{<!DOCTYPE "blah" "blah" "blah">} assert_next %{\n } assert_next %{<html>} end def test_cdata_tag tokenize %{<![CDATA[<br>]]>} assert_next %{<![CDATA[<br>]]>} assert_end end def test_unterminated_cdata_tag tokenize %{<content:encoded><![CDATA[ neverending...} assert_next %{<content:encoded>} assert_next %{<![CDATA[ neverending...} assert_end end def test_less_than_with_space tokenize %{original < hello > world} assert_next %{original } assert_next %{< hello > world} end def test_less_than_without_matching_greater_than tokenize %{hello <span onmouseover="gotcha"\n<b>foo</b>\nbar</span>} assert_next %{hello } assert_next %{<span onmouseover="gotcha"\n} assert_next %{<b>} assert_next %{foo} assert_next %{</b>} assert_next %{\nbar} assert_next %{</span>} assert_end end def test_unterminated_comment tokenize %{hello <!-- neverending...} assert_next %{hello } assert_next %{<!-- neverending...} assert_end end private def tokenize(text) @tokenizer = HTML::Tokenizer.new(text) end def assert_next(expected, message=nil) token = @tokenizer.next assert_equal expected, token, message end def assert_sequence(*expected) assert_next expected.shift until expected.empty? end def assert_end(message=nil) assert_nil @tokenizer.next, message end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/html-scanner/document_test.rb
provider/vendor/rails/actionpack/test/controller/html-scanner/document_test.rb
require 'abstract_unit' class DocumentTest < Test::Unit::TestCase def test_handle_doctype doc = nil assert_nothing_raised do doc = HTML::Document.new <<-HTML.strip <!DOCTYPE "blah" "blah" "blah"> <html> </html> HTML end assert_equal 3, doc.root.children.length assert_equal %{<!DOCTYPE "blah" "blah" "blah">}, doc.root.children[0].content assert_match %r{\s+}m, doc.root.children[1].content assert_equal "html", doc.root.children[2].name end def test_find_img doc = HTML::Document.new <<-HTML.strip <html> <body> <p><img src="hello.gif"></p> </body> </html> HTML assert doc.find(:tag=>"img", :attributes=>{"src"=>"hello.gif"}) end def test_find_all doc = HTML::Document.new <<-HTML.strip <html> <body> <p class="test"><img src="hello.gif"></p> <div class="foo"> <p class="test">something</p> <p>here is <em class="test">more</em></p> </div> </body> </html> HTML all = doc.find_all :attributes => { :class => "test" } assert_equal 3, all.length assert_equal [ "p", "p", "em" ], all.map { |n| n.name } end def test_find_with_text doc = HTML::Document.new <<-HTML.strip <html> <body> <p>Some text</p> </body> </html> HTML assert doc.find(:content => "Some text") assert doc.find(:tag => "p", :child => { :content => "Some text" }) assert doc.find(:tag => "p", :child => "Some text") assert doc.find(:tag => "p", :content => "Some text") end def test_parse_xml assert_nothing_raised { HTML::Document.new("<tags><tag/></tags>", true, true) } assert_nothing_raised { HTML::Document.new("<outer><link>something</link></outer>", true, true) } end def test_parse_document doc = HTML::Document.new(<<-HTML) <div> <h2>blah</h2> <table> </table> </div> HTML assert_not_nil doc.find(:tag => "div", :children => { :count => 1, :only => { :tag => "table" } }) end def test_tag_nesting_nothing_to_s doc = HTML::Document.new("<tag></tag>") assert_equal "<tag></tag>", doc.root.to_s end def test_tag_nesting_space_to_s doc = HTML::Document.new("<tag> </tag>") assert_equal "<tag> </tag>", doc.root.to_s end def test_tag_nesting_text_to_s doc = HTML::Document.new("<tag>text</tag>") assert_equal "<tag>text</tag>", doc.root.to_s end def test_tag_nesting_tag_to_s doc = HTML::Document.new("<tag><nested /></tag>") assert_equal "<tag><nested /></tag>", doc.root.to_s end def test_parse_cdata doc = HTML::Document.new(<<-HTML) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title><![CDATA[<br>]]></title> </head> <body> <p>this document has &lt;br&gt; for a title</p> </body> </html> HTML assert_nil doc.find(:tag => "title", :descendant => { :tag => "br" }) assert doc.find(:tag => "title", :child => "<br>") end def test_find_empty_tag doc = HTML::Document.new("<div id='map'></div>") assert_nil doc.find(:tag => "div", :attributes => { :id => "map" }, :content => /./) assert doc.find(:tag => "div", :attributes => { :id => "map" }, :content => /\A\Z/) assert doc.find(:tag => "div", :attributes => { :id => "map" }, :content => /^$/) assert doc.find(:tag => "div", :attributes => { :id => "map" }, :content => "") assert doc.find(:tag => "div", :attributes => { :id => "map" }, :content => nil) end def test_parse_invalid_document assert_nothing_raised do doc = HTML::Document.new("<html> <table> <tr> <td style=\"color: #FFFFFF; height: 17px; onclick=\"window.location.href='http://www.rmeinc.com/about_rme.aspx'\" style=\"cursor:pointer; height: 17px;\"; nowrap onclick=\"window.location.href='http://www.rmeinc.com/about_rme.aspx'\" onmouseout=\"this.bgColor='#0066cc'; this.style.color='#FFFFFF'\" onmouseover=\"this.bgColor='#ffffff'; this.style.color='#0033cc'\">About Us</td> </tr> </table> </html>") end end def test_invalid_document_raises_exception_when_strict assert_raise RuntimeError do doc = HTML::Document.new("<html> <table> <tr> <td style=\"color: #FFFFFF; height: 17px; onclick=\"window.location.href='http://www.rmeinc.com/about_rme.aspx'\" style=\"cursor:pointer; height: 17px;\"; nowrap onclick=\"window.location.href='http://www.rmeinc.com/about_rme.aspx'\" onmouseout=\"this.bgColor='#0066cc'; this.style.color='#FFFFFF'\" onmouseover=\"this.bgColor='#ffffff'; this.style.color='#0033cc'\">About Us</td> </tr> </table> </html>", true) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/actionpack/test/controller/html-scanner/tag_node_test.rb
provider/vendor/rails/actionpack/test/controller/html-scanner/tag_node_test.rb
require 'abstract_unit' class TagNodeTest < Test::Unit::TestCase def test_open_without_attributes node = tag("<tag>") assert_equal "tag", node.name assert_equal Hash.new, node.attributes assert_nil node.closing end def test_open_with_attributes node = tag("<TAG1 foo=hey_ho x:bar=\"blah blah\" BAZ='blah blah blah' >") assert_equal "tag1", node.name assert_equal "hey_ho", node["foo"] assert_equal "blah blah", node["x:bar"] assert_equal "blah blah blah", node["baz"] end def test_self_closing_without_attributes node = tag("<tag/>") assert_equal "tag", node.name assert_equal Hash.new, node.attributes assert_equal :self, node.closing end def test_self_closing_with_attributes node = tag("<tag a=b/>") assert_equal "tag", node.name assert_equal( { "a" => "b" }, node.attributes ) assert_equal :self, node.closing end def test_closing_without_attributes node = tag("</tag>") assert_equal "tag", node.name assert_nil node.attributes assert_equal :close, node.closing end def test_bracket_op_when_no_attributes node = tag("</tag>") assert_nil node["foo"] end def test_bracket_op_when_attributes node = tag("<tag a=b/>") assert_equal "b", node["a"] end def test_attributes_with_escaped_quotes node = tag("<tag a='b\\'c' b=\"bob \\\"float\\\"\">") assert_equal "b\\'c", node["a"] assert_equal "bob \\\"float\\\"", node["b"] end def test_to_s node = tag("<a b=c d='f' g=\"h 'i'\" />") assert_equal %(<a b='c' d='f' g='h \\'i\\'' />), node.to_s end def test_tag assert tag("<tag>").tag? end def test_match_tag_as_string assert tag("<tag>").match(:tag => "tag") assert !tag("<tag>").match(:tag => "b") end def test_match_tag_as_regexp assert tag("<tag>").match(:tag => /t.g/) assert !tag("<tag>").match(:tag => /t[bqs]g/) end def test_match_attributes_as_string t = tag("<tag a=something b=else />") assert t.match(:attributes => {"a" => "something"}) assert t.match(:attributes => {"b" => "else"}) end def test_match_attributes_as_regexp t = tag("<tag a=something b=else />") assert t.match(:attributes => {"a" => /^something$/}) assert t.match(:attributes => {"b" => /e.*e/}) assert t.match(:attributes => {"a" => /me..i/, "b" => /.ls.$/}) end def test_match_attributes_as_number t = tag("<tag a=15 b=3.1415 />") assert t.match(:attributes => {"a" => 15}) assert t.match(:attributes => {"b" => 3.1415}) assert t.match(:attributes => {"a" => 15, "b" => 3.1415}) end def test_match_attributes_exist t = tag("<tag a=15 b=3.1415 />") assert t.match(:attributes => {"a" => true}) assert t.match(:attributes => {"b" => true}) assert t.match(:attributes => {"a" => true, "b" => true}) end def test_match_attributes_not_exist t = tag("<tag a=15 b=3.1415 />") assert t.match(:attributes => {"c" => false}) assert t.match(:attributes => {"c" => nil}) assert t.match(:attributes => {"a" => true, "c" => false}) end def test_match_parent_success t = tag("<tag a=15 b='hello'>", tag("<foo k='value'>")) assert t.match(:parent => {:tag => "foo", :attributes => {"k" => /v.l/, "j" => false}}) end def test_match_parent_fail t = tag("<tag a=15 b='hello'>", tag("<foo k='value'>")) assert !t.match(:parent => {:tag => /kafka/}) end def test_match_child_success t = tag("<tag x:k='something'>") tag("<child v=john a=kelly>", t) tag("<sib m=vaughn v=james>", t) assert t.match(:child => { :tag => "sib", :attributes => {"v" => /j/}}) assert t.match(:child => { :attributes => {"a" => "kelly"}}) end def test_match_child_fail t = tag("<tag x:k='something'>") tag("<child v=john a=kelly>", t) tag("<sib m=vaughn v=james>", t) assert !t.match(:child => { :tag => "sib", :attributes => {"v" => /r/}}) assert !t.match(:child => { :attributes => {"v" => false}}) end def test_match_ancestor_success t = tag("<tag x:k='something'>", tag("<parent v=john a=kelly>", tag("<grandparent m=vaughn v=james>"))) assert t.match(:ancestor => {:tag => "parent", :attributes => {"a" => /ll/}}) assert t.match(:ancestor => {:attributes => {"m" => "vaughn"}}) end def test_match_ancestor_fail t = tag("<tag x:k='something'>", tag("<parent v=john a=kelly>", tag("<grandparent m=vaughn v=james>"))) assert !t.match(:ancestor => {:tag => /^parent/, :attributes => {"v" => /m/}}) assert !t.match(:ancestor => {:attributes => {"v" => false}}) end def test_match_descendant_success tag("<grandchild m=vaughn v=james>", tag("<child v=john a=kelly>", t = tag("<tag x:k='something'>"))) assert t.match(:descendant => {:tag => "child", :attributes => {"a" => /ll/}}) assert t.match(:descendant => {:attributes => {"m" => "vaughn"}}) end def test_match_descendant_fail tag("<grandchild m=vaughn v=james>", tag("<child v=john a=kelly>", t = tag("<tag x:k='something'>"))) assert !t.match(:descendant => {:tag => /^child/, :attributes => {"v" => /m/}}) assert !t.match(:descendant => {:attributes => {"v" => false}}) end def test_match_child_count t = tag("<tag x:k='something'>") tag("hello", t) tag("<child v=john a=kelly>", t) tag("<sib m=vaughn v=james>", t) assert t.match(:children => { :count => 2 }) assert t.match(:children => { :count => 2..4 }) assert t.match(:children => { :less_than => 4 }) assert t.match(:children => { :greater_than => 1 }) assert !t.match(:children => { :count => 3 }) end def test_conditions_as_strings t = tag("<tag x:k='something'>") assert t.match("tag" => "tag") assert t.match("attributes" => { "x:k" => "something" }) assert !t.match("tag" => "gat") assert !t.match("attributes" => { "x:j" => "something" }) end def test_attributes_as_symbols t = tag("<child v=john a=kelly>") assert t.match(:attributes => { :v => /oh/ }) assert t.match(:attributes => { :a => /ll/ }) end def test_match_sibling t = tag("<tag x:k='something'>") tag("hello", t) tag("<span a=b>", t) tag("world", t) m = tag("<span k=r>", t) tag("<span m=l>", t) assert m.match(:sibling => {:tag => "span", :attributes => {:a => true}}) assert m.match(:sibling => {:tag => "span", :attributes => {:m => true}}) assert !m.match(:sibling => {:tag => "span", :attributes => {:k => true}}) end def test_match_sibling_before t = tag("<tag x:k='something'>") tag("hello", t) tag("<span a=b>", t) tag("world", t) m = tag("<span k=r>", t) tag("<span m=l>", t) assert m.match(:before => {:tag => "span", :attributes => {:m => true}}) assert !m.match(:before => {:tag => "span", :attributes => {:a => true}}) assert !m.match(:before => {:tag => "span", :attributes => {:k => true}}) end def test_match_sibling_after t = tag("<tag x:k='something'>") tag("hello", t) tag("<span a=b>", t) tag("world", t) m = tag("<span k=r>", t) tag("<span m=l>", t) assert m.match(:after => {:tag => "span", :attributes => {:a => true}}) assert !m.match(:after => {:tag => "span", :attributes => {:m => true}}) assert !m.match(:after => {:tag => "span", :attributes => {:k => true}}) end def test_to_s t = tag("<b x='foo'>") tag("hello", t) tag("<hr />", t) assert_equal %(<b x="foo">hello<hr /></b>), t.to_s end private def tag(content, parent=nil) node = HTML::Node.parse(parent,0,0,content) parent.children << node if parent node end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false