From 991cf90267833885a88d613b9a04c9ee647ba9ac Mon Sep 17 00:00:00 2001 From: kojix2 <2xijok@gmail.com> Date: Wed, 20 Jan 2021 00:57:56 +0900 Subject: [PATCH] Add test for unrecognized command --- lib/youplot.rb | 2 ++ lib/youplot/command/parser.rb | 19 +++++++++++++------ test/youplot/command_test.rb | 8 ++++++++ 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/lib/youplot.rb b/lib/youplot.rb index aa26681..d7bcd80 100644 --- a/lib/youplot.rb +++ b/lib/youplot.rb @@ -8,8 +8,10 @@ require 'youplot/command' module YouPlot class << self attr_accessor :run_as_executable + def run_as_executable? @run_as_executable end end + @run_as_executable = false end diff --git a/lib/youplot/command/parser.rb b/lib/youplot/command/parser.rb index 3c9706b..1d454ab 100644 --- a/lib/youplot/command/parser.rb +++ b/lib/youplot/command/parser.rb @@ -7,6 +7,8 @@ require_relative 'plot_params' module YouPlot class Command class Parser + class Error < StandardError; end + attr_reader :command, :options, :params, :main_parser, :sub_parser @@ -193,7 +195,7 @@ module YouPlot when nil warn main_parser.banner warn "\n" - exit 1 + exit 1 if YouPlot.run_as_executable? when :barplot, :bar sub_parser_add_symbol @@ -263,8 +265,13 @@ module YouPlot end else - warn "uplot: unrecognized command '#{command}'" - exit 1 + error_message = "uplot: unrecognized command '#{command}'" + if YouPlot.run_as_executable? + warn error_message + exit 1 + else + raise Error, error_message + end end end @@ -273,16 +280,16 @@ module YouPlot create_main_parser.order!(argv) rescue OptionParser::ParseError => e warn "uplot: #{e.message}" - exit 1 + exit 1 if YouPlot.run_as_executable? end @command = argv.shift&.to_sym begin - create_sub_parser.parse!(argv) + create_sub_parser&.parse!(argv) rescue OptionParser::ParseError => e warn "uplot: #{e.message}" - exit 1 + exit 1 if YouPlot.run_as_executable? end end end diff --git a/test/youplot/command_test.rb b/test/youplot/command_test.rb index c69d6f2..ac07eba 100644 --- a/test/youplot/command_test.rb +++ b/test/youplot/command_test.rb @@ -138,4 +138,12 @@ class YouPlotCommandTest < Test::Unit::TestCase assert_equal '', @stderr_file.read assert_equal fixture('colors.txt'), @stdout_file.read end + + test :unrecognized_command do + assert_raise(YouPlot::Command::Parser::Error) do + YouPlot::Command.new(['abracadabra', '--hadley', '--wickham']).run + end + assert_equal '', @stderr_file.read + assert_equal '', @stdout_file.read + end end