Best Python code snippet using pytest
test_safe_repr.py
Source:test_safe_repr.py
...17 unicode = str18 xrange = range19class SafeReprTestBase(object):20 saferepr = SafeRepr()21 def assert_saferepr(self, value, expected):22 safe = self.saferepr(value)23 if len(safe) != len(expected):24 raise AssertionError('Expected:\n%s\nFound:\n%s\n Expected len: %s Found len: %s' % (25 expected, safe, len(expected), len(safe),))26 assert safe == expected27 return safe28 def assert_unchanged(self, value, expected):29 actual = repr(value)30 safe = self.assert_saferepr(value, expected)31 assert safe == actual32 def assert_shortened(self, value, expected):33 actual = repr(value)34 safe = self.assert_saferepr(value, expected)35 assert safe != actual36 def assert_saferepr_regex(self, s, r):37 safe = self.saferepr(s)38 assert re.search(r, safe) is not None39 return safe40 def assert_unchanged_regex(self, value, expected):41 actual = repr(value)42 safe = self.assert_saferepr_regex(value, expected)43 assert safe == actual44 def assert_shortened_regex(self, value, expected):45 actual = repr(value)46 safe = self.assert_saferepr_regex(value, expected)47 assert safe != actual48class TestSafeRepr(SafeReprTestBase):49 def test_collection_types(self):50 colltypes = [t for t, _, _, _ in SafeRepr.collection_types]51 assert colltypes == [52 tuple,53 list,54 frozenset,55 set,56 collections.deque,57 ]58 def test_largest_repr(self):59 # Find the largest possible repr and ensure it is below our arbitrary60 # limit (8KB).61 coll = '-' * (SafeRepr.maxstring_outer * 2)62 for limit in reversed(SafeRepr.maxcollection[1:]):63 coll = [coll] * (limit * 2)64 dcoll = {}65 for i in range(SafeRepr.maxcollection[0]):66 dcoll[str(i) * SafeRepr.maxstring_outer] = coll67 text = self.saferepr(dcoll)68 # try:69 # text_repr = repr(dcoll)70 # except MemoryError:71 # print('Memory error raised while creating repr of test data')72 # text_repr = ''73 # print('len(SafeRepr()(dcoll)) = ' + str(len(text)) +74 # ', len(repr(coll)) = ' + str(len(text_repr)))75 assert len(text) < 819276class TestStrings(SafeReprTestBase):77 def test_str_small(self):78 value = 'A' * 579 self.assert_unchanged(value, "'AAAAA'")80 self.assert_unchanged([value], "['AAAAA']")81 def test_str_large(self):82 value = 'A' * (SafeRepr.maxstring_outer + 10)83 self.assert_shortened(value,84 "'" + 'A' * 43690 + "..." + 'A' * 21845 + "'")85 self.assert_shortened([value], "['AAAAAAAAAAAAAAAAAAAA...AAAAAAAAAA']")86 def test_str_largest_unchanged(self):87 value = 'A' * (SafeRepr.maxstring_outer)88 self.assert_unchanged(value, "'" + 'A' * 65536 + "'")89 def test_str_smallest_changed(self):90 value = 'A' * (SafeRepr.maxstring_outer + 1)91 self.assert_shortened(value,92 "'" + 'A' * 43690 + "..." + 'A' * 21845 + "'")93 def test_str_list_largest_unchanged(self):94 value = 'A' * (SafeRepr.maxstring_inner)95 self.assert_unchanged([value], "['AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA']")96 def test_str_list_smallest_changed(self):97 value = 'A' * (SafeRepr.maxstring_inner + 1)98 self.assert_shortened([value], "['AAAAAAAAAAAAAAAAAAAA...AAAAAAAAAA']")99 @pytest.mark.skipif(sys.version_info > (3, 0), reason='Py2 specific test')100 def test_unicode_small(self):101 value = u'A' * 5102 self.assert_unchanged(value, "u'AAAAA'")103 self.assert_unchanged([value], "[u'AAAAA']")104 @pytest.mark.skipif(sys.version_info > (3, 0), reason='Py2 specific test')105 def test_unicode_large(self):106 value = u'A' * (SafeRepr.maxstring_outer + 10)107 self.assert_shortened(value,108 "u'" + 'A' * 43690 + "..." + 'A' * 21845 + "'")109 self.assert_shortened([value], "[u'AAAAAAAAAAAAAAAAAAAA...AAAAAAAAAA']")110 @pytest.mark.skipif(sys.version_info < (3, 0), reason='Py3 specific test')111 def test_bytes_small(self):112 value = b'A' * 5113 self.assert_unchanged(value, "b'AAAAA'")114 self.assert_unchanged([value], "[b'AAAAA']")115 @pytest.mark.skipif(sys.version_info < (3, 0), reason='Py3 specific test')116 def test_bytes_large(self):117 value = b'A' * (SafeRepr.maxstring_outer + 10)118 self.assert_shortened(value,119 "b'" + 'A' * 43690 + "..." + 'A' * 21845 + "'")120 self.assert_shortened([value], "[b'AAAAAAAAAAAAAAAAAAAA...AAAAAAAAAA']")121 # @pytest.mark.skip(reason='not written') # TODO: finish!122 # def test_bytearray_small(self):123 # raise NotImplementedError124 #125 # @pytest.mark.skip(reason='not written') # TODO: finish!126 # def test_bytearray_large(self):127 # raise NotImplementedError128class RawValueTests(SafeReprTestBase):129 def setUp(self):130 super(RawValueTests, self).setUp()131 self.saferepr.raw_value = True132 def test_unicode_raw(self):133 value = u'A\u2000' * 10000134 self.assert_saferepr(value, value)135 def test_bytes_raw(self):136 value = b'A' * 10000137 self.assert_saferepr(value, value.decode('ascii'))138 def test_bytearray_raw(self):139 value = bytearray(b'A' * 5)140 self.assert_saferepr(value, value.decode('ascii'))141# class TestNumbers(SafeReprTestBase):142#143# @pytest.mark.skip(reason='not written') # TODO: finish!144# def test_int(self):145# raise NotImplementedError146#147# @pytest.mark.skip(reason='not written') # TODO: finish!148# def test_float(self):149# raise NotImplementedError150#151# @pytest.mark.skip(reason='not written') # TODO: finish!152# def test_complex(self):153# raise NotImplementedError154class ContainerBase(object):155 CLASS = None156 LEFT = None157 RIGHT = None158 @property159 def info(self):160 try:161 return self._info162 except AttributeError:163 for info in SafeRepr.collection_types:164 ctype, _, _, _ = info165 if self.CLASS is ctype:166 type(self)._info = info167 return info168 else:169 raise TypeError('unsupported')170 def _combine(self, items, prefix, suffix, large):171 contents = ', '.join(str(item) for item in items)172 if large:173 contents += ', ...'174 return prefix + contents + suffix175 def combine(self, items, large=False):176 if self.LEFT is None:177 pytest.skip('unsupported')178 return self._combine(items, self.LEFT, self.RIGHT, large=large)179 def combine_nested(self, depth, items, large=False):180 _, _prefix, _suffix, comma = self.info181 prefix = _prefix * (depth + 1)182 if comma:183 suffix = _suffix + ("," + _suffix) * depth184 else:185 suffix = _suffix * (depth + 1)186 # print("ctype = " + ctype.__name__ + ", maxcollection[" +187 # str(i) + "] == " + str(SafeRepr.maxcollection[i]))188 return self._combine(items, prefix, suffix, large=large)189 def test_large_flat(self):190 c1 = self.CLASS(range(SafeRepr.maxcollection[0] * 2))191 items = range(SafeRepr.maxcollection[0] - 1)192 c1_expect = self.combine(items, large=True)193 self.assert_shortened(c1, c1_expect)194 def test_large_nested(self):195 c1 = self.CLASS(range(SafeRepr.maxcollection[0] * 2))196 c1_items = range(SafeRepr.maxcollection[1] - 1)197 c1_expect = self.combine(c1_items, large=True)198 c2 = self.CLASS(c1 for _ in range(SafeRepr.maxcollection[0] * 2))199 items = (c1_expect for _ in range(SafeRepr.maxcollection[0] - 1))200 c2_expect = self.combine(items, large=True)201 self.assert_shortened(c2, c2_expect)202 # @pytest.mark.skip(reason='not written') # TODO: finish!203 # def test_empty(self):204 # raise NotImplementedError205 #206 # @pytest.mark.skip(reason='not written') # TODO: finish!207 # def test_subclass(self):208 # raise NotImplementedError209 def test_boundary(self):210 items1 = range(SafeRepr.maxcollection[0] - 1)211 items2 = range(SafeRepr.maxcollection[0])212 items3 = range(SafeRepr.maxcollection[0] + 1)213 c1 = self.CLASS(items1)214 c2 = self.CLASS(items2)215 c3 = self.CLASS(items3)216 expected1 = self.combine(items1)217 expected2 = self.combine(items2[:-1], large=True)218 expected3 = self.combine(items3[:-2], large=True)219 self.assert_unchanged(c1, expected1)220 self.assert_shortened(c2, expected2)221 self.assert_shortened(c3, expected3)222 def test_nested(self):223 ctype = self.CLASS224 for i in range(1, len(SafeRepr.maxcollection)):225 items1 = range(SafeRepr.maxcollection[i] - 1)226 items2 = range(SafeRepr.maxcollection[i])227 items3 = range(SafeRepr.maxcollection[i] + 1)228 c1 = self.CLASS(items1)229 c2 = self.CLASS(items2)230 c3 = self.CLASS(items3)231 for _j in range(i):232 c1, c2, c3 = ctype((c1,)), ctype((c2,)), ctype((c3,))233 expected1 = self.combine_nested(i, items1)234 expected2 = self.combine_nested(i, items2[:-1], large=True)235 expected3 = self.combine_nested(i, items3[:-2], large=True)236 self.assert_unchanged(c1, expected1)237 self.assert_shortened(c2, expected2)238 self.assert_shortened(c3, expected3)239class TestTuples(ContainerBase, SafeReprTestBase):240 CLASS = tuple241 LEFT = '('242 RIGHT = ')'243class TestLists(ContainerBase, SafeReprTestBase):244 CLASS = list245 LEFT = '['246 RIGHT = ']'247 def test_directly_recursive(self):248 value = [1, 2]249 value.append(value)250 self.assert_unchanged(value, '[1, 2, [...]]')251 def test_indirectly_recursive(self):252 value = [1, 2]253 value.append([value])254 self.assert_unchanged(value, '[1, 2, [[...]]]')255class TestFrozensets(ContainerBase, SafeReprTestBase):256 CLASS = frozenset257class TestSets(ContainerBase, SafeReprTestBase):258 CLASS = set259 if PY_VER != 2:260 LEFT = '{'261 RIGHT = '}'262 def test_nested(self):263 pytest.skip('unsupported')264 def test_large_nested(self):265 pytest.skip('unsupported')266class TestDicts(SafeReprTestBase):267 def test_large_key(self):268 value = {269 'a' * SafeRepr.maxstring_inner * 3: '',270 }271 self.assert_shortened_regex(value, r"{'a+\.\.\.a+': ''}")272 def test_large_value(self):273 value = {274 '': 'a' * SafeRepr.maxstring_inner * 2,275 }276 self.assert_shortened_regex(value, r"{'': 'a+\.\.\.a+'}")277 def test_large_both(self):278 value = {}279 key = 'a' * SafeRepr.maxstring_inner * 2280 value[key] = key281 self.assert_shortened_regex(value, r"{'a+\.\.\.a+': 'a+\.\.\.a+'}")282 def test_nested_value(self):283 d1 = {}284 d1_key = 'a' * SafeRepr.maxstring_inner * 2285 d1[d1_key] = d1_key286 d2 = {d1_key: d1}287 d3 = {d1_key: d2}288 self.assert_shortened_regex(d2, r"{'a+\.\.\.a+': {'a+\.\.\.a+': 'a+\.\.\.a+'}}") # noqa289 if len(SafeRepr.maxcollection) == 2:290 self.assert_shortened_regex(d3, r"{'a+\.\.\.a+': {'a+\.\.\.a+': {\.\.\.}}}") # noqa291 else:292 self.assert_shortened_regex(d3, r"{'a+\.\.\.a+': {'a+\.\.\.a+': {'a+\.\.\.a+': 'a+\.\.\.a+'}}}") # noqa293 def test_empty(self):294 # Ensure empty dicts work295 self.assert_unchanged({}, '{}')296 def test_sorted(self):297 # Ensure dict keys are sorted298 d1 = {}299 d1['c'] = None300 d1['b'] = None301 d1['a'] = None302 if IS_PY36_OR_GREATER:303 self.assert_saferepr(d1, "{'c': None, 'b': None, 'a': None}")304 else:305 self.assert_saferepr(d1, "{'a': None, 'b': None, 'c': None}")306 @pytest.mark.skipif(sys.version_info < (3, 0), reason='Py3 specific test')307 def test_unsortable_keys(self):308 # Ensure dicts with unsortable keys do not crash309 d1 = {}310 for _ in range(100):311 d1[object()] = None312 with pytest.raises(TypeError):313 list(sorted(d1))314 self.saferepr(d1)315 def test_directly_recursive(self):316 value = {1: None}317 value[2] = value318 self.assert_unchanged(value, '{1: None, 2: {...}}')319 def test_indirectly_recursive(self):320 value = {1: None}321 value[2] = {3: value}322 self.assert_unchanged(value, '{1: None, 2: {3: {...}}}')323class TestOtherPythonTypes(SafeReprTestBase):324 # not critical to test:325 # singletons326 # <function>327 # <class>328 # <iterator>329 # memoryview330 # classmethod331 # staticmethod332 # property333 # enumerate334 # reversed335 # object336 # type337 # super338 # @pytest.mark.skip(reason='not written') # TODO: finish!339 # def test_file(self):340 # raise NotImplementedError341 def test_range_small(self):342 range_name = xrange.__name__343 value = xrange(1, 42)344 self.assert_unchanged(value, '%s(1, 42)' % (range_name,))345 @pytest.mark.skipif(sys.version_info < (3, 0), reason='Py3 specific test')346 def test_range_large_stop_only(self):347 range_name = xrange.__name__348 stop = SafeRepr.maxcollection[0]349 value = xrange(stop)350 self.assert_unchanged(value,351 '%s(0, %s)' % (range_name, stop))352 def test_range_large_with_start(self):353 range_name = xrange.__name__354 stop = SafeRepr.maxcollection[0] + 1355 value = xrange(1, stop)356 self.assert_unchanged(value,357 '%s(1, %s)' % (range_name, stop))358 # @pytest.mark.skip(reason='not written') # TODO: finish!359 # def test_named_struct(self):360 # # e.g. sys.version_info361 # raise NotImplementedError362 #363 # @pytest.mark.skip(reason='not written') # TODO: finish!364 # def test_namedtuple(self):365 # raise NotImplementedError366 #367 # @pytest.mark.skip(reason='not written') # TODO: finish!368 # @pytest.mark.skipif(sys.version_info < (3, 0), reason='Py3 specific test')369 # def test_SimpleNamespace(self):370 # raise NotImplementedError371class TestUserDefinedObjects(SafeReprTestBase):372 def test_broken_repr(self):373 class TestClass(object):374 def __repr__(self):375 raise NameError376 value = TestClass()377 with pytest.raises(NameError):378 repr(TestClass())379 self.assert_saferepr(value, object.__repr__(value))380 def test_large(self):381 class TestClass(object):382 def __repr__(self):383 return '<' + 'A' * SafeRepr.maxother_outer * 2 + '>'384 value = TestClass()385 self.assert_shortened_regex(value, r'\<A+\.\.\.A+\>')386 def test_inherit_repr(self):387 class TestClass(dict):388 pass389 value_dict = TestClass()390 class TestClass2(list):391 pass392 value_list = TestClass2()393 self.assert_unchanged(value_dict, '{}')...
test_saferepr.py
Source:test_saferepr.py
1import pytest2from _pytest._io.saferepr import _pformat_dispatch3from _pytest._io.saferepr import saferepr4def test_simple_repr():5 assert saferepr(1) == "1"6 assert saferepr(None) == "None"7def test_maxsize():8 s = saferepr("x" * 50, maxsize=25)9 assert len(s) == 2510 expected = repr("x" * 10 + "..." + "x" * 10)11 assert s == expected12def test_maxsize_error_on_instance():13 class A:14 def __repr__(self):15 raise ValueError("...")16 s = saferepr(("*" * 50, A()), maxsize=25)17 assert len(s) == 2518 assert s[0] == "(" and s[-1] == ")"19def test_exceptions() -> None:20 class BrokenRepr:21 def __init__(self, ex):22 self.ex = ex23 def __repr__(self):24 raise self.ex25 class BrokenReprException(Exception):26 __str__ = None # type: ignore[assignment]27 __repr__ = None # type: ignore[assignment]28 assert "Exception" in saferepr(BrokenRepr(Exception("broken")))29 s = saferepr(BrokenReprException("really broken"))30 assert "TypeError" in s31 assert "TypeError" in saferepr(BrokenRepr("string"))32 none = None33 try:34 none() # type: ignore[misc]35 except BaseException as exc:36 exp_exc = repr(exc)37 obj = BrokenRepr(BrokenReprException("omg even worse"))38 s2 = saferepr(obj)39 assert s2 == (40 "<[unpresentable exception ({!s}) raised in repr()] BrokenRepr object at 0x{:x}>".format(41 exp_exc, id(obj)42 )43 )44def test_baseexception():45 """Test saferepr() with BaseExceptions, which includes pytest outcomes."""46 class RaisingOnStrRepr(BaseException):47 def __init__(self, exc_types):48 self.exc_types = exc_types49 def raise_exc(self, *args):50 try:51 self.exc_type = self.exc_types.pop(0)52 except IndexError:53 pass54 if hasattr(self.exc_type, "__call__"):55 raise self.exc_type(*args)56 raise self.exc_type57 def __str__(self):58 self.raise_exc("__str__")59 def __repr__(self):60 self.raise_exc("__repr__")61 class BrokenObj:62 def __init__(self, exc):63 self.exc = exc64 def __repr__(self):65 raise self.exc66 __str__ = __repr__67 baseexc_str = BaseException("__str__")68 obj = BrokenObj(RaisingOnStrRepr([BaseException]))69 assert saferepr(obj) == (70 "<[unpresentable exception ({!r}) "71 "raised in repr()] BrokenObj object at 0x{:x}>".format(baseexc_str, id(obj))72 )73 obj = BrokenObj(RaisingOnStrRepr([RaisingOnStrRepr([BaseException])]))74 assert saferepr(obj) == (75 "<[{!r} raised in repr()] BrokenObj object at 0x{:x}>".format(76 baseexc_str, id(obj)77 )78 )79 with pytest.raises(KeyboardInterrupt):80 saferepr(BrokenObj(KeyboardInterrupt()))81 with pytest.raises(SystemExit):82 saferepr(BrokenObj(SystemExit()))83 with pytest.raises(KeyboardInterrupt):84 saferepr(BrokenObj(RaisingOnStrRepr([KeyboardInterrupt])))85 with pytest.raises(SystemExit):86 saferepr(BrokenObj(RaisingOnStrRepr([SystemExit])))87 with pytest.raises(KeyboardInterrupt):88 print(saferepr(BrokenObj(RaisingOnStrRepr([BaseException, KeyboardInterrupt]))))89 with pytest.raises(SystemExit):90 saferepr(BrokenObj(RaisingOnStrRepr([BaseException, SystemExit])))91def test_buggy_builtin_repr():92 # Simulate a case where a repr for a builtin raises.93 # reprlib dispatches by type name, so use "int".94 class int:95 def __repr__(self):96 raise ValueError("Buggy repr!")97 assert "Buggy" in saferepr(int())98def test_big_repr():99 from _pytest._io.saferepr import SafeRepr100 assert len(saferepr(range(1000))) <= len("[" + SafeRepr(0).maxlist * "1000" + "]")101def test_repr_on_newstyle() -> None:102 class Function:103 def __repr__(self):104 return "<%s>" % (self.name) # type: ignore[attr-defined]105 assert saferepr(Function())106def test_unicode():107 val = "£â¬"108 reprval = "'£â¬'"109 assert saferepr(val) == reprval110def test_pformat_dispatch():111 assert _pformat_dispatch("a") == "'a'"112 assert _pformat_dispatch("a" * 10, width=5) == "'aaaaaaaaaa'"113 assert _pformat_dispatch("foo bar", width=5) == "('foo '\n 'bar')"114def test_broken_getattribute():115 """saferepr() can create proper representations of classes with116 broken __getattribute__ (#7145)117 """118 class SomeClass:119 def __getattribute__(self, attr):120 raise RuntimeError121 def __repr__(self):122 raise RuntimeError123 assert saferepr(SomeClass()).startswith(124 "<[RuntimeError() raised in repr()] SomeClass object at 0x"...
request_vars.py
Source:request_vars.py
...35 for entry in list(attr_dict.keys()):36 if entry.startswith('tgdb_'):37 del attr_dict[entry]38 vars['GET'] = [(k, request.GET.getall(k)) for k in request.GET]39 vars['POST'] = [(k, [saferepr(p)40 for p in request.POST.getall(k)]) for k in request.POST]41 vars['Cookies'] = [(k, request.cookies.get(k))42 for k in request.cookies]43 vars['Headers'] = [(k, saferepr(v))44 for k, v in request.environ.items()45 if k.startswith('HTTP_') or k in request_header_filter]46 vars['Request Attributes'] = [(k, saferepr(v))47 for k, v in attr_dict.items() if not callable(v)]48 vars['Environ'] = [(k, saferepr(v))49 for k, v in request.environ.items()]50 return unicode_text(render(51 dict(vars=vars),52 tg.config['debugbar.engine'], 'tgext.debugbar.sections.templates.request!html'...
Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.
Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.
https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP
Get 100 minutes of automation test minutes FREE!!