def test_command_obj_defaults_set(): set_sysargv(test_command_7) c = Command() c.set_defaults({'test': 'arg'}) returned_string = c.obj_string() returned_string_list = returned_string.split("\n") assert returned_string_list[2] == """obj.defaults = {'test': 'arg'}"""
def test_command_get_doubledash_2(): set_sysargv(test_command_12) c = Command() assert len(c.get_double_dash_args()) == 4 assert c.get_double_dash_args() == [ 'lastpos', '--test', 'path2', 'another' ]
def test_command_optdefaults_define_multi_by_set_defaults_method(): set_sysargv(test_command_1) c = Command() c.set_defaults({'test': 'value', 'another': 'more'}) assert len(c.defaults) == 2 assert c.defaults['test'] == 'value' assert c.defaults['another'] == 'more'
def test_command_optdefaults_define_multi_by_index(): set_sysargv(test_command_1) c = Command() c.defaults['test'] = 'value' c.defaults['another'] = 'more' assert len(c.defaults) == 2 assert c.defaults['test'] == 'value' assert c.defaults['another'] == 'more'
def __init__(self): cli_args = Command() ep = dict() if cli_args.contains_switches("p"): ep["domain"], ep["port"] = cli_args.get_definition("p").rsplit( ":", 1) else: ep["domain"], ep["port"] = (G1_TEST_DEFAULT_ENDPOINT if cli_args.contains_switches("gtest") else G1_DEFAULT_ENDPOINT) if ep["domain"].startswith("[") and ep["domain"].endswith("]"): ep["domain"] = ep["domain"][1:-1] self.ep = ep
def test_commandobj_property_arguments(): """Test: obj.arguments property is defined with instantiated Arguments object""" set_sys_argv() c = Command() assert isinstance(c.arguments, list) assert c.arguments == sys.argv[ 1:] # the obj.arguments list is same as sys.argv[1:]
def test_commandobj_property_switches(): """Test: obj.switches property is defined with instantiated Switches object and includes correct strings""" set_sys_argv() c = Command() assert isinstance(c.switches, set) assert 'long' in c.switches assert len(c.switches) == 1
def test_commandobj_property_definitions(): """Test: obj.defs property is defined with instantiated Definitions object and includes correct key:value pairs""" set_sys_argv() c = Command() assert isinstance(c.defs, dict) assert len(c.defs) == 1 assert 'V' in c.defs.keys() assert c.defs['V'] == 'lastpos'
def test_commandobj_property_mops(): """Test: obj.mops property is defined with instantiated Mops object and includes correct characters""" set_sys_argv() c = Command() assert isinstance(c.mops, set) assert len(c.mops) == 4 # in this command will be read as four separate options in this property for test_option in ['n', 'a', 'm', 'e']: assert test_option in c.mops
def test_commandobj_property_argv(): """Test: obj.argv Command object property uses 0 based index for first positional argument, not executable""" set_sys_argv() c = Command() assert c.argv == [ 'subcmd', '-s', '--long', '-n', 'shortdef', '--name', 'longdef', '--nameeq=longdefeq', 'lastpos' ]
def test_commandobj_property_mops(): """Test: obj.mops property is defined with instantiated Mops object and includes correct characters""" set_sys_argv2() c = Command() assert isinstance(c.mops, set) assert len(c.mops) == 4 for x in "mops": assert x in c.mops assert "t" not in c.mops # confirm that 't' character from short switch is not included
def test_command_obj_string(): set_sysargv(test_command_1) c = Command() returned_string = c.obj_string() returned_string_list = returned_string.split("\n") assert returned_string_list[0] == "obj.argc = 9" assert returned_string_list[1] == """obj.arguments = ['subcmd', '-s', '--long', '-n', 'shortdef', '--name', 'longdef', '--nameeq=longdefeq', 'lastpos']""" assert returned_string_list[2] == """obj.defaults = {}""" assert returned_string_list[5] == """obj.mdefs = {}""" assert returned_string_list[6] == """obj.mops = {}""" assert returned_string_list[7] == """obj.arg0 = 'subcmd'""" assert returned_string_list[8] == """obj.arg1 = '-s'""" assert returned_string_list[9] == """obj.arg2 = '--long'""" assert returned_string_list[10] == """obj.arg3 = '-n'""" assert returned_string_list[11] == """obj.arg4 = 'shortdef'""" assert returned_string_list[12] == """obj.arglp = 'lastpos'""" assert returned_string_list[13] == """obj.subcmd = 'subcmd'""" assert returned_string_list[14] == """obj.subsubcmd = '-s'"""
def test_command_valid_nargs(): set_sysargv(test_command_2) c = Command() assert c.validates_includes_n_args(2) == True assert c.validates_includes_n_args(3) == False set_sysargv(test_command_3) c = Command() assert c.validates_includes_n_args(2) == True assert c.validates_includes_n_args(3) == False set_sysargv(test_command_empty_1) c = Command() assert c.validates_includes_n_args(0) == True assert c.validates_includes_n_args(1) == False
def test_command_dnval_nargs(): set_sysargv(test_command_2) c = Command() assert c.does_not_validate_n_args(2) == False assert c.does_not_validate_n_args(3) == True set_sysargv(test_command_3) c = Command() assert c.does_not_validate_n_args(2) == False assert c.does_not_validate_n_args(3) == True set_sysargv(test_command_empty_1) c = Command() assert c.does_not_validate_n_args(0) == False assert c.does_not_validate_n_args(1) == True
def test_commandobj_property_definitions(): """Test: obj.defs property is defined with instantiated Definitions object and includes correct key:value pairs""" set_sys_argv() c = Command() assert isinstance(c.defs, dict) assert len(c.defs) == 3 expected_keys = ['n', 'name', 'nameeq'] observed_keys = c.defs.keys() assert len(observed_keys) == len(expected_keys) for x in observed_keys: assert x in expected_keys
def cli(): # ep: endpoint, node's network interface ep, c = dict(), Command() ep["domain"], ep["port"] = "duniter.org", "8999" try: ep["domain"], ep["port"] = c.get_definition('p').split(':') except: pass try: ep["domain"], ep["port"] = c.get_definition('peer').split(':') except: pass if c.is_help_request() or c.is_usage_request(): usage() if c.is_version_request(): print("silkaj 0.1.0") return (ep, c)
def main(): c = Command() if c.does_not_validate_missing_args(): sys.stderr.write( f"[ufolint] ERROR: Please include one or more UFO directory arguments " f"with your command.{os.linesep}") sys.exit(1) if c.is_help_request(): print(HELP) sys.exit(0) elif c.is_version_request(): print(VERSION) sys.exit(0) elif c.is_usage_request(): print(USAGE) sys.exit(0) for argument in sys.argv: if argument[-4:] == ".ufo": hh = MainRunner(argument) hh.run() # if the script completes without status code 1 SystemExit # being raised, then all tests passed sys.exit(0)
def cli(): # ep: endpoint, node's network interface ep, c = dict(), Command() subcmd = ["info", "diffi", "network", "issuers"] if c.is_help_request() or c.is_usage_request() or c.subcmd not in subcmd: usage(); exit() if c.is_version_request(): print("silkaj 0.1.0"); exit() ep["domain"], ep["port"] = "duniter.org", "8999" try: ep["domain"], ep["port"] = c.get_definition('p').rsplit(':', 1) except: print("Fallback to default node {}:{}\nCause: no specifed node, node not reachable or parsing issue." .format(ep["domain"], ep["port"])) if ep["domain"].startswith('[') and ep["domain"].endswith(']'): ep["domain"] = ep["domain"][1:-1] return (ep, c)
def cli(): # ep: endpoint, node's network interface ep, c = dict(), Command() subcmd = ["info", "diffi", "network", "issuers", "argos", "amount", "transaction", "generate_auth_file", "id"] if c.is_help_request() or c.is_usage_request() or c.subcmd not in subcmd: usage() if c.is_version_request(): print("silkaj 0.2.0") exit() ep["domain"], ep["port"] = "duniter.org", "10901" try: ep["domain"], ep["port"] = c.get_definition('p').rsplit(':', 1) except: print("Requested default node: <{}:{}>".format(ep["domain"], ep["port"]), file=sys.stderr) if ep["domain"].startswith('[') and ep["domain"].endswith(']'): ep["domain"] = ep["domain"][1:-1] return ep, c
def profile(): # ------------------------------------------------------------------------------ # Setup a profile # ------------------------------------------------------------------------------ pr = cProfile.Profile() # ------------------------------------------------------------------------------ # Enter setup code below # ------------------------------------------------------------------------------ # Optional: include setup code here import sys from commandlines import Command sys.argv = "executable test --long -s --other=alternate bogus -- -stuff -here --help" # ------------------------------------------------------------------------------ # Start profiler # ------------------------------------------------------------------------------ pr.enable() for _ in xrange(10000): c = Command() # "-" in xstring[0] # "-" in ystring[0] # ------------------------------------------------------------------------------ # BEGIN profiled code block # ------------------------------------------------------------------------------ # include profiled code here # ------------------------------------------------------------------------------ # END profiled code block # ------------------------------------------------------------------------------ pr.disable() s = StringIO.StringIO() sortby = 'cumulative' ps = pstats.Stats(pr, stream=s).sort_stats(sortby) ps.strip_dirs().sort_stats("time").print_stats() print(s.getvalue())
def test_command_contains_mops_single(): set_sysargv(test_command_9) c = Command() assert c.contains_mops("m") == True
def test_command_optdefaults_raises_keyerror_with_bad_index(): set_sysargv(test_command_1) c = Command() c.defaults['test'] = 'value' with pytest.raises(KeyError): example = c.defaults['bogus']
#!/usr/bin/env python # -*- coding: utf-8 -*- from commandlines import Command import sys import shlex test_command_1 = "spam eggs --toast -b --drink=milk filepath" test_command_13 = "executable -o path1 -o path2 -t --flag" test_command_18 = "executable -o path1 -o path2 --file tests/path1 --file tests/path2" test_command_19 = "executable -mops -t --test=bogus --test=another --help me" def set_sysargv(argstring): sys.argv = shlex.split(argstring) set_sysargv(test_command_13) c = Command() print(c.obj_string())
def test_command_optdefaults_contains_default_multi_tests_present(): set_sysargv(test_command_1) c = Command() c.set_defaults({'test': 'value', 'another': 'more'}) assert c.contains_defaults('test', 'another')
def test_command_optdefaults_contains_default_when_empty(): set_sysargv(test_command_1) c = Command() assert c.contains_defaults('test') == False
def test_commandobj_property_arglp(): """Test: obj.arglp is defined as the last positional argument""" set_sys_argv() c = Command() assert c.arglp == "lastpos"
def test_commandobj_property_has_defs(): """Test obj.has_defs is defined as True when defs are present""" set_sys_argv() c = Command() assert c.has_defs is True
def test_command_contains_switches_multiple(): set_sysargv(test_command_1) c = Command() assert c.contains_switches("s", "long", "name") == True
def main(): """Defines the logic for the `font-line` command line executable""" c = Command() if c.does_not_validate_missing_args(): stderr("[font-line] ERROR: Please include one or more arguments with your command.") sys.exit(1) if c.is_help_request(): stdout(settings.HELP) sys.exit(0) elif c.is_version_request(): stdout(settings.VERSION) sys.exit(0) elif c.is_usage_request(): stdout(settings.USAGE) sys.exit(0) # REPORT sub-command if c.subcmd == "report": if c.argc < 2: stderr("[font-line] ERROR: Missing file path argument(s) after the report subcommand.") sys.exit(1) else: for fontpath in c.argv[1:]: # test for existence of file on path if file_exists(fontpath): # test that filepath includes file of a supported file type if is_supported_filetype(fontpath): stdout(get_font_report(fontpath)) else: stderr("[font-line] ERROR: '" + fontpath + "' does not appear to be a supported font file type.") else: stderr("[font-line] ERROR: '" + fontpath + "' does not appear to be a valid filepath.") # PERCENT sub-command elif c.subcmd == "percent": if c.argc < 3: stderr("[font-line] ERROR: Not enough arguments.") sys.exit(1) else: percent = c.argv[1] # test the percent integer argument try: percent_int = int(percent) # test that the argument can be cast to an integer value if percent_int <= 0: stderr("[font-line] ERROR: Please enter a percent value that is greater than zero.") sys.exit(1) if percent_int > 100: stdout("[font-line] Warning: You entered a percent value over 100%. Please confirm that this is " "your intended metrics modification.") except ValueError: stderr("[font-line] ERROR: You entered '" + percent + "'. This argument needs to be an integer value.") sys.exit(1) for fontpath in c.argv[2:]: if file_exists(fontpath): if is_supported_filetype(fontpath): if modify_linegap_percent(fontpath, percent) is True: outpath = get_linegap_percent_filepath(fontpath, percent) stdout("[font-line] '" + fontpath + "' successfully modified to '" + outpath + "'.") else: # pragma: no cover stderr("[font-line] ERROR: Unsuccessful modification of '" + fontpath + "'.") else: stderr("[font-line] ERROR: '" + fontpath + "' does not appear to be a supported font file type.") else: stderr("[font-line] ERROR: '" + fontpath + "' does not appear to be a valid filepath.") else: stderr("[font-lines] ERROR: You used an unsupported argument to the executable. Please review the" " `font-line --help` documentation and try again.") sys.exit(1)
def test_command_contains_switches_differentcase(): set_sysargv(test_command_4) c = Command() assert c.contains_switches("v", "V") == True
def test_command_contains_switches_alt_long(): set_sysargv(test_command_8) c = Command() assert c.contains_switches("name") == True
def test_command_contains_mops_single_false(): set_sysargv(test_command_9) c = Command() assert c.contains_mops("r") == False
def test_command_contains_switches_noargs(): set_sysargv(test_command_empty_1) c = Command() assert c.contains_switches("name") == False
def test_commandobj_property_has_mdefs(): """Test obj.has_mdefs is defined as False when mdefs are not present""" set_sys_argv() c = Command() assert c.has_mdefs is False
def test_commandobj_property_arg4(): """Test: obj.arg4 is defined as the fifth positional argument""" set_sys_argv() c = Command() assert c.arg4 == ""
def test_command_optdefaults_contains_default_when_absent(): set_sysargv(test_command_1) c = Command() c.set_defaults({'test': 'value'}) assert c.contains_defaults('bogus') == False
def test_command_optdefaults_define_nonstring_by_set_defaults_method(): set_sysargv(test_command_1) c = Command() c.set_defaults({'test': 1}) assert c.defaults['test'] == 1
def test_command_optdefaults_get_default_when_present(): set_sysargv(test_command_1) c = Command() c.set_defaults({'test': 'value'}) assert c.get_default('test') == 'value'
def test_command_optdefaults_contains_default_when_present(): set_sysargv(test_command_1) c = Command() c.set_defaults({'test': 'value'}) assert c.contains_defaults('test') == True
def test_command_optdefaults_get_default_when_absent(): set_sysargv(test_command_1) c = Command() c.set_defaults({'test': 'value'}) with pytest.raises(MissingDictionaryKeyError): example = c.get_default('bogus')
def test_command_optdefaults_contains_default_multi_tests_absent_difforder(): set_sysargv(test_command_1) c = Command() c.set_defaults({'test': 'value', 'another': 'more'}) assert c.contains_defaults('bogus', 'test') == False
def test_command_contains_mops_multiple(): set_sysargv(test_command_9) c = Command() assert c.contains_mops("m", "p", "s") == True
def test_command_optdefaults_get_default_when_empty(): set_sysargv(test_command_1) c = Command() with pytest.raises(MissingDictionaryKeyError): example = c.get_default('bogus')
def test_commandobj_property_mops(): """Test: obj.mops property is defined with instantiated Mops object and includes correct characters""" set_sys_argv() c = Command() assert isinstance(c.mops, set) assert len(c.mops) == 0 # should be empty, no mops included in command
def test_command_optdefaults_get_default_when_not_string(): set_sysargv(test_command_1) c = Command() c.set_defaults({'test': 1}) assert c.get_default('test') == 1
def test_commandobj_property_argv(): """Test: obj.argv Command object property uses 0 based index for first positional argument, not executable""" set_sys_argv() c = Command() assert c.argv == ['-v', '-V', 'lastpos']
def test_command_optdefaults_define_by_index(): set_sysargv(test_command_1) c = Command() c.defaults['test'] = 'value' assert len(c.defaults) == 1 assert c.defaults['test'] == 'value'
def test_commandobj_property_argc(): """Test: obj.argc is defined with appropriate argument length""" set_sys_argv() c = Command() assert c.argc == 3
def test_command_optdefaults_define_nonstring_by_index(): set_sysargv(test_command_1) c = Command() c.defaults['test'] = 1 assert c.defaults['test'] == 1
def test_commandobj_property_arg0(): """Test: obj.arg0 is defined as the first positional argument""" set_sys_argv() c = Command() assert c.arg0 == "-v"
def test_command_optdefaults_define_by_set_defaults_method(): set_sysargv(test_command_1) c = Command() c.set_defaults({'test': 'value'}) assert len(c.defaults) == 1 assert c.defaults['test'] == 'value'
def test_commandobj_property_arg1(): """Test: obj.arg1 is defined as second positional argument""" set_sys_argv() c = Command() assert c.arg1 == "-V"
def main(): c = Command()
def test_command_contains_switches_when_one_switch_notpresent(): set_sysargv(test_command_4) c = Command() assert c.contains_switches("v", "V", "bogus") == False