How to use mock_run method in pytest-cov

Best Python code snippet using pytest-cov

test_command.py

Source:test_command.py Github

copy

Full Screen

1import distutils.errors2import os3import pathlib4import subprocess5import unittest.mock67import pytest8import setuptools.dist910import setuptools_antlr.command11from setuptools_antlr.command import AntlrGrammar, AntlrCommand121314@pytest.fixture(scope='module', autouse=True)15def ch_resources_dir(request):16 os.chdir('.')17 init_dir = pathlib.Path.cwd()18 local_dir = os.path.dirname(__file__)19 os.chdir(os.path.join(local_dir, 'resources'))2021 def fin():22 os.chdir(str(init_dir))23 request.addfinalizer(fin)242526class TestAntlrGrammar:27 def test_read_with_imports(self):28 grammar = AntlrGrammar(pathlib.Path('distributed', 'SomeGrammar.g4'))29 imports = set(grammar.read_imports())3031 assert len(imports) == 232 assert {'CommonTerminals', 'SharedRules'} == imports3334 def test_read_without_imports(self):35 grammar = AntlrGrammar(pathlib.Path('distributed', 'CommonTerminals.g4'))36 imports = grammar.read_imports()3738 assert not imports3940 def test_read_nonexistent_file(self):41 grammar = AntlrGrammar(pathlib.Path('FooBar.g4'))4243 # check if DistutilsFileError was thrown44 with pytest.raises(distutils.errors.DistutilsFileError) as excinfo:45 grammar.read_imports()46 assert excinfo.match('FooBar.g4')474849class TestAntlrCommand:50 @pytest.fixture(autouse=True)51 def command(self):52 dist = setuptools.dist.Distribution()53 return AntlrCommand(dist)5455 @pytest.fixture()56 def configured_command(self, monkeypatch, tmpdir, command):57 command._find_antlr = unittest.mock.Mock(return_value=pathlib.Path(58 'antlr-4.5.3-complete.jar'))59 command._find_grammars = unittest.mock.Mock(return_value=[60 AntlrGrammar(pathlib.Path('standalone/SomeGrammar.g4'))61 ])62 command.output['default'] = str(tmpdir.mkdir('gen'))6364 monkeypatch.setattr(setuptools_antlr.command, 'find_java',65 unittest.mock.Mock(return_value=pathlib.Path(66 'c:/path/to/java/bin/java.exe')))6768 return command6970 test_ids_find_antlr = ['single', 'multiple', 'none', 'invalid']7172 test_data_find_antlr = [73 ({'antlr-4.5.3-complete.jar'}, 'antlr-4.5.3-complete.jar'),74 ({'antlr-0.1.1-complete.jar', 'antlr-3.0-complete.jar', 'antlr-4.5.2-complete.jar',75 'antlr-4.5.3-complete.jar'},76 'antlr-4.5.3-complete.jar'),77 ({}, None),78 ({'antlr-runtime-4.5.3.jar'}, None)79 ]8081 @pytest.mark.parametrize('available_antlr_jars, expected_antlr_jar', test_data_find_antlr,82 ids=test_ids_find_antlr)83 def test_find_antlr(self, tmpdir, command, available_antlr_jars, expected_antlr_jar):84 ext_lib_dir = tmpdir.mkdir('lib')8586 for jar in available_antlr_jars:87 antlr_jar = ext_lib_dir.join(jar)88 antlr_jar.write('dummy')8990 with unittest.mock.patch.object(AntlrCommand, '_EXT_LIB_DIR', str(ext_lib_dir)):91 found_antlr_jar = command._find_antlr()9293 assert found_antlr_jar == (pathlib.Path(str(ext_lib_dir), expected_antlr_jar)94 if expected_antlr_jar else None)9596 test_ids_find_antlr_log = ['single', 'multiple', 'none', 'invalid']9798 test_data_find_antlr_log = [99 ({'antlr-2016-12-19-16.01.43.log'}, 'antlr-2016-12-19-16.01.43.log'),100 ({'antlr-2016-12-18-16.01.43.log', 'antlr-2016-12-19-16.01.43.log'},101 'antlr-2016-12-19-16.01.43.log'),102 ({}, None),103 ({'foobar-2016-12-19-16.01.43.log'}, None)104 ]105106 @pytest.mark.parametrize('available_antlr_logs, expected_antlr_log', test_data_find_antlr_log,107 ids=test_ids_find_antlr_log)108 def test_find_antlr_log(self, tmpdir, command, available_antlr_logs, expected_antlr_log):109 package_dir = tmpdir.mkdir('package')110111 for log in available_antlr_logs:112 antlr_log = package_dir.join(log)113 antlr_log.write('dummy')114115 found_antlr_log = command._find_antlr_log(pathlib.Path(str(package_dir)))116117 assert found_antlr_log == (pathlib.Path(str(package_dir), expected_antlr_log)118 if expected_antlr_log else None)119120 def test_find_grammars_empty(self, tmpdir, command):121 dsl_dir = tmpdir.mkdir('dsl')122 grammars = command._find_grammars(pathlib.Path(str(dsl_dir)))123124 assert len(grammars) == 0125126 def test_find_grammars_standalone(self, command):127 grammars = command._find_grammars(pathlib.Path('standalone'))128129 some_grammar = AntlrGrammar(pathlib.Path('standalone/SomeGrammar.g4'))130131 assert len(grammars) == 1132 assert some_grammar in grammars133134 def test_find_grammars_distributed(self, command):135 grammars = command._find_grammars(pathlib.Path('distributed'))136137 common_terminals = AntlrGrammar(pathlib.Path('distributed/CommonTerminals.g4'))138 shared_rules = AntlrGrammar(pathlib.Path('distributed/SharedRules.g4'))139 some_grammar = AntlrGrammar(pathlib.Path('distributed/SomeGrammar.g4'))140141 shared_rules.dependencies.append(common_terminals)142 some_grammar.dependencies.append(common_terminals)143 some_grammar.dependencies.append(shared_rules)144145 assert len(grammars) == 3146 assert common_terminals in grammars147 assert shared_rules in grammars148 assert some_grammar in grammars149150 def test_find_grammars_incomplete(self, command):151 # check if DistutilsFileError was thrown152 with pytest.raises(distutils.errors.DistutilsFileError) as excinfo:153 command._find_grammars(pathlib.Path('incomplete'))154 assert excinfo.match('CommonTerminals')155156 def test_create_init_file_not_exists(self, tmpdir, command):157 path = pathlib.Path(str(tmpdir.mkdir('package')))158159 init_file = pathlib.Path(path, '__init__.py')160161 created = command._create_init_file(path)162163 assert created164 assert init_file.exists()165166 def test_create_init_file_exists(self, tmpdir, command):167 path = pathlib.Path(str(tmpdir.mkdir('package')))168169 init_file = pathlib.Path(path, '__init__.py')170 init_file.touch()171 origin_init_mtime_ns = init_file.stat().st_mtime_ns172173 created = command._create_init_file(path)174175 assert not created176 assert init_file.stat().st_mtime_ns == origin_init_mtime_ns177178 def test_finalize_options_default(self, command):179 command.finalize_options()180181 assert command.grammars is None182 assert pathlib.Path(command.output['default']) == pathlib.Path('.')183 assert command.atn == 0184 assert command.encoding is None185 assert command.message_format is None186 assert command.long_messages == 0187 assert command.listener == 1188 assert command.visitor == 0189 assert command.depend == 0190 assert command.grammar_options['language'] == 'Python3'191 assert command.w_error == 0192 assert command.x_dbg_st == 0193 assert command.x_dbg_st_wait == 0194 assert command.x_force_atn == 0195 assert command.x_log == 0196197 def test_finalize_options_grammars_single(self, command):198 command.grammars = 'Foo'199 command.finalize_options()200201 assert 'Foo' in command.grammars202203 def test_finalize_options_grammars_multiple(self, command):204 command.grammars = 'Foo Bar'205 command.finalize_options()206207 assert 'Foo' in command.grammars208 assert 'Bar' in command.grammars209210 def test_finalize_options_default_output_dir(self, command):211 command.output = 'default=.'212 command.finalize_options()213214 assert pathlib.Path(command.output['default']) == pathlib.Path('.')215216 def test_finalize_options_custom_output_dir(self, command):217 command.output = 'Foo=custom'218 command.finalize_options()219220 assert pathlib.Path(command.output['default']) == pathlib.Path('.')221 assert pathlib.Path(command.output['Foo']) == pathlib.Path('custom')222223 def test_finalize_options_custom_default_output_dir(self, command):224 command.output = 'default=custom'225 command.finalize_options()226227 assert pathlib.Path(command.output['default']) == pathlib.Path('custom')228229 def test_finalize_options_grammar_options_language(self, command):230 command.grammar_options = 'language=Python3'231 command.finalize_options()232233 assert command.grammar_options['language'] == 'Python3'234235 def test_finalize_options_grammar_options_invalid(self, command):236 command.grammar_options = 'language=Java'237238 with pytest.raises(distutils.errors.DistutilsOptionError) as excinfo:239 command.finalize_options()240 assert excinfo.match('Java')241242 def test_finalize_options_grammar_options_multiple(self, command):243 command.grammar_options = 'superClass=Abc tokenVocab=Lexer'244 command.finalize_options()245246 assert command.grammar_options['language'] == 'Python3'247 assert command.grammar_options['superClass'] == 'Abc'248 assert command.grammar_options['tokenVocab'] == 'Lexer'249250 def test_finalize_options_debugging_options_invalid(self, capsys, command):251 command.x_dbg_st = 0252 command.x_dbg_st_wait = 1253 command.finalize_options()254255 # check if error was logged256 _, err = capsys.readouterr()257 assert 'Waiting for StringTemplate visualizer' in err258259 @unittest.mock.patch('setuptools_antlr.command.find_java')260 @unittest.mock.patch('subprocess.run')261 @unittest.mock.patch.object(AntlrCommand, '_find_grammars')262 def test_run_java_found(self, mock_find_grammars, mock_run, mock_find_java, tmpdir, command):263 java_exe = pathlib.Path('c:/path/to/java/bin/java.exe')264265 mock_find_java.return_value = java_exe266 mock_find_grammars.return_value = [AntlrGrammar(pathlib.Path('standalone/SomeGrammar.g4'))]267 mock_run.return_value = subprocess.CompletedProcess([], 0)268269 command.output['default'] = str(tmpdir.mkdir('gen'))270 command.run()271272 args, _ = mock_run.call_args273 assert mock_run.called274 assert str(java_exe) in args[0]275 assert '-jar' in args[0]276277 @unittest.mock.patch('setuptools_antlr.command.find_java')278 def test_run_java_not_found(self, mock_find_java, command):279 mock_find_java.return_value = None280281 with pytest.raises(distutils.errors.DistutilsExecError) as excinfo:282 command.run()283 assert excinfo.match('no compatible JRE')284285 @unittest.mock.patch('setuptools_antlr.command.find_java')286 @unittest.mock.patch.object(AntlrCommand, '_find_antlr')287 @unittest.mock.patch('subprocess.run')288 @unittest.mock.patch.object(AntlrCommand, '_find_grammars')289 def test_run_antlr_found(self, mock_find_grammars, mock_run, mock_find_antlr, mock_find_java,290 tmpdir, command):291 java_exe = pathlib.Path('c:/path/to/java/bin/java.exe')292 antlr_jar = pathlib.Path('antlr-4.5.3-complete.jar')293294 mock_find_java.return_value = java_exe295 mock_find_antlr.return_value = antlr_jar296 mock_find_grammars.return_value = [AntlrGrammar(pathlib.Path('standalone/SomeGrammar.g4'))]297 mock_run.return_value = unittest.mock.Mock(returncode=0)298299 command.output['default'] = str(tmpdir.mkdir('gen'))300 command.run()301302 args, _ = mock_run.call_args303 assert mock_run.called304 assert str(antlr_jar) in args[0]305306 @unittest.mock.patch('setuptools_antlr.command.find_java')307 @unittest.mock.patch.object(AntlrCommand, '_find_antlr')308 def test_run_antlr_not_found(self, mock_find_antlr, mock_find_java, command):309 java_exe = pathlib.Path('c:/path/to/java/bin/java.exe')310311 mock_find_java.return_value = java_exe312 mock_find_antlr.return_value = None313314 with pytest.raises(distutils.errors.DistutilsExecError) as excinfo:315 command.run()316 assert excinfo.match('no ANTLR jar')317318 @pytest.mark.usefixtures('configured_command')319 @unittest.mock.patch('subprocess.run')320 def test_run_custom_output_dir(self, mock_run, tmpdir, configured_command):321 mock_run.return_value = unittest.mock.Mock(returncode=0)322323 configured_command._find_grammars = unittest.mock.Mock(return_value=[324 AntlrGrammar(pathlib.Path('Foo.g4')),325 ])326327 custom_output_dir = str(tmpdir.mkdir('custom'))328 configured_command.output['Foo'] = custom_output_dir329 configured_command.run()330331 args, _ = mock_run.call_args332 assert mock_run.call_count == 1333 custom_package_path = pathlib.Path(custom_output_dir, 'foo').absolute()334 assert any(custom_package_path == pathlib.Path(a) for a in args[0])335336 @pytest.mark.usefixtures('configured_command')337 @unittest.mock.patch('subprocess.run')338 def test_run_grammars_multiple(self, mock_run, configured_command):339 mock_run.return_value = unittest.mock.Mock(returncode=0)340341 configured_command._find_grammars = unittest.mock.Mock(return_value=[342 AntlrGrammar(pathlib.Path('Foo.g4')),343 AntlrGrammar(pathlib.Path('Bar.g4'))344 ])345346 configured_command.grammars = ['Foo']347 configured_command.run()348349 args, _ = mock_run.call_args350 assert mock_run.call_count == 1351 assert 'Foo.g4' in args[0]352353 @pytest.mark.usefixtures('configured_command')354 @unittest.mock.patch('subprocess.run')355 def test_run_grammars_multiple(self, mock_run, configured_command):356 mock_run.return_value = unittest.mock.Mock(returncode=0)357358 configured_command._find_grammars = unittest.mock.Mock(return_value=[359 AntlrGrammar(pathlib.Path('Foo.g4')),360 AntlrGrammar(pathlib.Path('Bar.g4'))361 ])362363 configured_command.grammars = ['Foo', 'Bar']364 configured_command.run()365366 assert mock_run.call_count == 2367 args, _ = mock_run.call_args_list[0]368 assert 'Foo.g4' in args[0]369 args, _ = mock_run.call_args_list[1]370 assert 'Bar.g4' in args[0]371372 @pytest.mark.usefixtures('configured_command')373 @unittest.mock.patch('subprocess.run')374 def test_run_grammars_not_found(self, mock_run, configured_command):375 mock_run.return_value = unittest.mock.Mock(returncode=0)376377 configured_command._find_grammars = unittest.mock.Mock(return_value=[378 AntlrGrammar(pathlib.Path('Foo.g4'))379 ])380381 configured_command.grammars = ['Bar']382 configured_command.run()383384 assert mock_run.call_count == 0385386 @pytest.mark.usefixtures('configured_command')387 @unittest.mock.patch('subprocess.run')388 def test_run_atn_enabled(self, mock_run, configured_command):389 mock_run.return_value = unittest.mock.Mock(returncode=0)390391 configured_command.atn = 1392 configured_command.run()393394 args, _ = mock_run.call_args395 assert mock_run.called396 assert '-atn' in args[0]397398 @pytest.mark.usefixtures('configured_command')399 @unittest.mock.patch('subprocess.run')400 def test_run_atn_disabled(self, mock_run, configured_command):401 mock_run.return_value = unittest.mock.Mock(returncode=0)402403 configured_command.atn = 0404 configured_command.run()405406 args, _ = mock_run.call_args407 assert mock_run.called408 assert '-atn' not in args[0]409410 @pytest.mark.usefixtures('configured_command')411 @unittest.mock.patch('subprocess.run')412 def test_run_encoding_specified(self, mock_run, configured_command):413 mock_run.return_value = unittest.mock.Mock(returncode=0)414415 configured_command.encoding = 'euc-jp'416 configured_command.run()417418 args, _ = mock_run.call_args419 assert mock_run.called420 assert '-encoding' in args[0]421 assert 'euc-jp' in args[0]422423 @pytest.mark.usefixtures('configured_command')424 @unittest.mock.patch('subprocess.run')425 def test_run_encoding_not_specified(self, mock_run, configured_command):426 mock_run.return_value = unittest.mock.Mock(returncode=0)427428 configured_command.encoding = None429 configured_command.run()430431 args, _ = mock_run.call_args432 assert mock_run.called433 assert '-encoding' not in args[0]434435 @pytest.mark.usefixtures('configured_command')436 @unittest.mock.patch('subprocess.run')437 def test_run_message_format_specified(self, mock_run, configured_command):438 mock_run.return_value = unittest.mock.Mock(returncode=0)439440 configured_command.message_format = 'gnu'441 configured_command.run()442443 args, _ = mock_run.call_args444 assert mock_run.called445 assert '-message-format' in args[0]446 assert 'gnu' in args[0]447448 @pytest.mark.usefixtures('configured_command')449 @unittest.mock.patch('subprocess.run')450 def test_run_message_format_not_specified(self, mock_run, configured_command):451 mock_run.return_value = unittest.mock.Mock(returncode=0)452453 configured_command.message_format = None454 configured_command.run()455456 args, _ = mock_run.call_args457 assert mock_run.called458 assert '-message-format' not in args[0]459460 @pytest.mark.usefixtures('configured_command')461 @unittest.mock.patch('subprocess.run')462 def test_run_long_messages_enabled(self, mock_run, configured_command):463 mock_run.return_value = unittest.mock.Mock(returncode=0)464465 configured_command.long_messages = 1466 configured_command.run()467468 args, _ = mock_run.call_args469 assert mock_run.called470 assert '-long-messages' in args[0]471472 @pytest.mark.usefixtures('configured_command')473 @unittest.mock.patch('subprocess.run')474 def test_run_long_messages_disabled(self, mock_run, configured_command):475 mock_run.return_value = unittest.mock.Mock(returncode=0)476477 configured_command.long_messages = 0478 configured_command.run()479480 args, _ = mock_run.call_args481 assert mock_run.called482 assert '-long-messages' not in args[0]483484 @pytest.mark.usefixtures('configured_command')485 @unittest.mock.patch('subprocess.run')486 def test_run_listener_enabled(self, mock_run, configured_command):487 mock_run.return_value = unittest.mock.Mock(returncode=0)488489 configured_command.listener = 1490 configured_command.run()491492 args, _ = mock_run.call_args493 assert mock_run.called494 assert '-listener' in args[0]495496 @pytest.mark.usefixtures('configured_command')497 @unittest.mock.patch('subprocess.run')498 def test_run_listener_disabled(self, mock_run, configured_command):499 mock_run.return_value = unittest.mock.Mock(returncode=0)500501 configured_command.listener = 0502 configured_command.run()503504 args, _ = mock_run.call_args505 assert mock_run.called506 assert '-no-listener' in args[0]507508 @pytest.mark.usefixtures('configured_command')509 @unittest.mock.patch('subprocess.run')510 def test_run_visitor_enabled(self, mock_run, configured_command):511 mock_run.return_value = unittest.mock.Mock(returncode=0)512513 configured_command.visitor = 1514 configured_command.run()515516 args, _ = mock_run.call_args517 assert mock_run.called518 assert '-visitor' in args[0]519520 @pytest.mark.usefixtures('configured_command')521 @unittest.mock.patch('subprocess.run')522 def test_run_visitor_disabled(self, mock_run, configured_command):523 mock_run.return_value = unittest.mock.Mock(returncode=0)524525 configured_command.visitor = 0526 configured_command.run()527528 args, _ = mock_run.call_args529 assert mock_run.called530 assert '-no-visitor' in args[0]531532 @pytest.mark.usefixtures('configured_command')533 @unittest.mock.patch('subprocess.run')534 def test_run_grammar_options_specified(self, mock_run, configured_command):535 mock_run.return_value = unittest.mock.Mock(returncode=0)536537 configured_command.grammar_options = {'superClass': 'Foo', 'tokenVocab': 'Bar'}538 configured_command.run()539540 args, _ = mock_run.call_args541 assert mock_run.called542 assert '-DsuperClass=Foo' in args[0]543 assert '-DtokenVocab=Bar' in args[0]544545 @pytest.mark.usefixtures('configured_command')546 @unittest.mock.patch('subprocess.run')547 def test_run_grammar_options_not_specified(self, mock_run, configured_command):548 mock_run.return_value = unittest.mock.Mock(returncode=0)549550 configured_command.grammar_options = {}551 configured_command.run()552553 args, _ = mock_run.call_args554 assert mock_run.called555 assert not any(a.startswith('-D') for a in args[0])556557 @pytest.mark.usefixtures('configured_command')558 @unittest.mock.patch('subprocess.run')559 def test_run_depend_enabled(self, mock_run, configured_command):560 mock_run.return_value = unittest.mock.Mock(returncode=0, stdout='FooParser.py : Foo.g4')561562 configured_command.depend = 1563 configured_command.run()564565 args, _ = mock_run.call_args566 assert mock_run.called567 assert '-depend' in args[0]568569 @pytest.mark.usefixtures('configured_command')570 @unittest.mock.patch('subprocess.run')571 def test_run_depend_disabled(self, mock_run, configured_command):572 mock_run.return_value = unittest.mock.Mock(returncode=0)573 configured_command.depend = 0574 configured_command.run()575576 args, _ = mock_run.call_args577 assert mock_run.called578 assert '-depend' not in args[0]579580 @pytest.mark.usefixtures('configured_command')581 @unittest.mock.patch('subprocess.run')582 def test_run_w_error_enabled(self, mock_run, configured_command):583 mock_run.return_value = unittest.mock.Mock(returncode=0)584585 configured_command.w_error = 1586 configured_command.run()587588 args, _ = mock_run.call_args589 assert mock_run.called590 assert '-Werror' in args[0]591592 @pytest.mark.usefixtures('configured_command')593 @unittest.mock.patch('subprocess.run')594 def test_run_w_error_disabled(self, mock_run, configured_command):595 mock_run.return_value = unittest.mock.Mock(returncode=0)596597 configured_command.w_error = 0598 configured_command.run()599600 args, _ = mock_run.call_args601 assert mock_run.called602 assert '-Werror' not in args[0]603604 @pytest.mark.usefixtures('configured_command')605 @unittest.mock.patch('subprocess.run')606 def test_run_x_dbg_st_enabled(self, mock_run, configured_command):607 mock_run.return_value = unittest.mock.Mock(returncode=0)608609 configured_command.x_dbg_st = 1610 configured_command.run()611612 args, _ = mock_run.call_args613 assert mock_run.called614 assert '-XdbgST' in args[0]615616 @pytest.mark.usefixtures('configured_command')617 @unittest.mock.patch('subprocess.run')618 def test_run_x_dbg_st_disabled(self, mock_run, configured_command):619 mock_run.return_value = unittest.mock.Mock(returncode=0)620621 configured_command.x_dbg_st = 0622 configured_command.run()623624 args, _ = mock_run.call_args625 assert mock_run.called626 assert '-XdbgST' not in args[0]627628 @pytest.mark.usefixtures('configured_command')629 @unittest.mock.patch('subprocess.run')630 def test_run_x_dbg_st_wait_enabled(self, mock_run, configured_command):631 mock_run.return_value = unittest.mock.Mock(returncode=0)632633 configured_command.x_dbg_st_wait = 1634 configured_command.run()635636 args, _ = mock_run.call_args637 assert mock_run.called638 assert '-XdbgSTWait' in args[0]639640 @pytest.mark.usefixtures('configured_command')641 @unittest.mock.patch('subprocess.run')642 def test_run_x_dbg_st_wait_disabled(self, mock_run, configured_command):643 mock_run.return_value = unittest.mock.Mock(returncode=0)644645 configured_command.x_dbg_st_wait = 0646 configured_command.run()647648 args, _ = mock_run.call_args649 assert mock_run.called650 assert '-XdbgSTWait' not in args[0]651652 @pytest.mark.usefixtures('configured_command')653 @unittest.mock.patch('subprocess.run')654 def test_run_x_exact_output_dir_enabled(self, mock_run, configured_command):655 mock_run.return_value = unittest.mock.Mock(returncode=0)656657 configured_command.x_exact_output_dir = 1658 configured_command.run()659660 args, _ = mock_run.call_args661 assert mock_run.called662 assert '-Xexact-output-dir' in args[0]663664 @pytest.mark.usefixtures('configured_command')665 @unittest.mock.patch('subprocess.run')666 def test_run_x_exact_output_dir_disabled(self, mock_run, configured_command):667 mock_run.return_value = unittest.mock.Mock(returncode=0)668669 configured_command.x_exact_output_dir = 0670 configured_command.run()671672 args, _ = mock_run.call_args673 assert mock_run.called674 assert '-Xexact-output-dir' not in args[0]675676 @pytest.mark.usefixtures('configured_command')677 @unittest.mock.patch('subprocess.run')678 def test_run_x_force_atn_wait_enabled(self, mock_run, configured_command):679 mock_run.return_value = unittest.mock.Mock(returncode=0)680681 configured_command.x_force_atn = 1682 configured_command.run()683684 args, _ = mock_run.call_args685 assert mock_run.called686 assert '-Xforce-atn' in args[0]687688 @pytest.mark.usefixtures('configured_command')689 @unittest.mock.patch('subprocess.run')690 def test_run_x_force_atn_disabled(self, mock_run, configured_command):691 mock_run.return_value = unittest.mock.Mock(returncode=0)692693 configured_command.x_force_atn = 0694 configured_command.run()695696 args, _ = mock_run.call_args697 assert mock_run.called698 assert '-Xforce-atn' not in args[0]699700 @pytest.mark.usefixtures('configured_command')701 @unittest.mock.patch('subprocess.run')702 @unittest.mock.patch.object(AntlrCommand, '_find_antlr_log')703 @unittest.mock.patch('shutil.move')704 def test_run_x_log_enabled(self, mock_move, mock_find_antlr_log, mock_run, capsys,705 configured_command):706 log_file = 'antlr-2016-12-19-16.01.43.log'707 mock_run.return_value = unittest.mock.Mock(returncode=0)708 mock_find_antlr_log.return_value = pathlib.Path(log_file)709710 configured_command.x_log = 1711 configured_command.run()712713 args, _ = mock_run.call_args714 assert mock_run.called715 assert '-Xlog' in args[0]716717 args, _ = mock_move.call_args718 assert mock_move.called719 assert log_file in args[0]720721 @pytest.mark.usefixtures('configured_command')722 @unittest.mock.patch('subprocess.run')723 def test_run_x_log_disabled(self, mock_run, configured_command):724 mock_run.return_value = unittest.mock.Mock(returncode=0)725726 configured_command.x_log = 0727 configured_command.run()728729 args, _ = mock_run.call_args730 assert mock_run.called731 assert '-Xlog' not in args[0]732733 @pytest.mark.usefixtures('configured_command')734 @unittest.mock.patch('subprocess.run')735 @unittest.mock.patch.object(AntlrCommand, '_find_antlr_log')736 def test_run_x_log_not_found(self, mock_find_antlr_log, mock_run, capsys, configured_command):737 mock_run.return_value = unittest.mock.Mock(returncode=0)738 mock_find_antlr_log.return_value = None739740 configured_command.x_log = 1741 configured_command.run()742743 _, err = capsys.readouterr()744 assert 'no logging info dumped out by ANTLR' in err745746 @pytest.mark.usefixtures('configured_command')747 @unittest.mock.patch('subprocess.run')748 def test_run_parser_generation_successful(self, mock_run, configured_command):749 mock_run.return_value = unittest.mock.Mock(returncode=0)750751 configured_command.run()752753 args, kwargs = mock_run.call_args754 assert mock_run.called755 assert 'SomeGrammar.g4' in args[0]756 assert kwargs['cwd'] == 'standalone'757758 @pytest.mark.usefixtures('configured_command')759 @unittest.mock.patch('subprocess.run')760 def test_run_parser_generation_failed(self, mock_run, configured_command):761 mock_run.return_value = unittest.mock.Mock(returncode=-1)762763 with pytest.raises(distutils.errors.DistutilsExecError) as excinfo:764 configured_command.run()765 assert excinfo.match('SomeGrammar parser couldn\'t be generated')766767 @unittest.mock.patch('setuptools_antlr.command.find_java')768 @unittest.mock.patch.object(AntlrCommand, '_find_antlr')769 @unittest.mock.patch('subprocess.run')770 @unittest.mock.patch.object(AntlrCommand, '_find_grammars')771 def test_run_package_not_exists(self, mock_find_grammars, mock_run, mock_find_antlr,772 mock_find_java, tmpdir, command):773 java_exe = pathlib.Path('c:/path/to/java/bin/java.exe')774 antlr_jar = pathlib.Path('antlr-4.5.3-complete.jar')775 mock_find_java.return_value = java_exe776 mock_find_antlr.return_value = antlr_jar777778 grammar = AntlrGrammar(pathlib.Path('SomeGrammar.g4'))779 mock_find_grammars.return_value = [grammar]780 mock_run.return_value = unittest.mock.Mock(returncode=0)781782 base_dir = str(tmpdir.mkdir('base'))783 package_dir = pathlib.Path(base_dir, 'some_grammar')784785 package_init_file = pathlib.Path(package_dir, '__init__.py')786787 command.output['default'] = base_dir788 os.chdir(str(base_dir))789790 command.run()791792 assert package_init_file.exists()793794 @unittest.mock.patch('setuptools_antlr.command.find_java')795 @unittest.mock.patch.object(AntlrCommand, '_find_antlr')796 @unittest.mock.patch('subprocess.run')797 @unittest.mock.patch.object(AntlrCommand, '_find_grammars')798 def test_run_package_exists(self, mock_find_grammars, mock_run, mock_find_antlr, mock_find_java,799 tmpdir, command):800 java_exe = pathlib.Path('c:/path/to/java/bin/java.exe')801 antlr_jar = pathlib.Path('antlr-4.5.3-complete.jar')802 mock_find_java.return_value = java_exe803 mock_find_antlr.return_value = antlr_jar804805 grammar = AntlrGrammar(pathlib.Path('SomeGrammar.g4'))806 mock_find_grammars.return_value = [grammar]807 mock_run.return_value = unittest.mock.Mock(returncode=0)808809 base_dir = str(tmpdir.mkdir('base'))810 package_dir = pathlib.Path(base_dir, 'some_grammar')811 package_dir.mkdir()812813 package_init_file = pathlib.Path(package_dir, '__init__.py')814 package_init_file.touch()815816 origin_package_init_mtime_ns = package_init_file.stat().st_mtime_ns817818 command.output['default'] = base_dir819 command.run()820821 assert package_init_file.stat().st_mtime_ns == origin_package_init_mtime_ns822823 @unittest.mock.patch('setuptools_antlr.command.find_java')824 @unittest.mock.patch.object(AntlrCommand, '_find_antlr')825 @unittest.mock.patch('subprocess.run')826 @unittest.mock.patch.object(AntlrCommand, '_find_grammars')827 def test_run_one_library_location(self, mock_find_grammars, mock_run, mock_find_antlr,828 mock_find_java, tmpdir, command):829 java_exe = pathlib.Path('c:/path/to/java/bin/java.exe')830 antlr_jar = pathlib.Path('antlr-4.5.3-complete.jar')831 mock_find_java.return_value = java_exe832 mock_find_antlr.return_value = antlr_jar833834 grammar = AntlrGrammar(pathlib.Path('SomeGrammar.g4'))835 grammar.dependencies = [836 AntlrGrammar(pathlib.Path('shared/CommonTerminals.g4'))837 ]838 mock_find_grammars.return_value = [grammar]839 mock_run.return_value = unittest.mock.Mock(returncode=0)840841 command.output['default'] = str(tmpdir.mkdir('gen'))842 command.run()843844 args, _ = mock_run.call_args845 assert mock_run.called846 assert '-lib' in args[0]847 assert any(a.endswith('shared') for a in args[0])848849 @unittest.mock.patch('setuptools_antlr.command.find_java')850 @unittest.mock.patch.object(AntlrCommand, '_find_antlr')851 @unittest.mock.patch('subprocess.run')852 @unittest.mock.patch.object(AntlrCommand, '_find_grammars')853 def test_run_multiple_library_location(self, mock_find_grammars, mock_run, mock_find_antlr,854 mock_find_java, tmpdir, command):855 java_exe = pathlib.Path('c:/path/to/java/bin/java.exe')856 antlr_jar = pathlib.Path('antlr-4.5.3-complete.jar')857 mock_find_java.return_value = java_exe858 mock_find_antlr.return_value = antlr_jar859860 grammar = AntlrGrammar(pathlib.Path('SomeGrammar.g4'))861 grammar.dependencies = [862 AntlrGrammar(pathlib.Path('terminals/common.g4')),863 AntlrGrammar(pathlib.Path('rules/common.g4'))864 ]865 mock_find_grammars.return_value = [grammar]866 mock_run.return_value = unittest.mock.Mock(returncode=0)867868 command.output['default'] = str(tmpdir.mkdir('gen'))869870 with pytest.raises(distutils.errors.DistutilsOptionError) as excinfo:871 command.run()872 assert excinfo.match('Imported grammars of \'SomeGrammar\' are located in more than one ' ...

Full Screen

Full Screen

test_simplivity.py

Source:test_simplivity.py Github

copy

Full Screen

1#!/usr/bin/python2# -*- coding: utf-8 -*-3###4# Copyright (2019) Hewlett Packard Enterprise Development LP5#6# Licensed under the Apache License, Version 2.0 (the "License");7# You may not use this file except in compliance with the License.8# You may obtain a copy of the License at9#10# http://www.apache.org/licenses/LICENSE-2.011#12# Unless required by applicable law or agreed to in writing, software13# distributed under the License is distributed on an "AS IS" BASIS,14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15# See the License for the specific language governing permissions and16# limitations under the License.17###18import mock19import logging20import pytest21import sys22from module_utils import simplivity23SIMPLIVITY_MODULE_UTILS_PATH = 'module_utils.simplivity'24sys.modules['ansible.module_utils.simplivity'] = simplivity25from copy import deepcopy26from module_utils.simplivity import (SimplivityModule,27 OVC,28 SimplivityModuleException,29 SimplivityModuleValueError,30 _str_sorted,31 transform_list_to_dict,32 compare,33 get_logger)34MSG_GENERIC_ERROR = 'Generic error message'35MSG_GENERIC = "Generic message"36class StubResource(SimplivityModule):37 """Stub class to test the resource object"""38class TestSimplivityModule():39 """40 SimplivityModuleSpec provides the mocks used in this test case.41 """42 mock_ovc_client_from_json_file = None43 mock_ovc_client_from_env_vars = None44 mock_ansible_module = None45 mock_ansible_module_init = None46 mock_ovc_client = None47 MODULE_EXECUTE_RETURN_VALUE = dict(48 changed=True,49 msg=MSG_GENERIC,50 ansible_facts={'ansible_facts': None}51 )52 PARAMS_FOR_PRESENT = dict(53 config='config.json',54 state='present',55 data={'name': 'testname'}56 )57 RESOURCE_COMMON = {'id': '123456',58 'name': 'Resource Name'}59 EXPECTED_ARG_SPEC = {'config': {'type': 'path'},60 'ovc_ip': {'type': 'str'},61 'password': {'type': 'str', 'no_log': True},62 'username': {'type': 'str'}}63 @pytest.fixture(autouse=True)64 def setUp(self):65 # Define Simplivity Client Mock (FILE)66 patcher_json_file = mock.patch.object(OVC, 'from_json_file')67 self.mock_ovc_client_from_json_file = patcher_json_file.start()68 # Define Simplivity Client Mock69 self.mock_ovc_client = self.mock_ovc_client_from_json_file.return_value70 # Define Simplivity Client Mock (ENV)71 patcher_env = mock.patch.object(OVC, 'from_environment_variables')72 self.mock_ovc_client_from_env_vars = patcher_env.start()73 # Define Simplivity Module Mock74 patcher_ansible = mock.patch(SimplivityModule.__module__ + '.AnsibleModule')75 self.mock_ansible_module_init = patcher_ansible.start()76 self.mock_ansible_module = mock.Mock()77 self.mock_ansible_module_init.return_value = self.mock_ansible_module78 yield79 patcher_json_file.stop80 patcher_env.stop81 patcher_ansible.stop82 def test_should_call_simplivity_exception_with_a_data(self):83 error = {'message': 'Failure with data'}84 SimplivityModuleException(error)85 def test_should_call_exit_json_properly(self):86 self.mock_ansible_module.params = self.PARAMS_FOR_PRESENT87 mock_run = mock.Mock()88 mock_run.return_value = self.MODULE_EXECUTE_RETURN_VALUE.copy()89 base_mod = SimplivityModule()90 base_mod.execute_module = mock_run91 base_mod.run()92 self.mock_ansible_module.exit_json.assert_called_once_with(93 changed=True,94 msg=MSG_GENERIC,95 ansible_facts={'ansible_facts': None}96 )97 def test_should_call_exit_json_adding_changed_false_when_undefined(self):98 self.mock_ansible_module.params = self.PARAMS_FOR_PRESENT99 mock_run = mock.Mock()100 mock_run.return_value = dict(101 msg=MSG_GENERIC,102 ansible_facts={'ansible_facts': None}103 )104 base_mod = SimplivityModule()105 base_mod.execute_module = mock_run106 base_mod.run()107 self.mock_ansible_module.exit_json.assert_called_once_with(108 changed=False,109 msg=MSG_GENERIC,110 ansible_facts={'ansible_facts': None}111 )112 def test_should_load_config_from_file(self):113 self.mock_ansible_module.params = {'config': 'config.json'}114 SimplivityModule()115 self.mock_ovc_client_from_json_file.assert_called_once_with('config.json')116 self.mock_ovc_client_from_env_vars.not_been_called()117 def test_should_load_config_from_environment(self):118 self.mock_ansible_module.params = {'config': None}119 SimplivityModule()120 self.mock_ovc_client_from_env_vars.assert_called_once_with()121 self.mock_ovc_client_from_json_file.not_been_called()122 def test_should_load_config_from_parameters(self):123 params = {'ovc_ip': '10.40.4.245', 'username': 'admin', 'password': 'mypass'}124 params_for_expect = {'ip': '10.40.4.245',125 'credentials': {'username': 'admin', 'password': 'mypass'}}126 self.mock_ansible_module.params = params127 with mock.patch('module_utils.simplivity.OVC', first='one', second='two') as mock_ovc_client_from_credentials:128 SimplivityModule()129 self.mock_ovc_client_from_env_vars.not_been_called()130 self.mock_ovc_client_from_json_file.not_been_called()131 mock_ovc_client_from_credentials.assert_called_once_with(params_for_expect)132 def test_should_call_fail_json_when_simplivity_sdk_not_installed(self):133 self.mock_ansible_module.params = {'config': 'config.json'}134 with mock.patch(SimplivityModule.__module__ + ".HAS_HPE_SIMPLIVITY", False):135 SimplivityModule()136 self.mock_ansible_module.fail_json.assert_called_once_with(msg='HPE SimpliVity Python SDK is required for this module.')137 def test_additional_argument_spec_construction(self):138 self.mock_ansible_module.params = self.PARAMS_FOR_PRESENT139 SimplivityModule(additional_arg_spec={'options': 'list'})140 expected_arg_spec = deepcopy(self.EXPECTED_ARG_SPEC)141 expected_arg_spec['options'] = 'list'142 self.mock_ansible_module_init.assert_called_once_with(argument_spec=expected_arg_spec,143 supports_check_mode=False)144 def test_should_call_fail_json_when_simplivity_exception(self):145 self.mock_ansible_module.params = self.PARAMS_FOR_PRESENT146 mock_run = mock.Mock()147 mock_run.side_effect = SimplivityModuleException(MSG_GENERIC_ERROR)148 base_mod = SimplivityModule()149 base_mod.execute_module = mock_run150 base_mod.run()151 self.mock_ansible_module.fail_json.assert_called_once_with(exception=mock.ANY, msg=MSG_GENERIC_ERROR)152 def test_should_not_handle_value_error_exception(self):153 self.mock_ansible_module.params = self.PARAMS_FOR_PRESENT154 mock_run = mock.Mock()155 mock_run.side_effect = ValueError(MSG_GENERIC_ERROR)156 try:157 base_mod = SimplivityModule()158 base_mod.execute_module = mock_run159 base_mod.run()160 except ValueError as e:161 assert(e.args[0] == MSG_GENERIC_ERROR)162 else:163 self.fail('Expected ValueError was not raised')164 def test_should_not_handle_exception(self):165 self.mock_ansible_module.params = self.PARAMS_FOR_PRESENT166 mock_run = mock.Mock()167 mock_run.side_effect = Exception(MSG_GENERIC_ERROR)168 try:169 base_mod = SimplivityModule()170 base_mod.execute_module = mock_run171 base_mod.run()172 except Exception as e:173 assert(e.args[0] == MSG_GENERIC_ERROR)174 else:175 self.fail('Expected Exception was not raised')176 def test_resource_present_should_create(self):177 self.mock_ansible_module.params = self.PARAMS_FOR_PRESENT178 ovc_base = SimplivityModule()179 ovc_base.resource_client = mock.Mock()180 resource_obj = StubResource()181 resource_obj.data = self.RESOURCE_COMMON.copy()182 ovc_base.resource_client.create.return_value = resource_obj183 ovc_base.data = {'name': 'Resource Name'}184 facts = ovc_base.resource_present(fact_name="resource")185 expected = self.RESOURCE_COMMON.copy()186 ovc_base.resource_client.create.assert_called_once_with({'name': 'Resource Name'})187 assert facts == dict(changed=True,188 msg=SimplivityModule.MSG_CREATED,189 ansible_facts=dict(resource=expected))190 def test_resource_present_should_not_update_when_data_is_equals(self):191 self.mock_ansible_module.params = self.PARAMS_FOR_PRESENT192 ovc_base = SimplivityModule()193 ovc_base.resource_client = mock.Mock()194 ovc_base.data = self.RESOURCE_COMMON.copy()195 ovc_base.resource_client.get_by_name.return_value = mock.Mock()196 ovc_base.set_resource_object(ovc_base.resource_client)197 ovc_base.active_resource.data = self.RESOURCE_COMMON.copy()198 facts = ovc_base.resource_present(fact_name="resource")199 assert facts == dict(changed=False,200 msg=SimplivityModule.MSG_ALREADY_PRESENT,201 ansible_facts=dict(resource=self.RESOURCE_COMMON.copy()))202 def test_resource_present_should_update_when_data_has_modified_attributes(self):203 self.mock_ansible_module.params = self.PARAMS_FOR_PRESENT204 ovc_base = SimplivityModule()205 ovc_base.resource_client = mock.Mock()206 resource_obj = StubResource()207 updated_value = self.RESOURCE_COMMON.copy()208 updated_value['name'] = 'Resource Name New'209 resource_obj.data = updated_value210 ovc_base.resource_client.get_by_name.return_value = mock.Mock()211 ovc_base.set_resource_object(ovc_base.resource_client)212 ovc_base.active_resource.data = self.RESOURCE_COMMON.copy()213 ovc_base.data = {'newName': 'Resource Name New'}214 facts = ovc_base.resource_present('resource')215 expected = self.RESOURCE_COMMON.copy()216 expected['name'] = 'Resource Name New'217 ovc_base.active_resource.update.assert_called_once_with(expected)218 assert dict(changed=facts['changed'], msg=facts['msg']) == dict(changed=True,219 msg=SimplivityModule.MSG_UPDATED)220 def test_resource_absent_should_remove(self):221 self.mock_ansible_module.params = self.PARAMS_FOR_PRESENT222 ovc_base = SimplivityModule()223 ovc_base.resource_client = mock.Mock()224 ovc_base.resource_client.get_by_name.return_value = mock.Mock()225 ovc_base.set_resource_object(ovc_base.resource_client)226 facts = ovc_base.resource_absent()227 ovc_base.active_resource.delete.assert_called_once_with()228 assert facts == dict(changed=True,229 msg=SimplivityModule.MSG_DELETED)230 def test_resource_absent_should_do_nothing_when_not_exist(self):231 self.mock_ansible_module.params = self.PARAMS_FOR_PRESENT232 ovc_base = SimplivityModule()233 ovc_base.resource_client = mock.Mock()234 ovc_base.resource_client.get_by_name.return_value = None235 ovc_base.set_resource_object(ovc_base.resource_client)236 facts = ovc_base.resource_absent()237 assert facts == dict(changed=False,238 msg=SimplivityModule.MSG_ALREADY_ABSENT)239if __name__ == '__main__':...

Full Screen

Full Screen

test_status.py

Source:test_status.py Github

copy

Full Screen

1from unittest import (2 TestCase,3 mock,4)5import pcs.lib.booth.status as lib6from pcs import settings7from pcs.common.reports import ReportItemSeverity as Severities8from pcs.common.reports import codes as report_codes9from pcs.lib.external import CommandRunner10from pcs_test.tools.assertions import assert_raise_library_error11class GetDaemonStatusTest(TestCase):12 def setUp(self):13 self.mock_run = mock.MagicMock(spec_set=CommandRunner)14 def test_no_name(self):15 self.mock_run.run.return_value = ("output", "", 0)16 self.assertEqual("output", lib.get_daemon_status(self.mock_run))17 self.mock_run.run.assert_called_once_with(18 [settings.booth_binary, "status"]19 )20 def test_with_name(self):21 self.mock_run.run.return_value = ("output", "", 0)22 self.assertEqual("output", lib.get_daemon_status(self.mock_run, "name"))23 self.mock_run.run.assert_called_once_with(24 [settings.booth_binary, "status", "-c", "name"]25 )26 def test_daemon_not_running(self):27 self.mock_run.run.return_value = ("", "error", 7)28 self.assertEqual("", lib.get_daemon_status(self.mock_run))29 self.mock_run.run.assert_called_once_with(30 [settings.booth_binary, "status"]31 )32 def test_failure(self):33 self.mock_run.run.return_value = ("out", "error", 1)34 assert_raise_library_error(35 lambda: lib.get_daemon_status(self.mock_run),36 (37 Severities.ERROR,38 report_codes.BOOTH_DAEMON_STATUS_ERROR,39 {"reason": "error\nout"},40 ),41 )42 self.mock_run.run.assert_called_once_with(43 [settings.booth_binary, "status"]44 )45class GetTicketsStatusTest(TestCase):46 def setUp(self):47 self.mock_run = mock.MagicMock(spec_set=CommandRunner)48 def test_no_name(self):49 self.mock_run.run.return_value = ("output", "", 0)50 self.assertEqual("output", lib.get_tickets_status(self.mock_run))51 self.mock_run.run.assert_called_once_with(52 [settings.booth_binary, "list"]53 )54 def test_with_name(self):55 self.mock_run.run.return_value = ("output", "", 0)56 self.assertEqual(57 "output", lib.get_tickets_status(self.mock_run, "name")58 )59 self.mock_run.run.assert_called_once_with(60 [settings.booth_binary, "list", "-c", "name"]61 )62 def test_failure(self):63 self.mock_run.run.return_value = ("out", "error", 1)64 assert_raise_library_error(65 lambda: lib.get_tickets_status(self.mock_run),66 (67 Severities.ERROR,68 report_codes.BOOTH_TICKET_STATUS_ERROR,69 {"reason": "error\nout"},70 ),71 )72 self.mock_run.run.assert_called_once_with(73 [settings.booth_binary, "list"]74 )75class GetPeersStatusTest(TestCase):76 def setUp(self):77 self.mock_run = mock.MagicMock(spec_set=CommandRunner)78 def test_no_name(self):79 self.mock_run.run.return_value = ("output", "", 0)80 self.assertEqual("output", lib.get_peers_status(self.mock_run))81 self.mock_run.run.assert_called_once_with(82 [settings.booth_binary, "peers"]83 )84 def test_with_name(self):85 self.mock_run.run.return_value = ("output", "", 0)86 self.assertEqual("output", lib.get_peers_status(self.mock_run, "name"))87 self.mock_run.run.assert_called_once_with(88 [settings.booth_binary, "peers", "-c", "name"]89 )90 def test_failure(self):91 self.mock_run.run.return_value = ("out", "error", 1)92 assert_raise_library_error(93 lambda: lib.get_peers_status(self.mock_run),94 (95 Severities.ERROR,96 report_codes.BOOTH_PEERS_STATUS_ERROR,97 {"reason": "error\nout"},98 ),99 )100 self.mock_run.run.assert_called_once_with(101 [settings.booth_binary, "peers"]...

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 pytest-cov 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