How to use redirect_io method in autotest

Best Python code snippet using autotest_python

test_io.py

Source:test_io.py Github

copy

Full Screen

1#2# Unit Tests for util/*_io3#4#5import os6import sys7from os.path import abspath, dirname8pkgdir = dirname(abspath(__file__)) + os.sep + ".." + os.sep + ".."9currdir = dirname(abspath(__file__)) + os.sep10import six11import pyutilib.th as unittest12import pyutilib.misc13def filter1(str):14 return True15def filter2(str):16 return ""17def filter3(str):18 str = str.replace('THERE', 'HERE')19 str = str.replace('[4, 5, 6]', '[1,2,3]')20 return str21class IODebug(unittest.TestCase):22 def test_redirect1(self):23 # Verify that IO redirection works24 pyutilib.misc.setup_redirect(currdir + "redirect_io.out")25 print("HERE")26 print([1, 2, 3])27 #28 # Force a flush to ensure code coverage29 #30 sys.stdout.flush()31 pyutilib.misc.reset_redirect()32 self.assertFalse(33 pyutilib.misc.comparison.compare_file(34 currdir + "redirect_io.out", currdir + "redirect_io1.txt")[0])35 self.assertFalse(36 pyutilib.misc.comparison.compare_file(37 currdir + "redirect_io.out",38 currdir + "redirect_io2.txt",39 filter=filter1)[0])40 self.assertFalse(41 pyutilib.misc.comparison.compare_file(42 currdir + "redirect_io.out",43 currdir + "redirect_io2.txt",44 filter=filter2)[0])45 os.remove(currdir + "redirect_io.out")46 def test_redirect2(self):47 # Verify that IO redirection will create an empty file is no output is generated48 pyutilib.misc.setup_redirect(currdir + "redirect_io.out")49 pyutilib.misc.reset_redirect()50 if not os.path.exists(currdir + "redirect_io.out"):51 self.fail("Redirection did not create an empty file.")52 self.assertFalse(53 pyutilib.misc.comparison.compare_file(54 currdir + "redirect_io.out", currdir + "redirect_io2.txt")[0])55 os.remove(currdir + "redirect_io.out")56 def test_redirect3(self):57 # Verify that IO redirection can be nested58 pyutilib.misc.setup_redirect(currdir + "redirect_io1.out")59 print("HERE")60 pyutilib.misc.setup_redirect(currdir + "redirect_io3.out")61 print("THERE")62 print([4, 5, 6])63 pyutilib.misc.reset_redirect()64 print([1, 2, 3])65 #66 # Force a flush to ensure code coverage67 #68 sys.stdout.flush()69 pyutilib.misc.reset_redirect()70 self.assertFalse(71 pyutilib.misc.comparison.compare_file(72 currdir + "redirect_io1.out", currdir + "redirect_io1.txt")[0])73 os.remove(currdir + "redirect_io1.out")74 self.assertFalse(75 pyutilib.misc.comparison.compare_file(76 currdir + "redirect_io3.out", currdir + "redirect_io3.txt")[0])77 self.assertFalse(78 pyutilib.misc.comparison.compare_file(79 currdir + "redirect_io3.out",80 currdir + "redirect_io3.txt",81 filter=filter3)[0])82 os.remove(currdir + "redirect_io3.out")83 def test_redirect4(self):84 # Verify that IO redirection works with file-like objects85 output = six.StringIO()86 pyutilib.misc.setup_redirect(output)87 print("HERE")88 print([1, 2, 3])89 #90 # Force a flush to ensure code coverage91 #92 sys.stdout.flush()93 pyutilib.misc.reset_redirect()94 self.assertEqual(output.getvalue(), "HERE\n[1, 2, 3]\n")95 def test_format_io(self):96 # Test that formated IO looks correct.97 pyutilib.misc.setup_redirect(currdir + "format_io.out")98 print(pyutilib.misc.format_io(0.0))99 print(pyutilib.misc.format_io(0))100 print(pyutilib.misc.format_io(1e-1))101 print(pyutilib.misc.format_io(1e+1))102 print(pyutilib.misc.format_io(1e-9))103 print(pyutilib.misc.format_io(1e+9))104 print(pyutilib.misc.format_io(1e-99))105 print(pyutilib.misc.format_io(1e+99))106 print(pyutilib.misc.format_io(1e-100))107 print(pyutilib.misc.format_io(1e+100))108 print(pyutilib.misc.format_io(-1e-1))109 print(pyutilib.misc.format_io(-1e+1))110 print(pyutilib.misc.format_io(-1e-9))111 print(pyutilib.misc.format_io(-1e+9))112 print(pyutilib.misc.format_io(-1e-99))113 print(pyutilib.misc.format_io(-1e+99))114 print(pyutilib.misc.format_io(-1e-100))115 print(pyutilib.misc.format_io(-1e+100))116 print(pyutilib.misc.format_io('string'))117 pyutilib.misc.reset_redirect()118 self.assertFalse(119 pyutilib.misc.comparison.compare_file(currdir + "format_io.out",120 currdir + "format_io.txt")[0])121 os.remove(currdir + "format_io.out")122 def test_format_float_err1(self):123 # Test that errors are generated for non floats124 try:125 pyutilib.misc.format_float('1')126 self.fail("Should have thrown a TypeError exception")127 except TypeError:128 pass129 def test_indenter_write(self):130 output = six.StringIO()131 indenter = pyutilib.misc.StreamIndenter(output, "X ")132 indenter.write("foo")133 self.assertEqual(output.getvalue(), "X foo")134 indenter.write("\n")135 self.assertEqual(output.getvalue(), "X foo\n")136 indenter.write("foo\n")137 self.assertEqual(output.getvalue(), "X foo\nX foo\n")138 indenter.write("")139 self.assertEqual(output.getvalue(), "X foo\nX foo\n")140 indenter.write("\n")141 self.assertEqual(output.getvalue(), "X foo\nX foo\nX\n")142 indenter.write("baz\nbin")143 self.assertEqual(output.getvalue(), "X foo\nX foo\nX\nX baz\nX bin")144 indenter.write("a\nb\n\nc\n")145 self.assertEqual(output.getvalue(),146 "X foo\nX foo\nX\nX baz\nX bina\nX b\nX\nX c\n")147 self.assertEqual(indenter.closed, False)148 indenter.close()149 self.assertEqual(indenter.closed, True)150 def test_indenter_writelines(self):151 output = six.StringIO()152 indenter = pyutilib.misc.StreamIndenter(output, "X")153 indenter.writelines(["foo"])154 self.assertEqual(output.getvalue(), "Xfoo")155 indenter.writelines(["foo\n", "bar\n"])156 self.assertEqual(output.getvalue(), "Xfoofoo\nXbar\n")157 indenter.writelines(["", ""])158 self.assertEqual(output.getvalue(), "Xfoofoo\nXbar\n")159 self.assertEqual(indenter.closed, False)160 indenter.close()161 self.assertEqual(indenter.closed, True)162 def test_redirected_stdout(self):163 with pyutilib.misc.capture_output() as output:164 print("test1")165 print("test2")166 self.assertEqual(output.getvalue(), "test1\ntest2\n")167 def test_redirected_stdout_with_arg(self):168 stream = six.StringIO()169 stream.write("before\n")170 with pyutilib.misc.capture_output(stream) as output:171 print("test1")172 print("test2")173 self.assertEqual(output.getvalue(), "before\ntest1\ntest2\n")174if __name__ == "__main__":...

Full Screen

Full Screen

utils.py

Source:utils.py Github

copy

Full Screen

...65 setattr(obj, attribute, new_value)66 yield67 setattr(obj, attribute, old_value)68@contextlib.contextmanager69def redirect_io(stream: str, new_stream):70 """Redirect stdio streams to a custom stream."""71 old_stream = getattr(sys, stream)72 setattr(sys, stream, new_stream)73 yield74 setattr(sys, stream, old_stream)75@contextlib.contextmanager76def change_cwd(new_cwd):77 """Change working directory before running code."""78 os.chdir(new_cwd)79 yield80 os.chdir(SERVER_CWD)81def _run_module(82 module: str, argv: Sequence[str], use_stdin: bool, source: str = None83) -> RunResult:84 """Runs as a module."""85 str_output = CustomIO("<stdout>", encoding="utf-8")86 str_error = CustomIO("<stderr>", encoding="utf-8")87 try:88 with substitute_attr(sys, "argv", argv):89 with redirect_io("stdout", str_output):90 with redirect_io("stderr", str_error):91 if use_stdin and source is not None:92 str_input = CustomIO("<stdin>", encoding="utf-8", newline="\n")93 with redirect_io("stdin", str_input):94 str_input.write(source)95 str_input.seek(0)96 runpy.run_module(module, run_name="__main__")97 else:98 runpy.run_module(module, run_name="__main__")99 except SystemExit:100 pass101 return RunResult(str_output.get_value(), str_error.get_value())102def run_module(103 module: str, argv: Sequence[str], use_stdin: bool, cwd: str, source: str = None104) -> RunResult:105 """Runs as a module."""106 with CWD_LOCK:107 if is_same_path(os.getcwd(), cwd):108 return _run_module(module, argv, use_stdin, source)109 with change_cwd(cwd):110 return _run_module(module, argv, use_stdin, source)111def run_path(112 argv: Sequence[str], use_stdin: bool, cwd: str, source: str = None113) -> RunResult:114 """Runs as an executable."""115 if use_stdin:116 with subprocess.Popen(117 argv,118 encoding="utf-8",119 stdout=subprocess.PIPE,120 stderr=subprocess.PIPE,121 stdin=subprocess.PIPE,122 cwd=cwd,123 ) as process:124 return RunResult(*process.communicate(input=source))125 else:126 result = subprocess.run(127 argv,128 encoding="utf-8",129 stdout=subprocess.PIPE,130 stderr=subprocess.PIPE,131 check=False,132 cwd=cwd,133 )134 return RunResult(result.stdout, result.stderr)135def run_api(136 callback: Callable[[Sequence[str], CustomIO, CustomIO, CustomIO | None], None],137 argv: Sequence[str],138 use_stdin: bool,139 cwd: str,140 source: str = None,141) -> RunResult:142 """Run a API."""143 with CWD_LOCK:144 if is_same_path(os.getcwd(), cwd):145 return _run_api(callback, argv, use_stdin, source)146 with change_cwd(cwd):147 return _run_api(callback, argv, use_stdin, source)148def _run_api(149 callback: Callable[[Sequence[str], CustomIO, CustomIO, CustomIO | None], None],150 argv: Sequence[str],151 use_stdin: bool,152 source: str = None,153) -> RunResult:154 str_output = CustomIO("<stdout>", encoding="utf-8")155 str_error = CustomIO("<stderr>", encoding="utf-8")156 try:157 with substitute_attr(sys, "argv", argv):158 with redirect_io("stdout", str_output):159 with redirect_io("stderr", str_error):160 if use_stdin and source is not None:161 str_input = CustomIO("<stdin>", encoding="utf-8", newline="\n")162 with redirect_io("stdin", str_input):163 str_input.write(source)164 str_input.seek(0)165 callback(argv, str_output, str_error, str_input)166 else:167 callback(argv, str_output, str_error)168 except SystemExit:169 pass...

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 autotest 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