How to use capture_stdout_stderr method in unittest-xml-reporting

Best Python code snippet using unittest-xml-reporting_python

test_command.py

Source:test_command.py Github

copy

Full Screen

...13 'command': 'uptime',14 'command_output': "0:40 up 1 day, 8:19, 4 users, load averages: 0.00 0.50 1.00",15 'exit_status': 0,16 }17 stdout, stderr = utils.capture_stdout_stderr()18 def mock_parse_args(self, args):19 return utils.create_command_namespace(command = [ EXPECTED['command'] ])20 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)21 def mock_execute(self):22 return EXPECTED['exit_status'], EXPECTED['command_output']23 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)24 main = CommandMain('tomahawk')25 status = main.run()26 o = stdout.stop().value()27 assert status == 028 s = \29"""tomahawk@localhost %% %(command)s30%(command_output)s31""" % EXPECTED32 assert o == s33def test_01_run_error(monkeypatch):34 EXPECTED = {35 'command': 'command_not_found',36 'exit_status': 127,37 }38 stdout, stderr = utils.capture_stdout_stderr()39 def mock_parse_args(self, args):40 return utils.create_command_namespace(command = [ EXPECTED['command'] ])41 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)42 def mock_execute(self):43 return EXPECTED['exit_status'], "/bin/sh: command_not_found: command not found"44 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)45 main = CommandMain('tomahawk')46 status = main.run()47 assert status == 148 assert re.search(r'failed on host', stderr.stop().value())49def test_02_run_timeout(monkeypatch):50 EXPECTED = {51 'command': 'sleep 3',52 'command_output': "/bin/sh: command_not_found: command not found",53 }54 stdout, stderr = utils.capture_stdout_stderr()55 def mock_parse_args(self, args):56 return utils.create_command_namespace(57 command = [ EXPECTED['command'] ], timeout = 158 )59 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)60 def mock_execute(self):61 raise TimeoutError()62 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)63 main = CommandMain('tomahawk')64 status = main.run()65 assert status == 166 assert re.search(r'timed out on host', stderr.stop().value())67def test_03_run_escape_shell_chars(monkeypatch):68 EXPECTED = {69 'command': 'echo \\\\',70 'command_output': "\\",71 'exit_status': 0,72 }73 stdout, stderr = utils.capture_stdout_stderr()74 def mock_parse_args(self, args):75 return utils.create_command_namespace(76 command = [ EXPECTED['command'] ],77 debug_enabled = True,78 )79 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)80 def mock_execute(self):81 return EXPECTED['exit_status'], EXPECTED['command_output']82 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)83 main = CommandMain('tomahawk')84 main.run()85 o = stdout.stop().value().strip()86 assert o == "tomahawk@localhost % echo \\\\\n\\"87def test_04_run_without_user(monkeypatch):88 EXPECTED = {89 'command': 'uptime',90 'command_output': "0:40 up 1 day, 8:19, 4 users, load averages: 0.00 0.50 1.00",91 'exit_status': 0,92 }93 stdout, stderr = utils.capture_stdout_stderr()94 def mock_parse_args(self, args):95 return utils.create_command_namespace(96 command=[EXPECTED['command']],97 ssh_user=None,98 ssh_options='-o User=tomahawk')99 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)100 def mock_execute(self):101 return EXPECTED['exit_status'], EXPECTED['command_output']102 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)103 main = CommandMain('tomahawk')104 status = main.run()105 o = stdout.stop().value()106 assert status == 0107 s = \108"""[user]@localhost %% %(command)s109%(command_output)s110""" % EXPECTED111 assert o == s112def test_05_run_utf8_command(monkeypatch):113 EXPECTED = {114 'command': 'echo -n "あ"',115 'command_output': six.u("あ"),116 'exit_status': 0,117 }118 stdout, stderr = utils.capture_stdout_stderr()119 def mock_parse_args(self, args):120 return utils.create_command_namespace(121 command=[EXPECTED['command']],122 ssh_user=None,123 ssh_options='-o User=tomahawk')124 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)125 def mock_execute(self):126 return EXPECTED['exit_status'], EXPECTED['command_output']127 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)128 main = CommandMain('tomahawk')129 status = main.run()130 o = stdout.stop().value()131 #print(o)132 if six.PY2:133 EXPECTED['command_output'] = EXPECTED['command_output'].encode('utf-8')134 assert status == 0135 s = \136 """[user]@localhost %% %(command)s137%(command_output)s138""" % EXPECTED139 assert o == s140def test_10_run_option_host_files(monkeypatch):141 EXPECTED = {142 'command': 'echo "hello world"',143 'command_output': "hello world",144 }145 stdout, stderr = utils.capture_stdout_stderr()146 def mock_parse_args(self, args):147 return utils.create_command_namespace(148 command = [ EXPECTED['command'] ],149 hosts = 'localhost,localhost',150 )151 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)152 def mock_execute(self):153 return 0, EXPECTED['command_output']154 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)155 main = CommandMain('tomahawk')156 status = main.run()157 assert status == 0158 assert re.search(r'hello world', stdout.stop().value())159def test_20_run_option_continue_on_error(monkeypatch):160 EXPECTED = {161 'command': 'failure_command',162 'command_output': "hello world",163 }164 stdout, stderr = utils.capture_stdout_stderr()165 def mock_parse_args(self, args):166 return utils.create_command_namespace(167 command = [ EXPECTED['command'] ],168 continue_on_error = True,169 hosts = 'localhost,127.0.0.1',170 )171 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)172 def mock_execute(self):173 return 127, EXPECTED['command_output']174 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)175 main = CommandMain('tomahawk')176 status = main.run()177 err = stderr.stop().value().strip()178 assert status == 1179 assert len(err.split('\n')) == 3180def test_21_run_option_parallel_continue_on_error(monkeypatch):181 EXPECTED = {182 'command': 'failure_command',183 'command_output': "hello world",184 }185 stdout, stderr = utils.capture_stdout_stderr()186 target_hosts = [187 'localhost', 'localhost', 'localhost', 'localhost',188 '127.0.0.1', '127.0.0.1', '127.0.0.1', '127.0.0.1',189 ]190 def mock_parse_args(self, args):191 return utils.create_command_namespace(192 command = [ EXPECTED['command'] ],193 continue_on_error = True,194 parallel = 2,195 hosts = ','.join(target_hosts),196 )197 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)198 def mock_execute(self):199 return 127, EXPECTED['command_output']200 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)201 main = CommandMain('tomahawk')202 status = main.run()203 assert status == 1204 # parse output to collect failure hosts.205 hosts = []206 hosts_start = False207 for line in stderr.stop().value().split('\n'):208 if re.search(r'failed on following hosts', line, re.I):209 hosts_start = True210 continue211 if hosts_start:212 h = line.strip()213 if h != '':214 hosts.append(h)215 assert hosts == target_hosts216def test_30_execute_option_ssh_options(monkeypatch):217 EXPECTED = {218 'command': 'echo "hello world"',219 'command_output': "hello world",220 }221 stdout, stderr = utils.capture_stdout_stderr()222 def mock_parse_args(self, args):223 return utils.create_command_namespace(224 command = [ EXPECTED['command'] ],225 ssh_options = '-c arcfour',226 )227 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)228 def mock_execute(self):229 return 0, EXPECTED['command_output']230 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)231 main = CommandMain('tomahawk')232 status = main.run()233 assert status == 0234 assert re.search(EXPECTED['command_output'], stdout.stop().value())235def test_40_output_format(monkeypatch):236 EXPECTED = {237 'command': 'uptime',238 'command_output': r'localhost @ uptime',239 }240 stdout, stderr = utils.capture_stdout_stderr()241 def mock_parse_args(self, args):242 return utils.create_command_namespace(243 command = [ EXPECTED['command'] ],244 output_format = r'${host} @ ${command}',245 )246 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)247 def mock_execute(self):248 return 0, EXPECTED['command_output']249 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)250 main = CommandMain('tomahawk')251 status = main.run()252 out = stdout.stop().value().strip()253 assert status == 0254 assert out == EXPECTED['command_output']255def test_41_output_format_newline(monkeypatch):256 """\n new line test"""257 EXPECTED = {258 'command': 'uptime',259 'command_output': "localhost\nuptime",260 }261 stdout, stderr = utils.capture_stdout_stderr()262 def mock_parse_args(self, args):263 return utils.create_command_namespace(264 command = [ EXPECTED['command'] ],265 output_format = r"${host}\n${command}",266 )267 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)268 def mock_execute(self):269 return 0, EXPECTED['command_output']270 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)271 main = CommandMain('tomahawk')272 status = main.run()273 assert status == 0274 assert stdout.stop().value().strip() == EXPECTED['command_output']275def test_42_output_format_no_newline(monkeypatch):276 """\\n no new line test"""277 EXPECTED = {278 'command': 'uptime',279 'command_output': r"localhost \\n uptime",280 }281 stdout, stderr = utils.capture_stdout_stderr()282 def mock_parse_args(self, args):283 return utils.create_command_namespace(284 command = [ EXPECTED['command'] ],285 output_format = r'${host} \\n ${command}',286 )287 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)288 def mock_execute(self):289 return 0, EXPECTED['command_output']290 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)291 main = CommandMain('tomahawk')292 status = main.run()293 assert status == 0294 assert stdout.stop().value().strip() == EXPECTED['command_output']295def test_50_parallel_adjustment(monkeypatch):296 stdout, stderr = utils.capture_stdout_stderr()297 def mock_parse_args(self, args):298 return utils.create_command_namespace(299 command = [ 'uptime' ], parallel = 10300 )301 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)302 def mock_execute(self):303 return 0, "mock execute"304 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)305 main = CommandMain('tomahawk')306 main.run()307 assert main.context.options['parallel'] == 1308def test_60_verify_output_ok(monkeypatch):309 EXPECTED = {310 'command': 'echo "hello world"',311 'command_output': r'hello world',312 }313 stdout, stderr = utils.capture_stdout_stderr()314 def mock_parse_args(self, args):315 return utils.create_command_namespace(316 command = [ EXPECTED['command'] ],317 hosts = 'localhost,127.0.0.1',318 verify_output = True,319 )320 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)321 def mock_execute(self):322 return 0, EXPECTED['command_output']323 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)324 main = CommandMain('tomahawk')325 status = main.run()326 out = stdout.stop().value().strip()327 assert status == 0328 assert out == """329tomahawk@localhost % echo "hello world"330hello world331tomahawk@127.0.0.1 % echo "hello world"332hello world333Verified output of all hosts.334""".strip()335def test_61_verify_output_ng(monkeypatch):336 EXPECTED = {337 'command': 'date',338 'command_output': r'hello world',339 }340 stdout, stderr = utils.capture_stdout_stderr()341 def mock_parse_args(self, args):342 return utils.create_command_namespace(343 command = [ EXPECTED['command'] ],344 hosts = 'localhost,127.0.0.1',345 verify_output = True,346 )347 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)348 def mock_execute(self):349 return 0, str(datetime.datetime.now())350 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)351 main = CommandMain('tomahawk')352 status = main.run()...

Full Screen

Full Screen

test_rsync.py

Source:test_rsync.py Github

copy

Full Screen

...24def test_00_run(monkeypatch):25 EXPECTED = {26 'exit_status': 0,27 }28 stdout, stderr = utils.capture_stdout_stderr()29 def mock_parse_args(self, args):30 return utils.create_rsync_namespace(31 source = hello_file,32 destination = hello_file_copied,33 )34 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)35 def mock_execute(self):36 shutil.copyfile(hello_file, hello_file_copied)37 return EXPECTED['exit_status'], ''38 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)39 main = RsyncMain('tomahawk-rsync')40 status = main.run()41 assert status == EXPECTED['exit_status']42 assert os.path.exists(hello_file_copied)43def test_01_run_error(monkeypatch):44 EXPECTED = {45 'exit_status': 1,46 }47 stdout, stderr = utils.capture_stdout_stderr()48 def mock_parse_args(self, args):49 return utils.create_rsync_namespace(50 source = 'file_does_not_exist',51 destination = TMP_DIR,52 )53 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)54 def mock_execute(self):55 shutil.copyfile(hello_file, hello_file_copied)56 return EXPECTED['exit_status'], ''57 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)58 main = RsyncMain('tomahawk-rsync')59 status = main.run()60 assert status == 161 assert not os.path.exists(os.path.join(TMP_DIR, 'file_does_not_exist'))62def test_02_run_timeout(monkeypatch):63 EXPECTED = {64 'exit_status': 1,65 }66 stdout, stderr = utils.capture_stdout_stderr()67 def mock_parse_args(self, args):68 return utils.create_rsync_namespace(69 source = 'file_does_not_exist',70 destination = TMP_DIR,71 )72 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)73 def mock_execute(self):74 raise TimeoutError()75 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)76 main = RsyncMain('tomahawk-rsync')77 status = main.run()78 err = stderr.stop().value()79 assert status == EXPECTED['exit_status']80 assert re.search(r'timed out on host', err)81def test_03_run_without_user(monkeypatch):82 EXPECTED = {83 'exit_status': 0,84 }85 stdout, stderr = utils.capture_stdout_stderr()86 def mock_parse_args(self, args):87 return utils.create_rsync_namespace(88 source=hello_file,89 destination=hello_file_copied,90 rsync_user=None91 )92 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)93 def mock_execute(self):94 shutil.copyfile(hello_file, hello_file_copied)95 return EXPECTED['exit_status'], ''96 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)97 main = RsyncMain('tomahawk-rsync')98 status = main.run()99 assert status == EXPECTED['exit_status']100 assert os.path.exists(hello_file_copied)101 assert not re.search(r'rsync -av.*@', stdout.stop().value()) # test no user on output102def test_10_run_option_rsync_options(monkeypatch):103 EXPECTED = {104 'exit_status': 0,105 }106 stdout, stderr = utils.capture_stdout_stderr()107 hello_file_dry_run = os.path.join(TMP_DIR, 'hello.dry-run')108 def mock_parse_args(self, args):109 return utils.create_rsync_namespace(110 source = hello_file,111 destination = hello_file_copied,112 rsync_options = '-av --dry-run',113 )114 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)115 def mock_execute(self):116 return EXPECTED['exit_status'], ''117 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)118 main = RsyncMain('tomahawk-rsync')119 status = main.run()120 assert status == EXPECTED['exit_status']121 assert not os.path.exists(hello_file_dry_run)122def test_11_run_option_mirror_mode_pull(monkeypatch):123 EXPECTED = {124 'exit_status': 0,125 }126 stdout, stderr = utils.capture_stdout_stderr()127 target_files = ( 'localhost__hello', '127.0.0.1__hello' )128 # remove target_files129 for f in target_files:130 path = os.path.join(TMP_DIR, f)131 if os.path.exists(path):132 os.remove(path)133 def mock_parse_args(self, args):134 return utils.create_rsync_namespace(135 source = hello_file,136 destination = TMP_DIR,137 hosts = 'localhost,127.0.0.1',138 mirror_mode = 'pull',139 )140 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)141 def mock_execute(self):142 for f in target_files:143 shutil.copyfile(hello_file, os.path.join(TMP_DIR, f))144 return EXPECTED['exit_status'], ''145 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)146 main = RsyncMain('tomahawk-rsync')147 status = main.run()148 assert status == EXPECTED['exit_status']149 for f in target_files:150 assert os.path.exists(os.path.join(TMP_DIR, f))151def test_21_run_option_continue_on_error(monkeypatch):152 EXPECTED = {153 'exit_status': 1,154 }155 stdout, stderr = utils.capture_stdout_stderr()156 def mock_parse_args(self, args):157 return utils.create_rsync_namespace(158 source = hello_file,159 destination = TMP_DIR,160 hosts = 'localhost,127.0.0.1',161 continue_on_error = True,162 )163 monkeypatch.setattr(argparse.ArgumentParser, 'parse_args', mock_parse_args)164 def mock_execute(self):165 return 127, 'error when rsync'166 monkeypatch.setattr(CommandWithExpect, 'execute', mock_execute)167 main = RsyncMain('tomahawk-rsync')168 status = main.run()169 err = stderr.stop().value()...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

...48#-----------------------------------------------------------------------------49# Functions and class declarations50#-----------------------------------------------------------------------------51@contextlib.contextmanager52def capture_stdout_stderr():53 r"""A context manager to temporarily redirect standard output and error54 >>> with capture_stdout_stderr() as sink:55 ... print('foobar')56 >>> sink.getvalue()57 'foobar\n'58 """59 sink = io.StringIO()60 orig = sys.stdout, sys.stderr61 sys.stdout = sys.stderr = sink62 try:63 yield sink64 finally:65 sys.stdout, sys.stderr = orig66SUPPRESS = re.compile(r'#\s*SUPPRESS\s*$')67def format_lines(lines):68 r"""Add >>>/... prompts to lines as if the were typed interactively69 >>> s = '''\70 ... x = (371 ... + 5)'''.splitlines()72 >>> print(s)73 ['x = (3', '+ 5)']74 >>> list(format_lines(s))75 [' >>> x = (3', ' ... + 5)']76 """77 for i, line in enumerate(lines):78 if SUPPRESS.search(line):79 break80 if line:81 yield ' {} {}'.format('>>>' if i == 0 else '...', line)82 elif any(lines[i+1:]):83 yield ' ...'84 else:85 # skip the ellipsis for the empty lines at end86 yield ' '87class CodesampleDirective(Directive):88 has_content = True89 required_arguments = 090 optional_arguments = 1 # filename91 final_argumuent_whitespace = True92 option_spec = { 'suppress' : directives.flag,93 'nosuppress' : directives.flag,94 'okexcept': directives.flag,95 'okwarning': directives.flag96 }97 @staticmethod98 def codesample_option(name):99 return 'codesample_' + name100 def getoption(self, name):101 if name in self.options:102 return True103 if 'no' + name in self.options:104 return False105 config = self.state.document.settings.env.config106 return getattr(config, self.codesample_option(name))107 def run(self):108 globals = {}109 locals = {}110 suppress = self.getoption('suppress')111 text = '\n'.join(self.content)112 textlines = text.splitlines()113 tree = ast.parse(text)114 lexer = 'python' if not suppress else 'text'115 lines = ['.. code-block:: {}'.format(lexer), '']116 nums = [stmt.lineno for stmt in tree.body]117 nextnums = [min((num for num in nums[i+1:] if num > nums[i]), default=999999)118 for i in range(len(nums))]119 num = 1120 for i, stmt in enumerate(tree.body):121 if stmt.lineno >= num and not suppress:122 # output the code up to the next statement123 batch = format_lines(textlines[num-1:nextnums[i]-1])124 lines.extend(batch)125 num = nextnums[i]126 source = ast.Interactive([stmt])127 module = compile(source, '<block>', 'single')128 with capture_stdout_stderr() as capture:129 exec(module, globals, locals)130 lines.extend(' {}'.format(line)131 for line in capture.getvalue().splitlines())132 self.state_machine.insert_input(133 lines, self.state_machine.input_lines.source(0))134 return []135# Enable as a proper Sphinx directive136def setup(app):137 setup.app = app138 app.add_directive('codesample', CodesampleDirective)139 app.add_config_value(CodesampleDirective.codesample_option('suppress'),...

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 unittest-xml-reporting 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