aboutsummaryrefslogtreecommitdiffstats
path: root/railties/test/commands
diff options
context:
space:
mode:
Diffstat (limited to 'railties/test/commands')
-rw-r--r--railties/test/commands/console_test.rb124
-rw-r--r--railties/test/commands/credentials_test.rb102
-rw-r--r--railties/test/commands/dbconsole_test.rb307
-rw-r--r--railties/test/commands/dev_test.rb65
-rw-r--r--railties/test/commands/encrypted_test.rb106
-rw-r--r--railties/test/commands/initializers_test.rb32
-rw-r--r--railties/test/commands/notes_test.rb128
-rw-r--r--railties/test/commands/routes_test.rb217
-rw-r--r--railties/test/commands/secrets_test.rb77
-rw-r--r--railties/test/commands/server_test.rb260
10 files changed, 1227 insertions, 191 deletions
diff --git a/railties/test/commands/console_test.rb b/railties/test/commands/console_test.rb
index de0cf0ba9e..0b2fe204f8 100644
--- a/railties/test/commands/console_test.rb
+++ b/railties/test/commands/console_test.rb
@@ -1,6 +1,9 @@
-require 'abstract_unit'
-require 'env_helpers'
-require 'rails/commands/console'
+# frozen_string_literal: true
+
+require "abstract_unit"
+require "env_helpers"
+require "rails/command"
+require "rails/commands/console/console_command"
class Rails::ConsoleTest < ActiveSupport::TestCase
include EnvHelpers
@@ -17,37 +20,36 @@ class Rails::ConsoleTest < ActiveSupport::TestCase
def test_sandbox_option
console = Rails::Console.new(app, parse_arguments(["--sandbox"]))
- assert console.sandbox?
+ assert_predicate console, :sandbox?
end
def test_short_version_of_sandbox_option
console = Rails::Console.new(app, parse_arguments(["-s"]))
- assert console.sandbox?
+ assert_predicate console, :sandbox?
end
def test_no_options
console = Rails::Console.new(app, parse_arguments([]))
- assert !console.sandbox?
+ assert_not_predicate console, :sandbox?
end
def test_start
start
- assert app.console.started?
+ assert_predicate app.console, :started?
assert_match(/Loading \w+ environment \(Rails/, output)
end
def test_start_with_sandbox
start ["--sandbox"]
-
- assert app.console.started?
+ assert_predicate app.console, :started?
assert app.sandbox
assert_match(/Loading \w+ environment in sandbox \(Rails/, output)
end
def test_console_with_environment
- start ["-e production"]
+ start ["-e", "production"]
assert_match(/\sproduction\s/, output)
end
@@ -64,52 +66,73 @@ class Rails::ConsoleTest < ActiveSupport::TestCase
end
def test_default_environment_with_rails_env
- with_rails_env 'special-production' do
+ with_rails_env "special-production" do
start
assert_match(/\sspecial-production\s/, output)
end
end
def test_default_environment_with_rack_env
- with_rack_env 'production' do
+ with_rack_env "production" do
start
assert_match(/\sproduction\s/, output)
end
end
def test_e_option
- start ['-e', 'special-production']
+ start ["-e", "special-production"]
assert_match(/\sspecial-production\s/, output)
end
+ def test_e_option_is_properly_expanded
+ start ["-e", "prod"]
+ assert_match(/\sproduction\s/, output)
+ end
+
def test_environment_option
- start ['--environment=special-production']
+ start ["--environment=special-production"]
assert_match(/\sspecial-production\s/, output)
end
def test_rails_env_is_production_when_first_argument_is_p
- start ['p']
- assert_match(/\sproduction\s/, output)
+ assert_deprecated do
+ start ["p"]
+ assert_match(/\sproduction\s/, output)
+ end
end
def test_rails_env_is_test_when_first_argument_is_t
- start ['t']
- assert_match(/\stest\s/, output)
+ assert_deprecated do
+ start ["t"]
+ assert_match(/\stest\s/, output)
+ end
end
def test_rails_env_is_development_when_argument_is_d
- start ['d']
- assert_match(/\sdevelopment\s/, output)
+ assert_deprecated do
+ start ["d"]
+ assert_match(/\sdevelopment\s/, output)
+ end
end
def test_rails_env_is_dev_when_argument_is_dev_and_dev_env_is_present
- stubbed_console = Class.new(Rails::Console) do
- def available_environments
- ['dev']
+ Rails::Command::ConsoleCommand.class_eval do
+ alias_method :old_environments, :available_environments
+
+ define_method :available_environments do
+ ["dev"]
end
end
- options = stubbed_console.parse_arguments(['dev'])
- assert_match('dev', options[:environment])
+
+ assert_deprecated do
+ assert_match("dev", parse_arguments(["dev"])[:environment])
+ end
+ ensure
+ Rails::Command::ConsoleCommand.class_eval do
+ undef_method :available_environments
+ alias_method :available_environments, :old_environments
+ undef_method :old_environments
+ end
end
attr_reader :output
@@ -117,38 +140,37 @@ class Rails::ConsoleTest < ActiveSupport::TestCase
private
- def start(argv = [])
- rails_console = Rails::Console.new(app, parse_arguments(argv))
- @output = capture(:stdout) { rails_console.start }
- end
+ def start(argv = [])
+ rails_console = Rails::Console.new(app, parse_arguments(argv))
+ @output = capture(:stdout) { rails_console.start }
+ end
- def app
- @app ||= build_app(FakeConsole)
- end
+ def app
+ @app ||= build_app(FakeConsole)
+ end
- def build_app(console)
- mocked_console = Class.new do
- attr_reader :sandbox, :console
+ def build_app(console)
+ mocked_console = Class.new do
+ attr_accessor :sandbox
+ attr_reader :console
- def initialize(console)
- @console = console
- end
+ def initialize(console)
+ @console = console
+ end
- def config
- self
- end
-
- def sandbox=(arg)
- @sandbox = arg
- end
+ def config
+ self
+ end
- def load_console
+ def load_console
+ end
end
+ mocked_console.new(console)
end
- mocked_console.new(console)
- end
- def parse_arguments(args)
- Rails::Console.parse_arguments(args)
- end
+ def parse_arguments(args)
+ command = Rails::Command::ConsoleCommand.new([], args)
+ command.send(:extract_environment_option_from_argument)
+ command.options
+ end
end
diff --git a/railties/test/commands/credentials_test.rb b/railties/test/commands/credentials_test.rb
new file mode 100644
index 0000000000..7842b0db61
--- /dev/null
+++ b/railties/test/commands/credentials_test.rb
@@ -0,0 +1,102 @@
+# frozen_string_literal: true
+
+require "isolation/abstract_unit"
+require "env_helpers"
+require "rails/command"
+require "rails/commands/credentials/credentials_command"
+
+class Rails::Command::CredentialsCommandTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation, EnvHelpers
+
+ setup { build_app }
+
+ teardown { teardown_app }
+
+ test "edit without editor gives hint" do
+ run_edit_command(editor: "").tap do |output|
+ assert_match "No $EDITOR to open file in", output
+ assert_match "rails credentials:edit", output
+ end
+ end
+
+ test "edit credentials" do
+ # Run twice to ensure credentials can be reread after first edit pass.
+ 2.times do
+ assert_match(/access_key_id: 123/, run_edit_command)
+ end
+ end
+
+ test "edit command does not add master key to gitignore when already exist" do
+ run_edit_command
+
+ Dir.chdir(app_path) do
+ gitignore = File.read(".gitignore")
+ assert_equal 1, gitignore.scan(%r|config/master\.key|).length
+ end
+ end
+
+ test "edit command does not overwrite by default if credentials already exists" do
+ run_edit_command(editor: "eval echo api_key: abc >")
+ assert_match(/api_key: abc/, run_show_command)
+
+ run_edit_command
+ assert_match(/api_key: abc/, run_show_command)
+ end
+
+ test "edit command does not add master key when `RAILS_MASTER_KEY` env specified" do
+ Dir.chdir(app_path) do
+ key = IO.binread("config/master.key").strip
+ FileUtils.rm("config/master.key")
+
+ switch_env("RAILS_MASTER_KEY", key) do
+ assert_match(/access_key_id: 123/, run_edit_command)
+ assert_not File.exist?("config/master.key")
+ end
+ end
+ end
+
+ test "edit command modifies file specified by environment option" do
+ assert_match(/access_key_id: 123/, run_edit_command(environment: "production"))
+ Dir.chdir(app_path) do
+ assert File.exist?("config/credentials/production.key")
+ assert File.exist?("config/credentials/production.yml.enc")
+ end
+ end
+
+ test "show credentials" do
+ assert_match(/access_key_id: 123/, run_show_command)
+ end
+
+ test "show command raise error when require_master_key is specified and key does not exist" do
+ remove_file "config/master.key"
+ add_to_config "config.require_master_key = true"
+
+ assert_match(/Missing encryption key to decrypt file with/, run_show_command(allow_failure: true))
+ end
+
+ test "show command does not raise error when require_master_key is false and master key does not exist" do
+ remove_file "config/master.key"
+ add_to_config "config.require_master_key = false"
+
+ assert_match(/Missing 'config\/master\.key' to decrypt credentials/, run_show_command)
+ end
+
+ test "show command displays content specified by environment option" do
+ run_edit_command(environment: "production")
+
+ assert_match(/access_key_id: 123/, run_show_command(environment: "production"))
+ end
+
+ private
+ def run_edit_command(editor: "cat", environment: nil, **options)
+ switch_env("EDITOR", editor) do
+ args = environment ? ["--environment", environment] : []
+ rails "credentials:edit", args, **options
+ end
+ end
+
+ def run_show_command(environment: nil, **options)
+ args = environment ? ["--environment", environment] : []
+ rails "credentials:show", args, **options
+ end
+end
diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb
index 7950ed6aa7..5e3eca6585 100644
--- a/railties/test/commands/dbconsole_test.rb
+++ b/railties/test/commands/dbconsole_test.rb
@@ -1,30 +1,31 @@
-require 'abstract_unit'
-require 'minitest/mock'
-require 'rails/commands/dbconsole'
-
-class Rails::DBConsoleTest < ActiveSupport::TestCase
+# frozen_string_literal: true
+require "abstract_unit"
+require "minitest/mock"
+require "rails/command"
+require "rails/commands/dbconsole/dbconsole_command"
+class Rails::DBConsoleTest < ActiveSupport::TestCase
def setup
- Rails::DBConsole.const_set('APP_PATH', 'rails/all')
+ Rails::DBConsole.const_set("APP_PATH", "rails/all")
end
def teardown
- Rails::DBConsole.send(:remove_const, 'APP_PATH')
- %w[PGUSER PGHOST PGPORT PGPASSWORD DATABASE_URL].each{|key| ENV.delete(key)}
+ Rails::DBConsole.send(:remove_const, "APP_PATH")
+ %w[PGUSER PGHOST PGPORT PGPASSWORD DATABASE_URL].each { |key| ENV.delete(key) }
end
def test_config_with_db_config_only
config_sample = {
- "test"=> {
- "adapter"=> "sqlite3",
- "host"=> "localhost",
- "port"=> "9000",
- "database"=> "foo_test",
- "user"=> "foo",
- "password"=> "bar",
- "pool"=> "5",
- "timeout"=> "3000"
+ "test" => {
+ "adapter" => "sqlite3",
+ "host" => "localhost",
+ "port" => "9000",
+ "database" => "foo_test",
+ "user" => "foo",
+ "password" => "bar",
+ "pool" => "5",
+ "timeout" => "3000"
}
}
app_db_config(config_sample) do
@@ -41,7 +42,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
end
def test_config_with_database_url_only
- ENV['DATABASE_URL'] = 'postgresql://foo:bar@localhost:9000/foo_test?pool=5&timeout=3000'
+ ENV["DATABASE_URL"] = "postgresql://foo:bar@localhost:9000/foo_test?pool=5&timeout=3000"
expected = {
"adapter" => "postgresql",
"host" => "localhost",
@@ -60,7 +61,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
def test_config_choose_database_url_if_exists
host = "database-url-host.com"
- ENV['DATABASE_URL'] = "postgresql://foo:bar@#{host}:9000/foo_test?pool=5&timeout=3000"
+ ENV["DATABASE_URL"] = "postgresql://foo:bar@#{host}:9000/foo_test?pool=5&timeout=3000"
sample_config = {
"test" => {
"adapter" => "postgresql",
@@ -81,144 +82,197 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
def test_env
assert_equal "test", Rails::DBConsole.new.environment
- ENV['RAILS_ENV'] = nil
- ENV['RACK_ENV'] = nil
+ ENV["RAILS_ENV"] = nil
+ ENV["RACK_ENV"] = nil
Rails.stub(:respond_to?, false) do
assert_equal "development", Rails::DBConsole.new.environment
- ENV['RACK_ENV'] = "rack_env"
+ ENV["RACK_ENV"] = "rack_env"
assert_equal "rack_env", Rails::DBConsole.new.environment
- ENV['RAILS_ENV'] = "rails_env"
+ ENV["RAILS_ENV"] = "rails_env"
assert_equal "rails_env", Rails::DBConsole.new.environment
end
ensure
- ENV['RAILS_ENV'] = "test"
- ENV['RACK_ENV'] = nil
+ ENV["RAILS_ENV"] = "test"
+ ENV["RACK_ENV"] = nil
end
def test_rails_env_is_development_when_argument_is_dev
- Rails::DBConsole.stub(:available_environments, ['development', 'test']) do
- options = Rails::DBConsole.send(:parse_arguments, ['dev'])
- assert_match('development', options[:environment])
+ assert_deprecated do
+ stub_available_environments([ "development", "test" ]) do
+ assert_match("development", parse_arguments([ "dev" ])[:environment])
+ end
+ end
+ end
+
+ def test_rails_env_is_development_when_environment_option_is_dev
+ stub_available_environments([ "development", "test" ]) do
+ assert_match("development", parse_arguments([ "-e", "dev" ])[:environment])
end
end
def test_rails_env_is_dev_when_argument_is_dev_and_dev_env_is_present
- Rails::DBConsole.stub(:available_environments, ['dev']) do
- options = Rails::DBConsole.send(:parse_arguments, ['dev'])
- assert_match('dev', options[:environment])
+ assert_deprecated do
+ stub_available_environments([ "dev" ]) do
+ assert_match("dev", parse_arguments([ "dev" ])[:environment])
+ end
end
end
def test_mysql
- start(adapter: 'mysql', database: 'db')
- assert !aborted
- assert_equal [%w[mysql mysql5], 'db'], dbconsole.find_cmd_and_exec_args
+ start(adapter: "mysql2", database: "db")
+ assert_not aborted
+ assert_equal [%w[mysql mysql5], "db"], dbconsole.find_cmd_and_exec_args
end
def test_mysql_full
- start(adapter: 'mysql', database: 'db', host: 'locahost', port: 1234, socket: 'socket', username: 'user', password: 'qwerty', encoding: 'UTF-8')
- assert !aborted
- assert_equal [%w[mysql mysql5], '--host=locahost', '--port=1234', '--socket=socket', '--user=user', '--default-character-set=UTF-8', '-p', 'db'], dbconsole.find_cmd_and_exec_args
+ start(adapter: "mysql2", database: "db", host: "locahost", port: 1234, socket: "socket", username: "user", password: "qwerty", encoding: "UTF-8")
+ assert_not aborted
+ assert_equal [%w[mysql mysql5], "--host=locahost", "--port=1234", "--socket=socket", "--user=user", "--default-character-set=UTF-8", "-p", "db"], dbconsole.find_cmd_and_exec_args
end
def test_mysql_include_password
- start({adapter: 'mysql', database: 'db', username: 'user', password: 'qwerty'}, ['-p'])
- assert !aborted
- assert_equal [%w[mysql mysql5], '--user=user', '--password=qwerty', 'db'], dbconsole.find_cmd_and_exec_args
+ start({ adapter: "mysql2", database: "db", username: "user", password: "qwerty" }, ["-p"])
+ assert_not aborted
+ assert_equal [%w[mysql mysql5], "--user=user", "--password=qwerty", "db"], dbconsole.find_cmd_and_exec_args
end
def test_postgresql
- start(adapter: 'postgresql', database: 'db')
- assert !aborted
- assert_equal ['psql', 'db'], dbconsole.find_cmd_and_exec_args
+ start(adapter: "postgresql", database: "db")
+ assert_not aborted
+ assert_equal ["psql", "db"], dbconsole.find_cmd_and_exec_args
end
def test_postgresql_full
- start(adapter: 'postgresql', database: 'db', username: 'user', password: 'q1w2e3', host: 'host', port: 5432)
- assert !aborted
- assert_equal ['psql', 'db'], dbconsole.find_cmd_and_exec_args
- assert_equal 'user', ENV['PGUSER']
- assert_equal 'host', ENV['PGHOST']
- assert_equal '5432', ENV['PGPORT']
- assert_not_equal 'q1w2e3', ENV['PGPASSWORD']
+ start(adapter: "postgresql", database: "db", username: "user", password: "q1w2e3", host: "host", port: 5432)
+ assert_not aborted
+ assert_equal ["psql", "db"], dbconsole.find_cmd_and_exec_args
+ assert_equal "user", ENV["PGUSER"]
+ assert_equal "host", ENV["PGHOST"]
+ assert_equal "5432", ENV["PGPORT"]
+ assert_not_equal "q1w2e3", ENV["PGPASSWORD"]
end
def test_postgresql_include_password
- start({adapter: 'postgresql', database: 'db', username: 'user', password: 'q1w2e3'}, ['-p'])
- assert !aborted
- assert_equal ['psql', 'db'], dbconsole.find_cmd_and_exec_args
- assert_equal 'user', ENV['PGUSER']
- assert_equal 'q1w2e3', ENV['PGPASSWORD']
+ start({ adapter: "postgresql", database: "db", username: "user", password: "q1w2e3" }, ["-p"])
+ assert_not aborted
+ assert_equal ["psql", "db"], dbconsole.find_cmd_and_exec_args
+ assert_equal "user", ENV["PGUSER"]
+ assert_equal "q1w2e3", ENV["PGPASSWORD"]
end
def test_sqlite3
- start(adapter: 'sqlite3', database: 'db.sqlite3')
- assert !aborted
- assert_equal ['sqlite3', Rails.root.join('db.sqlite3').to_s], dbconsole.find_cmd_and_exec_args
+ start(adapter: "sqlite3", database: "db.sqlite3")
+ assert_not aborted
+ assert_equal ["sqlite3", Rails.root.join("db.sqlite3").to_s], dbconsole.find_cmd_and_exec_args
end
def test_sqlite3_mode
- start({adapter: 'sqlite3', database: 'db.sqlite3'}, ['--mode', 'html'])
- assert !aborted
- assert_equal ['sqlite3', '-html', Rails.root.join('db.sqlite3').to_s], dbconsole.find_cmd_and_exec_args
+ start({ adapter: "sqlite3", database: "db.sqlite3" }, ["--mode", "html"])
+ assert_not aborted
+ assert_equal ["sqlite3", "-html", Rails.root.join("db.sqlite3").to_s], dbconsole.find_cmd_and_exec_args
end
def test_sqlite3_header
- start({adapter: 'sqlite3', database: 'db.sqlite3'}, ['--header'])
- assert_equal ['sqlite3', '-header', Rails.root.join('db.sqlite3').to_s], dbconsole.find_cmd_and_exec_args
+ start({ adapter: "sqlite3", database: "db.sqlite3" }, ["--header"])
+ assert_equal ["sqlite3", "-header", Rails.root.join("db.sqlite3").to_s], dbconsole.find_cmd_and_exec_args
end
def test_sqlite3_db_absolute_path
- start(adapter: 'sqlite3', database: '/tmp/db.sqlite3')
- assert !aborted
- assert_equal ['sqlite3', '/tmp/db.sqlite3'], dbconsole.find_cmd_and_exec_args
+ start(adapter: "sqlite3", database: "/tmp/db.sqlite3")
+ assert_not aborted
+ assert_equal ["sqlite3", "/tmp/db.sqlite3"], dbconsole.find_cmd_and_exec_args
end
def test_sqlite3_db_without_defined_rails_root
Rails.stub(:respond_to?, false) do
- start(adapter: 'sqlite3', database: 'config/db.sqlite3')
- assert !aborted
- assert_equal ['sqlite3', Rails.root.join('../config/db.sqlite3').to_s], dbconsole.find_cmd_and_exec_args
+ start(adapter: "sqlite3", database: "config/db.sqlite3")
+ assert_not aborted
+ assert_equal ["sqlite3", Rails.root.join("../config/db.sqlite3").to_s], dbconsole.find_cmd_and_exec_args
end
end
def test_oracle
- start(adapter: 'oracle', database: 'db', username: 'user', password: 'secret')
- assert !aborted
- assert_equal ['sqlplus', 'user@db'], dbconsole.find_cmd_and_exec_args
+ start(adapter: "oracle", database: "db", username: "user", password: "secret")
+ assert_not aborted
+ assert_equal ["sqlplus", "user@db"], dbconsole.find_cmd_and_exec_args
end
def test_oracle_include_password
- start({adapter: 'oracle', database: 'db', username: 'user', password: 'secret'}, ['-p'])
- assert !aborted
- assert_equal ['sqlplus', 'user/secret@db'], dbconsole.find_cmd_and_exec_args
+ start({ adapter: "oracle", database: "db", username: "user", password: "secret" }, ["-p"])
+ assert_not aborted
+ assert_equal ["sqlplus", "user/secret@db"], dbconsole.find_cmd_and_exec_args
+ end
+
+ def test_sqlserver
+ start(adapter: "sqlserver", database: "db", username: "user", password: "secret", host: "localhost", port: 1433)
+ assert_not aborted
+ assert_equal ["sqsh", "-D", "db", "-U", "user", "-P", "secret", "-S", "localhost:1433"], dbconsole.find_cmd_and_exec_args
end
def test_unknown_command_line_client
- start(adapter: 'unknown', database: 'db')
+ start(adapter: "unknown", database: "db")
assert aborted
assert_match(/Unknown command-line client for db/, output)
end
+ def test_primary_is_automatically_picked_with_3_level_configuration
+ sample_config = {
+ "test" => {
+ "primary" => {
+ "adapter" => "postgresql"
+ }
+ }
+ }
+
+ app_db_config(sample_config) do
+ assert_equal "postgresql", Rails::DBConsole.new.config["adapter"]
+ end
+ end
+
+ def test_specifying_a_custom_connection_and_environment
+ stub_available_environments(["development"]) do
+ dbconsole = parse_arguments(["-c", "custom", "-e", "development"])
+
+ assert_equal "development", dbconsole[:environment]
+ assert_equal "custom", dbconsole.connection
+ end
+ end
+
+ def test_specifying_a_missing_connection
+ app_db_config({}) do
+ e = assert_raises(ActiveRecord::AdapterNotSpecified) do
+ Rails::Command.invoke(:dbconsole, ["-c", "i_do_not_exist"])
+ end
+
+ assert_includes e.message, "'i_do_not_exist' connection is not configured."
+ end
+ end
+
+ def test_specifying_a_missing_environment
+ app_db_config({}) do
+ e = assert_raises(ActiveRecord::AdapterNotSpecified) do
+ Rails::Command.invoke(:dbconsole)
+ end
+
+ assert_includes e.message, "'test' database is not configured."
+ end
+ end
+
def test_print_help_short
stdout = capture(:stdout) do
- start({}, ['-h'])
+ Rails::Command.invoke(:dbconsole, ["-h"])
end
- assert aborted
- assert_equal '', output
- assert_match(/Usage:.*dbconsole/, stdout)
+ assert_match(/rails dbconsole \[environment\]/, stdout)
end
def test_print_help_long
stdout = capture(:stdout) do
- start({}, ['--help'])
+ Rails::Command.invoke(:dbconsole, ["--help"])
end
- assert aborted
- assert_equal '', output
- assert_match(/Usage:.*dbconsole/, stdout)
+ assert_match(/rails dbconsole \[environment\]/, stdout)
end
attr_reader :aborted, :output
@@ -226,39 +280,76 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
private
- def app_db_config(results)
- Rails.application.config.stub(:database_configuration, results || {}) do
- yield
+ def app_db_config(results)
+ Rails.application.config.stub(:database_configuration, results || {}) do
+ yield
+ end
end
- end
- def dbconsole
- @dbconsole ||= Class.new(Rails::DBConsole) do
- attr_reader :find_cmd_and_exec_args
+ def make_dbconsole
+ Class.new(Rails::DBConsole) do
+ attr_reader :find_cmd_and_exec_args
- def find_cmd_and_exec(*args)
- @find_cmd_and_exec_args = args
+ def find_cmd_and_exec(*args)
+ @find_cmd_and_exec_args = args
+ end
end
- end.new(nil)
- end
+ end
+
+ attr_reader :dbconsole
- def start(config = {}, argv = [])
- dbconsole.stub(:config, config.stringify_keys) do
- dbconsole.stub(:arguments, argv) do
- capture_abort { dbconsole.start }
+ def start(config = {}, argv = [])
+ @dbconsole = make_dbconsole.new(parse_arguments(argv))
+ @dbconsole.stub(:config, config.stringify_keys) do
+ capture_abort { @dbconsole.start }
end
end
- end
- def capture_abort
- @aborted = false
- @output = capture(:stderr) do
- begin
- yield
- rescue SystemExit
- @aborted = true
+ def capture_abort
+ @aborted = false
+ @output = capture(:stderr) do
+ begin
+ yield
+ rescue SystemExit
+ @aborted = true
+ end
end
end
- end
+ def stub_available_environments(environments)
+ Rails::Command::DbconsoleCommand.class_eval do
+ alias_method :old_environments, :available_environments
+
+ define_method :available_environments do
+ environments
+ end
+ end
+
+ yield
+ ensure
+ Rails::Command::DbconsoleCommand.class_eval do
+ undef_method :available_environments
+ alias_method :available_environments, :old_environments
+ undef_method :old_environments
+ end
+ end
+
+ def parse_arguments(args)
+ Rails::Command::DbconsoleCommand.class_eval do
+ alias_method :old_perform, :perform
+ define_method(:perform) do
+ extract_environment_option_from_argument
+
+ options
+ end
+ end
+
+ Rails::Command.invoke(:dbconsole, args)
+ ensure
+ Rails::Command::DbconsoleCommand.class_eval do
+ undef_method :perform
+ alias_method :perform, :old_perform
+ undef_method :old_perform
+ end
+ end
end
diff --git a/railties/test/commands/dev_test.rb b/railties/test/commands/dev_test.rb
new file mode 100644
index 0000000000..ae8516fe9a
--- /dev/null
+++ b/railties/test/commands/dev_test.rb
@@ -0,0 +1,65 @@
+# frozen_string_literal: true
+
+require "isolation/abstract_unit"
+require "rails/command"
+
+class Rails::Command::DevTest < ActiveSupport::TestCase
+ setup :build_app
+ teardown :teardown_app
+
+ test "`rails dev:cache` creates both caching and restart file when restart file doesn't exist and dev caching is currently off" do
+ Dir.chdir(app_path) do
+ assert_not File.exist?("tmp/caching-dev.txt")
+ assert_not File.exist?("tmp/restart.txt")
+
+ assert_equal <<~OUTPUT, run_dev_cache_command
+ Development mode is now being cached.
+ OUTPUT
+
+ assert File.exist?("tmp/caching-dev.txt")
+ assert File.exist?("tmp/restart.txt")
+ end
+ end
+
+ test "`rails dev:cache` creates caching file and touches restart file when dev caching is currently off" do
+ Dir.chdir(app_path) do
+ app_file("tmp/restart.txt", "")
+
+ assert_not File.exist?("tmp/caching-dev.txt")
+ assert File.exist?("tmp/restart.txt")
+ restart_file_time_before = File.mtime("tmp/restart.txt")
+
+ assert_equal <<~OUTPUT, run_dev_cache_command
+ Development mode is now being cached.
+ OUTPUT
+
+ assert File.exist?("tmp/caching-dev.txt")
+ restart_file_time_after = File.mtime("tmp/restart.txt")
+ assert_operator restart_file_time_before, :<, restart_file_time_after
+ end
+ end
+
+ test "`rails dev:cache` removes caching file and touches restart file when dev caching is currently on" do
+ Dir.chdir(app_path) do
+ app_file("tmp/caching-dev.txt", "")
+ app_file("tmp/restart.txt", "")
+
+ assert File.exist?("tmp/caching-dev.txt")
+ assert File.exist?("tmp/restart.txt")
+ restart_file_time_before = File.mtime("tmp/restart.txt")
+
+ assert_equal <<~OUTPUT, run_dev_cache_command
+ Development mode is no longer being cached.
+ OUTPUT
+
+ assert_not File.exist?("tmp/caching-dev.txt")
+ restart_file_time_after = File.mtime("tmp/restart.txt")
+ assert_operator restart_file_time_before, :<, restart_file_time_after
+ end
+ end
+
+ private
+ def run_dev_cache_command
+ rails "dev:cache"
+ end
+end
diff --git a/railties/test/commands/encrypted_test.rb b/railties/test/commands/encrypted_test.rb
new file mode 100644
index 0000000000..8b608fe8c0
--- /dev/null
+++ b/railties/test/commands/encrypted_test.rb
@@ -0,0 +1,106 @@
+# frozen_string_literal: true
+
+require "isolation/abstract_unit"
+require "env_helpers"
+require "rails/command"
+require "rails/commands/encrypted/encrypted_command"
+
+class Rails::Command::EncryptedCommandTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation, EnvHelpers
+
+ setup :build_app
+ teardown :teardown_app
+
+ test "edit without editor gives hint" do
+ run_edit_command("config/tokens.yml.enc", editor: "").tap do |output|
+ assert_match "No $EDITOR to open file in", output
+ assert_match "rails encrypted:edit", output
+ end
+ end
+
+ test "edit encrypted file" do
+ # Run twice to ensure file can be reread after first edit pass.
+ 2.times do
+ assert_match(/access_key_id: 123/, run_edit_command("config/tokens.yml.enc"))
+ end
+ end
+
+ test "edit command does not add master key to gitignore when already exist" do
+ run_edit_command("config/tokens.yml.enc")
+
+ Dir.chdir(app_path) do
+ assert_match "/config/master.key", File.read(".gitignore")
+ end
+ end
+
+ test "edit command does not add master key when `RAILS_MASTER_KEY` env specified" do
+ Dir.chdir(app_path) do
+ key = IO.binread("config/master.key").strip
+ FileUtils.rm("config/master.key")
+
+ switch_env("RAILS_MASTER_KEY", key) do
+ run_edit_command("config/tokens.yml.enc")
+ assert_not File.exist?("config/master.key")
+ end
+ end
+ end
+
+ test "edit encrypts file with custom key" do
+ run_edit_command("config/tokens.yml.enc", key: "config/tokens.key")
+
+ Dir.chdir(app_path) do
+ assert File.exist?("config/tokens.yml.enc")
+ assert File.exist?("config/tokens.key")
+
+ assert_match "/config/tokens.key", File.read(".gitignore")
+ end
+
+ assert_match(/access_key_id: 123/, run_edit_command("config/tokens.yml.enc", key: "config/tokens.key"))
+ end
+
+ test "show encrypted file with custom key" do
+ run_edit_command("config/tokens.yml.enc", key: "config/tokens.key")
+
+ assert_match(/access_key_id: 123/, run_show_command("config/tokens.yml.enc", key: "config/tokens.key"))
+ end
+
+ test "show command raise error when require_master_key is specified and key does not exist" do
+ add_to_config "config.require_master_key = true"
+
+ assert_match(/Missing encryption key to decrypt file with/,
+ run_show_command("config/tokens.yml.enc", key: "unexist.key", allow_failure: true))
+ end
+
+ test "show command does not raise error when require_master_key is false and master key does not exist" do
+ remove_file "config/master.key"
+ add_to_config "config.require_master_key = false"
+
+ assert_match(/Missing 'config\/master\.key' to decrypt data/, run_show_command("config/tokens.yml.enc"))
+ end
+
+ test "won't corrupt encrypted file when passed wrong key" do
+ run_edit_command("config/tokens.yml.enc", key: "config/tokens.key")
+
+ assert_match "passed the wrong key",
+ run_edit_command("config/tokens.yml.enc", allow_failure: true)
+
+ assert_match(/access_key_id: 123/, run_show_command("config/tokens.yml.enc", key: "config/tokens.key"))
+ end
+
+ private
+ def run_edit_command(file, key: nil, editor: "cat", **options)
+ switch_env("EDITOR", editor) do
+ rails "encrypted:edit", prepare_args(file, key), **options
+ end
+ end
+
+ def run_show_command(file, key: nil, **options)
+ rails "encrypted:show", prepare_args(file, key), **options
+ end
+
+ def prepare_args(file, key)
+ args = [ file ]
+ args.push("--key", key) if key
+ args
+ end
+end
diff --git a/railties/test/commands/initializers_test.rb b/railties/test/commands/initializers_test.rb
new file mode 100644
index 0000000000..bdfbb3021c
--- /dev/null
+++ b/railties/test/commands/initializers_test.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+require "isolation/abstract_unit"
+require "rails/command"
+
+class Rails::Command::InitializersTest < ActiveSupport::TestCase
+ setup :build_app
+ teardown :teardown_app
+
+ test "`rails initializers` prints out defined initializers invoked by Rails" do
+ initial_output = run_initializers_command
+ initial_output_length = initial_output.split("\n").length
+
+ assert_operator initial_output_length, :>, 0
+ assert_not initial_output.include?("set_added_test_module")
+
+ add_to_config <<-RUBY
+ initializer(:set_added_test_module) { }
+ RUBY
+
+ final_output = run_initializers_command
+ final_output_length = final_output.split("\n").length
+
+ assert_equal 1, (final_output_length - initial_output_length)
+ assert final_output.include?("set_added_test_module")
+ end
+
+ private
+ def run_initializers_command
+ rails "initializers"
+ end
+end
diff --git a/railties/test/commands/notes_test.rb b/railties/test/commands/notes_test.rb
new file mode 100644
index 0000000000..147019e299
--- /dev/null
+++ b/railties/test/commands/notes_test.rb
@@ -0,0 +1,128 @@
+# frozen_string_literal: true
+
+require "isolation/abstract_unit"
+require "rails/command"
+require "rails/commands/notes/notes_command"
+
+class Rails::Command::NotesTest < ActiveSupport::TestCase
+ setup :build_app
+ teardown :teardown_app
+
+ test "`rails notes` displays results for default directories and default annotations with aligned line number and annotation tag" do
+ app_file "app/controllers/some_controller.rb", "# OPTIMIZE: note in app directory"
+ app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory"
+ app_file "db/some_seeds.rb", "# FIXME: note in db directory"
+ app_file "lib/some_file.rb", "# TODO: note in lib directory"
+ app_file "test/some_test.rb", "\n" * 100 + "# FIXME: note in test directory"
+
+ app_file "some_other_dir/blah.rb", "# TODO: note in some_other directory"
+
+ assert_equal <<~OUTPUT, run_notes_command
+ app/controllers/some_controller.rb:
+ * [ 1] [OPTIMIZE] note in app directory
+
+ config/initializers/some_initializer.rb:
+ * [ 1] [TODO] note in config directory
+
+ db/some_seeds.rb:
+ * [ 1] [FIXME] note in db directory
+
+ lib/some_file.rb:
+ * [ 1] [TODO] note in lib directory
+
+ test/some_test.rb:
+ * [101] [FIXME] note in test directory
+
+ OUTPUT
+ end
+
+ test "`rails notes` displays an empty string when no results were found" do
+ assert_equal "", run_notes_command
+ end
+
+ test "`rails notes --annotations` displays results for a single annotation without being prefixed by a tag" do
+ app_file "db/some_seeds.rb", "# FIXME: note in db directory"
+ app_file "test/some_test.rb", "# FIXME: note in test directory"
+
+ app_file "app/controllers/some_controller.rb", "# OPTIMIZE: note in app directory"
+ app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory"
+
+ assert_equal <<~OUTPUT, run_notes_command(["--annotations", "FIXME"])
+ db/some_seeds.rb:
+ * [1] note in db directory
+
+ test/some_test.rb:
+ * [1] note in test directory
+
+ OUTPUT
+ end
+
+ test "`rails notes --annotations` displays results for multiple annotations being prefixed by a tag" do
+ app_file "app/controllers/some_controller.rb", "# FOOBAR: note in app directory"
+ app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory"
+ app_file "lib/some_file.rb", "# TODO: note in lib directory"
+
+ app_file "test/some_test.rb", "# FIXME: note in test directory"
+
+ assert_equal <<~OUTPUT, run_notes_command(["--annotations", "FOOBAR", "TODO"])
+ app/controllers/some_controller.rb:
+ * [1] [FOOBAR] note in app directory
+
+ config/initializers/some_initializer.rb:
+ * [1] [TODO] note in config directory
+
+ lib/some_file.rb:
+ * [1] [TODO] note in lib directory
+
+ OUTPUT
+ end
+
+ test "displays results from additional directories added to the default directories from a config file" do
+ app_file "db/some_seeds.rb", "# FIXME: note in db directory"
+ app_file "lib/some_file.rb", "# TODO: note in lib directory"
+ app_file "spec/spec_helper.rb", "# TODO: note in spec"
+ app_file "spec/models/user_spec.rb", "# TODO: note in model spec"
+
+ add_to_config "config.annotations.register_directories \"spec\""
+
+ assert_equal <<~OUTPUT, run_notes_command
+ db/some_seeds.rb:
+ * [1] [FIXME] note in db directory
+
+ lib/some_file.rb:
+ * [1] [TODO] note in lib directory
+
+ spec/models/user_spec.rb:
+ * [1] [TODO] note in model spec
+
+ spec/spec_helper.rb:
+ * [1] [TODO] note in spec
+
+ OUTPUT
+ end
+
+ test "displays results from additional file extensions added to the default extensions from a config file" do
+ add_to_config "config.assets.precompile = []"
+ add_to_config %q{ config.annotations.register_extensions("scss", "sass") { |annotation| /\/\/\s*(#{annotation}):?\s*(.*)$/ } }
+ app_file "db/some_seeds.rb", "# FIXME: note in db directory"
+ app_file "app/assets/stylesheets/application.css.scss", "// TODO: note in scss"
+ app_file "app/assets/stylesheets/application.css.sass", "// TODO: note in sass"
+
+ assert_equal <<~OUTPUT, run_notes_command
+ app/assets/stylesheets/application.css.sass:
+ * [1] [TODO] note in sass
+
+ app/assets/stylesheets/application.css.scss:
+ * [1] [TODO] note in scss
+
+ db/some_seeds.rb:
+ * [1] [FIXME] note in db directory
+
+ OUTPUT
+ end
+
+ private
+ def run_notes_command(args = [])
+ rails "notes", args
+ end
+end
diff --git a/railties/test/commands/routes_test.rb b/railties/test/commands/routes_test.rb
new file mode 100644
index 0000000000..693e532c5b
--- /dev/null
+++ b/railties/test/commands/routes_test.rb
@@ -0,0 +1,217 @@
+# frozen_string_literal: true
+
+require "isolation/abstract_unit"
+require "rails/command"
+require "rails/commands/routes/routes_command"
+require "io/console/size"
+
+class Rails::Command::RoutesTest < ActiveSupport::TestCase
+ setup :build_app
+ teardown :teardown_app
+
+ test "singular resource output in rails routes" do
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ resource :post
+ resource :user_permission
+ end
+ RUBY
+
+ expected_post_output = [" Prefix Verb URI Pattern Controller#Action",
+ " new_post GET /post/new(.:format) posts#new",
+ "edit_post GET /post/edit(.:format) posts#edit",
+ " post GET /post(.:format) posts#show",
+ " PATCH /post(.:format) posts#update",
+ " PUT /post(.:format) posts#update",
+ " DELETE /post(.:format) posts#destroy",
+ " POST /post(.:format) posts#create\n"].join("\n")
+
+ output = run_routes_command(["-c", "PostController"])
+ assert_equal expected_post_output, output
+
+ expected_perm_output = [" Prefix Verb URI Pattern Controller#Action",
+ " new_user_permission GET /user_permission/new(.:format) user_permissions#new",
+ "edit_user_permission GET /user_permission/edit(.:format) user_permissions#edit",
+ " user_permission GET /user_permission(.:format) user_permissions#show",
+ " PATCH /user_permission(.:format) user_permissions#update",
+ " PUT /user_permission(.:format) user_permissions#update",
+ " DELETE /user_permission(.:format) user_permissions#destroy",
+ " POST /user_permission(.:format) user_permissions#create\n"].join("\n")
+
+ output = run_routes_command(["-c", "UserPermissionController"])
+ assert_equal expected_perm_output, output
+ end
+
+ test "rails routes with global search key" do
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ get '/cart', to: 'cart#show'
+ post '/cart', to: 'cart#create'
+ get '/basketballs', to: 'basketball#index'
+ end
+ RUBY
+
+ output = run_routes_command(["-g", "show"])
+ assert_equal <<~MESSAGE, output
+ Prefix Verb URI Pattern Controller#Action
+ cart GET /cart(.:format) cart#show
+ rails_service_blob GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs#show
+ rails_blob_representation GET /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
+ rails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#show
+ MESSAGE
+
+ output = run_routes_command(["-g", "POST"])
+ assert_equal <<~MESSAGE, output
+ Prefix Verb URI Pattern Controller#Action
+ POST /cart(.:format) cart#create
+ rails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create
+ MESSAGE
+
+ output = run_routes_command(["-g", "basketballs"])
+ assert_equal " Prefix Verb URI Pattern Controller#Action\n" \
+ "basketballs GET /basketballs(.:format) basketball#index\n", output
+ end
+
+ test "rails routes with controller search key" do
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ get '/cart', to: 'cart#show'
+ get '/basketball', to: 'basketball#index'
+ get '/user_permission', to: 'user_permission#index'
+ end
+ RUBY
+
+ expected_cart_output = "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n"
+ output = run_routes_command(["-c", "cart"])
+ assert_equal expected_cart_output, output
+
+ output = run_routes_command(["-c", "Cart"])
+ assert_equal expected_cart_output, output
+
+ output = run_routes_command(["-c", "CartController"])
+ assert_equal expected_cart_output, output
+
+ expected_perm_output = [" Prefix Verb URI Pattern Controller#Action",
+ "user_permission GET /user_permission(.:format) user_permission#index\n"].join("\n")
+ output = run_routes_command(["-c", "user_permission"])
+ assert_equal expected_perm_output, output
+
+ output = run_routes_command(["-c", "UserPermission"])
+ assert_equal expected_perm_output, output
+
+ output = run_routes_command(["-c", "UserPermissionController"])
+ assert_equal expected_perm_output, output
+ end
+
+ test "rails routes with namespaced controller search key" do
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ namespace :admin do
+ resource :post
+ resource :user_permission
+ end
+ end
+ RUBY
+
+ expected_post_output = [" Prefix Verb URI Pattern Controller#Action",
+ " new_admin_post GET /admin/post/new(.:format) admin/posts#new",
+ "edit_admin_post GET /admin/post/edit(.:format) admin/posts#edit",
+ " admin_post GET /admin/post(.:format) admin/posts#show",
+ " PATCH /admin/post(.:format) admin/posts#update",
+ " PUT /admin/post(.:format) admin/posts#update",
+ " DELETE /admin/post(.:format) admin/posts#destroy",
+ " POST /admin/post(.:format) admin/posts#create\n"].join("\n")
+
+ output = run_routes_command(["-c", "Admin::PostController"])
+ assert_equal expected_post_output, output
+
+ output = run_routes_command(["-c", "PostController"])
+ assert_equal expected_post_output, output
+
+ expected_perm_output = [" Prefix Verb URI Pattern Controller#Action",
+ " new_admin_user_permission GET /admin/user_permission/new(.:format) admin/user_permissions#new",
+ "edit_admin_user_permission GET /admin/user_permission/edit(.:format) admin/user_permissions#edit",
+ " admin_user_permission GET /admin/user_permission(.:format) admin/user_permissions#show",
+ " PATCH /admin/user_permission(.:format) admin/user_permissions#update",
+ " PUT /admin/user_permission(.:format) admin/user_permissions#update",
+ " DELETE /admin/user_permission(.:format) admin/user_permissions#destroy",
+ " POST /admin/user_permission(.:format) admin/user_permissions#create\n"].join("\n")
+
+ output = run_routes_command(["-c", "Admin::UserPermissionController"])
+ assert_equal expected_perm_output, output
+
+ output = run_routes_command(["-c", "UserPermissionController"])
+ assert_equal expected_perm_output, output
+ end
+
+ test "rails routes displays message when no routes are defined" do
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ end
+ RUBY
+
+ assert_equal <<~MESSAGE, run_routes_command
+ Prefix Verb URI Pattern Controller#Action
+ rails_service_blob GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs#show
+ rails_blob_representation GET /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
+ rails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#show
+ update_rails_disk_service PUT /rails/active_storage/disk/:encoded_token(.:format) active_storage/disk#update
+ rails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create
+ MESSAGE
+ end
+
+ test "rails routes with expanded option" do
+ begin
+ previous_console_winsize = IO.console.winsize
+ IO.console.winsize = [0, 27]
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ get '/cart', to: 'cart#show'
+ end
+ RUBY
+
+ output = run_routes_command(["--expanded"])
+
+ assert_equal <<~MESSAGE, output
+ --[ Route 1 ]--------------
+ Prefix | cart
+ Verb | GET
+ URI | /cart(.:format)
+ Controller#Action | cart#show
+ --[ Route 2 ]--------------
+ Prefix | rails_service_blob
+ Verb | GET
+ URI | /rails/active_storage/blobs/:signed_id/*filename(.:format)
+ Controller#Action | active_storage/blobs#show
+ --[ Route 3 ]--------------
+ Prefix | rails_blob_representation
+ Verb | GET
+ URI | /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format)
+ Controller#Action | active_storage/representations#show
+ --[ Route 4 ]--------------
+ Prefix | rails_disk_service
+ Verb | GET
+ URI | /rails/active_storage/disk/:encoded_key/*filename(.:format)
+ Controller#Action | active_storage/disk#show
+ --[ Route 5 ]--------------
+ Prefix | update_rails_disk_service
+ Verb | PUT
+ URI | /rails/active_storage/disk/:encoded_token(.:format)
+ Controller#Action | active_storage/disk#update
+ --[ Route 6 ]--------------
+ Prefix | rails_direct_uploads
+ Verb | POST
+ URI | /rails/active_storage/direct_uploads(.:format)
+ Controller#Action | active_storage/direct_uploads#create
+ MESSAGE
+ ensure
+ IO.console.winsize = previous_console_winsize
+ end
+ end
+
+ private
+ def run_routes_command(args = [])
+ rails "routes", args
+ end
+end
diff --git a/railties/test/commands/secrets_test.rb b/railties/test/commands/secrets_test.rb
new file mode 100644
index 0000000000..6b9f284a0c
--- /dev/null
+++ b/railties/test/commands/secrets_test.rb
@@ -0,0 +1,77 @@
+# frozen_string_literal: true
+
+require "isolation/abstract_unit"
+require "env_helpers"
+require "rails/command"
+require "rails/commands/secrets/secrets_command"
+
+class Rails::Command::SecretsCommandTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation, EnvHelpers
+
+ setup :build_app
+ teardown :teardown_app
+
+ test "edit without editor gives hint" do
+ assert_match "No $EDITOR to open decrypted secrets in", run_edit_command(editor: "")
+ end
+
+ test "encrypted secrets are deprecated when using credentials" do
+ assert_match "Encrypted secrets is deprecated", run_setup_command
+ assert_equal 1, $?.exitstatus
+ assert_not File.exist?("config/secrets.yml.enc")
+ end
+
+ test "encrypted secrets are deprecated when running edit without setup" do
+ assert_match "Encrypted secrets is deprecated", run_setup_command
+ assert_equal 1, $?.exitstatus
+ assert_not File.exist?("config/secrets.yml.enc")
+ end
+
+ test "encrypted secrets are deprecated for 5.1 config/secrets.yml apps" do
+ Dir.chdir(app_path) do
+ FileUtils.rm("config/credentials.yml.enc")
+ FileUtils.touch("config/secrets.yml")
+
+ assert_match "Encrypted secrets is deprecated", run_setup_command
+ assert_equal 1, $?.exitstatus
+ assert_not File.exist?("config/secrets.yml.enc")
+ end
+ end
+
+ test "edit secrets" do
+ prevent_deprecation
+
+ # Run twice to ensure encrypted secrets can be reread after first edit pass.
+ 2.times do
+ assert_match(/external_api_key: 1466aac22e6a869134be3d09b9e89232fc2c2289/, run_edit_command)
+ end
+ end
+
+ test "show secrets" do
+ prevent_deprecation
+
+ assert_match(/external_api_key: 1466aac22e6a869134be3d09b9e89232fc2c2289/, run_show_command)
+ end
+
+ private
+ def prevent_deprecation
+ Dir.chdir(app_path) do
+ File.write("config/secrets.yml.key", "f731758c639da2604dfb6bf3d1025de8")
+ File.write("config/secrets.yml.enc", "sEB0mHxDbeP1/KdnMk00wyzPFACl9K6t0cZWn5/Mfx/YbTHvnI07vrneqHg9kaH3wOS7L6pIQteu1P077OtE4BSx/ZRc/sgQPHyWu/tXsrfHqnPNpayOF/XZqizE91JacSFItNMWpuPsp9ynbzz+7cGhoB1S4aPNIU6u0doMrzdngDbijsaAFJmsHIQh6t/QHoJx--8aMoE0PvUWmw1Iqz--ldFqnM/K0g9k17M8PKoN/Q==")
+ end
+ end
+
+ def run_edit_command(editor: "cat")
+ switch_env("EDITOR", editor) do
+ rails "secrets:edit", allow_failure: true
+ end
+ end
+
+ def run_show_command
+ rails "secrets:show", allow_failure: true
+ end
+
+ def run_setup_command
+ rails "secrets:setup", allow_failure: true
+ end
+end
diff --git a/railties/test/commands/server_test.rb b/railties/test/commands/server_test.rb
index ba688f1e9e..e5b1da6ea4 100644
--- a/railties/test/commands/server_test.rb
+++ b/railties/test/commands/server_test.rb
@@ -1,88 +1,284 @@
-require 'abstract_unit'
-require 'env_helpers'
-require 'rails/commands/server'
+# frozen_string_literal: true
-class Rails::ServerTest < ActiveSupport::TestCase
+require "isolation/abstract_unit"
+require "env_helpers"
+require "rails/command"
+require "rails/commands/server/server_command"
+
+class Rails::Command::ServerCommandTest < ActiveSupport::TestCase
include EnvHelpers
def test_environment_with_server_option
- args = ["thin", "-e", "production"]
- options = Rails::Server::Options.new.parse!(args)
- assert_equal 'production', options[:environment]
- assert_equal 'thin', options[:server]
+ args = ["-u", "thin", "-e", "production"]
+ options = parse_arguments(args)
+ assert_equal "production", options[:environment]
+ assert_equal "thin", options[:server]
end
def test_environment_without_server_option
- args = ["-e", "production"]
- options = Rails::Server::Options.new.parse!(args)
- assert_equal 'production', options[:environment]
+ args = ["-e", "production"]
+ options = parse_arguments(args)
+ assert_equal "production", options[:environment]
assert_nil options[:server]
end
+ def test_explicit_using_option
+ args = ["-u", "thin"]
+ options = parse_arguments(args)
+ assert_equal "thin", options[:server]
+ end
+
+ def test_using_server_mistype
+ assert_match(/Could not find server "tin". Maybe you meant "thin"?/, run_command("--using", "tin"))
+ end
+
+ def test_using_positional_argument_deprecation
+ assert_match(/DEPRECATION WARNING/, run_command("tin"))
+ end
+
+ def test_using_known_server_that_isnt_in_the_gemfile
+ assert_match(/Could not load server "unicorn". Maybe you need to the add it to the Gemfile/, run_command("-u", "unicorn"))
+ end
+
+ def test_daemon_with_option
+ args = ["-d"]
+ options = parse_arguments(args)
+ assert_equal true, options[:daemonize]
+ end
+
+ def test_daemon_without_option
+ args = []
+ options = parse_arguments(args)
+ assert_equal false, options[:daemonize]
+ end
+
def test_server_option_without_environment
- args = ["thin"]
- options = Rails::Server::Options.new.parse!(args)
- assert_nil options[:environment]
- assert_equal 'thin', options[:server]
+ args = ["-u", "thin"]
+ with_rack_env nil do
+ with_rails_env nil do
+ options = parse_arguments(args)
+ assert_equal "development", options[:environment]
+ assert_equal "thin", options[:server]
+ end
+ end
end
def test_environment_with_rails_env
with_rack_env nil do
- with_rails_env 'production' do
- server = Rails::Server.new
- assert_equal 'production', server.options[:environment]
+ with_rails_env "production" do
+ options = parse_arguments
+ assert_equal "production", options[:environment]
end
end
end
def test_environment_with_rack_env
with_rails_env nil do
- with_rack_env 'production' do
- server = Rails::Server.new
- assert_equal 'production', server.options[:environment]
+ with_rack_env "production" do
+ options = parse_arguments
+ assert_equal "production", options[:environment]
end
end
end
+ def test_environment_with_port
+ switch_env "PORT", "1234" do
+ options = parse_arguments
+ assert_equal 1234, options[:Port]
+ end
+ end
+
+ def test_environment_with_host
+ switch_env "HOST", "1.2.3.4" do
+ assert_deprecated do
+ options = parse_arguments
+ assert_equal "1.2.3.4", options[:Host]
+ end
+ end
+ end
+
+ def test_environment_with_binding
+ switch_env "BINDING", "1.2.3.4" do
+ options = parse_arguments
+ assert_equal "1.2.3.4", options[:Host]
+ end
+ end
+
+ def test_caching_without_option
+ args = []
+ options = parse_arguments(args)
+ assert_nil options[:caching]
+ end
+
+ def test_caching_with_option
+ args = ["--dev-caching"]
+ options = parse_arguments(args)
+ assert_equal true, options[:caching]
+
+ args = ["--no-dev-caching"]
+ options = parse_arguments(args)
+ assert_equal false, options[:caching]
+ end
+
+ def test_early_hints_with_option
+ args = ["--early-hints"]
+ options = parse_arguments(args)
+ assert_equal true, options[:early_hints]
+ end
+
+ def test_early_hints_is_nil_by_default
+ args = []
+ options = parse_arguments(args)
+ assert_nil options[:early_hints]
+ end
+
def test_log_stdout
with_rack_env nil do
with_rails_env nil do
args = []
- options = Rails::Server::Options.new.parse!(args)
+ options = parse_arguments(args)
assert_equal true, options[:log_stdout]
args = ["-e", "development"]
- options = Rails::Server::Options.new.parse!(args)
+ options = parse_arguments(args)
assert_equal true, options[:log_stdout]
+ args = ["-e", "development", "-d"]
+ options = parse_arguments(args)
+ assert_equal false, options[:log_stdout]
+
args = ["-e", "production"]
- options = Rails::Server::Options.new.parse!(args)
+ options = parse_arguments(args)
assert_equal false, options[:log_stdout]
- with_rack_env 'development' do
+ args = ["-e", "development", "--no-log-to-stdout"]
+ options = parse_arguments(args)
+ assert_equal false, options[:log_stdout]
+
+ args = ["-e", "production", "--log-to-stdout"]
+ options = parse_arguments(args)
+ assert_equal true, options[:log_stdout]
+
+ with_rack_env "development" do
args = []
- options = Rails::Server::Options.new.parse!(args)
+ options = parse_arguments(args)
assert_equal true, options[:log_stdout]
end
- with_rack_env 'production' do
+ with_rack_env "production" do
args = []
- options = Rails::Server::Options.new.parse!(args)
+ options = parse_arguments(args)
assert_equal false, options[:log_stdout]
end
- with_rails_env 'development' do
+ with_rails_env "development" do
args = []
- options = Rails::Server::Options.new.parse!(args)
+ options = parse_arguments(args)
assert_equal true, options[:log_stdout]
end
- with_rails_env 'production' do
+ with_rails_env "production" do
args = []
- options = Rails::Server::Options.new.parse!(args)
+ options = parse_arguments(args)
assert_equal false, options[:log_stdout]
end
end
end
end
+
+ def test_host
+ with_rails_env "development" do
+ options = parse_arguments([])
+ assert_equal "localhost", options[:Host]
+ end
+
+ with_rails_env "production" do
+ options = parse_arguments([])
+ assert_equal "0.0.0.0", options[:Host]
+ end
+
+ with_rails_env "development" do
+ args = ["-b", "127.0.0.1"]
+ options = parse_arguments(args)
+ assert_equal "127.0.0.1", options[:Host]
+ end
+ end
+
+ def test_argument_precedence_over_environment_variable
+ switch_env "PORT", "1234" do
+ args = ["-p", "5678"]
+ options = parse_arguments(args)
+ assert_equal 5678, options[:Port]
+ end
+
+ switch_env "PORT", "1234" do
+ args = ["-p", "3000"]
+ options = parse_arguments(args)
+ assert_equal 3000, options[:Port]
+ end
+
+ switch_env "BINDING", "1.2.3.4" do
+ args = ["-b", "127.0.0.1"]
+ options = parse_arguments(args)
+ assert_equal "127.0.0.1", options[:Host]
+ end
+ end
+
+ def test_records_user_supplied_options
+ server_options = parse_arguments(["-p", 3001])
+ assert_equal [:Port], server_options[:user_supplied_options]
+
+ server_options = parse_arguments(["--port", 3001])
+ assert_equal [:Port], server_options[:user_supplied_options]
+
+ server_options = parse_arguments(["-p3001", "-C", "--binding", "127.0.0.1"])
+ assert_equal [:Port, :Host, :caching], server_options[:user_supplied_options]
+
+ server_options = parse_arguments(["--port=3001"])
+ assert_equal [:Port], server_options[:user_supplied_options]
+
+ switch_env "BINDING", "1.2.3.4" do
+ server_options = parse_arguments
+ assert_equal [:Host], server_options[:user_supplied_options]
+ end
+ end
+
+ def test_default_options
+ server = Rails::Server.new
+ old_default_options = server.default_options
+
+ Dir.chdir("..") do
+ assert_equal old_default_options, server.default_options
+ end
+ end
+
+ def test_restart_command_contains_customized_options
+ original_args = ARGV.dup
+ args = %w(-p 4567 -b 127.0.0.1 -c dummy_config.ru -d -e test -P tmp/server.pid -C)
+ ARGV.replace args
+
+ expected = "bin/rails server -p 4567 -b 127.0.0.1 -c dummy_config.ru -d -e test -P tmp/server.pid -C --restart"
+
+ assert_equal expected, parse_arguments(args)[:restart_cmd]
+ ensure
+ ARGV.replace original_args
+ end
+
+ def test_served_url
+ args = %w(-u webrick -b 127.0.0.1 -p 4567)
+ server = Rails::Server.new(parse_arguments(args))
+ assert_equal "http://127.0.0.1:4567", server.served_url
+ end
+
+ private
+ def run_command(*args)
+ build_app
+ rails "server", *args
+ ensure
+ teardown_app
+ end
+
+ def parse_arguments(args = [])
+ Rails::Command::ServerCommand.new([], args).server_options
+ end
end