def test_get_long_version(self): """ Application.get_long_version() returns the long version of the application """ application = Application("foo", "bar") self.assertEqual("<info>foo</info> version <comment>bar</comment>", application.get_long_version())
def test_help(self): """ Application.get_help() returns the help message of the application """ application = Application() self.assertEqual(self.open_fixture("application_gethelp.txt"), application.get_help())
def test_execute_hello_world_command_no_params(): application = Application() application.add(HelloWorldCommand()) command = application.find('greet') command_tester = CommandTester(command) command_tester.execute() assert "Hello" == command_tester.io.fetch_output().rstrip()
def test_combined_decorators(self): """ Combining decorators should register a command with arguments and options """ application = Application() @application.command("decorated_foo", description="Foo command") @application.argument("foo", description="Foo argument", required=True, is_list=True) @application.option("bar", "b", description="Bar option", value_required=True, is_list=True) def decorated_foo_code(i, o): """Foo Description""" o.writeln("called") self.assertTrue(application.has("decorated_foo")) command = application.get("decorated_foo") self.assertEqual(command._code, decorated_foo_code) self.assertEqual(command.get_description(), "Foo command") self.assertTrue("decorated_foo_code" in command.get_aliases()) argument = command.get_definition().get_argument("foo") self.assertEqual("Foo argument", argument.get_description()) self.assertTrue(argument.is_required()) self.assertTrue(argument.is_list()) option = command.get_definition().get_option("bar") self.assertEqual("b", option.get_shortcut()) self.assertEqual("Bar option", option.get_description()) self.assertTrue(option.is_value_required()) self.assertTrue(option.is_list())
def test_find_alternative_commands(self): application = Application() application.add(FooCommand()) application.add(Foo1Command()) application.add(Foo2Command()) command_name = 'Unknown command' try: application.find(command_name) self.fail('.find() raises an Exception if command does not exist') except Exception as e: self.assertEqual('Command "%s" is not defined.' % command_name, str(e)) command_name = 'bar1' try: application.find(command_name) self.fail('.find() raises an Exception if command does not exist') except Exception as e: self.assertRegexpMatches( str(e), 'Command "%s" is not defined.' % command_name) self.assertRegexpMatches( str(e), 'afoobar1', ) self.assertRegexpMatches( str(e), 'foo:bar1', ) self.assertNotRegex(str(e), 'foo:bar$')
def test_merge_application_definition(self): """ Command.merge_application_definition() merges command and application. """ application1 = Application() application1.get_definition().add_arguments([InputArgument('foo')]) application1.get_definition().add_options([InputOption('bar')]) command = TestCommand() command.set_application(application1) command.set_definition( InputDefinition([ InputArgument('bar'), InputOption('foo') ]) ) command.merge_application_definition() self.assertTrue(command.get_definition().has_argument('foo')) self.assertTrue(command.get_definition().has_option('foo')) self.assertTrue(command.get_definition().has_argument('bar')) self.assertTrue(command.get_definition().has_option('bar')) # It should not merge the definitions twice command.merge_application_definition() self.assertEqual(3, command.get_definition().get_argument_count())
def test_combined_decorators(self): """ Combining decorators should register a command with arguments and options """ application = Application() @application.command('decorated_foo', description='Foo command') @application.argument('foo', description='Foo argument', required=True, is_list=True) @application.option('bar', 'b', description='Bar option', value_required=True, is_list=True) def decorated_foo_code(i, o): """Foo Description""" o.writeln('called') self.assertTrue(application.has('decorated_foo')) command = application.get('decorated_foo') self.assertEqual(command._code, decorated_foo_code) self.assertEqual(command.get_description(), 'Foo command') self.assertTrue('decorated_foo_code' in command.get_aliases()) argument = command.get_definition().get_argument('foo') self.assertEqual('Foo argument', argument.get_description()) self.assertTrue(argument.is_required()) self.assertTrue(argument.is_list()) option = command.get_definition().get_option('bar') self.assertEqual('b', option.get_shortcut()) self.assertEqual('Bar option', option.get_description()) self.assertTrue(option.is_value_required()) self.assertTrue(option.is_list())
def test_silent_help(app: Application): app.catch_exceptions(False) tester = ApplicationTester(app) tester.execute("-h -q", decorated=False) assert tester.io.fetch_output() == ""
def test_render_exception(self): """ Application.render_exception() displays formatted exception. """ application = Application() application.set_auto_exit(False) application.get_terminal_width = self.mock().MagicMock(return_value=120) tester = ApplicationTester(application) tester.run([("command", "foo")], {"decorated": False}) self.assertEqual(self.open_fixture("application_renderexception1.txt"), tester.get_display()) tester.run([("command", "foo")], {"decorated": False, "verbosity": Output.VERBOSITY_VERBOSE}) self.assertRegex(tester.get_display(), "Exception trace") tester.run([("command", "list"), ("--foo", True)], {"decorated": False}) self.assertEqual(self.open_fixture("application_renderexception2.txt"), tester.get_display()) application.add(Foo3Command()) tester = ApplicationTester(application) tester.run([("command", "foo3:bar")], {"decorated": False}) self.assertEqual(self.open_fixture("application_renderexception3.txt"), tester.get_display()) tester = ApplicationTester(application) tester.run([("command", "foo3:bar")], {"decorated": True}) self.assertEqual(self.open_fixture("application_renderexception3decorated.txt"), tester.get_display()) application = Application() application.set_auto_exit(False) application.get_terminal_width = self.mock().MagicMock(return_value=31) tester = ApplicationTester(application) tester.run([("command", "foo")], {"decorated": False}) self.assertEqual(self.open_fixture("application_renderexception4.txt"), tester.get_display())
class TestApplicationTester(TestCase): def setUp(self): self.application = Application() self.application.set_auto_exit(False) self.application.register('foo')\ .add_argument('foo')\ .set_code(lambda c: c.line('foo')) self.tester = ApplicationTester(self.application) self.tester.run( [('command', 'foo'), ('foo', 'bar')], { 'interactive': False, 'decorated': False, 'verbosity': Output.VERBOSITY_VERBOSE }) def tearDown(self): self.application = None self.tester = None def test_run(self): """ ApplicationTester.run() behaves properly """ self.assertFalse(self.tester.get_input().is_interactive(), msg='.run() takes an interactive option.') self.assertFalse(self.tester.get_output().is_decorated(), msg='.run() takes a decorated option.') self.assertEqual(Output.VERBOSITY_VERBOSE, self.tester.get_output().get_verbosity(), msg='.run() takes an interactive option.') def test_get_input(self): """ ApplicationTester.get_input() behaves properly """ self.assertEqual( 'bar', self.tester.get_input().get_argument('foo'), msg='.get_input() returns the current input instance.') def test_get_output(self): """ ApplicationTester.get_output() behaves properly """ self.tester.get_output().get_stream().seek(0) self.assertEqual( 'foo\n', self.tester.get_output().get_stream().read().decode('utf-8'), msg='.get_output() returns the current output instance.') def test_get_display(self): """ ApplicationTester.get_display() behaves properly """ self.assertEqual( 'foo\n', self.tester.get_display(), msg='.get_display() returns the display of the last execution.')
def test_help(self): """ Application.get_help() returns the help message of the application """ application = Application() self.assertEqual(self.open_fixture('application_gethelp.txt'), application.get_help())
def test_get_long_version(self): """ Application.get_long_version() returns the long version of the application """ application = Application('foo', 'bar') self.assertEqual('foo <info>bar</info>', application.get_long_version())
def test_find_command_with_missing_namespace(self): """ Application.find() returns a command with missing namespace """ application = Application() application.add(Foo4Command()) self.assertTrue(isinstance(application.find('f::t'), Foo4Command))
def test_all(app: Application): commands = app.all() assert isinstance(commands["help"], Command) app.add(FooCommand()) assert len(app.all("foo")) == 1
def test_execute_namespace_command(): app = Application() app.add(FooBarCommand()) tester = CommandTester(app.find("foo bar")) assert 0 == tester.execute() assert 0 == tester.status_code assert "foo bar called\n" == tester.io.fetch_output()
def test_set_get_version(self): """ Application version accessors behave properly """ application = Application() application.set_version("bar") self.assertEqual("bar", application.get_version(), msg=".set_version() sets the version of the application")
def test_register(self): """ Application.register() registers a new command """ application = Application() command = application.register("foo") self.assertEqual("foo", command.get_name(), msg=".register() registers a new command")
def test_find_ambiguous_command(app: Application): app.add(FooCommand()) with pytest.raises( CommandNotFoundException, match=r'The command "foo b" does not exist\.\n\nDid you mean this\?\n foo bar', ): app.find("foo b")
def test_find_namespace_does_not_fail_on_deep_similar_namespaces(self): applicaton = Application() applicaton.get_namespaces = self.mock().MagicMock(return_value=['foo:sublong', 'bar:sub']) self.assertEqual( 'foo:sublong', applicaton.find_namespace('f:sub') )
def test_set_get_name(self): """ Application name accessors behave properly """ application = Application() application.set_name("foo") self.assertEqual("foo", application.get_name(), msg=".set_name() sets the name of the application")
def test_execute_for_application_command(self): application = Application() tester = CommandTester(application.get('help')) tester.execute([('command_name', 'list')]) self.assertRegex( tester.get_display(), 'list \[--raw\] \[namespace\]' )
def test_find_command_with_missing_namespace(self): """ Application.find() returns a command with missing namespace """ application = Application() application.add(Foo4Command()) self.assertTrue(isinstance(application.find("f::t"), Foo4Command))
class TestApplicationTester(TestCase): def setUp(self): self.application = Application() self.application.set_auto_exit(False) self.application.register('foo')\ .add_argument('foo')\ .set_code(lambda input_, output_: output_.writeln('foo')) self.tester = ApplicationTester(self.application) self.tester.run( [ ('command', 'foo'), ('foo', 'bar') ], { 'interactive': False, 'decorated': False, 'verbosity': Output.VERBOSITY_VERBOSE } ) def tearDown(self): self.application = None self.tester = None def test_run(self): """ ApplicationTester.run() behaves properly """ self.assertFalse(self.tester.get_input().is_interactive(), msg='.run() takes an interactive option.') self.assertFalse(self.tester.get_output().is_decorated(), msg='.run() takes a decorated option.') self.assertEqual(Output.VERBOSITY_VERBOSE, self.tester.get_output().get_verbosity(), msg='.run() takes an interactive option.') def test_get_input(self): """ ApplicationTester.get_input() behaves properly """ self.assertEqual('bar', self.tester.get_input().get_argument('foo'), msg='.get_input() returns the current input instance.') def test_get_output(self): """ ApplicationTester.get_output() behaves properly """ self.tester.get_output().get_stream().seek(0) self.assertEqual('foo\n', self.tester.get_output().get_stream().read().decode('utf-8'), msg='.get_output() returns the current output instance.') def test_get_display(self): """ ApplicationTester.get_display() behaves properly """ self.assertEqual('foo\n', self.tester.get_display(), msg='.get_display() returns the display of the last execution.')
def test_add_with_dictionary(self): """ Application.add() accepts a dictionary as argument. """ application = Application() foo = application.add(foo_commmand) self.assertTrue(isinstance(foo, Command)) self.assertEqual("foo:bar1", foo.get_name())
def test_add_with_dictionary(self): """ Application.add() accepts a dictionary as argument. """ application = Application() foo = application.add(foo_commmand) self.assertTrue(isinstance(foo, Command)) self.assertEqual('foo:bar1', foo.get_name())
def find_alternative_commands_with_an_alias(self): foo_command = FooCommand() foo_command.set_aliases(["foo2"]) application = Application() application.add(foo_command) result = application.find("foo") self.assertEqual(foo_command, result)
def test_set_get_version(self): """ Application version accessors behave properly """ application = Application() application.set_version('bar') self.assertEqual('bar', application.get_version(), msg='.set_version() sets the version of the application')
def test_register(self): """ Application.register() registers a new command """ application = Application() command = application.register('foo') self.assertEqual('foo', command.get_name(), msg='.register() registers a new command')
def find_alternative_commands_with_an_alias(self): foo_command = FooCommand() foo_command.set_aliases(['foo2']) application = Application() application.add(foo_command) result = application.find('foo') self.assertEqual(foo_command, result)
def test_run_return_exit_code_one_for_exception_code_zero(self): exception = OSError(0, "") application = Application() application.set_auto_exit(False) application.do_run = self.mock().MagicMock(side_effect=exception) exit_code = application.run(ListInput([]), NullOutput()) self.assertEqual(1, exit_code)
def test_find_ambiguous_command_hidden(app: Application): foo = FooCommand() foo.hidden = True app.add(foo) with pytest.raises( CommandNotFoundException, match=r'The command "foo b" does not exist\.$', ): app.find("foo b")
def test_set_get_name(self): """ Application name accessors behave properly """ application = Application() application.set_name('foo') self.assertEqual('foo', application.get_name(), msg='.set_name() sets the name of the application')
def test_find_unique_name_but_namespace_name(self): """ Application.find() should raise an error when command is missing """ application = Application() application.add(FooCommand()) application.add(Foo1Command()) application.add(Foo2Command()) self.assertRaisesRegexp(Exception, 'Command "foo1" is not defined', application.find, "foo1")
def test_find_namespace(self): """ Application.find_namespace() should return a namespace """ application = Application() application.add(FooCommand()) self.assertEqual( 'foo', application.find_namespace('foo'), msg='.find_namespace() returns the given namespace if it exists' ) self.assertEqual( 'foo', application.find_namespace('f'), msg='.find_namespace() finds a namespace given an abbreviation' ) application.add(Foo2Command()) self.assertEqual( 'foo', application.find_namespace('foo'), msg='.find_namespace() returns the given namespace if it exists' )
def test_find(self): """ Application.find() should return a command """ application = Application() application.add(FooCommand()) self.assertTrue( isinstance(application.find('foo:bar'), FooCommand), msg='.find() returns a command if its name exists' ) self.assertTrue( isinstance(application.find('h'), HelpCommand), msg='.find() returns a command if its name exists' ) self.assertTrue( isinstance(application.find('f:bar'), FooCommand), msg='.find() returns a command if the abbreviation for the namespace exists' ) self.assertTrue( isinstance(application.find('f:b'), FooCommand), msg='.find() returns a command if the abbreviation for the namespace and the command name exist' ) self.assertTrue( isinstance(application.find('a'), FooCommand), msg='.find() returns a command if the abbreviation exists for an alias' )
def test_find_alternative_exception_message_single(self): """ Application.find() raises an exception when an alternative has been found """ data = ["foo3:baR", "foO3:bar"] application = Application() application.add(Foo3Command()) for d in data: self.assertRaisesRegexp(Exception, "Did you mean this", application.find, d)
def test_terminal_dimensions(self): application = Application() original_dimensions = application.get_terminal_dimensions(StreamOutput(sys.stdout)) self.assertEqual(2, len(original_dimensions)) width = 80 if original_dimensions[0] == width: width = 100 application.set_terminal_dimensions(width, 80) self.assertEqual((width, 80), application.get_terminal_dimensions(StreamOutput(sys.stdout)))
def test_as_text(self): """ Application.as_text() returns a text representation of the application. """ application = Application() application.add(FooCommand()) self.ensure_static_command_help(application) self.assertEqual(self.open_fixture("application_astext1.txt"), application.as_text()) self.assertEqual(self.open_fixture("application_astext2.txt"), application.as_text("foo"))
def test_argument_decorator_order(self): application = Application() @application.command("decorated_foo", description="Foo command") @application.argument("foo", description="Foo argument", required=True) @application.argument("bar", description="Bar argument", required=True) def decorated_foo_code(i, o): """Foo Description""" o.writeln("called") command = application.get("decorated_foo") self.assertEqual(["bar", "foo"], list(map(lambda a: a.get_name(), command.get_definition().get_arguments())))
def test_silent_help(self): """ Silent help should return nothing """ application = Application() application.set_auto_exit(False) application.set_catch_exceptions(False) tester = ApplicationTester(application) tester.run([("-h", True), ("-q", True)], {"decorated": False}) self.assertEqual("", tester.get_display())
def test_find_alternative_exception_message_single(self): """ Application.find() raises an exception when an alternative has been found """ data = ['foo3:baR', 'foO3:bar'] application = Application() application.add(Foo3Command()) for d in data: self.assertRaisesRegexp(Exception, 'Did you mean this', application.find, d)
def test_execute(): config = { "scripts": { "e": ["python", "-c", "print(1)"], } } application = Application() application.add(CustomCommand(config)) command = application.find("do") command_tester = CommandTester(command) command_tester.execute("e")
def setUp(self): self.application = Application() self.application.set_auto_exit(False) self.application.register('foo')\ .add_argument('foo')\ .set_code(lambda c: c.line('foo')) self.tester = ApplicationTester(self.application) self.tester.run( [('command', 'foo'), ('foo', 'bar')], { 'interactive': False, 'decorated': False, 'verbosity': Output.VERBOSITY_VERBOSE })
def test_find(self): """ Application.find() should return a command """ application = Application() application.add(FooCommand()) self.assertTrue( isinstance(application.find("foo:bar"), FooCommand), msg=".find() returns a command if its name exists" ) self.assertTrue( isinstance(application.find("h"), HelpCommand), msg=".find() returns a command if its name exists" ) self.assertTrue( isinstance(application.find("f:bar"), FooCommand), msg=".find() returns a command if the abbreviation for the namespace exists", ) self.assertTrue( isinstance(application.find("f:b"), FooCommand), msg=".find() returns a command if the abbreviation for the namespace and the command name exist", ) self.assertTrue( isinstance(application.find("a"), FooCommand), msg=".find() returns a command if the abbreviation exists for an alias", )
def test_all(self): """ Application.get_all() returns all comands of the application """ application = Application() commands = application.all() self.assertEqual( "HelpCommand", commands["help"].__class__.__name__, msg=".all() returns the registered commands" ) application.add(FooCommand()) self.assertEqual(1, len(application.all("foo")), msg=".all() take a namespace as first argument")
def test_adding_single_helper_set_overwrites_default_values(self): application = Application() application.set_auto_exit(False) application.set_catch_exceptions(False) application.set_helper_set(HelperSet([FormatterHelper()])) helper_set = application.get_helper_set() self.assertTrue(helper_set.has('formatter')) self.assertFalse(helper_set.has('question'))
def test_constructor(self): """ Application.__init__() behaves properly """ application = Application('foo', 'bar') self.assertEqual('foo', application.get_name(), msg='__init__() takes the application name as its first argument') self.assertEqual('bar', application.get_version(), msg='__init__() takes the application version as its second argument') self.assertEqual(['help', 'list'].sort(), list(application.all().keys()).sort(), msg='__init__() registered the help and list commands by default')
def test_argument_decorator_order(self): application = Application() @application.command('decorated_foo', description='Foo command') @application.argument('foo', description='Foo argument', required=True) @application.argument('bar', description='Bar argument', required=True) def decorated_foo_code(i, o): """Foo Description""" o.writeln('called') command = application.get('decorated_foo') self.assertEqual( ['bar', 'foo'], list(map(lambda a: a.get_name(), command.get_definition().get_arguments())) )
def test_find_command_equal_namesapce(self): """ Application.find() returns a command if it has a namespace with the same name """ application = Application() application.add(Foo3Command()) application.add(Foo4Command()) self.assertTrue( isinstance(application.find("foo3:bar"), Foo3Command), msg=".find() returns the good command even if a namespace has same name", ) self.assertTrue( isinstance(application.find("foo3:bar:toh"), Foo4Command), msg=".find() returns a command even if its namespace equals another command name", )
def test_command_decorator(self): """ @Application.command decorator should register a command """ application = Application() @application.command('decorated_foo', description='Foo') def decorated_foo_code(i, o): o.writeln('called') self.assertTrue(application.has('decorated_foo')) command = application.get('decorated_foo') self.assertEqual(command._code, decorated_foo_code) self.assertEqual(command.get_description(), 'Foo') self.assertTrue('decorated_foo_code' in command.get_aliases())
def test_command_decorator(self): """ @Application.command decorator should register a command """ application = Application() @application.command("decorated_foo", description="Foo") def decorated_foo_code(i, o): o.writeln("called") self.assertTrue(application.has("decorated_foo")) command = application.get("decorated_foo") self.assertEqual(command._code, decorated_foo_code) self.assertEqual(command.get_description(), "Foo") self.assertTrue("decorated_foo_code" in command.get_aliases())
def test_execute_for_command_alias(self): command = HelpCommand() command.set_application(Application()) tester = CommandTester(command) tester.execute([('command_name', 'li')], {'decorated': False}) self.assertIn('list [options] [--] [<namespace>]', tester.get_display())
def test_find_with_ambiguous_abbreviations(self): """ Application.find() should raise an error when there is ambiguosity """ data = [ ["f", 'Command "f" is not defined\.'], ["a", 'Command "a" is ambiguous \(afoobar, afoobar1 and 1 more\)\.'], ["foo:b", 'Command "foo:b" is ambiguous \(foo1:bar, foo:bar and 1 more\)\.'], ] application = Application() application.add(FooCommand()) application.add(Foo1Command()) application.add(Foo2Command()) for d in data: self.assertRaisesRegexp(Exception, d[1], application.find, d[0])
def test_get_invalid_command(self): """ Application.get() should raise an exception when command does not exist """ application = Application() self.assertRaisesRegexp(Exception, 'The command "foofoo" does not exist', application.get, 'foofoo')
def test_execute(self): """ ListCommand.execute() behaves properly """ application = Application() command = application.get('list') command_tester = CommandTester(command) command_tester.execute([('command', command.get_name())], {'decorated': False}) self.assertTrue(re.match('(?s).*help Displays help for a command.*', command_tester.get_display()) is not None, msg='.execute() returns a list of available commands') command_tester.execute([('command', command.get_name()), ('--raw', True)]) output = """help Displays help for a command list Lists commands""" self.assertEqual(output, command_tester.get_display())
def test_set_application(self): """ Command.set_application() sets the current application """ application = Application() command = SomeCommand() command.set_application(application) self.assertEqual(application, command.get_application(), msg='.set_application() sets the current application')
def test_constructor(self): """ Application.__init__() behaves properly """ application = Application("foo", "bar") self.assertEqual( "foo", application.get_name(), msg="__init__() takes the application name as its first argument" ) self.assertEqual( "bar", application.get_version(), msg="__init__() takes the application version as its second argument" ) self.assertEqual( ["help", "list"].sort(), list(application.all().keys()).sort(), msg="__init__() registered the help and list commands by default", )
def test_merge_application_definition_without_args_then_with_args_adds_args(self): application1 = Application() application1.get_definition().add_arguments([InputArgument('foo')]) application1.get_definition().add_options([InputOption('bar')]) command = TestCommand() command.set_application(application1) command.set_definition(InputDefinition()) command.merge_application_definition(False) self.assertFalse(command.get_definition().has_argument('foo')) self.assertTrue(command.get_definition().has_option('bar')) command.merge_application_definition(True) self.assertTrue(command.get_definition().has_argument('foo')) # It should not merge the definitions twice command.merge_application_definition() self.assertEqual(2, command.get_definition().get_argument_count())
def test_adding_single_helper_set_overwrites_default_values(self): application = Application() application.set_auto_exit(False) application.set_catch_exceptions(False) application.set_helper_set(HelperSet({"formatter": FormatterHelper()})) helper_set = application.get_helper_set() self.assertTrue(helper_set.has("formatter")) self.assertFalse(helper_set.has("dialog")) self.assertFalse(helper_set.has("progress"))
def test_set_run_custom_default_command(self): """ Application calls the default command. """ application = Application() application.set_auto_exit(False) command = FooCommand() application.add(command) application.set_default_command(command.get_name()) tester = ApplicationTester(application) tester.run([]) self.assertEqual("interact called\ncalled\n", tester.get_display()) application = CustomDefaultCommandApplication() application.set_auto_exit(False) tester = ApplicationTester(application) tester.run([]) self.assertEqual("interact called\ncalled\n", tester.get_display())