Best Python code snippet using stestr_python
test_app.py
Source:test_app.py  
1# -*- encoding: utf-8 -*-2from argparse import ArgumentError3try:4    from StringIO import StringIO5except ImportError:6    from io import StringIO7import mock8from cliff.app import App9from cliff.command import Command10from cliff.commandmanager import CommandManager11from cliff.tests import utils12from cliff.utils import damerau_levenshtein, COST13def make_app(**kwargs):14    cmd_mgr = CommandManager('cliff.tests')15    # Register a command that succeeds16    command = mock.MagicMock(spec=Command)17    command_inst = mock.MagicMock(spec=Command)18    command_inst.run.return_value = 019    command.return_value = command_inst20    cmd_mgr.add_command('mock', command)21    # Register a command that fails22    err_command = mock.Mock(name='err_command', spec=Command)23    err_command_inst = mock.Mock(spec=Command)24    err_command_inst.run = mock.Mock(25        side_effect=RuntimeError('test exception')26    )27    err_command.return_value = err_command_inst28    cmd_mgr.add_command('error', err_command)29    app = App('testing interactive mode',30              '1',31              cmd_mgr,32              stderr=mock.Mock(),  # suppress warning messages33              **kwargs34              )35    return app, command36def test_no_args_triggers_interactive_mode():37    app, command = make_app()38    app.interact = mock.MagicMock(name='inspect')39    app.run([])40    app.interact.assert_called_once_with()41def test_interactive_mode_cmdloop():42    app, command = make_app()43    app.interactive_app_factory = mock.MagicMock(44        name='interactive_app_factory'45    )46    assert app.interpreter is None47    app.run([])48    assert app.interpreter is not None49    app.interactive_app_factory.return_value.cmdloop.assert_called_once_with()50def test_initialize_app():51    app, command = make_app()52    app.initialize_app = mock.MagicMock(name='initialize_app')53    app.run(['mock'])54    app.initialize_app.assert_called_once_with(['mock'])55def test_prepare_to_run_command():56    app, command = make_app()57    app.prepare_to_run_command = mock.MagicMock(name='prepare_to_run_command')58    app.run(['mock'])59    app.prepare_to_run_command.assert_called_once_with(command())60def test_clean_up_success():61    app, command = make_app()62    app.clean_up = mock.MagicMock(name='clean_up')63    app.run(['mock'])64    app.clean_up.assert_called_once_with(command.return_value, 0, None)65def test_clean_up_error():66    app, command = make_app()67    app.clean_up = mock.MagicMock(name='clean_up')68    app.run(['error'])69    app.clean_up.assert_called_once_with(mock.ANY, mock.ANY, mock.ANY)70    call_args = app.clean_up.call_args_list[0]71    assert call_args == mock.call(mock.ANY, 1, mock.ANY)72    args, kwargs = call_args73    assert isinstance(args[2], RuntimeError)74    assert args[2].args == ('test exception',)75def test_clean_up_error_debug():76    app, command = make_app()77    app.clean_up = mock.MagicMock(name='clean_up')78    try:79        app.run(['--debug', 'error'])80    except RuntimeError as err:81        assert app.clean_up.call_args_list[0][0][2] is err82    else:83        assert False, 'Should have had an exception'84    assert app.clean_up.called85    call_args = app.clean_up.call_args_list[0]86    assert call_args == mock.call(mock.ANY, 1, mock.ANY)87    args, kwargs = call_args88    assert isinstance(args[2], RuntimeError)89    assert args[2].args == ('test exception',)90def test_error_handling_clean_up_raises_exception():91    app, command = make_app()92    app.clean_up = mock.MagicMock(93        name='clean_up',94        side_effect=RuntimeError('within clean_up'),95    )96    app.run(['error'])97    assert app.clean_up.called98    call_args = app.clean_up.call_args_list[0]99    assert call_args == mock.call(mock.ANY, 1, mock.ANY)100    args, kwargs = call_args101    assert isinstance(args[2], RuntimeError)102    assert args[2].args == ('test exception',)103def test_error_handling_clean_up_raises_exception_debug():104    app, command = make_app()105    app.clean_up = mock.MagicMock(106        name='clean_up',107        side_effect=RuntimeError('within clean_up'),108    )109    try:110        app.run(['--debug', 'error'])111    except RuntimeError as err:112        if not hasattr(err, '__context__'):113            # The exception passed to clean_up is not the exception114            # caused *by* clean_up.  This test is only valid in python115            # 2 because under v3 the original exception is re-raised116            # with the new one as a __context__ attribute.117            assert app.clean_up.call_args_list[0][0][2] is not err118    else:119        assert False, 'Should have had an exception'120    assert app.clean_up.called121    call_args = app.clean_up.call_args_list[0]122    assert call_args == mock.call(mock.ANY, 1, mock.ANY)123    args, kwargs = call_args124    assert isinstance(args[2], RuntimeError)125    assert args[2].args == ('test exception',)126def test_normal_clean_up_raises_exception():127    app, command = make_app()128    app.clean_up = mock.MagicMock(129        name='clean_up',130        side_effect=RuntimeError('within clean_up'),131    )132    app.run(['mock'])133    assert app.clean_up.called134    call_args = app.clean_up.call_args_list[0]135    assert call_args == mock.call(mock.ANY, 0, None)136def test_normal_clean_up_raises_exception_debug():137    app, command = make_app()138    app.clean_up = mock.MagicMock(139        name='clean_up',140        side_effect=RuntimeError('within clean_up'),141    )142    app.run(['--debug', 'mock'])143    assert app.clean_up.called144    call_args = app.clean_up.call_args_list[0]145    assert call_args == mock.call(mock.ANY, 0, None)146def test_build_option_parser_conflicting_option_should_throw():147    class MyApp(App):148        def __init__(self):149            super(MyApp, self).__init__(150                description='testing',151                version='0.1',152                command_manager=CommandManager('tests'),153            )154        def build_option_parser(self, description, version):155            parser = super(MyApp, self).build_option_parser(description,156                                                            version)157            parser.add_argument(158                '-h', '--help',159                default=self,  # tricky160                help="Show help message and exit.",161            )162    # TODO: tests should really use unittest2.163    try:164        MyApp()165    except ArgumentError:166        pass167    else:168        raise Exception('Exception was not thrown')169def test_option_parser_conflicting_option_custom_arguments_should_not_throw():170    class MyApp(App):171        def __init__(self):172            super(MyApp, self).__init__(173                description='testing',174                version='0.1',175                command_manager=CommandManager('tests'),176            )177        def build_option_parser(self, description, version):178            argparse_kwargs = {'conflict_handler': 'resolve'}179            parser = super(MyApp, self).build_option_parser(180                description,181                version,182                argparse_kwargs=argparse_kwargs)183            parser.add_argument(184                '-h', '--help',185                default=self,  # tricky186                help="Show help message and exit.",187            )188    MyApp()189def test_option_parser_abbrev_issue():190    class MyCommand(Command):191        def get_parser(self, prog_name):192            parser = super(MyCommand, self).get_parser(prog_name)193            parser.add_argument("--end")194            return parser195        def take_action(self, parsed_args):196            assert(parsed_args.end == '123')197    class MyCommandManager(CommandManager):198        def load_commands(self, namespace):199            self.add_command("mycommand", MyCommand)200    class MyApp(App):201        def __init__(self):202            super(MyApp, self).__init__(203                description='testing',204                version='0.1',205                command_manager=MyCommandManager(None),206            )207        def build_option_parser(self, description, version):208            parser = super(MyApp, self).build_option_parser(209                description,210                version,211                argparse_kwargs={'allow_abbrev': False})212            parser.add_argument('--endpoint')213            return parser214    app = MyApp()215    # NOTE(jd) --debug is necessary so assert in take_action() raises correctly216    # here217    app.run(['--debug', 'mycommand', '--end', '123'])218def _test_help(deferred_help):219    app, _ = make_app(deferred_help=deferred_help)220    with mock.patch.object(app, 'initialize_app') as init:221        with mock.patch('cliff.help.HelpAction.__call__',222                        side_effect=SystemExit(0)) as helper:223            try:224                app.run(['--help'])225            except SystemExit:226                pass227            else:228                raise Exception('Exception was not thrown')229            assert helper.called230        assert init.called == deferred_help231def test_help():232    _test_help(False)233def test_deferred_help():234    _test_help(True)235def test_subcommand_help():236    app, _ = make_app(deferred_help=False)237    # Help is called immediately238    with mock.patch('cliff.help.HelpAction.__call__') as helper:239        app.run(['show', 'files', '--help'])240    assert helper.called241def test_subcommand_deferred_help():242    app, _ = make_app(deferred_help=True)243    # Show that provide_help_if_requested() did not show help and exit244    with mock.patch.object(app, 'run_subcommand') as helper:245        app.run(['show', 'files', '--help'])246    helper.assert_called_once_with(['help', 'show', 'files'])247def test_unknown_cmd():248    app, command = make_app()249    assert app.run(['hell']) == 2250def test_unknown_cmd_debug():251    app, command = make_app()252    try:253        app.run(['--debug', 'hell']) == 2254    except ValueError as err:255        assert "['hell']" in ('%s' % err)256def test_list_matching_commands():257    stdout = StringIO()258    app = App('testing', '1',259              utils.TestCommandManager(utils.TEST_NAMESPACE),260              stdout=stdout)261    app.NAME = 'test'262    try:263        assert app.run(['t']) == 2264    except SystemExit:265        pass266    output = stdout.getvalue()267    assert "test: 't' is not a test command. See 'test --help'." in output268    assert 'Did you mean one of these?' in output269    assert 'three word command\n  two words\n' in output270def test_fuzzy_no_commands():271    cmd_mgr = CommandManager('cliff.fuzzy')272    app = App('test', '1.0', cmd_mgr)273    cmd_mgr.commands = {}274    matches = app.get_fuzzy_matches('foo')275    assert matches == []276def test_fuzzy_common_prefix():277    # searched string is a prefix of all commands278    cmd_mgr = CommandManager('cliff.fuzzy')279    app = App('test', '1.0', cmd_mgr)280    cmd_mgr.commands = {}281    cmd_mgr.add_command('user list', utils.TestCommand)282    cmd_mgr.add_command('user show', utils.TestCommand)283    matches = app.get_fuzzy_matches('user')284    assert matches == ['user list', 'user show']285def test_fuzzy_same_distance():286    # searched string has the same distance to all commands287    cmd_mgr = CommandManager('cliff.fuzzy')288    app = App('test', '1.0', cmd_mgr)289    cmd_mgr.add_command('user', utils.TestCommand)290    for cmd in cmd_mgr.commands.keys():291        assert damerau_levenshtein('node', cmd, COST) == 8292    matches = app.get_fuzzy_matches('node')293    assert matches == ['complete', 'help', 'user']294def test_fuzzy_no_prefix():295    # search by distance, no common prefix with any command296    cmd_mgr = CommandManager('cliff.fuzzy')297    app = App('test', '1.0', cmd_mgr)298    cmd_mgr.add_command('user', utils.TestCommand)299    matches = app.get_fuzzy_matches('uesr')300    assert matches == ['user']301def test_verbose():302    app, command = make_app()303    app.clean_up = mock.MagicMock(name='clean_up')304    app.run(['--verbose', 'mock'])305    app.clean_up.assert_called_once_with(command.return_value, 0, None)306    app.clean_up.reset_mock()307    app.run(['--quiet', 'mock'])308    app.clean_up.assert_called_once_with(command.return_value, 0, None)309    try:310        app.run(['--verbose', '--quiet', 'mock'])311    except SystemExit:312        pass313    else:...sysfunc.py
Source:sysfunc.py  
1import os2from bsddb3 import db34def sort():5    os.system("sort -u ads.txt > sortedAds.txt")6    print("Sorted ads.txt")7    os.system("sort -u prices.txt > sortedPrices.txt")8    print("Sorted prices.txt")9    os.system("sort -u pdate.txt > sortedPdates.txt")10    print("Sorted pdate.txt")11    os.system("sort -u terms.txt > sortedTerms.txt")12    print("Sorted terms.txt")13()1415def clear_phase1():16    clean_up = ""17    while(clean_up.upper() != 'Y' and clean_up.upper() != 'N'):18        clean_up = input("Would you like to clean up text files? (Y/N): ")19    if(clean_up.upper() == 'Y'):20        print("Cleaning up text files..."+21          "Removing terms.txt"+22          "Removing pdates.txt"+23          "Removing ads.txt"+24          "Removing prices.txt")25        os.system("rm -rf terms.txt pdates.txt ads.txt prices.txt")26    else:27        print("Maintained text files")28()2930def clear_phase2():31    clean_up = ""32    while(clean_up.upper() != 'Y' and clean_up.upper() != 'N'):33        clean_up = input("Would you like to clean up sorted files? (Y/N): ")34    if(clean_up.upper() == 'Y'):35        print("Cleaning up sorted files..."+36              "Removing sortedTerms.txt"+37              "Removing sortedPdates.txt"+38              "Removing sortedAds.txt"+39              "Removing sortedPrices.txt")40        os.system("rm -rf sortedTerms.txt sortedPdates.txt sortedAds.txt sortedPrices.txt")41    else:42        print("Maintained sorted files")43        44    clean_up = ""45    while(clean_up.upper() != 'Y' and clean_up.upper() != 'N'):46        clean_up = input("Would you like to clean up split files? (Y/N): ")47    if(clean_up.upper() == 'Y'):48        print("Cleaning up split files..."+49              "Removing splitTerms.txt"+50              "Removing splitPdates.txt"+51              "Removing splitAds.txt"+52              "Removing splitPrices.txt")53        os.system("rm -rf splitTerms.txt splitPdates.txt splitAds.txt splitPrices.txt")54    else:55        print("Maintained split files")56        57    clean_up = ""58    while(clean_up.upper() != 'Y' and clean_up.upper() != 'N'):59        clean_up = input("Would you like to clean up index files? (Y/N): ")60    if(clean_up.upper() == 'Y'):61        print("Cleaning up index files..."+62              "Removing te.idx"+63              "Removing ad.idx"+64              "Removing da.idx"+65              "Removing pr.idx")66        os.system("rm -rf ad.idx te.idx da.idx pr.idx")67    else:68        print("Maintained sorted files, split files, index files")69()7071def load_dbs():72    os.system("db_load -T -c duplicates=1 -f splitAds.txt -t hash ad.idx")73    print("Created ad.idx")74    os.system("db_load -T -c duplicates=1 -f splitPdates.txt -t btree da.idx")75    print("Created da.idx")76    os.system("db_load -T -c duplicates=1 -f splitPrices.txt -t btree pr.idx")77    print("Created pr.idx")78    os.system("db_load -T -c duplicates=1 -f splitTerms.txt -t btree te.idx")79    print("Created te.idx")
...test_tool_cleanup.py
Source:test_tool_cleanup.py  
...8def make_me_a_file():9    test_file = open("temp.txt", "w")10    test_file.write("file to be deleted")11    test_file.close()12def test_clean_up():13    """clean_up instantiates with cmd-line if clean_up is in $PATH"""14    assemble = clean_up.Clean_up("rm")15def test_clean_up_cmd():16    """clean_up instantiates, runs and returns correct form of cmd-line"""17    make_me_a_file()18    obj = clean_up.Clean_up("rm")19    target = ' '.join(["rm", "temp.txt"])20    results = obj.run("temp.txt")21    assert_equal(results.command, target)22def test_clean_up_exec_notexist():23    """Error thrown if clean_up executable does not exist"""24    try:25        obj = clean_up.Clean_up(os.path.join(".", "rm"))26    except NotExecutableError:...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
