Best Python code snippet using pytest-play_python
test_engine.py
Source:test_engine.py
1import pytest2import mock3def test_play_engine_constructor(request):4 from pytest_play.engine import PlayEngine5 executor = PlayEngine(request, {'foo': 'bar'})6 assert executor.request is request7 assert executor.variables == {'foo': 'bar'}8def test_get_file_contents(play, data_base_path):9 play.get_file_contents(data_base_path, 'included.yml')10def test_register_teardown(play, data_base_path):11 assert play._teardown == []12 import mock13 callback = mock.MagicMock()14 play.register_teardown_callback(callback)15 play.register_teardown_callback(callback)16 assert callback in play._teardown17 assert len(play._teardown) == 118 assert not callback.called19 play.teardown()20 assert callback.assert_called_once_with() is None21def test_executor_parametrize(dummy_executor):22 assert dummy_executor.parametrize('$foo') == 'bar'23@pytest.mark.parametrize("expr,expected", [24 ('{! variables["foo"].upper() !}', 'BAR')])25def test_executor_parametrize_expression(dummy_executor, expr, expected):26 assert dummy_executor.parametrize(27 expr) == expected28def test_execute(dummy_executor):29 execute_command_mock = mock.MagicMock()30 dummy_executor.execute_command = execute_command_mock31 yml_data = [32 {'provider': 'python', 'type': 'assert', 'expression': '1'},33 {'provider': 'python', 'type': 'assert', 'expression': '2'}34 ]35 dummy_executor.execute(yml_data)36 calls = [37 mock.call(yml_data[0]),38 mock.call(yml_data[1]),39 ]40 assert dummy_executor.execute_command.assert_has_calls(41 calls, any_order=False) is None42def test_execute_extra_vars(dummy_executor):43 execute_command_mock = mock.MagicMock()44 dummy_executor.execute_command = execute_command_mock45 yml_data = [46 {'provider': 'python', 'type': 'assert', 'expression': '1'},47 {'provider': 'python', 'type': 'assert',48 'expression': '2 == $does_not_exist'}49 ]50 assert 'does_not_exist' not in dummy_executor.variables51 dummy_executor.execute(yml_data, extra_variables={'does_not_exist': '2'})52 calls = [53 mock.call(yml_data[0]),54 mock.call(yml_data[1]),55 ]56 assert dummy_executor.execute_command.assert_has_calls(57 calls, any_order=False) is None58def test_execute_bad_type(dummy_executor):59 command = {'provider': 'python', 'typeXX': 'assert', 'expression': '1'}60 with pytest.raises(KeyError):61 dummy_executor.execute_command(command)62def test_execute_bad_command(dummy_executor):63 command = {'provider': 'python', 'type': 'assert', 'expressionXX': '1'}64 with pytest.raises(KeyError):65 dummy_executor.execute_command(command)66def test_execute_not_implemented_command(dummy_executor):67 command = {'provider': 'python', 'type': 'new_command',68 'param': 'http://1'}69 dummy_executor.COMMANDS = ['new_command']70 with pytest.raises(NotImplementedError):71 dummy_executor.execute_command(command)72def test_execute_condition_true(dummy_executor):73 command = {'provider': 'python',74 'type': 'assert',75 'expression': 'False',76 'skip_condition': '1 == 1'}77 dummy_executor.execute_command(command)78def test_execute_condition_false(dummy_executor):79 command = {'provider': 'python',80 'type': 'assert',81 'expression': 'True',82 'skip_condition': '1 == 0'}83 dummy_executor.execute_command(command)84def test_execute_get_basestring(dummy_executor):85 import yaml86 command = yaml.load("""87---88provider: python89type: assert90expression: 1 == 191 """)92 dummy_executor.execute_command(command)93def test_execute_get_basestring_param(dummy_executor):94 import yaml95 command = yaml.load("""96---97provider: python98type: assert99expression: "'$foo' == 'bar'"100""")101 dummy_executor.execute_command(command)102def test_new_provider_custom_command(dummy_executor):103 command = {'type': 'newCommand', 'provider': 'newprovider'}104 dummy_provider = mock.MagicMock()105 with pytest.raises(ValueError):106 dummy_executor.execute_command(command)107 dummy_executor.register_command_provider(108 dummy_provider, 'newprovider')109 # execute new custom command110 dummy_executor.execute_command(command)111 assert dummy_provider.assert_called_once_with(dummy_executor) is None112 assert dummy_provider \113 .return_value \114 .command_newCommand \115 .assert_called_once_with(command) is None116def test_execute_includes(dummy_executor, data_base_path):117 yml_data = [118 {'type': 'include', 'provider': 'include',119 'path': '{0}/{1}'.format(120 data_base_path, 'included.yml')},121 {'type': 'include', 'provider': 'include',122 'path': '{0}/{1}'.format(123 data_base_path, 'assertion.yml')},124 ]125 dummy_executor.execute(yml_data)126 assert dummy_executor.variables['included'] == 1127def test_default_command(play, data_base_path):128 play.variables['include'] = {'comment': 'default comment'}129 play.get_command_provider = mock.MagicMock()130 yml_data = [131 {"provider": "include", "type": "include",132 "path": "{0}/included.yml".format(data_base_path)},133 ]134 from copy import deepcopy135 expected_command = deepcopy(yml_data)[0]136 expected_command['comment'] = 'default comment'137 play.execute(yml_data)138 assert play \139 .get_command_provider \140 .return_value \141 .command_include \142 .assert_called_once_with(143 expected_command) is None144def test_default_command_override(play, data_base_path):145 play.variables['include'] = {'comment': 'default comment'}146 play.get_command_provider = mock.MagicMock()147 yml_data = [148 {"provider": "include", "type": "include",149 "comment": "override",150 "path": "{0}/included.yml".format(data_base_path)},151 ]152 from copy import deepcopy153 expected_command = deepcopy(yml_data)[0]154 expected_command['comment'] = 'override'155 play.execute(yml_data)156 assert play \157 .get_command_provider \158 .return_value \159 .command_include \160 .assert_called_once_with(161 expected_command) is None162def test_default_command_override_dict(play, data_base_path):163 play.variables['include'] = {164 'comment': {'comment': 'default comment'}}165 play.get_command_provider = mock.MagicMock()166 yml_data = [167 {"provider": "include", "type": "include",168 "comment": {"another": "override"},169 "path": "{0}/included.yml".format(data_base_path)},170 ]171 from copy import deepcopy172 expected_command = deepcopy(yml_data)[0]173 expected_command['comment'] = {174 'another': 'override', 'comment': 'default comment'}175 play.execute(yml_data)176 assert play \177 .get_command_provider \178 .return_value \179 .command_include \180 .assert_called_once_with(181 expected_command) is None182def test_default_command_override_dict_2(play, data_base_path):183 play.variables['include'] = {184 'comment': {'comment': 'default comment'}}185 play.get_command_provider = mock.MagicMock()186 yml_data = [187 {"provider": "include", "type": "include",188 "comment": {"another": "override", "comment": "other"},189 "path": "{0}/included.yml".format(data_base_path)},190 ]191 from copy import deepcopy192 expected_command = deepcopy(yml_data)[0]193 expected_command['comment'] = {194 'another': 'override', 'comment': 'other'}195 play.execute(yml_data)196 assert play \197 .get_command_provider \198 .return_value \199 .command_include \200 .assert_called_once_with(201 expected_command) is None202def test_default_command_override_dict_4(203 play, data_base_path):204 play.variables['include'] = {205 'comment': {'comment': 'default comment'}}206 play.get_command_provider = mock.MagicMock()207 yml_data = [208 {"provider": "include", "type": "include",209 "comment": "default comment",210 "path": "{0}/included.yml".format(data_base_path)},211 ]212 from copy import deepcopy213 expected_command = deepcopy(yml_data)[0]214 expected_command['comment'] = 'default comment'215 play.execute(yml_data)216 assert play \217 .get_command_provider \218 .return_value \219 .command_include \220 .assert_called_once_with(221 expected_command) is None222def test_default_command_override_dict_3(223 play, data_base_path):224 play.variables['include'] = {225 'comment': 'default comment'}226 play.get_command_provider = mock.MagicMock()227 yml_data = [228 {"provider": "include", "type": "include",229 "comment": {"another": "override", "comment": "other"},230 "path": "{0}/included.yml".format(data_base_path)},231 ]232 from copy import deepcopy233 expected_command = deepcopy(yml_data)[0]234 expected_command['comment'] = {235 'another': 'override', 'comment': 'other'}236 play.execute(yml_data)237 assert play \238 .get_command_provider \239 .return_value \240 .command_include \241 .assert_called_once_with(242 expected_command) is None243def test_include_string(play, data_base_path):244 play.variables['foo'] = 'bar'245 yml_data = """246---247- provider: include248 type: include249 path: "%s/included.yml"250- provider: python251 type: assert252 expression: "$included == 1"253- provider: python254 type: store_variable255 name: included256 expression: "2"257 comment: update included value from 1 to 2258- provider: python259 type: assert260 expression: "$included == 2"261 """ % data_base_path262 play.execute_raw(yml_data)263 assert play.variables['included'] == 2264def test_teardown(play):265 import mock266 play._teardown = [267 mock.MagicMock(side_effect=AttributeError()),268 mock.MagicMock()]269 play.teardown()270 assert play._teardown[0].assert_called_once_with() is None271 assert play._teardown[1].assert_called_once_with() is None272def test_elapsed_variable(play):273 command = {'provider': 'python',274 'type': 'assert',275 'expression': 'True', }276 assert '_elapsed' not in play.variables277 play.execute_command(command)...
engine.py
Source:engine.py
...142 command, default_flow_style=False))143 )144 command_type = command['type']145 provider_name = command.get('provider', 'default')146 command_provider = self.get_command_provider(provider_name)147 if command_provider is None:148 logger.error('Not supported provider %r', command)149 raise ValueError('Command not supported',150 command_type,151 provider_name)152 method_name = 'command_{0}'.format(command_type)153 method = getattr(command_provider, method_name, None)154 if method is None:155 logger.error('Not supported command %r', command)156 raise NotImplementedError(157 'Command not implemented', command_type, provider_name)158 logger.info('Executing command %r', command)159 start_time = time.time()160 try:161 return_value = method(command, **kwargs)162 except Exception:163 logger.error('FAILED command %r', command)164 logger.info('DUMP variables %r', self.variables)165 print(self.variables)166 raise167 finally:168 elapsed = time.time() - start_time169 print(dict(command, _elapsed=elapsed))170 self.update_variables({'_elapsed': elapsed})171 return return_value172 def update_variables(self, extra_variables):173 """ Update variables """174 self.variables.update(extra_variables)175 logger.debug("Variables updated %r", self.variables)176 # register commands177 def register_plugins(self):178 """ Auto register plugins and command providers"""179 for entrypoint in pkg_resources.iter_entry_points('playcommands'):180 plugin = entrypoint.load()181 self.register_command_provider(plugin, entrypoint.name)182 def register_command_provider(self, factory, name):183 """ Register command provider """184 self.gsm.registerUtility(185 factory(self),186 ICommandProvider,187 name,188 )189 def get_command_provider(self, name):190 """ Get command provider by 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!!