How to use raises method in Sure

Best Python code snippet using sure_python

test_paramparser.py

Source:test_paramparser.py Github

copy

Full Screen

...111 def testUnitArgument(self):112 result = paramparser.UnitArgument('7mm', float, ['%', 'mm'])113 assert result.get_default() == (7.0, 'mm')114 assert result.parse_argument('8%') == (8.0, '%')115 pytest.raises(ValueError, result.parse_argument, u'7m')116 pytest.raises(ValueError, result.parse_argument, u'7')117 pytest.raises(ValueError, result.parse_argument, u'mm')118 def testExtendedParser(self):119 tests = [120 (u'"a", "b", "c"', u',', None, [u'a', u'b', u'c']),121 (u'a:b, b:c, c:d', u',', u':', [(u'a', u'b'), (u'b', u'c'), (u'c', u'd')]),122 (u'a:b, b:c, c:d', u',', None, [u'a:b', u'b:c', u'c:d']),123 (u'a=b, b=c, c=d', u',', None, [u'a=b', u'b=c', u'c=d']),124 (u'a=b, b=c, c=d', u',', u'=', [(u'a', u'b'), (u'b', u'c'), (u'c', u'd')]),125 (u'"a"; "b"; "c"', u';', None, [u'a', u'b', u'c']),126 (u'a:b; b:c; c:d', u';', u':', [(u'a', u'b'), (u'b', u'c'), (u'c', u'd')]),127 (u'a:b; b:c; c:d', u';', None, [u'a:b', u'b:c', u'c:d']),128 (u'a=b; b=c; c=d', u';', None, [u'a=b', u'b=c', u'c=d']),129 (u'a=b; b=c; c=d', u';', u'=', [(u'a', u'b'), (u'b', u'c'), (u'c', u'd')]),130 (u'"a" "b" "c"', None, None, [u'a', u'b', u'c']),131 (u'" a " "b" "c"', None, None, [u' a ', u'b', u'c']),132 (u'"a " "b" "c"', None, None, [u'a ', u'b', u'c']),133 (u'" a" "b" "c"', None, None, [u' a', u'b', u'c']),134 (u'" a" "b" "c"', None, u':', [u' a', u'b', u'c']),135 (u'"a:a" "b:b" "c:b"', None, u':', [u'a:a', u'b:b', u'c:b']),136 (u' a:a ', None, u':', [None, None, None, (u'a', u'a'), None, None]),137 (u'a a: a', None, u':', [u'a', (u'a', None), u'a']),138 (u'a a:"b c d" a', None, u':', [u'a', (u'a', u'b c d'), u'a']),139 (u'a a:"b "" d" a', None, u':', [u'a', (u'a', u'b " d'), u'a']),140 (u'title:Help* dog cat', None, u':', [(u'title', u'Help*'), u'dog', u'cat']),141 (u'title:Help* "dog cat"', None, u':', [(u'title', u'Help*'), u'dog cat']),142 (u'a:b:c d:e:f', None, u':', [(u'a', u'b:c'), (u'd', 'e:f')]),143 (u'a:b:c:d', None, u':', [(u'a', u'b:c:d')]),144 ]145 def _check(args, sep, kwsep, expected):146 res = paramparser.parse_quoted_separated_ext(args, sep, kwsep)147 assert res == expected148 for test in tests:149 yield [_check] + list(test)150 def testExtendedParserBracketing(self):151 tests = [152 (u'"a", "b", "c"', u',', None, [u'a', u'b', u'c']),153 (u'("a", "b", "c")', u',', None, [[u'(', u'a', u'b', u'c']]),154 (u'("a"("b", "c"))', u',', None, [[u'(', u'a', [u'(', u'b', u'c']]]),155 (u'("a"("b)))", "c"))', u',', None, [[u'(', u'a', [u'(', u'b)))', u'c']]]),156 (u'("a"("b>>> ( ab )>", "c"))', u',', None, [[u'(', u'a', [u'(', u'b>>> ( ab )>', u'c']]]),157 (u'("a" ("b" "c"))', None, None, [[u'(', u'a', [u'(', u'b', u'c']]]),158 (u'("a"("b", "c") ) ', u',', None, [[u'(', u'a', [u'(', u'b', u'c']]]),159 (u'("a", <"b", ("c")>)', u',', None, [[u'(', u'a', [u'<', u'b', [u'(', u'c']]]]),160 (u',,,(a, b, c)', u',', None, [None, None, None, [u'(', u'a', u'b', u'c']]),161 ]162 def _check(args, sep, kwsep, expected):163 res = paramparser.parse_quoted_separated_ext(args, sep, kwsep, brackets=(u'<>', u'()'))164 assert res == expected165 for test in tests:166 yield [_check] + list(test)167 def testExtendedParserQuoting(self):168 tests = [169 (u'"a b" -a b-', u'"', [u'a b', u'-a', u'b-']),170 (u'"a b" -a b-', u"-", [u'"a', u'b"', u'a b']),171 (u'"a b" -a b-', u'"-', [u'a b', u'a b']),172 (u'"a- b" -a b-', u'"-', [u'a- b', u'a b']),173 (u'"a- b" -a" b-', u'"-', [u'a- b', u'a" b']),174 ]175 def _check(args, quotes, expected):176 res = paramparser.parse_quoted_separated_ext(args, quotes=quotes)177 assert res == expected178 for test in tests:179 yield [_check] + list(test)180 def testExtendedParserMultikey(self):181 tests = [182 (u'"a", "b", "c"', u',', None, [u'a', u'b', u'c']),183 (u'a:b, b:c, c:d', u',', u':', [(u'a', u'b'), (u'b', u'c'), (u'c', u'd')]),184 (u'a:b, b:c, c:d', u',', None, [u'a:b', u'b:c', u'c:d']),185 (u'a=b, b=c, c=d', u',', None, [u'a=b', u'b=c', u'c=d']),186 (u'a=b, b=c, c=d', u',', u'=', [(u'a', u'b'), (u'b', u'c'), (u'c', u'd')]),187 (u'"a"; "b"; "c"', u';', None, [u'a', u'b', u'c']),188 (u'a:b; b:c; c:d', u';', u':', [(u'a', u'b'), (u'b', u'c'), (u'c', u'd')]),189 (u'a:b; b:c; c:d', u';', None, [u'a:b', u'b:c', u'c:d']),190 (u'a=b; b=c; c=d', u';', None, [u'a=b', u'b=c', u'c=d']),191 (u'a=b; b=c; c=d', u';', u'=', [(u'a', u'b'), (u'b', u'c'), (u'c', u'd')]),192 (u'"a" "b" "c"', None, None, [u'a', u'b', u'c']),193 (u'" a " "b" "c"', None, None, [u' a ', u'b', u'c']),194 (u'"a " "b" "c"', None, None, [u'a ', u'b', u'c']),195 (u'" a" "b" "c"', None, None, [u' a', u'b', u'c']),196 (u'" a" "b" "c"', None, u':', [u' a', u'b', u'c']),197 (u'"a:a" "b:b" "c:b"', None, u':', [u'a:a', u'b:b', u'c:b']),198 (u' a:a ', None, u':', [None, None, None, (u'a', u'a'), None, None]),199 (u'a a: a', None, u':', [u'a', (u'a', None), u'a']),200 (u'a a:"b c d" a', None, u':', [u'a', (u'a', u'b c d'), u'a']),201 (u'a a:"b "" d" a', None, u':', [u'a', (u'a', u'b " d'), u'a']),202 (u'title:Help* dog cat', None, u':', [(u'title', u'Help*'), u'dog', u'cat']),203 (u'title:Help* "dog cat"', None, u':', [(u'title', u'Help*'), u'dog cat']),204 (u'a:b:c d:e:f', None, u':', [(u'a', u'b', u'c'), (u'd', 'e', u'f')]),205 (u'a:b:c:d', None, u':', [(u'a', u'b', u'c', u'd')]),206 (u'a:"b:c":d', None, u':', [(u'a', u'b:c', u'd')]),207 ]208 def _check(args, sep, kwsep, expected):209 res = paramparser.parse_quoted_separated_ext(args, sep, kwsep, multikey=True)210 assert res == expected211 for test in tests:212 yield [_check] + list(test)213 def testExtendedParserPrefix(self):214 P = paramparser.ParserPrefix('+')215 M = paramparser.ParserPrefix('-')216 tests = [217 (u'"a", "b", "c"', u',', None, [u'a', u'b', u'c']),218 (u'a:b, b:c, c:d', u',', u':', [(u'a', u'b'), (u'b', u'c'), (u'c', u'd')]),219 (u'a:b, b:c, c:d', u',', None, [u'a:b', u'b:c', u'c:d']),220 (u'a=b, b=c, c=d', u',', None, [u'a=b', u'b=c', u'c=d']),221 (u'a=b, b=c, c=d', u',', u'=', [(u'a', u'b'), (u'b', u'c'), (u'c', u'd')]),222 (u'"a"; "b"; "c"', u';', None, [u'a', u'b', u'c']),223 (u'a:b; b:c; c:d', u';', u':', [(u'a', u'b'), (u'b', u'c'), (u'c', u'd')]),224 (u'a:b; b:c; c:d', u';', None, [u'a:b', u'b:c', u'c:d']),225 (u'a=b; b=c; c=d', u';', None, [u'a=b', u'b=c', u'c=d']),226 (u'a=b; b=c; c=d', u';', u'=', [(u'a', u'b'), (u'b', u'c'), (u'c', u'd')]),227 (u'"a" "b" "c"', None, None, [u'a', u'b', u'c']),228 (u'" a " "b" "c"', None, None, [u' a ', u'b', u'c']),229 (u'"a " "b" "c"', None, None, [u'a ', u'b', u'c']),230 (u'" a" "b" "c"', None, None, [u' a', u'b', u'c']),231 (u'" a" "b" "c"', None, u':', [u' a', u'b', u'c']),232 (u'"a:a" "b:b" "c:b"', None, u':', [u'a:a', u'b:b', u'c:b']),233 (u' a:a ', None, u':', [None, None, None, (u'a', u'a'), None, None]),234 (u'a a: a', None, u':', [u'a', (u'a', None), u'a']),235 (u'a a:"b c d" a', None, u':', [u'a', (u'a', u'b c d'), u'a']),236 (u'a a:"b "" d" a', None, u':', [u'a', (u'a', u'b " d'), u'a']),237 (u'title:Help* dog cat', None, u':', [(u'title', u'Help*'), u'dog', u'cat']),238 (u'title:Help* "dog cat"', None, u':', [(u'title', u'Help*'), u'dog cat']),239 (u'a:b:c d:e:f', None, u':', [(u'a', u'b', u'c'), (u'd', 'e', u'f')]),240 (u'a:b:c:d', None, u':', [(u'a', u'b', u'c', u'd')]),241 (u'a:"b:c":d', None, u':', [(u'a', u'b:c', u'd')]),242 (u'-a:b:d', None, u':', [(M, u'a', u'b', u'd')]),243 (u'"-a:b:d"', None, u':', [(u'-a:b:d')]),244 (u'-"a:b:d"', None, u':', [(M, u'a:b:d')]),245 (u'-a:"b:c":"d e f g"', None, u':', [(M, u'a', u'b:c', u'd e f g')]),246 (u'+-a:b:d', None, u':', [(P, u'-a', u'b', u'd')]),247 (u'-"+a:b:d"', None, u':', [(M, u'+a:b:d')]),248 # bit of a weird case...249 (u'-+"a:b:d"', None, u':', [(M, u'+"a', u'b', u'd"')]),250 (u'-a:"b:c" a +b', None, u':', [(M, u'a', u'b:c'), u'a', (P, u'b')]),251 ]252 def _check(args, sep, kwsep, expected):253 res = paramparser.parse_quoted_separated_ext(args, sep, kwsep, multikey=True, prefixes='-+')254 assert res == expected255 for test in tests:256 yield [_check] + list(test)257 def testExtendedParserBracketingErrors(self):258 UCE = paramparser.BracketUnexpectedCloseError259 MCE = paramparser.BracketMissingCloseError260 tests = [261 (u'("a", "b", "c"', u',', None, MCE),262 (u'("a"("b", "c")', u',', None, MCE),263 (u'("a"<"b", "c")>', u',', None, UCE),264 (u')("a" ("b" "c"))', None, None, UCE),265 (u'("a", ("b", "c">))', u',', None, UCE),266 (u'("a", ("b", <"c">>))', u',', None, UCE),267 (u'(<(<)>)>', u',', None, UCE),268 ]269 def _check(args, sep, kwsep, err):270 pytest.raises(err,271 paramparser.parse_quoted_separated_ext,272 args, sep, kwsep,273 brackets=(u'<>', u'()'))274 for test in tests:275 yield [_check] + list(test)276class TestArgGetters(object):277 def testGetBoolean(self):278 tests = [279 # default testing for None value280 (None, None, None, None),281 (None, None, False, False),282 (None, None, True, True),283 # some real values284 (u'0', None, None, False),285 (u'1', None, None, True),286 (u'false', None, None, False),287 (u'true', None, None, True),288 (u'FALSE', None, None, False),289 (u'TRUE', None, None, True),290 (u'no', None, None, False),291 (u'yes', None, None, True),292 (u'NO', None, None, False),293 (u'YES', None, None, True),294 ]295 for arg, name, default, expected in tests:296 assert paramparser.get_bool(arg, name, default) == expected297 def testGetBooleanRaising(self):298 # wrong default type299 pytest.raises(AssertionError, paramparser.get_bool, None, None, 42)300 # anything except None or unicode raises TypeError301 pytest.raises(TypeError, paramparser.get_bool, True)302 pytest.raises(TypeError, paramparser.get_bool, 42)303 pytest.raises(TypeError, paramparser.get_bool, 42.0)304 pytest.raises(TypeError, paramparser.get_bool, '')305 pytest.raises(TypeError, paramparser.get_bool, tuple())306 pytest.raises(TypeError, paramparser.get_bool, [])307 pytest.raises(TypeError, paramparser.get_bool, {})308 # any value not convertable to boolean raises ValueError309 pytest.raises(ValueError, paramparser.get_bool, u'')310 pytest.raises(ValueError, paramparser.get_bool, u'42')311 pytest.raises(ValueError, paramparser.get_bool, u'wrong')312 pytest.raises(ValueError, paramparser.get_bool, u'"True"') # must not be quoted!313 def testGetInt(self):314 tests = [315 # default testing for None value316 (None, None, None, None),317 (None, None, -23, -23),318 (None, None, 42, 42),319 # some real values320 (u'0', None, None, 0),321 (u'42', None, None, 42),322 (u'-23', None, None, -23),323 ]324 for arg, name, default, expected in tests:325 assert paramparser.get_int(arg, name, default) == expected326 def testGetIntRaising(self):327 # wrong default type328 pytest.raises(AssertionError, paramparser.get_int, None, None, 42.23)329 # anything except None or unicode raises TypeError330 pytest.raises(TypeError, paramparser.get_int, True)331 pytest.raises(TypeError, paramparser.get_int, 42)332 pytest.raises(TypeError, paramparser.get_int, 42.0)333 pytest.raises(TypeError, paramparser.get_int, '')334 pytest.raises(TypeError, paramparser.get_int, tuple())335 pytest.raises(TypeError, paramparser.get_int, [])336 pytest.raises(TypeError, paramparser.get_int, {})337 # any value not convertable to int raises ValueError338 pytest.raises(ValueError, paramparser.get_int, u'')339 pytest.raises(ValueError, paramparser.get_int, u'23.42')340 pytest.raises(ValueError, paramparser.get_int, u'wrong')341 pytest.raises(ValueError, paramparser.get_int, u'"4711"') # must not be quoted!342 def testGetFloat(self):343 tests = [344 # default testing for None value345 (None, None, None, None),346 (None, None, -23.42, -23.42),347 (None, None, 42.23, 42.23),348 # some real values349 (u'0', None, None, 0),350 (u'42.23', None, None, 42.23),351 (u'-23.42', None, None, -23.42),352 (u'-23.42E3', None, None, -23.42E3),353 (u'23.42E-3', None, None, 23.42E-3),354 ]355 for arg, name, default, expected in tests:356 assert paramparser.get_float(arg, name, default) == expected357 def testGetFloatRaising(self):358 # wrong default type359 pytest.raises(AssertionError, paramparser.get_float, None, None, u'42')360 # anything except None or unicode raises TypeError361 pytest.raises(TypeError, paramparser.get_float, True)362 pytest.raises(TypeError, paramparser.get_float, 42)363 pytest.raises(TypeError, paramparser.get_float, 42.0)364 pytest.raises(TypeError, paramparser.get_float, '')365 pytest.raises(TypeError, paramparser.get_float, tuple())366 pytest.raises(TypeError, paramparser.get_float, [])367 pytest.raises(TypeError, paramparser.get_float, {})368 # any value not convertable to int raises ValueError369 pytest.raises(ValueError, paramparser.get_float, u'')370 pytest.raises(ValueError, paramparser.get_float, u'wrong')371 pytest.raises(ValueError, paramparser.get_float, u'"47.11"') # must not be quoted!372 def testGetComplex(self):373 tests = [374 # default testing for None value375 (None, None, None, None),376 (None, None, -23.42, -23.42),377 (None, None, 42.23, 42.23),378 # some real values379 (u'0', None, None, 0),380 (u'42.23', None, None, 42.23),381 (u'-23.42', None, None, -23.42),382 (u'-23.42E3', None, None, -23.42E3),383 (u'23.42E-3', None, None, 23.42E-3),384 (u'23.42E-3+3.04j', None, None, 23.42E-3 + 3.04j),385 (u'3.04j', None, None, 3.04j),386 (u'-3.04j', None, None, -3.04j),387 (u'23.42E-3+3.04i', None, None, 23.42E-3 + 3.04j),388 (u'3.04i', None, None, 3.04j),389 (u'-3.04i', None, None, -3.04j),390 (u'-3', None, None, -3L),391 (u'-300000000000000000000', None, None, -300000000000000000000L),392 ]393 for arg, name, default, expected in tests:394 assert paramparser.get_complex(arg, name, default) == expected395 def testGetComplexRaising(self):396 # wrong default type397 pytest.raises(AssertionError, paramparser.get_complex, None, None, u'42')398 # anything except None or unicode raises TypeError399 pytest.raises(TypeError, paramparser.get_complex, True)400 pytest.raises(TypeError, paramparser.get_complex, 42)401 pytest.raises(TypeError, paramparser.get_complex, 42.0)402 pytest.raises(TypeError, paramparser.get_complex, 3j)403 pytest.raises(TypeError, paramparser.get_complex, '')404 pytest.raises(TypeError, paramparser.get_complex, tuple())405 pytest.raises(TypeError, paramparser.get_complex, [])406 pytest.raises(TypeError, paramparser.get_complex, {})407 # any value not convertable to int raises ValueError408 pytest.raises(ValueError, paramparser.get_complex, u'')409 pytest.raises(ValueError, paramparser.get_complex, u'3jj')410 pytest.raises(ValueError, paramparser.get_complex, u'3Ij')411 pytest.raises(ValueError, paramparser.get_complex, u'3i-3i')412 pytest.raises(ValueError, paramparser.get_complex, u'wrong')413 pytest.raises(ValueError, paramparser.get_complex, u'"47.11"') # must not be quoted!414 def testGetUnicode(self):415 tests = [416 # default testing for None value417 (None, None, None, None),418 (None, None, u'', u''),419 (None, None, u'abc', u'abc'),420 # some real values421 (u'', None, None, u''),422 (u'abc', None, None, u'abc'),423 (u'"abc"', None, None, u'"abc"'),424 ]425 for arg, name, default, expected in tests:426 assert paramparser.get_unicode(arg, name, default) == expected427 def testGetUnicodeRaising(self):428 # wrong default type429 pytest.raises(AssertionError, paramparser.get_unicode, None, None, 42)430 # anything except None or unicode raises TypeError431 pytest.raises(TypeError, paramparser.get_unicode, True)432 pytest.raises(TypeError, paramparser.get_unicode, 42)433 pytest.raises(TypeError, paramparser.get_unicode, 42.0)434 pytest.raises(TypeError, paramparser.get_unicode, '')435 pytest.raises(TypeError, paramparser.get_unicode, tuple())436 pytest.raises(TypeError, paramparser.get_unicode, [])437 pytest.raises(TypeError, paramparser.get_unicode, {})438class TestExtensionInvoking(object):439 def _test_invoke_bool(self, b=bool):440 assert b is False441 def _test_invoke_bool_def(self, v=bool, b=False):442 assert b == v443 assert isinstance(b, bool)444 assert isinstance(v, bool)445 def _test_invoke_int_None(self, i=int):446 assert i == 1 or i is None447 def _test_invoke_float_None(self, i=float):448 assert i == 1.4 or i is None449 def _test_invoke_float_required(self, i=paramparser.required_arg(float)):450 assert i == 1.4451 def _test_invoke_choice(self, a, choice=[u'a', u'b', u'c']):452 assert a == 7453 assert choice == u'a'454 def _test_invoke_choicet(self, a, choice=(u'a', u'b', u'c')):455 assert a == 7456 assert choice == u'a'457 def _test_invoke_choice_required(self, i=paramparser.required_arg((u'b', u'a'))):458 assert i == u'a'459 def _test_trailing(self, a, _trailing_args=[]):460 assert _trailing_args == [u'a']461 def _test_arbitrary_kw(self, expect, _kwargs={}):462 assert _kwargs == expect463 def testInvoke(self):464 def _test_invoke_int(i=int):465 assert i == 1466 def _test_invoke_int_fixed(a, b, i=int):467 assert a == 7468 assert b == 8469 assert i == 1 or i is None470 ief = paramparser.invoke_extension_function471 ief(self._test_invoke_bool, u'False')472 ief(self._test_invoke_bool, u'b=False')473 ief(_test_invoke_int, u'1')474 ief(_test_invoke_int, u'i=1')475 ief(self._test_invoke_bool_def, u'False, False')476 ief(self._test_invoke_bool_def, u'b=False, v=False')477 ief(self._test_invoke_bool_def, u'False')478 ief(self._test_invoke_int_None, u'i=1')479 ief(self._test_invoke_int_None, u'i=')480 ief(self._test_invoke_int_None, u'')481 pytest.raises(ValueError, ief,482 self._test_invoke_int_None, u'x')483 pytest.raises(ValueError, ief,484 self._test_invoke_int_None, u'""')485 pytest.raises(ValueError, ief,486 self._test_invoke_int_None, u'i=""')487 pytest.raises(ValueError, ief,488 _test_invoke_int_fixed, u'a=7', [7, 8])489 ief(_test_invoke_int_fixed, u'i=1', [7, 8])490 pytest.raises(ValueError, ief,491 _test_invoke_int_fixed, u'i=""', [7, 8])492 ief(_test_invoke_int_fixed, u'i=', [7, 8])493 for choicefn in (self._test_invoke_choice, self._test_invoke_choicet):494 ief(choicefn, u'', [7])495 ief(choicefn, u'choice=a', [7])496 ief(choicefn, u'choice=', [7])497 ief(choicefn, u'choice="a"', [7])498 pytest.raises(ValueError, ief,499 choicefn, u'x', [7])500 pytest.raises(ValueError, ief,501 choicefn, u'choice=x', [7])502 ief(self._test_invoke_float_None, u'i=1.4')503 ief(self._test_invoke_float_None, u'i=')504 ief(self._test_invoke_float_None, u'')505 ief(self._test_invoke_float_None, u'1.4')506 pytest.raises(ValueError, ief,507 self._test_invoke_float_None, u'x')508 pytest.raises(ValueError, ief,509 self._test_invoke_float_None, u'""')510 pytest.raises(ValueError, ief,511 self._test_invoke_float_None, u'i=""')512 ief(self._test_trailing, u'a=7, a')513 ief(self._test_trailing, u'7, a')514 ief(self._test_arbitrary_kw, u'test=x, \xc3=test',515 [{u'\xc3': 'test', 'test': u'x'}])516 ief(self._test_arbitrary_kw, u'test=x, "\xc3"=test',517 [{u'\xc3': 'test', 'test': u'x'}])518 ief(self._test_arbitrary_kw, u'test=x, "7 \xc3"=test',519 [{u'7 \xc3': 'test', 'test': u'x'}])520 ief(self._test_arbitrary_kw, u'test=x, 7 \xc3=test',521 [{u'7 \xc3': 'test', 'test': u'x'}])522 ief(self._test_arbitrary_kw, u'7 \xc3=test, test= x ',523 [{u'7 \xc3': 'test', 'test': u'x'}])524 pytest.raises(ValueError, ief,525 self._test_invoke_float_required, u'')526 ief(self._test_invoke_float_required, u'1.4')527 ief(self._test_invoke_float_required, u'i=1.4')528 pytest.raises(ValueError, ief,529 self._test_invoke_choice_required, u'')530 ief(self._test_invoke_choice_required, u'a')531 ief(self._test_invoke_choice_required, u'i=a')532 pytest.raises(ValueError, ief,533 self._test_invoke_float_required, u',')534 def testConstructors(self):535 ief = paramparser.invoke_extension_function536 # new style class537 class TEST1(object):538 def __init__(self, a=int):539 self.constructed = True540 assert a == 7541 class TEST2(TEST1):542 pass543 obj = ief(TEST1, u'a=7')544 assert isinstance(obj, TEST1)545 assert obj.constructed546 pytest.raises(ValueError, ief, TEST1, u'b')547 obj = ief(TEST2, u'a=7')548 assert isinstance(obj, TEST1)549 assert isinstance(obj, TEST2)550 assert obj.constructed551 pytest.raises(ValueError, ief, TEST2, u'b')552 # old style class553 class TEST3:554 def __init__(self, a=int):555 self.constructed = True556 assert a == 7557 class TEST4(TEST3):558 pass559 obj = ief(TEST3, u'a=7')560 assert isinstance(obj, TEST3)561 assert obj.constructed562 pytest.raises(ValueError, ief, TEST3, u'b')563 obj = ief(TEST4, u'a=7')564 assert isinstance(obj, TEST3)565 assert isinstance(obj, TEST4)566 assert obj.constructed567 pytest.raises(ValueError, ief, TEST4, u'b')568 def testFailing(self):569 ief = paramparser.invoke_extension_function570 pytest.raises(TypeError, ief, hex, u'15')571 pytest.raises(TypeError, ief, cmp, u'15')572 pytest.raises(AttributeError, ief, unicode, u'15')573 def testAllDefault(self):574 ief = paramparser.invoke_extension_function575 def has_many_defaults(a=1, b=2, c=3, d=4):576 assert a == 1577 assert b == 2578 assert c == 3579 assert d == 4580 return True581 assert ief(has_many_defaults, u'1, 2, 3, 4')582 assert ief(has_many_defaults, u'2, 3, 4', [1])583 assert ief(has_many_defaults, u'3, 4', [1, 2])584 assert ief(has_many_defaults, u'4', [1, 2, 3])585 assert ief(has_many_defaults, u'', [1, 2, 3, 4])586 assert ief(has_many_defaults, u'd=4,c=3,b=2,a=1')...

Full Screen

Full Screen

test_operator.py

Source:test_operator.py Github

copy

Full Screen

1import operator2import unittest3from test import test_support4class Seq1:5 def __init__(self, lst):6 self.lst = lst7 def __len__(self):8 return len(self.lst)9 def __getitem__(self, i):10 return self.lst[i]11 def __add__(self, other):12 return self.lst + other.lst13 def __mul__(self, other):14 return self.lst * other15 def __rmul__(self, other):16 return other * self.lst17class Seq2(object):18 def __init__(self, lst):19 self.lst = lst20 def __len__(self):21 return len(self.lst)22 def __getitem__(self, i):23 return self.lst[i]24 def __add__(self, other):25 return self.lst + other.lst26 def __mul__(self, other):27 return self.lst * other28 def __rmul__(self, other):29 return other * self.lst30class OperatorTestCase(unittest.TestCase):31 def test_lt(self):32 self.assertRaises(TypeError, operator.lt)33 self.assertRaises(TypeError, operator.lt, 1j, 2j)34 self.assertFalse(operator.lt(1, 0))35 self.assertFalse(operator.lt(1, 0.0))36 self.assertFalse(operator.lt(1, 1))37 self.assertFalse(operator.lt(1, 1.0))38 self.assertTrue(operator.lt(1, 2))39 self.assertTrue(operator.lt(1, 2.0))40 def test_le(self):41 self.assertRaises(TypeError, operator.le)42 self.assertRaises(TypeError, operator.le, 1j, 2j)43 self.assertFalse(operator.le(1, 0))44 self.assertFalse(operator.le(1, 0.0))45 self.assertTrue(operator.le(1, 1))46 self.assertTrue(operator.le(1, 1.0))47 self.assertTrue(operator.le(1, 2))48 self.assertTrue(operator.le(1, 2.0))49 def test_eq(self):50 class C(object):51 def __eq__(self, other):52 raise SyntaxError53 __hash__ = None # Silence Py3k warning54 self.assertRaises(TypeError, operator.eq)55 self.assertRaises(SyntaxError, operator.eq, C(), C())56 self.assertFalse(operator.eq(1, 0))57 self.assertFalse(operator.eq(1, 0.0))58 self.assertTrue(operator.eq(1, 1))59 self.assertTrue(operator.eq(1, 1.0))60 self.assertFalse(operator.eq(1, 2))61 self.assertFalse(operator.eq(1, 2.0))62 def test_ne(self):63 class C(object):64 def __ne__(self, other):65 raise SyntaxError66 self.assertRaises(TypeError, operator.ne)67 self.assertRaises(SyntaxError, operator.ne, C(), C())68 self.assertTrue(operator.ne(1, 0))69 self.assertTrue(operator.ne(1, 0.0))70 self.assertFalse(operator.ne(1, 1))71 self.assertFalse(operator.ne(1, 1.0))72 self.assertTrue(operator.ne(1, 2))73 self.assertTrue(operator.ne(1, 2.0))74 def test_ge(self):75 self.assertRaises(TypeError, operator.ge)76 self.assertRaises(TypeError, operator.ge, 1j, 2j)77 self.assertTrue(operator.ge(1, 0))78 self.assertTrue(operator.ge(1, 0.0))79 self.assertTrue(operator.ge(1, 1))80 self.assertTrue(operator.ge(1, 1.0))81 self.assertFalse(operator.ge(1, 2))82 self.assertFalse(operator.ge(1, 2.0))83 def test_gt(self):84 self.assertRaises(TypeError, operator.gt)85 self.assertRaises(TypeError, operator.gt, 1j, 2j)86 self.assertTrue(operator.gt(1, 0))87 self.assertTrue(operator.gt(1, 0.0))88 self.assertFalse(operator.gt(1, 1))89 self.assertFalse(operator.gt(1, 1.0))90 self.assertFalse(operator.gt(1, 2))91 self.assertFalse(operator.gt(1, 2.0))92 def test_abs(self):93 self.assertRaises(TypeError, operator.abs)94 self.assertRaises(TypeError, operator.abs, None)95 self.assertTrue(operator.abs(-1) == 1)96 self.assertTrue(operator.abs(1) == 1)97 def test_add(self):98 self.assertRaises(TypeError, operator.add)99 self.assertRaises(TypeError, operator.add, None, None)100 self.assertTrue(operator.add(3, 4) == 7)101 def test_bitwise_and(self):102 self.assertRaises(TypeError, operator.and_)103 self.assertRaises(TypeError, operator.and_, None, None)104 self.assertTrue(operator.and_(0xf, 0xa) == 0xa)105 def test_concat(self):106 self.assertRaises(TypeError, operator.concat)107 self.assertRaises(TypeError, operator.concat, None, None)108 self.assertTrue(operator.concat('py', 'thon') == 'python')109 self.assertTrue(operator.concat([1, 2], [3, 4]) == [1, 2, 3, 4])110 self.assertTrue(operator.concat(Seq1([5, 6]), Seq1([7])) == [5, 6, 7])111 self.assertTrue(operator.concat(Seq2([5, 6]), Seq2([7])) == [5, 6, 7])112 self.assertRaises(TypeError, operator.concat, 13, 29)113 def test_countOf(self):114 self.assertRaises(TypeError, operator.countOf)115 self.assertRaises(TypeError, operator.countOf, None, None)116 self.assertTrue(operator.countOf([1, 2, 1, 3, 1, 4], 3) == 1)117 self.assertTrue(operator.countOf([1, 2, 1, 3, 1, 4], 5) == 0)118 def test_delitem(self):119 a = [4, 3, 2, 1]120 self.assertRaises(TypeError, operator.delitem, a)121 self.assertRaises(TypeError, operator.delitem, a, None)122 self.assertTrue(operator.delitem(a, 1) is None)123 self.assertTrue(a == [4, 2, 1])124 def test_delslice(self):125 a = range(10)126 self.assertRaises(TypeError, operator.delslice, a)127 self.assertRaises(TypeError, operator.delslice, a, None, None)128 self.assertTrue(operator.delslice(a, 2, 8) is None)129 self.assertTrue(a == [0, 1, 8, 9])130 operator.delslice(a, 0, test_support.MAX_Py_ssize_t)131 self.assertTrue(a == [])132 def test_div(self):133 self.assertRaises(TypeError, operator.div, 5)134 self.assertRaises(TypeError, operator.div, None, None)135 self.assertTrue(operator.floordiv(5, 2) == 2)136 def test_floordiv(self):137 self.assertRaises(TypeError, operator.floordiv, 5)138 self.assertRaises(TypeError, operator.floordiv, None, None)139 self.assertTrue(operator.floordiv(5, 2) == 2)140 def test_truediv(self):141 self.assertRaises(TypeError, operator.truediv, 5)142 self.assertRaises(TypeError, operator.truediv, None, None)143 self.assertTrue(operator.truediv(5, 2) == 2.5)144 def test_getitem(self):145 a = range(10)146 self.assertRaises(TypeError, operator.getitem)147 self.assertRaises(TypeError, operator.getitem, a, None)148 self.assertTrue(operator.getitem(a, 2) == 2)149 def test_getslice(self):150 a = range(10)151 self.assertRaises(TypeError, operator.getslice)152 self.assertRaises(TypeError, operator.getslice, a, None, None)153 self.assertTrue(operator.getslice(a, 4, 6) == [4, 5])154 b = operator.getslice(a, 0, test_support.MAX_Py_ssize_t)155 self.assertTrue(b == a)156 def test_indexOf(self):157 self.assertRaises(TypeError, operator.indexOf)158 self.assertRaises(TypeError, operator.indexOf, None, None)159 self.assertTrue(operator.indexOf([4, 3, 2, 1], 3) == 1)160 self.assertRaises(ValueError, operator.indexOf, [4, 3, 2, 1], 0)161 def test_invert(self):162 self.assertRaises(TypeError, operator.invert)163 self.assertRaises(TypeError, operator.invert, None)164 self.assertTrue(operator.inv(4) == -5)165 def test_isCallable(self):166 self.assertRaises(TypeError, operator.isCallable)167 class C:168 pass169 def check(self, o, v):170 with test_support.check_py3k_warnings():171 self.assertEqual(operator.isCallable(o), v)172 self.assertEqual(callable(o), v)173 check(self, 4, 0)174 check(self, operator.isCallable, 1)175 check(self, C, 1)176 check(self, C(), 0)177 def test_isMappingType(self):178 self.assertRaises(TypeError, operator.isMappingType)179 self.assertFalse(operator.isMappingType(1))180 self.assertFalse(operator.isMappingType(operator.isMappingType))181 self.assertTrue(operator.isMappingType(operator.__dict__))182 self.assertTrue(operator.isMappingType({}))183 def test_isNumberType(self):184 self.assertRaises(TypeError, operator.isNumberType)185 self.assertTrue(operator.isNumberType(8))186 self.assertTrue(operator.isNumberType(8j))187 self.assertTrue(operator.isNumberType(8L))188 self.assertTrue(operator.isNumberType(8.3))189 self.assertFalse(operator.isNumberType(dir()))190 def test_isSequenceType(self):191 self.assertRaises(TypeError, operator.isSequenceType)192 self.assertTrue(operator.isSequenceType(dir()))193 self.assertTrue(operator.isSequenceType(()))194 self.assertTrue(operator.isSequenceType(xrange(10)))195 self.assertTrue(operator.isSequenceType('yeahbuddy'))196 self.assertFalse(operator.isSequenceType(3))197 class Dict(dict): pass198 self.assertFalse(operator.isSequenceType(Dict()))199 def test_lshift(self):200 self.assertRaises(TypeError, operator.lshift)201 self.assertRaises(TypeError, operator.lshift, None, 42)202 self.assertTrue(operator.lshift(5, 1) == 10)203 self.assertTrue(operator.lshift(5, 0) == 5)204 self.assertRaises(ValueError, operator.lshift, 2, -1)205 def test_mod(self):206 self.assertRaises(TypeError, operator.mod)207 self.assertRaises(TypeError, operator.mod, None, 42)208 self.assertTrue(operator.mod(5, 2) == 1)209 def test_mul(self):210 self.assertRaises(TypeError, operator.mul)211 self.assertRaises(TypeError, operator.mul, None, None)212 self.assertTrue(operator.mul(5, 2) == 10)213 def test_neg(self):214 self.assertRaises(TypeError, operator.neg)215 self.assertRaises(TypeError, operator.neg, None)216 self.assertTrue(operator.neg(5) == -5)217 self.assertTrue(operator.neg(-5) == 5)218 self.assertTrue(operator.neg(0) == 0)219 self.assertTrue(operator.neg(-0) == 0)220 def test_bitwise_or(self):221 self.assertRaises(TypeError, operator.or_)222 self.assertRaises(TypeError, operator.or_, None, None)223 self.assertTrue(operator.or_(0xa, 0x5) == 0xf)224 def test_pos(self):225 self.assertRaises(TypeError, operator.pos)226 self.assertRaises(TypeError, operator.pos, None)227 self.assertTrue(operator.pos(5) == 5)228 self.assertTrue(operator.pos(-5) == -5)229 self.assertTrue(operator.pos(0) == 0)230 self.assertTrue(operator.pos(-0) == 0)231 def test_pow(self):232 self.assertRaises(TypeError, operator.pow)233 self.assertRaises(TypeError, operator.pow, None, None)234 self.assertTrue(operator.pow(3,5) == 3**5)235 self.assertTrue(operator.__pow__(3,5) == 3**5)236 self.assertRaises(TypeError, operator.pow, 1)237 self.assertRaises(TypeError, operator.pow, 1, 2, 3)238 def test_repeat(self):239 a = range(3)240 self.assertRaises(TypeError, operator.repeat)241 self.assertRaises(TypeError, operator.repeat, a, None)242 self.assertTrue(operator.repeat(a, 2) == a+a)243 self.assertTrue(operator.repeat(a, 1) == a)244 self.assertTrue(operator.repeat(a, 0) == [])245 a = (1, 2, 3)246 self.assertTrue(operator.repeat(a, 2) == a+a)247 self.assertTrue(operator.repeat(a, 1) == a)248 self.assertTrue(operator.repeat(a, 0) == ())249 a = '123'250 self.assertTrue(operator.repeat(a, 2) == a+a)251 self.assertTrue(operator.repeat(a, 1) == a)252 self.assertTrue(operator.repeat(a, 0) == '')253 a = Seq1([4, 5, 6])254 self.assertTrue(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6])255 self.assertTrue(operator.repeat(a, 1) == [4, 5, 6])256 self.assertTrue(operator.repeat(a, 0) == [])257 a = Seq2([4, 5, 6])258 self.assertTrue(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6])259 self.assertTrue(operator.repeat(a, 1) == [4, 5, 6])260 self.assertTrue(operator.repeat(a, 0) == [])261 self.assertRaises(TypeError, operator.repeat, 6, 7)262 def test_rshift(self):263 self.assertRaises(TypeError, operator.rshift)264 self.assertRaises(TypeError, operator.rshift, None, 42)265 self.assertTrue(operator.rshift(5, 1) == 2)266 self.assertTrue(operator.rshift(5, 0) == 5)267 self.assertRaises(ValueError, operator.rshift, 2, -1)268 def test_contains(self):269 self.assertRaises(TypeError, operator.contains)270 self.assertRaises(TypeError, operator.contains, None, None)271 self.assertTrue(operator.contains(range(4), 2))272 self.assertFalse(operator.contains(range(4), 5))273 with test_support.check_py3k_warnings():274 self.assertTrue(operator.sequenceIncludes(range(4), 2))275 self.assertFalse(operator.sequenceIncludes(range(4), 5))276 def test_setitem(self):277 a = range(3)278 self.assertRaises(TypeError, operator.setitem, a)279 self.assertRaises(TypeError, operator.setitem, a, None, None)280 self.assertTrue(operator.setitem(a, 0, 2) is None)281 self.assertTrue(a == [2, 1, 2])282 self.assertRaises(IndexError, operator.setitem, a, 4, 2)283 def test_setslice(self):284 a = range(4)285 self.assertRaises(TypeError, operator.setslice, a)286 self.assertRaises(TypeError, operator.setslice, a, None, None, None)287 self.assertTrue(operator.setslice(a, 1, 3, [2, 1]) is None)288 self.assertTrue(a == [0, 2, 1, 3])289 operator.setslice(a, 0, test_support.MAX_Py_ssize_t, [])290 self.assertTrue(a == [])291 def test_sub(self):292 self.assertRaises(TypeError, operator.sub)293 self.assertRaises(TypeError, operator.sub, None, None)294 self.assertTrue(operator.sub(5, 2) == 3)295 def test_truth(self):296 class C(object):297 def __nonzero__(self):298 raise SyntaxError299 self.assertRaises(TypeError, operator.truth)300 self.assertRaises(SyntaxError, operator.truth, C())301 self.assertTrue(operator.truth(5))302 self.assertTrue(operator.truth([0]))303 self.assertFalse(operator.truth(0))304 self.assertFalse(operator.truth([]))305 def test_bitwise_xor(self):306 self.assertRaises(TypeError, operator.xor)307 self.assertRaises(TypeError, operator.xor, None, None)308 self.assertTrue(operator.xor(0xb, 0xc) == 0x7)309 def test_is(self):310 a = b = 'xyzpdq'311 c = a[:3] + b[3:]312 self.assertRaises(TypeError, operator.is_)313 self.assertTrue(operator.is_(a, b))314 self.assertFalse(operator.is_(a,c))315 def test_is_not(self):316 a = b = 'xyzpdq'317 c = a[:3] + b[3:]318 self.assertRaises(TypeError, operator.is_not)319 self.assertFalse(operator.is_not(a, b))320 self.assertTrue(operator.is_not(a,c))321 def test_attrgetter(self):322 class A:323 pass324 a = A()325 a.name = 'arthur'326 f = operator.attrgetter('name')327 self.assertEqual(f(a), 'arthur')328 self.assertRaises(TypeError, f)329 self.assertRaises(TypeError, f, a, 'dent')330 self.assertRaises(TypeError, f, a, surname='dent')331 f = operator.attrgetter('rank')332 self.assertRaises(AttributeError, f, a)333 f = operator.attrgetter(2)334 self.assertRaises(TypeError, f, a)335 self.assertRaises(TypeError, operator.attrgetter)336 # multiple gets337 record = A()338 record.x = 'X'339 record.y = 'Y'340 record.z = 'Z'341 self.assertEqual(operator.attrgetter('x','z','y')(record), ('X', 'Z', 'Y'))342 self.assertRaises(TypeError, operator.attrgetter('x', (), 'y'), record)343 class C(object):344 def __getattr__(self, name):345 raise SyntaxError346 self.assertRaises(SyntaxError, operator.attrgetter('foo'), C())347 # recursive gets348 a = A()349 a.name = 'arthur'350 a.child = A()351 a.child.name = 'thomas'352 f = operator.attrgetter('child.name')353 self.assertEqual(f(a), 'thomas')354 self.assertRaises(AttributeError, f, a.child)355 f = operator.attrgetter('name', 'child.name')356 self.assertEqual(f(a), ('arthur', 'thomas'))357 f = operator.attrgetter('name', 'child.name', 'child.child.name')358 self.assertRaises(AttributeError, f, a)359 a.child.child = A()360 a.child.child.name = 'johnson'361 f = operator.attrgetter('child.child.name')362 self.assertEqual(f(a), 'johnson')363 f = operator.attrgetter('name', 'child.name', 'child.child.name')364 self.assertEqual(f(a), ('arthur', 'thomas', 'johnson'))365 def test_itemgetter(self):366 a = 'ABCDE'367 f = operator.itemgetter(2)368 self.assertEqual(f(a), 'C')369 self.assertRaises(TypeError, f)370 self.assertRaises(TypeError, f, a, 3)371 self.assertRaises(TypeError, f, a, size=3)372 f = operator.itemgetter(10)373 self.assertRaises(IndexError, f, a)374 class C(object):375 def __getitem__(self, name):376 raise SyntaxError377 self.assertRaises(SyntaxError, operator.itemgetter(42), C())378 f = operator.itemgetter('name')379 self.assertRaises(TypeError, f, a)380 self.assertRaises(TypeError, operator.itemgetter)381 d = dict(key='val')382 f = operator.itemgetter('key')383 self.assertEqual(f(d), 'val')384 f = operator.itemgetter('nonkey')385 self.assertRaises(KeyError, f, d)386 # example used in the docs387 inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]388 getcount = operator.itemgetter(1)389 self.assertEqual(map(getcount, inventory), [3, 2, 5, 1])390 self.assertEqual(sorted(inventory, key=getcount),391 [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)])392 # multiple gets393 data = map(str, range(20))394 self.assertEqual(operator.itemgetter(2,10,5)(data), ('2', '10', '5'))395 self.assertRaises(TypeError, operator.itemgetter(2, 'x', 5), data)396 def test_methodcaller(self):397 self.assertRaises(TypeError, operator.methodcaller)398 class A:399 def foo(self, *args, **kwds):400 return args[0] + args[1]401 def bar(self, f=42):402 return f403 a = A()404 f = operator.methodcaller('foo')405 self.assertRaises(IndexError, f, a)406 f = operator.methodcaller('foo', 1, 2)407 self.assertEqual(f(a), 3)408 self.assertRaises(TypeError, f)409 self.assertRaises(TypeError, f, a, 3)410 self.assertRaises(TypeError, f, a, spam=3)411 f = operator.methodcaller('bar')412 self.assertEqual(f(a), 42)413 self.assertRaises(TypeError, f, a, a)414 f = operator.methodcaller('bar', f=5)415 self.assertEqual(f(a), 5)416 def test_inplace(self):417 class C(object):418 def __iadd__ (self, other): return "iadd"419 def __iand__ (self, other): return "iand"420 def __idiv__ (self, other): return "idiv"421 def __ifloordiv__(self, other): return "ifloordiv"422 def __ilshift__ (self, other): return "ilshift"423 def __imod__ (self, other): return "imod"424 def __imul__ (self, other): return "imul"425 def __ior__ (self, other): return "ior"426 def __ipow__ (self, other): return "ipow"427 def __irshift__ (self, other): return "irshift"428 def __isub__ (self, other): return "isub"429 def __itruediv__ (self, other): return "itruediv"430 def __ixor__ (self, other): return "ixor"431 def __getitem__(self, other): return 5 # so that C is a sequence432 c = C()433 self.assertEqual(operator.iadd (c, 5), "iadd")434 self.assertEqual(operator.iand (c, 5), "iand")435 self.assertEqual(operator.idiv (c, 5), "idiv")436 self.assertEqual(operator.ifloordiv(c, 5), "ifloordiv")437 self.assertEqual(operator.ilshift (c, 5), "ilshift")438 self.assertEqual(operator.imod (c, 5), "imod")439 self.assertEqual(operator.imul (c, 5), "imul")440 self.assertEqual(operator.ior (c, 5), "ior")441 self.assertEqual(operator.ipow (c, 5), "ipow")442 self.assertEqual(operator.irshift (c, 5), "irshift")443 self.assertEqual(operator.isub (c, 5), "isub")444 self.assertEqual(operator.itruediv (c, 5), "itruediv")445 self.assertEqual(operator.ixor (c, 5), "ixor")446 self.assertEqual(operator.iconcat (c, c), "iadd")447 self.assertEqual(operator.irepeat (c, 5), "imul")448 self.assertEqual(operator.__iadd__ (c, 5), "iadd")449 self.assertEqual(operator.__iand__ (c, 5), "iand")450 self.assertEqual(operator.__idiv__ (c, 5), "idiv")451 self.assertEqual(operator.__ifloordiv__(c, 5), "ifloordiv")452 self.assertEqual(operator.__ilshift__ (c, 5), "ilshift")453 self.assertEqual(operator.__imod__ (c, 5), "imod")454 self.assertEqual(operator.__imul__ (c, 5), "imul")455 self.assertEqual(operator.__ior__ (c, 5), "ior")456 self.assertEqual(operator.__ipow__ (c, 5), "ipow")457 self.assertEqual(operator.__irshift__ (c, 5), "irshift")458 self.assertEqual(operator.__isub__ (c, 5), "isub")459 self.assertEqual(operator.__itruediv__ (c, 5), "itruediv")460 self.assertEqual(operator.__ixor__ (c, 5), "ixor")461 self.assertEqual(operator.__iconcat__ (c, c), "iadd")462 self.assertEqual(operator.__irepeat__ (c, 5), "imul")463def test_main(verbose=None):464 import sys465 test_classes = (466 OperatorTestCase,467 )468 test_support.run_unittest(*test_classes)469 # verify reference counting470 if verbose and hasattr(sys, "gettotalrefcount"):471 import gc472 counts = [None] * 5473 for i in xrange(len(counts)):474 test_support.run_unittest(*test_classes)475 gc.collect()476 counts[i] = sys.gettotalrefcount()477 print counts478if __name__ == "__main__":...

Full Screen

Full Screen

raises.py

Source:raises.py Github

copy

Full Screen

...4from _pytest.outcomes import Failed5from _pytest.pytester import Pytester6class TestRaises:7 def test_check_callable(self) -> None:8 with pytest.raises(TypeError, match=r".* must be callable"):9 pytest.raises(RuntimeError, "int('qwe')") # type: ignore[call-overload]10 def test_raises(self):11 excinfo = pytest.raises(ValueError, int, "qwe")12 assert "invalid literal" in str(excinfo.value)13 def test_raises_function(self):14 excinfo = pytest.raises(ValueError, int, "hello")15 assert "invalid literal" in str(excinfo.value)16 def test_raises_callable_no_exception(self) -> None:17 class A:18 def __call__(self):19 pass20 try:21 pytest.raises(ValueError, A())22 except pytest.fail.Exception:23 pass24 def test_raises_falsey_type_error(self) -> None:25 with pytest.raises(TypeError):26 with pytest.raises(AssertionError, match=0): # type: ignore[call-overload]27 raise AssertionError("ohai")28 def test_raises_repr_inflight(self):29 """Ensure repr() on an exception info inside a pytest.raises with block works (#4386)"""30 class E(Exception):31 pass32 with pytest.raises(E) as excinfo:33 # this test prints the inflight uninitialized object34 # using repr and str as well as pprint to demonstrate35 # it works36 print(str(excinfo))37 print(repr(excinfo))38 import pprint39 pprint.pprint(excinfo)40 raise E()41 def test_raises_as_contextmanager(self, pytester: Pytester) -> None:42 pytester.makepyfile(43 """44 import pytest45 import _pytest._code46 def test_simple():47 with pytest.raises(ZeroDivisionError) as excinfo:48 assert isinstance(excinfo, _pytest._code.ExceptionInfo)49 1/050 print(excinfo)51 assert excinfo.type == ZeroDivisionError52 assert isinstance(excinfo.value, ZeroDivisionError)53 def test_noraise():54 with pytest.raises(pytest.raises.Exception):55 with pytest.raises(ValueError):56 int()57 def test_raise_wrong_exception_passes_by():58 with pytest.raises(ZeroDivisionError):59 with pytest.raises(ValueError):60 1/061 """62 )63 result = pytester.runpytest()64 result.stdout.fnmatch_lines(["*3 passed*"])65 def test_does_not_raise(self, pytester: Pytester) -> None:66 pytester.makepyfile(67 """68 from contextlib import contextmanager69 import pytest70 @contextmanager71 def does_not_raise():72 yield73 @pytest.mark.parametrize('example_input,expectation', [74 (3, does_not_raise()),75 (2, does_not_raise()),76 (1, does_not_raise()),77 (0, pytest.raises(ZeroDivisionError)),78 ])79 def test_division(example_input, expectation):80 '''Test how much I know division.'''81 with expectation:82 assert (6 / example_input) is not None83 """84 )85 result = pytester.runpytest()86 result.stdout.fnmatch_lines(["*4 passed*"])87 def test_does_not_raise_does_raise(self, pytester: Pytester) -> None:88 pytester.makepyfile(89 """90 from contextlib import contextmanager91 import pytest92 @contextmanager93 def does_not_raise():94 yield95 @pytest.mark.parametrize('example_input,expectation', [96 (0, does_not_raise()),97 (1, pytest.raises(ZeroDivisionError)),98 ])99 def test_division(example_input, expectation):100 '''Test how much I know division.'''101 with expectation:102 assert (6 / example_input) is not None103 """104 )105 result = pytester.runpytest()106 result.stdout.fnmatch_lines(["*2 failed*"])107 def test_noclass(self) -> None:108 with pytest.raises(TypeError):109 pytest.raises("wrong", lambda: None) # type: ignore[call-overload]110 def test_invalid_arguments_to_raises(self) -> None:111 with pytest.raises(TypeError, match="unknown"):112 with pytest.raises(TypeError, unknown="bogus"): # type: ignore[call-overload]113 raise ValueError()114 def test_tuple(self):115 with pytest.raises((KeyError, ValueError)):116 raise KeyError("oops")117 def test_no_raise_message(self) -> None:118 try:119 pytest.raises(ValueError, int, "0")120 except pytest.fail.Exception as e:121 assert e.msg == f"DID NOT RAISE {repr(ValueError)}"122 else:123 assert False, "Expected pytest.raises.Exception"124 try:125 with pytest.raises(ValueError):126 pass127 except pytest.fail.Exception as e:128 assert e.msg == f"DID NOT RAISE {repr(ValueError)}"129 else:130 assert False, "Expected pytest.raises.Exception"131 @pytest.mark.parametrize("method", ["function", "function_match", "with"])132 def test_raises_cyclic_reference(self, method):133 """Ensure pytest.raises does not leave a reference cycle (#1965)."""134 import gc135 class T:136 def __call__(self):137 raise ValueError138 t = T()139 refcount = len(gc.get_referrers(t))140 if method == "function":141 pytest.raises(ValueError, t)142 elif method == "function_match":143 pytest.raises(ValueError, t).match("^$")144 else:145 with pytest.raises(ValueError):146 t()147 # ensure both forms of pytest.raises don't leave exceptions in sys.exc_info()148 assert sys.exc_info() == (None, None, None)149 assert refcount == len(gc.get_referrers(t))150 def test_raises_match(self) -> None:151 msg = r"with base \d+"152 with pytest.raises(ValueError, match=msg):153 int("asdf")154 msg = "with base 10"155 with pytest.raises(ValueError, match=msg):156 int("asdf")157 msg = "with base 16"158 expr = "Regex pattern {!r} does not match \"invalid literal for int() with base 10: 'asdf'\".".format(159 msg160 )161 with pytest.raises(AssertionError, match=re.escape(expr)):162 with pytest.raises(ValueError, match=msg):163 int("asdf", base=10)164 # "match" without context manager.165 pytest.raises(ValueError, int, "asdf").match("invalid literal")166 with pytest.raises(AssertionError) as excinfo:167 pytest.raises(ValueError, int, "asdf").match(msg)168 assert str(excinfo.value) == expr169 pytest.raises(TypeError, int, match="invalid")170 def tfunc(match):171 raise ValueError(f"match={match}")172 pytest.raises(ValueError, tfunc, match="asdf").match("match=asdf")173 pytest.raises(ValueError, tfunc, match="").match("match=")174 def test_match_failure_string_quoting(self):175 with pytest.raises(AssertionError) as excinfo:176 with pytest.raises(AssertionError, match="'foo"):177 raise AssertionError("'bar")178 (msg,) = excinfo.value.args179 assert msg == 'Regex pattern "\'foo" does not match "\'bar".'180 def test_match_failure_exact_string_message(self):181 message = "Oh here is a message with (42) numbers in parameters"182 with pytest.raises(AssertionError) as excinfo:183 with pytest.raises(AssertionError, match=message):184 raise AssertionError(message)185 (msg,) = excinfo.value.args186 assert msg == (187 "Regex pattern 'Oh here is a message with (42) numbers in "188 "parameters' does not match 'Oh here is a message with (42) "189 "numbers in parameters'. Did you mean to `re.escape()` the regex?"190 )191 def test_raises_match_wrong_type(self):192 """Raising an exception with the wrong type and match= given.193 pytest should throw the unexpected exception - the pattern match is not194 really relevant if we got a different exception.195 """196 with pytest.raises(ValueError):197 with pytest.raises(IndexError, match="nomatch"):198 int("asdf")199 def test_raises_exception_looks_iterable(self):200 class Meta(type):201 def __getitem__(self, item):202 return 1 / 0203 def __len__(self):204 return 1205 class ClassLooksIterableException(Exception, metaclass=Meta):206 pass207 with pytest.raises(208 Failed,209 match=r"DID NOT RAISE <class 'raises(\..*)*ClassLooksIterableException'>",210 ):211 pytest.raises(ClassLooksIterableException, lambda: None)212 def test_raises_with_raising_dunder_class(self) -> None:213 """Test current behavior with regard to exceptions via __class__ (#4284)."""214 class CrappyClass(Exception):215 # Type ignored because it's bypassed intentionally.216 @property # type: ignore217 def __class__(self):218 assert False, "via __class__"219 with pytest.raises(AssertionError) as excinfo:220 with pytest.raises(CrappyClass()): # type: ignore[call-overload]221 pass222 assert "via __class__" in excinfo.value.args[0]223 def test_raises_context_manager_with_kwargs(self):224 with pytest.raises(TypeError) as excinfo:225 with pytest.raises(Exception, foo="bar"): # type: ignore[call-overload]226 pass227 assert "Unexpected keyword arguments" in str(excinfo.value)228 def test_expected_exception_is_not_a_baseexception(self) -> None:229 with pytest.raises(TypeError) as excinfo:230 with pytest.raises("hello"): # type: ignore[call-overload]231 pass # pragma: no cover232 assert "must be a BaseException type, not str" in str(excinfo.value)233 class NotAnException:234 pass235 with pytest.raises(TypeError) as excinfo:236 with pytest.raises(NotAnException): # type: ignore[type-var]237 pass # pragma: no cover238 assert "must be a BaseException type, not NotAnException" in str(excinfo.value)239 with pytest.raises(TypeError) as excinfo:240 with pytest.raises(("hello", NotAnException)): # type: ignore[arg-type]241 pass # pragma: no cover...

Full Screen

Full Screen

test_filters.py

Source:test_filters.py Github

copy

Full Screen

...13 assert_false(f(3))14 assert_true(f(4))15 assert_true(f(0))16 assert_true(f('a'))17 assert_raises(TypeError, f, 1, 2)18 assert_raises(TypeError, f)19 def test_show_nodes(self):20 f = nx.classes.filters.show_nodes([1, 2, 3])21 assert_true(f(1))22 assert_true(f(2))23 assert_true(f(3))24 assert_false(f(4))25 assert_false(f(0))26 assert_false(f('a'))27 assert_raises(TypeError, f, 1, 2)28 assert_raises(TypeError, f)29 def test_hide_edges(self):30 factory = nx.classes.filters.hide_edges31 f = factory([(1, 2), (3, 4)])32 assert_false(f(1, 2))33 assert_false(f(3, 4))34 assert_false(f(4, 3))35 assert_true(f(2, 3))36 assert_true(f(0, -1))37 assert_true(f('a', 'b'))38 assert_raises(TypeError, f, 1, 2, 3)39 assert_raises(TypeError, f, 1)40 assert_raises(TypeError, f)41 assert_raises(TypeError, factory, [1, 2, 3])42 assert_raises(ValueError, factory, [(1, 2, 3)])43 def test_show_edges(self):44 factory = nx.classes.filters.show_edges45 f = factory([(1, 2), (3, 4)])46 assert_true(f(1, 2))47 assert_true(f(3, 4))48 assert_true(f(4, 3))49 assert_false(f(2, 3))50 assert_false(f(0, -1))51 assert_false(f('a', 'b'))52 assert_raises(TypeError, f, 1, 2, 3)53 assert_raises(TypeError, f, 1)54 assert_raises(TypeError, f)55 assert_raises(TypeError, factory, [1, 2, 3])56 assert_raises(ValueError, factory, [(1, 2, 3)])57 def test_hide_diedges(self):58 factory = nx.classes.filters.hide_diedges59 f = factory([(1, 2), (3, 4)])60 assert_false(f(1, 2))61 assert_false(f(3, 4))62 assert_true(f(4, 3))63 assert_true(f(2, 3))64 assert_true(f(0, -1))65 assert_true(f('a', 'b'))66 assert_raises(TypeError, f, 1, 2, 3)67 assert_raises(TypeError, f, 1)68 assert_raises(TypeError, f)69 assert_raises(TypeError, factory, [1, 2, 3])70 assert_raises(ValueError, factory, [(1, 2, 3)])71 def test_show_diedges(self):72 factory = nx.classes.filters.show_diedges73 f = factory([(1, 2), (3, 4)])74 assert_true(f(1, 2))75 assert_true(f(3, 4))76 assert_false(f(4, 3))77 assert_false(f(2, 3))78 assert_false(f(0, -1))79 assert_false(f('a', 'b'))80 assert_raises(TypeError, f, 1, 2, 3)81 assert_raises(TypeError, f, 1)82 assert_raises(TypeError, f)83 assert_raises(TypeError, factory, [1, 2, 3])84 assert_raises(ValueError, factory, [(1, 2, 3)])85 def test_hide_multiedges(self):86 factory = nx.classes.filters.hide_multiedges87 f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])88 assert_false(f(1, 2, 0))89 assert_false(f(1, 2, 1))90 assert_true(f(1, 2, 2))91 assert_true(f(3, 4, 0))92 assert_false(f(3, 4, 1))93 assert_false(f(4, 3, 1))94 assert_true(f(4, 3, 0))95 assert_true(f(2, 3, 0))96 assert_true(f(0, -1, 0))97 assert_true(f('a', 'b', 0))98 assert_raises(TypeError, f, 1, 2, 3, 4)99 assert_raises(TypeError, f, 1, 2)100 assert_raises(TypeError, f, 1)101 assert_raises(TypeError, f)102 assert_raises(TypeError, factory, [1, 2, 3])103 assert_raises(ValueError, factory, [(1, 2)])104 assert_raises(ValueError, factory, [(1, 2, 3, 4)])105 def test_show_multiedges(self):106 factory = nx.classes.filters.show_multiedges107 f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])108 assert_true(f(1, 2, 0))109 assert_true(f(1, 2, 1))110 assert_false(f(1, 2, 2))111 assert_false(f(3, 4, 0))112 assert_true(f(3, 4, 1))113 assert_true(f(4, 3, 1))114 assert_false(f(4, 3, 0))115 assert_false(f(2, 3, 0))116 assert_false(f(0, -1, 0))117 assert_false(f('a', 'b', 0))118 assert_raises(TypeError, f, 1, 2, 3, 4)119 assert_raises(TypeError, f, 1, 2)120 assert_raises(TypeError, f, 1)121 assert_raises(TypeError, f)122 assert_raises(TypeError, factory, [1, 2, 3])123 assert_raises(ValueError, factory, [(1, 2)])124 assert_raises(ValueError, factory, [(1, 2, 3, 4)])125 def test_hide_multidiedges(self):126 factory = nx.classes.filters.hide_multidiedges127 f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])128 assert_false(f(1, 2, 0))129 assert_false(f(1, 2, 1))130 assert_true(f(1, 2, 2))131 assert_true(f(3, 4, 0))132 assert_false(f(3, 4, 1))133 assert_true(f(4, 3, 1))134 assert_true(f(4, 3, 0))135 assert_true(f(2, 3, 0))136 assert_true(f(0, -1, 0))137 assert_true(f('a', 'b', 0))138 assert_raises(TypeError, f, 1, 2, 3, 4)139 assert_raises(TypeError, f, 1, 2)140 assert_raises(TypeError, f, 1)141 assert_raises(TypeError, f)142 assert_raises(TypeError, factory, [1, 2, 3])143 assert_raises(ValueError, factory, [(1, 2)])144 assert_raises(ValueError, factory, [(1, 2, 3, 4)])145 def test_show_multidiedges(self):146 factory = nx.classes.filters.show_multidiedges147 f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])148 assert_true(f(1, 2, 0))149 assert_true(f(1, 2, 1))150 assert_false(f(1, 2, 2))151 assert_false(f(3, 4, 0))152 assert_true(f(3, 4, 1))153 assert_false(f(4, 3, 1))154 assert_false(f(4, 3, 0))155 assert_false(f(2, 3, 0))156 assert_false(f(0, -1, 0))157 assert_false(f('a', 'b', 0))158 assert_raises(TypeError, f, 1, 2, 3, 4)159 assert_raises(TypeError, f, 1, 2)160 assert_raises(TypeError, f, 1)161 assert_raises(TypeError, f)162 assert_raises(TypeError, factory, [1, 2, 3])163 assert_raises(ValueError, factory, [(1, 2)])...

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