Best Python code snippet using slash
test_interruptions.py
Source:test_interruptions.py  
...39def test_sigterm_interrupt(suite, suite_test):40    suite_test.append_line('raise slash.exceptions.TerminatedException()')41    suite_test.expect_interruption()42    for test in suite.iter_all_after(suite_test):43        test.expect_deselect()44    suite.run(expect_interruption=True)45@pytest.mark.parametrize('hook_name', ['session_start', 'test_start'])46def test_sigterm_on_hook(suite, hook_name):47    @gossip.register('slash.{}'.format(hook_name))48    def session_start():  # pylint: disable=unused-variable49        raise slash.exceptions.TerminatedException('Terminated by signal')50    assert suite51    for index, test in enumerate(suite):52        if index == 0 and hook_name == 'test_start':53            # first test should be interrupted...54            test.expect_interruption()55        else:56            test.expect_deselect()57    result = suite.run(expect_interruption=True)58def test_test_end_called_for_interrupted_test(interrupted_suite, interrupted_test):59    ended = []60    @gossip.register('slash.test_end')61    def test_end():62        ended.append(slash.context.test.__slash__.id)63    s = interrupted_suite.run(expect_interruption=True)64    result = s[interrupted_test]65    assert result.test_metadata.id in ended66def test_ayalas(interrupted_suite, interrupted_test, interrupted_index, config_override, tmpdir):67    config_override('log.format', 'file: {record.message}')68    config_override('log.console_format', 'console: {record.message}')69    config_override('log.root', str(tmpdir))70    callback = Checkpoint()71    slash.hooks.log_file_closed.register(callback) # pylint: disable=no-member72    result = interrupted_suite.run(expect_interruption=True)73    num_closed_log_files = interrupted_index + 2 # One for each test that run (the index is zero based) + session log74    assert callback.called_count == num_closed_log_files75def test_session_interruption_in_start(suite, suite_test, session_interrupt):76    @suite.slashconf.append_body77    def __code__():78        @slash.hooks.session_start.register # pylint: disable=no-member79        def session_cleanup():80            raise KeyboardInterrupt()81    for test in suite:82        test.expect_deselect()83    suite.run(expect_interruption=True)84    assert session_interrupt.called_count == 185def test_interrupt_hooks_should_be_called_once(suite, suite_test, is_last_test, session_interrupt, test_interrupt_callback):86    @suite_test.append_body87    def __code__():88        @slash.add_critical_cleanup89        def cleanup():90            raise KeyboardInterrupt('A')91        raise KeyboardInterrupt('B')92    suite_test.expect_interruption()93    for t in suite.iter_all_after(suite_test, assert_has_more=not is_last_test):94        t.expect_deselect()95    result = suite.run(expect_interruption=True)96    assert test_interrupt_callback.called_count == 197    assert session_interrupt.called_count == 198    assert result.session.results.global_result.is_interrupted()99def test_interrupted_with_custom_exception(suite, suite_test, request):100    import test101    class CustomException(Exception):102        pass103    test.__interruption_exception__ = CustomException104    prev_interruption_exceptions = slash.exceptions.INTERRUPTION_EXCEPTIONS105    slash.exceptions.INTERRUPTION_EXCEPTIONS += (CustomException,)106    @request.addfinalizer107    def cleanup():108        del test.__interruption_exception__109        slash.exceptions.INTERRUPTION_EXCEPTIONS = prev_interruption_exceptions110    suite_test.append_line('import test')111    suite_test.append_line('raise test.__interruption_exception__()')112    suite_test.expect_interruption()113    for t in suite.iter_all_after(suite_test):114        t.expect_deselect()115    results = suite.run(expect_interruption=True)116def test_test_interrupt_hook_exception(suite_builder):117    # pylint: disable=reimported,redefined-outer-name118    @suite_builder.first_file.add_code119    def __code__():120        import slash121        @slash.hooks.test_interrupt.register # pylint: disable=no-member122        def test_interrupt(**_):123            1/0 # pylint: disable=pointless-statement124        def test_1():125            raise KeyboardInterrupt()126        def test_2():127            pass128    [res] = suite_builder.build().run().assert_results(1)129    assert res.is_interrupted()130@pytest.mark.parametrize('hook_name', ['before_session_cleanup', 'session_start', 'before_session_start'])131def test_session_scope_interruption(hook_name, suite, checkpoint):132    @gossip.register('slash.{}'.format(hook_name))133    def hook(*_, **__):134        raise KeyboardInterrupt()135    @gossip.register('slash.session_interrupt')136    def interrupt(*_, **__):137        checkpoint()138    if 'session_start' in hook_name:139        for test in suite:140            test.expect_deselect()141    else:142        assert hook_name == 'before_session_cleanup'143        suite[-1].expect_interruption()144    results = suite.run(expect_interruption=True)145    assert results.session.results.global_result.is_interrupted()146    assert checkpoint.called147@pytest.fixture148def session_interrupt():149    callback = Checkpoint()150    slash.hooks.session_interrupt.register(callback) # pylint: disable=no-member151    return callback152@pytest.fixture153def test_interrupt_callback():154    callback = Checkpoint()155    slash.hooks.test_interrupt.register(callback) # pylint: disable=no-member156    return callback157@pytest.fixture158def interrupted_suite(suite, interrupted_index):159    for index, test in enumerate(suite):160        if index == interrupted_index:161            test.append_line('raise KeyboardInterrupt()')162            test.expect_interruption()163        elif index > interrupted_index:164            test.expect_deselect()165    return suite166@pytest.fixture167def interrupted_test(interrupted_suite, interrupted_index):168    return interrupted_suite[interrupted_index]169@pytest.fixture170def interrupted_index(suite):...test_loader.py
Source:test_loader.py  
...60        suite_test.add_parameter()61    for test in suite:62        if suite_test.cls is None and test is not suite_test:63            # we are selecting a specific function, and that's not it:64            test.expect_deselect()65        elif suite_test.cls is not None and test.cls is not suite_test.cls:66            test.expect_deselect()67        elif specific_method and suite_test.cls is test.cls and suite_test is not test:68            test.expect_deselect()69    path = suite.commit()70    if suite_test.cls:71        assert suite_test.cls.tests72        factory_name = suite_test.cls.name73    else:74        factory_name = suite_test.name75    pattern = '{}:{}'.format(os.path.join(path, suite_test.file.get_relative_path()), factory_name)76    if suite_test.cls is not None and specific_method:77        assert len(suite_test.cls.tests) > 178        pattern += '.{}'.format(suite_test.name)79    suite.run(args=[pattern])80def test_import_error_registers_as_session_error(active_slash_session, test_loader):81    with pytest.raises(CannotLoadTests):82        test_loader.get_runnables(["/non/existent/path"])83    errors = active_slash_session.results.global_result.get_errors()84    assert len(errors) == 185    [error] = errors  # pylint: disable=unused-variable86def test_no_traceback_for_slash_exception():87    suite = Suite()88    summary = suite.run(expect_session_errors=True)89    assert not summary.session.results.is_success()90    [err] = summary.session.results.global_result.get_errors()91    assert err.exception_type is CannotLoadTests92    output = summary.get_console_output()93    assert 'Traceback' not in output94def test_no_traceback_for_marked_exceptions():95    suite = Suite()96    @suite.slashconf.append_body97    def __code__():  # pylint: disable=unused-variable98        from slash.exception_handling import inhibit_unhandled_exception_traceback99        raise inhibit_unhandled_exception_traceback(Exception('Some Error'))100    summary = suite.run(expect_session_errors=True)101    assert not summary.session.results.is_success()102    errors = summary.session.results.global_result.get_errors()103    assert [err.exception_type for err in errors] == [Exception]104    assert 'Some Error' in errors[0].exception_str105    output = summary.get_console_output()106    assert 'Traceback' not in output107def test_import_errors_with_session():108    suite = Suite()109    for _ in range(20):110        suite.add_test()111    problematic = suite.files[1]112    problematic.prepend_line('from nonexistent import nonexistent')113    for test in suite:114        test.expect_deselect()115    summary = suite.run(expect_session_errors=True)116    assert summary.exit_code != 0117    errs = summary.session.results.global_result.get_errors()118    for err in errs:119        assert 'No module named nonexistent' in err.message or "No module named 'nonexistent'" in err.message120    return suite121def test_fixture_and_test_overrides(tmpdir, config_override):122    tests_dir = tmpdir.join('tests')123    full_path = tests_dir.join('.dir').join('test_something.py')124    test_prefix = 'test_something'125    with full_path.open('w', ensure=True) as f:126        f.write('import slash\n')127        f.write('@slash.tag("tag-1")\ndef test_something1():\n    pass\n'.format(test_prefix))128        f.write('def test_something2():\n    pass\n'.format(test_prefix))...test_cyclic_fixture_detection.py
Source:test_cyclic_fixture_detection.py  
...5    fixture1.depend_on_fixture(fixture2)6    fixture2.depend_on_fixture(fixture1)7    suite_test.depend_on_fixture(fixture1)8    for test in suite:9        test.expect_deselect() # no test should start at all....10    summary = suite.run(expect_session_errors=True)11    assert not summary.session.results.global_result.is_success()12    assert re.search(r'yclic fixture dependency detected in \S+: {0} -> {1} -> {0}'.format(fixture1.name, fixture2.name),13                     summary.get_console_output())14def test_cyclic_fixture_detection_depend_on_self(suite, suite_test):15    fixture = suite.slashconf.add_fixture()16    fixture.depend_on_fixture(fixture)17    suite_test.depend_on_fixture(fixture)18    for test in suite:19        test.expect_deselect() # no test should start at all...20    summary = suite.run(expect_session_errors=True)21    assert not summary.session.results.global_result.is_success()22    assert re.search(r'yclic fixture dependency detected in \S+: {} depends on itself'.format(fixture.name),...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!!
