Best Python code snippet using slash
conftest.py
Source:conftest.py  
...98    if not is_last_test:99        _ = suite.add_test(type=test_type)100    return returned101@pytest.fixture102def last_suite_test(suite, test_type):103    return suite.add_test(type=test_type)104@pytest.fixture(params=[GlobalResult, Result])105def result(request):106    return request.param()107@pytest.fixture(params=[True, False])108def is_last_test(request):109    return request.param110@pytest.fixture(params=['method', 'function'])111def test_type(request):112    return request.param113@pytest.fixture114def suite():115    returned = Suite()116    returned.populate()...test_hook_calling.py
Source:test_hook_calling.py  
1# pylint: disable=unused-argument, unused-variable2from contextlib import ExitStack3import slash4from slash import hooks, plugins5from slash.plugins import PluginInterface6import pytest7import gossip8import vintage9from .utils import TestCase as _TestCase, make_runnable_tests, CustomException10class SessionEndException(Exception):11    pass12class SessionStartException(Exception):13    pass14class CustomTestEndException(Exception):15    pass16class BeforeTestCleanupException(Exception):17    pass18def test_test_skip_hook(suite, suite_test, checkpoint):19    slash.hooks.test_skip.register(checkpoint)  # pylint: disable=no-member20    suite_test.when_run.skip()21    suite.run()22    assert checkpoint.called_count == 123@pytest.mark.parametrize('autouse', [True, False])24def test_test_start_before_fixture_start(suite, suite_test, defined_fixture, autouse):25    if autouse:26        assert not defined_fixture.autouse # make sure we're not obsolete code and that that's still where it is27        defined_fixture.autouse = True28    else:29        suite_test.depend_on_fixture(defined_fixture)30    event_code = suite.slashconf.add_hook_event('test_start', extra_args=['slash.context.test.__slash__.id'])31    summary = suite.run()32    [result] = summary.get_all_results_for_test(suite_test)33    test_id = result.test_metadata.id34    event = summary.events[event_code, test_id]35    assert summary.events['fixture_start', defined_fixture.id].timestamp > event.timestamp36def test_last_test_end_after_session_cleanup(suite, last_suite_test):37    test = last_suite_test38    @test.append_body39    def __code__(): # pylint: disable=unused-variable40        import gossip # pylint: disable=redefined-outer-name,reimported41        # pylint: disable=undefined-variable,unused-variable42        def session_cleanup_callback():43            __ut__.events.add('session_cleanup')44        slash.add_cleanup(session_cleanup_callback, scope='session')45        @gossip.register('slash.test_end')46        def test_end_callback():47            __ut__.events.add('test_end')48    events = suite.run().events49    assert events['test_end'].timestamp < events['session_cleanup'].timestamp50def test_no_error_hooks_called_on_success(suite):51    called = []52    for hook_name in ['test_error', 'test_failure', 'test_skip', 'error_added']:53        gossip.register(lambda name=hook_name, **kw: called.append(name), 'slash.{}'.format(hook_name))54    suite.run()55    assert not called56def test_hook__error_added_during_test(suite, request, checkpoint, suite_test):57    request.addfinalizer(58        hooks.error_added.register(checkpoint)  # pylint: disable=no-member59        .unregister)60    suite_test.when_run.raise_exception()61    summary = suite.run()62    assert checkpoint.called63    [result] = summary.get_all_results_for_test(suite_test)64    assert checkpoint.kwargs['result'] is result65def test_hook__error_added_after_test(suite, request, checkpoint, suite_test):66    request.addfinalizer(67        hooks.error_added.register(checkpoint)  # pylint: disable=no-member68        .unregister)69    summary = suite.run()70    assert not checkpoint.called71    [result] = summary.get_all_results_for_test(suite_test)72    try:73        1 / 074    except:75        result.add_error()76    assert checkpoint.called77    assert checkpoint.kwargs['result'] is result78    assert 'ZeroDivisionError' in str(checkpoint.kwargs['error'])79def test_hook__test_interrupt(suite, request, checkpoint):80    request.addfinalizer(81        hooks.test_interrupt.register(checkpoint)  # pylint: disable=no-member82        .unregister)83    test_index = int(len(suite) / 2)84    for index, test in enumerate(suite):85        if index == test_index:86            test.when_run.interrupt()87        elif index > test_index:88            test.expect_deselect()89    suite.run(expect_interruption=True)90    assert checkpoint.called91def test_hook__test_failure_without_exception(suite, request, checkpoint, suite_test):92    request.addfinalizer(93        hooks.test_failure.register(checkpoint)  # pylint: disable=no-member94        .unregister)95    suite_test.append_line('slash.add_failure("failure")')96    suite_test.expect_failure()97    suite.run()98    assert checkpoint.called99@pytest.mark.parametrize(100    'hook_name,exception_type,should_raise', [101        ('slash.session_start', SessionStartException, True),102        ('slash.session_end', SessionEndException, True),103        ('slash.test_end', CustomTestEndException, False),104        ('slash.before_test_cleanups', BeforeTestCleanupException, False)])105@pytest.mark.parametrize('debug_enabled', [True, False])106def test_debugger_called_on_hooks(request, hook_name, exception_type, should_raise, forge, config_override, checkpoint, debug_enabled):107    @gossip.register(hook_name)108    def raise_exc():109        raise exception_type()110    config_override("debug.enabled", debug_enabled)111    def test_something():112        pass113    forge.replace_with(slash.utils.debug, 'launch_debugger', checkpoint)114    with ExitStack() as exception_stack:115        if should_raise:116            exception_stack.enter_context(pytest.raises(exception_type))117        with slash.Session() as s:118            with s.get_started_context():119                slash.runner.run_tests(make_runnable_tests(test_something))120    assert checkpoint.called == debug_enabled121    if debug_enabled:122        assert checkpoint.args[0][0] is exception_type123        assert type(checkpoint.args[0][1]) is exception_type  # pylint: disable=unidiomatic-typecheck124def test_before_cleanup_hook(request, forge):125    cleanup = forge.create_wildcard_function_stub(name='cleanup')126    before_cleanup_hook = forge.create_wildcard_function_stub(name='before_test_cleanup')127    test_end_hook = forge.create_wildcard_function_stub(name='test_end')128    gossip.register(before_cleanup_hook, 'slash.before_test_cleanups')129    gossip.register(test_end_hook, 'slash.test_end')130    before_cleanup_hook()131    cleanup()132    test_end_hook()133    forge.replay()134    def test_something():135        slash.add_cleanup(cleanup)136    with slash.Session() as s:137        with s.get_started_context():138            slash.runner.run_tests(make_runnable_tests(test_something))139def test_session_end_not_called_when_before_session_start_fails(checkpoint):140    @gossip.register('slash.before_session_start')141    def before_start_hook():142        raise CustomException()143    @gossip.register('slash.session_end')144    def hook():145        checkpoint()146    with slash.Session() as s:147        with pytest.raises(CustomException):148            with s.get_started_context():149                pass150    [err] = s.results.global_result.get_errors()  # pylint: disable=unbalanced-tuple-unpacking151    assert 'CustomException' in str(err)152    assert not checkpoint.called153#### Older tests below, need modernizing ####154class HookCallingTest(_TestCase):155    def setUp(self):156        super(HookCallingTest, self).setUp()157        self.plugin1 = make_custom_plugin("plugin1", self)158        self.plugin2 = make_custom_plugin("plugin2", self, hook_names=["before_session_start", "session_start", "after_session_start"])159        self.addCleanup(plugins.manager.uninstall, self.plugin1)160        self.addCleanup(plugins.manager.uninstall, self.plugin2)161    def test_hook_calling_order(self):162        # pylint: disable=no-member163        # expect:164        with self.forge.any_order():165            self.plugin1.activate()166            self.plugin2.activate()167        with self.forge.any_order():168            self.plugin1.before_session_start()169            self.plugin2.before_session_start()170        with self.forge.any_order():171            self.plugin1.session_start()172            self.plugin2.session_start()173        with self.forge.any_order():174            self.plugin1.after_session_start()175            self.plugin2.after_session_start()176        self.plugin1.session_end()177        self.plugin1.after_session_end()178        self.forge.replay()179        # get:180        plugins.manager.install(self.plugin1, activate=True)181        plugins.manager.install(self.plugin2, activate=True)182        with slash.Session() as s:183            with s.get_started_context():184                pass185def make_custom_plugin(name, test, hook_names=None):186    class CustomPlugin(PluginInterface):187        def get_name(self):188            return name189    CustomPlugin.__name__ = name190    if hook_names is None:191        with vintage.get_no_deprecations_context():192            hook_names = [hook_name for hook_name, _ in slash.hooks.get_all_hooks()]193    for hook_name in hook_names:194        setattr(CustomPlugin, hook_name, test.forge.create_wildcard_function_stub(name=hook_name))195    setattr(CustomPlugin, "activate", test.forge.create_wildcard_function_stub(name="activate"))...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!!
