How to use defined_fixture method in Slash

Best Python code snippet using slash

conftest.py

Source:conftest.py Github

copy

Full Screen

...150 def finalize(): # pylint: disable=unused-variable151 returned.__exit__(None, None, None)152 return returned153@pytest.fixture(params=["slashconf", "module"])154def defined_fixture(request, suite, suite_test):155 if request.param == 'slashconf':156 return suite.slashconf.add_fixture()157 elif request.param == 'module':158 return suite_test.file.add_fixture()159 raise NotImplementedError() # pragma: no cover160@pytest.fixture161def gc_marker():162 return GarbageCollectionMarker()163@pytest.fixture(autouse=True, scope="function")164def reset_gossip(request):165 @request.addfinalizer166 def cleanup(): # pylint: disable=unused-variable167 for group in list(gossip.get_groups()):168 if group.name == 'slash':...

Full Screen

Full Screen

test_hook_calling.py

Source:test_hook_calling.py Github

copy

Full Screen

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"))...

Full Screen

Full Screen

test_fixtures.py

Source:test_fixtures.py Github

copy

Full Screen

1import pytest2import operator3from functools import reduce4def test_fixtures(suite, suite_test, defined_fixture):5 suite_test.depend_on_fixture(defined_fixture)6 suite.run()7def test_fixture_cleanup_at_end_of_suite(suite):8 fixture = suite.slashconf.add_fixture()9 suite[-1].depend_on_fixture(fixture)10 cleanup = fixture.add_cleanup()11 summary = suite.run()12 assert cleanup in summary.events13def test_fixture_cleanup_failure_fails_test(suite, suite_test, defined_fixture):14 suite_test.depend_on_fixture(defined_fixture)15 defined_fixture.add_cleanup(extra_code=['raise Exception()'])16 suite_test.expect_error()17 suite.run()18def test_fixture_parameters(suite, suite_test, defined_fixture):19 defined_fixture.add_parameter()20 suite_test.depend_on_fixture(defined_fixture)21 summary = suite.run()22 all_results = summary.get_all_results_for_test(suite_test)23 num_combinations = reduce(operator.mul, (len(p.values) for p in defined_fixture.get_parameters()))24 assert len(all_results) == num_combinations25def test_fixture_dependency_chain(suite, suite_test):26 fixture1 = suite.slashconf.add_fixture()27 fixture1.add_parameter()28 fixture2 = suite.slashconf.add_fixture()29 fixture2.add_parameter()30 fixture2.depend_on_fixture(fixture1)31 suite_test.depend_on_fixture(fixture2)32 suite.run()33def test_fixture_dependency_both_directly_and_indirectly(suite, suite_test):34 fixture1 = suite.slashconf.add_fixture()35 num_values1 = 236 fixture1.add_parameter(num_values=num_values1)37 fixture2 = suite.slashconf.add_fixture()38 num_values2 = 339 fixture2.add_parameter(num_values=num_values2)40 fixture2.depend_on_fixture(fixture1)41 suite_test.depend_on_fixture(fixture1)42 suite_test.depend_on_fixture(fixture2)43 summary = suite.run()44 results = summary.get_all_results_for_test(suite_test)45 assert len(results) == num_values1 * num_values246def test_fixture_context(suite, suite_test):47 fixture1 = suite.slashconf.add_fixture()48 fixture1.append_line('assert this == slash.context.fixture')49 fixture2 = suite.slashconf.add_fixture()50 fixture2.append_line('assert this == slash.context.fixture')51 fixture2.depend_on_fixture(fixture1)52 suite_test.depend_on_fixture(fixture1)53 suite.run()54@pytest.mark.parametrize('where', [['before'], ['after'], ['before', 'after']])55def test_fixtures_in_before_after(suite, where):56 test_class = suite.files[-1].add_class()57 suite_test = test_class.add_method_test()58 fixture = suite.slashconf.add_fixture()59 fixture_event = fixture.add_event(name='fixture')60 assert len(suite_test.cls.tests) == 161 before = suite_test.cls.add_before_method()62 evt1 = before.add_event(name='before')63 after = suite_test.cls.add_after_method()64 evt2 = after.add_event(name='after')65 for func in before, after:66 if func.name in where:67 func.depend_on_fixture(fixture)68 func.append_line('assert {} == {}'.format(fixture.name, fixture.get_value_string()))69 summary = suite.run()70 assert evt1 in summary.events71 assert evt2 in summary.events72 assert fixture_event in summary.events73def test_fixture_and_parameter(suite, suite_test, get_fixture_location):74 fixture = get_fixture_location(suite_test).add_fixture()75 suite_test.add_parameter()76 suite_test.depend_on_fixture(fixture)77 suite.run()78def test_fixture_which_name_startswith_test(suite):79 fixture = suite.slashconf.add_fixture(name='test_my_fixture')80 suite[-1].depend_on_fixture(fixture)81 for test in suite:82 test.expect_deselect()83 summary = suite.run(expect_session_errors=True)84 assert not summary.ok()85 for output in [summary.get_console_output(),86 str(summary.session.results.global_result.get_errors()[0])]:87 assert 'Invalid fixture name' in output88def test_fixture_with_parameters(suite_builder):89 @suite_builder.first_file.add_code90 def __code__(): # pylint: disable=unused-variable91 import slash92 @slash.fixture93 @slash.parameters.iterate(my_param=['a',])94 def fixture_1(my_param): # pylint: disable=unused-variable95 yield my_param96 @slash.parameters.iterate(my_param=['b'])97 @slash.fixture98 def fixture_2(my_param): # pylint: disable=unused-variable99 yield my_param100 def test_a(fixture_1, fixture_2): # pylint: disable=unused-variable101 assert fixture_1 == 'a'102 assert fixture_2 == 'b'...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Slash automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful