Validate log level values, format unsupported level errors in a more human-friendly way

This commit is contained in:
Michael Klishin 2018-11-29 00:20:41 +08:00
parent 0e7608083b
commit df5db4ec1b
2 changed files with 19 additions and 5 deletions

View File

@ -17,13 +17,18 @@ defmodule RabbitMQ.CLI.Ctl.Commands.SetLogLevelCommand do
alias RabbitMQ.CLI.Core.Helpers
@behaviour RabbitMQ.CLI.CommandBehaviour
use RabbitMQ.CLI.DefaultOutput
@known_levels ["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency", "none"]
def merge_defaults(args, opts), do: {args, opts}
def validate([], _), do: {:validation_failure, :not_enough_args}
def validate([_|_] = args, _) when length(args) > 1, do: {:validation_failure, :too_many_args}
def validate([_], _), do: :ok
def validate([level], _) do
case Enum.member?(@known_levels, level) do
true -> :ok
false -> {:error, "level #{level} is not supported. Try one of debug, info, warning, error, none"}
end
end
use RabbitMQ.CLI.Core.RequiresRabbitAppRunning
@ -35,4 +40,10 @@ defmodule RabbitMQ.CLI.Ctl.Commands.SetLogLevelCommand do
def usage, do: "set_log_level <log_level>"
def banner([log_level], _), do: "Setting log level to \"#{log_level}\" ..."
def output({:error, {:invalid_log_level, level}}, _opts) do
{:error, RabbitMQ.CLI.Core.ExitCodes.exit_software,
"level #{level} is not supported. Try one of debug, info, warning, error, none"}
end
use RabbitMQ.CLI.DefaultOutput
end

View File

@ -11,8 +11,7 @@
## The Original Code is RabbitMQ.
##
## The Initial Developer of the Original Code is GoPivotal, Inc.
## Copyright (c) 2007-2016 Pivotal Software, Inc. All rights reserved.
## Copyright (c) 2007-2018 Pivotal Software, Inc. All rights reserved.
defmodule SetLogLevelCommandTest do
use ExUnit.Case, async: false
@ -27,10 +26,14 @@ defmodule SetLogLevelCommandTest do
opts: %{node: get_rabbit_hostname()}}
end
test "validate: with one argument succeeds", context do
test "validate: with a single known level succeeds", context do
assert @command.validate([context[:log_level]], context[:opts]) == :ok
end
test "validate: with a single unsupported level fails", context do
assert match?({:error, _}, @command.validate(["lolwut"], context[:opts]))
end
test "validate: with extra arguments returns an arg count error", context do
assert @command.validate([context[:log_level], "whoops"], context[:opts]) == {:validation_failure, :too_many_args}
end