How to use expected_regex method in Playwright Python

Best Python code snippet using playwright-python

base.py

Source:base.py Github

copy

Full Screen

1from __future__ import print_function, absolute_import2import os3import tempfile4import unittest5import sys6import re7import warnings8import io9from textwrap import dedent10from future.utils import bind_method, PY26, PY3, PY2, PY2711from future.moves.subprocess import check_output, STDOUT, CalledProcessError12if PY26:13 import unittest2 as unittest14def reformat_code(code):15 """16 Removes any leading \n and dedents.17 """18 if code.startswith('\n'):19 code = code[1:]20 return dedent(code)21def order_future_lines(code):22 """23 Returns the code block with any ``__future__`` import lines sorted, and24 then any ``future`` import lines sorted, then any ``builtins`` import lines25 sorted.26 This only sorts the lines within the expected blocks.27 See test_order_future_lines() for an example.28 """29 # We need .splitlines(keepends=True), which doesn't exist on Py2,30 # so we use this instead:31 lines = code.split('\n')32 uufuture_line_numbers = [i for i, line in enumerate(lines)33 if line.startswith('from __future__ import ')]34 future_line_numbers = [i for i, line in enumerate(lines)35 if line.startswith('from future')36 or line.startswith('from past')]37 builtins_line_numbers = [i for i, line in enumerate(lines)38 if line.startswith('from builtins')]39 assert code.lstrip() == code, ('internal usage error: '40 'dedent the code before calling order_future_lines()')41 def mymax(numbers):42 return max(numbers) if len(numbers) > 0 else 043 def mymin(numbers):44 return min(numbers) if len(numbers) > 0 else float('inf')45 assert mymax(uufuture_line_numbers) <= mymin(future_line_numbers), \46 'the __future__ and future imports are out of order'47 # assert mymax(future_line_numbers) <= mymin(builtins_line_numbers), \48 # 'the future and builtins imports are out of order'49 uul = sorted([lines[i] for i in uufuture_line_numbers])50 sorted_uufuture_lines = dict(zip(uufuture_line_numbers, uul))51 fl = sorted([lines[i] for i in future_line_numbers])52 sorted_future_lines = dict(zip(future_line_numbers, fl))53 bl = sorted([lines[i] for i in builtins_line_numbers])54 sorted_builtins_lines = dict(zip(builtins_line_numbers, bl))55 # Replace the old unsorted "from __future__ import ..." lines with the56 # new sorted ones:57 new_lines = []58 for i in range(len(lines)):59 if i in uufuture_line_numbers:60 new_lines.append(sorted_uufuture_lines[i])61 elif i in future_line_numbers:62 new_lines.append(sorted_future_lines[i])63 elif i in builtins_line_numbers:64 new_lines.append(sorted_builtins_lines[i])65 else:66 new_lines.append(lines[i])67 return '\n'.join(new_lines)68class VerboseCalledProcessError(CalledProcessError):69 """70 Like CalledProcessError, but it displays more information (message and71 script output) for diagnosing test failures etc.72 """73 def __init__(self, msg, returncode, cmd, output=None):74 self.msg = msg75 self.returncode = returncode76 self.cmd = cmd77 self.output = output78 def __str__(self):79 return ("Command '%s' failed with exit status %d\nMessage: %s\nOutput: %s"80 % (self.cmd, self.returncode, self.msg, self.output))81class FuturizeError(VerboseCalledProcessError):82 pass83class PasteurizeError(VerboseCalledProcessError):84 pass85class CodeHandler(unittest.TestCase):86 """87 Handy mixin for test classes for writing / reading / futurizing /88 running .py files in the test suite.89 """90 def setUp(self):91 """92 The outputs from the various futurize stages should have the93 following headers:94 """95 # After stage1:96 # TODO: use this form after implementing a fixer to consolidate97 # __future__ imports into a single line:98 # self.headers1 = """99 # from __future__ import absolute_import, division, print_function100 # """101 self.headers1 = reformat_code("""102 from __future__ import absolute_import103 from __future__ import division104 from __future__ import print_function105 """)106 # After stage2 --all-imports:107 # TODO: use this form after implementing a fixer to consolidate108 # __future__ imports into a single line:109 # self.headers2 = """110 # from __future__ import (absolute_import, division,111 # print_function, unicode_literals)112 # from future import standard_library113 # from future.builtins import *114 # """115 self.headers2 = reformat_code("""116 from __future__ import absolute_import117 from __future__ import division118 from __future__ import print_function119 from __future__ import unicode_literals120 from future import standard_library121 standard_library.install_aliases()122 from builtins import *123 """)124 self.interpreters = [sys.executable]125 self.tempdir = tempfile.mkdtemp() + os.path.sep126 pypath = os.getenv('PYTHONPATH')127 if pypath:128 self.env = {'PYTHONPATH': os.getcwd() + os.pathsep + pypath}129 else:130 self.env = {'PYTHONPATH': os.getcwd()}131 def convert(self, code, stages=(1, 2), all_imports=False, from3=False,132 reformat=True, run=True, conservative=False):133 """134 Converts the code block using ``futurize`` and returns the135 resulting code.136 Passing stages=[1] or stages=[2] passes the flag ``--stage1`` or137 ``stage2`` to ``futurize``. Passing both stages runs ``futurize``138 with both stages by default.139 If from3 is False, runs ``futurize``, converting from Python 2 to140 both 2 and 3. If from3 is True, runs ``pasteurize`` to convert141 from Python 3 to both 2 and 3.142 Optionally reformats the code block first using the reformat() function.143 If run is True, runs the resulting code under all Python144 interpreters in self.interpreters.145 """146 if reformat:147 code = reformat_code(code)148 self._write_test_script(code)149 self._futurize_test_script(stages=stages, all_imports=all_imports,150 from3=from3, conservative=conservative)151 output = self._read_test_script()152 if run:153 for interpreter in self.interpreters:154 _ = self._run_test_script(interpreter=interpreter)155 return output156 def compare(self, output, expected, ignore_imports=True):157 """158 Compares whether the code blocks are equal. If not, raises an159 exception so the test fails. Ignores any trailing whitespace like160 blank lines.161 If ignore_imports is True, passes the code blocks into the162 strip_future_imports method.163 If one code block is a unicode string and the other a164 byte-string, it assumes the byte-string is encoded as utf-8.165 """166 if ignore_imports:167 output = self.strip_future_imports(output)168 expected = self.strip_future_imports(expected)169 if isinstance(output, bytes) and not isinstance(expected, bytes):170 output = output.decode('utf-8')171 if isinstance(expected, bytes) and not isinstance(output, bytes):172 expected = expected.decode('utf-8')173 self.assertEqual(order_future_lines(output.rstrip()),174 expected.rstrip())175 def strip_future_imports(self, code):176 """177 Strips any of these import lines:178 from __future__ import <anything>179 from future <anything>180 from future.<anything>181 from builtins <anything>182 or any line containing:183 install_hooks()184 or:185 install_aliases()186 Limitation: doesn't handle imports split across multiple lines like187 this:188 from __future__ import (absolute_import, division, print_function,189 unicode_literals)190 """191 output = []192 # We need .splitlines(keepends=True), which doesn't exist on Py2,193 # so we use this instead:194 for line in code.split('\n'):195 if not (line.startswith('from __future__ import ')196 or line.startswith('from future ')197 or line.startswith('from builtins ')198 or 'install_hooks()' in line199 or 'install_aliases()' in line200 # but don't match "from future_builtins" :)201 or line.startswith('from future.')):202 output.append(line)203 return '\n'.join(output)204 def convert_check(self, before, expected, stages=(1, 2), all_imports=False,205 ignore_imports=True, from3=False, run=True,206 conservative=False):207 """208 Convenience method that calls convert() and compare().209 Reformats the code blocks automatically using the reformat_code()210 function.211 If all_imports is passed, we add the appropriate import headers212 for the stage(s) selected to the ``expected`` code-block, so they213 needn't appear repeatedly in the test code.214 If ignore_imports is True, ignores the presence of any lines215 beginning:216 from __future__ import ...217 from future import ...218 for the purpose of the comparison.219 """220 output = self.convert(before, stages=stages, all_imports=all_imports,221 from3=from3, run=run, conservative=conservative)222 if all_imports:223 headers = self.headers2 if 2 in stages else self.headers1224 else:225 headers = ''226 reformatted = reformat_code(expected)227 if headers in reformatted:228 headers = ''229 self.compare(output, headers + reformatted,230 ignore_imports=ignore_imports)231 def unchanged(self, code, **kwargs):232 """233 Convenience method to ensure the code is unchanged by the234 futurize process.235 """236 self.convert_check(code, code, **kwargs)237 def _write_test_script(self, code, filename='mytestscript.py'):238 """239 Dedents the given code (a multiline string) and writes it out to240 a file in a temporary folder like /tmp/tmpUDCn7x/mytestscript.py.241 """242 if isinstance(code, bytes):243 code = code.decode('utf-8')244 # Be explicit about encoding the temp file as UTF-8 (issue #63):245 with io.open(self.tempdir + filename, 'wt', encoding='utf-8') as f:246 f.write(dedent(code))247 def _read_test_script(self, filename='mytestscript.py'):248 with io.open(self.tempdir + filename, 'rt', encoding='utf-8') as f:249 newsource = f.read()250 return newsource251 def _futurize_test_script(self, filename='mytestscript.py', stages=(1, 2),252 all_imports=False, from3=False,253 conservative=False):254 params = []255 stages = list(stages)256 if all_imports:257 params.append('--all-imports')258 if from3:259 script = 'pasteurize.py'260 else:261 script = 'futurize.py'262 if stages == [1]:263 params.append('--stage1')264 elif stages == [2]:265 params.append('--stage2')266 else:267 assert stages == [1, 2]268 if conservative:269 params.append('--conservative')270 # No extra params needed271 # Absolute file path:272 fn = self.tempdir + filename273 call_args = [sys.executable, script] + params + ['-w', fn]274 try:275 output = check_output(call_args, stderr=STDOUT, env=self.env)276 except CalledProcessError as e:277 with open(fn) as f:278 msg = (279 'Error running the command %s\n'280 '%s\n'281 'Contents of file %s:\n'282 '\n'283 '%s') % (284 ' '.join(call_args),285 'env=%s' % self.env,286 fn,287 '----\n%s\n----' % f.read(),288 )289 ErrorClass = (FuturizeError if 'futurize' in script else PasteurizeError)290 if not hasattr(e, 'output'):291 # The attribute CalledProcessError.output doesn't exist on Py2.6292 e.output = None293 raise ErrorClass(msg, e.returncode, e.cmd, output=e.output)294 return output295 def _run_test_script(self, filename='mytestscript.py',296 interpreter=sys.executable):297 # Absolute file path:298 fn = self.tempdir + filename299 try:300 output = check_output([interpreter, fn],301 env=self.env, stderr=STDOUT)302 except CalledProcessError as e:303 with open(fn) as f:304 msg = (305 'Error running the command %s\n'306 '%s\n'307 'Contents of file %s:\n'308 '\n'309 '%s') % (310 ' '.join([interpreter, fn]),311 'env=%s' % self.env,312 fn,313 '----\n%s\n----' % f.read(),314 )315 if not hasattr(e, 'output'):316 # The attribute CalledProcessError.output doesn't exist on Py2.6317 e.output = None318 raise VerboseCalledProcessError(msg, e.returncode, e.cmd, output=e.output)319 return output320# Decorator to skip some tests on Python 2.6 ...321skip26 = unittest.skipIf(PY26, "this test is known to fail on Py2.6")322def expectedFailurePY3(func):323 if not PY3:324 return func325 return unittest.expectedFailure(func)326def expectedFailurePY26(func):327 if not PY26:328 return func329 return unittest.expectedFailure(func)330def expectedFailurePY27(func):331 if not PY27:332 return func333 return unittest.expectedFailure(func)334def expectedFailurePY2(func):335 if not PY2:336 return func337 return unittest.expectedFailure(func)338# Renamed in Py3.3:339if not hasattr(unittest.TestCase, 'assertRaisesRegex'):340 unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp341# From Py3.3:342def assertRegex(self, text, expected_regex, msg=None):343 """Fail the test unless the text matches the regular expression."""344 if isinstance(expected_regex, (str, unicode)):345 assert expected_regex, "expected_regex must not be empty."346 expected_regex = re.compile(expected_regex)347 if not expected_regex.search(text):348 msg = msg or "Regex didn't match"349 msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)350 raise self.failureException(msg)351if not hasattr(unittest.TestCase, 'assertRegex'):352 bind_method(unittest.TestCase, 'assertRegex', assertRegex)353class _AssertRaisesBaseContext(object):354 def __init__(self, expected, test_case, callable_obj=None,355 expected_regex=None):356 self.expected = expected357 self.test_case = test_case358 if callable_obj is not None:359 try:360 self.obj_name = callable_obj.__name__361 except AttributeError:362 self.obj_name = str(callable_obj)363 else:364 self.obj_name = None365 if isinstance(expected_regex, (bytes, str)):366 expected_regex = re.compile(expected_regex)367 self.expected_regex = expected_regex368 self.msg = None369 def _raiseFailure(self, standardMsg):370 msg = self.test_case._formatMessage(self.msg, standardMsg)371 raise self.test_case.failureException(msg)372 def handle(self, name, callable_obj, args, kwargs):373 """374 If callable_obj is None, assertRaises/Warns is being used as a375 context manager, so check for a 'msg' kwarg and return self.376 If callable_obj is not None, call it passing args and kwargs.377 """378 if callable_obj is None:379 self.msg = kwargs.pop('msg', None)380 return self381 with self:382 callable_obj(*args, **kwargs)383class _AssertWarnsContext(_AssertRaisesBaseContext):384 """A context manager used to implement TestCase.assertWarns* methods."""385 def __enter__(self):386 # The __warningregistry__'s need to be in a pristine state for tests387 # to work properly.388 for v in sys.modules.values():389 if getattr(v, '__warningregistry__', None):390 v.__warningregistry__ = {}391 self.warnings_manager = warnings.catch_warnings(record=True)392 self.warnings = self.warnings_manager.__enter__()393 warnings.simplefilter("always", self.expected)394 return self395 def __exit__(self, exc_type, exc_value, tb):396 self.warnings_manager.__exit__(exc_type, exc_value, tb)397 if exc_type is not None:398 # let unexpected exceptions pass through399 return400 try:401 exc_name = self.expected.__name__402 except AttributeError:403 exc_name = str(self.expected)404 first_matching = None405 for m in self.warnings:406 w = m.message407 if not isinstance(w, self.expected):408 continue409 if first_matching is None:410 first_matching = w411 if (self.expected_regex is not None and412 not self.expected_regex.search(str(w))):413 continue414 # store warning for later retrieval415 self.warning = w416 self.filename = m.filename417 self.lineno = m.lineno418 return419 # Now we simply try to choose a helpful failure message420 if first_matching is not None:421 self._raiseFailure('"{}" does not match "{}"'.format(422 self.expected_regex.pattern, str(first_matching)))423 if self.obj_name:424 self._raiseFailure("{} not triggered by {}".format(exc_name,425 self.obj_name))426 else:427 self._raiseFailure("{} not triggered".format(exc_name))428def assertWarns(self, expected_warning, callable_obj=None, *args, **kwargs):429 """Fail unless a warning of class warnClass is triggered430 by callable_obj when invoked with arguments args and keyword431 arguments kwargs. If a different type of warning is432 triggered, it will not be handled: depending on the other433 warning filtering rules in effect, it might be silenced, printed434 out, or raised as an exception.435 If called with callable_obj omitted or None, will return a436 context object used like this::437 with self.assertWarns(SomeWarning):438 do_something()439 An optional keyword argument 'msg' can be provided when assertWarns440 is used as a context object.441 The context manager keeps a reference to the first matching442 warning as the 'warning' attribute; similarly, the 'filename'443 and 'lineno' attributes give you information about the line444 of Python code from which the warning was triggered.445 This allows you to inspect the warning after the assertion::446 with self.assertWarns(SomeWarning) as cm:447 do_something()448 the_warning = cm.warning449 self.assertEqual(the_warning.some_attribute, 147)450 """451 context = _AssertWarnsContext(expected_warning, self, callable_obj)452 return context.handle('assertWarns', callable_obj, args, kwargs)453if not hasattr(unittest.TestCase, 'assertWarns'):...

Full Screen

Full Screen

case.py

Source:case.py Github

copy

Full Screen

1from __future__ import absolute_import, unicode_literals2import re3import sys4import types5import warnings6from contextlib import contextmanager7from functools import partial8from six import string_types, itervalues as values, iteritems as items9from . import mock10try:11 import unittest # noqa12 unittest.skip13 from unittest.util import safe_repr, unorderable_list_difference14except AttributeError:15 import unittest2 as unittest # noqa16 from unittest2.util import safe_repr, unorderable_list_difference # noqa17__all__ = ['Case']18# -- adds assertWarns from recent unittest2, not in Python 2.7.19class _AssertRaisesBaseContext(object):20 def __init__(self, expected, test_case, callable_obj=None,21 expected_regex=None):22 self.expected = expected23 self.failureException = test_case.failureException24 self.obj_name = None25 if isinstance(expected_regex, string_types):26 expected_regex = re.compile(expected_regex)27 self.expected_regex = expected_regex28def _is_magic_module(m):29 # some libraries create custom module types that are lazily30 # lodaded, e.g. Django installs some modules in sys.modules that31 # will load _tkinter and other shit when touched.32 # pyflakes refuses to accept 'noqa' for this isinstance.33 cls, modtype = type(m), types.ModuleType34 try:35 variables = vars(cls)36 except TypeError:37 return True38 else:39 return (cls is not modtype and (40 '__getattr__' in variables or41 '__getattribute__' in variables))42class _AssertWarnsContext(_AssertRaisesBaseContext):43 """A context manager used to implement TestCase.assertWarns* methods."""44 def __enter__(self):45 # The __warningregistry__'s need to be in a pristine state for tests46 # to work properly.47 warnings.resetwarnings()48 for v in list(values(sys.modules)):49 # do not evaluate Django moved modules and other lazily50 # initialized modules.51 if v and not _is_magic_module(v):52 # use raw __getattribute__ to protect even better from53 # lazily loaded modules54 try:55 object.__getattribute__(v, '__warningregistry__')56 except AttributeError:57 pass58 else:59 object.__setattr__(v, '__warningregistry__', {})60 self.warnings_manager = warnings.catch_warnings(record=True)61 self.warnings = self.warnings_manager.__enter__()62 warnings.simplefilter('always', self.expected)63 return self64 def __exit__(self, exc_type, exc_value, tb):65 self.warnings_manager.__exit__(exc_type, exc_value, tb)66 if exc_type is not None:67 # let unexpected exceptions pass through68 return69 try:70 exc_name = self.expected.__name__71 except AttributeError:72 exc_name = str(self.expected)73 first_matching = None74 for m in self.warnings:75 w = m.message76 if not isinstance(w, self.expected):77 continue78 if first_matching is None:79 first_matching = w80 if (self.expected_regex is not None and81 not self.expected_regex.search(str(w))):82 continue83 # store warning for later retrieval84 self.warning = w85 self.filename = m.filename86 self.lineno = m.lineno87 return88 # Now we simply try to choose a helpful failure message89 if first_matching is not None:90 raise self.failureException(91 '%r does not match %r' % (92 self.expected_regex.pattern, str(first_matching)))93 if self.obj_name:94 raise self.failureException(95 '%s not triggered by %s' % (exc_name, self.obj_name))96 else:97 raise self.failureException('%s not triggered' % exc_name)98class CaseMixin(object):99 """Mixin class that adds the utility methods to any unittest TestCase100 class."""101 def patch(self, *path, **options):102 """Patch object until test case returns.103 Example::104 from case import Case105 class test_Frobulator(Case):106 def setup(self):107 frobulate = self.patch('some.where.Frobulator.frobulate')108 """109 manager = mock.patch('.'.join(path), **options)110 patched = manager.start()111 self.addCleanup(manager.stop)112 return patched113 def mock_modules(self, *mods):114 """Mock modules for the duration of the test.115 See :func:`case.mock.module`116 """117 modules = []118 for mod in mods:119 mod = mod.split('.')120 modules.extend(reversed([121 '.'.join(mod[:-i] if i else mod) for i in range(len(mod))122 ]))123 modules = sorted(set(modules))124 return self.wrap_context(mock.module(*modules))125 def mask_modules(self, *modules):126 """Make modules for the duration of the test.127 See :func:`case.mock.mask_modules`.128 """129 self.wrap_context(mock.mask_modules(*modules))130 def wrap_context(self, context):131 """Wrap context so that the context exits when the test completes."""132 ret = context.__enter__()133 self.addCleanup(partial(context.__exit__, None, None, None))134 return ret135 def mock_environ(self, env_name, env_value):136 """Mock environment variable value for the duration of the test.137 See :func:`case.mock.environ`.138 """139 return self.wrap_context(mock.environ(env_name, env_value))140class Case(unittest.TestCase, CaseMixin):141 """Test Case142 Subclass of :class:`unittest.TestCase` adding convenience143 methods.144 **setup / teardown**145 New :meth:`setup` and :meth:`teardown` methods can be defined146 in addition to the core :meth:`setUp` + :meth:`tearDown`147 methods.148 Note: If you redefine the core :meth:`setUp` + :meth:`tearDown`149 methods you must make sure ``super`` is called.150 ``super`` is not necessary for the lowercase versions.151 **Python 2.6 compatibility**152 This class also implements :meth:`assertWarns`, :meth:`assertWarnsRegex`,153 :meth:`assertDictContainsSubset`, and :meth:`assertItemsEqual`154 which are not available in the original Python 2.6 unittest155 implementation.156 """157 DeprecationWarning = DeprecationWarning158 PendingDeprecationWarning = PendingDeprecationWarning159 def setUp(self):160 self.setup()161 def tearDown(self):162 self.teardown()163 def setup(self):164 pass165 def teardown(self):166 pass167 def assertWarns(self, expected_warning):168 return _AssertWarnsContext(expected_warning, self, None)169 def assertWarnsRegex(self, expected_warning, expected_regex):170 return _AssertWarnsContext(expected_warning, self,171 None, expected_regex)172 @contextmanager173 def assertDeprecated(self):174 with self.assertWarnsRegex(self.DeprecationWarning,175 r'scheduled for removal'):176 yield177 @contextmanager178 def assertPendingDeprecation(self):179 with self.assertWarnsRegex(self.PendingDeprecationWarning,180 r'scheduled for deprecation'):181 yield182 def assertDictContainsSubset(self, expected, actual, msg=None):183 missing, mismatched = [], []184 for key, value in items(expected):185 if key not in actual:186 missing.append(key)187 elif value != actual[key]:188 mismatched.append('%s, expected: %s, actual: %s' % (189 safe_repr(key), safe_repr(value),190 safe_repr(actual[key])))191 if not (missing or mismatched):192 return193 standard_msg = ''194 if missing:195 standard_msg = 'Missing: %s' % ','.join(map(safe_repr, missing))196 if mismatched:197 if standard_msg:198 standard_msg += '; '199 standard_msg += 'Mismatched values: %s' % (200 ','.join(mismatched))201 self.fail(self._formatMessage(msg, standard_msg))202 def assertItemsEqual(self, expected_seq, actual_seq, msg=None):203 missing = unexpected = None204 try:205 expected = sorted(expected_seq)206 actual = sorted(actual_seq)207 except TypeError:208 # Unsortable items (example: set(), complex(), ...)209 expected = list(expected_seq)210 actual = list(actual_seq)211 missing, unexpected = unorderable_list_difference(212 expected, actual)213 else:214 return self.assertSequenceEqual(expected, actual, msg=msg)215 errors = []216 if missing:217 errors.append(218 'Expected, but missing:\n %s' % (safe_repr(missing),)219 )220 if unexpected:221 errors.append(222 'Unexpected, but present:\n %s' % (safe_repr(unexpected),)223 )224 if errors:225 standardMsg = '\n'.join(errors)...

Full Screen

Full Screen

_unittest_backport.py

Source:_unittest_backport.py Github

copy

Full Screen

1"""2This is a backport of assertRaises() and assertRaisesRegex from Python 3.5.43The original copyright message is as follows4Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's5Smalltalk testing framework (used with permission).6This module contains the core framework classes that form the basis of7specific test cases and suites (TestCase, TestSuite etc.), and also a8text-based utility class for running the tests and reporting the results9 (TextTestRunner).10Simple usage:11 import unittest12 class IntegerArithmeticTestCase(unittest.TestCase):13 def testAdd(self): # test method names begin with 'test'14 self.assertEqual((1 + 2), 3)15 self.assertEqual(0 + 1, 1)16 def testMultiply(self):17 self.assertEqual((0 * 10), 0)18 self.assertEqual((5 * 8), 40)19 if __name__ == '__main__':20 unittest.main()21Further information is available in the bundled documentation, and from22 http://docs.python.org/library/unittest.html23Copyright (c) 1999-2003 Steve Purcell24Copyright (c) 2003-2010 Python Software Foundation25This module is free software, and you may redistribute it and/or modify26it under the same terms as Python itself, so long as this copyright message27and disclaimer are retained in their original form.28IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,29SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF30THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH31DAMAGE.32THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT33LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A34PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,35AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,36SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.37"""38import re39import warnings40import unittest41def _is_subtype(expected, basetype):42 if isinstance(expected, tuple):43 return all(_is_subtype(e, basetype) for e in expected)44 return isinstance(expected, type) and issubclass(expected, basetype)45class _BaseTestCaseContext:46 def __init__(self, test_case):47 self.test_case = test_case48 def _raiseFailure(self, standardMsg):49 msg = self.test_case._formatMessage(self.msg, standardMsg)50 raise self.test_case.failureException(msg)51class _AssertRaisesBaseContext(_BaseTestCaseContext):52 def __init__(self, expected, test_case, expected_regex=None):53 _BaseTestCaseContext.__init__(self, test_case)54 self.expected = expected55 self.test_case = test_case56 if expected_regex is not None:57 expected_regex = re.compile(expected_regex)58 self.expected_regex = expected_regex59 self.obj_name = None60 self.msg = None61 def handle(self, name, args, kwargs):62 """63 If args is empty, assertRaises/Warns is being used as a64 context manager, so check for a 'msg' kwarg and return self.65 If args is not empty, call a callable passing positional and keyword66 arguments.67 """68 try:69 if not _is_subtype(self.expected, self._base_type):70 raise TypeError('%s() arg 1 must be %s' %71 (name, self._base_type_str))72 if args and args[0] is None:73 warnings.warn("callable is None",74 DeprecationWarning, 3)75 args = ()76 if not args:77 self.msg = kwargs.pop('msg', None)78 if kwargs:79 warnings.warn('%r is an invalid keyword argument for '80 'this function' % next(iter(kwargs)),81 DeprecationWarning, 3)82 return self83 callable_obj, args = args[0], args[1:]84 try:85 self.obj_name = callable_obj.__name__86 except AttributeError:87 self.obj_name = str(callable_obj)88 with self:89 callable_obj(*args, **kwargs)90 finally:91 # bpo-23890: manually break a reference cycle92 self = None93class _AssertRaisesContext(_AssertRaisesBaseContext):94 """A context manager used to implement TestCase.assertRaises* methods."""95 _base_type = BaseException96 _base_type_str = 'an exception type or tuple of exception types'97 def __enter__(self):98 return self99 def __exit__(self, exc_type, exc_value, tb):100 if exc_type is None:101 try:102 exc_name = self.expected.__name__103 except AttributeError:104 exc_name = str(self.expected)105 if self.obj_name:106 self._raiseFailure("{} not raised by {}".format(exc_name,107 self.obj_name))108 else:109 self._raiseFailure("{} not raised".format(exc_name))110 if not issubclass(exc_type, self.expected):111 return False112 if self.expected_regex is None:113 return True114 expected_regex = self.expected_regex115 if not expected_regex.search(str(exc_value)):116 self._raiseFailure('"{}" does not match "{}"'.format(117 expected_regex.pattern, str(exc_value)))118 return True119class TestCase(unittest.TestCase):120 longMessage = True121 failureException = AssertionError122 def _formatMessage(self, msg, standardMsg):123 """Honour the longMessage attribute when generating failure messages.124 If longMessage is False this means:125 * Use only an explicit message if it is provided126 * Otherwise use the standard message for the assert127 If longMessage is True:128 * Use the standard message129 * If an explicit message is provided, plus ' : ' and the explicit msg130 """131 if not self.longMessage:132 return msg or standardMsg133 if msg is None:134 return standardMsg135 try:136 # don't switch to '{}' formatting in Python 2.X137 # it changes the way unicode input is handled138 return '%s : %s' % (standardMsg, msg)139 except UnicodeDecodeError:140 return '%s : %s' % (standardMsg, msg)141 def assertRaises(self, expected_exception, *args, **kwargs):142 """Fail unless an exception of class expected_exception is raised143 by the callable when invoked with specified positional and144 keyword arguments. If a different type of exception is145 raised, it will not be caught, and the test case will be146 deemed to have suffered an error, exactly as for an147 unexpected exception.148 If called with the callable and arguments omitted, will return a149 context object used like this::150 with self.assertRaises(SomeException):151 do_something()152 An optional keyword argument 'msg' can be provided when assertRaises153 is used as a context object.154 The context manager keeps a reference to the exception as155 the 'exception' attribute. This allows you to inspect the156 exception after the assertion::157 with self.assertRaises(SomeException) as cm:158 do_something()159 the_exception = cm.exception160 self.assertEqual(the_exception.error_code, 3)161 """162 context = _AssertRaisesContext(expected_exception, self)163 try:164 return context.handle('assertRaises', args, kwargs)165 finally:166 # bpo-23890: manually break a reference cycle167 context = None168 def assertRaisesRegex(self, expected_exception,169 expected_regex, *args, **kwargs):170 """Asserts that the message in a raised exception matches a regex.171 Args:172 expected_exception: Exception class expected to be raised.173 expected_regex: Regex (re pattern object or string) expected174 to be found in error message.175 args: Function to be called and extra positional args.176 kwargs: Extra kwargs.177 msg: Optional message used in case of failure. Can only be used178 when assertRaisesRegex is used as a context manager.179 """180 context = _AssertRaisesContext(expected_exception,181 self, expected_regex)...

Full Screen

Full Screen

utils.py

Source:utils.py Github

copy

Full Screen

1from __future__ import print_function2import functools3import os4import re5import shutil6import sys7import tempfile8import subprocess9from catkin_tools.commands.catkin import main as catkin_main10try:11 # Python212 from StringIO import StringIO13except ImportError:14 # Python315 from io import StringIO16try:17 from subprocess import TimeoutExpired18except ImportError:19 class TimeoutExpired(object):20 pass21TESTS_DIR = os.path.dirname(__file__)22MOCK_DIR = os.path.join(TESTS_DIR, 'mock_resources')23def catkin_success(args, env={}):24 orig_environ = dict(os.environ)25 try:26 os.environ.update(env)27 catkin_main(args)28 except SystemExit as exc:29 ret = exc.code30 if ret != 0:31 import traceback32 traceback.print_exc()33 finally:34 os.environ = orig_environ35 return ret == 036def catkin_failure(args, env={}):37 orig_environ = dict(os.environ)38 try:39 os.environ.update(env)40 catkin_main(args)41 except SystemExit as exc:42 ret = exc.code43 finally:44 os.environ = orig_environ45 return ret != 046class AssertRaisesContext(object):47 def __init__(self, expected, expected_regex=None):48 self.expected = expected49 self.expected_regex = expected_regex50 def __enter__(self):51 return self52 def __exit__(self, exc_type, exc_value, tb):53 if self.expected is None:54 if exc_type is None:55 return True56 else:57 raise58 if exc_type is None:59 try:60 exc_name = self.expected.__name__61 except AttributeError:62 exc_name = str(self.expected)63 raise AssertionError("{0} not raised".format(exc_name))64 if not issubclass(exc_type, self.expected):65 raise66 if self.expected_regex is None:67 return True68 expected_regex = self.expected_regex69 expected_regex = re.compile(expected_regex)70 if not expected_regex.search(str(exc_value)):71 raise AssertionError("'{0}' does not match '{1}'".format(expected_regex.pattern, str(exc_value)))72 return True73class redirected_stdio(object):74 def __enter__(self):75 self.original_stdout = sys.stdout76 self.original_stderr = sys.stderr77 self.out = StringIO()78 self.err = StringIO()79 sys.stdout = self.out80 sys.stderr = self.err81 return self.out, self.err82 def __exit__(self, exc_type, exc_value, traceback):83 sys.stdout = self.original_stdout84 sys.stderr = self.original_stderr85 print(self.out.getvalue())86class temporary_directory(object):87 def __init__(self, prefix=''):88 self.prefix = prefix89 self.delete = False90 def __enter__(self):91 self.original_cwd = os.getcwd()92 self.temp_path = tempfile.mkdtemp(prefix=self.prefix)93 os.chdir(self.temp_path)94 return self.temp_path95 def __exit__(self, exc_type, exc_value, traceback):96 if self.delete and self.temp_path and os.path.exists(self.temp_path):97 print('Deleting temporary testind directory: %s' % self.temp_path)98 shutil.rmtree(self.temp_path)99 if self.original_cwd and os.path.exists(self.original_cwd):100 os.chdir(self.original_cwd)101def in_temporary_directory(f):102 @functools.wraps(f)103 def decorated(*args, **kwds):104 with temporary_directory() as directory:105 from inspect import getargspec106 # If it takes directory of kwargs and kwds does already have107 # directory, inject it108 if 'directory' not in kwds and 'directory' in getargspec(f)[0]:109 kwds['directory'] = directory110 return f(*args, **kwds)111 decorated.__name__ = f.__name__112 return decorated113def run(args, **kwargs):114 """115 Call to Popen, returns (errcode, stdout, stderr)116 """117 print("run:", args)118 p = subprocess.Popen(119 args,120 stdout=subprocess.PIPE,121 stderr=subprocess.STDOUT,122 universal_newlines=True,123 cwd=kwargs.get('cwd', os.getcwd()))124 print("P==", p.__dict__)125 (stdout, stderr) = p.communicate()126 return (p.returncode, stdout, stderr)127def assert_cmd_success(cmd, **kwargs):128 """129 Asserts that running a command returns zero.130 returns: stdout131 """132 print(">>>", cmd, kwargs)133 (r, out, err) = run(cmd, **kwargs)134 print("<<<", str(out))135 assert r == 0, "cmd failed with result %s:\n %s " % (r, str(cmd))136 return out137def assert_cmd_failure(cmd, **kwargs):138 """139 Asserts that running a command returns non-zero.140 returns: stdout141 """142 print(">>>", cmd, kwargs)143 (r, out, err) = run(cmd, withexitstatus=True, **kwargs)144 print("<<<", str(out))145 assert 0 != r, "cmd succeeded, but it should fail: %s result=%u\noutput=\n%s" % (cmd, r, out)146 return out147def assert_files_exist(prefix, files):148 """149 Assert that all files exist in the prefix.150 """151 for f in files:152 p = os.path.join(prefix, f)153 print("Checking for", p)...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python 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