How to use captured_output method in tappy

Best Python code snippet using tappy_python

test_system_commands.py

Source:test_system_commands.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2# Copyright 2018 Google Inc.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""Tests for the google.colab._system_commands package."""16from __future__ import absolute_import17from __future__ import division18from __future__ import print_function19import collections20import contextlib21import os22import signal23import textwrap24import threading25import time26import unittest27from google.colab import _ipython28from google.colab import _message29from google.colab import _system_commands30import IPython31from IPython.core import interactiveshell32from IPython.lib import pretty33from IPython.utils import io34import six35# pylint:disable=g-import-not-at-top36try:37 import unittest.mock as mock38except ImportError:39 import mock40# pylint:enable=g-import-not-at-top41class FakeShell(interactiveshell.InteractiveShell):42 def system(self, *args, **kwargs):43 return _system_commands._system_compat(self, *args, **kwargs)44 def getoutput(self, *args, **kwargs):45 return _system_commands._getoutput_compat(self, *args, **kwargs)46class RunCellResult(47 collections.namedtuple('RunCellResult',48 ('output', 'update_calls', 'stdout_flushes'))):49 """RunCellResult contains details after invoking the %%shell magic.50 Fields include:51 output: The captured IPython output during execution52 update_calls: Any calls to update echo status of the underlying shell53 stdout_flushes: Number of calls to stdout.flush54 """55class SystemCommandsTest(unittest.TestCase):56 @classmethod57 def setUpClass(cls):58 super(SystemCommandsTest, cls).setUpClass()59 ipython = FakeShell.instance()60 ipython.kernel = mock.Mock()61 cls.ip = IPython.get_ipython()62 cls.orig_pty_max_read_bytes = _system_commands._PTY_READ_MAX_BYTES_FOR_TEST63 def setUp(self):64 super(SystemCommandsTest, self).setUp()65 self.ip.reset()66 _system_commands._PTY_READ_MAX_BYTES_FOR_TEST = self.orig_pty_max_read_bytes67 def testSubprocessOutputCaptured(self):68 run_cell_result = self.run_cell("""69r = %shell echo -n "hello err, " 1>&2 && echo -n "hello out, " && echo "bye..."70""")71 captured_output = run_cell_result.output72 self.assertEqual('', captured_output.stderr)73 self.assertEqual('hello err, hello out, bye...\n', captured_output.stdout)74 result = self.ip.user_ns['r']75 self.assertEqual(0, result.returncode)76 self.assertEqual('hello err, hello out, bye...\n', result.output)77 def testStdinEchoToggling(self):78 # The -s flag for read disables terminal echoing. First read with echoing79 # enabled, then do a subsequent read with echoing disabled.80 cmd = """81r = %shell read r1 && echo "First: $r1" && read -s r2 && echo "Second: $r2"82"""83 run_cell_result = self.run_cell(cmd, provided_inputs=['cats\n', 'dogs\n'])84 captured_output = run_cell_result.output85 self.assertEqual('', captured_output.stderr)86 self.assertEqual('cats\nFirst: cats\nSecond: dogs\n',87 captured_output.stdout)88 result = self.ip.user_ns['r']89 self.assertEqual(0, result.returncode)90 self.assertEqual('cats\nFirst: cats\nSecond: dogs\n', result.output)91 # Updates correspond to:92 # 1) Initial state (i.e. read with terminal echoing enabled)93 # 2) Read call with "-s" option94 # 3) Call to bash echo command.95 self.assertEqual([True, False, True], run_cell_result.update_calls)96 def testStdinDisabledNoInputRequested(self):97 with temp_env(COLAB_DISABLE_STDIN_FOR_SHELL_MAGICS='1'):98 run_cell_result = self.run_cell('r = %shell echo "hello world"')99 captured_output = run_cell_result.output100 self.assertEqual('', captured_output.stderr)101 self.assertEqual('hello world\n', captured_output.stdout)102 result = self.ip.user_ns['r']103 self.assertEqual(result.returncode, 0)104 def testStdinDisabled(self):105 with temp_env(COLAB_DISABLE_STDIN_FOR_SHELL_MAGICS='1'):106 run_cell_result = self.run_cell(107 textwrap.dedent("""108 import subprocess109 try:110 %shell read result111 except subprocess.CalledProcessError as e:112 caught_exception = e113 """))114 captured_output = run_cell_result.output115 self.assertEqual('', captured_output.stderr)116 self.assertEqual('', captured_output.stdout)117 result = self.ip.user_ns['caught_exception']118 self.assertEqual(1, result.returncode)119 self.assertEqual('', result.output)120 def testStdinRequired(self):121 run_cell_result = self.run_cell(122 'r = %shell read result && echo "You typed: $result"',123 provided_inputs=['cats\n'])124 captured_output = run_cell_result.output125 self.assertEqual('', captured_output.stderr)126 self.assertEqual('cats\nYou typed: cats\n', captured_output.stdout)127 result = self.ip.user_ns['r']128 self.assertEqual(0, result.returncode)129 self.assertEqual('cats\nYou typed: cats\n', result.output)130 def testMoreInputThanReadBySubprocessIsDiscarded(self):131 # Normally, read will read characters until a newline is encountered. The132 # -n flag causes it to return after reading a specified number of characters133 # or a newline is encountered, whichever comes first.134 run_cell_result = self.run_cell(135 'r = %shell read -n1 char && echo "You typed: $char"',136 provided_inputs=['cats\n'])137 captured_output = run_cell_result.output138 self.assertEqual('', captured_output.stderr)139 # Bash's read command modifies terminal settings when the "-n" flag is140 # provided to put the terminal in one-char-at-a-time mode. This141 # unconditionally sets the ONLCR oflag, which causes input echoing to map NL142 # to CR-NL on output:143 # http://git.savannah.gnu.org/cgit/bash.git/tree/lib/sh/shtty.c?id=64447609994bfddeef1061948022c074093e9a9f#n128144 self.assertEqual('cats\r\nYou typed: c\n', captured_output.stdout)145 result = self.ip.user_ns['r']146 self.assertEqual(0, result.returncode)147 self.assertEqual('cats\r\nYou typed: c\n', result.output)148 def testSubprocessHasPTY(self):149 run_cell_result = self.run_cell('r = %shell tty')150 captured_output = run_cell_result.output151 self.assertEqual('', captured_output.stderr)152 self.assertIn('/dev/pts/', captured_output.stdout)153 result = self.ip.user_ns['r']154 self.assertEqual(result.returncode, 0)155 def testErrorPropagatesByDefault(self):156 run_cell_result = self.run_cell(157 textwrap.dedent("""158 import subprocess159 try:160 %shell /bin/false161 except subprocess.CalledProcessError as e:162 caught_exception = e163 """))164 captured_output = run_cell_result.output165 self.assertEqual('', captured_output.stderr)166 self.assertEqual('', captured_output.stdout)167 result = self.ip.user_ns['caught_exception']168 self.assertEqual(1, result.returncode)169 self.assertEqual('', result.output)170 def testIgnoreErrorsDoesNotPropagate(self):171 run_cell_result = self.run_cell(172 textwrap.dedent("""173 %%shell --ignore-errors174 /bin/false175 """))176 captured_output = run_cell_result.output177 self.assertEqual('', captured_output.stderr)178 # IPython displays the result of the last statement executed (unless it is179 # None) with a "Out[1]: " prefix. When using io.capture_output(), older180 # versions of IPython don't appear to capture this prompt in the stdout181 # stream. Due to this, we don't assert anything about the stdout output. If182 # an error is thrown, then accessing the "_" variable will fail.183 result = self.ip.user_ns['_']184 self.assertEqual(1, result.returncode)185 self.assertEqual('', result.output)186 def testLargeOutputWrittenAndImmediatelyClosed(self):187 _system_commands._PTY_READ_MAX_BYTES_FOR_TEST = 1188 run_cell_result = self.run_cell('r = %shell printf "%0.s-" {1..100}')189 captured_output = run_cell_result.output190 self.assertEqual('', captured_output.stderr)191 self.assertEqual(100, len(captured_output.stdout))192 result = self.ip.user_ns['r']193 self.assertEqual(0, result.returncode)194 self.assertEqual(1, run_cell_result.stdout_flushes)195 def testRunsInBashShell(self):196 # The "BASH" environment variable is set for all bash shells.197 run_cell_result = self.run_cell('r = %shell echo "$BASH"')198 captured_output = run_cell_result.output199 self.assertEqual('', captured_output.stderr)200 self.assertEqual('/bin/bash\n', captured_output.stdout)201 result = self.ip.user_ns['r']202 self.assertEqual(0, result.returncode)203 self.assertEqual('/bin/bash\n', result.output)204 def testUnicodeCmd(self):205 # "小狗" is "dogs" in simplified Chinese.206 run_cell_result = self.run_cell(u'r = %shell echo -n "Dogs is 小狗"')207 captured_output = run_cell_result.output208 self.assertEqual('', captured_output.stderr)209 self.assertEqual(u'Dogs is 小狗', captured_output.stdout)210 result = self.ip.user_ns['r']211 self.assertEqual(0, result.returncode)212 self.assertEqual(u'Dogs is 小狗', result.output)213 def testNonUtf8Cmd(self):214 # Regression test for b/177070077215 run_cell_result = self.run_cell(u'r = %shell printf "\\200" ; echo -n Yay')216 captured_output = run_cell_result.output217 self.assertEqual('', captured_output.stderr)218 self.assertEqual(u'�Yay', captured_output.stdout)219 result = self.ip.user_ns['r']220 self.assertEqual(0, result.returncode)221 self.assertEqual(u'�Yay', result.output)222 def testUnicodeInputAndOutput(self):223 # "猫" is "cats" in simplified Chinese and its representation requires224 # three bytes. Force reading only one byte at a time and ensure that the225 # character is preserved.226 _system_commands._PTY_READ_MAX_BYTES_FOR_TEST = 1227 cmd = u'r = %shell read result && echo "You typed: $result"'228 run_cell_result = self.run_cell(cmd, provided_inputs=[u'猫\n'])229 captured_output = run_cell_result.output230 self.assertEqual('', captured_output.stderr)231 self.assertEqual(u'猫\nYou typed: 猫\n', captured_output.stdout)232 result = self.ip.user_ns['r']233 self.assertEqual(0, result.returncode)234 self.assertEqual(u'猫\nYou typed: 猫\n', result.output)235 # Ensure that ShellResult objects don't have a "pretty" representation. This236 # ensures that no output is printed if the magic is the only statement in237 # the cell.238 self.assertEqual(u'', pretty.pretty(result))239 def testFirstInterruptSendsSigInt(self):240 run_cell_result = self.run_cell(241 textwrap.dedent("""242 %%shell --ignore-errors243 echo 'Before sleep'244 read -t 600245 echo 'Invalid. Read call should never terminate.'246 """),247 provided_inputs=['interrupt'])248 captured_output = run_cell_result.output249 self.assertEqual('', captured_output.stderr)250 result = self.ip.user_ns['_']251 self.assertEqual(-signal.SIGINT, result.returncode)252 self.assertEqual('Before sleep\n', result.output)253 def testSecondInterruptSendsSigTerm(self):254 run_cell_result = self.run_cell(255 textwrap.dedent("""256 %%shell --ignore-errors257 # Trapping with an empty command causes the signal to be ignored.258 trap '' SIGINT259 echo 'Before sleep'260 read -t 600261 echo 'Invalid. Read call should never terminate.'262 """),263 provided_inputs=['interrupt', 'interrupt'])264 captured_output = run_cell_result.output265 self.assertEqual('', captured_output.stderr)266 result = self.ip.user_ns['_']267 self.assertEqual(-signal.SIGTERM, result.returncode)268 self.assertEqual('Before sleep\n', result.output)269 def testSecondInterruptSendsSigKillAfterSigterm(self):270 run_cell_result = self.run_cell(271 textwrap.dedent("""272 %%shell --ignore-errors273 # Trapping with an empty command causes the signal to be ignored.274 trap '' SIGINT SIGTERM275 echo 'Before sleep'276 read -t 600277 echo 'Invalid. Read call should never terminate.'278 """),279 provided_inputs=['interrupt', 'interrupt'])280 captured_output = run_cell_result.output281 self.assertEqual('', captured_output.stderr)282 result = self.ip.user_ns['_']283 self.assertEqual(-signal.SIGKILL, result.returncode)284 self.assertEqual('Before sleep\n', result.output)285 def testNonUtf8Locale(self):286 # The "C" locale uses the US-ASCII 7-bit character set.287 with temp_env(LC_ALL='C'):288 run_cell_result = self.run_cell(289 textwrap.dedent("""290 import subprocess291 try:292 %shell echo "should fail"293 except NotImplementedError as e:294 caught_exception = e295 """))296 captured_output = run_cell_result.output297 self.assertEqual('', captured_output.stderr)298 self.assertEqual('', captured_output.stdout)299 self.assertIsNotNone(self.ip.user_ns['caught_exception'])300 def testSystemCompat(self):301 _system_commands._PTY_READ_MAX_BYTES_FOR_TEST = 1302 # "猫" is "cats" in simplified Chinese.303 run_cell_result = self.run_cell(304 '!read res && echo "You typed: $res"', provided_inputs=[u'猫\n'])305 captured_output = run_cell_result.output306 self.assertEqual('', captured_output.stderr)307 self.assertEqual(u'猫\nYou typed: 猫\n', captured_output.stdout)308 self.assertEqual(0, self.ip.user_ns['_exit_code'])309 self.assertNotIn('_', self.ip.user_ns)310 def testSystemCompatWithInterrupt(self):311 run_cell_result = self.run_cell('!read res', provided_inputs=['interrupt'])312 captured_output = run_cell_result.output313 self.assertEqual('', captured_output.stderr)314 self.assertEqual(u'^C\n', captured_output.stdout)315 self.assertEqual(-signal.SIGINT, self.ip.user_ns['_exit_code'])316 self.assertNotIn('_', self.ip.user_ns)317 def testSystemCompatWithVarExpansion(self):318 cmd = textwrap.dedent(u"""319 def some_func():320 local_var = 'Hello there'321 !echo "{local_var}"322 some_func()323 """)324 run_cell_result = self.run_cell(cmd, provided_inputs=[])325 captured_output = run_cell_result.output326 self.assertEqual('', captured_output.stderr)327 self.assertEqual(u'Hello there\n', captured_output.stdout)328 self.assertEqual(0, self.ip.user_ns['_exit_code'])329 self.assertNotIn('_', self.ip.user_ns)330 def testGetOutputCompat(self):331 # "猫" is "cats" in simplified Chinese.332 run_cell_result = self.run_cell(333 '!!read res && echo "You typed: $res"', provided_inputs=[u'猫\n'])334 captured_output = run_cell_result.output335 self.assertEqual('', captured_output.stderr)336 self.assertNotIn('_exit_code', self.ip.user_ns.keys())337 result = self.ip.user_ns['_']338 self.assertEqual(2, len(result))339 if six.PY2:340 self.assertEqual(u'猫'.encode('UTF-8'), result[0])341 self.assertEqual(u'You typed: 猫'.encode('UTF-8'), result[1])342 else:343 self.assertEqual(u'猫', result[0])344 self.assertEqual(u'You typed: 猫', result[1])345 def testGetOutputCompatWithInterrupt(self):346 run_cell_result = self.run_cell('!!read res', provided_inputs=['interrupt'])347 captured_output = run_cell_result.output348 self.assertEqual('', captured_output.stderr)349 self.assertIn(u'^C\n', captured_output.stdout)350 result = self.ip.user_ns['_']351 self.assertEqual(0, len(result))352 def testGetOutputCompatWithVarExpansion(self):353 cmd = textwrap.dedent(u"""354 def some_func():355 local_var = 'Hello there'356 # The result of "!!" cannot be assigned or returned. Write the contents357 # to a file and return that instead.358 !!echo "{local_var}" > /tmp/getoutputwithvarexpansion.txt359 with open('/tmp/getoutputwithvarexpansion.txt', 'r') as f:360 print(f.read())361 some_func()362 """)363 run_cell_result = self.run_cell(cmd, provided_inputs=[])364 captured_output = run_cell_result.output365 self.assertEqual('', captured_output.stderr)366 self.assertEqual(u'Hello there\n\n', captured_output.stdout)367 def run_cell(self, cell_contents, provided_inputs=None):368 """Execute the cell contents, optionally providing input to the subprocess.369 Args:370 cell_contents: Code to execute.371 provided_inputs: Input provided to the executing shell magic.372 Returns:373 A RunCellResult containing information about the executed cell.374 """375 # Why execute in a separate thread? The shell magic blocks until the376 # process completes, even if it is blocking on input. As such, we need to377 # asynchronously provide input by periodically popping the content and378 # forwarding it to the subprocess.379 def worker(inputs, result_container):380 def mock_stdin_provider():381 if not inputs:382 return None383 val = inputs.pop(0)384 if val == 'interrupt':385 raise KeyboardInterrupt386 return val387 mock_stdin_widget, echo_updater_calls = create_mock_stdin_widget()388 with \389 mock.patch.object(390 _message,391 '_read_stdin_message',392 side_effect=mock_stdin_provider,393 autospec=True), \394 mock.patch.object(395 _system_commands,396 '_display_stdin_widget',397 mock_stdin_widget):398 _system_commands._register_magics(self.ip)399 with io.capture_output() as captured:400 with mock.patch.object(401 captured._stdout, 'flush',402 wraps=captured._stdout.flush) as stdout_flushes:403 self.ip.run_cell(cell_contents)404 run_cell_result = RunCellResult(captured, echo_updater_calls,405 stdout_flushes.call_count)406 result_container['run_cell_result'] = run_cell_result407 result = {}408 input_queue = []409 t = threading.Thread(410 target=worker, args=(411 input_queue,412 result,413 ))414 t.daemon = True415 t.start()416 provided_inputs = provided_inputs or []417 for provided_input in provided_inputs:418 time.sleep(2)419 input_queue.append(provided_input)420 t.join(30)421 self.assertFalse(t.is_alive())422 return result['run_cell_result']423class DisplayStdinWidgetTest(unittest.TestCase):424 @mock.patch.object(_ipython, 'get_ipython', autospec=True)425 @mock.patch.object(_message, 'send_request', autospec=True)426 def testMessagesSent(self, mock_send_request, mock_get_ipython):427 mock_shell = mock.MagicMock(parent_header='12345')428 mock_get_ipython.return_value = mock_shell429 with _system_commands._display_stdin_widget(delay_millis=1000):430 pass431 mock_send_request.assert_has_calls([432 mock.call(433 'cell_display_stdin', {'delayMillis': 1000},434 expect_reply=False,435 parent='12345'),436 mock.call('cell_remove_stdin', {}, expect_reply=False, parent='12345'),437 ])438@contextlib.contextmanager439def temp_env(**env_variables):440 old_env = dict(os.environ)441 os.environ.update(env_variables)442 try:443 yield444 finally:445 os.environ.clear()446 os.environ.update(old_env)447def create_mock_stdin_widget():448 calls = []449 @contextlib.contextmanager450 def mock_stdin_widget(*unused_args, **unused_kwargs):451 def echo_updater(echo):452 calls.append(echo)453 yield echo_updater...

Full Screen

Full Screen

test_cli.py

Source:test_cli.py Github

copy

Full Screen

...24 return out.getvalue()25 # Python 3.x writes 'bytes' to stdout.buffer26 return out.buffer.getvalue()27@contextmanager28def captured_output():29 """Captures output to stdout and stderr"""30 new_out, new_err = make_buffer(), make_buffer()31 old_out, old_err = sys.stdout, sys.stderr32 try:33 sys.stdout, sys.stderr = new_out, new_err34 yield new_out, new_err35 finally:36 sys.stdout, sys.stderr = old_out, old_err37@contextmanager38def cli_args(*new_argv):39 """Updates sys.argv[1:] for a single test."""40 old_args = sys.argv[:]41 sys.argv[1:] = [str(arg) for arg in new_argv]42 try:43 yield44 finally:45 sys.argv[1:] = old_args46def remove_if_exists(fname):47 """Removes a file if it exists."""48 if os.path.exists(fname):49 os.unlink(fname)50def cleanup_files(*filenames):51 """Makes sure the files don't exist when the test runs, and deletes them afterward."""52 def remove():53 for fname in filenames:54 remove_if_exists(fname)55 def decorator(func):56 @functools.wraps(func)57 def wrapper(*args, **kwargs):58 remove()59 try:60 return func(*args, **kwargs)61 finally:62 remove()63 return wrapper64 return decorator65class AbstractCliTest(unittest.TestCase):66 @classmethod67 def setUpClass(cls):68 # Ensure there is a key to use69 cls.pub_key, cls.priv_key = rsa.newkeys(512)70 cls.pub_fname = '%s.pub' % cls.__name__71 cls.priv_fname = '%s.key' % cls.__name__72 with open(cls.pub_fname, 'wb') as outfile:73 outfile.write(cls.pub_key.save_pkcs1())74 with open(cls.priv_fname, 'wb') as outfile:75 outfile.write(cls.priv_key.save_pkcs1())76 @classmethod77 def tearDownClass(cls):78 if hasattr(cls, 'pub_fname'):79 remove_if_exists(cls.pub_fname)80 if hasattr(cls, 'priv_fname'):81 remove_if_exists(cls.priv_fname)82 def assertExits(self, status_code, func, *args, **kwargs):83 try:84 func(*args, **kwargs)85 except SystemExit as ex:86 if status_code == ex.code:87 return88 self.fail('SystemExit() raised by %r, but exited with code %r, expected %r' % (89 func, ex.code, status_code))90 else:91 self.fail('SystemExit() not raised by %r' % func)92class KeygenTest(AbstractCliTest):93 def test_keygen_no_args(self):94 with cli_args():95 self.assertExits(1, rsa.cli.keygen)96 def test_keygen_priv_stdout(self):97 with captured_output() as (out, err):98 with cli_args(128):99 rsa.cli.keygen()100 lines = get_bytes_out(out).splitlines()101 self.assertEqual(b'-----BEGIN RSA PRIVATE KEY-----', lines[0])102 self.assertEqual(b'-----END RSA PRIVATE KEY-----', lines[-1])103 # The key size should be shown on stderr104 self.assertTrue('128-bit key' in err.getvalue())105 @cleanup_files('test_cli_privkey_out.pem')106 def test_keygen_priv_out_pem(self):107 with captured_output() as (out, err):108 with cli_args('--out=test_cli_privkey_out.pem', '--form=PEM', 128):109 rsa.cli.keygen()110 # The key size should be shown on stderr111 self.assertTrue('128-bit key' in err.getvalue())112 # The output file should be shown on stderr113 self.assertTrue('test_cli_privkey_out.pem' in err.getvalue())114 # If we can load the file as PEM, it's good enough.115 with open('test_cli_privkey_out.pem', 'rb') as pemfile:116 rsa.PrivateKey.load_pkcs1(pemfile.read())117 @cleanup_files('test_cli_privkey_out.der')118 def test_keygen_priv_out_der(self):119 with captured_output() as (out, err):120 with cli_args('--out=test_cli_privkey_out.der', '--form=DER', 128):121 rsa.cli.keygen()122 # The key size should be shown on stderr123 self.assertTrue('128-bit key' in err.getvalue())124 # The output file should be shown on stderr125 self.assertTrue('test_cli_privkey_out.der' in err.getvalue())126 # If we can load the file as der, it's good enough.127 with open('test_cli_privkey_out.der', 'rb') as derfile:128 rsa.PrivateKey.load_pkcs1(derfile.read(), format='DER')129 @cleanup_files('test_cli_privkey_out.pem', 'test_cli_pubkey_out.pem')130 def test_keygen_pub_out_pem(self):131 with captured_output() as (out, err):132 with cli_args('--out=test_cli_privkey_out.pem',133 '--pubout=test_cli_pubkey_out.pem',134 '--form=PEM', 256):135 rsa.cli.keygen()136 # The key size should be shown on stderr137 self.assertTrue('256-bit key' in err.getvalue())138 # The output files should be shown on stderr139 self.assertTrue('test_cli_privkey_out.pem' in err.getvalue())140 self.assertTrue('test_cli_pubkey_out.pem' in err.getvalue())141 # If we can load the file as PEM, it's good enough.142 with open('test_cli_pubkey_out.pem', 'rb') as pemfile:143 rsa.PublicKey.load_pkcs1(pemfile.read())144class EncryptDecryptTest(AbstractCliTest):145 def test_empty_decrypt(self):146 with cli_args():147 self.assertExits(1, rsa.cli.decrypt)148 def test_empty_encrypt(self):149 with cli_args():150 self.assertExits(1, rsa.cli.encrypt)151 @cleanup_files('encrypted.txt', 'cleartext.txt')152 def test_encrypt_decrypt(self):153 with open('cleartext.txt', 'wb') as outfile:154 outfile.write(b'Hello cleartext RSA users!')155 with cli_args('-i', 'cleartext.txt', '--out=encrypted.txt', self.pub_fname):156 with captured_output():157 rsa.cli.encrypt()158 with cli_args('-i', 'encrypted.txt', self.priv_fname):159 with captured_output() as (out, err):160 rsa.cli.decrypt()161 # We should have the original cleartext on stdout now.162 output = get_bytes_out(out)163 self.assertEqual(b'Hello cleartext RSA users!', output)164 @cleanup_files('encrypted.txt', 'cleartext.txt')165 def test_encrypt_decrypt_unhappy(self):166 with open('cleartext.txt', 'wb') as outfile:167 outfile.write(b'Hello cleartext RSA users!')168 with cli_args('-i', 'cleartext.txt', '--out=encrypted.txt', self.pub_fname):169 with captured_output():170 rsa.cli.encrypt()171 # Change a few bytes in the encrypted stream.172 with open('encrypted.txt', 'r+b') as encfile:173 encfile.seek(40)174 encfile.write(b'hahaha')175 with cli_args('-i', 'encrypted.txt', self.priv_fname):176 with captured_output() as (out, err):177 self.assertRaises(rsa.DecryptionError, rsa.cli.decrypt)178class SignVerifyTest(AbstractCliTest):179 def test_empty_verify(self):180 with cli_args():181 self.assertExits(1, rsa.cli.verify)182 def test_empty_sign(self):183 with cli_args():184 self.assertExits(1, rsa.cli.sign)185 @cleanup_files('signature.txt', 'cleartext.txt')186 def test_sign_verify(self):187 with open('cleartext.txt', 'wb') as outfile:188 outfile.write(b'Hello RSA users!')189 with cli_args('-i', 'cleartext.txt', '--out=signature.txt', self.priv_fname, 'SHA-256'):190 with captured_output():191 rsa.cli.sign()192 with cli_args('-i', 'cleartext.txt', self.pub_fname, 'signature.txt'):193 with captured_output() as (out, err):194 rsa.cli.verify()195 self.assertFalse(b'Verification OK' in get_bytes_out(out))196 @cleanup_files('signature.txt', 'cleartext.txt')197 def test_sign_verify_unhappy(self):198 with open('cleartext.txt', 'wb') as outfile:199 outfile.write(b'Hello RSA users!')200 with cli_args('-i', 'cleartext.txt', '--out=signature.txt', self.priv_fname, 'SHA-256'):201 with captured_output():202 rsa.cli.sign()203 # Change a few bytes in the cleartext file.204 with open('cleartext.txt', 'r+b') as encfile:205 encfile.seek(6)206 encfile.write(b'DSA')207 with cli_args('-i', 'cleartext.txt', self.pub_fname, 'signature.txt'):208 with captured_output() as (out, err):209 self.assertExits('Verification failed.', rsa.cli.verify)210class PrivatePublicTest(AbstractCliTest):211 """Test CLI command to convert a private to a public key."""212 @cleanup_files('test_private_to_public.pem')213 def test_private_to_public(self):214 with cli_args('-i', self.priv_fname, '-o', 'test_private_to_public.pem'):215 with captured_output():216 rsa.util.private_to_public()217 # Check that the key is indeed valid.218 with open('test_private_to_public.pem', 'rb') as pemfile:219 key = rsa.PublicKey.load_pkcs1(pemfile.read())220 self.assertEqual(self.priv_key.n, key.n)...

Full Screen

Full Screen

Teste_Agenda_Corporativa.py

Source:Teste_Agenda_Corporativa.py Github

copy

Full Screen

1"""=====================================================================================================================2Criado por Heitor de Carvalho-------------------------10/04/20223Arquivo Unittest - Unidades testadas:4- Input_Usuário.py5Histórico de Modificações:623/04/2022 - Criado7====================================================================================================================="""8import datetime9import io10import sys11import unittest12from unittest.mock import patch13from Auxiliar_Functions.Input_Usuário import nome, sobrenome, nascimento, cpf14class MyTestCase(unittest.TestCase):15 # =================================================================================================================16 # Sequência de testes para a função nome()17 @patch('builtins.input', lambda _: 'Heitor')18 def test_name_pass1(self):19 retorno = nome(teste=True)20 self.assertEqual(retorno, 'Heitor')21 @patch('builtins.input', lambda _: 'heitor')22 def test_name_pass2(self):23 retorno = nome(teste=True)24 self.assertEqual(retorno, 'Heitor')25 @patch('builtins.input', lambda _: 'júlio césar')26 def test_name_pass3(self):27 retorno = nome(teste=True)28 self.assertEqual(retorno, 'Júlio César')29 @patch('builtins.input', lambda _: 'H31T02')30 def test_name_error1(self):31 captured_output = io.StringIO() # Create StringIO object32 sys.stdout = captured_output # and redirect stdout.33 nome(teste=True) # Call function34 sys.stdout = sys.__stdout__ # Reset redirect35 self.assertEqual(captured_output.getvalue(), '\x1b[41m\x1b[37m\x1b[1mInserção de dados inválida\n')36 @patch('builtins.input', lambda _: 'H&it0r')37 def test_name_error2(self):38 captured_output = io.StringIO() # Create StringIO object39 sys.stdout = captured_output # and redirect stdout.40 nome(teste=True) # Call function41 sys.stdout = sys.__stdout__ # Reset redirect42 self.assertEqual(captured_output.getvalue(), '\x1b[41m\x1b[37m\x1b[1mInserção de dados inválida\n')43 # =================================================================================================================44 # Sequência de testes para a função sobrenome()45 @patch('builtins.input', lambda _: 'silva')46 def test_secname_pass1(self):47 retorno = sobrenome(teste=True)48 self.assertEqual(retorno, 'Silva')49 @patch('builtins.input', lambda _: 'DA silva NAscimento')50 def test_secname_pass2(self):51 retorno = sobrenome(teste=True)52 self.assertEqual(retorno, 'da Silva Nascimento')53 @patch('builtins.input', lambda _: 'D4 S1lvA Nascimento')54 def test_secname_error1(self):55 captured_output = io.StringIO() # Create StringIO object56 sys.stdout = captured_output # and redirect stdout.57 nome(select=False, teste=True) # Call function58 sys.stdout = sys.__stdout__ # Reset redirect59 self.assertEqual(captured_output.getvalue(), '\x1b[41m\x1b[37m\x1b[1mInserção de dados inválida\n')60 @patch('builtins.input', lambda _: 'da Silv@ Nascim&nt0')61 def test_secname_error2(self):62 captured_output = io.StringIO() # Create StringIO object63 sys.stdout = captured_output # and redirect stdout.64 nome(select=False, teste=True) # Call function65 sys.stdout = sys.__stdout__ # Reset redirect66 self.assertEqual(captured_output.getvalue(), '\x1b[41m\x1b[37m\x1b[1mInserção de dados inválida\n')67 # =================================================================================================================68 # Sequência de testes para a função nascimento()69 @patch('builtins.input', lambda _: '13/12/1991')70 def test_birth_pass1(self):71 retorno = nascimento(teste=True)72 self.assertEqual(retorno, datetime.datetime(year=1991, month=12, day=13))73 @patch('builtins.input', lambda _: '13121991')74 def test_birth_error1(self):75 captured_output = io.StringIO() # Create StringIO object76 sys.stdout = captured_output # and redirect stdout.77 nascimento(teste=True) # Call function78 sys.stdout = sys.__stdout__ # Reset redirect79 self.assertEqual(captured_output.getvalue(), '\x1b[41m\x1b[37m\x1b[1mFormato de data inválido\n')80 @patch('builtins.input', lambda _: '13-12-1991')81 def test_birth_error2(self):82 captured_output = io.StringIO() # Create StringIO object83 sys.stdout = captured_output # and redirect stdout.84 nascimento(teste=True) # Call function85 sys.stdout = sys.__stdout__ # Reset redirect86 self.assertEqual(captured_output.getvalue(), '\x1b[41m\x1b[37m\x1b[1mFormato de data inválido\n')87 @patch('builtins.input', lambda _: '13/21/1991')88 def test_birth_error3(self):89 captured_output = io.StringIO() # Create StringIO object90 sys.stdout = captured_output # and redirect stdout.91 nascimento(teste=True) # Call function92 sys.stdout = sys.__stdout__ # Reset redirect93 self.assertEqual(captured_output.getvalue(), '\x1b[41m\x1b[37m\x1b[1mFormato de data inválido\n')94 @patch('builtins.input', lambda _: '13/12/2100')95 def test_birth_error4(self):96 captured_output = io.StringIO() # Create StringIO object97 sys.stdout = captured_output # and redirect stdout.98 nascimento(teste=True) # Call function99 sys.stdout = sys.__stdout__ # Reset redirect100 self.assertEqual(captured_output.getvalue(), '\x1b[41m\x1b[37m\x1b[1mFormato de data inválido\n')101 @patch('builtins.input', lambda _: '29/02/2022')102 def test_birth_error5(self):103 captured_output = io.StringIO() # Create StringIO object104 sys.stdout = captured_output # and redirect stdout.105 nascimento(teste=True) # Call function106 sys.stdout = sys.__stdout__ # Reset redirect107 self.assertEqual(captured_output.getvalue(), '\x1b[41m\x1b[37m\x1b[1mFormato de data inválido\n')108 # =================================================================================================================109 # Sequência de testes para a função cpf()110 @patch('builtins.input', lambda _: '000.000.000-00')111 def test_cpf_pass1(self):112 retorno = cpf(teste=True)113 self.assertEqual(retorno, '000.000.000-00')114 @patch('builtins.input', lambda _: '00000000000')115 def test_cpf_error1(self):116 captured_output = io.StringIO() # Create StringIO object117 sys.stdout = captured_output # and redirect stdout.118 cpf(teste=True) # Call function119 sys.stdout = sys.__stdout__ # Reset redirect120 self.assertEqual(captured_output.getvalue(), '\x1b[41m\x1b[37m\x1b[1mFormato invalido!!!!\n')121 @patch('builtins.input', lambda _: '000.000.000-0')122 def test_cpf_error2(self):123 captured_output = io.StringIO() # Create StringIO object124 sys.stdout = captured_output # and redirect stdout.125 cpf(teste=True) # Call function126 sys.stdout = sys.__stdout__ # Reset redirect127 self.assertEqual(captured_output.getvalue(), '\x1b[41m\x1b[37m\x1b[1mFormato invalido!!!!\n')128 @patch('builtins.input', lambda _: '00.000.000-00')129 def test_cpf_error3(self):130 captured_output = io.StringIO() # Create StringIO object131 sys.stdout = captured_output # and redirect stdout.132 cpf(teste=True) # Call function133 sys.stdout = sys.__stdout__ # Reset redirect134 self.assertEqual(captured_output.getvalue(), '\x1b[41m\x1b[37m\x1b[1mFormato invalido!!!!\n')135if __name__ == '__main__':...

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