"""Unit tests for the bytes and array types. XXX This is a mess. CommonFshould be unified with string_j.py (and nvlatter 7 modernized). """ import  $os $re %syDcopyfunctoolUpickl6ftempfi@unitx @.supT BlistQ fromB bigaddrspaceN, MAX_Py_ssize_t if sys.flags. _warning: def check_ s()$(@S.wrap CGper(*args, **kwA&.{s(('', B<W)BFpreturn l!R elseq# no-op)~ Mn class IndexablWK__init__(self, value=0." =<3dex=4|;ABase(eTest: K]q_basicsMAb = J2)!()8TassertEqual(%K(b),32Ab.__.__6i(x_Z avb"abcd"t^<_method in (. , P.deep ;&(aV Oa, b# #1a),K(b))empty_sequencevG1len0=qRaises(Error, lambda: b[0]414 g0maxz>++~!o10**10!-o!/-2 -#+?##f]) def test_from_list(self): qints = range(256)) @b = 3`.type2L(i for i in >,(assertEqual(len(b), SR&'N)@def m\index [I)able(), 1Q254),f :_255)] P[0, 1454Raises(ValueError,\', /-1{G}1]) WlbufferXaaarray.p('B', [G, 3]* a, b"\x01\x02\x03"p# http://bugs.python.org/issue29159,Fallback when __A__ rQ exception other than OverflowiLclass B(bytesh\ !sB TypX 7B(b"foobar")) C}\ssizeQ`b0W/'' 1ob'\x0055f5 E'-1'0', 'ascii'?b'05  <psys.max4 + constructor_ _eswVs60.0CEpassE\O["0" O[0.0<&ONone=&/C( 0A2#'b'C#20, ='ignore>  K) se!lf.assertRaises(TypeError, self.type2test, '') 90, eTs='ignoreJ)b'asciiC)B6, b@def _constructor_value_(!):-  AV.BO[-1]D < sys.maxsizeF35/-2(10**100B'?256=)7='2E+(G@bigaddrspaceoverflowize = MAX_Py_sw!_tG#(OIaMemory )MO 6tryT_ # Should either pass or r2 anP (e.g. on debug builds withNadditional malloc() head), but sqn't crash.Bbytearray(F - 4except   _\mpareKb1 =([1, 2, 3/b2'3'K,Equal(b1, b2!True(b2 != b3"O1 <=D "D  f >f /3 " False(b1#?2 =#21 >juX ##istart in K3"/op!%# Skip step 0 (invalidg$MeMes[1:]:  self.assertEqual(b[start:stop:step], %type2test(L#@)) Y@def #_encoding(;!):!sample = "Hello world\n\u1234\u5678\u9abc"3for enc in ("utf-8", 716"[_ 1A 2B 30 F# check t ASCII whitespace is ignored1 1A\n2B\t30\vw for c in "\x09\x0A\x0B\x0C\x0D\x20": self.assertEqual(type2test.fromhex(c), 5())Jbfor c w 1C\x1D\x1E\x1F\x85\xa0\u2002 /28Raises(ValueError{U, c) '0000'), b'\0\0'B?Typ Ob'1BD /'aC//rtD/1a b cdI/ \xdZP12 Kg 34'rdata, posz(l# invalid first hexadecimal character2('12 x4 56', 3),OosecondP"3xP4P5twosyN non-ASCII stringAR3\xffD)BwithM z) as cm6v@<e)^`In('atition %s' %,(cm.excep)@def _t6hex9?, 1<E`(b"")._), ""8bytearray([0x1a, 0x2b530]Bo'1a2b3\x1a\x2b\x30Jmemoryview(b"F rAjoinO1").9 []. of<=b""?20lst,[[b"abc"], V", b"b ]Q= list(map.W, lst&  <3D.type2test(b"").join(tuple(lst)), b"abc") self.assertEqual(type2test(bKOiterJ@dot_p= = @#.:x#t? (["Ccd"]G.:cd>memoryview(IAJ"?), Qbytearray4P # Stress it with many itemsAq = tc"] * 1000expected =9p + b".:De * 999+dseq), K{2Raises(TypeError,C Bf, NoneF!# 2 handling and cleanup when some in the middle of# sequence hasp wrong .'I%):+c 1"cdFef"]a& jab"), b@def a_countbP'missFppi'qi = 105Up%12w%9 5g"b.b'i'), 4\+ ss,2,w+/0)iOw), Qo, 6), /p'.i', 1, 3), 1 _B7, 91ip+i;p, `starts*Whello_QFalseE.').ab"anything")ljTrue(b3r0.,False(b.startswith(b"hellow"))  self.assertFalse(b.start2a.G 3 Raises(TypeError) as cm:_f Rf[b'h']exc = str(cm.exception mIn('bytes', exc$Ttuple$def test_endW)b Ptype2+1(b'-'g+ytearray().Zb"anything"g0Truf1i.?llo,*w 0n\$O[b'og_find(@miss7ppiqi = 105kw519 [eEqual(b.sb'ss'), 2e +w*/-1+$an7Oi), _@w), P, 3), 5sO1, 71bPi, 6)aBi, 1- for index in (-1, 256, sys.maxsize + 1<+]eRegex($BValut1, r must benrange\(0sM\)',@,)d'r$j,t41,,90 )*] /02 W3 3), 1)  self.assertEqual(b.rfind(i, 3, 9), 7) *.w, 1, 3), -1) 0def test_index(;!):J2b =|Ptype2(p(b'missFppi'uui = 105;w"19fL[ tb'ss'), 2M,Raises(ValueError, b.9W, b'w53an'  _i), 1w[5b(/13#3ss'Oi, 6]iV*"<rZWui?), :66(08  ^ 0052 47 /  g?modhello, %b!vorig = b40b %Uorld' +Uw,X .i1 .False(b is 3(%s / 100 = %d%%a0 % seventy-nine', 79UQas1`(79_90Is(K(a),nh# issue 29714SRJ\x00$-G biglo, %b!')  orig = b  b %= b'world'self.assertEqual(b, b'hello, ,?!').f1/%b.False(b is 3RAb = type2test(b'%s / 100 = %d%%(b'seventy-nine', 79RN 1](79\90Is(K(b),h# issue 29714"OJ\x00!D  @def f`_rmod(!):'Bwith@Raises(TypeError+/object() %537abchf!Isv.-!._ __('%r'), NotImplemented) aeplaceM@miss?ppi#.rU@b'i'a`b'mass?ppa@!ssAxARixixi`_int_ed ;  (b'a b')@, 32'<split_stringv7VO, ' $I .,;S*s"Hunicodewhitespfor b in Q\x1CbAVa\x1D E 7Fb'"v(), [b]-K"\x09\x0A\x0B\x0C\x0D\x1E\x1F"Dm '\x1c\x1d\x1e\x1f']r_;Dpartition'W@b'ssOB(b'meissippi')) self.assertEqual(b.partition(b'w'), (b'missppi', b'@)) Edef test_r<Y!):#2b =lPtype2- V)+: XHb'ss!ssi)JiIRssippG'I'9!1 '&_string_error(3Raises(TypeE+,LVa b')_, ' ' LuM?intB/327L |icklingwfor proto in range(p+e.HIGHEST_PROTOCOL + 1=b9b"", b"a!bc\xffab\x800\0\377\0\0"+H3"Sps = dumps(b,,q+loads(ps%w<, qiterator_zFit = itorgeg.Qdata = list/ X/it6"e.d(3),  Pit), if not bGcontinue_~next(itd0N C[1:]zp_bytearray Jzaabc').G(memoryview(b'ac'))bVPlQ cR rRiew(b'ac')), b'ab') def test_stripng_error(self):'+.assertRaises(TypeE+!, Ptype2N(cAc').V, 'ac')I*lJ6rJ ?int1V abc /32%IJ/J ]cente# Fill character can be either bytes o array (issue 12380?b =*ffor fill_MQ in (^,e\1zEqual(b.&7,J(b'-')),h; Ly`--abc-: /\ljust"'&0$&r&&0!--N,'){x&_v4 abxP, 7, ,&J2JJz?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377' self.assertEqual(self.type2test.maketrans(b'abc', b'xyz'), transtable) N = b'\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'(M&?abcMOxyz'D"\M 4selRaises(ValueError,tU@abc'oxyzq')Q?TypPq'def') N def test_none_arguments(!):## issue 11828;b =(b'hellol%l!h!h!x!x!o!6.as2, b.find(l, None)^K3-/-212, b.find(l, None, -2)) self.assertEqual(0, b.find(h, 1?)) 434r5l5b ./-222`goindex(.2V2`6r/33_count1'. 2dx  @Trueendswith(o5 4 8k JFalsRstart 6l:p@t ;def test_integer_arguments_out_of_byte_range(%): 2b =Ptype2F(b'hello'Ffor method in (b.V'I  k?~Raises(ValueError,cF, -16?2567!C9999I`_etc_r_correct_e_messagesK# issue 11828ax&x' 8Regex(Typ<@r'\b0\b'~ ,d O5tu v( self.assertRaisesRegex(TypeError, r'\bindex\b', b. ?,  xx, None)5self.assv rkw xRScountw vRstartswith{R8end~|$def test_free_after_iterating(!):)L).support.check7 , G , C`.type2>`LreversedPtranslate;b =(b'hello'rosetta = bytearray(range(256)([ord('o')] = Ae') .B%b.X2T(Valu$q,s75))c(., 0Equal(b& IsInstance(c:)d Fc, dE lm NL K~(b'$\# delete as a keyword argument, v>?=b'(llS3}"  class BytesTest(Basea, unit|CCase[=Zgetitem_es ^pmsg = "6 indices must be integers or sl"K(rror, msg):  b'python'['a'] def test_buffer_is_readonly(self):'+fd = os.open(__file__,O_RDONLY),Qwith )fd, "rb", bing=0) as f[_n .assertRaises(TypeError, f.into, b"")lcustomzclass Ag__bytes__2return b'abc'aEqual(Fc(A()),,}_ passCO , P1GENone=T6b'aA_index/42|'z# Issue #25766BJG(str~'\u20ac' 5, 'iso8859-15'^O\xa4L4731'`OtherB1Sub3(` wIs(type6>), pi (xq79), P# Test Py_FromFormat(x-bfrom_fqQc1s =V.support.im_module('%_WOcapi9 (< R h api, py_object$0(c_int, c_u Along Qsize_;s !cchar_poll& =.Q@.res~B0q# basicW2(b'5'),N %$\Hello %s !'_worldj 3*7 !'N# formatters  )self.assertEqual(PyBytes_FromFormat(b'c=%c', c_int(0)), ?-E\0')"b ord('@')i@h+?255cO\xfffd=%d ld=%ld zd=%zd'3Ej 1)tolong(2t Asize_t(3 0d=123e--&----u=%u lu=%lu zu=%zuuC1123u?456%?789 Pu=1230456?789Ei=%i 0b'ise+-f%gEx=%x_0xabcA x=abc') izeof_ptr = ctypes.mof(c_char_p.if os.name == 'nt':J# Windows (MSCRT9Qptr_f = '0x%0{}X'.R(2 * z :Fdef >ter(ptr)|bpreturn j%9NJelse8# UNIX (glibc)Owa'%#x' qaZ5def.Iaptr=%p ('40' +0).encode('ascii')Hs=%sb'cstr' Bb's=&# test minimum and max integer values/0max_&_t(-1).value  for formatstr, ctypes_, value, py_"ter in ( <(b'%d', c_int, _testcapi.INT_MIN, str),4/AX4liHlongjOLONGk 7 nuuoUp9zissize_PY_SSIZE_ @?maxVpchar_p, .6ptr)):self.assertEqual(PyBytes_FromF[(@ b(a)[R 3.encode('ascii'C# width and precision (is currently ignored);b'%5s', b'a'  Z#.3[_bcdef` Ubc') cc# '%%'5ter%o /%')O[%%]U ["!%cint(ord('_') 9Ob'%_?%%s !sInvalidscartialOting ')m~x=%i y=%+#2)/(3. 1x=2: ^Issue #19969: %c must raise OverflowErrP<sP# not=the range [0; 255]$RV)s(W C s4'?-1)i>C256)7@def !_bblocking(Dclass IterationB'wed(list&_J_ = None:i = [0, 1, 2, 3SEqual(bytes(i), b'\x00\x01\x02\x03') *self.assertRaises(TypeError, bytes, IterationBlocked(i)) B# At least in CPython, becauseD.__new__ and the C APIC0PyBl_FromObject have different fallback rulwintegerD"is handled specially, so test separately.=class IntEnt):,!____ = NoneBaEqual((@(3),z_0\0\0p3jPWhileAre is no-defined!B for2ingQ# sub&esaly from other bux-ecrface 0,Fan implement may wellwA-casTm (asG 2.xGstr did)Gthem *Su,Qb'ab'#P+E! B\_arrayba, bb =:( Z/ba#cbb) @yteATest(Base`, unity.CCasePtype2W1def_getitem_e(=pmsg = " indices must be gers or sl"Pwith Q XRegex7msgrvoA(b'p{')['a']sjY"lnohash JE1M(TM_api[phort_sak"Hello world\n"s1+ b"\0"*(20 - len() tfn = tempfile.mk ( *ry@# PrK ?Xopen(tfn, "wb") as f=+zf.write  # 4 readinto iri  b = bytearray(20) n = f.readinto(b"self.assertEqual(n, len(short_sample)3 list(b), 4# Test writing in binary mode with open(tfn, "wb") as f:' f.Pe BrB )C(), u!xt is ambiguous; don't test1zfinally+tros.remove lexcept OSErrorL;Qpass s1def_reverse()2 )b'hello'n/ $b.J), None, , b'ollehRrQ1') # even number of items~w1x S AFalsLpO_clearM hpython.8~"') /b'OIappend(ord('r'b(b.-p-pD?opyC 8abc= .c9D b;H WTthat it's indeed a  and not a referencs"b'Ub7, by`IsNot( bd =db%|regexps Gby(sgreturn0map8, s 0("H, world"re.findall(br"\w+", 3[byE@"), K]x@_set [1, 2, 3]b[1] = 100; D1100FG-H2Hearray([1, 100, 200])) b[0] = Indexable(10self.assertEqual(b, bytearray([10, 1TEtry:ah0b[3e0]fail("Didn't raisefError"gexcept aEpass]!-1g5256_Value&-1\bONone ?Typ  \def test_delitem(r).7b =Arang@del "N(B)dF?-1]G9F4E[1, 2, 3, 4, 6, 7, 8setsliceJ list(b),  0r=Pb[0:5 D5, 1]z ` {4 55, 9t|O0:-59MIj A-7:-+ab?101\[; 2b[3[%%!3:R[42, Q8@QU'foo'i=  P2, 11)1171b[:memoryview(bd0\ k03:4[,1\for elem in [5, -5, 0, int(10e20), 'str', 2.3, ['a', 'b'], [b bY[]]]:6with self.assertRaises(TypeError)/pb[3:4] = elem N1for in [[254, 2556-256, 9000OValu def test_setslice_extend(!# Exercise the resizing logic (see issue #19087) b = bytearray(range(100)"jHEqual(list(b), 34del b[:10]iG!, ~K#b.iO, 11 7)Yfifo_overrunVPTest >23985, a buffer 9 when implementzea FIFO# Build PythonOpydebug modecblresults.9 (10Ppop()# Defeat expandff-by-one quirk\]@ # Advance start pointer Oout reallocaD2b +BAs(2)Dppend exactly@numb-f deletedssD# Free memoryj , |w9`verifi+onBdel_PReducH)size should no<=(} 8S= sys.getFof(b:?[:1BLessf @ , K  ed _% &indices = (0, None, 1, 3, 19, 300, 1<<333, -1, -2, -3 '30piS I" opt !0Ski#valid step 0 "Ke( K;[1:)8L =7255! ML!# Make sure we have a Y9 ofright lengthQ# butB0 di3ent datatQ = L[i`:stop:"-*..reverse(J! = rQbx. !b,L#L)Y del L[start:stop:step] _del b+self.assertEqual(b, bytearray(L)) bdef test_setslice_trap(>!):"a# This) verifies that we correctly handle assigning GEQto a f1 of (the old Lambert Meertens %).>7b =range(256))"@[8:]&Rlist(Ig8)) + Z $|iconcat gb"abc"1b += b"def" G&J1 !Isx?xyzx)[6tryO"Kexcept TypeError.EpassJelse`fail("s#unicode didn't raise_"_irepe.E*= 3 B:abc*| ho_1chara x_ a*= 100^|v"x"*100&_alloc p-1.__ 6__(rGreater*), Qq = [3for i in  q6b"x+F"(5, len(b)) # includPtrail AnullN1if >@ not:seq%seq.appendk 2nitC|t'g(g 3,E $(yyield i2a =@b6,,>Wa)+1): >k5o BLesss5i0?= bhinit__(g())  self.assertEqual(list(b), range(1, 100))) 7!en6&99%alloc = b.__ 6__(CGreater(%1, lL!) ndef test_extend(7!):@origcu'hello'aytearray(&z#a.LaW 0a, 6! +) B[5:]-& 6b''## Test iterators that don't have a __length_hint__rmap(intvW * 25int(x) for x in-RF* 50'/[- 5] FtlRaises(ValueError, H, [0, 1, 2, 256]@/-1?wen(a), ([Indexable(ord('a'))g @a, b% lremovebb#b.8{'l'_byGhelo@ ?dlambda: eB44TypA ~('e"# : first and last\ o; huer"bz tT'hM#j vps outside of the ascii 0: (}&27]p[126, 12789c1Bc, bytes(NIvJxJ 6, 128])) def test_pop(self): b = bytearray(b'world') /.assertEqual(b.F), ord('d'),0-w-$-2.r. Raises(IndexError, lambda: /109 )#; for issue #6846 Ksb'\xff'R, 0xff) :lnosortuAttributen!).J)blappendb Ghell#b.7o@, b'@oA&R 10FNoned 5A len(b), 1?G=TypBd)b'Uable({&,A' inZ wmsssspp`#b.:1i4 /-2 O1000!W@miss7ppi, 0%1 `?0, 2]copie'1# I4348. Make sure that operationsdon't mutat"!e Un# copy ther%s. l_b'abcDIsNot(b, b.replace(.9`cde', Yt?"[i in range(256)]Vx//b' x, x.translate(tyPparti_` _doesnt_share_nullstringza, b, cU"x").UV(b"y"h"! Oc, b!fcab += b"!"\ s Ra# Same for rpartitSion b, c, a = bytearray(b"x").rpartition(b"y")3self.assertEqual(b, b"! c!PIsNotBcab += b"!"s RV def test_resize_forbidden( !):%e# #4509: can't /& ap when there are buffer exports, eve# if it wouldPallocateC underlyingH.0Furgmore, no destructive changes toHmay be appliedKbefore raislthe errorobTr^F(10)v = memoryview(b\('(nJNb[1:-1] = Rn + 1, 2*n - 1C?&10@orig5[:]Raises(B~E,7, 1Z3[i"U 92T+T0# O` operaRs imp=@(b.pop, ~&b.remove, b[1]+>delitem(>1delOG~p# deleta non-contiguous slice|  :2/b" 51delO@@.supl.cpython_only"_obsolete_write_lock`from _.@capiJrort getK_with_null__ @,@A()) O itor_pickling2 V'abc'80datlist(b'qwertyfor proto inle.HIGHEST_PROTOCOL # initial #it(  Cd = mrdumps((2!, ,, 4it, b = pickle.loads(d) b[:] = data self.assertEqual(type(it), Zorig)M 5Blist5a)) c# running iterator0nex<g d = pickle.dumps((it& , ), protoVit, b8 nM[1:]_empty for i in range(1, len()):;CxhaustedGRaises(StopIPion, :", P BvnL[;dtest_e_G0 = .2_ s.CommonTest.51def<L_length_hint(?o# Issue 27443: _,__ can return negative integeba = bytearray(b'ab'xAit =6(baUba.clear($# Shouldn't rw an errd /X!, a class AssortedBytesAP(unitE.CCase# #  various combinations ofQs and 7p@check_Ps_wars!repr_str#f#Pstr, &  f(gf()), "Vb'')"NT? =[0]B_\\x00G, 1, 2545T q`1\\xfefQ"abc"_'abc' "'0'''b"'"''') # '''1@"'\":r"""b'\'"'"""=]formabB2c',^rray(b'abc')7: self.assertEqual(format(b), str(b))0O, ''4Wwith iRaisesRegex(TypeError,g r'\b%s\b' % re.escape(type(b).__name__))Gq, 's') r def test_compare_bytes_to `array(O 4b"abc" == =(v), True@8?" !7#<7$ Hc" >n"7n6ycOFalsK8>c78Gc" Oc", ooNsepdsep.join([val]`& \$) ~aFixedSUk(&.e-@Base): def fixtype(self, obj): if isinstance(obj, str!(preturn @.type2test-.encode("utf-8"))X3uper().fix94!) % contains_bytes = True class ByteArrayAsStringTqVFixed`, unit.CCasek0 = _aK\sX3$s U1Sub:@def a_basic}SL`assertC(issC*g,w@basecC4IsI*,()@@a, b!"abcd", b"efgh" P_a, _" SaTfb7# comparison operators with  wssj_a == _aX"_!= _b"  ?b >`IsNot(Na'ncat ofEqual(a + b, _ )(Qorepeat2a*5#*5Ajoin# Make sure  -ps a NEW ect for single item sequence.# involving a@.hthat it islthe appropriate 8Bs1 =vHb&g2%0().W([s1](Belf. os1, s2!(r4(s2c\,ajo reverse, call 5 on s313Rpickl]ajCa.x = 10?a.y71proto in range(.HIGHEST_PROTOCOL + 14.Tloads;dumps(a, Zf5u2NotZ0id( Oid(b.+i Q#.x, b.x'y'y' t(a), type(b))   self.assertEqual(type(a.y), pb.y)) 2def test_copy(:!):@a = .62'(b"abcd")$w.x = 10y7Gefgh7@for s_method in (.,P.deep1b = ;&(a#Noid(a), id(b).,Oa, b# .x, b.x'y'y' \ & |fromhex9D.*'1a2B30')Gb, b'\x1a\x2b\x-"Iso;b),<rclass B1P.base __new__(cls, value%N$meqJ.83me.foo = 'bar'return me)2A/B15L/B1 ,P2Pinit__(me, *args, **kw Z"ifX is not bytes(80?.__p s  x2xM2x yteArraySub(aMWpass .s*s&`OtherB`+& TTest(7 `, unit.4Cas@! =p= = a Toverride| / s#M & ne/=1oi=4,  !}source=(  M?4, T"ETest(SubclassTest, unittest. Case): basetype = bytes2.@ = BSubclass if __name__ == "__main__"PhP() # H_getopt.py # David Goodger 2000-08-19 fromG.support imverbose, run_dock, EnvironmentVarGuard 1  sentinel = object() ! G7$s(@ Fdef setUp(self[_o.env =!()o) if "POSIXLY_CORRECT" in A^*5del[8!] WtearDown.__exit__]JassertErrorM, *args, **kw 1rRaises(h.LE@l_short_has_argsbDTrue` 4'a', 'a:')hPOFals: 9sot;b')Dlongs, option = 0 6'abc', [?=']P!bEqual(i$bcY:^PSd8d5  M?def?:1d',eRst_doU `opts, {- []P[Wps, [('-+?'')- p , P1: ^ K1#B=#2 /v , ['1'])  self.assertEqual(opts, [('-a', '1')]) * .0arg.5]) $A = getopt.do_shorts([], 'Za:', ['1f/2'e R'T\rror(", [> def test_do_longs(%): 0,!bc+Pabc']N,-/?, '5 =(o['abc= V6ddDbOabcd7 6# Much like the preceding, except with a non-alpha character ("-") in# option namP#atQes "="; failed 3 http://python.org/sf/126863Y afoo=42Ipfoo-barN/',0foo8/42J( &bc D \+K Iq# note:empty string between  and '--beta' is significant# it simulates an Qargument - ""') on0`# commsUline.0cmd@ = [hP, '-b-=!'3"5a',Lh' rg'arg2'] S=:!['=Y3;,H?'')#('n12')>B&= I', '')])  # Note ambiguity of ('-b', '') andabove. This must be F!# accounted for in the code that calls getopt().9self.assertEqual(args, ['arg1yarg2']) 2Rrror(U., cmdline, 'a:a['alphEbetaLdef test_gnu_=(%):k# Test hanSgGNU style scanning modea = ['-vX%-- --F=2']%# g`opts, # =H.w1b:'A=t%])t )#[(0'),!fU'1'),9f'('>82')# recognize "-" as anUumentk-b6-']' UJ-= -SPosix@_via +/+a ,# POSIXLY_CORRECTZ[env["""] = "1"*?\@glibref_examplesls"E(Q fromM Library Reference: Doc/libF.texI3An p0 usuonly Unoptions: 4>>> importg'-a -b -cfoo -d bar a1 a2'.split(E6G8Cd0bara'aHH}optlistWZc:d:':c3foo%)]?o'['UuRlong j names is e|ly easy '--condi=f---output-file abc.e#-x~ = s.split() >>> args ['--condition=foo', '--testing output-filepabc.def -x!a152']Whoptlist,q = getopt.(0, 'A[71...'[=%]):q([(90), DC, ''g-:'')o' E""" "import type2m =.ModuleType("librefF", sprun_doc(m, verbose)d@def _issue4629(self):longopts, shorsphelp=']C, ['W.assertEqual(Yv1D'')$}x~0xrRaises(!.GjError, -- ']) if __name__ == "__main__"p@unit.() """Test the arraym.Roger E. MU+# .GQ from 0supP)tweakrefdpickleoperatorestruct$ys warnings} ~_b_reconNRor as  sizeof_wchar =$.A('u').item$ class A!1Sub(*0Opass,`WithKw6!__init__,{code, ne7S=Nonee{.;0) <D'ubBhHiIlLfdqQ'@Misc(.0Casd 'W_bad_L*2, spam=42;!O'xx'8 ^Value \empty# Exercise l for handling zero-lengthUXahB@a[:] ^en(a), 0$? + (:* 3Poa += a # Machine1mat s. # # Search "enum m+_format_code" in Modules/arraym >.c to get the # authoritative values. UNKNOWN_FORMAT = -1 UNSIGNED_INT8 = 0 S "16_LE = 28@16_B3<*4(5>"32T6,7@*8(9>"64T,10-'11B,2*3 IEEE_754_FLOATX4.5cDOUBLE/60T7 UTF+#189#2021 class A ReconstructorTest(unittest.Case): def _error(self):.assertRaises(TypeE+!, o(_rl,:> "", "b", 0, b"")+e9?strfP.n/''Hi o?0, B V# n?o6  X|:/22pW`d", 16p;a")|numberscases = (Ah(['B', 'HIYL'], , '=BBBB'[0x80, 0x7fj0xff])%@(['bVhil`,^=bbb]-^X , 'e.=hhh! % [IGNED_INT16_BE, '>hhh', [-0x8000, 0x7fff, 0])$(['I', 'L'], UNSIGNED_INT32_LX]try a = array.array(typecode, values) except OverflowError:&5continue # Skip this test case.5 b = array_reconstructor()^).&, mformat_>strself.assertEqual(a, b,jmsg="{0!r} != {1!r};={2!r}".wF1)) R1def@_uni(~)6str = "Bonne Journ\xe9e \U0002030a 147"V:Js = ((UTF16_LE, "UTF-16-LE")%B%B%&32J/32J532_J032-J1for 5 in s encoding =0[.a;Q('u',* e<O!, P {Astr.!e(Fing)hd+ class BaseTestI# Required  attributes (provided by sub!!esS#NU: the1 toR%example: an initializer usable7he  3ypeFusmallerMqsame length as c, but 0>Obigg=/<outside: An entry that is notx/mbemsizemum guaranteed it!a_f,p12  .*Z4bad Ngturn adifferent from our own!re9Z%s[qs.indexl. `)+1) %(&)]#_> ]K!, 4 rGreater$a.;UrRaises(Type,*l, None?len$a.append?.?[0]mSa), 1gde, self.exasmple)  self.assertEqual(len(a), 1exa3!) 5def test_buffer_info()!): Xa = array..typecode, ..W5Raises(TypeError, a.oF, 42 bin (UIsInstance(bi, tuWbi), kN[0], intx/[1*!bi%-a)uqyteswapSr"ifVev == 'u's = '\U001'Oelse1@1 /  if a.itemsize in (1, 2, 4, 8b w 4#.bw6 x:==1"Fa, b#S9#Now<b?xMcopy%`mport - l 9iF.&(a/!idP_id(b)*AdeepcXi>jGreduce_ex"for protocolwrange(3%8uIs(a.__4__(@)g , pickle.HIGHEST_PROTOCOL-_reconstructoru @, K + 1"^gcloads( dumps(a,8& . * ASubclass$s self.examplGe) a.x = 10b = pickle.loads( dumps(a, protocol)Mself.assertNotEqual(id(a), id(b.+Oa, bQ#.x, b.x' Atypew ydef test__for_empty_array(!):+#5for in range HIGHEST_PROTOCOL + 1<@Aa = Y._.;codrjASubclass >iteratorG!Oorig , hw.exampl0dat2Plist(D@2 = e[::-1]!# initial X  it! = d'(2 , 8)'4@it, _d$aa.from2=eRc(it), ~5 ^5c! +\92) # running Cnext nO[1:];ip1, len(k)*I[exhaustedBRaises(StopI{Pion, 5", r (itorig, orig), proto) it, a = pickle.loads(d$a.fromlist(data2self.assertEqual()it), []) n def test_exhausted_iterator(@!):'aarray..typecode, ..example Aa), 56exhit = '(a/mpfor x in 9@: # A theG`next(eQ)04not4%ed)a.appendooutsidej 1, [_] 6>- +G in -#a.M0/[0 0en(Q1+len0a[0], a[1[Raises(TypeError, T/_, Non5 08m("?(-1Suy, ,Zy[:-1] +.[:I-1:]Imy-/00t a!  @1_ > tokAfileB!2*\Ma` tol/upport.unlink(sfTESTFN'`f = op_ !f, 'wb''6try.q&(f%f.close(Ab =   +N, 'rb')  self.assertRaises(TypeError, b.fromfile) 1(f, len(Gexample)-bEqual(b, array.;typecode, /J2NotMOa, bp=EOF/, /+1Lof.close(9finally:3sif not .dTHsupport.unlink(TESTFN) cdef test_@_ioe[)k # Issue #5395: Check if 8! r a proper OS8f# instead of V.?a = P = op5f, 'wb''+trCI5, aV|1ilewriteu A, 2*Lf%$"f.abAr++nYbQ toOlist4 C@a.toF, 423 51f", [None]n((lstring# Warningswd when arguments are incorrect as Aq Clinicop # handles that before the wf can be raised.  nb_warnings = 2 Twith e.catch)(record=True) as r:8<Qt.filterF("always",.2message=r"(to|from)string\(\) is deprecatedR,cgory=D:BionW)a = array.(self.typecode, 2*zexample;b; +E assertRaises(TypeError, a.toO, 429 b.+;7$rU(/()bEqual(a, b#if a.itemsize>19DValuZ, "x"^AE+= 1Zlen(r), 2!) /def test_toNQbytes)%$! 4 :642 hK U c , 0YK7s()K Gcb <W^1, b^  I ..0  6, a@+ Orepr4pQeval(daa), {"(":)#})@  cb('%s')" % i/st6Ltr(a_?cmp[ Is(a == 42, FalsI &!&pa &b== a, %  $!= a, False)#  self.assertIs(a < a, False)$=%?Tru$>#H >Hmal = array.(typecode, smallerexampl/ab=Gbigg<zZ _== 2*!' K] /al0!= & $ Ko ?2l, % bbLk?< a$=%>$ J&def test_add!):a0% \7;+p9o[::-1]iEqual(W*a, d" +x s%) U4bad,/()Raises(TypeError, a._RW__, b`4 S"bad"8i+ ?a +$ !2*C26+ A 9 Yk4mul* a = 5*array.(self.typecode, example) assertEqual(!*a,^!5*J `%) BAa = %*57X0H&*5 0DeO(-1)~?5 *F[:1]0[a[0]] * gRaises(TypeError, a.__mul__, "bad"def test_imul?%):5b?*= Is(a, b'?E*= 0:/a,)WI *= 100gQ/-1MaxJgetitem2SEntry:[0]m/[05.,-1k-kl7$1len8.E)H$-I 1_getitem__)  "self.assertRaises(IndexError, a.__getitem__, len(1example)) G H-IA-1) Ldef test_swp!):la = array..typecode,50[0]8E[-1]EntryEqual(a[0], a*v"-10ZvcIb p%GType/__ 4o, None:#0=b:N Z, L [ T  p0del6-@del bUaO(.F[1:]O-j1?:-1> ] self.assertEqual( *a,`rray.a(self.typecode, example[1:])9%) %mRaises(TypeError, a.__delitem__?4o, None: _IndexoR, len)H$-I#-1def test_getsliceq%):Aa = ]csa[:], auC#raFq?:1]q#/:1Yq-r&-s$?-1:$:?-1:b"2`"O10007b 3a[-U#':'9" & 8:[2;7 Q2extendedt# Test ( ing by compar with listeX# (Assumes conversion works correctly, too!"indices = (0# , 1, 3, 19, 100, -1, -2, -3 6100sfor start in K"/op!%# Everythexcept the initial 0 (invalid step=fef ) 1(a[:stop:step]),   list(a)[start:stop:step]) ; def test_setslice(self):!a = array..typecode, ..example)5@[:1]9(assertEqual(e,p) +F[1:]^S@Oa[:-`-<P`A+ J//1:MOIN6 F2 D:?000D!2*9/-1GE:6Og9:hCG?1:0C ample + self.example[1:]) %) a = array.(self.typecode, D@a[2000:1000]@N/assertEqual(z*a,w!2*J y-V#Raises(TypeError, a.__setitem__, slice(0, 0), NoneG"1Gb= 4bad/()t,bD,bydef test_extended1R_del_.%):indices = HD , 1, 3, 19, 100, -1, -2, -3 6100for start in K\Q"/op!% # Everything except the initial 0 (invalid step=fefO )P"9L = list(a$# Make sure we have a of exactlyright length{I# but with (hopefully) different data.3Q = L[`:stop:@]..reverse(J! =QaxLI,Ix./a, #L)  ?del>el %QindexY: = j @QY.RxH KL.@@(x),U7FValuD5\soutsidea_countam  for x in example: self.assertEqual(a.count(x), 2);7outside), 033Non+_def test_remove(R)for x in .X = 2*&_!a = array.g.typecode4Upos =zindex(x#|2([:pos] +8[pos+1:]. O ,E2)) _ bxRaises(ValueError, a,t?71pop  I?pop ;e 6Typppop, 424 fA , len(a)g 5-6'-1 nTEntry #0)$?[0]r4v*a,naH1:]+o   12O2/[3, v1  -9 # )[:tgmrevers  k H7: oextend , a.extend)  a.extend(array.(self.typecode, example[::-1])) @assertEqual("*a,e+rH%) Aa = pIkb4badz(gRaises(TypeError, 7, b_+ x/Ifqdef test_constructor_with_iterable_argument%):B  @3.{  #a`# non-w @G#10-# pass through e/0s rAad in _9%__w cl0A8Fw*%X T@ Uni3T', AJ Vnext(+B(yield Nonev)B0vertraverseS:tryimport gcexcept In 2skipTest('gc module not availv'+ 'Pl = [E(a)]Pl.appDl*gc.collec*lbuffer Pm = memoryview(aexpected!.tobytes!a%$, =O0 6[0]36[0]6# Resizing is forbidden when there are vUorts.# For issue 4509, we also check after eacW that> th`ray was not modified.   self.assertRaises(BufferError, a.append, a[0]) 6 7 Equal(m.tobytes(), expected0g4extg/:1iIoremoveNopop, 013fromlist to /()oLp q)"ifDtypecode == 'u':bjf60uniA  I~1operator.imul, a, 2{FlVGlqsetitempslice(0?, aO5del|Po1K def test_weakref()s = array..,vexamplejCp = P.proxy(saps 3q = None hReferencelen, p) 3P@unit.skipUnless(hasattr(sys, 'getrefcount'),6i 'G needs sys.82()'Tbug_7823698Wfor i in range(10tbwC'B',,'64Mrc =1i5 ?rc,yrsubclass_with_kwargs # SF bug #1486663 -- this used to err oneously raise a TypeError ArraySubclassWithKwargs('b', ne A=1) 0def test_create_from_bytes(self):&Y# XXX This1 probably needs to be moved in a s # generalized3@use h.typecode.pPa = a.('H', b"1234")&=assertEqual(len(a) * a.itemsize, 4@support.cpython_onlyL1of_with_buffer  ,vexample@base[5 = palcvobj('Pn2Pi'1|_ ._info()[1]\Aheck=!ofU, a, #+ O_"?out!Qinitip0unig"ifv != 'u']'qR%s(z) as cm592 G'foo2TfIn("cannot .pa str",(cm.exception)[AEBu', }  JelseMI G"foo2 R/obsolete_write_lock\S _epcapi imC get_null_viewy!'BgB5,b<, a&free_after_iterating 2 , B,), w,reversed9 M StringTest(Base +):J0setzcsuper(). _$8 e, self.examcple)  self.assertRaises(TypeError, a.__setitem__, 0, /example[:2]) class UnicodeTest(String , unittest.aCase):|@type1a = 'u'W\x01\u263a\x00\ufeff%smaller, e,Obigg+1Woutside = str('\x33'%0min0siz!2 @def "_u(YV`rray.a, 'b', 'foo')[?Aa = &0('u%\xa0\xc2\u1234/T.from/' !\x11abc\xffzs4.to|3Equal(s, ' Z @$a. , of_wchar7'1="\'a\\b\x80 00G 00W>ls:>repr(a),"1\"\\()"5issue17223# this used to crash)ifXR == 4S# U+F is an invalid point in E 6.0_A._str = b'X*Lelse}#PyeS_From () cannot fail with 16-bit )_t@skip("specific(326""*^ MFValuN)3 steaNumber1Basm"):7extslice , range(5)[::], a# 2$ i[0,2,4]i ?1::G ?1,3E O::-1 4,3,2,1,0K ?4,2GO3::-H ?3,1 P-100: %.-1], a[::-1])#  self.assertEqual(a[-100:2], array.(,typecode, [0,2,4]))M a1000:2N I 10:-K- Ldef test_delslice!):?a = wrange(5del a[::2]D D8 01,3$1* '- (3E/10l)2,3,4,5,6,7,8,9#F issue7788%9::1<<333] Lassignment"  o[42]*5  p42, 1, 357 G.?-4] _10]*3'0, 10, 2,  6, 7, 8 ,10 4113?1,  bG&[:$c0ins202:35ins"b[nL2,3)dc[2:3:3iterationcontains/ mlist(a), '@(F[20]- `B] in a, True+b[0] not.check_overflow , lower, upper # method to be used by subcls # should not overflow assigning lower limit a = array.(self.typecode, [4&])0R[0] =KA# shyuess than4 oassertRaises(OhError,!, . '-1"P .__setitem__, 0,&-1G?uppG4aGGBmoreG4G:R+G,E!) def test_subcl!ng\!): ~* =!9 ExaggeratingA(OS__slots__ = ['offset'] __new__(cls, , data, 7 Z:hreturn.I 9wainit__ y# =gai9" +vm0H[3, 6, 7, 11], 4\)EntryEqual(7, 72(Attribute`setatt", "color", "blue"Hrfrombyte8Q('b', range(10)b) a*b, b) IntegerNumberTest( R _e  t/a.append(42Bwitha2Typ\D/.0F'G42.0 Bable)__7num_num = num%5S/605sub^other70IntB(intz0 - /}?addM+MfSigned (*pexample-1, 0, 1, 42, 0x7f] smallerexample = [-1, 0, 1, 42, 0x7e*Obigg)3)f)`outsidL123 e def test_overflow(self):a = array..typecode)'lower = -1 * int(pow(2, a.itemsize * 8 - 1)51upp50 6if.check}!, O^*Intable(24), ;) class UnsignedNumberTest(Integer$d17, 23fz. -[O0xaaC0*/ =/))Ybytes_extend%As = .)/! !, N61$a.n xassertEqual(<2,[ r+6reversed(s)If[::-1]E$) AByteS`, unit. CCasea = 'b'p5min4= 1]egBg PShort(#h^2f%Hh /In)i\ dIf OLong(l]4eypecode = 'L' minitemsize = 4 class LongTest(SignedNumber, unittest.aCase):NptypecodK/'qa8a1UnsVeI(kQk !FP]U`exampl [-42.0, 0, 42, 1e5, -1e10]smaller0 20Obigg/ ^Qoutsi3123 p def assertEntryEqual(self, e12.5bAlmost6 0`A_nanXHa = array.., [float('nan')])b7#Is(a != b, True[ $=$OFals%>H$ I compare8w0str>PvalueQ]stead#No@a.tofs(), b buSSFfb.D>UdU8alloc_overflowHfrom sys import maxg 'd', [-1]*65536R:trydDa *=O!//.E + 1Zq Memory @6pas*pfail("Ao@ of $ >u cHed -e expected" } 2.71828183, 3.14159265, -1])  Qtry: b * (maxsize//3 + 1)!except MemoryError=Fpass-:lseself.fail("Array of h3 > r created -e expected") if __name__ == "__main__"munittest.() # -*- coding: koi8-r import 1a from ;1sup"TESTFN, unlinkoad, rmtree, script_helper, captured_stdouthM4lib$os &sy ubproces tempfile class MiscSourceEnTTest(.qCase): 1def_pep263(),.assertEqual(5"".eke("utf-8"),%b'\xd0\x9fb8\xd1\x82e%d'8U /\~\`(9f`kcompilestring# see #18826Cc = 5e(b"\n#D \nu = '\xc3\xb3'\n", "dummy Vexec"ed = {}\V(c, d" pd['u'],cKf3')issue2301 cp932\nprintap94\x4e'aSyntaxV as vH4 v.text, "kPu5e74-e(L4626"=latin-1\n\u00c6  #C\xc6/c6O3297 Aa, bU0001010F'\ #afd['b'] len(d['a']), 23Vascii57 L78204# Ensure that check_bom() restores all bytes in the right order if #?2pydebug mode: a buffer starts withUQfirstLra valid BOM, but next`are diO2ent=1one#fcommoniUTF-16-LESqwRaises(, eval, dff\x20o1twoos in common with the UTF-8 BOM 'self.assertRaises(SyntaxError, eval, b'\xef\xbb\x20') ?def test_20731(J!):\sub = subprocess.Popen([sys.executable,04os.path.join( dirname(__file__)@L 'codingo.py')]9xstderr=EIPE)2err.communicate()[1]# UEqual(sub.returncode, 0O,NotIn(b'l', errqe_messageycompile(b'# -*- : iso-8859-15\n', 'dummy 'E/bf4! _utf-8wZRegexg'fake'w },|9R@ ?B&?BOM!8>*N /Bbad_ pmodule_F = ')'Bpverify_ 3(: -&o2p2q$(, #| __import__, 'iI.' +K+? = (@8`-bA A + '+;EE, "rb") as fpbytes = fp.read([ !, B&, l'N\_valiU d = C{} exec(b'# coding: cp949\na = "\xaa\xa7"\n', d)6self.assertEqual(d['a'], '\u3047') ,def test_file_parse(<!):# issue1134: all ens outside latin-1 and utf-8 fail onEmultiline strings.Plong s (>512 columnsunload(TESTFNrname =  + ".py"sf = open(+e, "w",="cp1252"Usys.path.in:(0, os.curdir&6try"jwith ff.write("# -*-w'\n}26'''A short3/! qA very t %s'\n" % ("X" * 1000) importlib.invalidate_caches(*"__,/__Knall9Ddel t5[0]Leunlink i cK#o#[~rmtree('__py-__3error_from_N: See http://bugs.python.org/UE6289Pinputascii\n\N{SNOWMAN}".1e('i'Raises(SyntaxEj) as ccompile(}B, "<P>", "{3expected''ec can't decode byte 0xe2 in position 16: " \e"ordinal not4range(128)True(c.excep[.args[0].starts(/),qxOmsg=F ) class AbstractSourceE[Test:<default_ src = (b'print(9("\xc3\xa4"))\ncheck_script_output(src, br"'\xe4'"$rs_Q#:iso8859-15\n''8c3\u20accsecond7 wOthir # Only first two1areed for a magic comment. src = (b'#\n'coding:iso8859-15= print(ascii("\xc3\xa4"))\n')kself.check_script_output(src, br"'\xe4'") 3def test_double_`_line(K!):'# If the first # matchesbsecondis ignorede #'olatin1Kc3\u20ac Osame k_non_utf8 - seaZ?isor7a9981480850009cc5577c6e1f573b4e6801dd23c4a7d679ccf(6c674cf b0ba465637458c6990e5a8c5f61d4af%e576d97ff94b876f8050361ee3da91ca5c11aa25eb4275cc5788063a5f19741120c4f2de2adebeb10a298dd76/ '\xaa'*131sd Using Larger Than Block-Sizb'e Key - Hash _First 95e9a0db962095adaebe9b2d6f0dbce28 'd499f112f2d2b7273fa687060e431591ee0b67f0d8a26aacbf5b77f'   '8e0bc6213728c5140546040f0ee37f54', B#hashlib.sha384: '4ece084485813e9088d2c63a041bc5b4'F Y'4f9ef1012a2b588f3cd11f05033ac4c6F0c2ef6ab4030fe8296248df163f44952512: '80b24263c7c1a3ebb71493c1dd7be89b46d1f41b4aeec1121b013783f8f3526b56d037e05f2598bd0fd2215d6a1eF95e64f73f63f0aec8b915a985d7865985}) # 4.8. Test Case 7 hmactest(key = b'\xaa'*131AAdata%This is a < using a larger thb'an block-size w7and=< h=B. ThG?nee< ds to be ed before be/us<  by the HMAC algorithm.zhexdigests = {i5 223a854166ac5d9f023f54d517d0b39dbdV '946770db9c2b95c9f6f565d1 56: '9b09ffa71b942fcb27635fbcd5b0e94 bfdc63644f0713938a7f51535c3a35e6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82461e99c5Fa678cc31e799176d3860e6110c46523e`e37b6a775dc87dbaa4dfa9f96e5e3ffdebd71f8867289865df5a32d20cdc6022cac3c4982b10d5eeb55c3e4de1134676fb6de0446065c97440fa8c6a5 1def<_sha224_rfc4231(self):6._mz_cases(D2, 'H', 28, 64 g$56Jg"#56g56', 32g/38%b.sha384, 's%ha384', 48, 128) def test_sha512_rfc4231(self):#'._1cases(hashlib.?2, ' _', 64h legacy_block_size_warningst class MockCrazyHash(object"""Ain't no X attribute here."""6__init__{{, *args]+Gx = "1(/ U.1digVcize = A. 7cupdatev.)-v)C_C@kreturn(Twith f.catch Q'simplefilter('error', RuntimeW gassertRaiJ 3|hmac.HMAC(b'a', b'b', Imod=* s?rfail('Expected about missingD'D c.l9= 1_small_U T&Js(Deprecation;ing6key = b"\x0b" * 166Adata @Hi T T = "9294727A3638BB1C13F48EF8158BFC9D8h=Pkey, j #Equal(h.hex ().upper()pB)  ConstructorTestCase(unitM."):ne@ignorzlnormalj# Standard cka call.@eed = 0:tryC fb"key"except E:ion<e/(" r"d JSion."> J_str_keyP a 8 of type str, which is an t, because it e!s 9$# CUbytesPTypeE  HGM dot_new_nVf type bytes# with self.assertRaises(TypeError):+2h = hmac.new("key") !@ignore_warningdef test_ePtext(iR# Constructor call + ,.Ct?tryaHMAC(b, b"hash this!")>except E:ionK.fail(" argument r"d TGion.iKE(Equal(h.hexdigest(), '34325b639da4cfd95735b381e28cb864'K 7_bytearray= 8!6), K ,,-o mod="md5X&]s^amemoryview_msgczE(Y ?EsO msg:`lmodule1 C and > 0", lib.sha16UN class SanityTestCase(unit./):default_is_md5DMping if  0s to MD5 algorithmAq# NOTE: whitebox} depends on the internalsxZdV_consA# UsH"d() in case somebody has overridden __eq__/__ne__id(h1) != v2), "No instanceeF1V ah ! ''l.l4l e?ity   ?sz1.update(b" random text6(),+())DeEdoes originalp2hexsh<$"H*y C|Rmparel!co8_Anput exception handlinga, b = 100, 200WqpRaises(bError, , JXb"foobar"^=YB%, hHncf.assertRaises(TypeError, hmac.compare_digest, a, b) # Testing bytes of different lengths-< = b"foobar", "!self.assertFalse((F%))4U\xde\xad\xbe\xef_d#eDsame,_value?baz#x "ab o1d\xeal# r?Tru8\k 4 Qarray!, 1yte7(!),+ t9 "lE6J*z;F and(T 3_b, a) |'4  X.!sG i%= import argparseudatetimtos.pathm drandomsubprocessy @tempbR def_#(#,"s)with open "w") as fp$@for >P`print(!s&fpkfp.flush(NgoutputxXaif notVnareturnuA"Wri%{%s" % (len(XM)`k Tformat_shell_args(3' '.join9o_opcmd = [executable, '-m', '!']cmd.extendO.+06 = :.run(cmd,>wstdout=5OPIPE2 universal_newbs=Trueexitcode = . if" e2cmdU%@FailoQs: %s1ed  tA %s"xB!% 0it(@?~d/a.split(%h3runk.p, huntr^cs=NoneFdtmp = 0.mk \6try-3tmpW)N^Pmatch"b', tmpbAf #+`? % //oc#@4gfinall3if G.exists(tmp):  os.unlink(tmp) def parse_args(): -qr = arg .ArgumentP,7r()'@.add> ('-i', '--input',)T $help='Test names produced by --list-tests written 'L\'into a file. If not set, runR' o?outResult of the bisectionb nb2max', type=int, default=1: Maximum number.zto stop<(xO: 1) NOiter/00< XaFs$00# FIXME: doc that following`s are e e ,2s =%!r.a_known 0.I& =;O`returnestDmainn=b@"()!if3.Kwith open(:v) as fp%)[line.strip() for q in fp]Felse<8a_casesjprint("Start !%ss" % len(J)o8aOAs: %-format_shell@ DBhR willwhen gett0%s #es! " "(-n/--0 opn ),4after %s =N=<#!% /P.max_"s,4b! ="e_: s>s|P_timekime.monotonichDA = 16tryWwhile& >F and! < s[JSn3' =PrBmax( r// 2, 1#0subHrandom.sampleE!, ;0[+] Iter1%s:8/%s80% (4,))2r pexitcod2run%, TCG@"ranlj2 % #"t0", { Lif exitcode:  %print("Tests failed: continuing with this subtest") C 4s ="s!output = write_b(args. ,D []else:L psucceedPskippP, tryPa new,seQ {iteration += 1 except KeyboardInterrupt Ia"BisecLi47ed!G(!) g (%s):" % len(f)1for21 insP"* %s:64Zg2if z 9Oten intoK1Admath.ceil(time.monotonic() - start_'ifA <= @max_8completed5%s Ps and;5% ($`, date.delta(seconds=dt)R=sys.exit(1 @. after @ if __name__ == "__main__" () # IMPORTANT:%file has the utf-8 BOM signature '\xef\xbb\xbf' # at, of it. Make s0Wis preservf any changesBre made! # Arbitrary encodedtext (stolen from@_doc2.py). x = 'ЉЊЈЁЂ' def y()1"""And agai a commen:(0Fpass #!/usr/bin/env python3 # # $Id: ncurses.py 36559 2004-07-18 05:56:09Z tim_one $ 9 aactiveq suite 2he R module. # TPcript displays variou2ing ser should verify whether #yB correctly. # import| iApad \|_ (stdscr, insert_mode=Falsencols, nlineA8, 3ipuly, ulA3, 2(ifHmVe!e'1 v'@overe*+.addstr(uly-3 , "Use Ctrl-G to end edit U.[H2HBoK1 tydwhe lower-right~Cner.Swin =}.newwin(0#, ?-|.Uangle1-3y +{Grefresh( box = textp&ad.Textbox(win, insert_mode) contents = box.edit(stdscr.addstr(uly+ncols+2, 0, "W entered in theB?\n"?Trepr(l)"O'\n'Press any key#getch() Pfor irange(3):Hmover + i, 0v(clrtoeolZdef main(DU c.clear/test_textpad-c, Falsi  True) if __name__ == '__t2__'curses.wrapper(P) docT""" Basic classstruction.3>>>CU0... eth(self): print("Hello1...LDAC.__e__ is type %Sa = C 5C) 2 .m|$>>> Use *args nota ra tA: passBBb< = (A, ByA C(* K ha trivial metaW  M(AVx@5 C(L*=M7+M @O*kwdGword(2E= {'%Q': M} \>B1 with a __preparsc(ho @3!od[(3, *+P called:", I , W_4return dic|new__(cls, !,  _space7New ?.__s Dinit% ,j3  ('C', ()) {AAlso anotherpobject,gaclass=M, other="haha"): ...T pass'Prepare called: ('C', (,)) {'other': '[!'}A5New=">>> C.__Sq__ is M;ATrue "bases__ == (z!,)! *ba = C(:a\C2 Check that build doesn't mutate the kwds dict. Ha= {'metar': type#P C(**-.):i&J% Use various combinations of explicit keywords and ~Q N ?M, 1T,lSB!7UC(B, _=M, *$-Ptest._Xl.B'>, ^2B,  g`for duU7=MD[Traceback (most recentS lastQ[...]SyntaxError:,` argum8repeated+q>>> AnG way "2CType'__p__() goPltipl6Plues kRa __p __2hod3`returnca instr=,ed'LoggingDict(Hdef __setitem__(self,{, value/ print("d[%r] = %r" % (key3b3y.g 1...RMeta(~U@staticmetho.7q(name, H "n&C(I Mfoo = 2+27 foo = 42 @... bar = 123 1... d['__module__'] = 'test._metaclass',uqualnam.C1fooA4-21bar#>>> Use a l that doesn't derive from type. Lq>>> def6(, bases, space, **kwds):2pprint("o":"/<)( ns&asortedi\.items())4'kw4/freturn|0 C( = Ra = 4bRb = 29R: C (hns: [(,0), 'Q, 'C'aa', 42 b', 24)]Rkw: [ (C) is dict#ATrue !dC-F|And again, with a __prepare__ attributv"=n 14$LoggingDictA.#= rd? K, other="booh"YX1@W hg Nvia_@', 'a' t8aO2d['Ad['b$-63/('u0TheAault0mus0fin ()&7hodT!{}fMake sure it works1subq7ingQ0 M(Y ! @amethod_/(cls, *arg|yd = super() 8 h7["hello"  LA M^[gF$'C.& Test failures in looking up the&`ObscureException( ;ass FailDescr: ... def __get__(self, instance, owner): ...raise ObscureException&>>> class Meta(type@ __prepare__ = FailDescr()@aX(metaL=L GApass2Traceback (most recent call last8Q[...]1Ptest._a. """ import sys # jP func introduces __locals__ which causes various ns to fail. if hasattr(sys, 'gett`') andp.( __E4r{} else@'doc&Ts' : a} def_main(verbose=FalsAfrom# up1 d=$s0S.run_z('#, y ) Q__namA= "_2__"9 True) # Ridiculously simpleof the os.startfilefor Windows. # # empty.vbs is an 5!(e 4a comment),does # nothing when run with cscript or w nA possible^@roveT would beBhaverdo somee that # we can detect here,:make sure (] only(?succeeded, but also. actually.@unit 0$os :. osMfpath #= >_pibute(o'Q')  TestCase(.+nonexisting .assertRs(OSError, t7, "B1") bI \# We neede child processjs in a directorya1'rePaboutOdelete. If we@runnunder -j,EQmeansP harn|providedy isn't a safe o.ISee http://bugs.python.org/issue155268@more2ailw#change_cwd(@.dir.executable)Cn1 = 3Jjoin= __a__), "+;("up, "openi$a#) As = HCloop0@ondiK"alW=qsum(i*iHir*(100) if i&1 == 1166650 `!neRlist((i,j)Uange(3) for j in range(4) ) [(0, 0), 1231 11, 11, 11, 2 2 2 2 '] Test nesting with the inner expression dependent on"aouter >>> list((i,j) for ii 333] Make sure`inductvariable is notFosedei = 20|sum(i*iB100)yV328350i:#200first classcOg = U4S'btype(gc<@ 'generator'>f(O([0, 1, 4, 9direct calls to next()34c14Traceback (most rec-q last):7 File "", linein -toplevel-1 `StopIt0 ion Does it stay stopped?c @runnwpgen whef!fi2funis out of scopesdef f(nX0...j returnn_4f(1c , 16, 25, 36, 49, 64, 81]{3)N+D o4) if |2Ry7 ] Verify that parenthesis are requireda{otement!wnA ...SyntaxError: invalid swused as a keyword arguX valuvict(a = ;l SyntaxError: invalid syntax Verify that parenthesis are required when used as a keyword argument value >>> dict(a = (i for i in range(10))) #doctest: +ELLIPSIS {'a': at ...>}early bindingnthe outermost-expression Ex=10 g *i.5x))$Ux = 5blist(g[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]i makes an immediate check fKterabilityg6Traceback (0reccall last): File "", linein -toplevel-0/ nBypeE`T'int'is not i%lel/ifpincluder2,4,6,8O>>> b10) if@5Q1,3,5,7,9 1?inn \(i,j)u3j5 4 (0, 0), 1231 11, 11, 11, 2 2 2 2 re-use of tuples (a side benefit usgenexps over fcomps)AQids =(map(id, ((i,ii=int(max(Ev) - min+0w| e' ai`uAas ls!(yy(1,2)) = KuS;can't assign to r+[& # Tests borrowed from 1nspC0by _Vs.py A## Make aacts like C?y=ambda n:'(n(7(O5, 6, 7, 8, 9] Gs always retur b6er:1pdef cre(v0...S r = 5 pr"8", next(r&rlSallerk ... r = creator() ... for i in r: print("caller", i?B>>> P^! 0F( 1 2 3 4 GenerQs can[ other g!: 5{def zrange(n)y uyield iOSlist(P"5)[0, 1, 2, 3, 4] Verify that a@ expnot be resumed while it is actively runningg = (next(me)#10eme = g4Traceback (most recentAClast0 F"", linein -toplevel-X' i B+28B<ression>NValueError:c already executingexception propaga )uv10 // id(5, 0, 2dgzj&7(j~ i+35Ai ZeroDiviointeger d or modulo by zero6 @ `StopItion Make sureANoneq valid return &ue+'&p[/, !] Check attributes are present'i*3 expected = set(['gi_frame', _"']({ in dir(g) if .startswith('__')) >=p(TrDfrom test.support imHAVE_DOCSTRINGS;C@g.__O__.__doc__ 4 else 'Implem2(self).'lVtypessinstance(g, .qBTypeZe __iter__ slodefined to_/^sR84the P flag1setFerlyMcme.gi_G(0,1 5ing 0  >>> next(me) 1me.gi_running 0 Verify that genexps are weakly referencable 4Jaimport$5ref g = (i*i for i in range(4);Dwr =9h.ref(gb() is ETrue[p6Xproxy8blist(pH[0, 1, 4, 9] """ @sys # Trace function can throw off the tuple reuse test. if hasattr(sys, 'gettG') and sys.1(): __<__ = {} else@'doc&Ts' : a} defz_main(verbose=None]Afrom" upz c_"s.S.run_w(%#, t)#'te countH if! ,"qotalref5"!gc#Ps = [U] * 5 WBlen(/)SE/gc.collect(MfU[i] =/Tprint :`__name A= "_2__" u )Test scriptQ'cmd' module Original by Michael SchneiderC8cmdw@unit=io <K class samplecmd(cmd.Cmdm3InstanceN2>PmycmdM OoparselinebI."""(>", "''1?2'help', '  7 " ;? z!?Pshell8 | !command@GaJ > 9 ] arg1>B"2') J onSsadd 4 59*& #*** Unknown syntax:g _empty_!~default"default") 4 *** Unknown syntax: default Test for the function completed+1():->>> mycmd.! qThis isL "q method'Gnames("a")!['add']:4"12Z]aDhelp+' _+& -,he/ zsorted(_(")k, 'exit', , 'shell "doM ~s"testet0No +B on  :3add702tex,adDonecmd("(7jgDocumentedmands (types=ZAadd E x>UndzeF! Vaprint_s "header", ["comD1", 2"], 2 ,10X.{ 9 2 columnizeq[str(i)i in range(20)]0 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19~$, 0p1 14G1{1 1521 167834an interactives, put some"inmdqueue attributefand let it exec includepreloop(), post uemptyline(),aSparse )s%kuse_rawinput=0c0=["0, "s04 5' "=""mdaHello from M invalid number of argQu/============= add helpUndocumented commands:D exit shell Vo text for&Hello from postlooA""" !pdef preb(self)xprint("C)'")<V=*>completedefaultE, *ignoredThis is the:< method^_e_URC1do_s;8, s>6assodo_add'l = s.split()s\if len(l) != 2tx *** invalid number of arg;&s"M5ereturn`:tryU[!i)!ui in l]1except ValueError? should be Dl[0]+l[1]E?c 0do_*7argO, True class TestAlternateInput(unittest.bCase):2 sicmd(cmd.CmP,7&args, file=*s.stdout'M6EOF K 6 %2(&\'Unknown syntax: EOF'[uZ__with_missing_final_nli = io.StringIO(" J&\n 2koutput820cmdEelf.q(stdin=q", =H 9.use_raw) = False1cmdP7assertMultiLineEqual(aP.getv{5(),KH0("(b" ?2\nB")) 1defG__reset_at__ub2v2\n"  "(Cmd) *** Unknown syntax: EOF\n")) ) input = io.StringIO("print \n+*>out+Icmd.stdinMU9ohF cmdloop(L self.assertMultiLineEqual(?.getvalue(),K(9\n"  +  def test_main(verbose=None):hAfrom"q import A_cmd0sup.run_docJ(!#, O+@unit'(TestAlternateI\)coverage( 3dirtrace = S_module(''v !r= .T8(ignoredirs=[sys.base_prefix, Dexec]Y=0, count=1v"('>Flib; .reload(cmd);Y)r.resultsH("Writing Cage &B..."r.write_ (show_missing=True, summaryKDdir= ) if __name__ == "_+2__" if "-c" ibs.argv"_L`'/tmp/4!elCiCsamplecmdclass().TKelsepC0 # ] iterators. 4sys  .U &, TESTFN, unlink, cpython_onlyDcheck_free_after_4ingdpicklecollections.abc  of triple ] (too big to ie) TRIPLETS = [(0, 3), 1 2gs0, 1, 0"41, -?1, -2-2-2-$ (X. [ [z-[RZ Z +[  .W(--G"% 02)]qHelper Aes BasicIterC__init__(83, n.nQi = 0A4nexA>0resAi-S ifDA >= Jnraise Stopa:0zX5+ 1`returnW +K IteratingSequenceClass: def __init__(self, n)h.n = n.3ter.+return BasicItereS`.n) ct? Se2sgetitem7, iif 0 <= i < iKelse#aise IndexErrorUnlimited y uDefault,Dpassp+Noe1__i = None # Main test suitejTestCase(unit.1): * # Helper to check that an dRator s a given s@80P, it,*, pickle=TrueP(H)n#res = []zwhile 1I:try;0valfext(itRexcept Stop^ationAUbreaky8res.append(valTassertEqual(res)x  for loop generatey@for_2yAexprj{00er(O)P ]0in 0 9#7qability~eRitorgproto in range(5.HIGHEST_PROTOCOL + 13d =s.dumps(cQ+&it,zloads(d!# Cannot p type e%ity because dictBs un as listo#). n!),{  4(isinstance`collec!bs.abc.0?or)Fm5n'continue//, !BE[1:] b^ !ofa() funef_/(self): self.check_iterator( (range(10)), list0) ;# Test that 3x)) is the same as!x)5def testn_idempotency(!):%^\seq =zBit =X2seqZ54it2&it[.assertTrue(it?it2for loops overdas work @for_0Y#!Yseveral independenhf;.cea3,res = []NTAi in (o j $k$ (`res.ap((i, j, k)Equal(res, TRIPLETSQriple@ comprehension usingIynested_2s?_N  A 03gwithouQ ?for$F ?seq#a class ! _ __naw _4_IingSequenceCr `explicBter( w +s on a s[/^ P?seqOF/()*C< dF =mutating_ sm_pickl}zorig = h5*PprotoI.HIGHEST_PROTOCOL + 1=p# initi;!or itorig = iter(orig) d = pickle.dumps((it& , ), proto4vit, seq:zloads(d&seq.n = 7p self.assertIs(type(it), u H2Equal(list5 range(7))) j# running Iator0nexFq ?1, _emptyfor i in Si1, 5):9959xhausted=Raises(StopIteration, 8", ^ rhTrue(isinstanc, collecbs.abc.:or) #[]def test_mutating_seq_class_eP_(Ona = SequenceC0&(5qexhit ='(a/mpx9S: # ~A theG eQ)04not4%edav0), B*p, [5, 6].aT0, 1, 2, 3, 4, 9# Test a new_style {q with _x__ but no () metho@3E  ,gobjectRx A preturn  X]TypeErrorS7er,z two-argument"()callable o_$ C;__init__1Qi = 0n;n;6? ;?E + 1 if i > 100: raise IndexError # Emergency stop6return iself.check_iterator( (C(), 10), list(range(10)), pickle=False) K# Test two-argument G) with function-def testr_()&spam(state=[0] Ai = 1[0]Xi = i+1{@a that qs StopIv _ 7if i == 1WX\82]PexcepE propaga fthrougbwEk=p[kqRuntimef vres = [6try/3for x in(+207)res.append(x)v$ `.assertEqual(res P?lseAfail("should havedy"Y?ionsequence ) Lclass MySIC( FY__getitem__Q;, i&l ru  .~:, 1  _g from 5, b_u raise StopIteration return SequenceClass.__getitem__(self, i):.check_for_loop(MyA(20), list(range(10)), pickle=False) Q# Test a big ,def test_iter_big_!):#2v!00y  qn empty^ }{[]), []co tuple]](0,1,2,3,4,5,6,7,8,9\ ,))}?}}.q ostringrsp"abcde"Rp"a", "bcd-e"idirectory~Ldict|Q = {}0Xfor i int 2[i] = Non+  n.keys(/fi f = open(TESTFN, "w":try 5?f.write("%d\n" %lfinallTv.close(wr *f, ["0\n123\4\n"]FV5` Xcunlink except OSError IpassP)'s use of aators.builtin_0.assertEqual(% 5.5AR15(h'(de"one": 1, "two": 2 0hre3UdWdI`3Ras(Type1#42Jaz, "r") try: self.assertEqual(list(f), ["0\n", "123i4\n"])Kf.seek(0, 0d ? kfinallf.close( ounlink(TESTFN0except OSError?;Qpass # Test tuples()'s use of iterators.(def test_builtin_2(()` &SequenceClass(5)), t1, 2, 3, 4)C0C6 []k((PP"abc"S "agbBc"))LZd = {"one": 1, "two":P"thre!3}Q-2d),(d.keys()b5Raises(Type7 , S2'42f = open\V, "w"O for i in range(5f.write("%d\n" % iPr '&'('2'e@  e (9ofilter(2 )(,mNone, 5/),U?@1, 51k 0)[+C/, 5OP]P+ Vd\H", D"c 9 jc BooleanH def __init__(self, truth): ." =% #def __boolJCvreturn JBbTrue = Boolean()HFals%) !class Seq _*argspvals = #[H?terJIterCGmr.+ !)_i = 0#z KL4nex3Ks = i + 1'if i < len.yZ/?[i]_OelseJraise Stop]ationNr0Seq$Pseq =A(*([1, bv] * 25)"assertEqual(list(filter(lambda x: not x, seq)), [M?*25J%i`O P# Test max() and min()'s use of ?aators./{test_builtin_max_3.aSequenceC (54W303 ax(8, -1), 8( %in('-1{d = {"one": 1, "two": 2 0hre!3} E d)-?wo" (i( @ax(d@ues(/3- 0in(28), f = open(TESTFN, "w:try5f.write("medium line\n2%xtra large) `itty-b)mfinallfclose(r @in(fseek(0, wS"axS a cunlink except OSError: Qpass # Test map()'s use of iterators.%def test_builtin_/Vself)[.assertEqual(list()lambda x: x+1, SequenceClass(5))),e Erange(1, 6)))d = {"one": 1, "two": 2 0hre%3}Zk, d=d: ( [k]), dd.items(dkeys = d.5())pexpecte[(i < len(d) and ;[i] or NoneiN for i in g63)]cf = open(TESTFN, "w"F6tryO K'10  f.write("xy" * i + "\n") # line i hase 2*i+17lfinallqv.close(r en, f)),@1, 2 1cunlinkbexcept OS/zi/) &[]*?*[]-2), 'ab'9'a'), (2, 'b')]yRaises(Type#a, zip,;0o0), 429$?zipGI[:ing3 @[(0,1 2," lc.~l,+Sd, d.valueDBP# Gene all ints starting at constructor argcX IntsFrom__init__(8,TCB.i =!G3terG@preturn G=4nex=xUelf.ixQun i f = open(TESTFN, "w") Etry: f.write("a\n" "bbbGcc\n7mfinall;fclose(^|rE |self.assertEqual(list(zip(IntsFrom(0), f, -100))), Q[(0, !, 20 D (1,_, -99a a (2, "%078)], cunlinkWexcept OSError Upass _prange(5I [(i,) for i in &])I@# Cls that lie about their lengths.yc. NoGuessLen5def __getitem__(J, i)&if i >= Araise Indexreturn i3( 3len `3`0a70bl$[*argsH$l s7en(V)), 3u/001 e(2j)> =! >4expected =/ i.0x0 (, } AyA)ntx, y), 8 test_unicode_join_endcase&):fr# This / inRs a U< object into its argument's natural*# iteration,the 3rd posi 7{OhPhooelc__init[, seqAit =w(% 7Gi = We3tere`bC.=4nex=t:/.i=i+1J== 2Dw return "fooled you!" return next(self.it) &f = open(TESTFN, "w")Etry: Xf.write("a\n" + "b7c\n8mfinall<oclose(~ rF$# Nasty: string.join(s) can't know whether unicode#) is needed.# until it's seen all of s's elements. But in this case, f'sFiterator not be restarted. So what we're testing here iG manage to remember everythJand pass tz on< .. got = " - "=OhPhooey(f) =assertEqual(got,  - b\n - fool? - b cunlink except OSError;t# Test s with 'x0y' J0'x Rin y'81def_in_and_not_Felf)mpfor sc5JI$ingSequenceClass(5), @DiBwrange(5_PIn(i,t E"abc", -1, 5, 42.42, (3, 4), [], {1: 1}, 3-12jJ p7NotsSRaises(Type, lambda: 3&1267map7d = {"one": 1, "two": 2 0hre3, 1j: 2j}kdvIn(k, d#.values(#`v`i Ev, d)r ,#i3k, lkitems() v)p-LZ(v, k0F0).""+ 2%Achun  f.seek(0, 0CN>, f+HAIn((F90 N4   unlink(TESTFN) except OSError:'Qpass  # Test iterators with op.countOf (PySequence_C!).?def test_)f(self)qEfromN import ,A4.assertEqual(!([1,2,2,3,2,5], 2), 37(7)7"122325", "2"k464"0)W Raises(Type,, 42, 15!Gvd = {"one": 3, "two 3hreu1j: 2j}for k in d _d, k) +.values(Sd4/2ji 150f =n/V, "w"v:tryf.write("a\n" "bc :mfinall>gclose(' r or letter@("a"sb, ("b"5("cWd", 0|f.seek(0E#f,` + "\nvf `Q[indexI ),L D! )1)7"in 73p 7V5), 5V{+, E0A-6 }%45B/6"*)5 indexOf)  f = open(TESTFN, "w") u try: f.write("a\n" "bcd7e\n@mfinallDfclose(grEpiter = &(fG self.assertEqual(indexOf(f.,O), 177 ?, 0nRaises(ValueError, $, lAT  :cunlinkWexcept OS  Upass  iclass = IteratingSequenceC&(3]for i in range(3)\c@, i)z0@ >2-1)a# Test8ators with filelines().idef test_y=>/ ?4Typ[if, None@N=#428\(["1\n", "2\n"]e )2("3)4)q{'5\n':}( }# Try a big chunk tooec*or8 __init__($p, start?Gnish/*.)" =1#' fiI2 = )iLYtF4nex1if yBi >= zZrGR Stop*?ion`result!tr..i) + '\n'0O+= 1 rreturn WzGn EWhateves o*, #  (6, 6+2000)o\ (TESTFN)  $expected = [str(i) + "\n" for i in range(1, 2006)] ; self.assertEqual(list(f), Y%) 1finally:Bf.close()+tr'+unlink(TESTFN0except OSErrorb;Rpass "# Test iterators on RHS of unpacking assignments.def test_$_?()mpa, b = *4y# !(&1), Q)q, c = IingSequenceClass(3V0, cY!0,\O# too many valuesnVCqmQFelse# fail("should have raised U"not enoughE 2EmCMable5lenOTypep=To {1: 42, 23"}.=@f = openV, "w"lines = ("a\n", "bbWccc\n)(_>s~#p.write(sr Kf2 s 8.Ec?c,))2), {42: 24} ( 422@cpython_onlyref_counting_behaviorc1 C(object>A = 0Ya__new__(cls4"Bcls.<I+= 1=rreturn s.K +h\del__F cl2!__)__D%m >%-= 1 x s= C()  self.assertEqual(C.count, 1%_del x303l = [C(),n]A3AEtry:2a, b = iter(l(except ValueError6EpassGlA0) '# Make sure StopIteration is a "sink state".1 This tests various thingat weren't :s in Python 2.2.1,J?pluDaalwaysKb fine.1defy_\`_list()!# used to faiAa = 4range(5)h|aZ =<;b),E2a.extend(aG, 10eQ?[])\tuple(0, 1, 2, 3, 43#ostringq"abcde"['a', 'bcd6e']$mequencaH S8vClass(5S.)+a.n = 10/#ncallab? iQspam(eG=[0]_2i =&[010[0]%+1`if i =qraise A1ion("shouldMhave gottenmfs far"qCueturn it', I2 ?dicXXX For a more thorough, see towardPe end of2# http://mail.pV.org/piper/ -dev/2002-July/026512.htm 0{1:A:2, 0:0, 4:4, 3:3}HPfor ba), a.keysca.item v+s(+WS1en(9b)). def test_ sinkstate_yield(self): def gen(for i in range(5#O% iJ2b =Jk.assertEqual(list(b), [/))2A[]) 'Vtest_In5a =9oiter(at;enumerateFe = 2eBzip($55),)x$L3720 # Avoid a crash, when an mator deletes its next() method.class BadIt(or(object __Y,__ preturn _<<8del2.__0 IMe16tryZG*) %)Epassaexcept TypeError/+, extending_Q_with!z_does_not_segfault5# The code to L! a K has a fair # amount of nontrivial logicCPtermsguessing how>much memoryallocate; advance, "stealing" refs,?Pand to`shrink` at end. This ibasic smoke@B that scenariof"+00 $lst = [0] * 500o,24Mlst.pop(0( xen(lst), 760H@cpython_only ;_overflow.3est1e issue 22939Ei(UnlimitedSequenceC(z # Manually set `it_index` PY_SSIZE_T_MAX-20out7oopqb.__set_(sys.maxsize - 2 (i4/1h7Raises(OT /# Check : eplways rZd5yelf.assertRaises(OverflowError): next(it) def test_iter_neg_setstate(self<Pit = & (UnlimitedSequenceClass())RkEit._If__(-42X.assertEqual(?, 0&1pfree_af\atingocheck_*,), l, (0,)neU0 dfor typ in (DefaultIterE, No W/!RaAType0typa% Smain(Irun_unit(TestCase) if __name__ == "__72__"0() import math $os ]%syD_asttempfileypes frome d0supl.!cript_helper, FakeP cj Specifics(.:compile_singl, source<&(B, "<0R>", " "InvalidSZ cSyntax~no_ending_newlin0"hi<6Vexec"Zoo("hi\r*i\emptyEA1oth\sJO\r\nNt$(p\nstuff]`f():\n&OpassI this_is\rreally_old_mac\rS Qdebug_assignment# catch "rs to __9_N>8 ]5, '; = 1', '?'builtinshtprev = .O"setattr(#tk7ureiR , mY -P_arguWo_handl # detect duplicate positional and keyword K seval, 'lambda a,a:0=/=1?rror, eval, 'lambda a=1,a=1:0') (self.assertRaises(SyntaxError, exec, 'def f(a, a): passB% = 0, a = 1J,): global a;Q1') atest_s _e(!):! compile, "1+*3", "filename "nnone_keyword_argr&f(None=1)k wduplicate_o_local}Z[1 _with_general_mapping_forstvclass Mc"Test > interface versus possible calls from eval()."YH__getitem__}W, key( ifz == 'a'return 12e'A Key# s, valueresults = (key- [5keyUlist('xyz $fm = M(3g =<s('z = a', g, m2&Equal(m., ('z', 12)/:tryV\b\except NameR :m Jelsefail('Did not detect a]dir()O aXs\"gRQ#mQ2Typrm=AwS"Non-  yAc# Verify that dict subes work as well30 D(- z-QG.Wd = D-TdaIad['z']def test_extended_arg(self): longexpr = 'x = x or ' + '-x' * 2500-eg = {}@code8'' def f(xY!%s$,`# the essions above have no effect, x == argumentyvwhile xax -= 1# EXTENDED_ARG/JUMP_ABSOLUTE here*return x ''' % ((,a,)*10)$NPexec( 6, gh .assertEqual(g['f'](5), 0) >6@testl_orderKRaises(SyntaxError, 0, 'Mf(a=1, b): pass'hfloat_literalsh # ing bad , , val, "2e" 3O.0e+6?1e-43-4e/21"indentationcompile() of 2ed block w/o trailDnewline": = """ if 1Bif 2 Z js, "", "a# This! is probably specific to CPython and may not gen"iz#(other impleJs. We are trypto ensuhat when`first  starts after 256, correc'bnumber1@# inAqcebackswPstilladuced.l_leading_l As256v.join(["\n"]6 + ["spam"]Uco = xp'fn', 'u')aco.co_no, 2571lnotab, bytes()~U_with]zeroe0forC["077787.20xj.e", "090!",Wu8"08&0A 98M1b42/qBADCAFE o12345678JBb1.1?4.2IB101jLCo153 Sb100e>3777 ?777H0&o 67"]3arg 3 eval("0xff")5,@777.-/77H -0. self.assertEqual(eval("0777e0"), 777) self.asse`.1.0/Z)000e-012[/09.5*?9.5@777j-.0 0U/0jS.T e3}9.6  1 R Z0 n!e-DF, DA0008m/8.6!097970b10y/42f6-0bh1$-6P0o777b?511coc^18) &def test_unary_minus(7!): I# Verify treatment of 1 1 on negative numbers SF bug #660455M if sys.maxsize == 2147483647sw32-bit machineCall_one_bits = '0xf'(>), 429496729e=k"-" + C-D.el922337203685477580/64 f 1844674407370955161 (N Jelseefail("How many *does* this have???"constant folding'-(y+2# i.e. -8/ 32 platforms. Should return int.lj1IsI}#ce%s" % (- - 1)), int)  .self.assertIsInstance(eval("%s" % (-sys.maxsize - 2)), int) A8if == 9223372036854775807:+/ def test_32_63_bit_values())- a = +4294967296 # 1 << 32P'_b = -'cN28147497671065S)48SdS,eX46116860184273879046f\0g`U`Y3 - 1hd4 5for variable in ..__code__.co_consts'ifNs not None)-l qB sequence_unpacking_errorJ# Verify 1 //9 with "or". SF bug #75781 i,j = (1, -1) or (-1, 1)CEqual(i jJFnone_assignmentstmts = [v='Xo = 0',+__builtins__.>(): pass^Rclass 1(a,),p`lrange(10k f(-!Rimpora 2x a sfrom x 'd" yIm]   += "\n"4=Raises(SyntaxE, compile, A, 'tmp', 'single'K'Sexec'n Puccee# / B?os, Z?bar>_.path%__future__ nested_scopes, generator@(A&\nB)C,D4sysPstdinAderr?outy5(6\nstdout)', ! 'from sys import (stdin, stderr,\nstdout,)', 9\;C?out9&sa as si1outo1erre,H I ][fail = [s'0os,  ), (sys"4(os#$1if .lower().endswith('pyc'+" =3F[:-14a open(%, 'r') as fRfcontentwf.read(QampleE = [['x = 5'],   ['', """if True:\n pass\n"""], h['rclass Tob 3bad  qnvalidS{('1\n2'%)[W2a = 13\nb/874Pdel xT?l y1f()\ng()-# blah\n8?xy ; px = 5 # G \nL6\n' particularly_evil_undecodab@7elf~# Issue 24022 srsb'0000\x00\n "\nu\x9e\n'5with temp 0.TeqaryDirectory() as tmpdafn = os.path.join($, "bad.pyfopen(fn, "wb"W*fpU+fp.write(src res = script_helper.run_python_until_end(fn)[0](b"Non-UTF-8", res.erryet_moreOstilf#25388y""#{v#\xfd\n"|_helper.run_ python_until_end(fn)[0] self.assertIn(b"Non-UTF-8", res.err) .@support.cTAonlydef test_compiler_recursion_limit(f!):-x# Expected is sys.get:() * the scaling factorI in symtable.c (currently 3)&AWe er to fail *atZ"at, because we up some ofGtack depth;1 in suite code7 SoVQcheck*and 75% of that9 XXX (ncoghlan): duplicat tP hereKxa littl ugly. Perhaps it should bAosedwC5...,_=31usuccess4Gint(Ec* 0.75R <*`prefix|gpeated6/;b_ok = +R + re,9 * :._single(N,+obrokenb _details = "C({!r} + * {})".format(=u,Q Qwith Raises(R}Error, msg= Nt@ "a", "()"/.b ?[0] 3*a"~ Z_null_terminSTBourc 4-4 internally, but bytes-lik+objects are accepted, which c5Fnot Y0Regex(Value@"canDcontain "("123\x00wp GevalEzAmemoryview(bO), "4 = Bo[1:-1]H `Equal((^G), 2q?4")nUO$23$n3a# Also]a when  ) 3exec() doTqation step ) self.assertEqual(eval(memoryview(b"1234")[1:-1]), 23) namespace = dict(JexecHax = 123L%, ?7 $['x'], 12) def check_constant(=, func, expected):.Afor ,1 in&.__code__.coFs.2if repr(6B) ==\.UbreakrJelseR.fail("unable to find`ant %r5%r"GY4% ()%# Merging ees is not a strict requirement )the Python# semantics, it's a more an impl9ation detail.7@support.cpLQ_onlytest_merge~Aants# Issue #25843: compile() must >which arek;# and have same type.M#Q uns = {}_@K = "f1, f2 = lambda: %r, B" % T,F8KJ, nsf1 = ns['f1']{o2pUIs(f1, h4 [ +_?/bf1()),,5Y cFNoneY"0 .! ob'abc'E #Z# Note: "..." emits "LOAD_CONST Ellipsis",;vwhereas=& BfGLOBALCBq}G"..`Q0d%*Z4P# {0}`convertedafrozenset({0}) bypeephole# optimizer P x: x.4{0}8$* *True(f1(0X?don-2buta differtype.  def check_different_constants( 11, W2): yns = {} exec("f1, f2 = lambda: %r, L" % [Y, ns)Kf1 = ns['f1'][2 self.assertIsNot(f1.__code__ k7NotEqual:@$ ant11f ,2,2,repr(f1()), o/1)727E2)) Rf0, 0.0b*+0.0, -.p(0,), (4^'a', b'a'(._1,# ) cannot be used becauselu-0j) is3`# '(-0vut when is evaluated to 0j: we loose the sign.O /Oj2Xj.3`7hU'2j' X2 0{0}IcconverIaant frozenset({0}) byYpeephole.# optimizer p x: x in {0}u&.0"|- , )2,7.0}9@True&0 2zltest_path_like_objects(X# An implicit 4 for PyUnib@FSDe 6r() compile("42", FakePath("@_|{"), "single"stack_overflowbpo-31113: S+ +k a long sequence of # %lex statementsif a: b\n" * 20, "", " class TestExpressionSize(unit.!CCaselP# The(BestsQ thatu Q size2de #ys within reasonable bounds (see! issue #21523 for an example # dysfunction).N = 100 def check_staize(self, code):&KTo assert thae alleged = size is not O(N), w@h< it( sm@rsn log(N0if isinstance(W, str& = compil'"", "single")Amax_= math.ceil( 1lenj@.co_Z&)):.LessEqual-X$, b)atest_andYS~"x and " * !|N + "x"P/orO/orNOand_R/x Xchained_oarison<bif_elsWPif x 2Z_binop+Pe@ = "f(x):\n"r+= " 6x\n(& G>) class TestSSizeStability(unit. 4Cas0# C"t repeating certain snippets doesn't increase the # beyond w6"a D requires.0 ,2, async_=Fal EhCile_'(i$qns = {}`script"Aunc(`"" + i 7#if$NR G B"B, "< Gexec^z@, nsreturn ns['wA']._"__b$ [0Ti in range(2, 5)]0if 3Aset(Rz)) != 1import dis, io< ouwio.StringIO(dis.dis(1), file=out2*q.fail("s diverge with # of consecutiveY6s: }R"%s\nB" % out.getvalue(6^=_ifLQu-m Aa$ """  self.check_staize(snippet) $def test_if_else(5!): .e = """Fif x(a$nelif y&b&.se$c$~try_except_bar/tr X 1qualified ImportError J& I$d>/asL^ as e tfinally% ` &Owith. x'Ohilew4J4?forIfor x in H&?forFoI7_break_continuC Oif zLn ,bKu2e  aelse: a(b$5"""self.check_staize(snippet) (&def test_for_break_continue_inside_try_finally_block(Y)R8 = ~for x in y./trNif z/oelif u:=c nfcTRt'mTL$oexceptud}t'MTdOwith9P/ cdreturn)M(1x p H pf test_return_inside_finally_block(self): snippet = """6try't#Z'Nif zAireturnFOelse1a,.check_staCize(!) 8def test_xoexcept@YOwith4/ c`async_4 4o x as $!, \l_=True?forfor x in^_G^db:{ for_break_continue/ $ bF6 nelif u6=; W ':uq 1)& if __name__ == "__main__"@unit.() from test import sup syslog =. _module(" ") #skip if no>2ed / unittest # XXX(nnorwitz): This n sucks. I don't know of a platform independent way # to verify that the messages were really logged. # The only purpose of tSe code does crash or leak. class Test(.Case): def_openlog(self): C.'python')!# Issue #6697.G.assertRaises(Uni!Enjrror, ^, '\uD800')(7.!('b from &>LOG_ERR, NeLd_closee!}@ etlogmask$s!5.\DEBUGLOlog_J8SMASK(OINFOGOupto7OUPTOG y_noargsM%( if __name__ == "__main__"Fp() """ Q suite for socketserver.!fcontextlib$io $os eselectUignal\tempfilehreading .Pqreap_children, tp s,xbose ;).requires("network") TEST_STR = b"hello world\n" HOST =. HAVE_UNIX_SOCKETS = hasattr(Q, "AF#4") zb_unix_!5s =.}Unless([,'lT Unix"')wFORKINGbos, "f ;_ in J&, q6,as+_alarm(n"""Call . when it exists (i.e.on Windows).&ifjb1, 'G'c%_0(n)HRemember,"l  ()avoid interferenc ith mock__3 = select.seleQpass P oDatagr3 g _ @contextlib. qmanager* simple_subprocess(testcaseK"""Tests that a custom child 4 is not waited(Issue 1540386)"""pid = os.fork((1if 2= 0P# Don't r7an exception; it would be caught by the harness.qLos._exit(72r6tryjyield None1hgfinall:pid2, statuspid(pid, 0mS.assertEqual% 2,( t72 << 8jB) dbSocketP(unitk.CC all@  s.6setUp(self#signal_alarm(60) # Kill deadlocks after 60 second{L.port_see0mX@elf.P_fileA"[]BtearDown 0Did*Qreap_Rren()]{`for fn' 'os.remove(f:1 OS K #  yh[:] = pickaddr,i'to5sroto ==.AF_INETyrY(HOST # XXX: We na way to tell AF its own nam8B`# like0`vides 6==0-Vdir =|fn = temp0.mk (prefix='unix_.', dir=dirDA ^}.append"fnxRmake_z, svrcls, hdlrbZm"My(*$[handle_e, request, client_l;ess=A0s.close_5()  praise  class MyHandler(hdlrbase):#'Qdef h#[(self"pline = .rfile.read)()K-&w&`write(()if verbose: print("creating server"U:try"a = MyS-f(addr,< except PermissionError as eT'# Issue 29184: cannot bind() a Unix socket on Android.skipTest('CCe (%s, %s): %s' %@9(svrcls, &e)iassertEqual(._1Cess,t.@.get Wname(Mcreturn,@reap_thsBrun_b#$, S, testfunc?29HmakeEP.pick. ess_family),~  (# We had the OS m a port, so pullArealhess out ofy#" y;rADDR =""QCLASS#BBt = Qing.T(fA='%sding' % (starget=_forever # Short poll interval to & finish quickly3 # Time between requests is s\ enough that we won't wake# up spuriously tony timesskwargs={'_v':0.01}vt.daemon = True # In case this Qtion `dwt.startVr runningpfor i iWWnge(3:0Kdclient", i0O j^1wai.shutdownXt.joi+g_close/ ,-1<(noif HAVE_FORKING and isinstanceForkingMixIn[# bpo-31151: Checkv3 {s untilall children completed%DFals.active_>Sdone"stream_examine(self, proto, addr): s = socket.((.SOCK_STREAM)5.connect(Nsendall(TEST74 buf = data = receive(s, 100%Rwhile%and b'\n' not in bufL #u+velf.assertEqual(buf, s.close() ;def dgram_examineW/8DGRVif HAVE_UNIX_x@ETS % =!AF$ as.bindP.pick)` s.%to10test_TCPServerSrun_s .6,0StreamRequestHandler;{s3E]hreading ?5@requires_forkingH<Fwith simple_subprocess. gK '? Sunix_: BUnix} =|.p/T  Fw   'aeamServer,  socketserver.StreamRequestHandler, = self.s7_examine) 2def test_UDPS_(-!):TR.run_~(6 0oDatagr}d2Threading?]@requires_forkingzFwith simple_subprocess gKASunix_= DUnixu! ?.tz hHx   9`Aap_tsshutdown# Issue #2302: ') should always succeed in maA1 anbi# other zq leave ouever()..class MyV#TC!bBpassLB .N es = []Pfor irange(20C/(HOST, 0), My)K3t =Bing./("&dname='WBNing'Gtarget=s.e(kwargs={'poll_interval':0.01}) !t.daemon = True # In case this function raises.=hreads.append((t, s)`@for R in t+:@v.start(3s.shutdownL8joi2Kerver_close() def test_tcps bind_leak(self)# Issue #22435: the 4 socket wouldn't be gPd if Q()/liste# failedI# Create many\ s SwhichJQ will<, to seefaresult#oFD exhauslVi range(1024>Pwith .assertR(OverflowError37 Q.TCPSW((HOST, -1),/ JStreamRequestHandlercontext_manager03 asBEpass^Equal(-1,6.c.fileno()) class yTest(unit.CCase0"""W that s normal excepas from(h_1 to _er(), andTxexitingDlike SystemExit,D KeyboardInterrupt are nothed."""0arD!=support.unlink(lTESTFNRsync_dABaseR+BValur.check_f(Q=-r?notv:elf\9-c(\False?ingT?ing#?|('@requires_forking= F46# ! self.check_result(handled=False) def c%cself, +!):%)with open(test.support.TESTFN) as log/3expected = 'H|r called\n' + 'Errorl* wH .assertEqual(log.read(), e) class BaseZTestServer(sockets B.TCP__init__(mVsception##ex5 = super().N(HOST, 0), Bad)0U.create_connec{._addressEpassM:try._request(|ofinall3sWclose1Owait_donz=de#, p, clientQ_, 'a'Vmwrite(@73+ "CR2[X0k$`raise .} (' }' Th"?ing  &aMixIn,Y 9, *pos, **kw$B.)D = tfX.Even 1Lshutdown]x 4ZH0.se?2#(pif HAVE_FORKING)OFork $U SW rQ(unitCCase:|_basics} oStream ?] X3T.wfile = s' /_4)no6.? ACi[/(/addCleanup(=_L-d.(5._family, +.SOCK_STREAM IPPROTO_TCP) withW s: s.connect(server._address)-.handle_request( lf.assertIsInstanceU wfile, io.BufferedIOBase?YEqual:_?Cno, ~!) def test_writz6lf)# Test that .') sends data immediately, and/qit doese:# not truncate@when interrupted by a Unix signal?pthread_kill =.support.get_attribu98, '3'qclass Hr(socket#rStreamR">19(se-.sent1 = B!b'JB6\n'B# Should b-tgwithout iring flushZDzreceivedr".XOline=big_chunk = b'\0' *{SOCK_MAX_SIZEx| 2y d.ATCPSo((HOST, 0),AuaddCleanupSH_cloA|"= ding.Even_ r(um, frame&X9.seJporiginaB2al.Pal.SIGUSR1,oF7GpAresponseENone  Rmain_}'z/id+qrun_cliO.{<P_famiJ.buSTREAM,I$IPPROTO_TCP ' s, s.make('rb') as *er4-nonlocal X # =xv s7rdall(b'E[+_AaderSJ(100`# The 1 sh]0nowaPblockFAin a() syscall.o# But in theory, it cO ge Sothers#2en retried. So keep3theAua loop, incase an earlix happens toPdelivO_ at aGinconvenient momkent. while True:+pthread_kill(main_, signal.SIGUSR1)>if interrupted.wait(timeout=float(1))y}]breakYnonlocal received2#p = len(0er.E()) 0background = Qing.T(target=run_client9v.start(server.handle_reques ;Ijoin:lf.assertEqual(Kcsent1,sponse1)q 7#re%, b'write data\n'5l:; O@2, test.support.SOCK_MAX_SIZE|@  - 100) class MiscTestCase(unit{"):1def0_alW'lfv# objects defined in the module should be_B%__Bpexpecte@%[]qfor nam2dir(socketczaif not.Kswith('_')-Bmod_ = getatt],Id5%if/Da, '__m__', None) == ''.append(x%seDCoun.J$, JshutdownD_called_if_verify`false(t4# Issue #26309: BaseSP f even if*# nP is FqZ^y_ B.TCP4 Y#, 2", _address?Clreturn0 }$q o`.6ZI+= 1[_?<rP)D = MS(HOST, 0), ]rStreamReHsr# =/.6RTt_familyTgSTREAME.connect=ys.close  Rae', _~._rp if __ __"__main__": uni ttest.main() # Run the _capi module 2s (1for& Python/C API): by defn, #se are all functionsYexports whose name begins with 'k_'. from colleD im: OrderedDict $os dpickleerandomsubproces8(sy dconfig8textwrapvhreadin!%im[1uni\ 0sup.!MISSING_C_DOCSTRINGS..script_helper<assert_p_failure, ok try: 8g_posixexcept IlRError0 ) = None # Skip this.0 ifmKisn't available. m#= .,_3%('# ')jWere we compiled --5-pydebug orE#define Py_DEBUG?  = hasattr(sys, 'gettotalrefcountiA defb(self) """some doc"""Lpreturn % class InstanceMethod:Fid =#.i#m#A(id)M3x0 ()wCAPITest(.qCase): __[nst =( /.^Equal(id(R0), _.id().ATrue*.Q() is:5c9nst6.__doc__,J TED `ibute = "(7 9.9,8Raises(AttrfP, set@X0, "-"[no_FatalN_infinite_loopuSuppressCrashRe(J0 p t.Popen([sys.executq, "-c",4'%K/;'6L .c_no_current_tO()']vstdout=4_.PIPE9pEqual(_Cvcapi.noJ ._ __, Nonep4?GtextJ_empty B3&no" "Th has no .,NA_s3with_invalid7($module, /, boo)\n" %3an - H ?.__DI2 2F ---Y  jAalsooUp8H "~!a VI!z"sig)") D self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None) V.Gtextr%_,[`"($module, /, sig)") "}!and_extra_newlines.Xzu\nThis  has a valid# and some U U%")O6,parameter2@def r_c_typematrix_multiplication(%):FM = .matmulType!vm1 = M(+m2R ~m1 @ m2, ("Q", m1, m2)G64646 42l1lE'm1leo = m1uo @= m2 oOiP4P P@ return_nullout_error# Issue #23571: A func- must not M` NULL Iout setting anyZ!# bif Py_DEBUGs)pcode = wrap.dedent("""<'fimport !Afrom +0sup3MG .SuppressCrashRe2(0!U6'""%rc, out,!2 = _python_failure('-c',  NRegex(err.replace(b'\r', b'')aw br'Fatal PwVor: a"ed'k O` br'T X/\n? br'SystemE: -Current thread.*:5 File .*", line 6 in ') Uelse:with self.assertRaises(SystemError) as cm7;_testcapi.return_null_QPout_e<({2hegex(str(cm.exception),4 'jO.* '<ed NULL setting an 1') H@def _saresult)# Issue #23571: A func must not L2 a Nz{if Py_DEBUGc code = textwrap.dedent("""<'uimport  !Afrom +0sup3C. .SuppressCrashRe2( 4|$G #:"""rc, out,2 = _python_failure('-c',  =qerr.replace(b'\r', b''w br'Fatal PwVor: aOed a b br'/\n br'Value.$The above  was the direct cause!of9`follow[U:$: H?C#Current thread.*H File .*, line 6 in @def _,_bad_arg($!):6q3Raises(AttributeError, @af, NoneL%MN5Mclass BadMq@ areturnR8:!9' =( ?Typ\N*/, P5% O" TestPendingCalls(unit.qCase): p*c*q_submit}g, l, n-&Wback(0#this function can be interrupted by thread switching so let's C#use an atomic operaU%@l.ap(kfor i in range(;time.sleep(random.()*0.02) #0.01 secs on average^CR#try 't until successful.7@relyTvregular to flush queue if we arw/un[while True'if_2Bing_( <obreak;-)wa+, context =S#now, stick around/l[0] has grown %108@counM%0;len(l) != nbusy loop is whereR`expectc %to_#run our s. Note thata only 1Kn th0mai baif Fald support.verbose;:  print("(%i)"%(len(l),),))for i in range(1000)Kya = i*i:if context and not.event.is_set(O8IinuePcount += 1self.assertTrue(' < )0,+"timeout waiting %i callbacks, got %i"%(n, )if Falsesupport.verbose_!) def test_pendings_threaded("):+#do every on a separate :[0n = 32 #total4s /es = []class foo(object):pas4=#+.lN.2 #submits perA!nTEn //.nTFinished = 0clock =fing.Lock( )E(H( O(target=.{Q cargs=(,h)-./)Twith SstartS"s(smd.l, n,, 6try tvkfinallL- kon4 C'=.c*.fU: ", h3&if' =s.]Do3non sy#again, just us*the mainZ, likely they will all be dispatc%at<#once. It is ok to asktoo many, because we loop until@findFlot.T(0can{interrupted` 2re are only&% slots, sop"go0wic_5at!v %64N'{%" 1SubpreterTest(unit.DCase(s5s(self):  import builtins r, w = os.pipe()code = """if 1:5MEsys,R, pickle) with open({:d}, "wb") as fQU? .dump(id(sys.modules), f, 0-""".format(wG_r, "rret = sup=.run_in_subinterp($Rself.assertEqual(ret, 0%#No(load(f), A" ) # Bug #6012 class Test(unittest.RCase)@def (_&capi.argparsing("Hello", "World"), 1}SkipitemsH#_s/ 1""")qIf this failed, you probably added a new " Din Python/getargs.ct neglected to update our poor friend) in the same file. (If so, sh on5!) >W4a few exceptions**,@func brute-forceUs allEprintable ASCII*** characters (32126 inclusive'%s,Mchecking4)see that PyArg_ParseTupleAndKeywords() return consistentMerrors both whe  is attempfPbe us"nd*Fit ifaped. 'e  doesn't exist, we'll get one of twospecific messages (,1for,:x); if itkLp we *won't*t0]&--either noxfor som@o7#weN%e "3 no"L&onLA and*aWere's a mismatch,+#8K&s. ** So0C haval funny semanticsRvit woul) be difficultcqaccommocthem her90Sinhese areJpwell-es3ish;properly  ~ ()5canI*Qaway &_ ehem--this really try|_ecapi.parseT_and_(", ,rYz$, 6BP_not_ped = Falsrexcept SystemENas ex#"aw 1 (impossible)(str(e) == sAType , # m 0optional_] = "|" += +% 0: '{}'". (   Gamessag"item_parity: K"detected mismatch between convertsimoCPH3h ({}),D {},5 {} Qc, i,a3ped)1self.assertIs(;#, 11def.L^# Test handl% helper itO uRaises(/, FQ (),xf42, []1sBValu&t5l'', 42tssertRaises("ValueError, _testcapi.parse_tuple_and_keywords, (), {}, '', [''] * 42)1self.assertRaises({DQ42]) w@def _bad_use(!):# Test handling invalid format and 7 in7pPyArg_P%T$CAndK"( oSystemn3$1,p1||Os?a']}W% 2OO, 'bW`'a': 1v/$$^1: 2OV`V"gV|[zO positional_only/ =4((1, 2, 3O'9, '(30P36 Pwith N Regex(TypQ2 r'func takes at least 2  arguments \(1 given\)'O4,), {}, 'O|OO', ['', ca']) with self.assertRaisesRegex(TypeError,/6r'function takes at least 1 posi al arguments \(0 given\)'):Oparse((), {}, 'O|O-@1, 21a'a': 37/O$74exactly 21 /1,5|Q:%bSystem~ r'Empty parameter name af /\$Rm8$U  keywordwva]) class TestThreadState(unittest.qCase): )@support.reap_t3s@def 3!_sId# some extra >-);@s dr` via _MAcapi^bgarget(S!idB= []3callback5 9.append(ing.get_:())R. kea = b = time.sleep(17# Check our main0A is te list  3 K)s.^MaEqual(s.count=, 3d"Couldn't findQcorre"Dt3t =y(&=t.start(Zjoin(;`_++W4if {verbose*8rin#fo uin dir(YTzaif not4s!(' 1continue14*0sub("internal",]= |: $pPf" {J}", flush=True+ = getatt)  test() class PyMemDebugTests(unit#.pCase): 8PYTHONMALLOC = 'd3' # '0x04c06e0' or '04C06E0PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+' Gdef check(self, cod} with support.SuppressCrashRe(,out = assert_python_failure('-c'a,{0 =.)Hstderr = out.errrreturn 0.de('ascii', 'replace')_buffer_overflow=0'im _>Vcapi; m.pymemS&)'regex = (r" memory block at addz p={ptr}: API 'm'\n"L r" 16 bytes originally requested8@The )S] padCRat p-are FORBIDDENBYTE, as expected.YBtail \znot alldP \(0xa-f]{{2}}\):k0at [\+0: 0x78 \*_ OUCH;1;/fb/2//.*P~was made by c#a]+ to  malloc/re{ @DataGSp: cbqFatal P error: bad trailing/".format(ptr1.compile(<, flags=re.DOTALL3rRGa(out, 6 api_misuse1N('PID: Aated using API 'm', verified using API 'r'\n") regex =  .format(ptr=self.PTR_REGEX1passertR<R(out,?!) Wdef check_malloc_without_gil(?, code):.`out = .9( expected = ('Fatal Python error:qmemory uator called 'Jm'P holdthe GIL'4In(W, outtest_pymem # Debug hooks must raise a if PyMem_MS() is/# "B = 'import _Vcapi; .)2f oobject0N OPPb classaTests(PYTHONMALLOC>d0' @unit.skipUnless(sup.4, 'need pyF(')PO_ Py_DEBUG Default # " d*o%Pcompi1in Q mode QE if __name__ == "__main__"c3() ?4sys "R from%@ pw_module('pwd')hasattr(pwd, 'getpwall'), 'Does not have &()S wdJ(.0CashNq_valueszentries = pwd.a"for e in +2.Equal(len(e), 7P(e[0], e.pw.IsInstance(-_, str24e[1`opasswd0 b/d2d/uiauid, int3^g^ tance(e.pw_gid, int) self.assertEqual(e[4], e.pw_gecos/IsInstance(._, str3b5b/di- `?dir^6^_shell `.b #)# The following won't work, because of duplicate entriesEfor one uid= pwd.getpwuid`zuid), e# insteadthis collect all {and check afterwards (d in test_values_extended) ?def(!):$g 5 = Fall(!byname = {}<Rbyuidsif len(=) > 1000: # Huge passwd file (NIS?) -- skip &M. hTest('@is huge; MCped'EhDe iny.setdefault, []).append(>=uid=u <#whether thy returned by l#8@each is among those from6,[ if not e[0] orj== '+'9=continue #yD NISfU etc.-5In(y6namlL[]M L2uidKCuid]-lerrors$Raises(TypeE,,73f, 3.149?nam3 O, 4272all7# try to]b some 6!)s ,% ~(n, p, u, g, p, d, s) ufu[n] = u}l [un0all?Slist(Bv.keys()%Ui = 0U@fake = s[%i]# wh)3in _ Echarfakename)   for i in range(len(chars)): "1if [i] == 'z'$.%M 'A'G#]break,elcZcontinueC/serchr(ord[i]) + 1)L/elbnamei = =+ 1N?try@fake7` = all s[-i]Dexcept IndexErrorR# should never happen... if so, just forget itfd''.joi* Aself.assertRaises(Key, pwd.getpwnam, M)=!# In some cases, byuids isn't a complete list of-` users&th # system, so we try to pick a value not:g(via a perturbing# loop, say) uid() might still be ableifind datagF thaf# uid. Using .maxint may provoke the same@blemut hopefullyDit w} more repeatfailure.0xTuid =z6siz9cNotIn(/#*2uid9uid#-16 id because it has a special mean3hin manuid-related functions-CQbe oupRuid_t(] o2**128B!-;` if __ __"__main__"unittest.() """ Collect variou+Pforma#0 ab`Pythonhelp debuggiK B!s.Nfrom __future__ import print_{ Terrno $re 4sys traceback def nlize_text(0if w is Nonareturn&R= str?re.sub(r'\s+', ' ',VJA.strip() class $BInfoj__init__(a:.info = {}01add+`, key,'ue7 ifAlTrR VS("duplicate:p: %r" % l"ifi9ne: return if not isinstance(value, int):'+ ;str+/!# convert other objects like sys.flags to stringlA =) (.E9p()F! @ self.info[key] = 8tdef get_ s(*5"""w@Get %rmation as a key:M@ dicary wheredPs areUings.LX {K*@ for_,I@ in .items()} copy_attributes(P_add,, name_fmt, $@, *,cmatter=Nonex(rTe=5B(objY!, F$ifsCcontinue/% =! %&if1 isp V fo@ter(DC!(u MG'2mod_/6try0getx(2except AVErrorC* all_func 0 D8A5|  ollect_syA = (T{'_framework',1abi pi_versionbuiltin_module%s yteorderdont_write_bytecodeexecutabl Bfloa=repr_styCAhash1?heximplement0.inuimaxsizlmaxuniHpathM@plat Xrefixmthread + wiTJ+`sys, '2%s'<cr/androidapilevel',0, ' JswindowsI ) encoding $= sys.getfilesystemencoding() if hasattr(sys, '-eerrors'):26E = '%s/%s' % (,vI#(){nfo_add('_H4', !) |for name in ('stdin', 3out 8errstream = getE3if 'vis NonecontinueVg4, '!',J e5notc ta_ Y4 4%s.A6 # Were we compiled --with-pydebug or  #define Py_DEBUG?Q. =totalrefcount'%ifA@text@Yes  =() present)'w7els@/No?smissing?i(0', F ) def collect_platform(2Gtimport earch =.itecture '.join(filter(bool,  ^c N'-x%('-python_impl5tation',<. 0Q!(aliased=True)]olocale[ #, getpreferred^(Falswbuiltinsy"b.float_a __lormat__("" JodoubleK %L o"os'Bdef _,s, value0if  ups_follow_symlinksdHT 's#effective_idl*`return(sorted(func.__ __ ,< N)ibutes = ('_bytes_envir" 8"f HAcopy0, oos.%s', attributes, formatter= #_attr) call_func(info_add, 'os.cwd', os, 'get1 (ui1)a g00 Tuname 3def_groups(!): return ', '.join(map(str, +K&~5getR\P`if haso(Kglogin'6try" = os.get(except OSError:&# 1 fails with ". [Errno 25] Inappropriate ioctl0i#U device" on Travis CI'EpassJelseVQ("os.1", #scpu_countv 9tloadavg7r# Get environment variables: filter to list#not leak sensitive Y1ion(ENV_VARS = (FW"CC",YOMSPExDISPLAY&DISTUTILS_USE_SDKYLD_LIBRARY_PATHLHOMEMDRIV 9HLANG9d MACOSX_DEPLOYMENT_TARGET?MAKEFLAGSS SDK_TOOLS_BIN:XSHELLJTEMP)RM XMPDIR!USERPROFILWAYLAND_q@for `, valuHw.items(! =3g.upperBif (!4in 9' # Copy PYTHON* and LC_*-1or Mp.starts2(("<", "LC_")_ Visual Studio: VS140COMN ]^Q"VS")y2endw"D7"))x1b(a8q[%s]' %&Y <Xumask9'&(02os.$!", '%03o, |getrandom # PEP 524: Check if system u. is initialized[   &J (1.GRND_NONBLOCK. st= 'ready (initialized)' except BlockingIOError as exc:+6state = 'not seeded yet (%s)' %5 4 info_add('os.getrandom', I),/OS%# Python was compiled on a more recent Linux version`# than the curr-kernel: ignIv(ENOSYSD if.errno != .*.raise def collect_readline()82try gdmport ,#I'0qreturn (mformat_attr(s, valuekbf isinstance(W, int#'Y "%#x" %FfFelse/O~ibutes = (;"_READLINE_VERSION",oRUNTIM% {LIBRARYJAcopyv,]4, 'hf.%s', ]Bter= _)0if 0hasF(Y', s&#  ' has been advCto C53.7<doc = get'__doc__', ''if 'libedin{' in do(.plibraryS Dc ele5GNUra! @)T5gdbNi' subprocess f' =$.Popen(["gdb", "-nx-O/"]Jvstdout=y_.PIPE8?err80uni`al_newYfs=True`ion = .communicate()[0]:\;# Only keepD`first rCg `.split siFCgdb_*$', |tkinter _,,Bpass% 0$4'TKO5TCLZ\3, ' [02btcl = Er.Tcl()  patchlevel = tcl.call('info', '0') 0_add('tkinter.,,X) def collect_time(1Qadd):Vpimport  3nfoc@ime.!',  2())(attributes = (;'altzone',daylightX (Ttznam:Vcopy_k0, 'Hf.%s', &`if has(&, 'get_clock_'Afor Q in (Vperf_couk/3tD' Z(K+.X 1b%s)' %XSOABI>cprefixlvalue = .P_var(0if ^ == ' and not Vi}# skip 5%=0%'continueK = normalize_text(@[%s], ssl, 'ssl", RBter= \ \ocket@host(Cs# ', hostname) def collect_sqlite(info_add): try rimport *3 except IVError/qreturn ( attributes = ('version', 'N_)/Vcopy_4,}9v3.%s', ,H) Ezlib@(|$ZLIB_VERSIONuRUNTIME 0, ' _expat from xml.parsers :)UEXPAT, p1, ' decimal _,)__libmpdec?__'z4, '  testcapi-call_funcc, 'pymem.allocator', _]E_get!ksname'Qwith_pym8 UWITH_PYMALLOC'resourci,Plimitf[A for in dir(TA) ifp.starts('RLIMIT_')]t==X`key = <&ttW , 0@3value = wQ.getrKF(key(w%('*Q%s' %O!, G Ko_socke- 9# all check;like HAVE_SOCKET_CANX$0= [  9!if j)Z7, '@_sup9`YX5T $('IPV6_ENABLEDqN nc(info_add, 'test_support._is_gui_available', >, ' ) call_func(info_add,X`python@optimizedZ ) def collect_c_!):x im subprocessysconfig dCC = sR.get__var('CC'if not CCcbreturnG6tryAhlexe.@argsk.split(CC\except IVErrorL7#CC42.append('--versionjp.Popen(5, vstdout=9_.PIPE48err4oSTDOUT6 0unial_newlines=True0 = .communicate()[0]"ifFcode3U# CC  failed: ignore e`D@0ext8ovt"normalize_(8.", ! + = False"40 = B.add5for^Q in (3#os() should be the first, to checkgetrandom.Btatu/Lc2os,{builtins/>gdbnlocaleplatform@readosocketOqlitd?ssl-y 0?tim[Odate~tkinterI?zli OexpaodecimaNcapi`resourc'cc2# CBing from Ss2plast as&y have side effects.s@_PT ?S' e2E90ion6exc%0 = Yprint("ERROR: %'%X" % ({.__name__)>file=sys.stderr#traceback.o__exc(1 '# l.flush()hPdump_8>!, {CNonevtitle = "P debug information" print(title)"=" * len!) )infos = P.get_ "s(* = sorted(.items()"for key, value inI!s:\= .replace("\n", " "F)"%s: %s" % (Xm#) def main()j = PythonInfoerror = collecxAdump1if 7ZCEion failed: exit with3", file=sys.stderrhE/ (1if __name__ == "__2__"v C() # test set -- part 6, built-in types from).support im@run__locale ions.abctinspectFpick4 B4sys'Z@unitT.mock"weakref class TeTests(/bCase):Hq_truth_Kcs(selfXif None: . ('a is trstead of false'Iif 0906.8.:)''qO\'\'tYnot 1=1:5 in : 1>,'xx@{A)1}{\'x\': 1} f(): passMCSx = C&0if ffv:C:C:9sys<?sys>x<x: %2boolean_op1M0 ora@P QP1 and :els'UEVf U >-=N'comparison< 1 <= 1q01 > o> 0 !=Gint _ `0.0 < Xe!.0g!.0i !m9 Ofloaq if '' < 'a' <==Abc' db': pass else: self.fail('string comparisons Eed')5if None isS identity testNO1def_float_constructor(!):& .assertRaises(ValueError, ?7, '1?5\04_6zero_divisiontry: 5.0 / 0.09except ZeroD:S "J didn't rH5") l8K!%6J&F{ // 0_ // 0}%|2%{ numeric_types pif 0 !=P or 1 01.0 - F-1.0 <a('int/ v not equal`# callbuilt-in  without argument must return,if int()03Adoesy:|"if>.@=() B.1.9) == 1z1.1) and-E== - -2P A ound properly1!.0{-0*0z EHworkO/B_to_ Q((f, resultL?PE+(f.__format__('e')9y4w8v'%e' % hs# all 2 digit exponents, both~ y9tr# '%' Etingfor i in range(-99, 100):  test(float('1.5e'+str(i)), 0e{0:+03d}'.format  G # E some 3 digit exponents&self.assertEqual(nb100.__Ui__('e'xo+100')Cs'%e' % J:;41~ 1~1~:~ - +&')|?-10  ;2'%g0f #+.\1def| _nl_integers(# Ensure the first 256 / are sharedW0a =$b = 128*2if a is not b: sq.fail('\Vif 12 + 24 != 369oint op.P(-24)1?-122U(-12)c1f12 < 24,o-24 < # Test for a particular bug in multiplyxsize, yz38, 356, 4*!if(2*1*0!= * == 338912P!mul commutativity# And another.m = -sys.maqE - 1pdivisor1, 2, 4, 8, 16, 32j = m // 4Hdprod =I * j1if "J!= mV="%r * %r %rs%r" % (tA, j,JF, m)Eif type(h)5?into expected;Pto be, n~q# ChecklpunifiedZQegraltY,  .#%r) to be int, not %r" % (prod, type 5)))7 # Check for unified integral2*m = sys.maxsize:divisor in 1, 2, 4, 8, 16, 32:+j = m // 49+ 1!% =9* j!if@ is :intfjself.fail("expected;%r) to be,AL*x#assertIsInstance(x +.Eint,B'"(y6) should have return"vO-x -w-x?- 1x-!2,s x2x Ntry: 5 << -5except ValueError: pass Qlse: ,, 'int negative shift <<') 2g/>>g=$>>gdef test_floats()if 12.0 + 24.0 != 36.09F op'6 (-8)9-I:())s9vh! <21 < 4hostringialen('', bZ\'\')c"'a11}?\'a2Rbcdef767 <'xyz' + 'a ' G concatenation94'*3D0xyz]E`repetiB: *3E(0*'> *0*>@min(@'a' or maxcUmin/max OA!in' and 'b'cc!d'7./s.inq'x'*103mif '%s!'%xgJx+'!SnastyK matting bug') #extended slices for strings a = '0123456789' self.assertEqual(a[::], a)# 2], '02468'* 11::+_13579+ ::-1],'9876543210/Z_97531+ A3::-,) P-100:%. 5?-1]  .7;fdef test_type_function(!):"Raises(TypeError, :o, 1, 21 , 3, 4) iint__format__&0(i,o$spec, result# just make sure we have the unifiedL integerC%`(i) =='",9str,J'i.>i(J, 'd', '*+@, 'cM \0# sign and aligning arePerdep%nt/L0"-" B-1, -f637- 9;++;; ;v;t 7U# hex3, "x", "3">X7<4d29- -! 8x %F&KJE @--int('be', 16) ,be  'N,BE'-(P )Q-Ru# octaloQ65, "=101->?232'!-"B-"! test(-1234, "-o"2322") Stest(" " "-#-#"+E+"E#E# binaryP3, "b,11--;0011010010D(-#)(-Q)R R {8*S+S+S* S # alternate (#) formatting#P0, "#t['0b0']-11<-?-0b 5| "A#+#!+C 10+!60'A#012l10b0TUS,--1W;3='0ou/-#=?-0o 5! "`#+#!+C+!,44 # h20o01+H1012,--,7x", '0x7#-#?-0x 5! "`#+#!+C+O+0x66g"0x5.00+6,--,#56d.-M1e24Fv /]/XXM3#-#s?-0X 5! "`#+#!+CC?+0X<$/0X,--W5234d.-/1E/]/ test(123, ',', '123') test(-123, ' D1234 \1,234!5"-#D%56Fo23,456H&W'L7MO,567O)*# issue 5782, commas with no specifier type47a, '010:T00,00*@# UnAdA for integers$N0**100, 'd' + '0' * 1001,+0 97;e100') d # make sure these are errors&precision disallowedE self.assertRaises(ValueEF, 3 .__format__, "1.3"# sign not We?'c'`$)+c_z must be string`?TypFNone:# can't havean%),n]P&,P]##']&#]C# enpat only and float-}es work>E_# in ([chr(x)axrange(ord('a'), z')+1)] +L L ALZL)):L!if 'bcdoxXeEfFgGn%'4}a[0[^FJ 1J6O(-1)M ;mat convert  # "Bto a#`'i h*v [0, 1, -1,a }`5678902234 ] aEqual(Z(,F)G IE6902]J, "0<20", '123456000C') test(123456, "1<20", '15*5*5"0>j2000x515 15 *5 *5 /0=!55@run_with_locale('LC_NUMERIC', 'en_US.UTF8;@def _float__form?aself):[#,  support for : code 'n' 7!i in range(-10, 10X\Bx = l7890.0 * (16* i+.assertEqual(.string('%g', x, grouping=True),`mat(x,)[#?.10^r.10n')) '/in; integersV  L0, 3d{# move to the next9est/vx // 10rfmt = ">20n"/l<c^x,67 8 9 UE2en(@(0, V)), lx 300, II*Ir(2($(f_spec, result*= &f.3@)A@  }=>>(0.0, 'fc"0.'^#default is '=Rexcep?Pempty@mat _^X|C1, '1q@'0.0 ]for issue 3411# test(1.23, '1'Z.23') -! "!gC"D g 1.0, ' #, 1d-->+>+>>1.1234e20CL+200-G?E- f(0+')$% & ' ' @H& &?A, '+&1+1.% ?& '-# Python versions <= 3.0 switched from 'f' to 'g' formatting ,# values larger than 1e50. No longer./Cf = &90or fmt inre, 'F':&"# don't do a direct equality check, since on some>@plats only the first few digits of dtoa:will be reliablYresult = f.__`at__(fmtself.assertER(len(<_), 98. *[-7], '. \IU[:12], ('1!00R12339&')w/20,/20g ^e,\.e+KS1, '( c)QEQEQ(Q)<2]00e+2e-[ 00  Nomat code means use g, but must haveeecimal)# and a number aft2e d) . This is tricky, becausM# a totaly emptyspecifier thFelseWp# So, ja sign flage1,Q +167%$ J.L.N)P(R# 0 paddin234., '010f', '1234.0C') Qtest(, '011f',+2+0<V0W-X-Z-3- 6/12256.!348#1.p5') N# issue 5782, commas with no specifier type4!.2`@0,.2@0,00 1.,# 0 paddingWc LN!1, 1,w.-2-3-0[ \-/^/4-551_2,345"56363,123,4565754=%3,;+# % formattingB-1.0, '%C-100%> must be strNself.assertRaises(TypeError, 3.0.__F__, None;0Sotherv s shouldn't work on floats,# in particular intB($fo`_5([chr(x)x xrange(ord('a'), z')+1)] +L L ALZL)):L`if not5mat'eEfFgGn%'.wkDValu0, 0 VDH\H0I0h1e100,1%-K7 1ey+ormat, -1e-100, format_spec) # Alternate float(Eting% test(1.0, '.0e', '1e+00')"##.$1.0fFB. Q1, 'g</.1#/001.0%C>00%D#".## Issue 7094:;]5 (bified by #$E@ '1./00)#*)QR/' x#'O .1L&K% .1Jk#"F! .1P '100%$ E69022345.6, "0<20" $J, "1616*6*6"0>161616*6*6/0="66@def __errors(self):'b# int,, and string all share the same @mini-language parser.aCheck that we can't askO too many digits. This is`probably a CPythonAific. It tries to putWwidthF@intoBe long..assertRaises(ValueE,3 , @1'*1{i + 'd'BSimilar with}precisioni! .'coAnd may as well_ bothn!hsyMake sure commas arebllowedvarious typ(&defor code in 'xXobns',&M!inl_sizes(self):# self.assertGreater(object.__basicsize__, 0)4 tuple.__item23 def test_slot_wrapper_types(!):'IsInstance@init<".WJDescriptorTypeL?strK5l- inoG)PomethodR' () TMSZPJ RI) H0(42D IdJstr.join, Plist./ndG))''rBuiltin+[]B:dict__['from_bytes']RClass%[QONGV__newD0 c MappingProxyTests(unit.CCasem*p*$ = ?Aype ?constructor @userM(iBpassP = {'x': 1, 'y': 2}s#QEquals.9( 4), >5 = x=1, y=2uc*collections.ChainMap(C}, {y-pRaises(0qError, '?, 1<q("a", "3/")H[H<2"]) dl a attrs = set(dir(self.mappingproxy({}))) - "object())) 5assertEqual(attrs, {")'__contains__',getitemOiter?lenMcopyb=getqs>keyXvalue1}) def test_getA!):qview = " W'a': 'A', 'b ?B'}RH`['a'],4)b)/B')Raises(KeyError, ] .___, 'xxx=2O'a')vIsNone(.W X*Q, 42) i|missingmclass dict! #__!!__D[, key(,return ".`=%s" %,#{8O(x=1/ D0['x1 0['y''Z/=yx\ .y+ .True('x' ingUFalse('y&LY`customR % G{D if == 'magic'LOelse6 .ZK $%0(('3',) H,G >500O8 '$';K; $;s< %=> &?D/}"" e"v2c, default=Gqm E'FT%r' %Tcustom = customdict({'key': 'value'}) view = self.mappingproxy(custom)"assertTrue(R@ in B'omagic') False('xxx( `Equal(p[~], 'getitem=Raises(KeyError,3.__;A__, |=tQtuplez), ('iter',)14len/?500).copy(), ' '. 2get~2?get e7d7default=Noneues 02key/ .0 1') def test_chainmap(!):d1 = {'x': 1}22 = collections.CZMap(d1, d2~6H*. Ay z& ['x'], 1'y'+z )bsorted1x', 'y'2" = (`IsNot( /,  IsInstance-b@b(:.p/')+y+n,zK .0()) ('1 'y', 2) LKJ AC1 |ontainsXdict.fromO'abc!zaT %b%! *.keys = view.kseys() values = view.Eitem self.assertEqual(list(keys), []e)m+z *mapping['key'] = 'Q'v7^(b,A)]) def test_len(!):for expected in range(6"&data = dict.from('abcde'[:@5j 0en(J%),s21 = 9mRproxy6+$ 0en(@ ]3iterators = ('x', 'y'V(1, 2t = tuple(zip", 0))Aict(G. 4set /.)_()), 68p9)~Lcopyzoriginal = {1': 27, b2': 51 q3': 93}WQwn O Ptype(%!),F &., o&1'%70 G+O, 70r +27) class CCreationTests(unit.bCase): 2PMeta(( __init__(cls, name, base ws, **kw2super().: 5@staticmethodvnew__(mvvreturn }Apreparen?y)`ns["y"71.update(kw2"ns*_m_basicCUypes.*F("C"] @C.__O__, *+(object,new_class_subclass(self): C = types.new_c#"C", (int,)))8.assertTrue(issub0C, int)) -def test_Q\_metayqMeta = W <settings = {":e0": &, "z": 2}/# We do this twice to make sure the pd in dict isn't mutatedIPfor i$wrange(2%) + str(i), (), 8<rtIsInstance(C,+Equal(C.y, 1%Oz, 2exec_body{func(ns ns["x"] = 0< , d)'%Ox, 0H! FBB _keywordJ#Test that #5 ar}t%e Hk_ (name, bases, ns, **kw}return +%kw reA 5X",# object)- O(= _, x=0=r4("Xiq {}, {"x": 0}S~default /o }, NoneK __z__, "C"* +(SS'`_with_6X=!s=  [kwds=?z=2< =^ UpGMmro_entrF1 A:C?$__JQies__1;1 return (A,) fc = C(D = types.new_class('D', (c,), {}+self.assertEqual(D.__bases__,f, Gorig1?c,)1 1mro[D, A, object)) def test_`_with_4entry_none(!):2 A: passBC=Aw_eid!, k."reA, c, B/ BZ h8 \BQerror0) ~5A 5 Raises(TypeE, g$ multipl1/A2B.B.A5fA1, A21B_5WB1, B_A(), B()%#, hU/_2/A3O, A3V6C C(@A3, @_# Many of the following`s are derived from_descr.pysprepareIW@q# Basic@mBmeta_QationOiexpected_ns = {}2 A(]4y__new__(*args, **kwargs): return type.__new__(*,6 6def __prepare.Zexpected_nsH1B =s s.rclass("B", (object,))tC,C,, {"metaHf": A})k# The most derived , of D is A rather tha ., ns, kwdsu0("D\B, C)[}self.assertIs(]AvA'Equal(len(C), 0test_bad_#s) must a mapping. BadMeta(L^@"emethod6h =(|ENone@Pwith <RaisesRegex(TypeError,/G3r'^'\.3\(\'G$`, not +$'A Foo= *Epassp# Also  the case in whichISaa <>a>Bar/()_resolve_bases(89A: BCg__mro_entries__d!, pkV@if A= M(q&A,Wc = C,%*s.g()), (6!c,8A":C::A >Oc, A%NA, c<Xx = (yCz = (A, C)  t = (A, C, B)  for bases in [x, y, z, t]:#+ self.assertIs(types.resolve_?("),M!) >def test_metaclass_derivation(T)g # issue1294232: correct <q calcul=_new_calls = [] # to check the order of __*_D%ls>a AMeta]9(mcls, nameK, ns04g.append('_'s&return super().i :@imethodprepare__"{}`_! B 7gc`nSUAns['_was_here'] = Truegz&nszBA = ^^("A", (), {" "":}OaEqual(B3, []/s.clear(BB#6oBwith f?', CCA # The most 'edt"isAl5e should've beenH/edX =X eY:Y:. AZAZAA<5i2Is(?, X8!Y! ZFcallableFT85`but noPdescendant of- = [] # to checks` order6 __* _ skprepare_Btrack __! 90Not'no0(mcw 4.append('A\')super().l -@emethodBname, bases4.&{}K# B( n_A!fA(_(_A/A/ { 1!,q6(A)[)= % TP !LBB!, type(B))   self.assertEqual(prepare_calls, ['BNotMeta', 'A 0]) > 1v.clear( `?new\-XwC = types.%lass("C", (A, B)4Is(,=/(C) 2 2 OB, A 2*# This is a TypeError, because of a metac3 conflict:Y$# $Dneither a sub3B, no1perTCWwith uRaises()nBDDuC,), {"!":5}) lE=E=}EF"F"object(), $F1F14C, 8.:t#  5int, XXC, int()\ types.new_c-lass("X", (int(), C)) def test_one_argument_type(self):&*expected_message = '( .__new__() takes exactly 3 Ps (1 given)'wQp# Only D0 itn can use the one-A form (#27157)4.assertIs(I(5), intgc! MEpassMWwith RRaises(TypeError) as cmB?M(5 Equal(str(cm.exception), F Na, meta/=M>N0 SimpleNamespaceTests(unitU.bCase):nconstructorhQns1 =+s.^(l?ns2&x=1, y=2.3.u**dict(5 v1, 2, 3V2**{1: 2}len(ns1.__f__), 0 /@vars0_), {}(W2WkW2W@'y':o'x': 1e3e3e{unboundw)},M ?ns1j mns2, {5 derlyingJ&.Oa=True, b=False5mapping = nsT0del(09+ B` d , 2(mK~attrgetsmLS, w=3Ovns.x, 1? ons.y, zal(ns.w, 3)  with self.assertRaises(AttributeError): /Qns.z def test_attrset(J.ns1 = types.SimpleNamespace()BQ?ns2&x=1, y=2, w=331.a = 'spam'J01.bhw2.z = 4(`2.thetCBNone Equal(ns1.__dict__, 2(a=wP, b='j)@2@ q, z=4, =")) \?del\N!@del +I0!2.IJ_52.y ivars(ns2)w=3, x=1Pns2.y]6KU+=E = 51-=51?G ,{}pOreprm   &`.x = ""_ @name)B"( ns( "{2$}(2)".format(=E 0O\O@_y=5`PeP\"CO1,  , t#4NotC2];%onesteda"6b=2+3v<|Q = 0hamQ?N-3W1R2 44i=ns3, ham='?'= ns2.spam, nsC3) self.assertEqual(vars(ns3), dict(x=ns1)1ns3.x.a, 1) Wdef test_recursive(f!):xns1 = types.SimpleNamespace(c='cookie't?ns20&3&8x=1)1.spam = ns12332 :"nsW,Vn(V-7_ Z (2Px-__reprname = "" "{} , _=...))".format(,=yII= I , O xa( , +"2)+21as_9 ''UEPwith MQRaises(TypeErrord/flen(ns;?Oiter@)u' in nso2ns[G]RMsubclassGo Spam(9 #BpassZ1t" =>ham=8, eggs=9!Isd(7!),7m(2+{'ham': 8, 'bS': 9}e_pickl=breakfast="h", lunch_for protocolbrange(p.HIGHEST_PROTOCOL + 16nE%{} s6try2ns_uBd = .dumps(ns, Iuexcept ^ as e[r& (p) from eroundtrip = pickle.loads(ns_pickled) self.assertEqual(ns, ns_roundtrip, pname7def test_fake_space_compare(O%):b.# Issue #24257: Incorrect use of PyObject_IsInstance() causedFSystemError.class FakeSimpleNameG(str!__.__ = types.4VoFalse(/_() ==|/))K?TruJ!JWwith Raises(Type <g5h=>S>! U CoroutineTests(unit$.CCase<wrong_args0 sas = [None, 1, o!5()]?Bfor *3 in suVRegex6,R3 'Rc.*expects a callable'H 7( Lnon_gen_value@EPKfoo(xreturn 'spam'-=:,'PAwait Ws0__a,__>( Uaw = S$/awqIs(aw, # decorate second timeE5fooF(foo@h_async_def # S thati p1s '=e def' s # out modification>1():W>foo_code =!._ )__ @flag|5foo!A.co_*N/d_7Efoo,@a;3Is(ed_foo.__code__, foo_code) @ro =%()def bar(): return U_coro#for _ in range(2):^bar = types.8utine(bare'" =l @self.assertIs( , 1 C*`Equal(#1.cr.co_flags ?.Slose(test_duck(dclass CoroLike>Csend4Y pass!_throw" cxD__await__H4% =@Gfoo(_Q+l ,()#./Sz z3gen!}?Geno__iter(,7nexBo}Lf s# Setup generator mock objectgen = unit.#.MagicMock(Dgen.; = lambdac:V.__name__ = 'gen'!} & Instance(genllections.abc.G >6Q )VJsp6gen`wrappeQ w.,~_WG8 4## G proxies 's completely (Z$,  /*co aself.assertIs Instance(wrapper, collections.abc.Awaitable) self.assertIs;.__qualname__, gen)> :u# Test AttributeErrorsV@for 4 in {'gi_running', Sframe 4cod yieldfrom',J8'crJ5cr_J4cr_J@cr_a(9'}:GWwith .zRaises()4xtgetattr[, $ s pass-through  = object(" F$-+:865 49> 9<:865 45Fk.close< _called_once_(Efsend(1D ,reset_mock^Dnext- \ __/__` /_`w(1, 2, 39e3li 0f 3 -`QexcepL propaga ZeD = E' ^side_effect = 4B:try> kj as ex= q2ex,nE?lse3cfail('{ did notRe an Gion'&invalid arg \ZT2Typ O.L` self.assertFalse(gen.throw.called) with self.a0Raises(TypeError):+2wrapper.close(1HCs&s5_send(q $p# Test that we do not double *@types.coroutinedef bar(): return85per"0Is(VBper,5%) 'weakrefs support cref = D.refK0Is(#$),j test_duck_functional_gen(class Generator """Emulates the following g1 (very clumsy):0 v7futuresult = yield fu t,5* 20 9"""s__init__,W~ y._i = 0AU fu a3tera\G \<4nex< .V(NoneGa?, vF:try8"if?= 0%)` v is !,._.% w1wrp StopItion(v * 2X/> W ofinall8k/I+= 1:_ntp, *excDN= 10uPif tpnOExit.*-tpz d=X  7foo Cw('spam'F1 = 3]IsInstance", _YWuYQasync[(Rawait~) +s90 = @`Equal(%$, + k2&20jexceptj as ex ex.args[0], 14R8lse< self.fail(''StopIteration was expected') def test_gen(self):gen_func(uyield 1,return (%2)fgen = K@types.coroutinesfoo(): V5genwrapper = $.assertIsInstance(.", m@_Gen2orWG @8.__await__(),:for name in ('__ __', '__qualgi_code',@'gi_running>gi_frame'v getattr(,)`i03gen.R1.cr.ET(next6O), 1^+.send(None), 1Wwith `RaisesRegex(|, 'spam( _" 7 X PExcepzO, 'hgthrow(- (7t# decorate second tim;Sfoo =Y$ Is/() ing_iterY / _ yC V)(X PaP&ocF m[1genc$ 7 +((CD(gen-1 ABC@Truef!.___.co_flags & insa.CO_ITERABLE_COROUTINEOFalsPGg/ 2M /Is pt|_objectl'6yield @types.coroutine @def 5():return gen() wrapper =4 self.assertIn('GeneratorW1', repr(@/))9iEqual((O, st6 True(set(di*.issuper{m'__await__', '__iter 3nexpcr_code#cr_running',Jqcr_fram&%gi1)gi=m 'sendE1losB throw'})) if __name__ ==rmain__'unittest.() import  # For scope )*ing. g = "Global variable" class DictComprehensionTest(S.bCase):8Z_basics(C4expected = {0: 10, 1: 11, 2: 12, 3: 13, 4: 14, 5: 15, 6: 16, 7: 17,l8: 18, 9: 19}"`actuall k: k + 10 for k in range(10)0uA$, ^30: b7, 8: vvP if k v_isolationkvLocal Vt ANone 22: 3 4 5 N6A89 k(( Kk, " , 18: 2, 1927: 3, 28936: 4, 37  381 3945: 5, 46789Z54: 6 552 5678963: 7, 645 662 6789!72"7345L 762 77!7981: 9, 8234L 852 8678?9: r _ ,0v *7 * X eq_from_g  3: None, 4: None, 5: / 6$ 7 8 9 }8actual = {g for g in range(10).self.assertEqual(?, expected)Y +g, "Global variable") 0B9: 1, 18: 2, 1927: 3, 28936: 4, 37K 381 3945: 5, 46789o54: 6,L 552 5678963: 7, 645L 662 678972: 8, 7345L 762 778981: 9, 8234L 852 8678F9: 9 Ag: v8v8K0v *V + Zdef test_gv_visibility(C!):&V|K0: 'O', 1@D2*/ 3@4*@6@7@8*/ 9 Ak: gk +zB _local`v = "L%WB  ( >B ) > ) > )'> ) Pk(B -v,illegal_assignmentWwith [RaisesRegex(SyntaxError, "can't J"compile("{x: y@y, x ((1, 2), (3, 4))} = 5", "<\/>"+X"exec) co.mpile("{x: y for y, x in ((1, 2), (3, 4))} += 5", "", "exec") if __name__ == "__main__":9@unitI.() """Sort performance b See &command line syntax.$tabulate()(`output Pmat. bP impf4sys Dtime drandomtmarshalutempfil-os td = @.get dir() def Qfloats(n)"""Return a list of n)2om ,[0, 1)."""/# Generating&s expensive, so this writes them out to a 3 inKa directory. If2( already exists, it just YH@backdshufflyaa bit.'fn = os.path.join(td, "rr%06d" % n)(2try!V fp5`pen(fn-"b"%except OSError03r =C.s!omSJresult = [rirange(n)]) :  w8b.dump(B, fp%fp.close(u = None1Winall(Vif fpos.unlink(fr Epass 5z as msgprint("can't1", 0:",/Felse9M4 = cXload([S2# S.#10iZ8$'k6[:iUBdel 9m.rever2.extend()RVassert lenp)srmPcflush(sys.stdout.%cdoit(L% t0@ime.p_countecL.sort/t1*P%6.2f(t1-t0), end=' ' rSr"""T y` speedPsQvarious sizes. %2The are 2**i4 (the argument,);Odisplays i,D , =In0arr%!of%point numbers with|Qollow!roperties:*T:Q dataR\pdescend:/a3sort: ascending, then 3 random exchanges +sort: ascendi.$10/ at@A end0%0\ly replace 1% of:lements w/TCvalu~Pmany duplicat=all equal!worst case Qario 1"""s = tuple([ch + "< " for ch in r"*\/3+%~=!"])8fmt = ("%2s %7s"7 %6s"*len(V)*`print(0% (("i", "2**i") +s)pio:cwn = 1 << i1L = floats(nf-j"%2d %7d" % (i, n),F=' '+fflush(doit(L) # *m.reverse,\,D/EO# DoX.!Qdummyu6(3)#i10om.Er&%2%L[i1], L[i2] =%1]3Rthe last 10 with2om if n >= 10`L[-10:[Aom()y ?10)$# W#atxn // 100L| B !ArA@lots:* 48del L[4:QL * (4z# Forcefto be distinct objects, else timings can beMartificially low list(map(lambda x: --x, L(cd /. Again,: abs, [-0.5] * nVThis one looks like [3, 2, 1, 013]. It was a badZ# an older impPationPquick, which usedgmedianJJbfirst,and middle eYAs as?Vpivot"qhalf = A2U8(%-g-1, -1;L.extend(*o"s, so th6pare comparable. gi6`# signantly fast6f we leav amFints, L)) doit(L) # !sort print() def main():"""Main program when invoked as a script. /One argument: tabulate&ingle row.)5Two)s*range (inclusive)1VExtra3 are used to sehe random generator1"""u# default) e rk1 = 15 a2 = 20 if sys.argv[1:]:9# osFpoin\VkOdI!])]Ha2a:# t-rspecifyD+f2f"j3j!$5rivL\pfrom re6ing }>xA for a inF{A69069 * x + hash(a*$."(x2r =(k1, k2+1)* !# Xde the end (r) if __name__ == '__2__' () import array unittest 5 A.sup(/_module, get_attributeFos, struct fcntl = 7!('') termios!9') b( , 'TIOCGPGRP') #Can't run s without this feature trytty = open("/dev/tty", "rb") except OSError1draise .SkipTest("UnableN Mb) else= # 0 if anotherpcess isYforeground}  .ioctl(tty, .0, ""?tty.close(srpgrp =.unpack("i", r)[0]i2if (0notp(os.get;B(), csid(0)Qr 1Nei1proQp norsession M""`attachoY4Adel "r,kD ptyIpNone class Ik%s(CCase^^_CselfB# Ifohas been pu_!to@backEnd,  returnsNF0ID instead oeeAJBp idg: idN e%#tt.W!8i )[.assertIn(rpgrp, id(s) def _check_ioctl_mutate_len(self, nbytes=None):48buf = array.U('i')intsize = buf.itemds = (os.getpgrp(), fsid(0)J# A fill value unlikely to be in `ids`Z+= -12345#if is not # Extend thefer so that it8exactly `!` U longiJeL ([R] * (4C // 5l.assertEqual(dbuf) *2) # sanity Jelsepappend(Xwith open("/dev/tty", "rb") as ttyIr = fcntl.( (tty, termios.TIOCGPGRP,;6, 1hr5[0] Fr, 061In(DH, idItestD I\_1024N# Issue #9758: a )%bl,4of !?wouldn't be# copied back afterusystem call.- i N2048QTest a largerfer, just foorecordksigned_un code_paramMot p|0ais itP.Skip('pty module requiredmfd, sfd =S.Fpty(f+tr)ifSWINSZ < 0 t_winsz_opmaybe_neg =E<+se@ poRS& 0xf GY L:, = struct.unpack("i",AE+)*I"(),/2ourOj?HHHH",80,25,0,#6 # T bothpositive and potentially nega  5newF%, SJeP0fin os.close(mfd{s if __name__ == "__main__"B: unittest.main() PKi=n*filename_with_o.txtswP::9out9Ou /PKC~<C:@PK&s uimport% operator4sys pickle from Y 40supL class G 'Sequence using __getitem__' def __init__(self, seqn)?.! =7L:i7ureturn >4[i]I] "it protocol*Wi = 0g,4nex,"ifi >= len#): raise StopI1ionQvC!lf,[%i]U += 1Fv;g< defined Jb a gen^UYfor val iPyield$X L'Mis@ and?ter,zn ~E@Testpagation of excep sY?A9d3 // 0NEor m?)e5P]l# Helper to check uability_e q, itorgK8brange(5.HIGHEST_PROTOCOL + 192d =~e.dumps(cQ)'&it,zloads(d!.assertEqual(typeQ3), )4 list(it) it = pickle.loads(d) Itry:znext(it*except StopIteration; self.assertFalse(seq[1:]Lecontinue~4d =dumps(it, protoA&it)Equal(lis%, class EnumeTestCase(unittest.1, PD1): penum = >seq, res = 'abc', [(0,'a'), (1,'b r2,'c')]H@def m_basicfuncZ()`X0typ]0lf./`.seq))4Ae = C -_iter(e), eE %T W;res>(.__doc__ gcheck_! oTgetitemseqnZ G1T T[G('')^yRaises(9 , d^ xOator!II;0gen!or  \ i!Ig2j/Ig31nonn"blITypeErrorl7, X illformedd-Ndion_propag/ ZeroDivision!(EF argument(n :t) # no Js y 1B`wrong d (not j ,6 # X@2, 3too manyS@support.cpython_onlytuple_reuD'lfd # s an imple detail where tuple is reused  # whenever nothing else holds a reference to it8!self.assertEqual(len(set(map(id, list(enumerate(0@seq)", .1lf.VQ, min(1,V) class MyEnum!):qDpass#1Sub,TestCase(21): 6# =T?%_Empty8seq, res = '', []<?Big:  = range(10,20000,2)QlBzip(%"2), \Rsed(unittest., Pickle@def %b_simpl;=0" AL4__getitem__7, i7&if i < 5@return str(iraise StopIt1ion 3lena58for data in 'abc',s`5), tuo!e(!t)), A()(k1,17,5k 'hs)[::-1])r)ARs(TypeErrorOversed, {}3# don't allow keyword arguments[[], a=1)[k_optimizatio'lfxu8Utype( x)niter(x))xis('hello')e7(5)E< opor.length_hintsHrsrxF), 09SeqWithWeirdLenNcalled = False/__# if J ^G!j = Truj#r)10 ZeroDivision ( YKndexR?iG  8(s /, [, r) '!gc N B9 return index s = Seq()r = reversed(s!s. )def test_args(self):W .assertRaises(TypeError,[Y?elf/, [], 'extra')P@unit.skipUnless(hasattr(sys, 'getrefcount'), '. needs sys.2()'bug1229429# this bug was n.5 inA, it%in # PyObject_CallMethod, and7 _new calls that sometimes.F'f(lpEpass"Df.__a__ = oy=c =rSQfor i{ange(10s6try1s&(fIuexcept : 3>lse'Yfail("non-+Yable didn't rz&!"=Equal(rc,\i-Q_objm "# s must havqlen__()__getitemimplementedclass NoLen( jHc, i): 1Cnl =KC, nl~GetItem 2!giI-giBlocked w/^ ( be%neDb = bplpickler@data'abc', r5), tuple(enumerate(!$))#k1,17,5Ws.check_rh), list( [::-1]) EjStartTestCase("):basicfunctione O.seqQiter(e), e% W1), 6resK = lambdaHP, i: @i, s2=110seqn, [(11, 'ar(12, 'b 3, 'c')]o~ALonglf, i: enume&rate(i, start=sys.maxsize+1) seq, res = 'abc', [('y,'a'), q2,'b'),AE  ,3,'c')] if __name__ == "__main__":Iunittest.() """Test script for the gzip module.$ import @` from J 0sup".!`bigmem3T, _4GR$os tpathlib$io dstructaarray #= d._ (':') data1 = b""" int length=DEFAULTALLOC, err = Z_OK; PyObject *RetVal;flushmode,`FINISHunsigned long_total_out; @2r/* zlibQ.c --q-compatible / ression */ /* See http://www.P.org/O!winimage.com/zLibDllpWindowsW""" class UnseekableIO(io.BytesIO)=Ddef S(selfreturn False k.Mtell*aise io.UnedOperation;i;x, *argslB @Base(.CCaseK@file* GhTESTFN1tUp4q.unlink.L)<tearDown!?TGzip(BVwrite_and_read_bac,7, e==!b_R0= b( Awith.rAFile`, 'w'+f) as fW>al = f. X#.assertEqual(l,()r g f.C(), j2st_7U/b'c1 * 50Wa# Try ?Q and -!o.& !f. (oif hasattr(os, 'fsync'<1os."(f'o(v!f.close( # | multiple !f calls :]S_0ke_X(ab.Path'6ameQ BIsInstance(f.r{le(filename, 'a') as f: f.write(data1) with gzip.GzipFile(filenameFd = f.read(Dself.assertEqual(d, gG * 5l(IsInstance(f.mq, str) # The following test__xy methodsa that  acceptsBthe correspondFbytes-like object type*Sinput82andUA^Pten e!s G(xy) in all cases.?1defmemoryview()P_and_Pg_back(3}1B&0)kGm = $range(256)*?- .cast('B', shape=[8,8,4]TC x_array2V7Y..F('I'z48`incompatible_ b# Test@non-:/s raise TypeErrorl # Issue #21560: attempts toH(e }=should not affhe state of 8+[?'wb:,R%s(iG&''AK([Kc)fb r'-  D`# Try 46ing c?*501blocks = []SnE = 0&while True1Q!if d8Ubreak.append(d>o+= len r# Checkposition was updatedVctly (see if10791)j6 ztell(),  *b''.join()(@bigmemtest(size=_4G, memuse=1) def test_read_large(self, size):%)# Read chunk# over UINT_MAX should be supported, despite zlib'sLlimitation per low-level call(compressed = gzip.(data1, =f2 GzipFile(fileobj=io.BytesIO(>ed), mode='rb'E .assertEqual(f.'(!, !) Hio_on_closed_objectQ KTest that I/O oper Rs on ;  Ds raise an# ValueError, just like the corresponding funck_T.N WrPto a $,n it for @ing,^E it.*HwG(D,cname, 'rrobj = f. dEFals.2ss;?Tru:Wwith -Rt&s(i6LBfseek(0BGtell`# Open wGe(b'glflush(lappendD1# A21 topreviousb7ab') as f"f.c2 * 15WWW 2d, b*50) + S2*15)'_many_<# Bug #1074261 was triggered whenIcontainedD # e,bers. Creat$chAand verifyL7 itMVworksKowb', 9 7b'aii in range(0, 200rwF"ab"w # append  f.write(b'a') # Try reading the file with gzip.GzipFile(self.%name, "rb") as zg:;bcontents = b""zwhile 104cztxt =O.i(8192)>)]0+= 5 !aif notu: break#assertEqual(M , !C*201%def test_exclusive_IC)*A'xb'*f6data1 * 50VrV.fL?), i4pRaises(ExistsError iDbuffered_!erLT# Issue #7471: a u can be wrapped in a BMReader for# performance.i'::io.!(frj@line[  Rin r]/&%rs, 50 *a.split(keepends=True)vm( od z19!) @vary' lengths# P_PE = 0(BL = ?(D?A QL ando*\ != 01W(len(L) <=Bl8 = + 1) % 505 s&#s(' TU48s(1if L == []<AseekO<9,r?  Poldpof.tell(01%\12newkf.tell()   f.seek(oldpos) # negative  , if len(line1)>10:"&amount = 10 Oelse6 b >y2 = f.read(i)'self.assertEqual"[:01], H84newFposiidef test_"_whence(r).%fwrite(kQ# Try](;P=1), U cEwith gzip.GzipFile.filename) as fs4&10pU(10, th!yS<Gy, data1[20:30]) ;!, | _, 'w' or pos in range(0, 256, 16~c (b'GZ\n'2modWrSr@f.my@obj.f, 'rb'support.unlink"x&xk q16474841@for S('wb' DBTrue(hasattr(f, "7&")=04/ f.+!,  `paddedA_gete0!'b ?obj ZX Mmtim23456789QT'w', AW> f.i UJReadT F+1, ''+5IsNone(f/.-X $Ov5e. |J @metaT(self):  mtime = 123456789 with gzip.GzipFile(self.filename, 'w',BJ) as fWrite:IP .w{(data1)jMopena2rb'SJReadR# see RFC 1952: http://www.faqs.org/rfcs"V.htmltidBytes = f`.read(2)assertEqual(5, b'\x1f\x8#*: IDb cmb a1a 4`08') # deflate\_flags_7 bonly the FNAME %z is setuu 64 8, struct.pack('`s wereA0header ends hereA# Ra;than procese0ed 7`, let' ekoztrailerRseek(os.stat]).st_size - 8_crc3274PCRC325$unA [)1]@]-af\xd7d\x83'ic 8m#))pdef test__)q$# p supporhntext managementUtocolUHB"wb"rf0fb"xxx"?f =Q (rb/r.close(A try:  with f: Epassexcept ValueError0 ,:lse'self.fail("__enter__ on a closed file didn't raise an tUion"):try[gzip.GzipFile(nilename, "wb") as51/0[o ZeroDivision*?1/0 ydef test_zero_padded_)'f.write(data1 * 50) |# Pad thefeAopen.YaYq|b"\x00"sP rYd = f.read(assertEqual(d, , "Incorrect1 in" non_seekableuncompres=MSQbuf = UnG'IOOobj=buf, mode=W buf.getv7K *, 2zApeek`0 m&20VNRgsizes( wh;TruPfor n]range(5, 50, 10C+vyield nv`f.max__chunk = 33mn6 = <"stn#if s == b''Ybreak%le^)), sk2+= % TPP100), O /\,Zu) atextioh\lines# Issue #10791: TextIOWrapper7 ) s when wDing ..8 = .decode("ascii").split*(keepends=test_write()  with gzip.GzipFile(self.filename, 'r') as f: 19io.TextIOWrapper(f, encoding="ascii"=t=Eg assertEqual(t.readlines(), !) udef test_obj_from_fdopen)` # Issue #13781: Opening a for writfails when usar## o created 3os.z%).,fd = os.Bos.O_WRONLY |%O_CREAT)> Xrfd, "wb;x =f, mode="w:gOpassS; L hm|.close(?"r+&G g.,FREADk 5obj@"'wn_WRITEoao[xo<Raises(ValueError}| &z'A in "rb", E w:} B548n wa:xb"`if "x" vupport.unlinkY.* s QbytesD#5str1 = m,H:try" T8G.$e(Gexcept UnicodeE ]skipTest("Temporary  needs to be ASCII" h  f.e(data1 * 50Wrn self.assertEqual(f.read(), data1 * 50) 2# Sanity check that we are actually operating on the right file. H with gzip.GzipFile(str_%name, "rb") as f:~=self.asser 4 def test_decompress_limited(H)[E"""D%!edp buffershould be @1"""cbbomb =h(b'\0' * int(2e6), vlevel=9ULess(len(T ), io.DEFAULT_BUFFER_SIZE) |io.BytesIO: lhAobj=g- >A1), 3max[o = 1 +` d_m.raw.tell`,Dq"Excessive amount ofBwas 3ed"+Q# Tes/' shortcut functionsa@5 62forxAin [07&2]Z(Pargs ((1,), (6;9,)04Oc0, *M/ Ptype(3c!5VE_mode= U^` 1`qPbuf =~ Rbuf, wq`bf.writK [ buf.getvalue()W D# Roundtrip  NId_trunca%:! =A1*50;a# DropCRC (4 blA andV sizekU[:-8]gS)? Raises(EOFError, Np<eO6, 1@# In4lete 10-~v headerkirange(2, 10): 2 with gzip.GzipFile(fileobj=io.BytesIO(truncated[:i])) as f: self.assertRaises(EOFError, f.read, 1) 6def test__p_extra(E)\ # R data1an )a fieldLP!gz#= (b'\x1f\x8b\x08\x04\xb2\x17cQ\x02\xff'8<8p05\x00E#bI-.\x01*r2\xd1Mxe 00%')``YUbEqual(J(), b'Test'Rprepend_ezPSee issue #20875Aopen9. name, "wb"f.write(1MrM_buffer.raw._fp.() class O@Base -Qbinary_modes!uncompressed = R * 50# a O@ile_" ==$de_'C*, ih#a X URsC * 2% ZaExists56xb"support.unlink&R plpathlike_]2 = (ab.Path';>JM KHx -U * 51) def test_implicit_binary_modes(self): t# Test , , , (no "b" or "t" in string).E uncompressed = data1 * 50 #with gzip.open.filename, "w") as ff.write(`)SN/rbO@ile_" =$de(f.read()_-.assertEqual(C*, rhg%agP[ * 2)=$Raises(FileExistsError&x"support.unlink& xnj2def9Otext..Fde("ascii")2i_raw =9 .replace("\n", os.linesep|/wt}v  K %rlO agOad6c1objN Tbytes;str_;C F"p.open(io.BytesIO(compressed), "r") as f: self.assertEqual(f.read(), unAu_bytes);with gzip.open(io.B!ubvbtv*Qstr) def test_bad_params(2)E# Test invalid %eter combinations.Nw9CuRaises(TypeErrorZ/c{123.456JOValuK 5filename, "wbt"XAxXDrb", encoding="utf-8Bis="ignorehGnewline="\n"}non-defaults = data1.decode("ascii") * 502i_raw = .replace(P, os.;sepE rt/16f.write( g bry_" =&)Zj 21ileT 3;rawrB _e_handlerPU > >c1wb"foo\xffbar`U 3,) \HB explicit , (universalmode disabled)Rwith gzip.open(self.filename, "wt", newline="\n") as f: f.write(uncompressed)"with gzip.opbrbrbassertEqual(f.readhs(), [{]) def test_main(verbose=None)support.run_unit-(TestGzip, Open) if ____ == "_T2__"I9fTrue) im`.m # Skip s Ymultiprocessing wasn't built. \=.Q_module('_;-')^@sem_t implementation is brokenb a.synchronize') fromscript_helperuBort _python_ok contextlibitertoolsrloggingk .handlersabQueueH9oCq%sy thA]XT time(rweakrefdpickle~PingErrorconcurrent&rfuturesA.U._basS(;PENDING, RUNN CANCELLED, _AND_NOTIFIaFINISH r,KBExecutor)7PBPool9 .Cget_ rcreate_u(state=Pexcep, result Qf = F(M1f._E1 = 5f._K5 = X# =areturn f _FUTURE = #) . %&) ^ '2o ? ) EXCEPTION? 2;1=OS()) SUCCESSFULGq=42) INITIALIZER_STATUS = 'uninitialized'-mul(x, yRx * yNsleep_and_raise(t*."(t( $ Ea`('this&an %:Wprint(t, msg\%"Jsys.stdout.flush({#(xF~global CB = xTK3us(Q:62fail(log_X5if  is not None:  logger = ing.getL('concurrent.futures') 80er.addHandler(Queue Plog_q)3setLevel('CRITICALWpropagate = Falsex time.sleep(0.1) # let some be scheduled5raise ValueError('e in initializer') class MyObject(o!):Gdef my_method(selfEpass@EventfulGCObj(&? __q!__>S, ctxC mgget_context( .Manager(F{ .edq = mgr.p5() S__delgb9@.set1 make_dummy_#(_5freturn#BaseTestCase(unittest.?]QsetUp_thread_key = @support.ing_setup7PtearDownS @reap_children: %ecleanup(*ExecutorMixinworker_count = 5~e(_kwargs = {}  upU t1if hasattr w, "ctx"eC1 = Sa_type(,Bmax_!s=0 ,/p.)/*e(Belse`0C t_prime_81`.shutdwait=True *r = None8da.B() -%t1*ifC\verboK print("%.2fs" % dt, end=' assertLess(% 60, "synchronization issue:w lasted too long"s-x| ".A  E# Make sure that the @ is y to do  before running0c#s. This should reduc]e probability of @outshw}%s.N0= [..submit(? , 9TPfor _`Qrange.%)]6+f in futures:' f.result() class ThreadPoolMixin(Executor!):?e_type = futures.<6WpProcessXAForkN\A]ctx = "fork" def get_context(self1 if sys.platform == "win32"$7.skipTest("require unixAQtem")p-return super().[_Spawn>sV"tRservez=[vcreate_`ests(m, bases=(BaseuCase,), GA6s=(< J7 A)*)<Dastrip_S(name0if .endswith(('@', 'S$s'I.46U[:-5]n-elMC'oA4A*sel%for exe ins9 = ("%s%s"8% (`exe.__8X__), 5)<`cls = KT#, ) + (exe, F, {}8globals()[qu] = clsInitializ worker_count = 2LetUp;r INITIALIZER_STATUSu = 'uni%d'-bIPkwarg Vdict(1 r= *F0=(' 7d',ns)Vtest_6rI = [.submit(?v_status(v_tQrangeb.")]/,f,yassertEqual(), ) class Faili ngInitializerMixin(Executo ): worker_count = 2 def setUp(self+/if hasattrw, "ctx"!%&# Pass a queue to redirect the child's logging outputx>v.mp_contex4get.()1Blog_s!= 0B .Q5e_kwargs = dict(i== i_fail,t3O='.&,)BelseF# In a thread pool,2 shares our;Ysetup# (see _assert_d7ed(vl y = NoneH#">super().c)tPtest_<>^Bwith 'ValueError: eG in J'F:try|sfuture >.submit(~Rv_status;except Brokenib# Perhapsb` is al1y bB `Ipass>'!zRaises( 8{.result+# At some pointshould breakt1 = time. Twhile notN"._=(ifL - t1 > 5)$("Zl] after 5 s."<.sleep(0.01!# ... and from this ()guaranteed %kt_prime_1 OU-@jClib. qmanagerLRSW, msgNi6&lf _ Qyield\qY = []<;TruBIMq.append.nowait() |Message&R_.Empt2Bq Logs('concurrent.ts', 'CRITICAL') as cm0`4cm.output self.assertTrue(any(msg in line for in output), ! create_executor_tests(InitializerMixin)(~Failing/ class EXShutdownTest:@def m_run_after_s%()'..&)H!Raises(RuntimeError+ [_ubmit0 pow, 2, 5) ~interpre #  the atexit hook of worker threads and processesu0rc,, err = _python_ok('-c', """if 1K;from concurrent.futures import {je_type}r;Y-_sleep#Aest.h_h;_and_printE if __name__ == "__main__"context = '{ )}'M& if)?= "H&F &(5g#Nelse[Smulti4ing+Cget_ <7 = *(3D, mpi=?1t.s(, 1.0, "apple"w""".format($=F7.M=getattrp, "ctx"&))|!# s9s don't changeWv ]code, checkqP# std3manually.HFalse(errEqual(out.strip(), b0Od# mo@.registerWlast(9?try8id, Noney8xexcept LN2("r -e Pr- @ not context?: t = {executor_type}(5)+OelseAfrom multiprocessing import get_contextR( =*(3D, mpi=? .submit(id, 42).result(m""".format(i=self..__name__,3 =getattr(D, "ctx", ""))|# Errors in atexit hooks don't change the l $code, check# stderr manually..assertIn("Runtimez: cannot schedule new futures", err.dep(QEqual(out.strip(), b"rb -e1") def test__issue12364 )lafs = [cy.sleep, 0.1) for _=r)Q(50)]l9 Bwhutdown=f=&fs~:f% class ThreadPoolSIVTest(Mixin, EY&`, Base0CCaset_prime_ Kpass;ts_terminate4 mul, 21, 2z)O6, 7([3, 14)e1len?#._K), 39#.s_ t N Pt.joift_manager_gTDwith.(max_workers=5) as &A = eVi ist(e.map(abs, -5, 5)))^L [5, 4, 3, 2, 1, 02#4]r+=8?del,R/ =2=(3O[$Ddel P1 C,s_assigned%l  8', g_prefix='Speciald'l( = executor._threads del executor for t in /:7!self.assertRegex(t.name, r'^SpecialPool_[0-4]$')=t.join()mdef test_Hs_default(i)| = futures.TnE(max_workers=5|=.map(abs, range(-5, 5)(% =.5+# Ensure that our   is reasonably sane and unique whenFC# no4_prefix was supplied.2LEO-\d+  class ProcessPoolShutdownTest(t_prime_ Kpass"pies_terminate6S.submit(mul, 21, 2)O6, 7([3, 14)Equal(len._)r: = 2- !sqNpX.values(~%pcontext_manager_d{CEwith V as el.%vY_ist(e%),*= [5, 4, 3, 2, 1, 02#4]6F-?del:@l.Squeue4menhrC_$DI 6(BcallM )*r 7$Dv# Make iuall the resources were properly cleaned byc#:+WGK6:Tf creat?_D's(Gwt,  executor_mixins=(ProcessPoolForkM(, 3  =oserverC&QSpawn>)) class WaitTests: def test_first_completed(self):$future1 = ..submit(mul, 21, 2)323time.sleep, 1.5)ldone, not_ 2 = }us.wait(`+[CANCELLED_FUTURE,11 /2]return_when=aFIRST_COMPLETEDassertEqual(set([8P1]), /2Au_some_already&}finished, pending AND_NOTIFISUCCESSFUL@ z.])2 Cexceptionl"otlg_and_raiseq==337*0 3 EXCEPTIONq?), 3`divmod?, 09[ T Ps# s0 1CANCELLED_AND_NOTIFIED_FUTURE,  future1]), finished)3self.assertEqual(set([CANCELLc E2Epending) Edef test_first_exception_one_already_failed(m!):7T@1 = .executor.submit(time.sleep, 2n7#, # =us.wait(a.[EXCEPTION42/1]>return_when=s.FIRST_G B*q9~tolall_completWdivmod, 2, 0t21mul2#21W[SUCCESSFUL}oAND_NO kS12ALL_COMPLETED H9 '# '6)"?out|F6, 7xh:6: 6#1,^out=5/ZTT class ThPoolWaitTests(uMixin, `, Base&kCase):^_calls_race# Issue #14406: multi-t0ed 3` condiG  waiting on all  # futures.  event = threading.E%()"3def7_func():EAW.wait4 oldswitchinterval = sys.get4 s F1e-6:try~ fs = {self.executor.submit() for i in range(100)}(seFsfs, return_when=ALL_COMPLETEDkfinall 1) create__tests(WaitT ,0 mixins=(ProcessPoolForkM=C =oserverC&QSpawn>)lass AsCompleted# TODO(brian@sweetapp.com): Should have a  with a non-zero timeout.%&C_no_(51Nmul, 2, 21M23 a7, 6) Uc5Us.as_(.2[CANCELLED_AND_NOTIFIED_FUTUREEXCEPTION#SUCCESSFUL$,62])?.assertEqual(<&q%@'$].sleep, 2-k_S0"#orw7( ,"50'4(.1]t$Wout=0~ )C.add-cexcept2s.TRError<KFpass}\X90 B/])%2  `duplic%ss # Issue2 20367. Duplicate futures should not raise exceptions or give 5# d@responses.Issue #31641: acJ arbitrary iterabl41 = self.executor.submit(time.sleep, 2)jcompleted = [f for f inE.as_0(tools.repeat(F, 3)`]TassertEqual(len(Oa), 1) -def test_free_reference_yielded_h(P!):2## 314406: GeneratorUkeep Rs=to finishedr`s_list(F0() "_"range(8)4.append(create tate=CANCELLED_AND_NOTIFIEDBIFINISHED, result=42)R BwithRss.TimeoutErrorV: s ! , k[out=0IM;Ks.remove4(wr = weakref.ref)3del@&.IsNone(wr([0].set_A (""  i  #if,B!gcorrect__L_msg^L_FUTURE, PENDINGyGRUNN( SUCCESSFUL;]]4 j as cm%ustr(cm.5), '2 (of 4)4 unS') I_Ts(AsCQTests*class E #.shutdown() and context manager usage isQed byAS@]|pow, 2, 8y@4C256,. |_keyword1mul!y= self.a)ssertEqual(16, future.result()) def test_map(self):'.aGAlist6.executor.Hpow, range(10) ?)),D6 s?, chunksize=3,O_exception#YAi = 6divmod, [1, ], [2, 3, 0, 5])=>i.__next__(), (0, 1)/1 Raises(ZeroDivisionError, r btimeou~es = []6tryufor i in%Xn.sleepJ;![0?/6]2eWout=5Y.append(ieh2s.T. EpassJelsefail('expected M'p,p[None, 3], 1 shutdown_race_issue124560# I! # : /` condiD at J where trying to post a# sentinelthe call queue blocks (is full while processe5# have exited).g U0strDA] * .worker_count +&>(>@'.support.cpython_only]no_stale_referenceszLX6284: check that s don't unnearily hang ontow&# k my_object = MyO (R_collf= threading.Event0allback = weakref.ref(^, lambda obj: u1.se6# Deliberately discarl usubmit(f.my_method6delw@Uwait(&.0QUTrue(Jo "S!U not 8 within n#."bBmax_s_negativec for number in (0, -1): with self.assertRaisesRegex(ValueError,4? "max_workers must be greater "G{than 0"oexecutor_type(t=!) k def test_free_reference(D[,# Issue #14406: Result iterator should not keep an internalg%# _R to rCobjects.'pfor obj..map(make_dummy_9, range(10)owr = weakref.ref(obj)f"0delj sIsNone(wr()) class ThreadPoolEaVTest(xMixin, `, Base(CCaseymap_submits_lBout_Xing timeW_reduce__(selfZ _cz!UnN&u@r', OExit !~$&"! &+ %7& !n q %Bfrom}e import @ingEqmu !("# 'e"h=/Ati c#;, (.', xecutorDeadlockTestTIMEOUT = 15 6@amethodsleep_id, x, delay&(<x_Nfail_on_d#3, eW# If we did not recover before seconds, consider%he#_0 is$a  state and forcefully clean all itsGcomposants.uhandlerutempfil TefaryFil (mode="w+") as fWp.dump_traceback(n"=f{,f.seek(0tb = f.read,@or p(.es.values(3p.terminateI # This should be safe to c\^shutdown heregpossib"#s should have been broken.  executor.shutdown(wait=True)%"print(f"\nTraceback:\n {tb}", file=sys.__stderr__;self.fail(f"Elq deadloE!\nF1) ndef test_crash(>!):# extensive&uing forP caused by @es in a poolU.E_cases = [Check problem occurrwhile pickla task in?1the_handler thread&(id, (ErrorAtPRqe(),), 1ing@, "e#1 atR|Ie"),M/# ,unon workersIbxitAtU5B^ProcessPoole "exitq `a6bCdbbm!du&Rfunc Oion k o, (), ^a  (_bSystemExitZaraise_, (Runtime9),  crviresultz#return_instance, (Bexzyq)Yr D v /T nV _PS w eyR result_handsler") ] for func, args, error, name in crash_cases:4Ewith self.subTest(3)%)# The captured_stderr reduces the noism test reportpKt!@.sup".W(9executor =m_type(h3max_workers=2, mp_context=get (Fctx)_=dres = r.Bmit(s*t7[assertRaises(r>tryres.result(timeout=fTIMEOUT=except fu2s.T=E/r # If we did nocover before y seconds,# consider that?[0 isa deadlock stateP _fail_on_9(S.shutdown(wait=True) o@def _"[r # <pool calling >1 do:UcausejRif a  Qs aft$eEV.5. [/7 Y3>5 as' R M # Allow clean up f?_, delay=.1( BrokenProcessPool?f) create_x_I3s(ED7,;mixins=(~PForkM= =oserverC&QSpawn>)alass FU`s(Base CCase+OPdone_Pback_q_#.$f = Non Q5fn(&@DrnonlocaqM PC! =.UU(kif.add_8(fn 4set5.qEqual(5,_result) ! def test_done_callback_with_exception(self): '"u = None"W5fn()gfutureCJnonlocal 'PI(& =4[.;5() >Qf = F{&()J.add8(fn 7setE'*&')+.assertEqual((#6,),S.args!N xlcanceluBwas_?ledp+ Kk ff.;rTrue(f.\(_$ I mraisesD1ith.support.capd_stderr() as QBing_lFFals'/fn" dN$T(6 Y,#0 = =*'e Sdoh!'VK  u  &f,$result(5@ hy0 +EIn('!: ,}.getvalue!2already_successfu9?;+ M2 ?<5|M lfailed>L4PORUexception(Exception('test')) f.add_done_callback(fn self.assertEqual(CD,), 1Q_exce`q.args) ^@def n ]_already_cancelled(c!):46wasu = NoneU5fn(zgfuture>Bnonlocal KD# & =Q.5Qf = Fq(!cTrue(f<(e#D OLrepr4CaRegex(%PENDING_FUTURE),"'< at 0x[0-9a-f]+ state=pending>'qORUNNq1OrunnqCANCELLED.uAND_NOTIFIV EXCEPTION finished raised OSError  SUCCESSFUL/eturned int X  f1breate_(/f2**3* ,4, _7959FINISHED, h= e6@result=5S:{/f1%Af1._V', 0False(f2V2VT3S3S U4U4U  5c5cU6Ulf.assertEqu'al(f6._state, FINISHED) def test_cancelled(self):" .assertFalse(PENDING_FUTURE.9/))5ORUNN5True(CANCELLEDk 6AND_NOTIFICEXCEPTIONz7SUCCESSFUL8qOdonel4g0 ,1]> W1 Q2 LrunningO7R" 2  5YB ]5a6 desult_with_timeoutpRaises(futures.T1aError,X[ \rt#, p/=0bl$ l!C6pUQ}"OS cGoEqual(k>(L, 42w|successw# TODO(brian@sweetapp.com): This iming dependent.notification( # Wait until the main threadZ@wait[1for`D.sleep(1rf1.set_5( = create_M(=*I3t =ing.Thread(target=notification) t.start() self.assertEqual(f1.result(timeout=5), 42FDjoinEdef test_6_with_cancel(]%):l# TODO(brian@sweetapp.com): ThisH iming dependent.Cn(_ # Wait until the main threadZ@wait[1for`D.sleep(13f1.Bf1 = create_future(state=PENDINGC3t =Qing.T_(targ$rRaises(u1s.CuledError,  , J/t.Pexcep69 6 T5m= _FUTURE.w09o/RUNNINGo- cCANCELLEDsaAND_NOTIFI True(isinstQ(EXCEPTION"?0), !OS)~SUCCESSFULn S NoneD|success/B9vE!`_condik"+Af1._E = FINISHEDb%~3 = _(_On.Ty_all(g q&f1c@ @.support.reap_ s _ 26tryx<pun_unit(__name__Uofinall9uqchildre 4if @a == "_2__"zaB() #is a helper module aQed_imS The4mports this # module, and this^ tries to run various Python library functions in # their own thread, as a side effect of being imported. If: spawnedHread doesn't complete in TIMEOUT seconds "appearedhang" message # is "nd3the -global `errors` list. That remains emptyK0f (&only if) alletested4. q= 10 i6ingtempfile"os.path = [] # Tclass merelya!7its! Tevv}Qholdslock, so ifccalled by T#To do zBs it will bL waiting forg#'sG". Worker(tOQing.T ): def __init__(self,c, args(, C.9)P(G.=Q !]! =d 1runv N!(*<0) Bname[P# Bug 147376: TeAaryFile hung on Windows, starb$inE2.4.N3("th.J", lambda: !().close(), ()),The real causeb nt@.abs"()(i e -;", p, ('.',~"]:2tryCt = 9[!t.+(Sjoin(.is_alive(f.]2("%h  % Qgfinall del t # Test some Unicode : semantics # We doi many opera!on7`s otheca at!irPs can be used withtcharacters. , %@, tidshutiluEdata@unit` from .supportd (run_', rmtree, c ae_cwd,TESTFN_ENCODING, wUNICODE#ABLE, create__file) if notJsk's? H t0.en2(x2INGexcept (ESa, Type ;C# Eiqsystem _"is None, *%{#"be7 ed: Reraise unittest.SkipbTest("No Unicode filesystem semantics on this platform.") def remove_if_exists(filename): if os.path.exists(`n!%os.unlink> class F(unittest.4Casi# The 'do_' functions are the actual 90s. +y generally assum) # already c etc. aDo allZS we can given onTb singlPw[cshouldM`. RB_do_;a(self,2A)R.assertTrue(oc)V2 isx2 Vacces,_R_OK)6 0absxCC$>os.chmodv, 0o777Gtime"ONone! (1.@(),  G# Copy/rK{ ux6sam\ BwcopyishG- # S  appear in glob output0 vaY,==\.I)[0]2bas rlistdir0yH , 1 =e.splitn_T= @dir(E# Normaliz%# u+ strings, as round-trippingZ1via %OSt # may return a different (but equivalent) valueddata.nb("NFD" [8 f) for f6]g0In(=)(#ps that  , ,"on to anothe1j\A1 21# SD be ableV.- eik LJdAd?11)) # mustA2os.o + ".new"rFFals s/2)4  3P1 + 'o'<, filename2)# self.assertFalse(os.path.isfile(name1 + '.new'))=?Tru<F2)) 4hutil.copy]$, hP2 + "h"gos.unlink1& # remove using equiv .t# And a couple of 1Us, on7;ach6s+y NeexistsG 4 E 3Mo  p <&1)p# Note - due to the implementationl,it tries a re first. This only fail  Windows when onGdifferentg systems - and tJtest can't ensure thatBaSo we (`2 func, which is thGmost`likely bQ(1\ ;U b.>def _do_directory(Lp, make_q, chdir !):46if Edir(1%)grmtreeCZos.mk;6trylGwith change_cwd()cwd_result =0get4%*% Runicodedata.normalize("NFD", *o G UEqual1bas(,L?kfinallf[os.rm# The '_Y'Is 'entry points params' - iej atfFtop-level 'Kwould be if1yld take TD<_H#le~pK_if_create_empty_C$ }48c3\ 1STrue(not os.path.exists(filename))  # and again with os.open."4f =A,vO_CREATLos.close(fEtry:Ktself._do_singleS3kfinall7os.unlink1X# The 'test' functions are unit entry points,simply call ourJ_.Eeach of the A combinalwe wish to AM1def _: s().u'(TESTFN_UNICODE5if ENCODABLE is not NoneUe Y>*) directorie`# For ,'equivalent'# Make dirRencoded, ch0uni5eck+`# (or.//>5etc,ext = ".dir"b4do_ycV+ext,\w{P# Our y A that can't use a non-"@",*175) Smain(Drun_10(____) if p == "__62__"d0()  isa sample module$Qd forping doc:4. #6m*)is(4how, handles aV@no ##strings. class Foo(object):B# A :8."__init__@passest properties@bool mised by PEP 285 importQ from 0sup"*$osBoolTest(.DCaseEA_sub |&0 C(8except TypeError +/ls`fail("lq should4be Sable"YassertRaises(~, int.__new__, U3, 0< _print foCpen(~.*V, "w"QFalse, True,:=fo(#fo jrjEqual(fo.read(), '6\n'c)ose()   os.remove(support.TESTFN) def test_repr(self):.assertEqual(%False), ' /')/ 1Tru.- *eva1), a`3]A)),  /st$n.j0, ''M?intL$s0hIsNot((0q,O), 1S ' 1Ofloa&O, 0. ,4.?, 1Y+ Omath+/, $+\#-!L $+LBabs($P (0]+& #)- ?, -i ' '.~v ~EC, -2I_+2, 2I$3$2I 2T3 #w  h(SS ( S $#z 'z T ) V%l ( SNv%Equal(True*1c, 1)  self.assertEqual(False*1, 0%VIsNot%./) OoTrue/1sN$uL%% $M4 5(2@%2, , t%for b in m:"i"z0, 1, 2" b**i, int(b)**i.22Vbool(7'a  ye(a&b, u2a)&|) :(a|8|8^8^8aW  {:zz$ z+ dd z zz+ zz a) b: ):n#@` z:zni a) z:zn R(1==1p ""0,#/0D />1 /1> 0" /0!E!ux = [1]self.assertIs(x is x, True) self.assertIs$0not(False) *@1 in&N 0$Jr s 1 pM) 0)vx = {1: 2} e L/, L '!8def test_convert(\!):, Raises(TypeError, bool, 42_$D(10)vUY2Is(&%/-1&p "hello"Q"&R)B^keyword_argscHwith!hXRegexm'D argument'RDCx=10}_forma Equal("%d" %E_, "0"< ,w/"1+ xW,W G|hasattrB L%[], "appendU9Is(3`wobble3 callable &?len` +sisinstancu (~ 4|5i?inth4102 issubclas N(a/, [?int contain z%{}] &{1:1}, True) def test_string(self):.assertIs("xyz".endswith("z"), True)1x1OFals2 0123".isalnum(c I@#$%.`.?pha\.\ _digit]M%is-\ ._lower[0XYZ-[ oecimal^d/`numeric`/`  _space[O\xa0.Ou3000w XOtitlx+W ?upp)-[ .Sstart34g6boolean`Equal(p & 1, 1xNotIsInstance.`1$Is&[ |.|M^0.^fileclosed6try33 f = open(support.TESTFN, "w"* a"f.a#, #(A*kfinallos.remove)\types!#  are always true.7for t in [w, complex, dict, float, int, list, object,A set, str, tuple,{]s Is%(t;Tdef test_operator(self): import operator'.assertIs(.truth(0), False)01), Tru/Pnot_(.^/]contains([], e718n`lt(0, 0_@is_()Y 6jis_notqBr:3;def test_marshal3 t.loads(Qdumps) 2@opickle1for proto in range(".HIGHEST_PROTOCOL + 1= 8 ,gIJ!) lvaluesp# Test specific backwards-compatible  F`TEqualB @col=}b"I01\n."DE0ED.E)2), b'\x80\x02\x88.'% L9L convert_to_boo,# Verify that TypeError occurs when bad things are returnedh(# from _a __(). This isn't really a jW, but?it's related.check = lambda o: {uRaises(,^6, oLclass Foo(object"Z x (W)*m?Barm def __bool__(self): return "Yes"check(Bar()) lass Baz(intKdef __boolkTjzj#Ls) must a c not an intIOSpam+1RRJEggsM?len-d  .assertRaises(ValueError, , kftest_from_bytesT0Is(0.- b'\x00'*8, 'big'), False)@ abcd', 'littleACTrue(sane_lenp# this j s our assumptions about _B%__=will start failing i} changesO!erN@for badval in ['illegal', -1, 1 << 32]cYAE w>tryV (A#except (Eion) as eqDYK \`>len_1%Equal(str(2), 4len9,_blocked1ePu = None<|5:Typ41^B %10J(BM~real_and_imagfj.3?, 1'Q?, 0'Is(type(P ),N,U,Q(S R}-W- oSmain(support.run_unit(BoolTest) Tname__ == "__>2__"I/P() # 4` case ethe os.poll() func@ imr4 os subproceserandom Telectthreading4ime   test.support iTmport TESTFN, run_unittest, reap_threads, cpython_only try: select.poll except AttributeError:'draise \.SkipTest("@ not defined") def find_y_matching(r, flag)Q = []nfor fd, mode ind"if&CBJ.append(fd)Pqreturn  class Poll%s(qCase): 7K_poll1(selfj# Basic functional -@ of 0q objectI/Create a bunch(ripe and9Bthat;works with them.FGp = s&()NUM_PIPES = 12xMSG = b" This is an(.""_LEN = len(MSG5o6ersMwritr2w = {}V2w2riUange(T_Prd, w<os.pipe(p.register(rp.modify(C&oPOLLINC4wr,P*:OUT+Q r +wr>2w[rd] = wr`w2r[wr&rd3bufk-cwhile g Qy = p &_8/ = ) !if N qRuntime5P("no s Jing"$random.choice  .0os.G e(+?ead  = M&@_rd = /:ersbuf = os.0MSG '.assertEqual(obuf), 0' hos.close(r0) ;J rd |Ep.un 4$ Cr6movx= , [MSG] * n3 5_s=as NVALinvalid fdescripto@FD, 7&FD!wp.register(FD)  r = p.poll()  self.assertEqual(r[0], (FD,ect.POLLNVAL)) 7f = open(TESTFN, 'w'Ufd = f.filenom4p =U p.register(fH&fd;wf.close}M_, (fd5os.unlink# type error for invalid argumentsDRaises(TypeET&, +6, p4 $una6# can't p non-exnt object/5Key_9, 3/CTest/Gcase0oll4class Nope:Fpass&jAlmost(Cdef =)Jreturn '&'U06,_(), 0CE# Another tD>r[ . This is copied from the/K`select_Pmodif0rto use O instead.<v_ 2(@ cm' in 0 1 2 3 4 5 6 7 8 9; do echoing...; sleep 11ne'@proc ub Qess.P} cmhell=True, stdout=s)EIPE,IMbufsize=j.__enter__H.addCleanup()Pxit__(ne<-C !Q9( p6IN gv@touty(0, 1000, 24816000) + (-1,)*10`fdlist3(ZlL if/-G= []continuecPflags,m9[0]"2if !&6:HUPM@lineP.read  0if ~ != b""D$afail(': pipe seems to be Xd, but still 'gs dataP /el.IN 1not:  bbreak self.assertEqual(line, b'testing...\n')8continueYelse:ic0fail('Unexpected return value from select.poll: %s' % fdlist) H@def _" 3(W)n# int overflow1hster =e(!P.regi*#(1uyj$Raises(ObuError, ? , 1 << 64Bx = 2 + 3if x != 5k,d must have occurred'[# Issues #15989, #17919iv, 0, -1C$Hmodify, 1%A@cpython_only W_c_limits__ capi import USHRT_MAX, IN U ]T~$D? + "cL.#C%EF@reap_threads!edT r, w = os.pipe/ddCleanup(os.close, r6%w%rfds = [].for i in range(10 dGdup(n&fds*w.append(C !fd:fds=E4fd,qgPOLLINBt = ~fT(target=J wt.start:trytime.sleep(0.5;# trigger uvarray reallocation. +4.un9 K $"w:OUTj0Runi;hfinall  # and mak e the call to poll() fromthread return os.write(w, b'spam')!t.join() @unittest.skipUnless(^qing, 'Tjing required for this 8_b@reap_:s[1def"__blocks_with_negative_ms(self):1\ imeout_ms in [None, -1000. 00.1 e]BF# Create two file descriptors. Twill be usedc unG.b insid ?r, w = os.pipe(@ster = selectR%P.regi.4(r,/cPOLLINV2 = Bing.(target=&Ns, args=(tv.,)Uo.start \KJ=0.1J.assertTrue(:is_alive()0# WL" s1 unXs and"Yends.!OFalsos.close(rMUw) 2 maDrun_(PollTests) if __name__ == '__72__'82() 8est import sup ._module("dbm.ndbm") #e if no72ed 14 os C|error class DbmTCase(G."):\setUp2T Nu.TESTFN'Dd = Q.openM.>C, 'c3rtearDow= asuffix'', '.pag2dir+b'junlink2 + R mst_key<REqual~!d._V), []_['a'] = 'b'\[b'bytesmb'data#'12345678910( '019237410982340912840198242> waIn('a';f.d#b$ IXq# get()nsetdefaulawork adict interfaces.get(b'a'), sb'b') self.assertIsNone(d.get(b'xxx').^Equal-, b'foo') kQwith ^pRaises(KeyError):*)!d[]? setdefaul D []1d.close() Idef test_empty_valu;if dbm.n library == 'Berkeley DB'skipTest(") doesn't distinguish the  ! ">Q"from2absent one"6d =Bopenfilename, 'c; keys(), []_!['u'] = ''Ib8 Q 4In(!,`d([24 ;[QmodesU@for  in ['r', 'rw:n']R:tryqfI8< except euMfailCcontext_manager8DIj as dbw@db["5 b b""r?r')rolist(db.bYK*b,cmj]btr(cm.Uion),,| "DBM object has already been #d">bytRcRQdb[b'T key \xbd@n( %TTrue(/db58  junicod with dbm.ndbm.open(self.filename, 'c') as db: db['Unicode key \U0001f40d'] = XvalueFPwith w|r|assertEqual(list(db.keys()), 0.enE()])SUTrue( @o in dbE#< a)],  C}2@unittest.skipUnless(support.TESTFN_NONASCII'requires OS ? of non-< Rings'@def x_nonascii_)$ =Z ~for suffix['', '.pag2dir6b']^7ddCleanupunlink, +^;J. Qb'key!b'"'cany(os.path.exists(c )'i %&.4], K) if __I__ == '__main__'A() # interactions between, float, Decimal and F*@ im1 UdrandomDmath 4sys operator from daSp2s D!fv#s #,F # Constants related to the hash6plementa!; (x) is based # on0Aredu rx modulJprime _PyHASH_MODULUS. 0ys.wa_info.B%us(=INF$inf class HashTest(Y.CCase Fpcheck_e_j@c, x, y&c!# ( both that xay are >Qtheir&es w1x),3?(y)*"got different hashes for {!r} and ".format(x, y)) self.assertEqual  def test_bools(+!):=.check_e:_hash(False, 0b (True, 1)j}integerm!# Ba that o values vK# exact Ni in range(-1000, Bi, float(iB/ D+F+# the currentis based on reduction modulo 2**n-1GsomeHn, so pay special atten=to numbers ofr'M;V.N A;10090n =>Ui - 16#pif n ==(E+n)<'ynyny3U-n, -i d,D(`+F+?D(-X-F- U r&#4domof various sizes:_3e =MR.rand*'30u'om&P-10**0t*U7!ainary_J #to corresponding FrasRDecimalsEare distinct butericallyr shouldt%'sai0.0, -0.0qf# zero:7D(0y)^/, *'3'YFinfinitieW nans  self.check_equal_hash(float('inf'), D 3) 6 -7 %) 9for _ in range(1000):^0x = dom.random() * math.exp(*200.0 - 1Jx, D.from_/x)6F6def test_complex(v##  numbers with zero imaginary part should  1 tod# the corresponding \values = [0.0, -1 0.40625, -5136.5,bf],k"(']tnl:0.0# &z;<,G(u)Ydecimalsr that D% instanceshave different representations&S# butas giveAsame.q'0', '-!0.!e1 000e-10']95=4s.* D(+0XrD('1.001]/02-b-c1d4S123e20230_230e15 0i16m$oV%Afrac&special case 2 where eithernumeratords2# opdenomin is a multiple of _PyHASH_MODULUS>passertE(\(F(1,3&))6INFCk-1, 3*yF-G7C0, 1F0i:_normalizATesta bug encountered while chang&Along.f # * # Given objects x and y, it should be possible for y's  # __hash__ method to return (x) in orderensure thatD*"==5y). ButCs not exactly equalO7theGresult of x.(): there's some internal normalizationFto make @ \@fitsa C long,/iD invalid value -1. ThiL= P mustareforePchangEe'of@Nuany x. class HalibutProxy:5defj(self) $r"'hK/')GAeq__E0, oLE == PUx = {,5()}x.assertE (len(x), 1) ComparisonTest(unittest.CCase_mixed_c6s&):#aed lis{distinct Bsvarious typesU#, float, Frac, DecimalN_=Us = [=('-inf'),D('-1e4250 j-1e3083F(-22, 7JZ-3.14**-2:0.0[1e-32JTrue&lF('1.2D3<1.4F(275807, 195025O 41421356237309504880168872O114243, 80782NF(473596569, 8461oK7e20D('infinity]i, firsthenumerate(4`second2(f[i+1:]l-*QLess(n", D /]4Greater(_f 2i 7*4lex # as withlex are special: I2ityn1ityeIalways succeed, butev-Jraise TypeError.z = 1.0 + 0jAw = sv + 2.7jsv 1,7, F(1), D1$Equal(z, v)   self.assertEqual(v, z) " for v in 2, 2.0, F(2), Dcomplex(2):19U#NoX_z, v)&~DLwLwR(1, 1191), ;, w6 op7operator.le, t g*gtKRaises(TypeErrorG., \7m if __name__ == '__main__'unittest.() import U fromc.mock #Tpatch0builtins"rltter class CPBteMez""" Trivial "@usedWGing E.>ar. """spam = 1 !_h $2 oVTestR(.CCasedef setUp(b5std/ =(C.1Pdict(O=int egg=str=#M6Me= )O# forces to bind  WQspace5c('', 0duB ~ A(+dEpassq(oB(list() ATruep.2use+ns7CFals8.5_(A())AM, B((1,)bglobal_m!es( # _ withIasortedN E o_'di')v [x+'('o xDdir(`) if x.starts(O]/st:O  n )akaksajadhak'), [],)a customizedce self.assertEqual(s completer.global_matches('CoM'), [(Ue('])*^o/egh 9egga# XXX: see issue5256~&$pdef test_attr@!):!<## with builtins namespace'66std fo'str.s: ${}('.format(x) for x in dir(str if x.starts_('s')tuple.foospameg' [Qexpected = sorted({'None.%s%s' % (x, '('  != '__doc__' else '' X&)}0AT.'), L-_M: Nha customizedIOe.sp ,/am> I?me.Pwmro(', ./0Me. 8 :._hFI ?m_=%HWZTrue($T?, x'Ini@e.__S__', t6@ew__62 p.object(, "me", pcreate= AUOme.mb 6 'z s('egg.s'),   ['egg.{}('.format(x) for x in dir(str) C if x.startswith('s')]) 6def test_excessive_getattr(self):&`# Ensure ) is invoked no more than once per HUibuteFclass FooY]calls = 0)@property-ba1.PI+= 1; return Non0f =(Jcompleter = rl$.C(dict(f=f)5{assertEqual(8 ('f.b', 0), ?ar'@f<, 1uncreated_dAAttrzss like J ies and slots should be d even when9# they haven't been } on an instancP!__x__ = ("bar",r_Foo()v uP@unit.mock.patch(' _readline_available', FalseB_ IB/\t< w. 4('a;=!1?as <Rs', 2=An)pOpassF>?$elOelif?xOelse}$tr}\try:'Gduplicate_globalsnamespace = {3' :J, # Keyword vs builtin B >''?4try': lambda9 lmemoryviewp1Cal ?on-DEllipsisN6N J} completer = rlcompleter.C (namespace) self.assertEqual(8 ('False', 0), BoIsNoneC 1)) # No duplicates0# S or colon added due to being a reserved keyword?/ '8_', 1);L4try}Otry:z@wN@open"bracket "(" because we overrode the built-in clas~?memoryview ;J Ellipsis(T:` if __-__ == '__main__':lunittest.() import dis "q from -bytecode_helper 6BTestCase  Tranforms(&1): 1def^`_unot()# UNARY_NOT POP_JUMP_IF_FALSE --> QTRUE'W>[VxSif not x2nUdel xF`TNotIn([5, '4 <m9)F elim_inversion_of_is_or_in\for line, cmp_op in ( ('&a is b', 'is7O',),'n'5/in'F+NF'N 0 = Bile('gsingle`dE, 'COMPARE_OP' fglobal_as_constanLOAD_GLOBAL Ua/True/"\CONST!`+f(1x =1&greturnPgP P;h;<mfunc, elemk1(f,), (g, True), (h, Falwse)): self.assertNotInBytecode(func, 'LOAD_GLOBAL'):7CONST', elem) =kdef f('Adding a docstr made this test fail in Py2.5.0'Qreturn Nonej30h_while_one(E# Skip over: RH trueconst POP_JUMP_IF_FALSE xxc 2o* 1 Epass;Elist1forQ(M', ''Q5& gABSOLUTE',V {@ mppack_un otBline('a, = a,N',),(b* b,ROT_TWO)3, c,5, c/0HRE Z p = compile('','singlewC 1'BUILD_TUPLEh:eUNPACK;:0fol_of_tuples Oants  = 1,2,3', (1, 2, 3)("a","b","c")* 'a.c'0@a,b,ZA, 1,a\ q), 3, 41  0E H;r# Long  should be ued too.,JQrepr(9(range(10000))),X# Onei2the@, on r  "UvalueQload_s = [instr J in dis.get_uctions(  1if 4.opname ==j]Equal(len(C), 2b# Bug 1053819: Tuple of constants misidentified when presentcith: 1# . opcode_with_arg 100 unary_ BUILD_TUPLE 1 8.JThe following would segfault upon compilation8def crater()5(~[&0, 1, 2, 3, 4, 5, 6, 7, 8, 9,.A],) test_folding_of_lists constants(selffor line, elem in (N## in/notE qLIST shbded to a tuple 'aJ[1,2,3]', (*))uC('a w["a","b","c"3p'a', 'b/c'9`in [No01, 7  7p): 9L0# ="e(['single')_.assertInByte@(, 'LOAD_CONST'</No?e'#/se"M/SE!frozenset%{%E}', (#({/}0{0 >:c/b'D@in { ) BQ<@{/ ? K2, 1D 6N?SET, # Ensure that the result actually works#;f(aqreturn _&5g51, 2, 3}  self.assertTrue(f(3)) < not f(4)) # gE gABdef test_folding_of_binops_on_constants(!):3for line, elem in ( ('a = 2+3+4', 9), # chained | ?@"@"*;o'@@@@'@?eck string opsC a="abc" + "def"', 'abcdefOCQ = 3*/81 # binary power?/12>?multiplyB@13//D3Cfloor divideF 4%E_odulo@2+3', 5 ?add=013-}=subtractB(12,13)[1]', 1 _subscp13 << 2@_lshifQ13 >>@ |@r@0& 7B@/an?! ^=/10>=/xo|== <code = compile('Svsingle'/.`InByte@(, 'LOAD_CONST'? <[PinstrVdis.get_quctionsH uaFalse(5 .opname.startswith('BINARY_'G# Verify that unables are skippeq'a=2+"bd257'b' large sequences do Fresult from5ingw"x"*10000 HeNotIn(l , 2.cos4 01<  ?Iposi1g :/ <Pinstrdis.get_quctions 9uaFalse(5.opname.startswith('U#')=# Check thatSworksmarshalingbnegzero(return -7Hg",bVerify unables are skipp", = P"abc"0abcUNEGATIVE'),+?('~1hINVERT/ Ncode = compile(line, '', 'single') self.assertInBytecode(, 'LOAD_CONST', elem<opname) m def test_elim_extra_return(!):&# RETURN {T NoneS --> 5_7f(xGKa% x'k(NofrIs = [instr for in dis.get_uctions(f> "if>.$R == '_VALUE']Equal(len(O), 1`jump_tobJUMP_FORWARD toNZcond, true_value, fals v-@ if AX else9 4ABSOLUTE592Safter1/Eliminate dead  : s immediately F can't be reachedJ!1,2#1:L% 1<22vwhile 14r / 3.f48Q5f6F'E4z6z2zn<# There should%RBthe Uloop.K\%K & en(returns),S 1) returns = [instr for in dis.get_uctions(f>E"if> .opname == 'RETURN_VALUE']{self.assertEqual(len(a), 2) +def test_make_fun_doesnt_bail(J!):.2'f(g()->1+1+Epass@% gdNotInBytecode(f, 'BINARY_ADD'constant_folding # Issue #11244: aggressive ; ;.Aexpr'3 * -5',- P2 * (,4)1(m3) * 4-1, 2, 35O1, -O2, -4L * 6llambda x: x in {-5) + (-1 - 6), (w *WNone}JoeI=  = compile(e, '', 'single'HL!N ~BaFalse(F).startswith('UN*')yDE,PUILD_D class TestBuglets(unit.kCase):bug_11510&edset optimizah@ wasm d  the tuple# unpacking?hich would fail if?hhad duplicatKelements so that1alengthunexpectedpx, y = {1, 1}+[!!Raises(ValueErrorPf() if __g __i"__main__"@() -BEGIN RSA PRIVATE KEY- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,2D5DD30B9D440DBB 01gIwpy3XxPGsY0PoK59vAxdLhkVj3odO0Z1ULamUzIte6ThKL1HqnZiUlXpYKfK XqHVVeQ1xouxiDRNFLJ4CqBG4HbRtqTkl+sfaNTVveL18lOOMAZy6W3dCGAnWOTZ Z0RJyZlQxxjNQLuko4tIvFkrShXIgdiVFjwAhRU0KTUb7UQ2xfFA9R0Kfde30pzz zSjb/OmYqAIhkdvafGXvJxzZAorQkU9akDh+uJ6cht5B/RGZsbKACYDSv2WSV5yW r+fKVYcTup33r0Jj8hAD6fVY15K8BJknpkF9HfSlZnmmr2WDaffLokOOnCV/I1ie WD7ENA7K//48km5D3Ogh2b2/0Iwuzjq8Mvd8aR39N9nINbGR+HNT85pawoo1S0W9 pQTU4XTmxfXjtR2287C6XZyQ/tBwvNDMFP!VhlxsGOdLYwoV5e/L1t1qIfkTlbuvd JaMzOhSSLjiC156IFoH7PTPe+g75hw2b32XJURFGlaYknHF7P4BmCiwXOQYo5CCo MQGGlw5qBCqODrIsc03wpL2jUzgvyPqLyaw395ITuSoGX+WO7vUQaGW0Tz/sOoTs 3pK+bTi2QmqZMe7xBOj07CYMMOo4QPrM6NpbObt+Jja2UXaxvKa9BwqCEQzA4pQZ 8ZHHfEWIaDffKTGkAlqm+S8qCtsrEZJhIn3aI/ikzK8v+YkWw6w+8t/tR1V8ET/s CoYGIR7I8WhdfKAwgx2QT5bt1jkYKJyKPm4Iacp2mNh9gNFVq+JSKF318e7BrR3+ wyqMkDxRYnov3ybtf6kiICxPREDqa6UG1xRq3SbWz6NnIF/1hoHs79YlSYbMfXNU ffIxBaXNCcH6jM9duP2YRnO29jLwfLM/mmokTBBjyOBaKZia9GPa4naXoATXW3z+ Xx4EKIUkKdb53kiV6NtEKMPialAnkeoHTEjyLPgaV8mCHLvGQbnxbYwvpPJH0e2f CWgiw6ci4ROOzcZ7HJHIDUprwK0xRKn43hoI44fivlSHOFX6da6o3wIqhEUqMKwL JQDS1GORRk1ndRXP+7Ub1dO+Vo/DqO1VcTr2o5RwZ1LWPnzLqbCG50mvTLH4djB+ +hf6vlmnFC30N3yUFXWE5vS10nJHYP88dD9CB2RsaWzpxD9Zxl+PKcRsppen6HyO u3b71a/TBOkJcI+lkOatEFvbuqzBAqhMceMctO+Dl55RFsbxfIw/IXZjdP0PYZ0C t20DrIdBsvl9F/mfYpmkV4DF7yci78DqnRBcxylVNF2vwX7o+2fq/TsEwsHn3KnT kvcF5Cq8Vr5C8ugWX8JfveNym0BjLu6Lr58qS4a6qCNGEGPFKyB+xkm4KEScbarQ aLbEbfulMM7q9//sEOOLexIx7mNoLd29Xzn5hsLCAZLWX6wMq6JVJ/zbBOAHDbBT yhi03yd5Kvw3swSt4QZj+uR3qTFwxkXUFiVvrSfxRZoyKsxsLr9Z7D8aoH9Rkb2L 6KjZ31nt9Drh7NJfh6ReANBW6INdDW0Y2mbzoDozLszAYjVfuUUEE76iJqXY0N4W kNr0OQQTUtDpVk0AZZZvy17xV+rkqGgwlOqTvHbwFYEQvgwVz4EKUw== -----END RSA PRIVATE KEY----- import errno from http import client import io import itertools import os import array import socket6threading unittest TestCase = .p from (0supmP her4os.path.dirname(__file__) # Self-signed cert  for 'localhost' CERT_4 = SPjoin(g`, 'keyB_.pem'[ @fakeZ^a 2bsp.python!B.net _odotnet}2 # constantsBsing chunked encoP_starp ( 'HTTP/1.1 200 OK\r\n'Transfer-EC:U%)a hello worl3 7d! 8 xand now'22 asomethompletely differenHt\r\n' ) chunked_expected = b'hello world! and now for something completely different' N_extension = ";foo=bar" last_"07da"0" + ,N2+ "5trailersHX-Dummy: foo`2: bar"nC HOST = support.& class FakeSocket: def __init__(self, text, file3 =io.BytesIO, host=None, [ )JNif isinstance(I7str"&! =h.encode("ascii")$.) & = #Adata'sendall_calle0ZQ_closZFalse!! =  ! = [nZ "A+= 1=4@ += X@makeYmode, bufsize q != 'r'&b'traise client.Uni mentedFileM# keep the" around so we can check how much was read from it@elf. ~ w8".4r #nerf (9ureturn @PN<q gFTrue;f 6Fpass#setsockopt(, level, optname, valueu?S EPip(&):_pipe_triggeP# Whe`() is ed with 7", eEPIPE..zngP "if J!inOSError(errno., "gotchaak]SNoEOF("""Like !tJs Assertion on EOF. @Thisu| below to test that http. doesn't try%UBmore^punderlyGn it should1""":GCn=-1)&= .,!if =k[ !('}tr triedP past'Z/line(self, length=None): data = io.BytesIO.readline(self, length)12if 4V= b''IPraise AssertionError('caller tried to a past EOF'Zareturn^ class FakeSocketHTTPConnecZ(client.:"""B subPWusingV; counts c[0() Qs""" def __init__S*argsk'.@ions = 0<uuper().D'example.comEafake_s_e0 = Melf._create_r1 = ? -@"""C the number of timeis invokedt8E+= 1s) , *pos, **kwO!(* 3):HeaderTests(4Castest_auto_h)s}qs# Some  are added 5@mati(y, but should not b'%by # .request() ifmyQexplicitly set.[ingBuffer(list.` $.U = {}@aappendo, itemD kv)tem.split(b':J if3(kv) > 1  #c is a 'Key: Value'oy string7lcKey = kv[0].decode('ascii').lowo:.setdefault(P6, 0f4[))] '.CDfor r in True, False)0{''Content-', 'HostAccept-encodingz? = 1(8<.' =5d('blah7!_b? =  f0bodT'spam'f G,ifg X$E[]Bptr(len() P'POST~@/', 1,s9BaaEqual(JC], 1c_!_0&):a2(LQCheck2st):  def __init__(self): Zlist.% $;.content_length = None+oaappendmo, itemsAkv =.split(b':', 1)Mif len(kv) > 1 and kv[0].lower() == b'-'Kkv[1].strip( # Here, we're testing that methods expeca body get aB  set to zero if the7is empty (either~f or ''bodies = (,a_with_= ('PUT', 'POSGATCHQ3for,nrtools.product([-;iesconn = client.HTTPConnon('example.com8.sock = FakeSocket)_buffer = CLPCheck5|2drequesQ, '/'y^CassertEqual(JN 0}, b'0',3t'Header- incorrect on {}'.forma )0For5#ses make su tais not{Ewhen#Jsqbecause it might "uned behaviour&th"# server.`85out!TA 'GEaCONNEC `DELETE@HEADpOPTIONS WTRACEj-4 in ~ <x:,Q__IQato '',P's considered!be "present but3#'A" ra'than "missing", soI[@woulI, evc don't .abNone)  conn._buffer = ContentLengthChecker() +2request(method, '/', ''*self.assertEqual(HOL~".c|!_l}}, b'0',3t'Header- incorrect on {}'.forma %) V# If the body is set, make suref!.?Bfor  in itertools.chains_without_d,0%):P = client.HTTPConnection('example.comnLsock = FakeSocket(None)u. .1Jdef test_puthI(4.{ %4put;'GET','/A#'-V', 42^KIn(b-q: 42', R@'FooH bar cRFoo: % [ Z0BarZw\tbaz\t \TBar: '^AuthorizahBearer mytokeno :+: 8BIter}A B})7 : pA\r\n\t BV ZRLatinF'-O\xFFt/!: ,IUtf8hoc3\x80l2k/o0C1-1rolnext\x85lines6): 3wEmbedded-Fold-Space is allowed@+: >#6Tab/\t4Tab\tallowed', conn._buffer) cputheader('Key Space', 'value'-self.assertIn(b-": +!, Pfe f-fb'Nonbreak\xa0Co 5woFw 5wdef test_ipv6host_!):$# Default % % on IPv6 transaction should be wrapped by [] ifMsit is a?uaddress #expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:85' \C b'Accept-Encoding: identityK'8w = client.sQConne'('qock = FakeSocket('R".s# k.request(U=)PTrue(A.data.startswith(/5)) ]Cq102A::] ETs$Gvmalformeds_coped_} (Issue 19996body = "Pp 200 OKp0Fir0val3: n aSecond"P rb`JresprResponsB )w.begin(=v`Equal(P5.ge"')9:jparse_all_octets( ^Ensure no)$idafield 5 as the Prd %E = ('#"!#$%&'*+-.^_`|~!ue # Special token characterF'VCHAR: ' + bytes(range(0x21, 0x7E + 1))'\ 'obs-textC 80C/FFC`fold: Ie 0ed  s\r\n' b'\tfolded with tab\r\n' b'Content-Length: 0% )Csock = FakeSocket(body resp = client.HTTPResponse(; )v.begin(self.assertEqual(O.getheader('), '0'@ Lmsg[:]:z"!#$%&'*+-.^_`|~"{_value ? ? vchar = ''.join(map(chr, range(0x21, 0x7E + 1)) `'VCHAR.c9 03?], 3IsNotNoneobs-text'EIn('#!, 6msgCfor ?in _=[R5]):VPTrue(%ed.starts*,(' 71 space', 8o3endm%def test_invalid_ s(JconndConnection('example.com4. '#putrequest('GET', '/') # http://tools.ietf.org/html/rfc7230#s-3.2.4, white2g is noMlonger allowed in e names)cases = (B(b'I*0Nam0b'V<V,1/n/1/n/ ./\t/-::/.+;]1/n/--')f1/n/h!name, value in cases: with self.subTest((name, value)).92assertRaisesRegex(V5Error, 'Invalid header'KOconn.put& } class TransferEncodingCCaseXexpected_body = b"It's just a flesh wound" def test_end|s_chunked(W = client.HTTPConnection('example.com')[4.sock = FakeSocket(b'$pputrequz'POST', '/%a._makeP(), eeb=True)c_, _, ._parse_wV.data3!)U `Equal(,V {xplicit_y3# e" z `A# this shouldn't actually be automatic-}d because the # *ing code hasly stated that i1tak,are of itI4r ${'=->A': 'Ced'}K#_,s/"NotIn('content-length', [k.lower() for k ins.keys()]V%[&],B sP, str>|AX. \0.dee('latin-1'),  User-specified TE, but `) does5ingw$Nz/={'Transfer-Encoding': 'gzip, chunked'}, e)#e_Z=True!body=self._make_5())E_, headers, 2 = . parse_request(conn.sock.data?,"assertNotIn('content-length', [k.lower() for k ins]IcEqual(['Transfer-,],H_'("),expected!) def testE!):}empty_lines(False, +/= = client.HTTPConnection('example.com'8u = FakeSocket(b'(B'POST', '/' = ) @&,Ct ]  p.W> \ 7E '3# CL] and  SHOULD not be sent 9thes# same  =#N*(Zc# Zero iterable shouldtreated like any other*he!4 $#(CUW#EI, b"0\r\n"9", |=xi ,P.spli? @Pidx, 8enumerate(sZ#ing handl Cs,/(ifHvidx % 2M(0yie,''B2S< lenO - 1?j + b' GOelse4 +q@f@s = VYA" =5[0]xU = {}n = 1 while n < len(lines) and[n]) > 0: key, val = 5[n].split(b':'), = key.decode('latin-1').strip(0headers[key] =f9un += 1 }return request, Y, b'\r\n'.joi[n + 1:])>def _parse_chunked(self, data) body = []ttrailers = {}Un = 02! =M6 !#  b9FTrueasize, F:n+2'r = int(2#160if < ==` Rbreak8-.assertEqualpd)3.append( Oy23 # we /should/ hit the end, but check agains!+ofKso we're not stuck in an infinite loop t;getImalformed fif n >XF I#b'&) class BasicTest(CCaseRtest_status_!k # 6b HTTP (xn@ = "#/1.1 200 OkUText"sock = FakeSocket(?resp = client.SResponse(; )g.begin NO.read(0)') # Issue #200073elfaFalse(<isclosed(f*(&P"/~-md%d 400.100 NotO7sRaises( ABadSaLine, 4badLrepr6exca U'('pr(exc), '''9`"''")'?Opartial_s@# ifhave Content-Length,p knows when to 0 it,psame behaviour a60we whole thing with%TP/1.1 200 Ok\r\nContent-Length: 4sText" sock = FakeSocket(body) resp = client.HTTPResponse(; )v.begin(self.assertEqual(O.read(2), b'Te'.RFalse.isclosed()*X/xtX?TruW}d%1d) Ndef test_mixed_ s(!!):  # line() should update the remaining l, so that7() knowsN(how much data is left and does not raise IncompleteReadB @ = "/1.1 200 O` 13]aAnotherloPo xtu\[ ?y-qpartial{Ointoif we have A , i when to 0 it,=#same behaviour as6w!ad#@wholCwithIbb = bytearray(2*An = r&(b- 7n, < b1s(bk7$Fobs_no_c_D#nod6present,$etbe gracefully dR# all1wasJ? resp = cl ient.HTTPResponse(sock) resp.begin(self.assertEqual(&read(2), b'Te'.RFalse.isclosed()*X/xtX .1,?Trud%1d) Qdef test_partial_3 intos_no_content_length(e!):8# when no  is present, the  et should be gracefully BQall data was body = "/1.1 200 Ok\r\nUText"-y = FakeSocket(? -_ = cll"b = bytearray(2WAn = E&(b= 7n, < b1s(b7$F f0s_incomplete_"iferver shuts downconnection beforeQwholeu-delivered.isGCb!-Lb@: 10Y }>}9=:1al(n, 2)  self.assertEqual(bytes(b), b'Te') &*False(resp.isclosed()*An = readinto(bGqOn, 2'xtf0f?TruO(;d%1d) Vdef test_host_port(5!):t# Check invalid )A#!for hp in ("www.python.org:abc", "user:password@$"mNRaises(client.ISURL, HTTPConnection, hpIR, h, ("[fe80::207:e9ff:fe9b]:8000",< "70", 8)8  80  HFD0C"=J O:P *?c = (TPh, c.-0 (p(X0ponse_headers7W' with multiple message =the same field name.text = ('/1.1 200 OK\r\n'&'Set-Cookie: Customer="WILE_E_COYOTE"; 9 Version="1"; Path="/acme"iPart_NumblRocket_Launcher_000S`sqNo body1hdr7  .',2' cs = FakeS8(@RespV'(s#g.begincXRr.getl&(""> =^, hdr!adTest thae library doesn't attempt to read any data "# from a HEAD request. (Tickles SF bug #622042.):sock = FakeSocket(\'HTTP/1.1 200 OK\r\n'"Content-Length: 14432(,<NoEOFBytesIOresp = client.Response(, method=""8v.begin(0if P.read(): self.fail("Did not expect3qWhU1") Ddef test_Y`into_hbSf# Test thae library doesn't attempt to H/ ab = bytearray(5(b) != 02.assertEqual(s(b), b'\x00'*5*too_many*@ers(E-Aqers = ', .join('Header%d: foo' % ifor i in range(H@_MAXERS + 1)) +hOtext = (3 + k:@r#FRaisesRegexException9r"got moreoEn \dB", r send_file edb'GET /foo Host: example.com @b'Ac-Encoding: identity5 Transfer7chunked6 with open(___, 'rb') as bodyJconn`Connec'(''g I\ $\.)zA(s@', 'v!', K;2Tru.p.starts(`), '%rY%r' %w{\BV[:len<#],3ed)W@;b'this is a- Conly2zxample.com')# sock = FakeSocket(None) Sconn.% end(expected5self.assertEqual# , DW.data.1ocko = b''baarray.e('b', sFt0_F"""Check that %P) ress the configured 6.""ih = 8 # For easy debugging.zci%R"a" *f + b"b."PUT", "/", J, {"o": "9"all_calls, 3 & =.split(b"<", 1)[1]_ (C :# > "he configured block size."""  = 8 # For easy debugging.-conn = client.HTTPConnection('example.com',pY=c)Is= FakeSocket(None i.%9expected = b"a" *hf + b"bDend(io.BytesIO(@)lself.assertEqual(q.sendall_calls, 20 edata, _ def test_N_type_error(t!):$# See: Issue #12676t4?d&''#Pwith Raises(TypeERrequest('POST', '0', )|chunked!"_ M_start + last_1 + fed_end@respdResponse, method="GET"7v.begin(&!]x.read()(cclose(# Various :sfor n in range(1, 121 ; "Pn) + t1 @R2 D'x' ('foo\r\n'*xm=6trye^dexceptX@IncoIteRead as iK si.partialel_message = 'oP(%d b-)' % len8O grepr(im u</st;Oelse[fail(~ofinall }Binto~bPn%]bytearray(128I unk + chunked_end) resp = client.HTTPResponse(sock, method="GET"7v.begin(@n = P.readinto(bself.assertEqual(b[:nexpected], 25n, 2'rclose() # Various e sizesfor n in range(1, 12): = FakeSocket(chunked_start + last_1 + e\H` ; dm = memoryvieweifm[0:n]2&+m[i:n + i+ & 6i+J.x('', 'foo\r\n'xm=:tryd4 !dexceptIncompleteRead as iTU.partialge_message = 'o(%d byteT)' % len(9 BS vrepr(i)m</st;Oelse[fail(w'ofinall ddef te ed_head( =9= (m'x/1.1 200 OK "Transfer-Encoding:t-'1ahello world1 (% 1LeOHEAD} q `^g(), b'+pstatus, Vson, 'OKWQTrue(+!is?d()UCFals*(&?cd%d_chunked_head(sself): chunked_start = (!'HTTP/1.1 200 OK\r\n'"Transfer-Encoding: T- 1ahello world1 ()sock = FakeSocket(q+ last_$ +F_endDresp = client.Response(_, method="HEAD"8v.begin(b = bytearray(5@n = j.readinto(bself.assertEqual(n, 0bs(b), b'\x00'*j Mwpstatus,Y+reason, 'OK',QTrue(+isclosed())CFals*(&?>d%1d) def test_negative_content_length(C !GCQ!-LQ1: -H >?GET= ]1(437incomplete_/" 10"56try]"dexceptIRead as iCB}i.partial_e 6repr(i),& "!(7. s , 3 more expected)1J t/stsX_OelseXjfail(''_epipeDEPip d"/1.0 401 Authorization Require@"6type: text/html *@WWW-Wenticate: Basiclm=\"exaS!\"< $b"hO0conx`Connec(UK.com4.Raises(OSErroOr, lambda: conn.request("PUT", "/urlubody"))Gbresp =40getVonse("self.assertEqual(401, ).status+ "Basic realm=\"example\""Z getheader("www-authenticate# Test lines overflowing the max size (_MAXLINE in http.client) Jdef test_F___(!):,E = "HTTP/1.1 200 Ok" + "k" * 65536U\r\n"8m|.>AResppFakeSocket(^|Raises((.LineTooLong, ABadS)_begin l ('K'"X-Foo: bar' + 'r''04E%4$[. chunked:Transfer-Encoding: g aI+ '02a$'hello world0 t,N.Lreadearly_eofsx4 with no termination]K|sock = ~ l; B[ ;O.v(), b''@QTrue(*isclosed(CFals*(O?d%rror_leakAthatiet is not 2ied if Me failsV V`Connec#('&G.com!f= NoneLUlass Hn[__init__, *pos, **kw,0nonlocal{ # Avoid garbage collector n: N nse.__init__(self, *pos, **kw) conn.response_class = R 'sock = FakeSocket('Invalid status line']quest('GET', '/! .assertRaises(client.BadSSaLine, 4getcBTTrue(".closed)S@.fil/ def test_chunked_extensionJ!):&Bextra = '3;foo=bar\r\n' + 'abc ,pected = X0+ b1%' . m5start + |D+ laVded +cneDHTTP(p, method="GET"<7v.begin(zQEqual{.read(), ex0E"() gmissing_endi"""some servers may up a short encoding stream"""W$ { s) #no terminatuEcrlfLlrtrailersoSee that $P are  and ignored\I& +|@# weyquld havched the end of ` 6m;qb"") #wPAd toE5endDTJOsyncRCheckwe don'tDpasthp-N,0dat'" nh s}e#O$2now(2ouryb+O. e("ascii")) #we read to the end resp.close() def test_content_length_sync(self):(A"""Check that we don't read past o1 of CS!-LS stream"""Qextradata = b"!apected Hello123\r\n#sock = FakeSocket(b'HTTP/1.1 200 OK1 @: 10c' + exh )6 = client.]Response(~, method="GET"7v.begin(S.assertEqual(].C5(),0#J file should now have our 4qy to be  r.Rw2 #w?JJ>[linesH C1(2000), []11o_bound6 (1 r\6'b"cw have our extradata ready to be #  self.assertEqual(sock.file.4T(), eFB) #w?Juthe endJresp.close() def test_J1_bound_content_length(!):/lU = b""!apected Hello123\r\n# = FakeSocket(b'HTTP/1.1 200 OK1C!-L@: 30b' + exh!*3 H) = client._ResponseB, method="GET"7v.begin( ]A1(202520 #  should now have our+iF_,no  # Make sure fd returned by 1 is valid.pserv = 2et.(v.AF_INET,+SOCK_STREAMIPPROTO_TCP\ddCleanup(r $rv.bind((HOST, 0)Plisteresult = NoneW@run_f7er(>[conn, address]erv.acceptu,Rwith 0P.makeG("rb") as &er6a# ReadSrequest header until a blank li9while TrueY 5# =| )aif noti.rstrip(b""-UbreakQsendall(b"4Connection establishedhMnonlocal  m 9D th62 = Qing.T(target=H,X.star 'join, float(1  (*w@.get5[name(:.("CONNECT", "dummy:1234+2l0onnU:try'5Dtus,&OKSs 5no=A8 &s.*proxied k'\n)kfinalls.detach,]=kG thread.jocin() @self.assertEqual(result, b"proxied data\n") class ExtendedReadTest(TestCase): V1"""_ peek(), read1 Cline-Qs = (;G'HTTP/1.1 200 OK\r\n' hello world!(and now for something completely different/oz<_expected = [q.find(''):].encode("ascii"AQchunk@Transfer-EVSing: F+'a' 3F 9Z 2Mo DCo"0 # terminatP % # end of trailers"!) def setUp( )sock = FakeSocket!.&resp = client.Response(A , fsod="GET7I.begL .fOQio.Bug erFp.fpy.20 = & Qtest_{&)0 = <# patch up the b} so that it returns not too much stuffK0old{@.fp.p myW(n=-1A&(nif n >= 0e p[:n]i &102 = >5vall = [0while True{# try a short+ }k3pN{Greater(len(p), 0@.#pn unbou&$p2Gu zA2), )9 (p2.startswith(p2Dnext2*;J, p2;els, g 5#``False(4 'all.append0ot 6Ubreak kb"".join(all),WQ,"3_t_verify_readline(self.resp.readline, self. s_expected) def _verify_0(/$, %, 4:48all = []while True%)u# shortNs2% =9(5)1if "2and != b"foo"eK,0en(0^) < 5"&p.assert/.endswith(b"\n")all.append- aif notpUbreakzEqual(b"".join(all)eAtest1)c" = fgdef r(*1rese:1(4BLesslen(res), .return re+Sr = Rv6r(rfb h7_unboundedJdata1P' B3Lt    X&10  k,, _<O0@f1(0), b""B]peek_Np.$(B[ 00, }p)) class Exte\TestChunked(1"""+ s)#1( Ur() in cKQ mode5=#7('HTTP/1.1 200 OK\r\n'Transfer-Encoding:])-ahello worl3Kd!\n9.Mnow )2Mfor something completely differentDCo0 # terminat\g,# # end of trailerR$) rg@a si8 class that uses !an arbitrary read function and buffering """def __init__(self,;:!):"..S% =# !mainder = b"" a:ClineaWlimit^data = []1pulen = 0E3 = j6tryCwhile True3idx.find(b'\n')L#0if *^!= -1E"_break8`+ len(Q) >= Kj!4 - @=- 1_#Q more( !=r.append{ "L ad(1noto 0 #eof condio o+++= j[:idx] V[idx:Bs`return`.join(\Jjexcept Z?b""<^aise class OffPTest(CCasetest_allE%# Documented objects defined in the module should be_M%__jPexpecD= {"responses"} # White-list dmcdict()tH# HTTPMessage, parse_headers(),I& status codestants areOPintenally omitfor simplicity/QblackdI", "%"}5L1namdir(clien_h0if $.startswith("_") orS} >vcontinum_ = getatt,Xn2%if% =S, "___", None) == "http."P.add(oassertCountEqual.=$, A)A W R1[ .NOT_FOUND], "Not Found"i.B_con= p# Make sure we don't u backward compatibility E 3.4a'CONTINUE',SWITCHING_PROTOCOLS#PROCESSING,OK|CREATED_ACCEPNON_AUTHORITATIVE_INFORMATIONENO_CONTENT',  'RESET_CONTENT',  'PARTIALMULTI_STATUS;|IM_USED3PLE_CHOICE7MOVED_PERMANENTLYAMFOUNVSEE_OTHER.NOT_MODIFIUSE_PROXcTEMPORARY_REDIRECBAD_REQUESUNAUTHORIZrqPAYMENT;.IR FORBIDDENpMETHOD_^ALLOWTCCEPTABLEY_ENTICATION}_TIMEOUnCONFLI-=GONxoLENGTHjPRECONDINFAILTY_TOO_LARGj(2URI%q(HOST, (Uport,;?s`"_aaC=(''/6%))7JrwKect(assertEqual(.sock.getname()[1]i P@unit .skipIf(not hasattr(0, 'S).')r 'http.75 Zdefined'*!?># We don't5 anything here other than the constructor@barf,%as# this codW esYdeal with sett1up an active runn@SSL 'erN0for+ssl_wrappedP() toDually return from. class TimeoutTest(CCaseMPORT8QsetUpp&0 = y!et3et(`AF_INE ocket.SOCK_STREAM F.|0sup`.bind_ z8~.listen()`aarDown8l.close\3AttributeX0# Twill provettj  through [Zand into;F+#ault -- use global} kO"0 Is`getdefI3(s$&30}Etry:h) IsRE 0fin u![87(, (.D# nop!doh9==u+@op?onn.sock.gettimeout(), None) httpConn.close() # a value, = client.HTTP>ection(HOST, TlTest.PORT, ~?=30yvonnect(self.assertEqual(y.sock.getQT class Persistence(bCase):def test_reuse_rec%):# Should (E or + depending on header from serverDhUs = (('1.0', '', False), o: keep-alive\r\n', Tru91Y X SSALIVE:nS4 nPfor v3on,_,!insRPwith @.sub(?=G=?=msg'/{} 200 OK %O'{}'Content-Length: 12FDummy body%).format] = FakeSocketN(msg5d Is^(G-request('GET`/open-I'8"`responD as  MEI1 is R, notKxCaW.readc,?Ns, 1 .I@subs]3nt-Lq2 ifs else 2)0dis`ected(QK&0makI seU [(texte"""Return BufferedR9that raises ECONNRESET at EOF"""Qstream = io.BytesIOm &ainto(bo IsizeJ4g#, < ];2if >?= 0 PResetErrorVrS k4 = 'return io.BufferedReader(stream) tests = ((io.BytesIO, client.RemoteDisconnected),5make_reset_ro2, C,@ionRWError7)ABfor _factory, exception in :0with self.subTest(2= )48 = FakeSocketHTTP[(b'',AEP.requx'GET', '/eof-response'5assertRaises!, R4get@? qIsNone(4Nsock-*# .,ect() should be automatically invokede#reR REqual0sions, 21def_100_close('7 b'/1.1 100tinue\r\n')# Missing final 9gA', hs={'Expect': '100-con&'}E.m  GO a classfS~bCase):`\setUpif not hasattr(!, S'@skipi('ssl support Wired'U@servelf, certfilPAfromR.ssl_.As imVBShttps}return !i=r_aibutes2# simple to check it's storthe timeout4h =G(HOST, T1<d.PORT,C?=30#h.j , (pnetworkedDefault settings:s a valid a trusted CAb5sslxcires('`.trans_internet('G-signed.pythonL.netqTF V, 443S rssl.SSL0 as^_infoh mdMEqual(exc_infoN.exception.reason, 'CERTIFICATE_VERIFY_FAILED') def test_networked_noverification(self):-1# Switch off cert v.'import ssl0sup.requires('nt%')$Twith )transient_internet('-signed.pythonW.net'c@xt =._create_un3ed_!(~7`h = clv.HTTPSConnecV} e, 443,J{= "est('GET', '/"Vresp = h.get LonseM.clo>.assertIn('nginx', DL`headerjrver')&V@system_must_validk'dtrusted_by_default_/(2# D settings: ?1 a ksfrom a X1 CAz-8w"3wwwoL.orgk4 :( Xh1Jnt_type =-M-hCtext/html', e_OgoodWe feed the ses$asal}BSSLC} (ssl.PROTOCOL_TLS_CLIENTSaEqual(I1xt.qy_mode,_REQUIREDEcheck_hostname, True;oSload_t1loc!s(tv_vjdotnetL  EB/xtHW_string) #:f[{ /ba aa "CA" that is unrelated to the server's cert import ssl0sup.requires('network')$Twith )"transient_internet('self-signed.pythontest.net'):Gc@xt =R.SSLC (ssl.PROTOCOL_TLS_CLIENT> .load_verify_locations(CERTZlhost:`h = cl.HTTPSConnec8 s, 443, = [elf.assertRaisesSSLError) as exc_infoh~est('GET', '/~"a_dEqual(M`.excep.reason, ' IFICATE_VERIFY_FAILED') @def -_unknown_+(j# The customLq isn't 2mdefault trust bundleit6Rmake_ #',.+ /FPgood_Onamer(valid) Aates >;/sl: ddCleanup(h.close1nonexistentresp = h.get Vonse(H i# l$9%status, 404/ba1doe"!:Dfakeh$Cs';7Certificate @5q# Same _explicit checkF=TruB*)warnings(('', DeprecationWarning)): h = client.HTTPSConnec1 ('localhost', server.port,AL context=, check_Rname=True)Mwith self.assertRaises(ssl.CertificateError.request('GET', '/'X0# WZ |False, the mismatching is ignored.A1 = C' up",wss(('', Depre5hSnonexistent^resp = h.get Vonse(HI.clohaEqual(8status, 404Rc# The +'sTS settused if one isn't pZEd to+# .c A!x5Qk`# Pass[ ,toD should overridefW#$'stEKC@unittest.skipIf(not hasattr(;, '/')b'http.7  Zavailable@def ~_(k0# C invalid 9) $for hp in ("www.python.org:abc", "user:Zword@$"mN 3IOURL,\, hp)R, h, ("[fe80::207:e9ff:fe9b]:8000"S/ "70", 88 0443 _, 443H www.python.org:", "www.python.org", 443), (2D[fe80::207:e9ff:fe9b]PQ)):$c = client.HTTPSConnection(hp)+ self.assertEqual(h, c.host( p(port) class RequestBodyTest(CCase0""" cases where a r5 includes a message body.""" def setUp(TZ.conn'example.com'9.sock =  FakeSocket(""4get_headers_and_ff = io.BytesIOV.datamf.readline() # E the57Tparse&(fXdreturnh6, ftest_list_~k.# Note that no content-length is automatically calculated for# an iterable. Twill fall back to send chunkedCtransfer encoding.a5= (([b'foo', b'bar'] 3\r\nfoo 0bar 0'^*((F)F1forp, expec'"in Cwith ubD( !=A2'')45=('PUT', '/urly6ody7Pmsg, @=3*NotIn('CType', msg6L8$msg.get('T#-ES'), 'jJ", #()Xsmanual_k_k1SetVncorrect"sowe can verify%Q# it not be over-ridden b-e librarylr.@"PUT"4 {"": "42"}) message, f = self.get_headers_and_fp() "assertEqual("42", mesF<("content-length")>4, len(f.read())) jdef test_ascii_body(z!): .conn.request("PUT", "/url6"|'text/plain_o_type(sIsNone('_charset1] k\ b'5', ^ ]olatin1^(O\xc1b5b.f_bytese# b"`f__filej addCleanup(support.unlink, fTESTFN4with open2", "w") as ff.write(IDftU3c @ G5S# No 3# will be determined for ps; the G5sent using chunked transfer encodinstead.Dl =~ Q-"$Jpb'4\r\n0f _inarysupport.unlink, support.TESTFN) with open(", "wb") as f:.5f.write(b"body\xc1"OrOself.conn.request("PUT", "/url", f^message, f = =get_headers_and_fp(3& assertEqual("text/plain", R.Hcontent_type()GyIsNone(:oharset5|zchunkedy("Transfer-Encoding"NotIn("Cv-LengthQtb'5\r\n 0', f.read class HTTPResponseTqCase): def setUp(k)0d@ = "B/1.1 200 OkjAMy-H: first-value\_fsecond-1UText"*sock = FakeSocket(.resp = client.(@..begin()test_getting uf%(''p-7, '&(, '#.q, 'some default3 qnonexisR_p@_str4}5sNo-Such=C', 'G 2<iterable_G,[?s']#, 5 C(~2K?outE2.! ?int+H?=42%g`Tunnel\ s(baS_A = ( 'HTTP/1.0 200 OK\r\n' # Reply to CONNECT 'HTTP/1.19 5JHEAD2Content-Length: 42j')) self.host = 'proxy.com* conn = client.Connection("B U5._create_ 01 = 2(response_text) def tearDowk!):$HZw.close(3^.*, dLh (address, timeout=None, source_return FakeSocket , 1=A[0], port&1]MK  st_set_tunnel_\_P_headers(pdestina (Ku = 8888|a' = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}M.(b3ost,<n =2Tqrequest('IP', '/'+assertEqualL1ock<,x9T__PORT@$, ?ost>> >Tktest_disallowTafterPp# Once  ected, we shouldn't be able0 anymoreD(Raises(RunSError7.k '; Lect_with t(Y0SIn(b' / rNFdata# issue220951Not_\Host:]:'b MMJEp# This removed when CONNECT gets the HTTP/1.1 blessing self.assertNotIn(b'Host: proxy.com', %conn.sock.data) Cdef test_ect_put_request(7!):(n.( .set_tunnel('destinationn)0Q'PUT', '/'*QEqualzkChost 9port, client.E__PORT@;CONNECT }CGE0W_debuglog expected_header = 'X-Dummy: 1'Kresponse_text%/1.0 200 OK\r\n{}'.format(^$Q#etkevel(1M$t_createURion =(Nn with sup .captured_stdout() as output  slines =F.getvalue().split('O: {}n!, D) if __name__ == '__main__'@unit.!(verbosity=2) #!/usr/bin/env python3 # -*- mode:a # Re suite and benchmark@v1.5*The 3 possible0comes for each pattern [SUCCEED, FAIL, SYNTAX_ERROR] = range(3)UBm(needs expansion) # # { does not correctness, just speed. < # first element ofrtuple ieTregex;x`second!a # string to match it againstg:'code will embedPDRKinside several sizespadding,lQ how " #}b0pers on largeEs. .[#+mmon prefix?1('P(P|Perl ),!@# Al.(/)0# Grouped a676<|Tcim7 q6uA)\\1'Backreference([0a-z][a-z0-9]*,)+@a5,b7,c9,=`# Disa fastmap optimiz1GL A few sets ('Python', :), # Simple text literal $O('.*@ _# Bad; /.*}o# Worsx(y)= x. with grouping ] # Test suite (for verifying correctness) #+h/is a list of 5- or 3-tuples. The 5 parts `a # coF1te % are: # element 0: a str{Pntain the pattern #t01: /to match against525expected result (SUCCEED, FAIL, SYNTAX_ERROR)t3that will be eval()'ed to produce a tZ.G 0is ?n arbitrary  expression;availableC@varisG "found" (Rwhole), and "g1", "g2", .. up"g99" coxy "en3eac9,+th'None' ifAi wasn't given a valueE [ErrorFPindexL1 oupjrange;aalso "w1s",breturnv!m.R() (a)!4: "!of4uat?B I`two do ereported.V2qregex i-rto workl [4Ps canAomitQ uQs = [1?P<?P= exten_s"('(?PaI # Beginswa digitB!Bn illegal cha?fooM JR# Sam0s, $fLAform# Fw>a)(?P=T-aa 71=2!24i`ackrefundefined: KK2'g1/),1">?octal escape#\\j}aerenceL('[\\1]', '\21', SUCCEED, 'found', '\1'), # Character ('\\09', chr(0) + 'A %),< 14p/'au%a'+(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)\\11~'abcdefghijklk r+"-"+g1{ , -ks# Test \0 is handled everywhere$Q(r'\0 fsr'[\0a]e0~Xor'[a\0.^/qFAIL), various letter escapes"a[\b]\f\n\r\t\v9a\b $ a]S[\f][\n][\r][\t][\v 9 $]# NOTE: not an error under PCRE/PRE:u^YNTAX_ERRORcA Perl 2 #  c\e\g\h\i\j\k\m\o\p\q\y\zL!ceXPmopqy #Y0xffC@\377 f%C255)3# new \x semanticIx00fX U"00 01110ebO6', 1625444 v656((r"^\w+=(\\[\000-\277]|[^\n\\])*", "SRC=eval.c g.c blah\0n\tQ2.c"FG"that . only matches \n in DOTALL mod@'a.b/ ac'[(- \n.*q'acc\ncN _{4,5}$  \rsD(?s)3%nb!'3 8 o@/'ae ')  "Und right bracketA@ 7'AEmpty pan70abc:bc'), ('abpc', 'xbFAIL), ('a?'ax_bx', 4xabcy', SUCCEED, 'foundiV cb/*]*/07bc'`/bb35++ 'a f1 nq?1d/ ?FT^abc$SJ/f zK /{ LLx/@+"-"-tu X- a.N- \.0xyzd02 2@[bc]$l&bd#qa[b-d]eb1 Nc%O,ceONafQa[-b].-?[\\/# NOTE: not an error under PCRE/PRE:#7[b-YNTAX_ERROR} ]b! /\\ ?bc)! ( ']]a.b//\\1^eTbe1@^-b]N0'adOdV1-1 $^]OVmEED, 'found' , 'adc'), ('\\ba\\b'-', SUCCEED, '"-"-,/-a,Yyxy', FAIL/yzxxU 9@x\\B6 B>'*zT &Bxo a9a)B))S y|yB[ \\8:B bI, XPab|cdW9abcCfoun./@()ef\d -p+"-"+g1 'ef#$@a\\(!'aMa(b-ErrorB\\(*= </ab.(l0' b"2Q((a))Iw2'F-a-ao(a)b(cAWbc-a-@a+b+_'aabb3q(a+|b)*H7ab-Q8+8$?8 )(2SYNTAX_ERROR{Q[^ab]?cde0'7aC@a|b|c|d|i'e/(0)98=abcd*efg  qxabyabbb7#ab21 0(:)'9?fcde-cd>[abhgefdc]ijh^uT`, 'xg1&6'xyfS(abc|e, 'found+"-" +g1', 'ef-'), ('(a|b)c*d0abcSUCCEED, 'found+"-":Xbcd-b<b|ab*)bc>?', =Vabc-a=a([bc]*)c*=.bc>S(c*d)A2(\-bc-dL/+)L7_*)(c+!(-c[bcd]*dcdcde fa?+4%'a EFAIL((ab|a)b*(a)(b)c)(#g1}34(-b[a-zA-Z_] R0-9_]!Nlpha`H^a(bc+|b[eh])g|.h$%.bh>vbh-NoneEd$|ef*g.|h?i(j|k)k_effgzMTl)-]/ijZij-ij-j:', ?bc+0bcdG.r) ($a)Vmultiple words of text%@uh-u /' P, yea6\ *vq.*)c(.*> @x)W-ab-do0\\(I , !\\RP(a, b S#g2PIbP0[k],abRa[-]?L4Yq(abc)\\Aabca4B@([a-5p^(.+)?B~A bAera+).\\1?aaa!7a-aj,^(B # )c-+;FaA  8ound+"-"+g1' , 'aa-a'), ('(a+)+\\1' ', SUCCEED, 'found+"-"+g 9%).9/ba: btD)ba*u<a|a)a\\1$z /|a>)+z'u[abc]*)Ocabc5 #-')(b)c|ab2&Q-None1)+x aaG! E[ac]=c= Gcx-cw[^/]*/)*sub1/_d:msgs/tdir/trial/away.cpp# <-G o.u.([^:]*):[T ]+(.*)|track1.title:TBlah by[3G -d-d-c[^N]*N)+OabNNxyzN%-*I H(-N2?'ab ;bcx@w', FAILdxyz]*) |'x-pa)+b|aa6'95aac# Test symbolic groups ('(?Pa_!aaYYNTAX_ERROR-,9$idM-QCq)(?P=ida# HGxG octal escapes/memory reference@ M;\\09', chr(0) + '  B\\14U^ :3a(c)(d)(e)(f)(g)(h)(i)(j)(k)(lV1~defghijklk 1{'bc, -ks'All tests from Perl+,b-x-  axb_xabcy7}ababc', SUCCEED, 'found', 'abc'), ('ab*c, SUCCE. b/#7_ )Q'abbb 3A{0,}.8+5k ,10GFAILKq', &{1;T83."O{3,49#<4,59 !?1 E{0,13b] FL72_^abc$/f K- /{) Lx'$pS( a.v-x4W(ax#.?xyz02X tPa[bc]$'bdb[b-d]eL1 Nc%O,ceONaA[-b].-*a-\-a.ZYNTAX_ERRORe0[]b|! _e]]ka.b/^e1e1b1 @^-b]0'adOd1-1 O]b]c', 'a]c' , FAIL), ('a[^]b]c', 'adSUCCEED, 'found12b|cb//b'.6^/@()efrd -p+"-"+g1 6ef-d *a-', SYNTAX_ERRORO(*)b! $ /\\7 @a\\(5!'aa(b-Error<*= <wa.(l0Pa\\\\Z"'ab20bc)HGa'!1(a)C) r2jVa-a-aR(a)b(Afbc-a-cC@a+b+_'aabbExb3P{1,}b9 **MBa.+?S/bca(a+|b)VaAu7ab-8B{0,} u9;+8$6;$?8 O{0,1; )(mQ[^ab]v>cde<<)'HC@([abc])* Q'abbbK #B:"'aB (cda|b|c|d|' ;e0)=@*efgT  qeO@xaby&zX $b21 )E 7fcde-cd>[abhgefdc]ijh @>^(au tS(abc| d(a|b)c[ Y 'found+"-"+g1', 'bcd-b'), ('(ab|ab*)bcaSUCCEED, 'found+"-"+=Vabc-a=a([bc]*)c*=.bc>S(c*d)AOd', 2(\-bc-dL/+)L7_*)(c+!(-c[bcd]*dcdcde a?+4%'a EFAIL(?)b*(a)(b)c)(#g1}34(-b[a-zA-Z_] R0-9_]!NlphaH^a(bc+|b[eh])g|.h$%.bh>fh-NoneEd$|ef*g.|h?i(j|k)k_effgzMTl)-]/ijZij-ij-j:', ?bc+0bcdG.r) (%a) X2g107'((9#\\(,<# Python does not have the same rules for \\41 so this is a syntax error #  4ZaQ0!G!q ?YNTAX_ERROR15?i)8 5960 rmultiple words of text%@uh-uP /' P, yea6 **q.*)c(.*"abJ @x)W-ab-d0\\(I , !\\RP(a, b S#g2PIb0[k],abRa[-]?Lr(abc)\\],bcxn0[a-l5?i)abc', 'ABC', SUCCEED, 'found', 'ABC'), ('(?i)abc XB1OFAIL/AX _BX', <_XABCY AB*23"(YZ$*?i/BB8 vO{0,}=&+:+4 QD{1,}C#C1(O{1,3M'O{3,4>(=4,5>]?"6 F{0,18l7P^abc$3 !S M3 T T1 |Y ,/a.d1X[2.*?d?XYZC .OXYZDZE[bc]h!B+BDb[b-d]em5"/CE?ACEWVA 7A[-b]2-e-d1nd', 'A-'),  ('(?i)a[b-a]', '-', SYNTAX_ERROR), '/]b%#kASUCCEED, 'found;DEFp+"-"+g1 :EF- *ao ?(*)o$#X/\\dAa\\(B A(D A(B-Error@*A@Ae3\\(2(t4 {B\\\\h/\\j 60bc)Pg !ab% 1(a)KAM(2rZA-A-A+R(a)b(E\BC-A-P1+b+OAABBIB7P{1,}b=! **U" Ba.+?[/BC/.*6"_{0,5}: a(a+|b)AG;AB-<@{0,} ?$+<(?(?<1O{0,1?Z-None7 )({ Q[^ab]>CDE@), ('(?i)abc ', '', FAIL), ('(?i)a*SUCCEED, 'found *([abc])*ABBBCD', 7p+"-"+g1>#?-C'F#bcHFJCD-ADa|b|c|d|egE w4!)fF7KEF-Etpbcd*efg=~ABCDEFGB !abg@XABYZ; t65 4q(ab|cd)kjCDE-CDB[abhgefdc]ij>HIJD ^} rq(abc|)e d(a|b)c? \BCD-B@b|ab*)bc>ABC"=ABC([bc]*)cABaBS(c*d)M2(K-BC-P/+)P;_*)(c+! Sa[bcd]*dcdcd_DCDCDA \C+Cb_|a)b* #(a)(b)c)(#g134L-A-B[a-zA-Z_] R0-9_]ANLPHAL ^a(bc+|b[eh])g|.h$).BHB{BH-None bc+d$|ef*g.|h?i(j|k)OEFFGQ)-aSWYIJ-IJ-J10BCDwARl(%a) 2g10 ;'((=#\\,BD, 'found', 'AA'), #('(?i)(%a)p\\41', .o, FAIL4!', SUCCEED, 'foundL!z yx'> =??:(P)QgNE|b|cRCRCRmultiple words of textiUH-UH'V 3+MULTIPLE WORDS, YEA:\ * P(.*)cSYABCDEr+"-"+g12)j-AB-DEO0\\(M , !\\P(A, B "g2Mo%B-v2[k]e #2abc2?BCD&\\#\\SCD-$&-\\YO(bc)[%\\ RBC-$1-\\B`a[-]?c"A8q(abc)\\ZABCAB8I 6o[a-c]*9pa(?!b).0aba ad x_a(?=d1/c|30:b|5 (..I'acee2*3/+?4(c|e){1,2}?|d)>A + g%cp^(.+)?BrApy! lookbehind: split by : but not if it is escaped!-.<I1234abc5678|cvDv8uda-fA-F> y0123d# not an error under PCRE/PRE: q[\\d-x]P O(r'([\s]*)([\S3ing!1972?g3+g2+g1&% r'(\s*)(\S!s*'Q$p(r'\xffrI\377chr(255)%ew \x semanticsJ)00L!# k ! m5t\n\v\r\f\a C('\"(,, Hr9 I09)+#101327f (r'[\t][\n][\v][\r][\f][\bx_tb@# post-1.5.2 addition+# xmllib problem1([a-z]+):)? KY'smil7`g1+"-"3QNone-/ # bug 110866: reference to{fined groupQ.)\1+uzT1869: search (PCRE fails on thie, SRE doesn't)h!.*pabc\nab b 2468: various expected syntax errors (r'(', '', SYNTAX_ERROR),P[\41]"!#UCCEED, 'found,# bug 114033: nothing to repeatPP(x?)?9xP+x'P"5040: rescan if flags are modified inside patternj?x) foo n?foop r618: negative lookaheadYK/,  d/[m3y30748: ^*y be an error ()^*t[3283: minimizH problemK "(?:\\"|[^"])*?"', r'"\" ko477728kP^.*?$ one\ntwo\nthree1JFAILW_83789Wa[^>]*?bZ a>LO9057#^a., IP70582sted groupsS^((a)c)?(ab)aMg1+"-"+g23QNone-&ab,a/er (capturin assertions2'^([ab]*?)(?=(b)?)cu ab(DO!(b)C,Oclass Base:  x: Any = 15.0  y: int = 0 @dataclass C1(Base):KzC1[x5\@o = D%()D6self.assertEqual(repr(o), 'TestCase.test_overwrite_fields_in_derived_..c x=, y=0)')/C1L0C1(~_, z=1?x=5 K5Adef WMp_named_( 7U: strc=C('foo' c.8#, (<# Make sure the first parameter is not 'D%'.=sig = inspect.signature(C.__init__Y= next(iter(sig.i&s)+f#No{,e# But we do useq if no sUmxn<3/Y,0_compareC# En at order=False !vdefaultK0pF7(fj? C1D for cls in [C0, C1]/Qwith 0sub(cls=clsx\' `cls(),a(+|pidx, fnenumerate([lambda a, b: a < b,: >=?*>>+O= b]+[idx=idx0 4hRaisesRegex(TypeError-U f"supported betweestances of '{cls.___}' and"lfn(cls(), cls())3 @dataclass(order=True)5 C:7Epassself.assertLessEqual(C(), C()I'|Greater*R def test_1_field_compare(@)# Ensure that False is the default.V0W)ox: int"hF1F for cls in [C0, C1]1Pwith .subTest(cls=cls'tFpcls(1),b'(1v-16Not404pidx, fnenumerate([lambda a, b: a < b,Tn >=?*>>+O= b]aidx=idx0 4RaisesRegex(TypeError-Uf"not supported betweestances of '{cls.__name__}' and"l fn{(?0)) /Q[1!(CjC $) R(!y'|S,osimplegy9U YHK50,  14, 2 7 71fn|:"01, "/wBambda a, b: a <= b, lambda a, b: a >>+o= b]): with self.subTest(idx=idx04 assertRaisesRegex(TypeErrorU*f"not supported between instances of '{cls.__name__}' and"lfn(cls(0, 0), %) '@dataclass(order=True)* CWex: int$iyfor idx, f enumerate([=4 7k 7>%D(T(fn(C^ )]< $!M61))B;p1), C(16-6lwl q? 7qE;;10, ;1-q0qdef test_compare_sub00es(G1# C$isons fail 1@, evf no fieldsd# are added.}* Bi87C(ByFpass*(fn, expected) in( False);x LH , y)$PEqual B(!WC(0)) e([lambda a, b: a < b, lambda a,6=7">6#i= b]): with self.subTest(idx=idx(, assertRaisesRegex(TypeErrorM!"not supported between instances of 'B' and 'C'"Ifn(B(0), C(0)) def test_eq_order(A # combining eqh-.D\por (eq, , result ) in [+#(False, 'neither')'True, 'exception)"P?nly'.X'both$] 0eq==+$if(== ]*0 CValu1 'eq must be true if 1 is'a@dataclass( /2/ C%MpassBOelse7  g0.NotIn('__', C.__dict__)k??lt_?*e?*g~+g~*eliYfc)<`#< <Z#<x WZN]#?__le__', C.__dict__) self.assertNotIn('__gt__', C._?#e?_else: False, f'unknown result {Q!r}' D def test_field_no_default()i@dataclass8& C$x: int = Q"()gQ3Equal(C(5).x, 5%Wwith *RaisesRegex(TypeError,Xr"__init__\(\) missing 1 required "H "positional argument: 'x'"C UR = object(nm<pU=ZU@Is(Cy%c = C(106c9"<# If we delete the instance attribute,"`should"An se+F P3.udel c.x1Is(%!C(k 'not_in_repr4K=LOr(c), 'TestCase...C()'ps y?, 2Z NEy=20 compare.0le#, \'=4Y?C(), C(0 (Q1, 10-1-4NotX3,46Y,&0FChash\rulesH # d all 6 cases of0# Ba=True/Q/NonedH4# <#Pfor (@ _,-*,u ) in [/$(G.1 ':' ).+5+' ),  p(False,  'absent'), +2Tru4+2Non! V+V{field' )]:with self.subTest(hash=_, compare=)<@dataclass(unsafe_;=)i-(. CFx: int = (s{!, X_, default=5) eif result == 'M'r1# ___ contains the.Y*assertEqual.b(C(5))n((5,))*elT is not preO1 in&/sef'unknowne{mB!r}'def test_init_fC_no_(BHP# If *=t and no@ val%2the won't be,# !instance%7 l.NotIn('x', C().__dict__-yoy0z(6t'"10z0)-Dvars {'t': 10, 'x': 5, 'y': 0} g|_marker+5str1  8z: 5BreprzAthe_Zs]6s(CG#! is a tuple of 3 items, each # in __annotations__n3IsI(,i@for >  R(type(f), FG*n(f.name, C.&27lenO), 3. 3[0]o6'x' ` 2,22Maattr(C\ KW-the_fields[0].repr) self.assertEqual(the_fields[1].name, 'y'2type, stdIsNone(getattr(C\][FalseOinit-[True -2z?2]. 5has?z')?2].W2def testp_order(!): @dataclass& B$( a: = 'B:a',bbc5c' 7v7C(B ^7C:bC 3[(ff.default) for f in U(C)],_ b[('a',)(@ ('b(( c(B:c')])DC(D:C#D:OB:b';E(DyEyd^?E:d.E k dCC_Us# We only have a , ,ibute if a ) value i# specified, either directly or via aWV withM.a^= object( xex: intRy" =}(= ^'#z:v$ = GtGG=100fc(x*y*Is (C.z,{VC.t, disallowed_mutable_For the known types, don't allow mutable default values. for typ, empty, non_  in [(list, [], [1]),7>(dict, {}, {0:1}9set, set()v>)]: with self.subTest(typ=typ)(@# Ca5use a zero-length10-]assertRaisesRegex(Vd_Error1RL f'`{typ} yfield '6'x is no ?ed'?@dataclass`n Point:@ x:H" =I- Jp# Nor ab-a .`y`Xy`cCheck sub  also fail1Sub @): pS"$.*='>"c'"zJ Hz/()@Beca@this0a CVar, it can be/ C%z:hp[typ] =zx Kdef test_deliberately_i_ s(d# If aT* isin the known 5 ofS3# "Pset),0n it's okayM __init__v.l = []9@dataclass  class C: x: Mutable  # These 2 instances will share this value of x.8Tlst =O%()o1 = C(lst2self.assertEqual(o1, o251.x.l.extend([1, 2]?!P/, JpIs(o1.x2.x)$def test_no_options(\)[# Call with data|&(),@)&2intzj &PC(42).42~t_tupleMake sure we can't be compared to a ; VPoint0x: y#NoI(2), E# And thatnother unrelatedz)P3), C#3)5BTest1som^the problemth named0 doehappen# herem/3DzuJDateaByear>I^month#da5W63D(2017, 6, ~z( y 3D2@ /# 6funpackp RaisesRegex(TypeError, '8'5cx, y, z = (4, 5, 6ao|4same field1us isn'tF@# eb*v1E = 0U 0 " 00, $),=v1(H@func|p_annota SIbdummy #5and6use as a default0FEpassgf = F(validate_@K(cls# First, check _ __, even though they're noh4#   self.assertEqual(cls.__annotations__['i'], int) self.asser< j<?str<!k<F:!l:Ofloa"z>complex) # Verify __init__. signature = inspect.^9 # Check the return type, should be None.5Is(g.A,= seach parameterbs7terb/s.values()! = next( s!# This is testing and ernal name, and probably 0n't 4*edw.K''  4 2RiO.RIs .LDbpdefault1CPZemptyyOkindBPOSITIONAL_OR_KEYWORDR'j".k @# DoA for2 since it's set to MISSING+2glRaises(StopIterc,%,6s) Q@dataclass5 C: i:: ij: strk: F = f l: float=field(default=None) z: complex=+3+4j, init=False) 8validate_class(C # Now repeat with __hash__.?R@data;frozen=True, unsafe/-5 C:Cii: intij: strk: F = fl: floatJdef test_missing_f(self)# Test that MISSING works the same as a ? not being# specifiedv)WxW .assertRaisesRegex(TypeError,j@r'__gs__\(\)  1 required 'H'positional argument'Y&C(NotIn('x', C.__dict__<D_<$%D%D%_factory-G^"#  (which is really3Fo, too)93=A},Uq1Dreprf self.assertIn('MISSING_TYPE object', repr(')) def test_dont_include_other_annotations(self):37@dataclass& C$(ei: int$r2fooR0 ->! 5&return 4;@propertyQ?barQ5;3Equal(list(C.___), ['i'])9`C(10).O), 4)obar, 5'\i, 100pos"it8# Just make sure it gets calledU%__o,__qraise CustomError(Wwith hR,'s(-SM#C( dU = 10@"if0i =EUF>Y # f:-in, but doesn't ~. This is jusU# checking that&used correctly.7C(5gP# If e's not an __0__,n wo3getXU(<f=False er# Creat"e i7 : x? = \$ex *= 2izC().x, 0/#2$4D# Maif we're frozen, ca)se7attributesFO=Tru &A=FInstancerE_aCsupe*H!):iG0 by2Fault28BP|@&*!(B de f __post_init__(self): u.x = 5 assertEqual(C().x, 5)$# Now call super(), and it will raise.S@dataclassK C(B/dex.Wwith Rs(CustomError{'C(># Make sure I-I1 ised, even if not defined in our1#  "p.K'QGteststaticmethodflag = False~ Sex: int7my@ -  aRnonlocal ?v = True(&)<c = C(3, 43 (cbc.y), ,-y_` ~i ; ;cls'(Ccls.jC(+l>anL_varCVars are ignor_7, __repr__, etc Q = 10O4z: Q[int]"0$w$+20$t$3$s${P = 4$5 (c), 'TestCase.y!.<s>.C(x=5, y=10)'Slen(fields(C)), 2)# We have 2 + PC.__annoons__), 6Xu# And 4zsOc.z, 1000Pc.w, $ 0t, $ !s,$C.z += 1 c.z, 1001)  c = C(20)  self.assertEqual((c.x, c.y), (20, 10)/0c.z#/01$ ow, 200w oc.t, 3$ As, 4$def test_class_var_no_default(!):)# If a C+Var has no . value, it should not be set on the f.QQ@data& Cuy%x:ue[int] /|NotIn('x', C.__dict__)+_factoryat makesense forto have aLe. WhenA# wicalled? Call-@your, since it's)V-wide.HwithmRaisesRegex(TypeError,w9@'can'B  = field(tC=int7 # BU = 104C3'10vrn =V\x (nfrozenMake sures work even if we're ?(V=True5int=jy: intUz+"0y$w$[ `t$[OE5 [repr(C(5)), 'TestCase.n..C(x=5, y']Alen(U0s(Ca 2) B# We2s O6ations__), 5Wv# And 3N "can still modify\ 's only instances that are-# C.z += 1$self.assertEqual(c.z, 1001) c = C(20self.assertEq6(c.x, c.y), (20B)/e Sc.w, 200w ac.t, 3$def test_init_var_no_default(b!):(# If an InitVar has no . value, it should not be set on the class.QQ@data& Cuy$x:te[int] .VNotIn('x', C.__dict__)+_factoryat makesense forto have aLe. WhenA# wi called? Call+@your, since it's'V-wide,Pwith *RaisesRegex(TypeError,w7@'can'B  = field(sC=int6 AU = 10 C '10 sok =UYw # int = NonebZparam, -D__po_&, E bf"Ax is G# 7x =M"*2*iG  Oinheritance# Note that this deliberatelys%a )A neeZo$#  0 function ifi^q# It c1jusqused inRrived@, asgwn her"JBaseex: intpb*# We can instantiate by passing`P, everEoughf"# ^@b = (2)vars(b), {'x': 0}C) @dataclass C(Base):1iy: int init_derived: InitVar[int]e;def __post_3_(self, Cbase K yB0S.x = +< ,y,#y ,]c = C(10, 11, 50, 51)NiassertEqual(vars(c), {'x': 21, 'y': 101}U0tesfault_factory# Test a that returns a new list. x!y:L = field(de=i>!c03 ,c1 gc0.x, 4"Vy, []W#?, cIsNot(c0.y#/.yFastuple(C(5, [1])),  ashared:ol = []Rambda: lAvarious otherf flagso# repr! ,[o=Falsej0(C(a'_Case...C()'R0C()H&e# hash (unsafe_G=Tru N d_([],)S( 7())# (see also B_with_no?k  (~# compare;^qC(), C( def test_default_factory_with_no_init(self): # We need a 0 0 a side effect.0$= Mock() @dataclass& Cnux: list = field(=b , g=Falsef# Make sure the >is called for each new instanceUC().x.assertEqual(.M_count, 1)0> 2def test_@not_oed_if_value_giventhat we can^ if it's been */in  atam has afunction,v"# 3notF, is specified  C(10).x, 10 &`>Y~derived,See bpo-32896=Foo?dicYwBar(Foo}2y: I1K P0FooO, {}va&yZzp 6Bazcintermediate_non_5QTest  an$9 Xfdefines# annota:ps does /(p&s.kA6int8?B(A(`;C(B;z ;c = C(1, 3 (cbc.z), ,r# .y waOXializ RaisesRegex(AttributeErrorq'objectDno aC'6c.yP# Andwe again u a non-#C, no are add class D(CG): et: intd = D(4, 5)self.assertEqual((d.x, d.z), ,!) .def test_classvar_default_factory(L# It's an error for a C>Var to have a @ function.pPwith WRaisesRegex(TypeEY,/3t'cannott|'BQ@data ]* Cf0%x:[int] = field(h$L=intP5is_n DqqNotData; |Bpass*iFalse([/0)*,a53())y ux8D1Ed: C5qeIc = C(107Gc, 4k;TrujC )c)?c.x,U?d.d+W4d.e~qhelper_ s__instance # Check that we can calls() on eithe4or O# and get baQe same thing%y: float5D(C),C(0, 0.0,Pexcep" P is rPd if Ued a 5 or%# 4 #& 'RWtype  00C: {FC}dG(nasdictQBasics( ), it should return a new Gfionary+, 2) ! self.assertEqual(asdict(c), {'x': 1, 'y': 2}) 6 A/XIsNote/c.x = 42o/42 vIs(typey0), !) edef test_helper__raises_on_cl$ s(!):4 "# *() should 3a on a 4 object.3Q@data& CW[ex: int$yHwithRRegex(TypeError, 'q instance'YC\>?intl copy_valuef3+List[int] = field(default_factory=listinitial = []c = C(1, /4d =c( Wod['y']@**e{@.append(1/jc.y, [] lnestedjUserIdZtokenvZgroupW Uname: strTBid: 1u =q('Joe', Id(123, 1)Nu 5d}3': R'id': {'2['}9{4u),FuQu.id.I? = F){' 2I(builtin_container*GV V@ pusers: -[^ _Tuple_.`_, ...eODictd-B[strca@Alic1) b = User('Bob', 2)  gl = GroupList(0, [a, b]"t"PTuple#(#)#d#1DicE {'first': a, 'second': b}5self.assertEqual(asd>gl), {'i00, 'users': [{'name': 'Alice', %51},US?2}]t(UP)dB_ gA}}) def test_helper_ _builtin_containers(8!):5@dataclassf Child(,d: objectt?jParent@cSZCB(a([1]))EP': {'0[1]Lo{1: 2}ORVfactoryK ax: intayyc = C(1j$@(c, _=Ordered= 7d, )([('x', 1), ('y]JIsNot(d, c.x = 42D/42`(type(<t*q# Basicgs for as) ), it should return a new ..C"E = 0N&G K (c$O1, 0A-c1%=y/42pr"),]_raises_on_e#4 on a class objeSct. @dataclass5 C:+ix: intywith self.assertRaisesRegex(TypeError, 'q instance')lastuple(C)p]?Qint) `def test_helper__copy_values(6+List[int] = field(default_factory=listinitial = []c = C(1, /Ct = &(cEqual(t[1]?(_IsNot(axg.append(1.gc.y, [] onestedjUserId_ZtokenQZgroupW Uname: strT@id: ,%Id1u =q('Joe', Id(123, 1) Nu 74t, KE/5u),%uwQu.id. E = 2 wH ?2)) builtin_container`MyG V@pusers: -[^ T_.`_, ...eODictd-B[str~ca@AlicbvBob', 2fgJ(0, [a, b]""#(#zQgd = #" {'first': a, 'second': b}XPgl), E6[(',]|GtG(GGdG P$('}H9 class Child: d: object @dataclassz Parent@cSZC self.assertEqual(astuple(C(([1]))), ( U,),))qAc{1: 2}D GHdef test_helper__factory(d)C$9ax: intbyNT = named'NT', 'x y'gnt(lstMreturn NT(*ic = C(1, 2ECt = A(c, o6=nt)  t,bN&IsNot(t,_ :c.x = 42- 42aIs(type(t))vOdynamic__creationpcls_dic{'__annot)s__': {'x'B, 'y %},}0# Cnae the .3acls = 'C', (), CMake it a  F61 =G(cls>$vAcls1hH$ asJ\#),1#2}cc _using_fieldoFcdefault=5)M1(1)5init_in_orderab2 = yM`c: lisI , j=False>d> 2eo/=4df241cal%[]bsetatt<,{, value?.append(((,CC.__QS__ = qF0, 1 p('a', 0/?[0]- b'O!, [1]) self.assertEqual(('c', []), calls[2]) s.d.3.NotIn(('e', 4[X f*Q[4]) def test_items_in_dicts(!):#@dataclass& C$(ea: int$b: list = field(default_factory=, init=False>c> 2d o/=4de20xf = C(0[0# C &'a', C._F&__?*b*AT @In(':' 0C.d6HTH9e, #Instance&`#c# 9c.a`DHAHb`IcIL d' dalternate_method_construW @# Si@__ponit__ can't take params, use a Vy5# w k. This is mostly an example to showE0howit8technique.&nx7@<from_file(cls, Gname*# In a realp, creatSnew i ~; and popul/@'x' y4tents of a}9Pvalue] = 20`return cls(.F)F C.'[').x, 209! P_meta_RM8sure the ' 8qread-onEd of# zero lengthiPD(s(C)[0].!?len4 Wwith mRaisesRegex(TypeErr_or, 'does not support item assignment'):Ifields(C)[0].metadata['test'] = 3 /@def _0_)_mapping(selfZ# Make sure only a * can be passed as Lh# zero length.Pwith i.<rtRaises(TypeErrorG@UclassB* Ci: int = (2=0)$an empty dict works}yu5{})aFalse( 0Equal(len46, 08`VRegexek _ non-H : 10, 'bar': '42', 3: 'three'z3z87, 1<!],y39</O(Key0# Nxistent key-Ubaz'] sz)ocustom0 Tr%&,"<SimpleNameSpacey__init__k, **kwk2 ____.update(kw&P0getAS S"ifh== 'xyzzy'Qreturn 'plugh'sgetattrs(3lenK "__4- g(a=10)` 1^self.assertEqual(fields(C)[0].metadata['a'], 10) with self.assertRaises(AttributeError):07\5b']''# Make sure we're still talking to our custom mapping.?OEquaPxyzzy'plugh') Cdef test_generic_ cl s(\T = TypeVar('TB@6UD LabeledBox(Ga7[T]S*ontent: T=l;: str = ''"Xbox =c&42Rbox.ck/, *~,x1y# Subscripthe resulshould work, etcPAliasFist[ b[int]] extendingS&S' FBase<, SxBy: SDataDerived(e-, Anew_0 0FF[strAAc = %P(0, '#1' 2 astuple(c), ;7Non lmethod.breturnTy no[floatg10, 1. 'c.).p2lynamicO fParentQN Child = make!('', [('y', T 'z', Optional[T], None)],Xrbases=(7],  , namespace={'other': 42}VZ1Is(H(1, 2).z0 31, 363c3 # Check that type ai!es correctlyT[ ^Fx, 1{0MRO0olui Pr.__mro__, I", , object)mses_pickleableglobal P, Q, R@dataclass class P: ix: intyE = 0Q@data@/ QN field(default=0, init=False)ViRiList[int] = o_factory=listnwq = Q(1e.y = 2 samples = [P(1), P(1, 2),7a, q, RR[2, 3, 4])]BBfor F3 in s#Pproto"range(pickle.HIGHEST_PROTOCOL + 1)=with self.subTest(r=!, ^=?CBnew_.3 = ~TloadsSdumpsXQ)8CassertEqual5F.x, f/.x=y=y=DIsNo;9F = 4another_., '094v< ERy) 3FNoAnnotation(unittest.CCase;@def _b_}Vout_a:-8"RaisesRegex(TypeError,23"'f' is a but has no type "NYCTfC!) )_b_in_base(Bf|Fr`# Thisstill an e: make sure we don'tGq up theB,# @the 0.24I8;C(B6U_not_ a# Same, u not a DE  "'f' is a field but has no type annotation"): 3`# This<still an error: make sure we don't pick up theE g0 in& base class.2Q@data K C(B2f =R() *TestDocString(unittest.CCaseFdef asser,Equal(self, a, b'e # Because 3.6 and 3.7 differhow inspect.signat!5ork # (see bpo #32108), fortime being just comparehm withGwhitespace strippedF.a.replace(' ', ''), b!) b+_existing_doceng_not_overridden("CY"""Lorem ipsum"""xdbx: int 0C._I__, H _s%OpassbfOC()"2one%$_x:int 2two(&y ?, y3hreK@ z:ir, z:str __default$+O = 3!/=3__none(Union[int,4(None)] = N@`Type]=  Blist(@List]: (_factory(self):  @dataclass ! 5 C:x: List[int] = field(default_factory=list) 8self.assertDocStrEqual(C.__doc__, "C(x:X#=)"Gdef test1string_deque_b)Fcollections.Bk_with_/(,/  TestInit(unit.CCasebase_has_i/ MBf;_/,__ H.z = 100kp# Make sure that declaFS thisdoesn't raise an error.F The issuJPwe ca6override r in our],F but it should be okay to add?to us ifEC6 ha # l#(B x: int = ?c = C(10)f_c.x, "NotIn('z', vars(c)o if we do>0an !a, the # gets called(Cf=FalsedC1<#z#0 1_no z i tC().i, j)2J%ef Ui = 3;N3+N@writ dA# If(5hasP, use`no matter)value of!# o&=.!= :J;, xp'x = 2 * xB  3)i6<)>Tru__init__(self, x): self.x = 2 * xassertEqual(C(4).x, 8) %@dataclass(init=False)* Ctex: int$`def __B0__(y-5b10) TestRepr(unittest.CCase _r&WB%87C(B_cyV = 10`@o = xQ.Po), '...C(x=4, y=10)'b;D(C'0,?D() oD(x=20 EYE i^C ECEpassA_C.D(0&!i=OEKEC.E(/no # &2 a )with no _-p__ and R.,(AIn('>!es object at',<g(C(3))aR^ V$return 'C-'3,/jUoverwriting w# If the5has, use itamatter)value of"# &."&$xx?Tru&YO*_(self):  return 'x'  self.assertEqual(repr(C(0)),) ) class TestEq(unittest.aCase):M@def p_no_eq(Xk#?2 a L with no __eq__ and eq=False.N4Q@data0()" C|.ex: int$#No , Lf = C(39ec, c) Y/anLe4aw, otherh%e == 10 C, 10doverwritingcIf the3has, use itamatter'value of # .V$"3kO1), O%1;FTrueXN4 4CN5 5 Orderingfunctools_total_o:lvUthat 4.4q works Bthis8 /PwOlt__. # Perform "backward", just to make# sure is being called*@R.x >=ALessO, -1"'bGreate/, K$N\M1no $  ions are added by default(<b# Makeno order methods are added. self.assertNotIn('__le__', C.__dict__)/ t/g^g^# Test that __lt__ is still called+@dataclass(order=False5 C:1 ix: int3defk(;, other)8<qreturn gB# Make sure9S meth?n't@o4test_overwriting_JPwith WRaisesRegex(TypeError,,'Cannot te attribute'H.*using functools.totalGing' .7Tru-#15A 1Upass KWw'Kw?e__KKKoK=Hash(unit].CCase4_unsafe_h-[ &= clawss C: ix: intey: strself.assertEqual(hash(C(1, 'foo')), !) ?def test_ p_rules(O)#non_bool(value # Map to something else that's True, but not a H.}=1if X is None|areturn:2I(3,)2J0\(case, unsafe, eq, frozen, withkresult  <.subTestQ=V=bI=eq, = w*2if != 'exception'."&@dataclass("M k_,__(  ~Fpass# See if thematches wMexpectedAA_== 'f$# ^ containso@func4 we generafjoDIn('P', C.__dict__u6:@sNot(5[L]6*el!istpresent in our Ag!if1?Not  Onone0setf5 :sa'~ p# Creat& should cause an E# This only happens> ==x?(0 RaisesRegex(TypeError, 'Canoverwrite attributek'@dataclass(unsafe_hash=unsa , eq=eq, frozen=?) class C:!8Qdef _k__(self)0 4return 0 ZOelse@assert False, f'unknown result {F!r}'V# There are 8 cases of`7# a=True/a # 4?6And for each of thea different(ifmJ is defined or not.'X7, (,,^,aC_no_G) in enumerate([fJ([5 ''O''),J^DJ(CLnoneJL 'fnH/ J5Jexception1SSL9S#K], 1IRtest( , ),?(eqN)\"j$zr_eq_onlyvr# If a 0s _.%_,automatically addeda0# and seW Nonenormal Python behaviorCtArelated toees. Mwe don't interX withFthat (see bpo=32546).@1[ classW C: ii: intdef __eq__(self, other)8Cpreturn %R.i ==)%.iNassertEqual(C(1), )%+No(E4)) )# And make sure things work ins case if we specify? unsafe_hash=True.@dataclass(% At6.0) hm4), 2 Ncheck that the #es is being used, despite5$# e$/eqT#, .{]J_3 and 3)3k 1()utest_0_fieldyafrozenrD Epass*(()sqv%1=x 4  4, 12223o@']x_no_argsu# Test ,es with nof = argument. This exists to)#  at{+ parameter namexchangedF!ornon-defaultbehavior 7!s,*&Dability keepMCs}Fway.JBase>_5<.6301PR# If ` or eqANonenx value (do noC any%e decorator).  for frozen, eq,@base expected in [ @(Non)object, 'unhashable'),2 Bi20Fald `.`,0TruQ2^" 2d9 '`"%Q" 2^"] "?tup? -_-  [.[,Q?, ' -Y-9]: 0with self.subTest(===$, = )):S # First, create the class.+#if@ is t and eq]aQ@dataR Q0 C(#mi: intB-el }(eq=eq)Kf0 C/se? F1 a# Now, make sure it Ues asw9 ==Sc = C(10H assertRaisesRegex(TypeErroro type':(c)P 'aEqual(Wo), 301ac# I'm notwhat test to use here. object's # hash isn't based on id(), so calling%/()C wo>tell us much. So, just check the?functionEd is.2self.assertIs(C.__3__,8-) @ elif expected == 'tuple':*-j`Equal(i(C(42)),o(42,))j/seV False, f'unknown value for$={!r}' class TestFrozen(unittest.RCase)t@def "_f(Q@dataM(!V=True" CL1fi: intTc = C(107f0Xc.i, "Wwith 'rRaises(InstanceError}uc.i = 5D k#inherit(0S2E7D(CyjId = D(0*4d*s&qd.j = 6PC d 2d.jD# both ways: anWermediate normal (non-d2# 1and=Lout @": B_nonmE5int_RP in [&,]I@.sub(C=wcV $  )ifm '`IN pas@/elI)N$Regex(Typ,,/'cannot  5 <p from azen one'wn{?D(I?C*> }um }'self.subTest(intermediate_class=K): Q@data0 . C4C}i: int 5 if C`I(C): passLOelse;^I = C}with self.assertRaisesRegex(TypeError,h'cannot inherit frozen 6m a non-Oone'jbn(-o=True)?D(ILP7>def test__from_normal(L?forP in [, False]bsubTesty&^\j9d = D(10 l!(FrInstanc,rd.i = 5$0non4zen|derived# See bpo-32953.H]  7x.@yV = 10]=;S(D vs = S(3.Equal(s.x, ! 8y, qps.cache# But can't change theattributes.&1s.xEI(yI 1Vc1 , 0)1ioverwritingqb uses __setM__ and __delY ""'C e m  04 (# with self.as sertRaisesRegex(TypeError, 'Cannot overwrite attribute __delY__'):O@dataclass(frozen=True)$* C9ix: int,8defs[(selfw'Upass AGFals2set, name, value.__dict__['x'] =-E * 2' asEqual(C(10).x, 20)~Rtest_RQ_hashv x2Anye># If x is immutable, we can comp@the . No exception is0# rx%d.1S(C(3) mkdDing f@an eOWwith 9@ 'uny\ typeP(C({} "TestSlots(unitv.4CasosimpleZ 0__sg__ = ('x',$;x: There was a bug waa variPin a U%ssumed to# also have a default1(of%.5s.MemberDescriptorType)Wr"__init__\(\) miss 1 required posioal argument: 'x'" ^)C(jW0rea n instance, and assign to xAc = rc&10c.x = 52 5''tPanythFelse A "'C' object7 no-'y11c.yderived_added_field# See bpo-33100T JBase ZD(b ynDd = BF1, 2  (dqd.y), (, add a new :`U3d.z = 10 xset_name(selSf): # See bpo-33141. Create a descriptor.vclass DJQdef __set_name__(self, owner, {1$.! =#e + 'x'i#X5getSinstance]W4if % is not None]return 1v@ThisVthe case of just normal2 behavioo_r# dataE@codeM involved in initializing f@DYRCc: int=D()(.assertEqual(C.cx, 'cx')Now test withfault value anit=False, which5theo# only time t=really meaningful. IfXusing>bKthen will be overwritten, anyway0field(de>,KHts().c, 1nhV_non_E# PEP 487 saysp should work on non-Is /# rGHjdqlookup_on_3u(&75J*FpassBHd = |}n attribute , Ftypel(d.] = Mock(>b# Make sure -fcalledSiC dT  ._count, 0[0D? -0is ;6?D()= =: ' TestStringAnnotations(un st.TestCase):  def test_classvar(self): # Some expressions recognized as C9Var really aren't. ButF if you're using strpannotatY, it's not an exacAscience.UQTheses assume that both "import typing" and "fromA * *" have been run in this filx0forU@estr"$('u[int]',`C) *)V*Tx O&  . 0?str 56inga1 a 1.[ba 1# Not syntactic$valid, but tOwillB be treatss d '<.H 1+*oPwith 7.subTest(typ= 04Q@datat & C0 x:F] 9# x is a, so C() takeYO arg5?C()NAnd it won't appeaAthe 's dict because,fdoesn'#YapNault@assertNotIn('x', C.__d#__?isnV%'t'&LW1t?var $M x1o /esx?Varj 4d6 class OC: x: typestr # x is not a ClassVar, so C() takes one arg.=self.assertEqual(C(10).x, 10)ldef test_initvar(4)q# These$s assume that both "import dataces" and "from(# " 5*" have been run in this file4for "('InitVar[int]',e Z( )( Q)Ru M% /.}|4?str vi5 i 5!.[ji 5# k# Not syntactically valid, but tOwillB be treated ass K.!+MPwith .subTest(\= 04@  '$an(doesn't cG a memberC RaisesRegex(AttributeError3 "object haU$ aK_ 'x'"@lC(1).x0/sn5V4'dc& xCes.x61 etyping+x Hr L`there K. xMHvar_module_level_ $ .;1 from . import dataclass_module_1_str from . -2)V.or m in (,,>. *2>2|>)):Swith self.subTest(m=m${# There's a differencehow the CQVars ared@ interpreted when using strannotations o;# not. Seel2ed s for details.|if m.USING_STRINGSac = m.CV(10)EOelse7 5Y assertEqual(c.cv0, 20) cdOInitc;IV(0, 1, 2, 3, 4)field_nam@('iv0', 'iv12/3'R= > BRaisesRegex(AttributeError, f"object has no a 6 '{m?}'"pt@# Si34s is an m, it's;3UinstaM10getF(c, {&P# iv4abnormalf In('not_iv4', c.__dict__E9I=g#_so it# won't exist on?Not!  TMakeD(unittest.CCasei@def _simple($ CEake_nO('C'.[('x', int)( B ('y(T(default=5))];  space={'add_one': lambda:v.x + 1} aC.@(c.xJ y), (10, 5)) self.a6ssertEqual(c.add_one(), 11) def test_no_mutate_namespace(self):(,# Make sure a provided 0r isn't G%d.8uns = {}C = make_dataclass('C', l [('x', int)( B ('y(, field(default=5))]; E=ns)'.aH{ns, {})>=bas/u Base1:PEpass&2&3+ 1s=(,&2)vc = C(2IsInstance(c, C$e(2e4@N\  x:K(?}  Pwith RaisesRegex(TypeError, 'required positional'"| ?1, i(c.x, c.y), ( init_var(<Ppost_!7, y obx *= yg+_ InitVar[int]  E{'__@__':} F2, 3Tpvars(c), {'x': 6},Alen(2q OCrO, 10 k('z', 6]?20)E ]-m1j 1j) se lf.assertEqual(C.y, 10) -se"qz, 20) #def test_other_params(5!):!GC = make_dataclass('C', $ [('x', int)( ('y', CUVar[int]6 z6field(default=20){ ]d init=FalseM# Make sure we have a repr, but no 7.INotIn('__"__', vars(C)_.+Z +Zqrandom   don't workWwith e%RaisesRegex(TypeError, 'unexpected keyword argument' 7[| # xx)no_typePoint', [nF'z']vc = C(1, 2, 3([c), {'x': 1, 'y':6'z': 3}<C.__annotations__F'typing.AnyQ  ~@)@}g J Q?int  Hqinvalid_specific  jfor bad_o in [( ?, 4( ] subTest(u=  8tA2r'I ,: 6LUf ['a',]Q# And )qthings no len()"KOfloa lambda x:x L]0hasYlen\(\)'):  make_dataclass('C', ['a', bad_field]) .def test_duplicate _names(self):*.Afor ?3 inRV'ab']"&Pwith :.subTest(4=N,0assertRaisesRegex(TypeError, 'F  /d'QU!,  ckeywor%@for'SAsync Await sUmust not be s >.} ['non_identifier$ () 0x,y*02@3little johnny table5[be valid /er9e-=22Aunderscora # Unlikedtuple, it's okay if es haveV# an p. '__$'aafunny_Q "# No reason to prevent weird >xs, sinctypes.newe allows themFaJ= NKC = :/X 'b2Equal(C._72__, 1) P +Replace(unit.CCasex @dataclass(frozen=True) 5 C:ix: intyc = C(1, 2L1 = replace(c, x=3self.assertEqual(c1.x, " yavdef test_(Q)Q@data2z = field(init=False, default=107t310) 1P/ (cPc.y, c.zAt), @, 10&0)? !c1B1C!1.D@3, 2@DWwith K RaisesRegex(ValueError, '5' 1, z=20, t=5Sg;b  # Make sure the result is still .0 FtInstanc%"cannot assign toq[ 'x'"5=F = 3we can't an attributpat does"eexist,# if we're alsoBging on; 8. Test thisChere, because settACs on.# i+s C andled slightly differen from non-ssx4Typn@r"____\(\) gyn unexpected "#"keyword argument 'a #3a=5 invalid_s__nameL S?JzJzm Doobject@U,'CKcr, 'dataclass instance'): replace(0, x=3) def test_no_init(self9@dataclass/O* C]ex: int$(y = field(^=False, default=100c = C(1)Ec.y = 20## Make sure y gets theOv value.@D1 = c5].assertEqual((c1.x, c1.y), (5, 10)# Trying toU y is an erroryWwith aRaisesRegex(VE06, 'h2, y=3,b;]?var;CJVar[int] = 100 d2VIs(c.y, d.y#gEu: can'tsCType1r"_X__\(\) got0""unexpected keyword argument 'y'"D 3x=5  ##9  ##: /ty: Init n4, 2# In our caK$anfh no-opS<$c, (cc5k\e7 if __name__ == '__main__'@unitN.() import enum 0insTpydoc ? threading from collections ZOrderedDict$kEnum, Int Meta, Flag unique, autoF$ioDStringIOdpickledumps, loads, P3ingHIGHEST_PROTOCOLA?0supudatetim\ delta try^except Ifx)" = None # for sWStooges(&XPLARRYI@CURL2MOE = 3 Eion as exc` =~3Int!o(int,  MOE = 3 except E ion as exc: IntStooges =R tryclass Floa# (f r, Enum)%DLARRY = 1.39U@CURLE2.72MOE = 3.142596 y#ag_(Flag| d # for pickle test and sub2sG0Str6M(str@0'acs only string values'XSName(H BDFL = 'Guido van Rossum;2FLU#Barry Warsaw' mPQuestB=$('', 'who what when re why', module=__name__)z T ~tAnswer |zhim this tzthere because'm E keTheorykkrule law supposip', qual='spanish_inqui  ^]?docG`Fruit(J`TOMATO.BANANA = |2CHE3pass def__dump_load(asser, source, target=None#if@ is \-# =>Irotocol in range(HIGHEST_PROTOCOL + 1`I( s($s(pO= $)))8ionS, objz"Vwith YTTobj, " TestHelpers(unit!.4Cas# _is_descriptor,Ssunde d  ~ 4W(self~6foo/ @attr('__get__','__s delete__'\<obj = foo().<False(enum.( 7t , <, 1"#lfY?TruX &J "s a_(=_aa wU"))SaQW #__k _ak% '_a_', '_',  '__', '_8): ,self.assertFalse(enum._is_sunder(s)) 2def testd7elfPfor s in ('__ama &~v7TruuY!))t,Vaa !__b{+%',MQ#3! #s class TestEnum(unit7.fCase):P`setUp(!ApSeason(DSPRING = 1SUMMER = 2AUTUMN = 3AWINT.4.w2 = vKonstants(float, E.7182818^D PI.14159260TAU7U * PIs5 = Grades(Inu 1UA = 5UFB = C $D UF = 0x2 = Directional(str/AST = 'east'^"WE,wePNORTH5Znorth62SOU8sou7 = from datetime import Holiday(+qNEW_YEA{013, 1,IDES_OF_MARC2'*l3 = qdir_on_ O1 = JeEqual(set(dir(5*))H2['_vs4doc umembersPodule dh'  +'] OitemF. ` 'name_valuewith_added_behavioru2@this.;thacRthese:oseI^@wows return ("W'! I'm %s!" %nm QSq, d s__', '__doc__', '__members_Rodule@this%these']), )self.assertEqual(3set(dir(Test.[)Q%['__clas2doc7__m@nameAvalu owowserdef test_dir_on_sub_with_behavio@per(!):6# see issue22506 SuperEnum(8<vinvisibleY!return "did youoMme?"ibb(q lsample = 59!Su].E>enum_in_u.SUMMEReAUTUMN0], sLfor i, sB0in (rerate('` X P H'.split()Rr&(i e, getattrc<9b#No~?e, & e.A} mDIn(ePIs(type(eV+InstanceX1strZ'bC.' +f9 T1repO#''.formapXX |_d{'7 , 1) with self.assertRaises(AttributeError): Season.SPRING.name = 'invierno',w\.@valu]!2 U def test_changing_member(" =A(`WINTERreally cold'a;_deletionbclass W(EnumYE = 11UMM~2AUTUMN = 34BDspam(clsxFpass1XTrue(has(0, 'J5'))z3del.IOFalsJ3!EN5?DRYK57ibool_of_ 5_Empty4nY(;/))tIo Countuzero = 0} on  tw(Bfor r2 in` c2 invalid_s7FVY_Wrongm9c@_create_= 1IhAget_mixins_ = Kfind_newjK1anyj9 %# plain s are always E"_Logic"!tr 36f1 = M W.DT$P%# unless overriddeneAReal_(Enum):  true = True @falsF def __bool__(self): Apreturn %#._value_)*9p.assert|(RealLogic.()*# mixed Enums depend onv-in typclass IntuQ(int,: E = 1yE = 0 X (S!) Qatest_containsCSeason = w:Y2In(.AUTUMN, 4BwithF2Warns(Deprecation7ing} dNotIn(3[G''bSval =&(3 ?val<POther1( on1; two = 2x`GK.twomomemberU Raises(TypeError, lambda: 'B' inK3F2M4compariso  SPRING <"q.WINTERU*2> 4JNotEqualy3, 1/{OPartv2 tICLIPJBARREL = 3{.h5*!< Tenum_duplicate mSUMMER+b = FAL&E = 4ANOTHER_ ylst = list/ TIlst,[v#. ++ +]#Is.AAUTUMN) self.assertEqual(Season.FALL.value, 3) /oAUTUMN1 #Is]S(3), h9a010oSPRING0rname, 'd'5 [k for k,v in __members__.items() if v.h~ != k],J'K'rNOTHER_',!) ?def test_duplicate_b(}!):#Pwith Raises(TypeError+/class Color(Enum#ured = 1bgreen = 2blue = 3K4Drw% 9weason.SPRINGS))) !self.assertEqual('{:<20}'.format(Season.SPRING),9@ 9;str=1)) ?def test_c_enum_custom(!):'[class TestFloat(fg, Enum&*one = 1.0<{two = 2_~_tk, specTBreturn ' success!'j EA9o.one),JF}wIsValue, member }.  .v\ 2dat}oHoliday = y  c'{}', /.IDES_OF_MARCH >:?,*^B.>B.*_%Y %mK,Do %M:00Jj XKonstantsZIq \1O.TAUT7 9 D: <: 4: n8 ?5.2:$f8H=)EgLhashdSeason6dates = {}[(.WINTER] = '1225'&aSPRING&?031&3UMMLO0704LaAUTUMNLF1031&HaEqual(71, '6!) 1intfrom_scratc)class phy(int, Enum.api = 3Ztau = 2 * piTrue(phy.pi <]O.tauinherited0Int5ass37TOfloal0n.1415926v6zx Fz3|;~G1str?str6'Pi}F'Tauz 1Strxv7t5def test_intenum(self): class WeekDay(IntEnum 'SUNDAY = 17#MO2BTUES/3DWEDN4CTHUR352FRIJ6RSATUR%7 .assertEqual(['a', 'bCc'][.], 'c')?i for i in range(A)], [0, 1, 2])lst = list2flen(lst), b)1 '6, 7*Ptargez'  p`P' L v.split(l, weekday"enumerate(3;, 1F5e =hiKJ ?e, # oint(e)(ee.nameyTIn(e,&Zlst.index(e)+1 True(0 < e < 8WqIs(type "IsInstance?intV*def test_int_duplicates Y3TEU*RHn$Is.,.8^83(3)d'4W kW0k,v7C.__members__.itemsmAif viP != k}'4',  from_by IsStooges.3b'\x00\x03Fbig'), Int+6MOE!Wwith VRaises(ValueErrorHs5s Bfloa7a2['m%']tAldunder@ASeas TTrue(', '__eq__')tPitera?_oru{SUMMER = AWINTAUTUMN = iSPRINGHRlist(-),[.#, ]N 5reversed_> O.)P . " %]% programmatic_func:'SummerMonth'june july august'K lsI !len(lst), i)5 +X, 3,  p[8. J. .august],  Ylst, E )*for i, month in enumerate('june july august'.split(), 1):B\e = SummerMI&(iaself.assertEqual(int(e.value), .#No1e& Tce.nameXIn(e,*ps(type(!) "def test_programmatic_function_string_with_start(6R = Enum('>', !, K6=10lst = list(? w {len(lst), 45 +?, 3E p.[I.d J.q ~]C0t0[ ly&']@*2C) self.assertEqual(len(SummerMonth), 3, # +se;!' [8Y.juneJZ.julyaugust],J>lst)'for i, m in enumerate('w j ]'.split(), 20):C8e =&(ib int(e.value), .#No]e& ce.name:In(M*ps(type(!) def test_programmatic_function_iterable(-I = Enum(O&'%'(p', 1), aly', 2 J, 3)]lst = list llst), U51kfrom_dict@OrderedD^ th)  self.assertIs(type(e), SummerMonth) )def test_programmatic_function_:M!):/3E = Enum('', 'june july august', JU=int)Hlst = list(? wEqual(len(lst), 45 +;, 3 p[I. J. -],J>lstfor i, m in enumerate([.split(), 18e =&(ia ?e, #S.nameOIIn(e *-_with_start( !, U6=30?'30from_subclass ?IntaIW self.assVertIs(type(e), SummerMonth) def test_programmatic_function_type_from_subclass_with_start(self): H^ = IntEnum(' ', 'june july august', sNA=40)Klst = list(? self.assertEqual(len(lst), 45 +;, 3$ p[I. J. -],J>lstfor i, m in enumerate([.split(), 40)8e =&(ib ?e, #S.nameOIIn(e *s1.__N.p@propertyjhEAE # () is updated to includeUFtype infof"{}({!r}, {})".format(7,N ;_<<i4strS# str#nchanged, even if it relies on0l() fallback-Bbasep_str = & ._ -__(!if c.__objfnobject\ c+g &#8simplicity, we only de`fine operator that  # propagates expressions% def __add__(self, other):&Vtemp = int)1) + 0 /if isinstance2, NamedInt) andt ~ereturnF(t%'({0} + {1})'.forma.__name__/),M)Oelse 8 7class NEI(k, Enumib__qual = 'NEI' # needed for pickleutocol 4h-x = ('the-x', 1yvy', 2) .assertIs(NEI ew.P1EQ(repr90x +d.y), "1('(0 + y)', 3)"Pglobals()['4E'] =)"EI$%EI7NI56('test', 5j 9NI5!3_g_dump_load",, 8YEI.y.valueoa3Is,C4)31subes_with_reduce_ex&oG(int 0__n`(cls, *argspt0 =  +;#pif len(?o) == 0aise TypeError("[ must be specified$- /Q._intk = %@ = _ #O c_protojH1.__ X.z@_Oertytoh ENE # () is updated to includebPtype infof"{}({!r}, {})"37#9 BF;u<`int.__))  def __str__(self): ## str() is unchanged, even if it relies on the rep.fallbackObase = int0 = &. (!if +.__objclass__nobjectareturn<0.__ c+g & # for simplicity, we onlyT in e operator tha # propagates expressionsd3add, otherBtempV +b(0 U sinstance2, NamedInt) and it ] F(tx'({0} + {1})'.format.__name__/),M)Oelse 8 7@T NEI(k, Enumib__qual = 'NEI' # needed`pickleutocol 4h-x = ('the-x', 1yvy', 2) .assertIs(NEI ew.P1E(90x +d.y), "1('( +-y)', 3)"Pglobals()['4E'] =8)"EI$%EI7NI56('test', 5j 9NI5!3_g_dump_loadD",, 8YEI.y.valueoa3Is,C4)31subes_without_directbsuppor$5~G(int '&0__nJ(cls, *argsK)_0 =  B;#pif len(?o) == 0aise TypeError("[ must be specified /Q._intk = %1 =  #5O @IertyytRE#E#is updated to include the name and type info return "{}({!r}, {})".format(7(self).__M=__,B Q =<%int.__repr__)}def __st:# str() is unchanged, even if it relies on0l() fallbackObase = int0 = &. (!if +.__objclass__nobject\ c+g; &# for simplicity, we only defin e operator tha # propagates expressionsd3add, other)BtempV +b(0 U sinstance2, NamedInt)it ~S2F(t%'({0} + {1})'& )1 dOelse 8 @T NEI(k, Enumib__qual = 'NEI'Dwx = ('the-x', 1yfy', 2)assertIs(NEIBew__O1E(90x +d.y), "1('( +-y)', 3)"Pglobals()['4E'] =)"EI$%EI7NI56('test', 5j ?NI5! EI.y.value6h\_pickle_exception.KRaises, TypeError,xCPg6ingGF1subEes_without_directsupport_usingb@sG(int  0__n?(cls, *argsKO0 = ;#pif len(?o) == 0q ("[c must be specified6  /Q._intk=% = _args  return self @propertydef __name__(4)): >RP._int. %EOreprE # () is updated to include the X and type infof"{}({!r}, {})".format(7.,BF<%`int.__)}%/st$ 3str#nchanged, even if it relies on0l() fallbacknbase = intp_str = & ._ -__(!if .__objclass__nobject/{3\ c+g &# for simplicity, we only defin e ator tha # agates expressionsd3add, otherBtempV +b(0 U sinstance2, NamedInt)it ] F(tx'({0} + {1})'& )1 dOelse 8 @T NEI(k, Enumi`__qual__ = 'NEI'Dwx = ('the-x', 1yZy', 2reduce_ex[protojgetattr, 1.__1__,j.C)gassertIs(NEId ew11E(690x +2d.y), "71('( + -y)', 3)"Pglobals()['4E'] =}O)"EI$%EI7NI56('test', 5j ?NI5! EI.y.value\_pickle_dump_loadqK, 43tuple_sube` SomeT((.4'> # neededutocol 4-Pfirst@1, 'fmoney'n)`second*2, 'for the swhow')  third = (3, 'for the music)self.assertIs(type(SomeTuple.first), a 8xInstanc;second, tI7WEqualm,@globals()['F'] =test_pickle_dump_load( ?Adef ?duplicate_values_give_unique_enum_itemsV!):<class AutoNumber(Enum $\8__new__(clsdQ` = len"P.__mes__) + 1-obj = object.\*.A_ = i $`returnO \int__=:1int"j/L bCVlist(-),"[,. ]IgUO), 240r.^?, 34'Is9(1)i)inherited<from_enhdsN WColorA!re^greenJblue sA), [ b.red, Y O]yLsmap(int4)V1, 2, 3]@Omixe=?Int@F)in,4objfgolor), [Color.red, Color.green blue]) self.assertEqual(list(map(int4)), [1, 2, 3]) <def test_e6@ity(J!):\class AlwaysZ@a__eq__9w, other@%return True\OrdinaryEnum( >Ua = 14 H(), N/.a! ),,()ordered_mixin#O#)/ge)1if !__XR__ isV. _c>value_ >=<H15NotImplemented&t]4ls] %r"L % (a, e)% Po yred = 1S@gree20blu(3BwithwR&s( k8 @gren2oPlanetMERCURY = (3.303e+23, 2.4397e6xxpVENUS ,4.869e+24, 6.0518,REARTH,T5.976,\37814-0MARXYR6.421l3.3972,pJUPITER, 1.7, 7.1492e7aSATURN5.688e+26<268,1URAp= (8.685 L5559,rNEPTUNE2024Xl2.4746,9mass, radiu$1 = |0 #bkilograms T# =] 6Zmeter3@propertyIsurface_gravitQp# universal +ational constant (m3 kg-1 s-2FG.67300E-1 2G * !/ .cC8bround(.., 2), 9.80G A?, ()QgnoreMeriod(timedelta,  'G''  different lengths of time&'6ef __new__(cls, value, period):=nQobj =Xndelta.=)4!._Y2_ =b$u# =~ $return objp_ignore\!'P* i|:rs(for i in range(13@ ['month_%d' % i] = i*30,  s W5W JweekV@7, 'T /329daySj, 'dayPOneDay = -1TOneWeek = _M 2 =  self.assertFalse(hasattr(C4, '&')6?4i/True(isinstance.,=.C is D/309T48A28) def test_nonhash;(% class AutoNumberInAList(Enum'Q "p = [lenP.__meVs__) + 1]+ hobject*EColo kred = ^greenJblueapEqual(lPH), [i.red, n k]Cenumm|Hzip(G,+3)6+= sg `.-1, [ 2)Is|(0 , F conflicting_types_resolved_inJLabelledInt`(int, {, *args%0, lX0 = &)inwNDobj.OP@  unprocess1, "Unprocessed")   payment_complete = (2, "P# CD") 4self.assertEqual(list(LabelledList), [.unprocessed,  /])h 9 S16;(1)Gdef test_auto_number(%):class Color(Enum&`red = @(0blucVgreen5jymzf .rW b,.TQ 3red.value, H -`.2 ./3a?ame__generate_next_ _(name, start, count, lastpreturn 2m_'red'' 3 ''_inheritAutoName49F oogarbagq f-e1_corrected 2" 8t@Tlf.assertEqu al(Color.blue.value, 2) self.assertEqu.Tgreen/13) 0 def test_duplicate_auto(D!):#Vclass Dupes(Enumfirst = primero = E%osecondOthir [.p,.XJ], list(.R)) TestOrder(unit.kCase):same_members _od_ = 'red y 'Q9= 1,9= 2<O = 3_with_aliasewrverde = BrongD y  RaisesRegex(TypeError, '  does not match Z+_'": + _has_extraz purple &:  -B  Oenumjc:*K = 43}@oes not match _order_'): class Color(Enum*: = 'red green blue'J+ == 14== 2HM = 3purple = 4@verdV2 TestFlag(unittest.CCase0"""s of the -as.""" bFPPerm(5pR, W, Xh, 2, 11; 2BLACK = 0ZD8ED hGREEN @BLUEc3PPURPL@RED|wMOpenOsW)RWo)ACwCiR1<<19f@def E_str(self$0 = . assertEqual(="b.R), ' /')0W0W0X0X0AR | i/R|k;D}OR|W|5(0)0 ~Cd33 ( Wo <EXE'(~Lc( "0.RO  'W2/WO2%ACd/AC2QRO | n%CE</CE<W<|~rCE|AC|RW<OCE|Rdr #~("#_? %?5?rep(>< O: 4> 66OW: 26l(repr(Perm.X), '') self.assertEqual(repr(+AR | W?oR|W: 6AJR|W|X: 7L6(0)O0: 07~R7p39 OX: 59 .~q BrK87((~p9qOpen = @  R#1.RO ,W8/WO8&ACpOAC: 8QRO | &CEBCE: 524288 =WG|J9J~K:CE|AC|RWG9GIRCE|RW9OR!~(? YZE WE2Pdef test_or(!): for i in04jb F(i | j),K(i.value )?C1., D?CyIs(typet DFi, i;=  9.,P 3?andARW =R.N-RXXWWRX's = list) + [RW, RX, WX, RTE(0)]`oBZY|(i & j)2& j self.assertIs(type(i & j), Perm) for i in: D?Fi, i;$?RWX& jRWX & LqOpen = s a.RO & 2CE, ARO) 3def test_xor(<)d 1j:bgEqual((i ^ j).value, i  > CD(^?(0) _(0) ^+^&CE"3Is( 2oinvertARW =B.R | W-RXXWW: X's = list(V) + [RW, RX, E(0)]}_~B-~i **~~_hf 94 W~&7.WO 3 1WO|1kCE) & =HqOboolffTrue(fO"Df", ) programatic_function_string`Flag('', 'R W X'9lst< zlen(lst), P)G.$<, 3-Pst, [/".R-#.W&X]eN@i, nenumerate(.split()v = 1<1-`.2./4a}_garbag 9RsRegex(TypeError, 'Invalid Flag value: .not an int.'): class Color(Flag*vred = 'E'B#blue = auto() def test_cascading_failure(selfhBizarreQc = 3Ul4Uf = 6## OE.c | d .assertRaisesRegex(ValueError, "5 is d validG$", O, 5)Sm22S@11Sduplicate_ Dupes(Enumufirst = primeroPsecona OthirqEqual([.p", XJ], list(!)wbP^mbm mmb Srepr((7)), '<.d|c|b: 7>'@support.reap_threadsunique_compositA# override __eq__ to be identity onlyS@Testp'on3/tw4Ofour+?fiv4?six3_seven@eighx{w, otherpreturn '8%Jahash__LE%#0._vW_ # have multiple >@ads Peting 0leter member!!seFset(aiUFalsecycle_enum(nonlocal >6f:try7for i in range(256R%U.add(u&i)"except E?ionm1ail6Tru:9= [ threading.Thread(target=cycle_enum) for _ in range(8"]4with support.start_ti#s(%):-hEpass# check that only 248 members were created3self.assertFalse(^}failed,'at leasj"e  -S whilling composite'Equal(256, len(seen), 'too manyG') class TestIntFlag(unittest.CCase<0"""s of the 0as.""" LSPerm(;X = 1 << 0,W1R2S_ColorTwBLACK =S0REDBPGREEN = 2BLUE = 4PPURPL@RED|zOOpeny)ROvWreAC = 3pClR1<<19i@def p`_type(6M0 = . F 8f8/ FTrue(isinstance(f, 0)b1ff, f.value)% VSA.W |\-.Xd;` 13h0<Sa.WO | 1RW, f ) 33h?str b=AR 3 0W0W0X0X0Ri/R|k;D}OR|W|8?8|R5(0)3018181 ~b3D3 3(pWo < | Perm.X)), 'Perm.-8')  self.assertEqual(str(~(P)R | 8)), '?W|X9 (6(~04/R|6j6qOpen =  "0.RO  'W2/WO2%ACd/AC2QRO | n%CE</CE<W<|!(4|4p ~'CCE|AC|RWm<M_CE|RWrQ#~(STE \E'(~[ )def test_repr(!):2 ( ># .R< O: 4>\ 6W6OW: 26X6OX: 16:uoR|W: 6A1 | J?: 7L8o8|R: 1(mO0: 0t(7O8: 87~W|X: -5: j:3: Z?: -"W]} C_-8: -> D1 <f-((~=9. #< ,')  self.assertEqual(repr(Open.AC), '< r: 3>') 6/ 8QRO | 6&CEBCE: 524288GWG3|WOJ9J6(4)O4: 47~&RO8CE|AC|RW~/-1CWCoRW: -2=?- B~Q QK/90U((~ V5Cbdef test_or(j!):}bPerm = for i in 04jb i | j, i.value  7 ;(<)0CsIs(typeD, twrange(8  T5= nqj | i, sf (/k=0)eaFY!Is Ji, i$0$ 0H'  ].,u 3E?andFARW =xB.R | WN-RXXWW:RX'ps = list() + [RW, RX, WX, RE(0)]}BY[8i &2& jY, 'i is %r P' % () X(Ya`0a %r' % (i, j)7) for j in range(8):*self.assertEqual(i & j, i.value T56)4=sIs(type>o, Permnqj & i, s5(/=0)aia ]Y!IsJi, i$7$ 7HqOpen = K 0Is(a.RO & 2CE, ARO) 3def test_xor(<-d 1 |1 :b x^x?^ je(i ^ jCD F X = n2j ^F^f k6k0F)?^ 0" 0"'^"&CET6f:tryiUrange(256R%U.add(x&i)"except E?ionm= True  threads = [ Qing.T&(target=cycle_enum)4for _ in range(8"]4with support.start_s#s(%):-Epass# check that only 248 members were created3self.assertFalse(^}failed,'at leasje5 -S whilling composite'Equal(256, len(seen), 'too manyG') class TestUnique(unittest.qCase): @def !_u)P_cleao'lf]@1_C+E uone = 1/3two = 'dos' re^54.0noer(Ints^singlvAdoub2^1rip3`dirty(#RaisesRegex(ValueErrorres.*one'>w KDq#OSW > 'T".*s.*turkey.*tU'it ]M = 3 7\_name oSilly(ol.*\ov = 4 expected_help_output_0doc"""\ Help on PColormodule %s:(#.-R | v , s=None, *, mC Ctype &=1) |\x20[0An meration.Method resolu"q order:<Kbuiltins.object`Data and other attributes defined hereoZ0blu<~.L: 3>]green = '=: 2(6red&mred: 1$---------------$' | Data descriptors inherited from enum.Enum: |\x20:Aname The  of the 2 member.9Jvalu:;$ 7MMeta"__1s__NReturns a mapping'!->MLEThisGlists allWs, includialiases. Note that thisOiread-only viewinternalnD.""" expected_help_output_without_docs = """\ Help on class Color in module %s: c(O)0(,$s=None, *,C@qual`Ctype pstart=1PJ[Method resolution order +builtins.object@and other attributes defined hereo blue = <.L: 3>]Vgreen'=: 2(6red&mred: 1$ $-)  $ 7 TestStdLib(unittest.Case): KmaxDiff = >(!):+/1E = 2&B = 3K@def x_pydoc(selfN# indirectly'a __objr if Str ._Q__ is+utext = @% __m0els PGW /s T =uingIO()0Qer = ".2er(2= -G.Presul4A.get().strips.assertE(<,1)0insgB_get(spmedict(( ('__class__', EnumMeta), q('__doc''An enumeration.'0bmember[self.Color.__9Qodulel__name__*wblue', \+Zgreen,-s.__dict__[']1:red\?red)"vaj[\%))result = (inspect.getO(6assertEqual(ls.keys(), Vmfailed = Falsefor k in F: 6#ifUc[k] !=+:[k]'+fprint(vp'\n%s\nb key:  ex"ed 9' %>('=' * 75, kF[k],$, #)XNp=''6Tru2if  "(" does not e p!e above") def test__2ify a_attrs){# indirectly>a __obj;!__XSfrom X import AttributE = [9=-(3='_Okind='data'Q=defining4=object, =$vtxproperty0 > {}?', u0.UK |}>V~;C v Enum, object =Enum.__dict__['name']), Attribute(#='value', kind='data'5Ddefining_classp, object }T~]$s.sort(key=lambda item:.)0result = list(inspect.2ify_attrs(self.Color)@pfailed = Falsefor v, r in zip(", %):)3if r != vprint('\n%s' % ('=' * 75, r,o), sep=''M6Tru2if  ""(" does not equal ex_ edp!e above") v MiscTestCase(unittest. @def q__all__support.check$`, enumm2# These are unordered here on purpose to ensure that declaration 3a # mak difference. CONVERT_TEST_NAME_D = 5CBA is one should o firstE7F{e0IntConvertc)__lookup_priorityatype =.n#._G(#'UG ('X._', '__main__')[__F__==]dfilter1x: x.startswith('' # We don't want the reverse  Lvary when&r}# multiple possible s ra givenKT. ItgalwaysG reb lexigraphicalTgUcase.<passertE(S1(5)9*, AA') DQO&En!has all of@desia2ands}.|sF-8A.e.CONVERT_TEST_NAME_B, 5) self.assertEqual(test_type.CONVERT_TE;C;'D;'E;# Ensure that  only picked up names matching the filter.[5A for>v in dir5<!if4[0:2] not=('CO', '__')],w6 [], msg='NPother)n * found.') if __P__ ==dmain__':h@unit.() """Test suiteprofile module.""" import sys UpstatZos from difflib @unified_!$ioStringIO1supw>rFN, run_q, unlink6wcontextrumanager6lefunc, tim: class P8(.qCase): iMr3#= .= $g %`methods = ['print_s<{callersAes']Dexpected_max_output = ':0(max)'def tearDown()+Z(w)0Eget_]Y ;return _O~B@2do_$wing(clsaresult-p = cls. 2ilel(v, 0.001astart_" =(B.runctx("()", globals(), loc 7r.appendzW() - n.@ sxy0 .S(, stream=sw1.strip_dirs().sorOA("sti"5getattr(e&, ) = s.getvalueaplitlines/1mod0estc2.__P__.rs9('.', 1)[10# Ocompare again originat}eI Prevents outside code (e.g.,#io!) NqcausingCD# un I:puth[ !.r!()l$ ifp0in  p'\n'.join(A)~1wf _cprofile(self):# results = self.do_profiling()&expected'Dget_w_output.JassertEqual(e[0], 1000Yfail = []k for i, method in enumerate(Xunames):6Da = ['W!Db = :i+1if a != bU8.append(f"\nStats.{c"}  "<1f"{berclass.__O__} > "does not fitvation:"Qp0extunified_diff(a.split('\n'), b lineterm="")q0if l 6("\n".join(1)) cdef test_calkp_convens# Issue #5330: =q and cP e wouldn't report C funcO c!edw # with keyword arguments. WeA all5Ging .C1stm2[Y"max([0])",,tO=int!**dict(key()*d/,) j A/, ns = StringIO0 #il(timer, 0.001I4 .r x(n, globals(), loc 3sA = p .(p, stream=s1q.print_4 !re.getvalue!In.uC_max,i "Z{0!r} dimax:\n{1}".format=res:"ru~*wsilent(y`moduleh("int('1')C,0, ffame=TESTFNb=True(os.path.exists(/ 7elfPctx("Y?()"@ Fh &/ *Qregen ubD, cl% =.rstrip('co') : print('Regenerating %s...' % filename) results = cls.do_profiling() "0new3Q = []with open(K, 'r') as f:#Zfor line inS.append(&!if;p.startsq('#--cut')b*abreak y+ w`.writey#s(fP("_Pr eOutput = {}\n")or i, method@enumq e(N!sb'b[%r] = """\\\n%s n(`,g[i+1])'\nif ____ == "__main__":\nR()\n') @contextmanager def s4#t(AstdoBsys. 6try = StringIO(Qyield7ofinall;`Atestrun_unit(aTest) 0if '-r' notBargvD]FelserLe_expected_o0(__J__,  # Don't remove this comment. Everythbelow it is auto-Bed. -6 r !['@t_stats'P 28P7.9726_0.999Gee.py:110(__getattr__1 269.996 999.769 K025(CfuncG23/3 149.9376.519 1Y1x56.639 G35(factorialH 20 19.98  HV48(muB 3B6K93 599.830 299.91555(helper 4 115.984X81611E#73E1FP-0.00 '4)73F#84F2_indirectO8 311.97=3A7 3j8d$88O F3 63FP 7.99Q79.96t c98(sub#?"""gcaller2:0(^))<-D0(4)4 :0(exc_infoKI0hasH I  profilee.py:88(helper2)(8) 399.912 $110(__getattr__)D <- :0(has@)(12r11.964 " cb98(sub@)(16Li79.96025(testfunc"a<- :1()(1) 999.767F35(factorialG)<-kJ9 o(20) 16f7L$84_indirect)(zy139.946W48(mu/ #55y1 % 4~9#73JJo(4) 599.83   HHH H1 " ` b""" _POutput['print_callees'] = """\ e )-> 27.972 O 66 tR)->[J! p&^ n "+hj 19.988! J#+ 1n!  h(T ->qappend)y -0.004j  &  :0(hasattr)(8) 11.964  profilee.py:98(subhelper)(K79.960 &c8-> %110(__getattr__)(1627.972""" if __name__ == "__main__": 8() # # multibytecodec_support.py # Common Unittest Routines for CJK c6ps # im9$os$re %syuX from http.client @HTTPException&$io6BytesIO class TestBaseencoding]= '' # 5$% = None(tuple (with 4 elements);Gtstrb;must set. 2 $Qs to StreamReader GsG#@8roundtrip<1A#zE if is possible 0uniSGhas_iso10646@0= 0GUthis Ncontains whole 91mapNpxmlchar_(refreplace>unmapped = '\udeee' # a  point thatBnot <.V0def Up(self)i0lf.Ec;#2 =0rs.lookuM.2Fe = @+(d ((r% (s? .owriter. .Aincr"al : @@ b_chunk X!_lE= []|for b inc) 6b.split(b"\n"^qlast = *Z.pop(rassert &U= b"">@1 + a*"inY5.0nd(0L$native, utf8Yzip(*=5ug(A:)[0rEqual(ud.7'utf-8') ,K o ],` (u)errorhandle source, scheme, expectedusif isinstance(Gs@func = self.decWode Yelse:func = self.enc5if expected<result = E(source, scheme)[0]m!if+2 isq deqYassertTrue(type(r)AHtr, )o GSEqualC,,7; B'%a.(%r, %r)=%a != %a'B&% #n4ing2", % )X _bytesZ]zZVRRaises(UniaError,+,  5 def test_xmlcharrefreplace(V)"if3has_iso10646skipTest('Sing contains full ISO =b map')? = "\u0b13260 nd eggs")R|me(s, "" b"ଓ 51N912;{6ccustom2_v?elf9Y from html.entities import point2namekG(excMif not isinstance$$, _e 8<rQ Type"("don't know how to handle %r" % ~ Zl = [for c in-.object[exc.start: Jend]if ord(c)< -1l.append("&%s; 6[O]T1#%dUF Ereturn ("".join(l),Sc.endcs.register_e (".>", N%J 1sinFqh. else:  sin = "\xab\u211c\xbb = \u2329\u1234 6a" 6 sout = b"«ℜ&r = ⟨ሴ6ng;Aself.assertEqual(encode(sin,kw "test.xmlcharnamereplace")[0],!) J@def -_callback_returns_bytes!):+a/#myNG(exc =@ (b"", exc.end)Bcs.register_error(0cjk5", d9henc = r"abc" +unmappedunic + "def", [Mm`enc, bX@'wrong_object'&?ret#1for ret in ([1, 2, 3], [], None, +() Raises(TypeE,_ l '.'RlQ_indexv%'x', intv>w"o'abcd'o'efgh'  9; 'A, (b`xE3 9);0sys.maxsize + 1;1I21 _./GBA5Oward#&ifr.limit > 0r%E-= 1}!'REPLACED', 0d#Nelse^9TERMINAL' 5= 3$ self.asser tEqual(self.encode('abcd' + unmappeduni + 'efgh', 'test.cjk.')6!(bpREPLACED| TERMINALQ 9)) @def __callback_forward_index!):+/myreplace(exc return ('', exc.end + 2)Ics.register_error("5", k9Y_asser] oI A_outofboundL&f', 100@1Raises(IE,   aincrementalarUTF8Reader = Agetr('utf-8' for sizehint in [None] + list(range(1, 33)) + \{[64, 128, 256, 512l624]- isFm = (BytesIO.tstring[1]);o;0 " =* 0zwhile 1i'if`s not )-sdata = .g(P p.OelseH^9!ifvH]breakCe = eCe.write(e 7/getvalue()#0]C_ deW rO, -1Q& (X%Cu = .(  ostream.write(u) self.assertEqual(/getvalue(), %tstring[1]Cdef test_incrementalencoder_error_callback(A%):yRinv =Vunmappeduni:e"^%()JYRaises(UIEEB, e., inv, True!e.s = 'ignore'`K(JY, b''PWreset*mpreplace(excreturn ('3ed', exc.endcs.registc ('.$ {U', tezNC u# againJt-^2st_lreadersPUTF8WCr = K1getr('utf-8'for name in ["S1", Hline 6s"];sizehint?None, -1] + list(range(1, 33)) + \@  [64, 128, 256, 512, 1024w7i:er(BytesIO.60])<6 = /?0func = getattr(,:^zwhile 1.wpdata = R(>C*pif not 1K%_breakW?&==/s"J? s({OelseKF rQnf ('1',  sRY ??e? $q '#Y+"1" ,cb#K4if 1 is[ W data = func(sizehint) _else:-&daH/) 'pif not *H_break?ame == "readlines"Jostream.write-({! KF self.assertEqual(6getvalue(), %tstring[0]*def test_r_reset_no_pending(=) # Issue #23247: Calling 8() on a fresh S W r instance# (without ka) mustUcrash0 = BytesIO(T" =(0 %. class TestBase_Mapp@unit.CCasepass_encQ = []+devsupmaps'#co$<\setUpd6tryqr.open_m_file().close() # it to report the error earlysMexcept (OSEq, HTTPE3ion)z@skipq("Couldretrieve "+$0map7url_,creturn supurlresource.[  ["if>P.endstw('.xml'_XG_ucmlx.8gplain($B`unichr* lambda s: ''.join(map(chr, eval, s.split('+')))Purt_wg&{}j) as fz@for < in4^" 8Z! =Yp#')[0].3p()Lbif len_ != 2wcontinue=!cs0 = >I4if +<= 0x7Fjsetch = b$([5~& 0xff]'el[>[!10`(a>> 24), (B16) z%), >8= VOtch = bytes([(csetval >> 16), (8) & 0xff), <6-])7Uelif u= 0x100:'m&ch = bytes(8!n /se]ontinue {1univrs(data[1qif ord((0) =fffd or  in urt_wa 5[E1] =/.chself._testpoint~2ch,~)0Adef #_mapping_file_ucm(?)Pwith Y.open/v() as f,0ucm = f.read(uc = re.findall('', VLfOq, codedTc@chr(@uni,D?N.fromhex(d*4W?odeWy'supplementalZ~`zsupmapsz*6 .,P;if E notpass_enc5)W.assertEqual0.en+ Ding)Aw/dew5strv_errorhandlesource, scheme, expS` if isinstance(GGc;0fun'0.deV d/el 7e7%if u2`result1unc/#1+True(type(N) is str, GfCrC '%ae(%r, %r)=%a != %a'@ %% |4ing#, O% )e@lt))  self.assertEqual(result, expected, /  '%a.encode(%r, %r)=%a != %a'B% (source, Ning, scheme, O% )))3Yelse:t Raises(UniError, func ) def load_teststring(name)idir = os.path.join( 0dir)(__file__), 'cjk"s'with ope9FPdir, @ + '.txt'@rb') as f~Ped = f.read(W_-utf8\ Ysreturn w , $ import fractionsoperatordrandom%sydstructDtime @unitp from  y0sup._grammar& (VALID_UNDERSCORE_LITERALS /IN<)vDmathiisinf, isnan, copysign, ldexp INFVloat("inf") NANnan") have_getformat = hasattr(f:F, "___") requires4 = 6.skipUnless(Zg"c |s| 2$ D #locate z b4 K values _ 0 orrcurdir E` Q2, '*{/Rcasesq class F1Sub[Dpass&_Other+qGeneral-Cp(@Test1): &()| A&q3.14), F, +B14.0,!" T? "^ VB, " 0x3.1A: -;/p-=#+=' ++H"%+-7 self.assertRaises(ValueError, float, "-+3.14") oself.a7-7"O.nanl_+.inf6.2-3 ;Typ=/{}7gRegex(5"not 'dict'"C# Lone surrogate'\uD8F0'(# check that we don't accept alternate exponent markersw"-1.7d29n?3D-xaEqual((" \u0663.1p4 "),  A\N{EM SPACE}2NF # extra long strings should be a problem*b'.' + b'1'*1000 ?def test_underscores(!): for lit in VALID_UNDERSCORE_LITERALS.2!if`any(ch8?G'jJxXoObB'f8}Hlit), eval( 48 lit.replace('_', ''))J_in IN3P('0_7T09_99'): # octals arerecognized herbzcontinuM4P# Additional cases; nan and infever valid as!gerals,J@only2the() construct(buWllow Jin or around them.W'_NaN5?Na_5OIN_FjO-_IN6 GINF_l9# Crhandle bytesues correctlyBb'0_.\xff9') }; non_numeric_input_types(selfC): 0# Test possible non-numeric types for the argument x, includingHsubclasses of2explicitly doc=ed accepted_.B= CustomStr(str): pass#pBytes(b' QArray+a /Wfactories = [!_,G lambda b:b.decode())- memoryview]6tryQfrom r import 1 ex! IZError@ zJelse5.append(u('B', b)) rJUf in < Sx = f(b" 3.14 "):with self.sub(7(x)('rtEqual(float(x),\ Y1]6RaisesRegex(Value!, "could not convert"Rrf(b'A' * 0x10 def test_$_(P.1b'12.3')[1:4]), 2.3?O\x00C, @,A@,4@:he_messagee&wcheck(s{ Qmsg='(%r)' % (s,)) as cmR*s rstr(cm.;ion>4' string to fE: %rf'\xbd'?123 123 456 6*b'{#Mascii digits (a came o= '!Zq'\u066314%# embedded NULwN 245r*00 # az3S{ XUTF-8L :3a0'5@support.run_x _locale('LC_NUMERIC', 'fr_FR Sde_DEfwith_comma(sself): 6# set locale to something that doesn't use '.' for the decimal point L # float must not accept2cspecificB8 buFit still hasG1norxython syntaxTimporf.conv()['_'] == ','self.skipTest(31 is]e","') s3assertEqual((" 3.14 "), )2+1-1 c?.14.$3.0-#e3/O000.22323b2.5e-1gO0.250/0.-Raises(ValueError, , ,9 /+3:%-:&A0x3.-;pX=+= 525.2\AlmosN .2 .0def test_wpersion( Make sureAcallr_;__() work properly`class Foo1(objectX F y!return 42.<Y26X>3Xnew__(cls, v;=0.^7.__5!2*7 0 * 4,__zeW# Issue 5759: 0ed ^atr subes (though it%on # unicodJ.%).@*{Str(strQDV) + 1;.vFoo1()), 42.)  self.assertEqual(float(Foo2()), 42.) +w with 2Warns(DeprecationUing):3;2 d\3(21)f/Raises(TypeError, , Foo4(42)6 epStr('8'hE9.) PclassJ5adef __i0__(X return ""O)Jtime.sleep75()# Issue #24731Q'`OtherF1SubN(I0AtIs(type ()5 *FIk9), test_keyword_args XRegex;'D argument'X(x='3.14'is_integerFalse((1.1).11Tru,+X_"nan"4=inf4jb]0asr qfor f, Q in [;(0.875, (7, 8)),!-"-#0.0, (0, B011.b\23, 2c]'%.a_#()irange(10000% = random.(C *= 10 **'pint(-10*001pn, d = a (n).__truediv__(d), fR[ractions.F Y UR1R(*+_(0.0)V0R(5^?2.5^1^ R(*float(0. 5).as_integer_ratio())) (self.assertEqual(R(4728779608739021, 2251799813685248),@GR(*float(2.1|-}4-~#2100, 1--/.0!aRaises(OverflowError, .^'inf'LH -IZValue?nandef test__containment(!):&!s = (INF, - 0.d6NANfor f insEIXIn(f, [f];"7(f,#?{f}E {f: None(6[f].count(f), 1, "['%r') != 1" % fq 2&) C # nonidentical ers, same type EentsY True([f] ==]0%r]@[%r]wfSAuBq, "(%r, E0{f}D{f}, "{%r}A H NI!= "E L/#  #l, t, s, d s6y 3ollPnot e` to it-sDtDtE#sEsa/} D#dDdD`K1AndASigng, a, b# fail unless asqb and ab have theAsign bit;n#only difference from is that th 7estAdistinguishes -0.0|E0.0.&((a, copy (1>|a)), (bb))) @sup%port.requires_IEEE_754 def test_float_mod(self):"# Check behaviour of % operator for S 754 special cases.DIn particular, cSPsignsOGzero/Umod =bU.mod K.assertEqualAndPSign(-1.0, 1.0), 0.0):Ee-10=C=0w%9&1 (;iO), -e$?q$, ?~l;#y2oO@sup>pow builtin pow and **?S taken from section F.9.4.4rthe C99@fica!rpow_op ,F.pow[_x**NAN is =any x except 1)+True(isnan(n`(-INF,F&))P62?NAN66?0.5 l5$ A""5NAN? #<**yGyG9+-01I gN6?2.06 Nl?0.5lertTrue(isnan(pow_op(NAN, 0.5))) self.assertTrue(isna5?1.0525!0INFj 2# (+-0)**y raises ZeroDivisionError for y a negative odd integer  RM(M", 1, -0.0, - ED Efinite and Jbut not an: j>rE'>+D eis +-0GOposiGEqualAnd5Sig;=Jv:BA_0.0) ,GG0AA$(@ P-1)**+-inf is 1"10 , B$A B0# 1any y, even if yQan iny or nanC.Ai"A;H$A+G$v)@//5)!op(1.0, 1.0), 1.0) self.assertEqualAndSign(pow_op(1.0, 2.0)@)?INF@*4NAN@ # x**+-0 is 1 for any x, even if x a zero, infinity, or nanK -INF, 0 ' -2NA)A)?0.5+0,@/+B--D-?NAN+-D)B*B*B,?0, B)A+5+G..M.E y defers to complex powe negative x andCnon-integral y. T(typet-0.5)),{C @?'%1.0, 0.5)), complex) self.assertEqual(type(pow_op(-0.5, _)), c@$90.5? # x**-INF is for abs(x) < 1, 1AndKSignPINF),P B00, B%/0.A.w  3'0 1>1!5INF?0.01 2B"A. 1\9is 0a'"-A(@/5!, ,3^2 l;A@-[ 1# ()0**y y a negative odd integer=Q-1.0)90) D "0.y~but not an17E 2y K}KOposiK4JJ }J:II#HA 3INFINF for y positWive self.assertEqualAnd Sign(pow_op(INF, 0.5), INF)@#?1.0@*2@ #**y is 0.0 for y negat&-m?0.0$-A(oA "basic checks not covered by the special cases abo  , )/25=#, - xC , RB$A.|$Q4Q!C}%61.0CJ)BA.$HA2HA/0.!B}XW AG(A@- D#:!,  A# 1 ** large and -; some libms apparently@have problems withsP-1e10 jCB*D,.0, 1e100), w1.0) # check sign for results that underflow to 09self.assertEqualAnd Sign(pow_op(-2.0, -2000.0), E _(type>5)), complex)C  ?, -FD 5D "o-0.5, %=,I#DcRC&Ch we don't raise an exceptiosubnormal,# and validates. Tests currently disabled, sinceCthey fail on systems where a from powEis flushedzero (e.g. Debian/ia64.#4True(0.0 <\-B1048) < 1e-315?@'7>o7) > -^'lA'%A @requires_setft class F @FuncsCase(unittest."):Odef setUp(L%):b.save_as = {'double':float.__g4__()b '=D&)}tearDown*&._-, []C'B]) def test_getformat(self): .assertIn(float._/__('double'),5< ['unknown', 'IEEE, big-endiadlittle%])NRRaises(ValueError, } , 'chicken'F?TypE 11) Adef sfor t in 1, ''5.__Ie__(t, .1if }Rsave_ s[t] == i?<<7BME 1 /el @^ /sewxh{>@( Y BE_DOUBLE_INF = b'\x7f\xf0\x0<' L4ytes(reversed(S'))c8NANc8c4c`NAN)) d[FLOAT8 # RcP#P# on non-'A plas, attempting to unpack a bit prn # represen'an infinity or a NaN should r  an exception. @requiresb class UFfTestCase(unit.{_setUpD = {:  'float':.__getformat__(3)} - &s&double', 'unknown')1 F 01def tearDown(self):~4?.__z-b.save_3s[']BsA']) 2st_Y_specials_dont_unpackor fmt, data in [('>d', BE_DOUBLE_INF),a 1?NAN1 08]32serialized_>roundingProm _pcapi im FLT_MAX bcEqual(UW"x, spec) andD3x._`1__(!}bq.assertEqual(K0.0, 'f'), '0.0&')8ault is 'g', except` empty 1mats r/')1D1, '213g4h#presentation typ0 in same way asG(issue 5920x = 100/7.* xfstr(x)C0 -1>1211A1A-9 {: : ;:g3, '::fB, '+t+pt :t[3# %AEtingR %D'-10%qconverso4ingaOfailhRaises(ValueError,0, 39"s"Sother#cifiersgn't work on floats,u # _particular in?B($fo`_5@([ch0x xrange(ord('a z')+1)] +L L ALZLHQif no5mat'eEfFgGn%'.kVDH(H0 +Oe100J2/-1K(rror, format , 1e-100, format_spec)  self.assertRaises(ValueError;?, -LM# issue 3382ZbEqual((NAN, 'f'), 'nan'2 F2?NAN25INFd?inf2daINF') @support.requires_IEEE_754def test__ Pfile(!):$qwith open)A) asB604for line in"&!if%p.startshW('--'|&continuei=KFrip($aif not$ !^_ hs, rhs = map(str.strip,N.split('->')wfmt, arg = lhs,'romt % float(arg)8-9P'-' +L5864(123.456, '.45Y1234.9.235e+03=(5.v=4class ReprTestCase(unit.PLrepr2 s_" =os.path.join( _)}__)[0],1SA 'Xing_points.txt((+   x S#R v = eval(s o "v,+N'v)s.close({@skipUnless(getattr(sys_T_style', '') == 'short'o "applies only when using :N [ ["&{ #GintroducedPython 3.1. One at# of this is that we get some degree(cstr ->'->EProundping. In particula any numeric 'ngD0ain 154fewer significant digits, those exact sam~## (modulo trailS`zeros)/uld appear!the output.No more repr(0.03) -> "0.029S"! test_strings = [ )# output always includes *either* a decimal point and atE least one digit after that6, or an exponent.@j'0.0',1L0.01'3451.234567890# values >= 1e16 ge5.*10 tm'1e+16Ke+17Q# ...Tso doj< 1e-4?0.0p/019(9.>e-0e designed to provoke failure if the FPU rounding# precision isn't set correctly,'8.72293771110361e+27.47005307342313e+22.86438000439698e+28'8.89142905246179$3.08578087079232e+3]@for  :!neY'-'+sself.assertEqual(s, repr(float(s)))0 Z 3 6# Since Python 3.23@tr adenticalq O, st<?) @support.requires_IEEE_754 class RqTestCase(unitz."):2definf_nan(m)|Raises(OverflowError,V, INF5-6 V h?NANh JType1INF, 0.06?, 17NAN, "ceci n'est pas un integer"0.0, 1j)mlarge_ck [324, 325, 400, 2**31-1 2F100]lrH (123.456, n), 123.456)  self.assertEqual(round(-123.456, n), #) 6;R1e3008 55-326 7h150, 300), 1e150313073;fp-3.1415h8 j9jQ.4e-3k!156!) def test_small_n(!): for n in [-308, -309, -41-2**31, -F100]IM\ '0.o5;-7:43749overflow:Raises(O*qError, d, 1.6e[8? H-1.7@P@unit-.skipUnless(getattr(sys, 'float_repr_style', '') == 'short',J  "applies only when using : [ [ ["2previous_\_bugs=# particular cases that have occurred0bugjEortsz{562949953421312.5, 1) 1cb3b a&.5`#-half-even @25.0PI), 2304040506`60708`8090!10aYmatches_~_formatZv uld give the same results asDAtingi{range(500): x = i/1000.  self.assertEqual(float(format(x, '.0f')), round?0))C1C1C2C2C3CE3)) for i in range(5, 5000, 10):%9J0Brrandom.(Qϒdef test__specials(r# Test &ting of nans and infs.U(fmt, value, expectedUYwith both %Ri/()G Lmt %bZ, fmtPfmt =[1:] # strip off the %z \lAmin ['%e', '%fg".0".6e.20g',?2'%#,#+#B3#.2DC#.15Z.3g']Ap= '%+' + is" "INF, 'inf'Y"-#-$ NAN, 'nanF## When ask}ga sign, it's always provided.)re%# )zositive`9", +$ %+$-% us0' ' code, only can be nega# Others haveC?pacX$ '-inf')   test(sfmt, NAN, ' nan') $-%&@def "_None_ndigits(self):!Cfor x in round(1.23), , > L=LP_.assertEqual(x, 1#IsInstance(6int* '78-782o V # Beginning with Python 2.6 float has cross platform compatible # ways to create and represent inf nan class InfNanT @unit.CCaseinf_from_strrTrue(isinf(("inf")) - +.-.infinity33 "", +4)5b")), " k8o ::?") 2INF4!+Ij Io+iNfInItY-INFINIT: 3458]' 99Raises(ValueError,I/o"56o") self.assertRaises(ValueError, float, "in") Oself3+4 -4 infinitI97_-INFI6_ys") HO+Infq?-+i6 $+-q-P4itydef test_inf_as_str(;/):Equal(repr(1e300 * )~5-.6|8 674k nan_from True(isnan(n("nan"))p-+.-. ", 455kPNAN")!40+NA^j 9-NajkT53<4;Onana66#-h=+ k+l60--nu_as_str(selfC): self.assertEqual(repr(1e300 * 0), "nan")9 -2:;/sts#8rdef test_inf_signs( @copy* (1.0, float('inf')), 1.0;-<-= P@unit .skipUnless(getattr(sys, 'y_ _style', '') == 'short',J  "applies only when using : [ [,?nan,6# WLthe dtoa.c code, 92 ofcp('nan')v5uld# be predictable. QU$< fromHex =.hhex toclass HexFTestCase([0MAXU_h('0x.f8p+1024') # max normal :MIN;p1p-1022- X# min;JTINY<70.0J;7suby?EPS= 0') # diff between and nextDA up Pidenticalwc, x, y"# check tha>1s xPey are ?B, or&Aboth_@&ENaNsif isnan(x)4 t8%#==1 %)ereturn]`elif xy(x != 0.0k x 'y)_fail('%r not to %r' % (D)dHO_endC.MIN, ldexpZ) 4V 5/745 :EPS4/522 MAX, 2.*(x1023) -\970))invalid_input  E = [Ai', isspelt infinitF&and5"-I" 0'++ l'-+Inf* -- *\+-NaN*  0 1d_.0p +'/ - K-+ ~.p-+5f # double signs=-D \+-\ 3&.p+21+ 4-43.r!0x # no hex digits before or after point@0x1,Q # wrong decimal, character6.pa1p\uff10', # fullwidth Unicode K2xa!0x!1.0Kp \n 0x2 n \0hembedded null byte is not end of stringH] for x in invalid_inputs:!:tryresult = fromHex(x)5except ValueErrorC:pasNelse' self.fail('Expected float.{hex(%r) to raiser9; ''got %r instead' % (x, A)) <def test_()v_pairs = [7g0('iZ INF)E('-I/ -!M NAN; 1.=1.0-0x.2', -0.125:J-0.0 '4 `,\t#\?\n ' #-\vKrdinp, e!7in .@lead $(_trail) -N lead + inp + trail) self.identical(got, expected) 4def test_from_hex(6!):T`MIN = V.MIN;%AX&AXDTINY 4EPSBEPS;c4# two spellings of infinity, with optional signs; case-insensitive GHex('inf'), INF+,/+I-@-INFZ[/iNI^NFINITY2-g2-iNFiNite3o# nans 0nan?NANVO+NaN---&nAZPvarias in input format%^1?1.0+/1.V?1.0,p.00/0xXxY ?+0x;?0x1;X.P/x1..0O.1p4o0x.1p001?1p+L-/40mHex('0x1p00'), 1.0) self.identical(fromHex(' 0x1p0 0"\n21`/\t11ap0.0?0xA//aP^/#be9B1/bEbqXBE0P-4Rd_xB.Epc_.BEp8w.0BEp124 # moving the point around"Upi = 0x1.921fb54442d18p1',0x.006487ed5110b46p11/pi=c90fdaa22168cp1=19y3243f6a8885a3ww 7v 6; 5;  3t t/, ;)3.K)6.-)c.-)9.q-a832.'864.-K8c9.-H192.^-8G324.-%0x648.7ed5110b46p-9'), pi) self.identical(fromHex('0xc90.fdaa22168cp-10<1921.fb54442d18p-11=_# ...KJl.8p-47K3243f6a8885a3p-48;6487ed51194:959M8p-58_0p-52$<3<6c90<4< 8=5= # results that should overflowGassertRaises(O&sError, , '-0x1p1024' ?>_+1025?#0+0X~/30?#O+110@$~234567891 #o+0X.8p *@x0.8M$`-0x0.4A6#10X23?$0x2.~?$o-0x2.0)A+0X4@2%91.fN&XO9(0M*$J+0x36&34/97%;x10?p96M$3-0Xfffffffffp96c0') # ...and those that rouo +-max float1self.identical(fromHex('+0x1.fp+1023'), MAX)A;-0XA$7pA-BAfNMu# zerosP0x0p0?0.0.?1001-21-d X04d52d2234567891 qa-0X0p-71k4-\1102mfngo4 722h21107kx0p-10747f62o2i rB# valuesshould underflow to 0,!X1:3} f0-0xgB 0S0OTINY.6-7| z Ejr# checkv-half-even is working correctly near 0@DC/0710X223243/X53632*TINY) self.identical(fromHex('0x7p-1076'), 2*TINY) 5/X85!95 /xa5 &Xb53/xc5 /Xd5!e54f5!/106F-0x16O-0.0O-0X24'x34{O-0X45 /x55!657-0XR-7T7V7X7xZ-[(-0\7^7x`-a7-0Xb7d8D# ... and near MINcGx0.fd 22?MIN0HfH H@H0vH0H/e1H0H0H".fffffffffff fe6p-1022'), MIN-2*TINY) self.identical(fromHex('0x0.f/e8H4aH$cF2eF1/f0F22F24F2 4#f2sf+A &A !A91.0 A A A A  E + F F% F$13F% F% !F% &F% ++# ... and near 1.0.@f0p01.0-EPS /f1AXA2A /f3A identical(fromHex('0X0.f4p0'), 1.0-EPS) self.identical(frA5A//2C 6Cx7C/8C M9C/aC bC cC d= ze= zf=IX1.0=)1=xz2= 3= z z= = = 7 E?1.0h P=!  b+ {A NA$A A A$A A !10A self.identical(fromHex('0X1.011p0'), 1.0+EPS) self.identAxA2A 3A-4A 5A-6A 7A /7fU'8X3/2*5 8  l 9/aC/bC cC/dC/eC fC -20C;def test_roundtrip(!):"xtreturn / to5Ex)) @for x in [NAN, INF, cD.MAX &IN -CTINY F0.0]{(q8x, ,---# should exactly recover x, any non-NaN float x.import random7iprange(1 Z3e =6.=)p-1200,  m.:om( s choice([1.0, -1.0]+:tryiAx = s*ldexp(m, e3except OverflowErrorDEpassUNelse' ^_subclass1 F( `=__new__(cls, value):  return float.__new__(cls, value + 1) 5f = F.fromhex((1.5). %))# self.assertIs(type(f), F"Equal(f, 2.5gclass F2(%):]def __init__(n '+.foo = 'bar'2#2 pgetattr'foo', 'none'),P) iname__ == '__main__' unittest.() # Test the support for SSL and sockets im4sys J  T %I)DTelectDtime Hdate$gcouTerrnoUpprinKurllib.requesthreading5tracebackuasyncortweakrefplatformfunctoolsysconfig tryecs except IBRError& = None ssl =.C_module("ssl"PROTOCOLS+orted(ssl.__NAMES) HOST#. IS_LIBRE = 7OPENSSL_VERSION.startswith('LibreSSL')9*1_1_0 = not P,4sl.(R_INFO >= (1, 1, 0M1M'`1) PY_DEFAULT_CIPHERR.get_o_var('3@') data_file(*nameos.path.join( 0dir*!(_7R__), ; \he custom keyRcertificate is used inC_ are generated # using Lib/fP/make(_Ks.py. # Other ] s Gsimply fetched he Internet servers1y #4meant to authent. CERTFILE = '@"keyv.pem") BYTES_*os.fsencode(`) ONLY K1sslL%>KEY$3key#o)NoP &EKEY)_LZECTEDzSasswdT44KEY_PASSWORc"somepass" CAPATHw cat[#8@) CA_NEURONIOI, "4e1295a3.0"4#CAB{h", "5ed36f9 9.0") WRONG_CERT = data_file("wrongcert.pem") #'FILE_INFO = { 'issuer': ((('countryName', 'XY'),),)-(('localit*Castle Anthrax6organizationdPython Software Found"FFcomm@@host/q'notAft 'Jan 17 19:09:06 2028 GMT',Before': -9-1-serialNumb]F9BA076D5B6ABD9BUsubjectWU!?(('S.Q1Alt.@'DNS% Tversion': 3 } # empty CRL CRL Qrevoc@.crl# Two keys and s signed by the same CA (for SNI tests) SIGNEDj0keyL3 ,_HOSTNAME = Z T D@OCSP'http://Aca.p C.nett/ocsp/'WA'caIsA@pycaG.cerHrlDistribu__PointT V0 CA8` our-ca-server0hNov 28/27682EDBF41C880919C O2|4|2}@fake|n ?ECC[?ecc]I_ECC`P-ecc'SOXificate as kpem, but without extra text in sIAcapath", "ceff1710#Q all kinds of lP alt s ALLSANFILE = data_file("allsans.pem") IDNSANSFILE = data_file("idn'& REMOTE_HOST = "self-signed.pythontest.net" EMPTYCER*Rnullcertz>BAD$7bad#NONEXISTING+XXXnonexistingU:KEYcbadkey!^NOKIAMTnokia#ULLBYTE&wullbyte> DH<cdh1024OK%S_'os.fsencode(@) # Not defined in all versions of OpenSSL OP_NO_COMPRESSION = getattr(ssl, "O"P", 0)9SINGLE_DH_USg8 ! 7/EC9#;CIPHER_SERVER_PREFERENC},MENABLE_MIDDLEBOXAd +K2 def handle_error(prefix): exc_format = ' '.join(traceback.f_exception(*sys.6info()))Gif support.verbose_c1stdout.write' +})can_clear_on#s(# 0.9.8m or higherw return ssl._OPENSSL_API_VER/>= (0, 9, 8, 13, 15jno_sslv2_impliesz3_hellou/7hutpf_INFO u7xthave_verify_flagh&G8, 0_isecp_curvehaif not/@HAS_LQFalse]Qctx =-@SSLC xtw.PROTOCOL_TLS6tryPctx.set_ecdh ("b384r1"1Wp ValueE? (elU True HAVE_SECP_CURVES =  e!utc_offset(): #NOTE: ignore issues like #1647654 # local time = utc + O)!if.daylight andA@().tm_isdst > 0-%.altzone # seconds`$)%@asn1(_ >OSomecb@, seA8207nx!.ik=k9 fm_"%b %d %H:%M:%S %Y GMT"[)d%@date. @strpR, fmtB8t.replace(second=0)  cert_time = dt.strfc(fmt) $" # %d adds leading zero but ASN1_TIME_print() use(UspaceH5if p[4] == "0": p!' =-:4] + " " +A5:] =freturnR # Issue #9415: Ubuntu hijacks their OpenSSL and forcefully disables SSLv2 def skip_if_broken_ubN_ssl(func) if hasattr(ssl, 'PROTOCOL_SI''@7tools.wrapsGdef f(*args, **kw ?$2tryw ssl.SSLContext.3sexcept 6^ErrorT1if IOPENSSL_VERSION_INFO(0, 9, 8, 15)Pgplatform.linux_distribution()K'debian', 'squeeze/sid+')Uraise unittest.SkipTest("Patchedbreaks behaviour"J %Felse6unc needs_sni =skipUnlessWHAS_SNI, "SNI support :e` this A")  _8_socket(,_version=qTLS, *,7pAreqs4CERT_NONE, ca_os=None=Sipher#Bfile2F key} c = J is not  "=R'w.check_hostnaFFals'verify_mod5$_v8E@loadJ@loca$s(t EM4 or\ d`chain( M,?gO Rset_c)(AwCing_2q(servero=SIGNED_CFILE"""Create 4dclientH$, IH', 5t4"""<0ert ^T $_HOSTNAMESEelifU2V2W oQValueK)$text = ssl.S SLContext(ssl.PROTOCOL_TLS_CLIENT) client_c,.load_verify_locations(SIGNING_CA) 6dserver60 = dSsbSERVERs =scert_chain(2ert0#kreturn$, ^, hostname class BasicSocketTests(unittest.bCase):@def stants(self):#]CERT_NONEOPTIONALREQUIREDOP_CIPHER_N_PREFERENC\OP_SINGLE_DH_US!ifHAS_ECDH: <OPENSSL_VERSION_INFO >= (1, 0RNO_COMPRES2elf.assertInSNI, {True, False}P23sl.OP_NO_SSLv2} 3_TLSv1_2T ?, 1h_jQEqual8,3private_initPwith RaisesRegex(TypeError, "public constructor"JI!.sz() as sx2SSLv,(sstr_for_enumd# Make sure that the *` have D0-li2Utring# reprs.SprotoP5TLS!&1tr(6@), 'riMethod}'3ctx_:@dqIs(ctx.!Qcol, ,lrandomviRAND_status(upport.verbosesys.stdout.write("\n K is %d (%s)\n" % (v, (v and "suffic ness") orF o "in>{data, is_cryptographic pseudo_bytes(16 @len(P?), ( n, v == 1[Jif vbX else:' self.assertRaises(ssl.SSLError, RAND_bytes, 16) A # negative num is invalid"__Value]?-5):dpseudoABif hasattr1, 'eegd'):% =Typfegd, 1:Y'foo'A[padd("th? s a random string", 75.0w 6b7 object= ytearray(GK);$@unittest.skipUnless(os.name == 'posix', 'requires @def >_`_fork(status =(Crif not fail("OpenSSL's PRNG insufficientpWness"rfd, wfd = os.pipey#pi := 0:tryos.close(rfdDSchild!q(16)[0]4KEqual(len(Q)0os.write(w 1 dwexcept BaseE ?ionk_exit(TOelse. *ddCleanup|-, }#_,Rwaitpid(pid, ~4V>h( 1KW@read Uoparent. m N+ 62Not*, C3parse_cert#qe that uses an 'unoal' function in _%c,# provided solely forLr, to exercish e xificateEarsing cod1 1sl._i0_de<CERTFILE)2U_INFOL p&tSIGNED_`),  SIGNED_CERTFILE_INFO %) (# Issue #13034: the subjectAltName in some certificates@(notably pro7s.developer.nokia.com:443) wasn't parsedCp = ssl._test_decode_r`(NOKIA)2if support.verbose:sys.stdout.write("\n" + pprint.pformat(p) + Zself.assertEqual(p['9'],lp(('DNS', '  /')C CVforumL&')z  # extra OCSP and AIA field0'], ('http://ocspgPisign'',C!caT/rs, aSVRIntl-G3-aiak/oG3.ceryrlDistributionPoint?crl!rlAdef _CVE_2013_4238() ULLBYTEV = ((('country_US'),(('stateOrProvince5oOregon9 ulocalitgBeavert5 organizakPython Software Found" JQalUniPbCore DOmentM dcommonanull.p.org\x00exampleH emailAddressER-dev@ AY0 ir/`OPENSSL_API_VERSION >= (0, 9, 81sanL?alt?com!(' @UZuser@ZP('URICJ L7IP 192.0.2.1 02001:DB8:081\n,el# OpenSSL 0.9.7 doe<r IPv6 a5!esubjectAltNam7e %san = (('DNS', 'altnull.python.org\x00example.com'),ALp('emailC@@@Tuser@E?orgE0URICphttp://J LIP AddressS192.0.2.1| 0')) self.assertEqual(p['subjectAltName'], san4 def test_parse_all_sans(H%):Wp = ssl._1decode_cert(ALLSANFILE)3B.(l('othern, '= 0.9  self.assertGreaterEqual(n, 0x90)-u# < 3.0=BLess53460007major, minfix, patch, status = tT EW ~"3y" LL "?256NL JL'6a/, S (&15:# Version string as returned by {Open,Libre}SSL, the format might change lif IS_LIBRESSL: True(s.startswith("eSSL {:d}".e(9)),IM(s, t, hex(n))Oelse. @support.cpython_onlydef test_refcycle(2)# Issue #7943: an object doesn't c reference K s fg:@# it].rsocket.(.AF_INETVs+Rwrap_'&(s!wr = weakref.ref(sEith  heck_warnings(("", ResourceW)fdel ss9wr(), None) &Vped_unconnectedaMethods on_+kS  propagateoriginalm# OSError raiseG6punderlye3 !+&ss1R#s(, ss.recv, 13_into, bytearray(b'x'zFOfrom} 7Masend, 6'x', ('0.'H NotImplemented&T?msg 0 [0], 0|.0.0.0', 0)) def test_timeout(self): !# Issue #8524: when creating an SSL socket, the G0 ofGoriginal. should be retained..5forIin (None, 0.0, 5.03s =T.(.AF_INET)W.C.set( "BwithRwrap_M(s) as ssN1.assertEqualVf, ss.gm+))rerrors_ssli yx vRaisesRegex(ValueEY,"certfile mustspecified"6@ssl.,tP, keyK=CERTFILEM server-side operationsH_H_=True { $, 6="" C#/, B | "can't connect inlOmode#s.E, (HOST, 8080)3elf1(OS*cm4(t *<lNONEXISTING5'cm.excep.errno, g.ENOEN]2 C}@bad_u_"""Check that try`to usez@ givQlientificate fails"""#  certfile = os.path.join( dirname(__&`__) or*ucurdir,HOc)-psock = 2et.(elf.addCleanup(!f.close$awith s) ssertRaises(ssl.SSLError):qtest_wrap_P!etW = !) TAdef P`empty_(s"""Wrapping 1an . . N1"""N>A.badL_\`("null-\.pem"zmalforme2~p badly 4Qattedificate (syntax e8 ?bad?key ?key?key$tch_hostd0ok($, % Ysl.maF 0OOfailQ CCert   ,c# -- H 7&--#$ = {'subject': ((('commonName', 'example.com'),),)}G % 2ExAE6Om'8Y'www.kF&#E?orgk"X?*.a  4foo#Obar.$ c@X z;b# only wildcards when they are 'Wthing<in left-most segment>/f*/  ?uK:Ba# NULL bytesbad, CVE-2013-4073,,'.python.org\x00q8 #raise an error?   fail(cert, 'example.org') ! "null.python&' # error cases with wildcards%i" = {'subject': ((('commonName', '*.*.a.com'),),)}>tbar.foo)$EX V;?a.* a\"a.B9#c doesn't match IDNA prefix 'xn--'4idna = 'pü.encode("$R").defascii" C #okiN9'x*w[!On--p_in first fragment and A-labels in sequ'# are supported.f2www"ö~L1www{, E1F/?ftpE/ # Slightly fake real-world <+notAfter': 'Jun 26 21:41:46 2011 GMT',8v" linuxfrz A1AltYj@'DNSb@? |(;v3 ('othern5') '  # Not a "DNS" entry $p# When se is a C&, ! inEused@d $ # _istin?Dec 18 23:59:59?untryName', 'US'o),), (('stateOrProvinceName', 'California'Flocality?Mountain ViewBorganizationFGoogle IncCFcomm=amail.gB@.comB%)}ok(cert, '($Dfail&g'H v# Only w is considered(HX "# -- IPv4 matching -- = {'subject': ((('xtexample@1AltbGN'DNS?{< 'IP AddressB10.11.12.13'w V(B4.15.16.17') d1B "?8')"I^net')6if hasattr(sockeYAF_INET6'):i5L l$( g2001:0oCAFE\n C3A`0:BABACuW:cafe #{3::baba#0200%,ebH% Miscellaneoush# Neither Cnor o0notAfter': 'Dec 18 23:59:59 2011 GMT'Euntrz US64No DNS e; ing but a/99 (('localityName', 'Mountain View'),), (('common@mail.google.comBC'subjectAlt9: (('othernblabla'), )}ok(cert, 'g %# No DNS entry j and no 8Z = {'notAfter': 'Dec 18 23:59:59 2099 GMT''uP, 'US 6\(('stateOrProvince>CaliforniP FOloca+organizatiG@ IncDfail9aEmpty /5ertself.assertRaises(ValueError, ssl.match_host_, None, 'exampO(-{}MN4# Issue #17980: avoid denials of service by refusing more than one  # wildcard per fragment.l Ia*b.7,),]with ReRegex(i\Certificatr &"partials in leftmost label are not supported"):Jl 5;axx;_www.*]cly be present ;the$/su+?a*b^too many*:xxc *MEsole pout addim"als /') ('commonName', '*.com'),),)}  with self.assertRaisesRegex(%, ssl.CertificateError,&r"hostname 'r doesn't match '\9"):;]"_?b(cert,E%) -# extra checks for _inet_paton())invalid in ['1P1.2.3 256.0.0.2127 Z/24'](R(Valu 3 Spaddrq192.168 ]True(iT)iif hasattr(sockeVAF_INET6'6A!:: 2001:db8:85a3::8a2e:370:733-T def test_server_side(##  YAwork! sZQctx =SSLContext5PROTOCOL_TLS_SERVER5/.RQ() as^  @, ctx.wrap_E,A , =t="some."=unknown_channel_bindingIphould r DEU typeBs@ .F6 s.v5(('NG', 0xs.listec^c.connect(s.geti(`Lu(c, do_handshake_on_Jb=FalsesK s "W-W"/cclose(P@unit .skipUnless("tls-unique"CHANNEL_BINDING_TYPESO&"'E#' ! ing not availableVBtls_~ C# unVCed seeturn None`^% _s. Is("Ip# the s- ,W= file=CERTFILE$inding("tls-unique")) def test_dealloc_warn(self):!%Bss =&wrap_socket(.AF_INET))=r = repr(ssPwith f.assertWarns(Resourceing) as cmENoneaupport.gc_collect(mhIn(r, str(cm.ing.args[0] gefault_verify_paths = ssl.4Equal(len(DO), 6(IsInstance),l!DeVPbEnvironmentVarGuard(^:env_ env["SSL_CERT_DIR"] = CAPATHr )BFILE*0ERT ,!%D.cafile, g.5 =,$P@unit(.skipUnless(sys.platform == "win32", "Windows specific"z?enum_cert=ate%PTrue(-5G"CA"<5@ROOT7u8Raises(TypeErro=sl.z E<? C, ""YDtrust_oid9(sefor storename in (2, " )9 (G}8-j, list/0ele( U8z, tupleX 65N), 32Cq, enc, E3 = 0YAGbyteo/3!n(f{"x509_asnapkcs_7}?, (set, booludif isi27sete'!@.update(bserverAuth = "1.3.6.1.5.5.7.3.1".7`eXB/rl -B'rl 4s(WindowsErr or, ssl.enum_crls, "") * =#e("CA")#self.assertIsInstance(9f, list*for element in #:GqK3v, tupleO 2Equal(len(1O), 2./[0], bytes5\ [1], {"x509_asn", "pkcs_72}) Cdef test1object()expected = (129, 'serverAuth', 'TLS Web S entication',@'1.3.6.1.5.5.7.3.1'3valb_ASN1O4MgTval, 0(.nid, 129' shortname6 Clong5* H o= BLkRaises(ValueErry7 .fromnid5qCF, -1Wwith %YRegex"unknown NID 10"47sl.=p(.suioQrange J6try[>obj%ei`-vexcept PEpass4>lse'2objF'inOF4S:str: W9H(str, type(None))~ YOame( I\ )K}]"unknown object 'serverauth'"):  ssl._ASN1Object.fromname(5!) 4 def test_purpose_enum(selfUkval = W('1.3.6.1.5.5.7.3.1')TB.assertIsInstance(CPi.SERVER_AUTH,\H_EqualC?val7.nid, 129; PshortX,AJ Eoid,:>m42oCLIENT* C7/30W;oclientJ!mcunsupported_dtlsgseqocket.s(.AF_INET, SOCK_DGRAMddCleanup(s.close!Wwith Raises(NotImplementedError) as cxU%Rwrap_(s, cert_reqs=CERT_NONEtotr(cx.exception), "only streames are -"Q0ctx%sl.SSLContextROTOCOL_TLS_6,Ictx.Z6*Tqtime_ok! , dstring 7amp6sl.Hto_seconds(J)K 6MfailuTRValueF @"^P@unito .skipUnless(utc_offset(),a'local2 needs to be different C UTC _0Azone # Issue #19940:A() returns wrong#results if z is not UTC self.cert_time_ok("May 9 00: 2007 GMT", 1178668800.0) DJan 5 09:34:43 2018D515144883DEdef test_to_seconds(_!):)qstring = "i0Ws = 1uY \F, ts# accept keyword parameter, assert its name^Equal(ssln=) both %e and %d (space or zero generated by strfQ@0 case-insensitivB?JaNmBU Qfail(:7)c # no  hF"EF?GMTB@ UTCFt `?zon3e) # invalid day oU G_monthI %24 IOhourHT09:60f$uminute Knewyear_tp2307680R"o# leap Dec 31 23:5hga# sameUstampr [Z19(, [C&59,(99 allow 60th (even if it is not a?/60'90## 82ndd for compatibility withHP.strp(11BG6:62D   special treatment5theVvalueg # 99991231235959Z (rfc 5283u !59F9253402300799@support.run_X_locale('LC_ALL', '') 706# `vconds()` sho uld be locale independent 2def _february_name():#*return time.strf ('%b', (1, 2, 3, 4, 5, 6, 0&))hig.lower() == 'feb'xself.skipTest("-specific month needs to""different from C'e"#-3CPcert__ok("Feb 9 00: 2007 GMT", 1170979200.0) DQfail( O + "[test_connect_ex_error(dserver = socket.(.AF_INETaddCleanup(?f.close&@portS up `.bind_ /q) # Re<  but don't listen1 = Rwrap_ ,<reqs=ssl.CERT_REQUIRED#. rc.\q((HOST,)I"# Issue #19919: Windows machines or VMs hosted on"#,@some[#s vEWOULDBLOCK.1Us = (errno.ECONNREFUSED, uUNREACHTIMEDOUTM1w=ssertIn(rcTors) class Context`s(unit.bCase):@_if_broken_ubuntu_sslnstruct for protocol in PROTOCOLSMcsl.SSL(20ctx 'Equal(ctx.F , izO_TLS9Raises(ValueE8O, -1:%#42T -QN-Q6 2 lipherss wg_CLIENSset_cUV"ALL" wDEFAULT#Wwith `Regex(3SSLB"No h@ canselected" w^$:,;?*'dorothyx":)Unless(PY_SSL_ _CIPHERS == 1,   "Test applies only to Python default ciphers") >def test_p&_q(self):#'ctx = ssl.SSLContext(PROTOCOL_TLS_CLIENTY6k = ctx.get_$for suite inxF@name}% ['%']!.assertNotIn("PSK", +i*?SRP*?MD5*?RC4*E3DES+P@unitq.skipIfeOPENSSL_VERSION_INFO < (1, 0, 20), 'OpenSSL too old'5/Gtx.ss'AESGCMxrsDet(d d :0In(Z256-GCM-SHA384's2 4128262562kb_if_broken_ubuntu_ssl6options3# OP_ALL | NO_SSLv23 is theQvalue#= O7OP_S 3)&#  also enablewTse by| vB|= (fpCOMPRES CIPHER_SERVER_PREFERENCE |FOP_SINGLE_DH_USEE$EC<ENABLE_MIDDLEBOX_A}@cEqual(9," |UTLSv1V! |3hif can_clear_q(8= (6& ~;3_5= 01# UG has3oced on-: 0 JelseWwith SRaises(V[ErrorB verify_mode_protocol"3# Dd ,;CERT_NONEQ (Gsl.CERT_OPTIOSNAL %self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL)= ,& =-REQUIRED,i<iONONEe!8aWwith Raises(TypeError):d9ENone#NOValuO542 N3ctxZSSLContext(PROTOCOL_TLS_SERVER 9QFalsecheck_hostname)oCLIENT" ?Trudef test_s_common_(Nm-u !if3 HAS_NEVER_CHECK_COMMON_NAMEyY0 = ;C=-1 = $qr=qpJelse`Attribut(7P@unit.skipUnless(hasattr, 'minimum_version'),} "required OpenSSL 1.1.0g"tmin_maxT#q I [BTLSV.MINIMUM_SUPPORT=f(ax1f/AXfMzTLSv1_15 ~525  -Equal(  ctx.maximum_version, ssl.TLSV Rv1_2 2E ) ?(in?, =@MINIMUM_SUPPORTED? ~?UTLSv13self.assertEqual( )Lf f 3 =?MAX3/\/In ,x{ `eSSLv3}9 a Z-_2_Wwith @Raises(ValueError):/Y = 42bSSLContext(ePROTOCOL_1Eg R31Fo" o  @unittest.skipUnless(haveify_flags() E"ver* need OpenSSL > 0.9.8" @def k [3ctxar_SERVERW# default vtf = getattr, "VERIFY_X509_TRUSTED_FIRST", 0R NDEFAULT | tfD 34CRL_CHECK_LEAFy E{_CHAIN|!FY_CRL_CHECK_CHAIN) ctx.verify_flags = ssl.VERIFY_DEFAULT.self.assertEqual(?,>m# supports any value\ K CRL_CHECK_LEAF |hX509_STRICy wWwith 'Raises(TypeError):xQNone % def test_load_cert_chain(`I3ctx-SSLContext(PROTOCOL_TLS_SERVER# Combined key and c in a single fil CERTFILE,DPfile=e4F8i B/, UL"OSn as cm NONEXISTINGdm.exception.errno, v.ENOENT;QRegex1SSL, "PEM lib" J(BADgCZEMPTYi# SeparateT 1ONL| , 6KEYU/.1@`BYTES_4 F LzChGP :KEYh# Mismatchinge9B/3s m CA*0_CA# Password protectG.U`ECTED, pPd=KEY_PASSWOSRD) 8ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD.encode())P0 lbytearray(v @ONLY , BG4 .with self.assertRaisesRegex(TypeError, "should be a string"):FTrueP(ssl.SSLq-@"bad1"v EValu`cannotllonger# openssl has a fixed limit on the buffer.># PEM_BUFSIZE is generally set to 1kb3eReturn larger thar*is0b'a' * 10240043# P callbackpdef getfQ_unic (rV?+s(=LFJf THgOhuge9p(qxO_typH9yexception~% E' e'class GetCallable& __0__(W v DC!lJUsH4L( (TFILE_PROTECoTED, password=GetPassCallable().get)@with self.assertRaises(ssl.SSLError):.uctx.load_cert_chain(CERTFILE_PROTEC ht@_bad| Regex(Value, "cannot be longer"5Ohuge5Typmust return a string6bad_typException, "h e6eb(# Make sure theP func isn't called if iteneededPL ,X=_Cdef test_verify_loca s(*cctx = qContextOCOL_TLS_SERVER _,tcafile=3, capath=NonldBYTES_?r 9x) @# , R!OS) as cm NONEXISTINGBfEqual(cm.dp.errno,Ono.ENOENT;c, "PEM lib :BADy, CAPATH4$AZ# Issue #10989: crashsecond argument  is invalic[[aTrue) lcadata# =qopen(CA!CAfLfKapem = f.read(Z3derO2PEM ato_DER "(c&6pem: NEURONIO neuronio_pem = f.read()  neuronio_der = ssl.PEM_cert_to_DER ((bpem) = # test PEM3ctxISSLContext(XROTOCOL_TLS_CLIENT)6self.assertEqual(ctx. store_stats()["x509_ca"], 0?.load_verify_locations(cadata=caMt!1t 4v)2v #  already in hash tableN:w# combined#G = "\n".join((), Z3!2with junk around thes7["head", z"other", "again",~{9, "tail"]*@JK9N8DERN F6der5; 7@$3${A+b"7derY/error case-Raises(TypeE`/, mgobjectig UQRegex`3SSL]"no start line"):  ctx.load_verify_locations(cadata="broken") 'with self.assertRaisesRegex(ssl.SSLError, "not enough M5"):FMoctx.lo}b~ :def test_7dh_params(]cctx = qContextPROTOCOL_TLS_SERVERXfDHFILE#if os.name != 'nt'ClBYTES_I @S(Type89f, None?(FileNotFound) as cmNONEXISTINGCERTiEqual(cm.excep^.errno, g.ENOEN;?@skip_if__ubuntu_ssl^session_stat]for proto in QS*5"&:tx.~A), {0'number': 0,connect __good# renegotiate* ac i ?_hOhitsf_misseotimeou<cache_full]+})tset_default/Mpath!# There's much we can do to that it actslexpected# so just check-doesn't crash or r|F an [9CLI}|P@unit.PaUnless_HAS_ECDH, " disabled on this OpenSSL buildTvt_ecdh_curve7X"prime256v1V)b*  p9 ?HValu4 yg, "foo Ases(ValueErr or, ctx.set_ecdh_curve, b"foo") @needs_snidef test_callback(self):!4ctx = ssl.SSLContext(PROTOCOL_TLS_SERVERg7 # servername` expects a sable, or Noneu.assertRaises(TypeErr])B.?, 4E1/""F17ctxSPdummy8Vock, Epass"3(* [_refcycled# Reference !s through the3 are detected# and cleared.5o,=6Az P<wr = weakref.ref(c0del), >gc.collect(WIs(wr(),xcert_store_statsQoCLIENT~PEqual.k%),{'x509_ca': 0, 'crl  }bQload_Vchain(CERTFILE&Mverify_locationsV1A0_CA%!81,2}gaget_cacI gV), [] # % is not flagged as X509v3 Basic Constraints: CA:TRUEyc Xbut Ca CA cert  ctx.load_verify_locations(CAFILE_CACERT) -self.assertEqual(Bget_ca_certs(),-1[{'issuer': ((('organizfName', 'Root CA'),=A =dalUnitChttp://www.caO.orgQdcommonE CA Cert Signing AuthorityIemailAddresssupport@ q'notAftasn1time('Mar 29 12:29:49 2033 GMT'@Before': A(30A0AserialNumbJ'00' 'crlDistribu`Points'wsx/revoke.crl''subjectA  >/R3J%version': 3}]) Owith opene as f:'1pem = f.read(der = ssl.PEMq_to_DER F(pem,True), [derdef test_Uqdefault] s(Q)3ctxSSLContext(ROTOCOL_TLS_CLIENo\&X:urpose.SERVER_AUTH&h#Raises(TypeError,% f, None C"'U'P@unitE(.skipIf(sys.platform == "win32", "not-Windows specific" FIS_LIBRESSL, "LibreSSL doesn't  env varsGO_env3.EnvironmentVarGuard()6env>env["SSL__DIR"] = CAPATH )ERT_FILE"] = CERTFILE  ctx.load_default_certs()%self.assertEqual(6)_store_sta4, {"crl": 0, "x509": 1 0_ca1}) [2@unittest.skipUnless(sys.platform == "win32", "Windows specific")FIf(hasattrJ<, "gettotalrefcount"), "Debug build does not share environment between CRTsn@def _1b_env_w(/!):jctx = ssl.SSLContext(PROTOCOL_TLS_CLIENTxchu0 = )f'with support.EVarGuard() as1menv["SSL_m_DIR"] = CAPATH)*'[vi] += 1pW_"_c_options,}e1! &OP_NO_SSLv2,2if )COMPRESSION != 0np C,  0 SINGLE_DH_USE" B //EC/D1 CIPHER_SERVER_PREFERENC-#M:fcreate0WMprotocol@9verify_mode<WREQUIRED=BTrueheck_hostname,7ctxopen(SIGNING_CAfcadata = f.read;vcafile=`, capath=5 s= self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS) self.ass9verify_mode<CERT_REQUIRED=_>_context_options%) hQctx =create_default7(urpose.CLIENT_AUTHmlFKNONErdef test__fstdlib_elf): 0 _rPFalse.check_hostname j+v1h;"$,A cert_reqs=# F L=Tru`N?xlVpgQP s (kBSSLCijhZ # Auto set ! 0 = "":#E2RT_REQUIRED)3 &# Changing verify_mode does not affect check_hostname>Jctx.z = Fals#Z= ssl.CERT_NONEKself.assertd()P-QEqual-,9# Auto setLhf = Trunm a, REQUIRED)  sOPTIONAL, h5q# keep  m"?jP# Can2set[ with+ enabled;$Raises(ValueError):,t,(9Px def test_context_client_server(U# PROTOCOL_TLS_CLIENT has sane defaults BSSLCb(wG~u_?9 aSERVERdifferent but also*Z: ustom_class MySSLSocket Gpass Q<UObjec<< /tx! >Assls" =Q.sslo *ZRwrap_\(.B(), `_side= ) :ock-IsInstanceN, MySSLSocket)# obj = ctx.wrap_bio(ssl.MemoryBIO(), )=8self.assertIsInstance(obj, MySSLObject) class SSLErrorTests(unittest.qCase): [def test_str(d!):`# The e) of aT doesn't include the errno<1e =(1, "foo"`Equal(j/e)(!e.l6, 1M# Same for a subZeroReturnE{]lib_reasond1estAlibrary and - attributesP6ctx[qContextGPROTOCOL_TLS_CLIENTPwith CaRaises8v) as cmn .load_dh_params(CERTFILE]Xcm.exception., 'PEM'6, 'NO_START_LINE?8tr(l]True(s.starts("[PEM: ZQ] no $` line")#WCheck thaappropriate4P is rd# (this only etFthem#qc`_hostn'u= False#verify_modU_NONE(? socket.(7s6s.bind(("127.0.0.1", 0)[s.listen(c b7c.connect(s.get(^c.setblocking( hGRet(c,, do_handshake_on_u=J+ T fWantReadx7 nD(c. !!s%"Popera did not complete (read)NQ# For,atibility,~SSL_ERROR_WANT_READDAbad_server create_default%RValue ',  server_hostname="") with self.assertRaises(ValueError):,4ctx.wrap_bio(ssl.MemoryBIO(),  ;? .example.org?Typ[\x00evil.com") class Tests(unittest.qCase): @def _read_write(i\bio =M=@Bbio.7fb'foo'G`Equal(+g-WFq7bar40Z tzt2), b'ba-1-Y,+')?eofQFalse?eofLCB< _: fON?Tru^5 Kpending&"J6, 0mC3Cfor i in range(3e:13G3-i-1dXxh'i+f  0buffer_types|J -Gytearray(?r') Rbar') bio.write(memoryview(b'baz')) self.assertEqual(bio.read(), . .def test_error_types(?!): Qbio = ssl.MtOBIO(lRaises(TypeEO , x, 'foo'7ONone6?Tru6 1) class SSLObjectTests(unit'.CCase?private_init@Pwith rEXRegexJ"public constructor"impleBackground1"""!P thatwnect to a sI server running in the b`6"""e\setUpB@= ThqedEchoSW(SIGNED_CERTFILE:_addr = (HOST,X.port/.__enter__ddCleanu+pxit__, })@_con !wrap_socket(.AF_INET),n cert_reqs=_NONE) as s7(s..(( #{}, s.getpeerq(Q 2tFalse(s^Cside)# this should succeed because we specify/Proot o>QREQUIREDw a_ s=oING_CAs4(n/\_fail7# T"have no verificationBs. C5ion # Aure crashes@, soin an independentL$ method.2s ==G _.closD 3SSL"/GeRy0?ed"j 5 $lf\) def test_connect_ex(self): # Issue #11326: check 0) implementation:s = test_wrap_socket(.AF_INET),<}  cert_reqs=ssl.CERT_REQUIRED9 a_<s=SIGNING_CA)j.addCleanup(s.close!ssertEqual(0, s.Bserver_addr)<True(s.getpeerA()) 2def)non_blockingDnon-7 should allow handshakeu[# to proceed after the  gets ready.2 5do_4_on_N=Fal D.setn(>Orc = K"# EWOULDBLOCK under Windows, EINPROGRESS elsewherrapIn(rc, gerrno.:#, h# Wait for4efinishrselect.p([], [sf], 5.08# NjI`while [:try(s.(gUbreak\pexcept SSLWantReadError`  Y_WriteZ+^ Z# SSL established.3 @withNtextrSame asf3`, but 8 a separately createdM0ctxsl.SSLCon(pPROTOCOL_TLSYOctx.)si.f6 {} n*!#  hostnamf h="dummy"%verify_mode #s# This succeed because we specify the root cert ctx.load_verify_locations(SIGNING_CA).Pwith 3wrap_socket(.AF_INET)) as s:Bw s.connect(self.server_addrj( = s.getpeer(#AassertTrue(#!) ndef test_m_ text_fail)# This should " because we have no )i&LBs. C1ion{#A ure crashes ThreadedEchoS, so run txin an independen# method.c0ctxsl.SSLCon(ssl.PROTOCOL_TLS0cy_mode;CERT_REQUIRED[?s =;addCleanup(s.closeRaisesRegexSSLError, " ifhesyQEed",kha!, m b> ncapathV Bqs usingW`>z` argumQNOTE:&subject hash:algorithm been changed betweeMOpenSSL 0.9.8)d 1.0.0,`a resultg directory musKcontain bothZs of eachp (same 0ent, differfilename) fort to be portable across releasesR*v=CAPATH(b0# Sa bytes 5HjoBYTES_p8Ldata8HopenF%fnpem = f.3der@PEM_ q_to_DER F(pemxt(ssl.PROTOCOL_TLS) ctx.verify_mode = ssl.CERT_REQUIRED,Sload_1locations(cadata=pemZPwith _wrap_socket(.AF_INET)) as s:p s.connect(self.server_addrj(@cert.getpeer(#AassertTrue(#%) nq# same 5DER0ctxYsl.SSLContext(%_PROTOQK'deQ@unittest.skipIf(os.n_== "nt", "Can't use a a file under Windows"@def SP_make&a_close)6 # Issue #5238: creating Z-like objectN() shouldn't# delay jE#th lyS"realq" (here"ed\7itsK descriptor, hence "pN] %).CAss =`_T=K!fd.'noAf-X f.e,# The fd is still open1os.read(fd, 0d# Clos3SSLX e $efd tooP-sspgc.coll7a@Raises(OSError}eGDEqual(e.excep .errno, c.EBADFdnon_blocking_handshak.Ts.setuf(Falsekx V,a  =`_reqs= 0ONONE5 &doC_on_=addCleanup(@coun0 wh6 :try?E+= 1@(s.Ybreak77SSLWantReadT{ se.q([s], [fT_WriteUPYU if support.verbose: &sys.stdout.write("\nNeeded %d calls to do_handshake()establish session.\n" % count) edef test_get_server_certificate(self)_, 0, *3.K`addr, Q=SIGNING_CA{\_fail# Connection ! ure crashes ThreadedEchoS, so run this in an^# independentu method"  |ciphersAwithy_wrap_socket(.AF_INET), i_reqs=ssl.CERT_NONE, ="ALL") as sG2s.cY)saDEFAULT&# Error checking can happen at instantiaQor when :ingassertRaisesRegex(l1SSLiS, "Noolbe selected"ItP:ock<?s =;" <! ) ^$:,;?*'dorothyx"D 4 9 ]!caYs_capathh"# s are lo on requestU~cctx = xqContextPROTOCOL_TLS_CLIENT@ctx.T_verify_loc"s({v=CAPATH1`Equal(B)f(), []1%5Ghostname='l'%@0ertA.getpeer8(#PTrue(#"?lenC), 1 @needs_snicP_setg p0# C that theP of a 2ed Fqreplaced.k@ctx1osl.SSL213Octx2i ctx2.load_verify_locations(capath=CAPATH) s = socket.(.AF_INET*with ctx1.wrap_'(s, server_hostname='ul') as ss:ovss.connect(self.@Faddrn)assertIs(7Qtext,, p_sslobjk4 =S2~ 2~ 12) adef ssl_io_loop,, incoming, outgo func, *args, **kw )T# A simple IO Sp. Call 9(8) depending on the error we getr# (WANT_READ or WRITE) move data betweeGA andVUBIOs.Otimeout = c.get('V', 10Gdeadline = !.monotonic() +&ou@counX0lwhile True!if= P$> n ,0`fail("Fout"!errno = None~I+= 1>tryf re 3`except%Q.SSLE;as tRif e.not in (ssl6q_ERROR_,b<<>Jrais= x# Get anyJAfrom8 BIO irrespective of/,h Psend it toIUbuf =Qj.read(6.Jzall(buf@# If]rre's no;, we're done. F-kW@need_#{Pd putiZ  !isYbreak)%el6$==Z $I;.recv(32768nif buf?n.write^$?els>G_eofif support.verboEsys.stdout?("Needed %d calls co;te %s().\n"8 1% (,_0.__6__)return rettest_bio_handshakedaddCleanup(sock.close)  sock.connect(self.server_addr) & incoming = ssl.MemoryBIO(#_outgo# 3ctxASSLContext(PPROTOCOL_TLS_CLIENTYassertTrue(ctx.check_hostname,QEqual-verify_mode,CERT_REQUIRED=YSload_1locations(SIGNING_CA.sslobj = 7wrap_bio()$, , False,LT c0ED_FILE_HOSTNAMEq Is7Robj._a.owner?obj4DNone8cipher()+version,tZrshared_as6Raises(ValueErro.getpeercertif 'tls-unique' inHANNEL_BINDiTYPES:i=(Isget_channel_binding(d ssl_io_loop(5,do_handshak-*)_ 6 2 h?try unQaexceptESSLSyscall j# If the  shuts downCTCP =ion without seP) a# secureECmessage, this is reported as SSL_ERROR_SYSCALLMEpassYU1SSL.write, b'foo') ?def testa_read_&Q_data)`ocket.!et et.AF_INEddCleanu4X.clos}~"90sl.Q_NONE=aVreq = b'FOO\n'. _ck, incoming, outgoing, sslobj.write, req) buf = self.ssl_io_loop(sock, incomB Lread, 1024LF assertEqual(buf, b'foo\n'(nunwrap) class NetworkedTests(unittest.qCase): @def _timeout_connect_ex(!):' # Issue #12065: on a 7', 8 ) should return the originalNerrno (mimicking(behaviour of non-SSL lUets).>with support.transient_internet(REMOTE_HOST2s =0_Z:et.AF_INET),v@ cert_reqs=ssl.CERT_REQUIRED=do_handshake_onf=Falsex.addCleanup(s.clo%C.setA(0.01I rc.2j, 443)20if 56= 0@skip]'("| responded too quickly"[?In(rc, (.EAGAIN, WOULDBLOCK))@~tUnless( IPV6_ENABLED, 'Needs IPv6hget_server_ificate_ipv6w '5.google.com'}_kql-, C G __failL F (, host, e , @=Non;0pemE?sl.(>MiVt pemEi.B"No lg%s:%s!" % TA, ca s==%ifvverbosesys.stdoutq("\nVerifiedAfor is\n%s\nP ,pem l6tryO%BFILES`exceptW.SSLError as xh#$6 :xxli\Got server certificBate %s for %s:%s!" % (pem, host, port)) from test.ssl_servers import make_https class ThreadedEchoS4!(tBing.): 1ConnectionHandler04"""A mildly complicatedL, because we want it to work bothwGwith and out the SSL wrapper aroundsocket cE, soJ@thato1can-3STARTTLS funality."""def __init__(self, d,kv, addr):m8+.*# =3!running = False!`% =k!{! =>.setblocking(1)% sl5j = Non . Ldaemon = TrueE_iF .:try?CR.context.U9et(@54ock`_side= - .selected_npn_protocols.w!ndp+/()`/ala , bexcept (ResetError, BrokenPipen) as et# We treat H6`though}were any#gp - Openon Ubuntu abruptPlosesC[q when asked'9an unsup4ed .H  is raised in 1.3 mode,zJ0trio send session tis after handshake h://github.com/opensslissues/63420 _eOtr(e9if :Ohatt"leXC("\na: badattempt " + repr() + ":\n"  c0(BoreturnCqssl.SSLA, OS ! may occure wronglzs, e.g. # g s PROTOCOL_TLS_SERVER  - # XXX Various errors can have happened here, for example *# a mismatching protocol version, an invalid certificate,J-or a low-level bug. This should be made more discriminating.O bpo-31323: StEthe exception as strto preventFa reference leak: server -> conn_O&->\G-> traceback;self (ConnecHandler)a E3.}.z.d(str(e))79if :mhatty:'hC("\na: bad attempt from " + repr(gaddr) + ":\n"$@runnyn= Falsg%_stop(H_closeoreturn]Nelse ohared_ciphers\pelf.sslw).s#(sontext.verify_mode == ssl.CERT_REQUIREDG# =pgetpeer6Qupporwbose andF/.c C sys.stdout.write(" client1 ispprint.pformat(W"_binary NTrueADCert R1len)o bytes9 ,7:~1nowk`selected1is `[N+u*PJT_npn_R(j" mdef read\)Kf R dM ? =ock.recv(1024)Fe,B1U else:  return self.sock.send(bytes) *def close()%):!#if?jslconn!4".s.G)BOelse745?runmrunning = True7cif noterver.starttls_s4Pwrap_(]R tRwhilesd>tryP msJead(;"stripped = msg.+2vT # eof, so quit this handler,JFals)N" =?F un:except OSError,# Many tests shu`e TCP ection downFwithout an SSLJ60. T:ocausesC  to raise ] errno=0!F ?pasgkto = Non,A elj == b'over'0upport.verbose and._chatt8sys.stdout.write(" r clientd?\n"fT%. NSTARTTLS'rSYTread S fromf , Z_OK...cOb"OK,  -% ?ENDastdout.write((" server: read ENDTLS from client, sending OK...\n") self.write(b"OK,qsock = 8sslconn.unwrap(f . = Noneif support.verbose andq.uectionchatty:Msys.stdoutAI is now unencrypted; el tripped == b'CB tls-unique'9U! (our CB data N$ get_channel_bi{&(" Prepr(^ ).encode("us-ascii") + b"Oelseq (R4 g n)k!ctype = (#"[w") or "m" v%r (%s)Sback ` % (msg, , msg.lower()) S80except ConnResetErrorb# XXX: OpenSSL 1.1.1 sometimes raisesP|# when t shut down gracefully.C* qs i*" r0` by pe{}\n".format(F JNaddr9_close!@runnn= Fals/OS^Jhandle_eAc("Test) failure:Ad0# nlly, we'd ju top here, but for the testFpharnessE want to stop the server Rself. .stop() (def __init__(%, certificate=None, ssl_version; f5Breqs 0 ca.hatty=True, connectionc@Falsvtarttls_=Mnpn_protocolr> al:dcipher4qcontext%):. if-.4$ =$7Oelse1 ssl.SSLCv(dDg (if is not EG.PROTOCOL_TLS_SERVER)H.verify_mode = ( 12ert  CERT_NONE`_ `* @load@locac#s(TXa_chain1 V X Iset_0( \ ] 1( _X*(J# Q '  1s; =  /0ock$qocket.s(@port$ up `.bind_ 4 1jflag =gPactiv zelected_ = []) *chared_w![z_errorsthreading.T . daemon = 7Senter82 (h{Event()[JW.waitpreturn F mx^*argssAX.join , } .! = 2JK1run6 ock.settimeout(0.05 `.listeWif self.flag:  # signal an event  self.flag.set()Rwhileuactive:?:trynewconn, baddr =Bsock.accepc3if support.verbose and:_chattk8sys.stdout.write(' server: newection from 'Bt+ repr() + '\n'6ehandleBConnoH(\,LJ_.star"jW.join exV bet.timeoutIpass8KeyboardInterrup;_.stopzQBaseEi;as *6 Z'/ing failed: ' eKclose() Adef )R. = False class AsyncoreEchoS(threading.T "):^# this one's based on aA.dispatcher/`X/ (+\17_with_sendAE__init__wertfile0 = test_wrap_V,_side=True,r?c= A0do_%shake_on_Aect=6 .#JR_ssl_ =  +!do.)cAableif isinstanc%., ssl.SSLSocket;g 7@.penf() > 0-0le__ G1breturn _X_0.(WantReadError.Wru a`1EOFDDC GKexcept ssl.SSLError: ]raiseexcept OSE:o as erA if.args[0] ==no.ECONNABORTED{ return self.handle_close()?lseI>p_ssl_acing = False GCdef fPread(9)T"if S(CA._do,\Oshakbdata =srecv(1024nupport.verbo, sys.stdout.write(" server: %s from client\n" % repr()@not "z!eSAsend.lower())j6."OK \d connection %sL{osocketea__init__3, certfile{% ='Kh0ockx.(.AF_INET, SOCK_STREAMGjJPbind_NJ, ''4asyncore.dispatcher.w 5ilisten(5Px#lee_obj, addr" 8newI3%s:q mC%Hr!,( LUm0fla(6NoneactiveC,CQEchoSU(f0.<.% thQing.T Mdaemon = Tru3str\"<%s %s>6.__class__.__name__,~}ZOente\fstart(PEvent.&gW.wait mx*S (" cleanup: stopping server.\n") Pself."(if support.verbose:07sys.stdout.write(" cleanup: joinl threads(s4successfullyeq.# make sure that ConnectionHandler is removed from socket_map asyncore.close_all(ignor q=True) -def start (^, flag=None)H.! = :]2Ring.T<KJ`2run Ractive = Tp1nG.setawhile S 7:tryL!floop(1Pnexcept5Hpass7/op UFalseA()  _params_test(client_context,indata=b"FOO\n",eachatty5, cJ, sni_nameKqsession%1"""yLaunch aj2 a  to it and try variou1adsB!s.Zstats = {}>2oqedEchoS?(,=$+8  7E@Cwith=b.wrap_(..()Ahostf) as sz#s.`((HOST4X1)'for arg in [`, bytearray(), memoryview]sL-ifn%) $s Ep: send@%r..3 % Bs&:arg0outwP = s.+S %r\n" % $if3 !=s.lower(raise Asser|mError(/2Q"bad <<%r>> (%d) received; expected "\n>  % (outdata[:20], len2), %%in6.lower()>9)))>s.write(b"over\n"if connectionchatty:@if support.verbose$(sys.stdoutu" client: closingn.stats.update({'compression': s.(5r'cipher+ &peercert(4get-_alpn_protocol9selectedD nCB5ver (s-s_reused@j'4- &}B s.&e(['serverbs'] = .3s HG "Frshared_ G ?qreturn def tryr_combo(,expect_successM7sreqs=None,&0_op5s=0Z)1"""Try to SSL-! ut**'*!*.EJIf ** is true, assert thae #edif it's fals8 Rfails{Also, ia string!it4he  actually h by thw? 1ertVasl.CERT_NONEqvtype = s'5: "3"$OPTIONAL(,REQUIRED,, }[] formatstr = ( and " %s->%s %sr or " {}d$ ]%%) (5get2k_name(FB B 2>}scontextBSSLC  5. |= client_options server_context = ssl.SSLC( protocol)5.options |=O .2# NOTE: we must enable "ALL" ciphers on the client, otherwise an # SSLv23" will send an3 hello (ra<3 th2!# starting from OpenSSL 1.0.0 (see issue #8322).#ifp!. " =+PROTOCOL_TLS:45Cset_()for ctx in (3,J)\ tx.verify_mode = certsreqtx.load__chain(SIGNED_CERTFILE -VAloca3bING_CA.6tryPstats1Bparams_test ,'~chatty=False, connec3# P mismatch can result\!eiError, or aE# "C^5et by peer" e- dexceptF if expect_successQraisenF!OSAV as e+ Fe.errno !=no.ECONNRESET: e*lsV?not` Asserd(Y!"C 1%s eded with"-!"H0% (eDget_KT_name7)); )jelif (@ is 2Tru);and,{['version']7 A".:Yed %r, got %r Q %,(ts ) class ThreadedTests(unit.bCase):| @skip_if_broken_ubuntu_ssl@def 8_echo(self"""Basic"3 of,ng to a &""if support(bosys.stdout.write("\n"8&F&if@in {;+_CLIENT, zSERVER}aS+in5`lf.subh(=s_[dNAMES[ E`5/=ext serv er_params_test(context, / chatty=True9wnection%) Htclient_`v serverhostname = 4ing(Fwith self.subTX =ssl.PROTOCOL_TLS_CLIENT,h SERVER): `= >B Q=,> JaC@sni_W=`M t.check_( = False{[{ {_assertRaises(SSLError) as epV"5U3B0G 3In('called a fun you should not !' str(e.excep)1~   E )`c1def3_getpeercert(J_if support.verbosGe: sys.stdout.write("\n") $client_context, serverhostname = testing%()E5 = ThreadedEchoSJ(Z=$=, chatty=FalseJCwith  .wrap_socket(.5(),  do_handshake_onBnectK7= j) as sPs.conmd((HOSTf.port)+# getpeercert() raise ValueError while the m isn't}# done.jself.assertRc&s(d))s. X(s.g>=? = HPTrue(7, "Can't  ificate."Haciphern `if sup{.verbos[ cpprint.pformat) + '\n'B""CBion is " + str(S.Tif 'subject' not inQfail("No 8d field9J: %s." %!if ((('organizationName', 'Python Software Found">'),Jz[]"Missing or invalid &C?; "_should be In('notBefor91qAfter',0bO0sl.S_time_to_seconds[z]EacDCRLess(!, [P@unit.skipUnl)have_verify_flags ") need OpenSSL > 0.9.8?1def_crl_check(c1 )5t() % tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0) #self.assertEqual(client_context.verify_flags, ssl.YDEFAULT | tf) P+# should pass%server = ThreadedEchoS(y=$, chatty=TrueRwith *:^ wrap_socket(.9(),=A q_hostname= j) as sHs.connect((HOST,f.port)+cert = s.getpeer('(', "Can't  < ificate."CRL_CHECK_LEAF 9out a lo CRL file fail \'8 |=) a*FY RaisesRegex.SSLError" Ned")^  Q# now% aU. The is signed by t%A.A "O__locations(CRLFILE Jdef test_check(R`if sup"Jbosensys.stdout.write("\n S! =4ing(,# correct 0oiUname) as s:  s.connect((HOST, server.port)) . cert = s.getpeer('self.assertTrue(', "Can't get <Mificate.") m# incorrect hostname should raise an exception7 = ThreadedEchoS(context=$_, chatty=Cwith:^ dclientC.wrap_socket(.9(),=A ="invalid") as sIjRsRegex(zssl.Certx_Error$"Hmismatch, is not c for 'N'.")q # missing_D arg;cauU, tooETN _Value > f"checkrequires5 def test_ecc_(t Drsl.SSLCt(sPROTOCOL_TLS_CLIENTp A.load_verify_locas(SIGNING_CA9set_ciphers('ECDHE:ECDSA:!NULL:!aRSA'>Q = ]ED_CERTFILE_ECC_FNAMENfSERVERr # A ECCF Yja_chain /# ,D f N  Fi ;pAh n ()[0].split('-.s Qc[:2], 0', _dual_rsa_ecc(self):  client_context = ssl.SSLC(PROTOCOL_TLS_CLIENT)A.load_verify_locations(SIGNING_CA9 # TODO: fix TLSv1.3 once ~ can restrict signature|#algorithms. 1.op" |POP_NOEv1_34# only ECDSA certs Oset_ciphers('ECDHE:6:!NULL:!aRSA'hostname =  ED_CERTFILE_ECC_HOSTNAME ooserverfSERVERr #  ECC and RSA key/V pair k'a_chain f<)# correct rshould <  = ThreadedEchoS(=, chatty=TrueRwith *@ wrap_socket(.5(),= q_= j) as sLs.connect((,f.port)+.getpeer('p.assert(', "Can't get <ificate."En ()[0].split('- wi1c[:2], 60', ?-def test_check:L_idn`if sup.verboseQsys.stdout.write("\n"ge, ;pIDNSANSv.Ik_0modQN_REQUIREDj.JL&ruE&0 Y , when specified in severalDdifferent way5idnUs = [3('könig.idn.pyth{st.net''xn--knig-5qa0 (1a-bbA sgäßchen.idna2003.pythontest.net', 'xn--knigsgsschen-lcb0w.idna2003.pyth?)@(@ ? ? bA/ @q# ('kö@@äßB<8< |(# 9-b4a3dunA @ .}T}] for server_hostname, expectedu in idn%s:AA = ThreadedEchoSV (c2xt=$_, chatty=True)MCwith fjD.wrap_socket(.(:[) as Lself.assertEqual(s.NL K.connect((HOST,o.port)3cert = s.getpeer(+9(v, "Can't get  ificate.") # incorrect b should raise an exception7Va0@N ]Y7c0"=" .example.org"ZRs(ssl.CertWjError)MW@def p_wrong_p_tls12({YB"""Cing when the rejectsclient'sLaunch a:CERT_REQUIRED, and check that tryt!to%q to it C!a  ~|u fails.=5""" ., hostname = testing_context() # load client cert4.(_!_chain(WRONG_CERTNrequire TLSUauthentication_eserver_verify_mode = ssl.[_REQUIRED7#[1.3 has differhandshake* maximum_versioneBTLSV.TLSv1_2 A = ThreadedEchoS(%HW=1, chatty=True, connecH)xRwith L5, \"j wrap_socket(.=(),<@q_hostname= y) as s:K:tryT# Expect either an SSL error about the@ rej)ngYH'/ , @ low-levelJ reset (whichI sometimes happens on Windowsu#s.us((HOST,j.port)/aexceptBSSLE>s e`if supC.verbos$}ys.stdout.write("\n[is %r\n" % e/OS e.errno !=no.ECONNRESETFraisL)?or l# self.fail("Use of invalid should have &Ced!"R@unittest.skipUnless(`BHAS_3, "Test needsa"j@def ?@_wroCert_tls13()> >Q! =P EufI 7?min3f @A_V^ [2XtperformDx exchange after (HOST, server.port)) Itry:s.write(b'data'2!jread(4 except ssl.SSLError as ea`if sup.verbos$hys.stdout5"\n[is %r\n" % e/OS e.errno != .ECONNRESET]raise/)`socket?or l#self.fail("Use of invalid cert should have &aed!") def test_rude_shutdown(Q)"""A brutal $fan SSL servergC an wh5in the client when attempting handshake.15""" listener_q`y = th ing.Event(+Ogone*VCs = zGPbind_(s, HOSTB4# `u` runs in a. It sit@n ac() until#!ma' connects. T.0it ly closes1,Gand sets _` to let<mGknowE[:5(' "s.I8.se!0newo`, addrw.''. dszySf,or:\y.waiLwith@c;#c.h ((= , K (ut%@ssl_GAwrapFet(c"+$Epass0e:'"tod00'TtT (target=%ht.star $kfinallst.join(#"\O_verify_e * s?Kp_contexEC(PROTOCOL_TLS_SERVER A.load_cert_chain(SIGNED_CERTFILE) context = ssl.SSLC(PROTOCOL_TLS_CLIENT;server = ThreadedEchoS(W=$_, chatty=True)Rwith *:<.wrap_socket(.9(),6:c_hostname=SIGN_HOSTNAME) as sQ>trys.connect((D,f.port)+dexceptqPErrorre]msg = 'unable to get local issuer certificate'  self.assertIsInstance(e,rCertVerD1ionKEqual(e.v:y_code, 208message, msg<In(msg, repr(e\ GIn(' failed'H8 @skip_if_broken_ubuntu_sslunittest.(Unless(hasattr05, '2oSSLv2' "OpenSSL is comp Aout ?@ supC"@def ~_protocol0v2()<B"""C0ing0$anOd various client options"""F$if;bossys.stdout.write("\n?6tryPcombo#.!  I,c_OPTIONALO0\REQUIRED\+TLS, Fals?if d'3')3yy!]TLSv1J#3nP specr}"no_implies3_hello(@# NoHVv2 =>fsll use !3 <p on recswA%q_q=gaOP_NO_?5  client_options=ssl.OP_NO_SSLv3) )try_protocol_combo(,PROTOCOL/92, TLS, False,HPqTLSv1) < @skip_if_broken_ubuntu_ssldef test_TLS(self):!p"""Connecting to an 23 server with various  5"""Iif support.verboseeisys.stdout.write("\n"Lif hasattrD5, ''N:try_ | \f, TrueKexcept OSError as xp# this fails on some older vers= of OpenSSL (0.9.7l, for instancw{I $ Q"2!to# unexpectedlyed:\n %s\nT % str(x); 3 3Aw  E"Qv1, ''ZaCERT_OPTIONAL2X?-]@eREQUIRED@=X4@]@7# Sspecific+k[w& ov# Will choose |WL_TLS, True,/ server_options=ssl.OP_NO_SSLv2 | %3)Mtry_protocol_combo(,PROTOCOL_TLS,>v1, False,HTLSv1) = @skip_if_broken_ubuntu_sslunittest.(Unless(hasattr5, '?3')"OpenSSL is compiled without ? support"#@def ~$sslv3(self):"""Connecting to anOd various client 5"""H$if.verbosedhsys.stdout.write("\n  ''L3iCERT_OPTIONAL_DREQUIRED_?if %'2')2y!dP7; Pif nov2_implies3_hello(FA# NoD2 =>will use<p on recs%H EI gL/2)_tlsv1 n t'0L $_Nb 3protocol_combo(ssl.PROTOCOL_TLSv1, SSLv3, False) try_protocol_comJ3TLSH,HOclient_options=ROP_NO!) < @skip_if_broken_ubuntu_sslunittest.(Unless(hasattr:, "O_1")"TLS version 1.1 not supported."@def utlsv1_1(self):"""Connecting to a {.1 server with various  .Ga TesDagainst olderMUs."""2$if.verbosesys.stdout.write("\n_B' 2.1'/R9if 'x'2'5/#K{{3{7>$2@2#_1BO #R L)>2)2)2)2)232, ]/2' ) 3|<92K bKE$  ; ocol_combo(ssl.PROTOCOL_TLSv1_2, sSSLv3, False) try_protocol_combo(6L3TLSJ,JQclient_options=YTOP_NO%) > ' ?.2'0#v1Ln5?v1_$8y def test_starttls(self):-"""Switching from clear text to encrypted and back again."""E msgs = (b"msg 1", b"MSG 2 STARTTLS 3 +4 4END5 '6"Jserver = ThreadedEchoS(CERTFILE  _S_=True:ochatty1Ponnec';wrapped =QRwith grsocket.(M .setblocking(1cs((HOST,bj.port)+`if sup.verboselys.stdout.write("\n"Gfor indata in 'Gko."" p: send%r...\n" % >3if  <C'1out!= 1 &/elR s.(cs.recv(1024B#= .strip().lower#ife == b"Amsg.6sg(b"ok"E$# ;P ok, 1 chJsecure modeis{R*2 %ra!, &2TLS'O %oj" =rM_s/#u elif" indata == b"ENDTLS" and msg.startswith(b"ok"): "# 9P ok, /ch back to clear text;if support.verbosecvsys.stdout.write(R*!" client: read %r from server, ending TLS...\n"M %)#s = conn.unwrap(&ped = FalseJ/el"eO\n"  @closx3`ection} 53if 0 8b"over\n">K`s.send4rei,def test_socket~W(selfMA"""U%>Rreateanage SSLo<Fs.""] = make_https_q , certfile=SIGNED_CERTFILEAQ# tryzVonnec F'\n'XDd open(t, 'rb') as fpd1 = f.rqd2 = ''U# now fetch the same SHTTPS80urlI://localhost:%d/%s' % XA., os.path.splitF)[1]0con = ssl.c_default_5(cafING_CA@f = urllib.request.url<@url,`=K9;tryI1lenKinfo().get("7nt-length<@if d5P(int(W) > 0~,#: $ BO$ %d bytescremote_ '%s' % (len(d2),3)kfinallU$f..assertEqual(d1, d2) asyncoreV`"""Che5he example 4 integra0] U"\n") indata = b"FOO\n" server = AsyncoreEchoS(CERTFILE).Rwith 3:Js = test_wrap_socket(.&()G2.connect(('127.0.0.1',^[.port2`if sup.verboseVys.stdout.write("" client: sending %r...\n" % i- O3out^zs.read(;"S2 %rl b3 !=.lower()#elf.failAbad <<%r>> (%d) received; expected Q`3% ([:20], len/),# 2:} sPb"ove' 6@clos!0ion' d s.&e<r _dy72defpPrecv_W(selfp"""Test0v()Xnd() and friends."" sYa"\n") P = Th/edHAcertreqs=ssl.__NONE<ssl_version?PROTOCOL_TLS_SERVERI ca s=6hatty=True1Bionc;VFalse]p*a_side=z3Ofile0ca_6M0_! fCLIENT^ss@HOST(# helper methods for standardi%* signatures&r_)__intobytearray(b"\0"*100Kcount = x"cvPb' return b[:count] def _recvfrom_into():"- b = bytearray(b"\0"*100))c, addr = s.Zb1?ret# (name, method, expect success?, *args, Gvalue funcjRsend_D]s = [ ('#P', s. , True, [], len),1%to3to, Fals6`"some.Oess"D 5allE9all{ambda x: None] *whether to54 !! #  . ('#Q0  C"', x,9|]s Ldata_prefix = "PREFIX_"9Pfor (S_7B_!,  &qret_val8U) in F>ods in@ = (+).encode('ascii'r>tryX0ret)(l-/0msg ing with {}".format>self.assertEqual(ret), msg=msgI0outo.read('4if *2!= o.lower_fail(#a"While 0<<{:s}>> bad "H 3<<{ :r8({nout:d}) received; D %bed <<{L inK%\n ==^[:20]:S=len(7 + =gA ninF@except V?Error as e)#ifQ'=`FailedLIsoEto succeed.\n".format(name=meth_ ?)  if not str(e).startswith(R:Sself.fail(#"Method <<{`:s}>> 70ed l unexpected "J exception message: {exp:s}\n".C 3, exp=e6 =L)) 9Efor ;p, recv_eect_success, args in#>odskindata = (_prefix +d).encode('ascii'>tryXrs.send(c8#0outx& = (*/4if 22!= Y.lower()eGPWhilebeiving< UAbad G 3<<{ :r({nout:d})_?ed;2<<{L inK)=i[:20],i9 S=len(7)3=gA ninF{ ValueError as e if1'?Failed toA 1to 7ed. ` 1] # consume"L{s.read(!# -1, buffer) is supported, even though+#9notg@= b"  r = bytearray(len(dataG)) self.assertEqual(s.read(-1, buffer), len(data< 1!, , h# sendall accepts bytes-like objects1if ctypes is not None:#uG# =,2.c_* 32sx!= .b.from_R_copy 9#s.(C MQ)Make sure!msg et al are disallowed to avoid# inadvertent.1cloK!of and/or corruption?of the encrypted6istream+ Raises(NotImplementedError, "msg, [b"*"]#IArecvI?100C!  aa_into,`array(p q.write(b"over\n")UValueK, -1VzS 6"ad6 s.#e(def test_e`_zero()*server = ThqedEchoS(CERTFILE.0.__Hr__(+ddCleanup(+axit__,5 = socket.create_connec((HOST, IGportb'.ao [Rwrap_e(s, suppress_ragged_eofs=False<}]l # R/3(0) should return no*-( g ^cv(0), b"") /ad)Qq2# S@rblock iother endvat2Oing(=%!cvsDrS)), 04non_w!,certreqs=ssl.__NONE<ssl_version?PROTOCOL_TLS_SERVERI ca s=6hatty=True1 connectionchatty=False) with server:s = test_wrap_socket(.9(),26 ZR_sidez3certfile=CERTFILE3 a_6s3ert_reqs=ssl.kO_NONlssl_version;PROTOCOL_TLS_CLIENT^As.cos((HOST,nl.port)+setblocking( d%# If we keep sending data, at some point the buffersAwill be full and+Rcall  3buf = bytearray(8192def fill_r*()Kwhile True s.J(buf[self.assertRaises((SSLWantWriteError%6ARead5(),)) # Now read Qaoutput5discard it5 s.close(l9ehandshake_timeout(H# Issue #5103: SSL 4 must respec L2 = gAF_INEhost = "127.0.0.1"JH up `.bind_ (cpstartedMhLing.Event($finish = P Qr.listenIIq8.sec%[]Bnot pr, w, eqelect.s"([C], [60.1]#ifK in f I# Lehang around rather than having@Q# it _d by garbage colOion.7s.append.accept()[0]1for=9.N ItT (target=Gh!t.5`ed.wai:try {c .c>=;(0."Pect((& ,  (0# Wowattemptyjime ouB6 TRegex~0, " dB"  test_wrap_socket, c) "finally:!c.close(//tr+2 = _.(.AF_INETC]< = ((.settimeout(0.2J# Will attempt handshake and :M outself.assertRaisesRegex7`out, " dB-",Dc.connect, (host, port)v+finish = Truekt.joineserver12def_accept()# Issue #16357: &) on a SSLSW created throughb#$Context.5().$cEcsl.SSL0(ssl.PROTOCOL_TLSD3.verify_mode?CERT_REQUIREDcc.load_5locations(SIGNING_CAb2cert_chain,0ED_gFFILE1G   = "127.0.0.1"0H up `.bind_ (csa-", `_side=.?_.1%) 0evthreading.EventgPremot6Nonypeer = yd(h,0non"l L , >"7|r.listep# Block3theDwaitqion to c0evttP  +c.send( wrecv(4)N LTV(target=ht.stark# Client Suntila setupperform a ;cQ=- (6(%vb'data'! @_add=$0get8nam  (l# Sanity checks;8IsInstance , 5`Equal(", 0get$w@enot sl.SSLContext(ssl.PROTOCOL_TLS)  with context.wrap_socket(.p()) as :;B? self.assertRaises(OSError5*cm37I.getpeercert(Q Equal(cm.exception.errno, .ENOTCONN) def test_do_handshake_enotconn()0 = !BSSLC 01?no_shared_ciphers-client_4, serverhostname =4ing# OpenSSL enables all TLS 1.3 z, enforceQ2 forU"c!.o2s |POP_NOEv1_341# FUdifferent suites on P and master6E.set!"AES128"  -7256-<ThreadedEchoSR(b=ML G ,= q_=  Lf15 s.ect((HOST[h.port)]grIn("no 7"8N _eLs[0]version_basic5""" B!wsASSLS.C5().-CMore,are done in th_protocol_*() methods>wv_CLIENT!:e.check = False'verify_modCERT_NONE,*OFILENCssl_0=d_SERVEREqchatty={+ OA <vFIs(sf, Noneh-1_sslobj/Zif IS_OPENSSL_1E4HAS=self.assertEqu al(s.version(), 'TLSv1.3') elif ssl.OPENSSL_VERSION_INFO >= (1, 0, 2):<Kself.assertEquy2yse: # 0.9.8 to 1.0.1e *In(':2')Is(s._sslobj, None+ C-@unittest.skipUnless(CAHAS_j1_3,*! "; requires 1.3 enabled OpenSSL"@def 0_tls1_3(context =BSSLCPROTOCOLN3 .load_cert_chain(CERTFILE*options |= (POP_NObAv1 |_2Dk with ThreadedEchoServer(=a) as s @%.wrap_socket(."()A <s.connect((HOST,e[.portO/cipher()[0], {+_AES_256_GCM_SHA384').CHACHA20_POLY13054?2564 b4128b.}yX@qhasattr{, 'minimum_N/')"| 1.1.0gtmin_maxT client_hostname =^4ing(1# cG09.BTLSV.@ >(ax%>_~#S only%^ @ aZt  = &9 5r$1.n#t.minimum_version = ssl.TLSVe Cv1  server_context.maximum_v->5_1 Awith ThreadedEchoSR(R=aR) as :CGeclientwrap_socket(.9(),=A q_hostname=  Hs.connect((HOST,}.port)){self.assertEqual(s.@(), 'TLSv1.1')5"# D 1.0^ 1.2 (mismatchfPO.min2 @@~ >~>]3pRaises(SSLErrore+In("alert", str(e.exception))  @unittest.skipUnless(hasattrC,;, ' ' "required OpenSSL 1.1.0g"yHAS_SSLv3, C!s @ supB@def _min_maxp_sslv3(r)S $, #! =U4ing( >-Y |Y;0 pECDH, "|  s f-enabl default_ecdh_curve # Issue #21015: elliptic .-based Diffie Hellman key exchaSnge  # should be enabled by default on SSL contexts.8 = ssl.SSLC#(PROTOCOL_TLS)3 .load_cert_chain(CERTFILE*# TLSv1.3 s to PFS key agreement and no longer has KEA ins# cipher name.options |POP_NOGv1_3DPPrior@Open1.0.0, ECDHa`s have$HBexplicitly using the 'ECCdraft'E alias. Otherwise,D4our0Dlistapreferc-based%sCautomatically!ifOPENSSL_VERSION_INFO < (1, 0, 0):J<R.set_e4s(":" with ThreadedEchoServer(E=a) as s m@%.wrap_socket(."()A <s.connect((HOST,ef.port)+self.assertInrDH", s.q()[0]) @unittest.skipUnless("tls-unique" in]CHANNEL_BINDING_TYPESv &"'E' channel bind?not availh@def R_tls_~a8_8("""Test k jA."""( up4.verbosejsys.stdout.write("\n")@sclient_@host! =4ing(F / =P $>gchatty=TruwS3ion;WFalse )  rxn_J= 4Q# getMdata0cb_ .gv_   g *\" got : {0!r}\n".format()G# check if it is sanB&\5sNotNoneV Fsion() == '',_Equal(len_N, 48Q&el * self.assertEqual(len(cb_data), 12) # True for TLSv1 # and compare with the peers version5 s.write(b"CB tls-unique\n"),J_repr = s.read().strip(2 C,c j .encode("us-ascii"))# now, agai client_context.wrap_socket(./()server_hostname= }) as s:Ys.connect((HOST, An.port)CCnew_ rget_channel_binding("`if sup_.verbosexsys.stdou &"got another   : {0!r}\n".forma`L!# is it really  #No\M/, v :IsNotNone hc]cq() == '?.3'l .48/elM ?W  pdef tesQmpres) $, ! =K4ingPstatspparams_{(` B pchatty=#, 48ionGJsni_6  " cW:: {'['#'']?In(-@, { m, 'ZLIB', 'RLE' }P@unitc.skipUnless(hasattr(ssl, 'OP_NO_COMPRESSION'i]"ssl.3q neededpAthis]`_disabled(i_context, ho stname = testing_context() dclient.options |= ssl.OP_NO_COMPRESSION8oserver8 stats = @pparams_(,#,{chatty=True, connecG@sni_:2=hoC0self.assertIs(s['compression'], None) i1def}B_dh_(B!):# Check we can get a with ephemeral Diffie-HellmanF<    # scenario needs TLS <= 1.2n5uTLSv1_34W.loadhDHFILEg _set_ciphers("kEDH"+  "["U"][0]q1parj.split("-:if "ADH" not in 2Pand "c:DHE..fail("Non-DH }S: " + 3[0]P@unit.skipUnless(HAVE_SECP_CURVES, "secp384r1 curve support LIf(IS_OPENSSL_1, "TODO: Test doesn't work on 1.1.1KQecdh_m ", U auto%  FlF. "?ECDHE:!eNULL:!a:N' |"`1&#~k(* E,("ECDHE:!eNULL:!aNULL") server_context.options |= ssl.OP_NO_TLSv1 |&_1Fstats = Nparams_test(clienta,#q,Cchatty=True, connecGsni_name=host %) 7#2 / curve mismatch) \0 = 4ing,(u E.set_ecdh_t("prime256v1 4secp384r3 ciphers("ECDHE:!eEEtry:9s'Jb+(K/aexceptSSLErrorEpassJelse"# OpenSSL 1.0.2 does not fail although it should.L~if IS_OPENSSL_1_1_0_%Pself.O$("5didl"1def _selected_alpn_protocol(N)e.() is None unless ALPN7use  EMKI4ET.assertIs(#[' ~1'],TP@unit\a.skipUh(@HAS_p0, " support requiredM C_if_Auses 3s by thea7,  Es(['foo', 'bar']zH pn_protocol'#], None) @unittest.skipUnless(ssl.HAS_ALPN, " support needed for this <!")L1def_alpn_protocols(self):#sfserver = ['foo', 'barmilkshake']7P_rs5V(D1], S,),%bp%6, 'Ohttp/3.0 E4.0'c8fclient, expected in 7H:context, Khostname =Cing_(E 9N.set  @ @"sp}:try@stataparams(O ;N;!chatty=TruesconnectionB%@sni_= pexcept SSLError as eTe(Fif (vs and IS_OPENSSL_1_1_0@>)|* VERSION_INFO < (1, 1, 0, 6)># OpenSSL 1.1.0 to e raises hand e Q.assertIsInstance(>, 5/ls! msg = "failed trying %s (s) c).\n" \ "wz;, but got %%s from the CGs% (str(8 , I3)Nresult = ;#[' :TEqualO3},% A""k s'][-1]bif len5/['@) else 'nothing't I ! A" }dd1sel3'_nl k"# 'ed_npn_proto col() is None unless NPNcused client_context, serverhostname = testing%()Etstats ==pparams_0(` Cchatty=True, connectionG@sni_=elf.assertIs(#['npn_protocol'],Q!) qP@unita.skipUe(ssl.HAS_NPN, "ssupport needed for thisP"1def_ns(self):lr['http/1.1', 'spdy/2']2+0Q(?&, V,),2e%] 2 -E,0abc1def(#Es, expected in EH:+IIM.setOs? ?!?wF{3Kmsg = "failed trying %s (s) and c).\n" \=c "was9, but got %%s from the AGs% (str(u ,   A0)`result<n TEqual[J , L,% ""F o'][-1]dif len9;) else 'nothing' D "X@def qJrsl.SSLCPROTOCOL_TLS_SERVERp .load_cert_chain(SIGNED_CERTFILE86oth^x @ wn(SIGNED_CERTFILE2)  client_context = ssl.SSLC(PROTOCOL_TLS_CLIENTA.load_verify_locations(SIGNING_CA9return serverX, oth  def check_common_name(self, stats, !):.1cer`['peer%']!=.assertIn((('ZSName'N@,), 6['subject'])@needs_sniP@test_callbackalls = [ telf.sni<#s( ./@host = False/ 0_cbd_sock,, initialtGs.append((Q9 9(ifg is not None(1ssl. 5) [R.set_xbCKh _params_(#,chatty=True0='supermessage'Ge# The was fetched properly, and theificate was# changed for*Ponnec.&.aEqual(X, [(""()]1CER4 selectedeI(t, 'fake' Y] xed withx=q.G( :`4ED__HOSTNAMEj0# C disabling0Gl p'notfunnyDCertacdidn'tZ%P@  i def test_sni_callback_alert(self): # Returning a TLS ' is reflected to the connect+eclientFserver_context, oth.0 = .2Es() Mdef cb_rsl_sock, nname, initial]E ssl.ALERT_DESCRIPTION_ACCESS_DENIED^R.set_pN()CBwithassertRaises(SSLError) as cmQstatsOparams_test(C,{Gchatty=False5='supermessage'Equal(cm.exception.reason, 'TLSV1_ |'`@needs y_raisingi fails1on handshake*2ure.t<R4?1/0 s\5, \r: support.captured_stderr( SSSLV3HANDSHAKE_FAILUREIn("ZeroDivision2", >.getvalue()Swrong,__typeI1 1 terminate5%on#Cn internal e=Q  (U"foo" P  Zulient_context, server_context, chatty=False5 sni_name='supermessage')u2self.assertEqual(cm.exception.reason, 'TLSV1_ALERT_INTERNAL_ERRORLIn("TypeError", stderr.getvalue()) def test_shared_ciphers(!):#eclient3 CP host! =N4ing,( EE.seto"AES128:AES256"4  4 -expected_algs = [d0 , - !# TLS 1.3  are always enabled1"TLS_CHACHA20", FAES"]g@statpparams_}("iD!= #[' U'][0]Greater(len(KF), 0`@for , tls_versitbits inMM if not any(alg'B K >Pfail(: read_write_aftlose_raises_B_P = ThqedEchoSu(u=$%(, ]Cwithm @I 6.wrap_socket(.&()U H= As.connect((HOSTm.port)+}(BR (V0, s{d, 1024O8 , b'hello'v|endfileTEST_DATA = b"x" * 512open(sup.1FN, 'wb') as f!f.((YaddCleanupSunlink, c8> = ssl.SSLC(PROTOCOL_TLS3.verify_mode?CLREQUIREDcP.load5@locas(SIGNING_CAb2cert_chain,0ED_gFFILE1a   8H u=ket(socket.socket()) as s: s.connect((HOST, server.port))/with open(sup$.TESTFN, 'rb'eNfilehw`s.send (^%elf.assertEqual(s.recv(1024), oq_DATA) def test_session(self)client_contexthostname =G4ing(# TODO: ds aren't compatible TLSv1.3 yet .options |= ssl.OP_NO_8"_35`# firsa1iona4out`sstats =_params_({ Cr@sni_=( {#['%']YSTrue("8.idGuGreater'time, 0,?out/ `has_ti[#ifENSSL_VERSION_INFO > (1, 0, 1Y1`P_lifeO_hinaFalse(F_reused']>_&s.1ionsM1ess&['accept'] 1@hits/0{!# ]=/,  6=261/ @@ion2 ,l50.idz 2/TIsNot2, G _.8i=@9outanother on9|.Oion3NotEqual(session3.id, session.id) self.assertNotEqual((32/ ss_stat = server_context.6(s(3b_&['accept'], 31@hits/51) t# reusee againsparams_test(client,C+=, sni_name=host QTrue(#[';_8d']14Etats,%']^Oion4 2qzGreater3U.time8=:out@8outCoD4do2o@def ;_handling(%):[  ! =P4ing: E2, _, _2xu# TODO: U does not work with TLSv1.39 l.options |= ssl.OP_NO_4_425 j7 = ThreadedEchoSL(L=$, chatty=False+z wrap_socket(./()Xq_Z as s1#is None before <Ushake/M^,B.2X9.connect((HOSTo.port)h" wMRaises(TypeError)ReR = object Fptr(e.extion), 'Value iba SSLS#.'mTus # cannot session after handshake with self.assertRaises(ValueError) as e:9HBs.seg#= (\Equal(str(e.exception),3[ /'CI.') I client_context.wrap_socket(.(server_hostname= -s- fbeforeS and .th# connec3 wstablished.Q((HOST, ~.port))S#0.id=?.id;85_reused, True27#dre-use$ a different SSLC y,E>1 , S;refers to  def test_main(verbose=False)p`if sup. im warningseplats = {.'Linux': `form.l_distribu H'Mac0{mac_ver%xWindows)Zwin32+}t.catch_(t.filter(M%'ignore' r'A\(\)'R1funs are deprecated .*gPendingD'BionW @for j , m1 in|s.items ! =.(K!if@*6[0]-! = '%s %r' % (W6Ybreak$?els@B = repr( h (qprint("Assl:ing with %r %r" %  (ssl.OPENSSL_VERSION, _INFO)) <tprint(" under %s" % plat+HAS_SNI = %r/o6OP_ALL = 0x%8x87Etry: OP_NO_TLSv1_1OVexcept AttributeErrorhAass zfor filename in [CERTFILE, BYTES_"@ONLY , 4KEY+;:fSIGNEDS !2,uING_CA,73BADW ADPQ EMPT]if not os.path.exists(f))!raise support.TestFailed("Can't read certificate, SJxtests =B`ontextVs, BasicSocke1SSL!MemoryBIOSSLObjec7impleBackground/0 The>]%ifis_resource_enab'network'.append(N [)Utou_info =`ing_setup( mrun_unitk (*s.gfinall2]cleanup(*) if ____ == "__main__"dP() im4 io Ushlex Ttring # The orig S$ data set was from shellwords, by Hartmut Goebel. 2= r"""x|x| foo bar|foo|/  %$ 80blae fasel$Bbla|q x y z$0xxxAy|z| 0 \xPB|\|x-\ \26:B a"bar" 1oo||q "foo" q "bla"|#%9bar#] !UBU'bar'a'foo' q 'bla'||| 9 #a !r/B` blurb a" baz| |;;'; ;""|""| ''|''"r!""N&''2"" Q :I'' '@p4a \""|\@"\"|\ bar"|"foo\ bar"| "foo\\ b  6\"|\4"5$\""|bar|\|"! d dfadf&|e*\"* +xB , - +)\''|\|''| ' ]''|  Q df'a\ 'df'-\|d \J"'Sfoo"|%\x3\|xx4xQ A "| xx|foo|\|xx\,4 x\k  \ 8# ,5\'' \/}J 4Q"fo'o"4|4 'don'\''ts?&?'|t ^ #bar\nbaz :-) ;-)|:|-|)|;$ áéíóú|á|é|í|ó|ú| """ posix_data = r"""x0foo[u/  %$ 8p blae fasel$Bbla|q x y z$0xxxAy|z|  "|x!\ %| r .)"6:> U "  "_"bla"Obar  !oo r^'bar'r""' Z'bla'rr f ` blurbj!z|habarbar|[7 ' 7""|| ''|"fr)|D 2"" |2G'' '8K0| "rT  <pD\\1yU8Wd &' ( ) '&:\'|e}NhT_S !\xXoo\x"|foo\x| "foo\ "|!|  xx4 xx\\3S xx"|D1x\xW\ x\x\+\}6bar7z\foobar&.\'(')'AR1'foT" 'don'\''t'6t<? \\?0\| S\ bare u!0foo3#bar\nbazf| :-) ;-)|:-)| áéíóú|  """ class ShlexTest(unittest. Case): def setUp(self .data = [x.split("|")[:-1]<' for x in 83vlines()1X`posix_&^kdDj*@itemvpK T[0] = .replace(r"\n", ) RX"Y^,@, commentsrange(len()#Pl = s$f[i][0]V=_7*assertEqual(l?I1:],-1 "%s: %s != %s" %. h1)) <@oldS!0retB_6lex(io.StringIO(s)tok = lex.get_token(while tokret.append(tok/Q return retP0"""  ting with yp parser,;R.,mGTruecaCompat4cibility interface}Ielf.qj*0]\H \1> ^89l, 81:]BaSyntaxAmpersandAndPipeWPhandlAof s?xof &, |d# Could take these forms: &&,.@&, ;!;&A # of course, the same applies to | and || #'se should all parse-Aeoutput4 for delimiter in ('&&', '|;8s0'||8&;Y;|'):9src = ['echo hi %s fbye' %,6l6/%s4]45refjGhi',` M{ ; ss:srcs = shlex. (ss, punctuation_chars=True)<result = list(s!self.assertEqual(ref, 7, "While splitting '%s'" % ss) mdef testSyntaxS)Semicolon(]"""Test handlNAof s8bqof ;"""]1# CdCtakevforms: ;, ;&&1?the/;;^4PRedirect%>of cour/?<, +><?out 0 / ? 3OPare&*()h(T]hi )'!'(hi)'] ref = ['(', 'echo hiS)'] for ss in src:s = shlex. (ss, punctuation_chars=True)8result = list(sself.assertEqual(ref, 3, "While splitting '%s'" % ss) edef testSyntaxS)pCustom(Z)"""Test handlKAof s5_awith c@ 1"""g@ref B0~/a6&0b-c --color=aut] ||dW*.py?fsL"~/a && b-c <a || d 3}1w} 6"|"_Ext1TokenTypesm`that t'Cs ar ft8 as expected.leource,!("('UF?c',0A [('a'), ('&c bG2 (';_a')])  kobservedVwItQ.get_(Cif t == s.eofA#]break'90[0]-s.Jt='c'MOelse3 a3.append((t, tt) 6| nPpInWordC 8any._@remofrom wordz `'a_b__b SF='_'NotIn('_', s.f+2, [ :'_ ?c']WithWhitespace w1_, behaviour is,+ V  %&%,# ynFalse, soll be based on# YrZ2^X) s.whitespace_split = True x# white"!is#Q, so 4ting will be based onB Cself.assertEqual(list(s), ['a', '&&b ||Qc']) @def testPunctuationWithPosix(Y!):("""Test that p1_chars and p8 behave correctly together."""O# see Issue #29132s = shlex.('f >"abc"',c=Y,)Hf >!ab} \\/\\C\"EmptyStringHandling 0ars>@of e;! s<Gs ishK/edE1999Bexpected = ['-)2$2for in (False,<Y@"'') kK0 = +(s s&$, ."''", '  z \Quotepsafeunq.ascii_letters +`.digit'@%_-+=:,./'8unicode_sample = '\xe9\xe0\xdf' # e + acute accent, a + grave, sharp sPH"`$\\!' + df `(''), }  .0w9), B ' file name "u unmU!%see % u),< "1"21'"'V0'\"9 '@ # Allow thisF0 touwith oldpy if not getattr(1, "s", None2@methuuPdir(S/$94if 'p.startsv(!") A != zCompat"1dele,Y ) ____ == "__main__Eunittest.mainL() # A test suite for pdb; not very comprehensive at the moment. import doctest import os 4pdb$%syEtype @unit(ubproces"textwrap from conClib fExitStack!$ioStringIOf0sup # This little helper class is essential@0ing!s under .`.%_m_FakeInput)T.mock%patch }qPdbTest5(object): """C manager that makesdPdb ins easier.""" Fdef __init__(self, iei." =;Senter< 5real_stdin = sys. xY6 = p)+elf.orig_traceO1get() if hasattr(sys, '') else NonexH*exc1if  *@) y$pdb_displayhook(1"""$smwcustom ,Bpdb.E>>> Wfunction(foo, barX0...nCPdb(nosigint=True, readrc=False).set}(IFpassYwith [3.j'foo', <&_q[0]>(3)OH1-> \(Pdb) foo17bar&0@2 34R Zbasic_commands]""0 ofR %_2T='default'r2foo=:i8 0 O+10Pnever_executed?V`'afterK'uK'...`return.upper() ]hx&Qret ={_2('baz7retwith PdbTestIn+put([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE ... 'step', F entering the function call7Gargs7vdisplay2 2Glist2/jsource1b/c|backtra.u.p up to _*()eGdown7 9_2() againA6nex # Ap@o print(foot3vzor loophY h in7Tuntil8# continur out ofA `execut@;barcjump 8w!# over second fkTretur"#  Tretva$# $;KvaluU5e',I5]): / /3> <_.S5pdb _basic_commands[1]>(3)'z ->! =I_2('baz'HQ(Pdb)K--Call-- Z0]>(1Mm-> deffoo, bar='default'#afoo = O0bar53q 1 ->p{1 25{]4 3bi in range(51 4Ji{8 59 6 g%10h7( bnever_A#ed8`'after%5 9# '4...! 10foo.upper|Q[EOF]y!bt 1... 2[8)f*->Q^D+(pu= test_funct ion_2('baz') (Pdb) down> (1)'Rfuncta\a-> defI_foo, bar='default'):}Anext"2print(foo n?bazv'3vfor i in range(5Ostepv'4viQuntilm01234w"5 8barz'6z {)10|ojump 8y'8y~'after forlRreturn!1...1--R#!--".10q->'BAZ'U2-> foo.upper(Rretva.52continueH1BAZe""" pdb_breakpoint.(@"""TcL L related to =1s. b/>>NQ0... import pdb;.Pdb(nosigint=True, readrc=False).set_traceI1 23"4)First, neclear bdb state that might be left ov9rom previousFs!Otherwise, the new0Kget assigned different numberUfg=Bx.2 = =bplist = {};Bbpby = [None] 1Now . NORMALIZE_WHITESPACE isTed becausEoutputs a tabk"stop only" and "ignorQ1xt" lines, which we don't want0putGherewith PdbInput([ # W?: +nh'J 3',disable 1L1 10condition 1 1 < 2', ... 'break 4 ,|clear 3Z condition 1nenable_ /commandslp "42"_`print(, 7*6)', # Issue 18764 (not about zpoints)3 (3), P2-> 1`R(Pdb)! 3BP 1$:N`2disbDdwk:4 (Pdb) condition 1B4 1 is now un&1al.'=cenable:E &d v 1 at #%0(4)TP_func(A-> p2CzCM2allAs? yY2)gt! 5id4a)N&onkXo0'5 3/-_""" def do_nothing():;EpassJsome$242)#J6lis,G"""Test the ! and source X@ of | y@>>> Tc_2(foo0...z importC!C,. ''2...\=^'more?cod.to*?mak*a)OlongOistinuseful1return fool gApdb;Pdb(nosigint=True, readrc=False).set_traceTIQret =v_2('baz')with Pdb7Input([ # : +ELLIPSIS, +NORMALIZE_WHITESPACEt!',/" #dfirst Z /Fstep/ into se5d0c}ing to EOFc@ 1,3specific lines/x-;invalid argument, 'next', # step to import ... 'next', *Oover,H ,into do_nothing\qlonglis` # all lines*`sourceIAsomeKi 5 of functionA`fooxxx;P that doesn't exi continue',Z5]): test_!()`> (3)" F-> ret =Dc_2('baz'jQ(Pdb)Ey2 1j def:(5 2% P pdb;.Pdb(nosigint=True, readrc=False).set_tracep 3 ->LQ[EOF]C--Call-- FZ0]>(1F#_2.-> c_2(fooxE E 9J3pdbS3 ".*4 4*'C...'M5W'more6H'cod77'to:8H'mak:9&'a9$10''i5ing! 1u'useful/* 1L' 7 3return fooR A 1,3o!! x0*** 525 ds,  lyAstep .%..u.py(...)Z [_5"2pasNY3a0do_ [xrint(42`Z """ def test_post_mortem(): """Test   traceback debugging. .r>>> defNfunction_2M0...TB try^11/0Dofinall)print('Excep`?!')~ |import pdb;.Pdb(nosigint=True, readrc=False).set_)()2 0NotOXched.with Pdb\Input([ # docW: +ELLIPSIS, +NORMALIZE_WHITESPACElp'next',EEstep over e#-raising call<b:<`get a  +5lis- # { code o )['downNinto&o#` :continue',]^z_ I ZeroDivisionErrorCorrectly re{3> <.u3pdb q[1]>(3) !-><`(Pdb) "# d by zero(P!btj1... 2]>(10) J04-> V10 S1 2!.t 3 ->Ph5 4"  Q[EOF] ?@ A >  9 5B9 'K "De""" pdb_skip_shis illustrates the simple case of module skipping. >>> def _module():0..." import stringpdb; pdb.Pdb(I0=['.*'], nosigint=True, readrc=False).set_trace()Y>ng.capwords('FOO')with PdbTestInput([@z'step',continue]>> (4)#->@ c`(Pdb) t--Return--/a->NoneM)1""" # MA for 1ing4KB of ; that makes a callback mod = types.HbType('51_toE') exec('foo_pony(E): x = 1;WQ(); r) ',.__dict__) I_A_["""This illustratess= into other codeTBpr M|'Nmod.~|,x(TEpass # providPometh@to "A" toy} X5f OCall "&2)w- .3x  t* \  ules_with_ca8llback[1]>(10)() -> pass # provides something to "step" to/(Pdb) continue""" def test_pdb_ _in_bottomframe():2Test that "-" and "next" workperly in G H (issue #5294). UE>>> functionr0... import pdb, sys; inst =.Pdb(nosigint=True, readrc=False/Inst.set_traceL 2bot=jB._ge ()lphackerya ge pe right7Qzprint(123&4))with PdbpInput([0doc: +ELLIPSIS'*',|break 7 C,]C_3> <.$5pdb q[0]>(4)0 T!->*.1C053svB`point K/at5)!:7Tf12+7 \3y08y 4ky 4}pinvoke(_sod, arga"""Run(.>getattr( ", B)C @run__incorrect_argument-0"""1runruneval : :` first@[pti =a'2',]5R2pti,'run', lambda x: x=Ty (most recent call lastYTypeError: exec() 1 must be a string, bytes or code object2 $4?val91 def test_pdb_run_with_code_object(): """Testing run andPeval 3 3 3 as a first argument. F2>>>/0PdbO'Input(['step','x', 'continue']): # doctest: +ELLIPSISK0... pdb_invoke('run', compile('x=1Q qexec'))B$> (1)()...`(Pdb) --Return--=a->None"@x 1 B9x=0  + ?val  """ def _next_until_r94_at LevenZP that stops after a H/H/H issued at a adebug Wjfunction_2I2 = 2 D BQimpor;.Pdb(nosigint=True, readrc=False).set_trace(y6 )1endQfrom bdb Breakpoint#.@? bC!',P@' L # y' oI p9q]y =w3> (3)6Z!->R_v* t 1+B0]>:xk-Z0]>(2E-> x0|zH* 2~> (4)6function() -> #_2(Pdb) continue,`> (2o-> x = 1i|1--R!--13R->Non2oa-5u16;end """ def_ command_for_generator():?"""Testing skip unwindtack on yield for =s"^#" _ OE>>> 4geng0...M0,>nv2V42import pdb;.Pdb(nosigint=True, readrc=False).set_traceI2t =C :tryv0if (it) != 0"&raise AsserYError\%H except StopItion as exjif ex.value1"gprint("finished")with Pdb7Input(['step',g#4 i #3|#']LA_ ?pdb2 #O-> i%}3 ) -> try: (Pdb) step> (5)3function()W`-> if ;(it) != 0--Call--5*R0]>(1'ge1def(()x32xqyield 0atp73preturn 1q1--Rh5"->s?-> `StopIt8Cion:*}7 }lzcontinuefinished U""" (>pdbcoroutineC"""Testing skip unwindtack on Efor = s "#" S >>> import asyncio N0...U awai:.sleep(0#/ LmainPpdb; FPdb(nosigint=True, readrc=False).set_trace9 [ <dloop =I.new_event_ h.run_untilaplete(z H1Lclostprint("Z&")with Pdb2Input(['!',\#KF #3a#']gL S[2]>(S#->p.(t,Zto *| ncio.sleep(0) (Pdb) next> (3)3(b -> await asyncio.sleep(0=4+Internal StopIteration/2Lmain 4Astep{--Return--* a->NoneYrcontinu,finished9""" def50'dgen():3Testing skip unwindtack on yield for Ncs"#"  O>>> imporh{ a0...g1F#2f>4_x in print(x)\C \Ppdb; Pdb(nosigint=True, readrc=False).set_traceC@func<eloop =new_event_ h.run_untilSaplete(a#]\.clos0""9with PdbkInput(['W)',v#F #F#']]3L> _gen[3,OCall'1c8 S)2.gx6 q> (2)2coro() -> " for x in agen():(Pdb) step--Call-- `> yield 1xk-*3)kRawaitio.sleep(0zcontinue~2finished """ defy_returnzgeneratorN"""Testing no unwindng stack on;so! "e#"  E>>> 0...V0,Im2Vufunctio2import pdb;.Pdb(nosigint=True, readrc=False).set_trace~I2t =L 2try-0if (it) != 0"&raise AsserYError\%H except StopItion as exjif ex.value1"gtprint("h&")with Pdb>Input([')',g#4,kRw#']a_[3 YO-> iw54t?5tR  R0]>(1-O~ :07 & 98x ration as ex: (Pdb) step> (9)5function()Y-> if ex.value != 1continue,finished """ defcoroutine()V"""Testing no unwindng stack on yield for ;s"#"  >>> import asyncio P0...dU awai:.sleep(0#/ LmainPpdb; Pdb(nosigint=True, readrc=False).set_trace  <dloop =I.new_event_ h.run_untilvaplete(z H1Lclostprint("\&")with Pdb2Input(['!',\#OnextF #']oD"b[2]>(3<U#->r. --Call--5,)1q_N 025  4 .9-sn" 4d3target breakpo`is not_c@W/-ge0,12U@  6CBi in1|i9/ 4q 'step',  ... 'step', #continue']):)test_function()`> (3)4 X-> for i inY5(`(Pdb) --Call-- +R0]>(1$geo-> def! 4|01/4qyield 2b oReturn6"->t?-> + t rprint(it finishedU""" ?pdbcoroutine[ """Testing no unwindng stack2se! "#"  if target breakpoQis not reac@>>> import asyncio {z0EawaiO{.sleep(#818$28$/3)LmainPpdb; RPdb(nosigint=True,Ldrc=False).set_trace fE s dloop =.new_event_ hF.runiaplete(z :1Lclos""9with PdbInput([/ 8mq&[22-> 4.d7[xpT!83I nue 3 8 finished """ def test_pdb_next_command_in_generator_for_loop(): <@The 1 1 on returning from a B controlled by a for R!. E>>> 4geni0...p yield 0,n/ 1B}functioGimport pdb;.Pdb(nosigint=True, readrc=False).set_trace()|Bi in=print('value', iCvx = 123 with PdbTestInput(['breake)',d'd inl' J #3"])7r`> (3); _!->sj(Pdb) kB~point 6 at1Q0]>:1]v$2R0]>(2Z)->C|^6  Internal StopItzRion: .2)-65% & Asubi>$orF=""")in}'a =5sub] F? rqMxBBT bOstep # 'next', ... 'next',#-continue']):Ltest_function()`> (3)1 U-> for i inVS_gen((Pdb) step--Call-- (R1]>(1mPo-> def v,2vx = yield frombsubgen<} aqvalue 0 , return x` {Internal StopIaion: 1-(%),51123<U""" Apdb_issue_20766q"""Test!reference leaks when the SIGINT handler is set. f'>> 3i =<while i <= 2,Wpsess = 3Pdbo;! .set_trace(sys._getframe()0 print('pdb %d: %s' % (i, j._previous_sigint_I0i +with PdbEInput(['  '3o[0]>(67 *hU1: :   2Pd classCase(unitG.+{arDown(selfupport.unlink(srTESTFN)Z@@_run@,s_args, sTelf.addCleanupUrmtree, '__pycache__'#pcmd = [Cexecutabl.-m', 'pdb'] + pdb_arg3s with subprocess.Popen(&] cmd,xstdout=>?IPE(/in'8err(fSTDOUTQP) as :, stderr =# .communicate(str.encode(eands))D@ =Aout and bytes.de4! 1ir16err1creturn` def run_pdb_script(self, %, """Run '#' lines 1pdb@the '?Q'."""rfilename = 'main.py'I'Q, 'w'~fH.write(textwrap.dedent(delf.addCleanup(support.unlink, j49_"$([(]IomoduleI s . gart of a M>._F t_HERrmtre37_YQ+ '/_Z)__Oinit6 # 6os.mkdir@;pasJ69f7-V,, WsR?N'-m'6M`_asserfnd_function:_content,  , expected)(C,< = +)ZJoTESTFNTP = None if notj else 3\[0], &1]u7_EqualP,8.fiWC j)(;tesa_empty w'', 'foo', b _found]GI"""\Gfoo((N -?bar-Oquux. w """, Z'bar'(6 4)!) 6 def test_issue7964(self):W'# open the file as binary so we can force \r\n newline?AwithB(support.TESTFN, 'wb')Ofmqf.write(b'print("ing my pdb")h%')bcmd = [sys.executable, '-m', 'pdb', |]<proc = sub Pess.PF(cmd+xstdout=)=IPE$/in#8err$jSTDOUTI.addCleanup(.g.close+, stderr = ,communicaQgquit\n<` ssertNotIn(b'SyntaxError9V1  "Got a s6 e7P runn script under PDB"z\13183{;= from bar imS Gfoo(Cbar(.Onope/Opass\H Pv ^ H1fooD-5""" _ands dQbreakvcontinuEsteps2"~JIdJ"0.pyw textwrap.dedent(bar) 8elf5unlink, g2<run_pdb_($, ?qFUTrue(1any('main.py(5) ->None' in l= l PsplitD7s()L'Fail to Q intocaller aft` retur\13210hp# invok"(" on a non- thread triggered an exceptioniJside signal. Bz5ing!6pdb(Pstart %pdb.Pdb( rc=False).set_trace(.]x = 1y 3t =qQing.T{(target=start_pdb)  t.start()""").encode('ascii')) +cmd = [sys.executable, '-u', support.TESTFN]5proc = sub ess.Popen(cmd,%bxstdout=)=IPE$/in#8err$jSTDOUTIself.addCleanup(.g.close+, stderr = ,communicate(b'cont\n'5`ssertNotIn('Error2O1.deo)"Got an e: running test script under PDB") V1def!_issue16180(!):[# A syntaxYin the debuggee.*e0= "Wf: pass\n"!ands = ''pexpecte5!"Si:8hR.run_pdb_w($, e\4In(oO:outQc'\n\nE:\n{}\nGot 'Fail to handle a( =}.format;)) readrc_kwarg = textwrap.dedent(""? imwP pdb;R.Pdb(Y=False).set_trace(7print('hello%save_home = os.environ.pop('HOME', Non&6trydBEwithtemp_cwd(%)'.pdbrc', 'w') as fT/f.write("invalid\nYmain.pyZ :Yb./ 1% 4P(,0 + 8W~:^6q3Ya?R"NameHs name '' is not defined"Mkfinall6if o+[']L_M}_header  = StringIO(|2orNobody s... blah, with ExitStack() as resources: .enter_context(patch('sys.stdout', /))A .object(pdb.Pdb, 'set_trace'H#(header=qself.assertEqual(.getvalue(), 4 + '\n') def test_run_module(L) script = """print("SUCCESS")"""G8commands*intinueEquitIV`err = .5pdb$, v True(any in l for l k.splitlines())y>()in l for l in "0b.xq2b.yz~I@, "g@ ["Nz S U/# u1 # fail8gc # gcb.x # b.Y from b import y # b.y  from b.z8*8z.* a/gc.py a/sys J Bmymodule a/b/__init__@x y z )iz b/unusedC\!b/Z!b/X"""] relative__test = [2"a.!",["__future__l "a", )b4b.y z4D.b.cceC&.d!exCgc"]C], [ T"""\ kalC $.by, z # a.b.y,Bz a/]O8Wtabsoluty6 # $mX  gc # gcO_L xx#;cC;:.7zE   g c |ev"c.cC_! MdMd!c/eR /_2u5sys/a.d7:.c.rf6a.anotherFm1sysocsys a/vdC   c`5 lT+"!f *#m1f _b.c.f<.=x<   from ... import another # a. a/b/c/d.py e f """] relative_K_test_3 = [ t"a.module",f["a", ]T.bar""""\ a/__init__vU def foo(): pass a/<1foon 2Obar 4[j*bytecodep"" ] open_file(path):idirname = os..%$2try-os.makedirs(+)&except OSError as e6if e.errno != v.EEXIST$^QraiseOpreturn c, "w")create_package(sourceofi = NonH for line in 5`.split#s(A!if,.startswith(" ") D ;\t">Bofi.write(a.strip() + "\n"6'7els/jif ofi#]jclose(Jjoin(TEST_DIR,)Fgfinall{ class MrFinderTest(unit.4Cas1_do(self, info, re=False, debug=00lacgths=[]hRhis, s issing, maybe_m! =od+K ?0Cmf =lf.=bDPATHvD7rep D3mf.Shook( Jthis(#ifaN2mf.|T() ##Y# This wouldn't work@ general when executed sevotimes:OoeR = syp?[:]&5 = M'__.HQ traceback; .print_exc9 sys.path = oK ## xreturn modules = sorted(set()))+Vfound)4mf.( '# check if we 5@whatexpected, not more IlessEself.assertEqual(H%, r .sfor missing and maybe< :Cbad,'= mf.any_B_>( At+ Pne3finally: shutil.rmtree(TEST_DIR) %def test_package()AP._do_%(% A? #=O_newA, absolute_importsL .relativR .R/_2 T,_2 &?s_3V 3V4V 4V}bytecodjPbase_t|U.joinV, 'a'Usourc2>"+ lib.machinery.SOURCE_SUFFIXES[0]}K BYTECODMwith open_file(P) as ]~.write('dBing_efinder = True\npy_compile.i0, cU=8os.remov D Srepla m4oldQo2, '7.py?new<Jspam:0sup.captured_stdout(joutput , debug=2,  4=[($, ')]~ .getvalue#a = "coH name %r changed to %r" % n4In(W", f test_extended_opargs(self): Vexten_test = [!(I"a",[[ "b"]K], ["""\ a.pyBW /%r#import b bQ""" % list(range(2**16))] # constants[A._do() if __name__ == "__main__";@unit+.`() # T9packages (dotted-B 2) D sys o tempfiletextwrapr` from |X@ sup4 # Helpers to create and destroy hierarchies. def cleanout(root)ps = os.[2dirB@for !1 ins4Afull;path.join=,-)C, if_$ isb=)7not Ulink(!qI dJelse-os.removeN.mr0fix$ls ifbuiltins__"6lstc4lst`7"__*AinitializingE .Ireturn lstXXX ThingD # # without __T/__"*Jing submodule #*~global #PdefinAvariables #MBVother& hJAS via /1 # @ 2A! ( edAV*.q classSDPkg(.dqCase): \setUpq = None./0pkg 0sys" =W@sys.yBs_before =.vsetup()tearDowna0[:]GCelf.\Aup(*r1if : # Onlyr if theDwas actually runvjJ`# deleblso1cerc%edxDZt 8\.pkgname in name.split('.')] @for ! in modules:!,del sys.![1!] 'def run_code(self, )Eexec(textwrap.dedent($, globals(), {">0": &})^cmkhier\Wdescr]root = tempfile.mkd !()path.insert(0, 5!if not os.'Qsdir(#I os^`A`ntentsK @qcomps =na@fullZ! =b@or cYF Y <Tjoin(T:, cmTif cons NoneVG D?els5xf = ope|:"w":t.write("5and[-1] != '\n'\"Xxf.close%@elf. |# packagec is th !of first itemC.pkg W[0][04atest_1 = [("t1",0),  __init__.py", ""p'Bimport t1Oy2yu2  P'doc kt2'"),-?subH= 2Y"Docstrings are omNd with -O2 and above"@def o0_8(!): E = [O("t8Z 8"+os.extsep+"b'doc for t8'~%t8.d3t8.,6, "st") if  == "__main__" () Here we check that `__}` is provided:8>>> type(#h idpickleRsys XCest 40supf py_operator = support.import_fresh_module('operator', blocked=['_E]) c = support.imLe J class Seq1: def __init__(self, lst)!`.lst =43len3.return lenM9)4sgetitem8>, i;p7[i]95add5_other91 + "|B?mulB*B>r?v4 *  mt2(objecXuKvOVTestCasezqtest_ltGqcBelf. assertRaises(TypeError, <2.lt2, 1j, 2j:gFalse(`o(1, 0),..1Z1Z=Tru2Y+XyeCeI ee,?Ku *-+X2X /eqC%O__eq%rq SyntaxG/eq  Xqeq, C()>erator.eq(1,c 0)) self.assertFalse(operator.eq(1, 0..=Tru-1Y+X2Y,Zdef test_ne(!):0 = u.moduleclass C(object8<Wa__ne__V{, other%)raise SyntaxError`twR%as(Type$$, ?.ne2X 4Q, C()> !ne`+_ Y,Z+X{gg 2, 1j, 2jg+ (-+X Y,Z tha" ts2 tZg+ ).,Z2Z ?absB?absabs, NoHVEqualo-1), 1g.- /ddC/dd2add, None) 6 self.assertEqual(operator.add(3, 4), 7) def test_bitwise_and(B!): $@" =\emodule.pRaises(TypeError, <o.and_)4 b, None@ nd_(0xf, 0xa) pconcat(=[6B 6('py', 'thon'), 'py lB[1, 2], [A]), ", HSeq1([5, 6E07])QO, 7]ISeq2N?2([Nhl13, 29countOfD\ 7C 7(11, 4], 3), 1E-5Y @delitem@aa = [4_2, 1]o"u?, a:Y Is~Bo (aEr!a, (floordiv)g]?, 5;8`(5, 2) pOtrueE\ :7,.5?get$range(10.getitem)  )self.assertRaises(TypeError, operator.getitem, a, None) =7 @lEqual(4`(a, 2) 5def test_indexOf(B!):U@" =\emodule.\7C 7([4, 3, 2, 1], 3), 1?MValujL*, M-0)>Overt=D[ # in65v(4), -5_lshifC[6O, 42@ 4 (5O, 104_0), 53< t,-1V?mod.B?mod +?modM5CN ?mulC/ul$ul% 0mat !=[>vclass M"__i!__w, other)breturnO - 1bM() @ 42, 41neghaO26neg2neg 9.5 g.-/".O self.a0ssertEqual(operator.neg(-0), 0) def test_bitwise_or(self):#=0 = u.moduleamRaises(TypeError, <_.or_)3b, None? or_(0xa, 0x5,xf?posB?pos?pos5f --.-/\.B?pow[Dw[ w[? @w(3,5?3**7q 1h6l, 2, 3orshiftQB[6QO, 42@ U4(5, 1), 3e MValuisT,-1UcontainC]8[DFTrue7(range(4a8OFals9 ,5)*setitema = list/3) w?, a:'H IscJu(8{a, [2, 1, 2]'\Indexh`, a, 4i ?subpy(TypeError, operator.sub) self.assertRaises(TypeError, 3b, None?hEqual(3(5, 2), 3) pdef test_truth({!)::0 = u.moduleclass C(object8<Z__bool__X rq Syntax[o9[;7_, C()<FTrue5-/(5+?[0]-MFalsY0,[Y#]bitwise_xore b?xor$`x0xb, 0xc)7/isa = b = 'xyzpdq'7tc = a[:3] + b[3:]?is_ 6is_(a, b-.c)O_notx?not !is ,.a,attrgetteAEpass!&A(`a.name2farthur26f =w'1'B@ysf(a), 'P)Hf(, a, 'dent[30sur=;Orankc AttributOf, a.XT=C# multiple getrecord =  .xXyYzZ('x','z','y')(record), ('X', 'ZcY')) !self.assertRaises(TypeError, operator.attrgetterKx', (), 'yJKclass C(object):kdef __getK0__(xk, name)-rq SyntaxK7 &('foo'), C()) I# recursive getsfa = A(! a. = 'arthur'*m.child06fthomas6?f =X&('7'~Equal(f(azV)AttributBf, a6,("4, 'k##,  z^nZ+hZ ]Icjohnsonj> p]V ;tO5, 'Xtest_item\V1 = Ofmodulej=_ABCDE;Z2K9/'CNP]fL(o, a, 3.Wsize=3 /10W BInde , >sjOf-42' ?, a+n.8.dict(key='val.7key'yM f = operator.itemgetter('nonkey') self.assertRaises(KeyError, f, d) + # example used in the docs#inventory = [('apple', 3), ('banana', 2pear', 5 Porang+51)]Ngetcount = o1Equal(list(map(D%, )), [3, 2, 5, 1]Gusorted(;d, key=T%),N7[(' ]dPmultie6getYudata = Qstr, 4_(20)):2,10,5)(Vp2', '10/5'NCTypeZ3 'x^?def test_methodcaller(|%):DP0 = u.module a<F, 12@vclass A1foo, *args, **kwds*preturn &R[0] + 1%S"bao, f=42Jf:/z(['name'], a'p&A(f+_('fooS SIndex6Of, aU0, 1/@f(a)`"fyJ(?, aV.fspam=3a/?bar/4TzX5\" @z', G ='!',o='eggs(50 .qinplaceb ) C(object8(__iadd__ ], other): """V*:n:/nd:floordiv__t"?`lshift?lshift"  def __imod__ (self, other): return ""!" ":/ul: /ul:2atm=t"=#orv/or93pow:v?pow:`rshift=:"=0sub:/ ?sub:truediv__:">x)x)getitem__8 5 # so that C is a sequence'uc = C()[ .assertEqual(operator.iaddX(c, 5), "";n;/nd;floordivv@l& @>,mo/mo;mul/?mulvUm>!orx/or:1pow;,iXy;subykyZzx.mzbconcatcL{test_length_hint!): [1 = wWmodullass X(object8<`e__init[value'+\1 =  KRKqif type.K)XTRraise/ y%Oelse;([], 2), 09iter([1, 2, 3])), 3)}0X(292|X(NotImplementaed), 4# 'self.assertEqual(operator.length_hint(X(TypeError), 12EWwith JgRaises4:+wcu"abc"))+VCValuW/-2TbLookupU1!) def test_dunder_is_original()Y" =6bmoduleG!names = [ Q for ein dir) if notp.starts4a('_')]M?Gs = getatt],V+-a'__' +4a.strip0 + j, NoneL2if O g-2Is(& , ) class PyOTestCase(`, unit.$nd = py_5 @/skipUnless(c!, 'requires #')C~!m WdPickle3pAcopy], obj, protoK support.swap_item(sys.Ds, '(',FJpd6 w.dumps(vqu(2vrreturn }r.loads( dvagetterI p._AbEpass"fa = A(a.x = 'X'" .yYzZtH?t.u .v<V< in range.HIGHEST_PROTOCOL + 1 0subQ(K= ,0Ff = (F('x' $f2Yf%m`repr(fO 0 4f2(a), f(a.# multipleJ, 'y', 'zrecursivt.u.v')   f2 = self.copy(f, proto) $assertEqual(repr(f2), )4f2(a), f(a)) cdef test_itemgetter(k!):vmodule.,a = 'ABCDE'2for in range(pickle.HIGHEST_PROTOCOL + 1y}Bwith subTest( = ,0Ff = .(2rh# multiple gets2$ o, 0, 4zEmethodcallG IQvclass Aj1foo, *args, **kwds preturn &R[0] + %1]dS"bao, f=42Jf:/z(['name'], k'?&A(;^f('bar'-Azpositional : = foo', 1, keyword5 Qbaz',='eggs', $o='spam)q# Can't$ consistently Zm .| HPyPyOperatorPVCase(ckleTestCase, unittest.TestCase): module = py_operator2% @IskipUnless(c;, 'requires ') class PyCOddPickle(* +?CPy'l;Ck> if __name__ == "__main__"p?p() # WrPn to  interrupted system calls~fering with our many buffered # IO implementations. http://bugs.python.org/issue12268 # # It was suggested that this code could be merged in_io and thes # madepwork ussame method as2Pexist bsignalB1 in @_io.QunablV@get Tle process.sjalarm or setitimerPway #reproducePEINTRI@blem0@ThisY0bas est suite =1pro:` prior`i^ patch reliably on Linux50OSX - gregory.p.smith import os eselect0#ub y9@ # 0gaall ofthings we're about !ryfup front.V5_io _pyio u0os.'posix', '%s 9!a .?qFileIOSI*[0defsUp(self_#._ = None 3tearDown6iN&lf9 K.poll() isSq:try ? ki?except OSErrorAFpass@_gene_infile_setup_code"""Returnu0 = ... line8 fhDader.u1subeses sho`overri:,/!di ntobjects.5""" r3 (' %sUio ;'$|'2io.(sys.stdin.no(), "rb")' %  self.modname)  def fail_with_process_info(., why, stdout=b'' 1err BFcommunicate=True):2P"""A on way to cleanup and  useful debug output.uKills the  if it is still running, collects remaiNxPBtest an error message includingy FArgswhy: Textgo after "EVtfrom IOA" inXn.J: standard<W)soJN0fary@`: bool 0en  we call%B() o  @killPi"ather additional 5"""J0if .p.poll()JNonetime.sleep(0.1) # give3finish printD<:try[ terminate(iQEnsurkJdiesNexcept OSYHpassD_end% + =$@/()A3 +=? !3err!9err!P!('  %s:\nSTDOUT:\n%sSTDERR Y\n' %k7 (.decode())_@_readata_to_write, _and_verify_V Generic buffered3 method a harness5validate EINTR behaviorTAlso 'cat Python sighandlers areD durM c B: St;!o TchildjA for=ingwbefore senD aK0nfiBwas -d,O@a fiqnewline@closinfile pipe! : Single "LP" of /|r-lepobject 2d 'w' result. This wRbMexecuted as part3a p#ubY fed  a_setupg0ate7ile## Total pipe IO in this function is smaller thae minimum posix OS # pipe buffer size of 512 bytes. No writhould block.Bassert len(data_to_00) Anot :O b, _, _ect.select([err], ()F0.05*N 11endH*al! 5k1I+= 1#if!Z> 200zZkill(f%' ('a4er I ed|ei&.'J#% assumes anythpnexpectD2hatb[Q will#% a newline. That is true of the traceback printing code. signal_line = self._process.stderr.read %()68if 9!= b'$\n':"_Nfail_withW_info('while awaiO)',AE=8%) =# We append a new to our input so t1$a call canGAon its own beforeZ0EOFmseen andP0we'" esJjf{was interrupted by aXjfKdata stream has bwreachedrtdout, - communicate(j=b'\n' `returnC@'exirc=%d' %{hs', f=Falser# PASS!P# Strformat for_and_verify_2 us methods\ _READING_CODE_TEMPLATE = ('got = infile.{H_H_name}() ;'2Pexpec4= { =!r}(qassert a$= *:, (Ps.'"~ eed wrong S_.\\n"Cm%d %r\\nt %r" % (got,*))Edef test_ ($)L5""") must handleslnot lose5"""DO%._c:ing _to_write=b'hello, world! =i.\y}Q ='~1o ^s_/s(`Z/\n`qsa[r\n', b'_\n'])h?allfdNrite=b'hello\nworld!', )read_and_verify_code=self._READING_CODE_TEMPLATE.format(IXQmethod_name='?all}4expected=b'helloU\n'))j # J() is the same thing aseall().1Ptest_:>ingdata_to_writeI0Pz- class CTestFileIOSignalInterrupt(`, unit0.$aCase):N0mod = '_io'e Py(fB!pyhgBuffered def _generate_infile_setup((+e"""Returng0 = ... line of ' to make a Reader."""7NrK ('import %sEio ;Yio.open(sys.stdin.no(), "rb") ;'PT'assert isinstance(QZ, io.M)' %A.!) )/M$  Y.() must handle sos and not lose g Z%._mH$P nOText,b~K_Wrappzh =ipt", new3_=None st_readline(self): ("""readline() must handle signals and not lose data."""@Op._test_HEing(c5 _to_write=b'hello, world!',0I_and_verify_code=i READING_CODE_TEMPLATE.formatyQmethod_name='~5expected=a\n')) Edef N s(^s_[O\r\naqsb[cb\n', 'O\n']h?allfa\_nZ"l 0\n"Tclass CTestTextIOSInterrupt(`, unit.$CCase0modZ = '_io' e Py(fB!pyhQ if _@__ =_main__'() Certificate!BData Version: 3 (0x2)Serial Number: 00?ture Algorithm: sha1WithRSAEncryptionN@IssuG C=US, ST=Oregon, L=Beavert O=Python Software FoundaKD, OU Core Development, CN=null.p@.org\x00example/emailAddress='R-dev@ #ValidityNot Before: Aug 7 13:11:52 2013 GMT1iAfter 121Subject: ! Public Key InfoV1'?rsa04-Key: (2048 bituzModulusp00:b5:ea:ed:c9:fb:46:7d:6f:3b:76:80:dd:3a:f3: 03:94:0b:a7:a6:db:ec:1d:df:ff:23:74:08:9d:97B16:3f:a3:a4:7b:3e:1b:0e:96:59:25:03]_26:e2B88:a9:cf:79:cd:f7:04:56:b0:abP32:6eN/c1B32:30:54:eb:58:a8:cb:91:f0:42:a5:64:27/d4B56:31:88:52:adPbd:7fB 06?P1f:ccE/b8Ba3:8b:8ckd8:29:1f@b:f5 06Oca:0 45{70a:9c:bf:bb:b9:ae:0d:16_60:75@e:06P9c:7cdc:92:2fa:e0:4b:0c90:6c:e9:37:c5:90:d7:2aP97:1580:8f:5dQ7b:49!4 d4:2c:1c:5bW!b5968:43:d3:33:78@2:60GP3c:44 a1cef0:0f:d1:5e:87:9ecf:62:fc:f9Y0c:65:1f1:93:c8:35f ec 47Pef:bed82:1e:2d:9a:9f:98:5a:67x e1Z 70/cbJd3:c2:ceN 45V27:dc:e3T0d4:8/2fB9e:77:b8:140:c4:36:Pae:6a _8c:daB]2f:85 Exponent: 65537 (0x10001)*X509v3 extensions_ Basic Constraints: criticalJCA:FALSEHSubject Key IdentifiersHpA:55:C0FF:61:CD A3 0F:EA:5A:9C:24:38:22:F7:5Cwo^UsagejDigital Signature, Non Repudiation,EnciphermentcAlternative Namr*) {*.WARNING: The values for DNS, email and URI are WRONG. OpenSSLNRdoesn't print the text after a NULL byte.C)*NDNS:altnull.python.org:@URI:http:// 3IP Address:192.0.2.1, 2001:DB8:01 Algorithm: sha1WithRSAEncryp,/Aac:4f:45:ef49:a8:21:70:8e :88:59:3e:d4:36:42:70:f5: &a3:bd:8b:d7:a8:d0:58:f6:31:4a:b1:a4:a6:dd:6f:d9:e8:44@3c:b6:0a:71:d6:7f408:61:9d:60:ce:75:cf:77:0c:d2:37@86:02:8d:5e:5d:f9:0fLPb4:16c1:3d:23:1c:f1:11:b3@56:6e:ca 8d:34:94:e6:87:2a:99:f2:aePcc:c2'86@Pde:08h7f:c5:05:fa81:a7:82L334:f4:ac@3e:40:fe:89:57:7a:29491:7e:0b:c6:51Oe5:10:2f60:76:cd:95(P1a:bea1:b0:fd:ad:52Pd7:1b'60P1:c7:17:c4:18:4f:2dP25:a34f:b7:92'*e2 25V 548 b3q61:a2:f7:da:ed:e1P6f:2cP1f:d81 c5b05:ab:c9:09:62:49:a9:145 cc'@P4a:19P99:971d:81:5f!cf@8:96w 51'3d 0b65:12:ebP70:80P48:72 c6 daWcd:8e@P5b:baz 2f b4k 565e:3a:43P63:04 2a c1Va -BEGIN CERTIFICATE6- MIIE2DCCA8CgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBxTELMAkGA1UEBhMCVVMx Dz-NVBAgMBk9yZWdvbjESMBA)0wwJQmVhdmVydG9uMSMwIQYDVQQKDBpQ eXRob24gU29mdHdhcmUgRm91bmRhdGlMAgMB4MCwwXUHl0aG9uIENv, RGV2ZWxvcG1lbnQxJDAiBgMMG251bGwuc5Lm9yZwBleGFtcGxl ZzEkMCIGCSqGSIb3DQEJARYV5sWRldkBwub3JnMB4XDTEzMDgw NzEzMTE1MloIwgcUxCzAJYTAlVTMQ8wDI DAZPcmVnb24xEjAQ)cMCUJlYXZlcnRBjMCE5gwa FNv ZnR3YXJlIEZvdW5kYXRpMBIDAeMsMF1B5dGhvbiBDb3,RldmVsb3Bt ZW50MSQwIgDDBtudWxsLn55vcmcAZXhhbXBsZSm4kq -dCQEWFX5e1kZXZAI~`zCCASIJKoZIhvcNAQEB BQADggEPAfQoCggEBALXq7cn7Rn1vO3aA3TrzA5QLp6bb7B3f/yN0CJ2XFj+j pHs+Gw6WWSUDpybiiKnPec33BFawq3kyblnBMjBU61ioy5HwQqVkJ8vUVjGIUq3P vX/wBmQfzCe4o4uM89gpHyUL9UYGG8oCRa17dgqcv7u5rg0Wq2B1rgY+nHwx3JIv KRrgSwyRkGzpN8WQ1yrXlxWjgI9de0mPVDDUlywcWze1q2kwaEPTM3hLAmD1PESA oY/n8A/RXoeeRs9i/Pm/DGUS8ZPINXk/yOzsR/XvvkTVroIeLZqfmFpnZeF0cHzL 08LODkVJJ9zjLdT7SA4vnne4FEbAxDbKAq5qkYzaL4UCAwEAAaOB0DCBzTAM( HRMBAf8EAjAAMB0ndDgQWBBSIWlXAUv9hzVKjNQ/qWpwkOCL3XDAL=HQ8E BAMCBeAwgZdEQSBiDCBhYIeYWx0bnVsbC5weXRob24ub3JnAGV4YW1wbGUu Y29tgSBudWxsQHB5dGhvbi5vcmcAdXNlckBleGFtcGxlLm9yZ4YpaHR0cDovL251 bGwucHl0aG9uLm9yZwBodHRwOi8vZXhhbXBsZS5vcmeHBMAAAgGHECABDbgAAAAA EwDQYJKoZIhvcNAQEFBQADggEBAKxPRe99SaghcI6IWT7UNkJw9aO9 i9eo0Fj2MUqxpKbdb9noRDy2CnHWf7EIYZ1gznXPdwzSN4YCjV5d+Q9xtBaowT0j HPERs1ZuytCNNJTmhyqZ8q6uzMLoht4IqH/FBfpvgaeC5tBTnTT0rD5A/olXeimk kX4LxlEx5RAvpGB2zZVRGr6LobD9rVK91xuHYNIxxxfEGE8tCCWjp0+3ksri9SXx VHWBnbM9YaL32u3hxm8sYB/Yb8WSBavJCWJJqRStVRHM1koZlJmXNx2BX4vPo6iW RFEIPQsFZRLrtnCAiEhyT8bC2s/Njlu6ly9gtJZWSV46Q3ZjBL4q9sHKqZQ= -----END CERTIFICATE----- ''' Tests for fileinput module. Nick Mathewson ''' import os import sys import re import fileinput 0collection9fbuiltitempfileNunittest try: Mbz2 except IpRError#bz2 = None7Ogzip89 from iopBytesIO, StringIO!i0PFileI, hook_encoded.tpathlibTRPath A.supOKverbose, TESTFN, check_warnings9unlink as safe_/ojmock # The module has 2 interfaces: the  class which does # all%work, and a few fun! (I, etc.) that use a global _state # variable. iBaseTests`# Writ:content (str or bP) to j`returne# 's name.Pdef w\Tmp(self, c@, *,4e='w'): # ope in text0 ise defaultU1fd,g! =zq@.mks%()&r.addCleanup(.B.Awith(^Pmode)f%v!f.(?hLineReader: __init__)]_linesread = []6@propertyD& E ]1[:]L"cfinall. 0~, it = iter((a.splitm(True)Eo.oPsize=jq = next&v.it, ''Yself._linesread.append(line) preturn  def reads(self, hint=-1):":U = []size = 0while True8<0 = [.j(#aif not <smk+= len1if !!>=w x+Qclose'pass class BufferSizesTests(Base , unittest.CCaseDY!_b=_!# First, run the 2 s with default and teeny J.Cfor round, bs in (0, 0), (1, 30m.$t1writeTmp(''.join("Line %s of f1\n" % (i+1) gi_range(15))/t2Z2Z 0Z3Z3Z4Y4Y1^if bs~3assertWarns(Deprecation;ing:N_-(t1, t2, t3, t4, ;elsS"w ., #=0=pat = re.compile(r'LINE (\d+) OF FIL"')0tar921 +!*6if verboprint('%s. Simple iterp (bs=%s)'s\ +0Bfi = FileInput(+s=u ),6=bsw` = lis92fi.s>.dEqual(os), 31) ines[4], '5'9%30:1:?4\n: 0fi.?no( 0fi.2@name,'t4tatus variables17us = "x"QsCs !=a6'J2\n'C/fi  2ual(fi.lineno(), 21) self.assertEqual(fi.filelinen.6-PFalse-pisfirst0/()+ Pstdin'if verbose:print('%s. Next (bs=%s)' % (start+2, bsvCfi.n.(Bread, 'Line 1 of hO3\n'> :&22*fi.close() S3 = FileInput(s=(t1, t2, t3, t4, '-'), bufsize=bsAsaveq = sys. :try# = StringIO("+?!\n2<"r+ps = lis  ~Alen(2_), 33- ines[32] j@name!'<>7Qofinall0k Boundary conditions4 ~0> FNone.5Dm(bInplaceM5M6out%5outm &/fiB), i/=1@for j in fi Hne[:-1].upper%;/ 5 !0[-1 m = pat.match3 R#No:m, N)"}m.group(1)), /hV class Un&4Raidef __init__(t, exception_type).+ =/-pinvokeddef __call__(self, *args, **kw C): self.invoked = Truearaise "exception_type() class FileInputTests(Base , unittest.qCase): Z@def _zero_byte_files(iBt1 =}writeTmp("")C/t2 3 The only line there is.\nW48Ffi =(=(t1, t2, t3, t4))j= fi.read(.assertEqual( ?, ''<0fi.?no(), 1) -@nameX/t3 QFalse -0V 4,qfi.clos1 s_that_dont_end_with_newvwA\nB\nC9wD\nE\nF&_ )s = list(fiRs, ["A\n", "BC D E?F"]H0fi.yb3- )`6) ##b cbunicod).p# XXX AH, string is always returned by ".kB So4this needed?$e(")&Pencod~= sys.get dsystem(24if XNone:R!= 'ascii'" 1strm;)uu O^/noGC\nD#'t2 -o = nex#NohE0fi.A @ B zopening_mode&ryH# invalid /, should raise ValueError  fi = FileInput(mode="w")%self.fail("+ should reject invalid A argumentGexcept Val:bEpass# try opening in universal newlineg0Qt1 = writeTmp(b"A\nB\r\nC\rD",1G="wbwith check_warls(('', DeprecationW*)) 6files=t1gUf3s = list(fiassertEqual(*0, [p", "B\nCQD"]) .def test_stdin_binary_(Tmock.patch('sys.6r') as mC .buffer = BytesIO(b'spam, bacon, sausage, and '_S['-']b;'rb3,P.0 9detachedB Borig&>:try=a8'False(hasattr(\2, '/')s ofinall(d _B\_hook # cannot use|6kinplact <(5=1,@=lambda f, m: NonevYaise if both ]% "A "Rs are given / s/=1{+p for becallableclass CustomOpenHookl__init__TpinvokedQc%EEw, *argsF' LITrueK$areturn(HtC("\c$ =penHook()  with FileInput([t], openhook=custom__) as fi: ;fi.readline()self.assertTrue(K.invoked, "_^S not 1") Kdef test_cY)B(TESTFN, 'wb'&f.write(b'A\nB\r\nC\r'$# l TextIOWrapper buffer.%M123456789\n' * 1000TIssue #20501: ) shouldn't whole filemG\x80  .addCleanup(safe_unlink, H+h"s=&,-Z=_encoded('ascii')g :tryyKiEqual(6 , 37?B\n7!C7except Uni De_Errorfail('Read to end of u~Raises(h$# `8thed +zlist(fizwu 0) _binary_mode(GH#DZ3 4='r+ iD4u68C\rk'Pcontext_managerQt1 = }QTmp("6nC".t2&wD\nE\nF&I (t1, t2Ms = *0, [p", "B\nCD E6F"] H0fi.XOno(), 3- )6) _W]s, ()lose_on_?ionwriteTmp("")# Etry: with FileInput(files=t1) as fi,0raise OSErrorJdexcept 6self.assertEqual(fi._ha, ()) Edef test_empty_list_specified_to_constructor(X)k/[];M'-',_getitem__x"""Tests invokingN'._7!) the currentT line number"""At = writeTmp("*01\nU2\n"),_ /[tretval1 = fi[0]Eq-$, }v1 2M1M2M5invalid_keyw,an index une1 tou0 RYlRZs(Runtime`&cmhEb2cm.ion.args, ("accesss out of order" ?eof~, _i but aend-of-i /''$pIn#n0end^ reachedf@next @_oseR_deleting_backupyLq() when0attRA to Zeg y would . This  pxpectedRbNsilently ignoredn@os_uk_orig = os.#replacemenUnconditionally'(  ;; /K addCleanmcupport, t + '.bakt8KkA, inQ=TrueD(fi) # make sureis openeds4@Q. 2 fi.nextfsile() finally:os.unlink = os_ e_orig (,# sanity check to make sure that our test scenario was actuqE hitLself.assertTrue(treplacement.invoked,7"!()mCnot 6"")1def_readline_os_fstat_raises_OSError()"""TestsQing FileInput.Lwqhen os.S2() U U. This exception should be silently discarded."""o]!? = UncondinR(+tr@t = .writeTmp("\n"1Fwith(files=[t], in=v) as fiU;1,'fit[8OL~_7Q?as P@unit_.skipIf($hasattr(os, "chmod"),  B doeMSexist0;SG_.1os_ [Z~2}no_when_ValuedQclass!nos3(1xv__init__\ G.5&, v Y`^__call__(wually_raise_V alueError = FilenoRaisesVC() t = self.writeTmp("\n" AwithFInput(files=[t]) as fi:IP_backup = fi._ #:try48* = unconditionally_r_ M<Presul0fi.n'no!!fiJv 9# make sure the  gets cleaned up # sanity check to>at our test scenario was actuE hitLassertTrue(  .invoked,B"{Cnot 9&")}bEqual(Yp, -1, "Z should return -1C1def_readline_buffering([)src = LineReadern'P01\nA2', _3\n']openhook=src. .u2jsF, [] [ 00fi.*3#()O1\n'7 g8p!2n"/2'l!y = Pb]7Pitera0nex Q kE gGd(StopI8 , O, fi 6 self.assertRaises(StopIteration, next, fi) 4sel7 Equal(src.linesread, []) 1def test_pathlib_file(?!):!Ut1 = Path.writeTmp("@lib 56.") with FileInput(t1) as fiTX` = fi.(C!$9, 'x'4 !fino(), 1-h1@name`Pos.fsLd _inplacl  l#, \_=TruezWprint('Modified %s' % K @open   f[Y \n') class MockwZR"""A that mocks outi.3 for use during unit Fs"""2__init__~les=None{ False, backup="", bufsize=0,Ymode="r", AhookOs25lesF$ = # =  0 =  % = !N0 =  Qinvoc`_count`collecs.defaultdict(lambda: 0Greturn_value@&{}Mclos\6 z!["-v"] += 1CZq F0I2  } &["3wsN1w0w3w/no.s1qu2y5 }D/nou1qpisfirstts["isfirstline"] += 1 return self. _values["isfirstl6 2def isstdin(3!):L.invocation_countF/x2! class BaseFileInputGlobalMethodsTest(unittest.CCase0""": E@for * + s Qthe gOP func4 ofPfileiv module.""" _setUp_orig_state = F.bv, 03Lu = Mock}tearDowE x( =xassertExactlyOneI.p, mock__^1, mD_namT"# J` that (Q with`given 7P was ked oncebactual, =|e]FhEqual(W:, 17 pno otheexpectedds were?e7totKlen(B)DUD, 1)nF(Ia qGUnitbG.)()@N_is_not_None_and?>m 0"""7ingkqW whenZ is not p( and its  attribute/Ealso4A. E RuntimeError toMbe raiseda meaningful e0qmessagew ) to *not* beQified pinstancq ( #.= object" 4 = 5}UR(s( v) as cm\vM\#("# already active",), cm.excepV.argsI4Is(,6, "&")@N?butA*is*}Po creyreturn a new fileinput.FileI  object with all method parameters passed G explicitly to the __init__()A; also ensure thatA_state is setNreturned instance."""@u = Mock-()# ._ju = None~=i$self.do_test_call_21() #Adef @_is_b(6!):"+"""Tests invokingOW when*is` Expi&0cre7Band -/   J.L j8r 6nsd# Q,7XgivenTunmodified to>.]b. NotPQ this depends onOmonkey patch'ofb done byMUp()3s = e_placeobackup_ufsiz5?modopenhookO # different values for each argumenresult =K!s=A, in=", =,b= 2=$, = yU#W.7/waH.RrtIs(,N<, "a"/'toJq() wereed directly#" 2s, .&s" 46" :o" 7# " : "1#lopenhook, "openhook") class Test_fileinput_close(BaseFileIGlobalMethods/ ): """Unit tests for G.GQ)""" ,1def(_state_is_None(selfNR`ns thatN does nothing if"XkI` is c /! =#6 .assertIsW(,{)?not"invokes J= on and sets =instance = Mock%()F 4 = 6$#ExactlyOneInvocation(K1, ";"y;^@next/J&D.LN whe.= Ensureit raises RuntimeError with a meaningful exmessageN.} modify?@ {R(r) as cmsPEqual(("no active K()",), cm.excepI_.args<1notO Zo3e>e once,, returns whatever ', Mto point to a different object._retval =%;^#._values["^T"] = k 0-Oti>(r, 3,_?nam/.filename()""" def test_state_is_None(self):"&"""Tests fileinput. name() whenK@ is K.E* Ensure that it raises RuntimeError with a meaningful exmessageNand does not modify5"""3= {.assertR(v) as cmX UPEqual(("no active ()",), cm.exception.args)D IsU(i=.)?not9j hinvoke,3exactly once, returns whatever'/, Mto point to a different object._retval =%(instance = MockFileI #._values["^A"] = k%4 = s$- OtiOneInvoca^(W&, >2Is(r,/,) class J_(_lineno(BaseSGlobalMethods0q"""UnitQs forpH)0&JY%*_~f = object()  instance = MockFileInput() # .return_values["lineno"] = u_retval9PfileiM`._statdL$36 = -Mself.assertExactlyOneInvocation(U$, <2Is(n,-,-) class Test_( EBaseMGlobalMethods4!):"""Unit tests forVLQ)""" 11def-_is_None(S0"""esNW whenM@ is M.iG* Ensure that it raises RuntimeError with a meaningful exmessageNand does not modify} ! =S{R(r) as cmoXeWREqual(("no active ()",), cm.excep_.argsJW(k= )?not;n hinvoke2." e~e once,02 s whatever-.?s, Mto point to a different object."|# ='?i'o% =-$} 7q@"|+1)?no(2?no(4Jno() se,lf.assertEqual(("no active input()",), cm.exception.args) %seDIsNone(file=._state) -def test_is_not_2D!):&V"""Tests J no() whenM is not M.G Ensure that it invokeX@._exactly once,Jreturns whateverO, and doemmodifyMto point to a different object."""._retval =#(instance = MockFileID#._values["\A"] =#nog9*/&4 = {S- $OneInvoca(U$, <2Is(n,-,) class _(_isfirstline(Base}GlobalMethods5q"""UnitQs foruM)6(T2 O7N3 raises RuntimeError with a meaningful eqmessage/ /! =S{ R(v) as cmO\.XS  * d~<3aq9Yi$7) "x', ,_retval) ( self.assertIs(fileinput._state, instance) class Test_(_isstdin(BaseFileI>GlobalMethods1 ): """Unit tests for I.IQ)""" .1def*_is_None(PTbsKW whenJ@ is J.fD* Ensure that it raises RuntimeError with a meaningful exmessageNand does not modify} ! =S{R(r) as cmiX_TOEqual(("no active  ()",), cm.exception.args)D IsT B)?not8h hinvoke){ exactly once, returns whatever$/, Mto point to a different object._retval =$(iu = Mock#._values["]S"] = i,*q$-NneOneInvocaX(%, =2Is(p,.RecorderF__init__wR_count = 0:Ccall:0, *:`, **kw KA+= 1L#Vlast_s@ = (J#, R hook_compressed(unitw.-CCase D _setUpfake_open = \(empty_stringP0do__use_builtin_l("", 1Oono_extIabcd", 2M@/ skipUnless(gzip, "Requires Rzlib" gz_  original! =H./Z" =G/#2tryPresul ".gz", 3) finally: gzip.open = orig$_ 'self.assertEqual(Afake).invocation_count, 1)=Vlast_B, (("test.gz", 3), {}))Q@unitskipUnless(bz2, "Requires bz2"~@def -_bz2_ext_) =?.BZ2File4bz2: = %+trYresult = fileinput.hook_compressed2, 4 :^}0lah~ y1do_use_builtinS("abcd.blah", 5T gzR2Z!G]6X)Y!wBz2", 7Z,name, mode/{.replac-<H!y  ^z +((@staticmethodDy1newt__funcQsiS 9 = N&lreturnclass Test_Vencoded("4CasRq"""UnitQs foryAB)"""Q *0ing1fbject(soerrorsN1ed(Ring, D=<E = IsRecorder }Z~ _z @5S_ zn / Equal(fake_o pen.invocation_count, 1) args, kw = fake_o7Vlast_<1self.assertIs(7[0], filename)) 1], mod%.pop('encoding'), ] 8Qrrors6 4bFalse(7 def test_e7(%):Pwith (TESTFN, 'wb') as f&Uf.write(b'\x80abc'ddCleanup(safe_unlink, YJbcheck(, expected_lines/FileInput("s=UwU='r',3 Phook=_ved('utf-8', =)iQ` = lisW?aEqual(. 'ignore', ['S]VWRaises(UnicodeDeE /YostrictY!breplac{k\ufffd(backslash1]gsf'# UTF-7 is a convenieseldom used8 A\nB\r\nC\rD+IKw-0  $ E ;/7'\r<A\n', 'BCD\u20ac'Warns(Depre?ing/rUmXl+_Value*rbr: C\W'A class MiscTest(unitJ.bCase):6ci /,. M/M4, U0 /incINT =  DINT,+ GGH ' , - Olong 0 = 8e ',- K ssertEqual(ts.T_LONG, s_MIN) tU1 = E_MAXself.assertEqual(0,/!) 1def test_py_ssize_t(A!):r?PYSSIZET = PY_ /_Tw8,7 ' _%IN8 _-9P@unit .skipUnless(hasattr(ts, "fL"), "long not present"+ )K@ = L$',2r~U/UV;$G 5L4MZ!## make sure these will accept a plain int as we1s auEs]E = 3';, 3:O = 4F ,3, 4bad_assignmentsinteger_Yibutes = [p'T_BOOL',YTE', 'T_UB !SSHORT" #$IN! A !H']8if 7'7'* .extend([6#']pB# issue8014: this produced 'bad argu0 toGernal function#Uerrorpfor nonin None, 3.2j, "full of eels", {}, [] >   ,0Raises(TypeEP, setL ,  inplace_string~dSTRING_INPLACE, "hi:"T_K_", "sK2delK) class TestWarnings(kCase):byte_max with support.check_wV('', Runtimek)zp = CHAR/+1|/in|(C)z cl]D(C):I?  override of D 9D _still&"D&?E(D& e N%EOset(!E(4nowo_, tooo IFals E` ?F(Ek,,$F'_{"barLFEL8barLO nowH PEF)) 0)test_descriptors_with U8e|aC(meta =abc_ABCMeta@propertyFJT@abc.qz $return 3(@foo.setterhS, val M , 0@C.gpsuper()9 h DD @D[C5:, 3# check that the #V's __6__ P does4 `# righLing when presented  a"uesfails truth :ingQ)NotBool(object__bool__+  raise ValueError() __len__ = __bool__#with self.assertRR&s(S)):0^class F(C def bar(W#'Mpass\bar.__isabstractmethodNotBool9foo = property(bar) ctest_customdescriptors__oD9d__init__B, fget, fset=None, ._,! =3&0set&=set&Rgette, callablxvreturn (1,Whsh*th@&wfr(getatt#v?, 'M', False;or RsR S[aC(meta =abc_ABCMeta@ Z@abc. $3foo- 3(R@foo.h, val):   2Typ?, C)D}0@C. psuper()9 2 D?E(D[C!(ES)SC_abc # eves can be ABCs, too.,&/ A$x\1 Equal(A._s__, {"x"}(type, A 01g_;m@regition_basics class A(metaclass=abc_ABCMeta): Ipass5 B(object2yb = B()Fself.assertFalse(issub\o(B, A)/O(A,)2NotIsInstance(b^ +Z .B1 = A.register(B?Tru.}_ (T {Is(B1, O C(B_c = C C.1cZ1c, T ,def test_A_as_`_deco(1 _ A(meV$@RYn8 Sm .-i b o+0Is(1}?C))3isi_invalidationB9i6/token_old = get_cache_  .O_newHNotEqual(BRold, ?newx. Lt_registration_builtins(self): class A(meta =abc_ABCMeta,7IpassAA.register(int)p.assertIsInstance(42, A)O(A,),True(issub[0b 3NO B(AB?strI C(-: <  ""I), 0str[ 0b3Ca3C, _def test_Wration_edge_caseNA) # should silently#/A1$d0RaiRuntimeErro1E@cycles not allowedB(objectAd!(B)okS!C*C_7 C61 zqer_non_:B Regex(Typ"Can only 1er Ees",rU, 4) 3 dtransitiveneshC lAgA9/ B'IFals]OA, B/O(B,)2B aB C(metaclass=abc_ABCMeta): IpassA.register(B)class B1(BHself.assertTrue(issubCz(B1, A)]/ K(A,)2L_ C1(C&B1/C1|IFalsKC, By/-(B2 /B1b1c oCo/oa%/% 2% 0f 3C:intP`MyInt(,H2{ IsInstance(42_  )V -def test__bad_arguments(K X!aA(meta [sxPwith ZRaises(TypeErrorq30({} # unhashable-`+Q`No __mro__`# Python version supports any iter4 as?.# But it's implej atHdetail and don't emulate it in Cq P. CP = 42is not tup:;0C()-` all_new_methods_are_calledb6B(objectOcounter = 0A___(cls>&$B.DM+= 1E#QreturXer().T 00C(Ad :eEqual(8, 0 C()  self.assertEqual(B.counter, 1) % def test_ABC_has___slots__(C%):*2VTrue(hasattr(abc.ABC, '?/')ftricky_new_worksewith_metaclass( , *bases% % _(type'+]__(cls, name, this__?, d;?areturnk(:5 ),.s, 'temporary_', (), {})J A: ...B+C(D0abcMeta, A, B)IpassfH2C._G__, T") UTestABCWithInitSubP(unito.!8Cas_dinit_s> W(= J = (psaved_kwargs = {}] ReceivesCK+d)___t"**` super().> ,.update(a/r(, x=1, y=2, z=3*z, dict(USLegacyAPI, R J 15_Py4 7R_Py =tfactory /[%get_cache_token)C C@_py_^?ABC8V ` if ____ == "__main__"q() from` it support, seq_#s ; $gc pickle oPTuple(Dp.Commong2`11_getitem_errorwmsg = "t8 indices must be integers or sl"( RaisesRegex(TypeEnS, msgQ{()['a']pconstru  )) # ca*lling built-in types without argument must return empty self.assertEqual(tuple(), ())&t0_3 = (0, 1, 2, 3r_bis = <-aPTrue(@ is 7*+[]R (2</''dQ'spam,p's', 'pa/m'fx for x in range(10) if x % 2),n(1, 3, 5, 7, 9)) +def test_keyword_args(!):!A   RaisesRegex(TypeError, 'D3'DHsequence=d\truth~super()."9notu ](42, ?lenv t<o()), 0% 0,'1'#,3Oiadd !butQ2 = u{ju += ( 8uo]-u2?mul !~E*= 3bresizebug # Check that a specific bugP@_PyT!_RA ()squashed.+f(iE+00"juyield iKJ3ist>0f()lU =has3# See SF942952: Weakness) <Q# Thev should# be non-commutative=#9 spread-?closely spaced values7`exhibit cancellations like (x,(x,y-be distinct from eleAes: P(x)!=I((x,L Th\est exerc those cases # For a pure1dom[ and N=50, the expected number of occupied buckets when toss252,600 ballto 2**32 . E0is 3p592.6, b67.4collisions. c The #'standard deviation is 2.73. On a box with 64-bit hashF&codes, no collisions are expected. Here we accept noEmore than 15H. Any worse and theP func Iis sorely sus%. #EN=50 base = list(range(N))xp = [(i, j) for i in 4j]2binps =#+; uxp] + \= w!xpur + xp +@zip(`= len(1) - set(map(!, ;self.assertTrue(Kb<= 15)Odef test_repr(5%):l0 = tuple(Rl2 = (0, 1, 2a,@`.type2T7(l0 7 21Equal(str(a0), /l0,2,2, OYF"()" )V""8_not_tracked;7, t># NestedBs can take severaleqs to unL~0gc.7ect~False(gc.is t)86IW@support.cpython_onlyrV@_litEsy vTest GC-optimiz"of 8Tx, y, z = 1.5, "a", [].  (^ /1,   B! 2I, (None, !, P, ())t@ 1obj] a(1, x)&s(2, 3))0# T s^mutable element?qalways ed, even if thos 54not2P righl%w.SN(([]1 /{};c) <Scheckqdynamicb, tp, H check = self._tracked if always else self._notCed check(tp())/[]_set()[1, x, y6obj for ?in , b!tuple([obj])W2/tp5 3V!([z[$ o{x: y}$ (V/, | ==@support.cpython_onlysdef tes^_dynamic($!):"n # Test GC-optimization of 1ally constructed %s.BQ.j), False) 0subtypes S must\C be mclass MyT6("Epass/B_, Trubug7466rying to un an unfinishe could crash P =(gc.collect(i in range(101#Drepr_largeCP the &)P list46ect<R+(ncl = (0,) * n}x1s =Z&(lNassertEqual(s,8$'(' + ', '.join(['0']b)&)'R010)7Q # B our Ecoded 1(10Oiterator_pickl6AUser"*s don't  9uyet sincz#ny are based on genrubdata =C)2([4, 5, 6, 7]Vproto e.HIGHEST_PROTOCOL + 1itorg = (vXO2d =e.dumps(0!, p +&it,zloads(d!}Q3),  4,Lit),&Dznext(itt, proto)  self.assertEqual(type2test(it), data)[1:]) I@def -_reversed_pickleL!):$(\ata =N[4, 5, 6, 7]),for proto in range(U.HIGHEST_PROTOCOL + 1eiitorg = (\#Cd = Qadumps(4,t+&it,zloads(d!D?Q3), )4 E,x )~1nex 2no_comdat_folding4# Issue 8847: In the PGO build,MSVC linker's COMDAT P# optimization causes failuresf code that relies on distinctGAfuncCaddresses.class T(tuple): passBwithHRaises(TypeError[3,] + T((1,2klexicographic_order>U21100G1, 2b#7, 0&c&3#'Less(a, b  b, c) if __name__ == "__main__"L@unitp.H() # Copyright 2007 Google Inc. # Licensed to PSF under a Contributor Agreement. """Uc #ip module.""" import $re contextlib<Doolsoperatoryweakref jBaseTestCase(.Q# One big chIZQ overForiginal " i0# e0 re2ing* tr) to assume users *don't know[arules*#Rwfconstitutes an RFC compliant IP ud`# EnsuR"ses are emd correctly0all evNDcase me1movo a more systematic structur`allows|%Ro mapK#di to1JR3Not^!if)w"orrefactored sL$at0es Pmultipleblems get $ified differently, th#at's OK - just # move the affected examples tonewly appropriate test case. FThere is some duplication betweenJoriginal relativeXSd hocGYsuite and4new systematic{s. Whilemredundancy inH0ingconsidered preferableaccidentally delet2wa validH,will lik0be ced over time asHt a-}SifiedF@aAerty5def factory(self):raise NotImentedError@contextlib. qmanagerBYassertClean9b , exc_type, details, *args|1"""F`Ensure6!epdoes not display a bdRfault@Wraps unitU`.TestCUResRegexr~0if S$ =! %&BPcm = P.f()7with cm as t@yiel6## we produce cm tracebacks on failuref if^B.excQ3.__@ __[JNone@True CsuppressL) 0Add" Ja>QValueChreturnsw2ipaz.D,R qNetmask 2L;""">* D3InstancesEqual{lhs, rhPCheck@struQu7sequivalent iZdq.Rlhs),) class CommonfMixin:s_empty_ r{*"@ can1be M"A<@'""floats_rejre.escape(repr("1.0")) <1.0not_an_index_issue15559%# _1_ makes for a very nasty interaction with the 2# bytes constructor. Thus, we disallow implicit use as an integerJself.assertRaises(TypeError, opera\qindex, - fao_y(1))Fh;'xydef pickle_test(, addr):!-for proto in range(4.HIGHEST_PROTOCOL + 19=Bwith@subTdK= ,02x =/$#3y =d.loadsdumps(x,_5 Equal(y, x) class CommonMixin_v4(1): :3_leading_zerosAnInstanceswW"000.a", "0." @s192.168D1@K.1")"in03232235521, " opacked&.fromhex(40/") Hc0a80001H negative_ints_rejectmsg = "-1 (< 0) is not permitted8AIPv4\Aess"E!CqAddress?(re.escape(msg):]',-1Olarg%d (>= 2**32F# %a  Bbad_9|_length@=BBadL#* lL = b'\0' * $T%r (len %d != 4I@ % (,)O . 3@ ?5) 6I10::_, "::P000:::ssertInstancesEqual(0, "::") self.assertInstanc+32322355214c0a8:1") ;def test_packed(G!):Yaddr = b'\0'*12 + bytes.fromhex("0N.b 0000Nb60h ']h?!:15Nnegative_ints_reject^msg = "-1 (< 0) is not permitted as an IPv6 Aess"hWwith AddressError(re.escape(msg):5factory(-1 Olarg%d (>= 2**128F$ %b  3bad|_length6BBadL#* m@$2 * $W%r (len %d != 16J@ % (,)O .6# &15@ 7) class TestCase_v4(Base, CommonMixin_v4tP = ipess.IPv4R network_pSd_as_4 p127.0.0.1/24Pa"Unexp '/' in %r",G iess_split S"0 q. $"E4 octets %kRrtBad"S "742.K&#   .' .'.) t?.42P.) assertBadSplit("016.C") |assertB&"  /00 Tx0a.0)$ ._bogus O.com$/10 0J 92.168.0.1t def test_empty_octet(self): $O"Gaddr"&Pwith :.,AddressError("E_ _ not permitted in %r",nL |0 ipess.IPv4~(%) ]2Bad"42..42.42:$ ..C .invalid_characters5, < msg = "Only decimal digits)/A % (M",  re.escape(msg)BH"oy0, "Z'0x:"5a4 -0-- ,+,+,1-42Y +1.+2.+3.4,/+11.2.3.4e+ ::U?4::V aX). coctal_I_ambiguity1AM1ous3al/fr) valuea 7J?016s001.000.0081308"^_lengthr2t most 3 mcZess(addr)  assertBadOctet("0000.1", 2") 1, 3 12345.67899.-54321.-98765<1") >def test_om_limit(self): b$ baaddr, 4)-qmsg = " %d (> 255) not permitted in %r" % (D , QIPwith .| AddressError(re.escape(msg)> ipRess.IPv4<(%YjP257.0f", 257 )192.168.0.999", 999W,PlpickleK_' ('Kl0.2.1'B|weakrefC..factoryK) class TestCase_v6(Base, CommonMixin_v6OX9 = M6R @network_p,Pd_as_mS6\ At least 3 M  ?msg9% /":??":1FEDC:9878CPtoo_many_colonO.rmost 8 M QPh9:8:7:6:5:4:3::2D :10:0/ :\, H2:1:# A trailing wess is twoE 3 442.  [Exactly 8ZGtout '::(  Xg>i3ffe:0 ]ssertBadSpli t("9:8:7:6:5:4:3:2:1") assertBadSplit("(# A trailing IPv4 address is two partsW 442.-a.42") edef test_bad_ _s_v6_too_many_ _with_double_colon(self):J N T"&msg = "Expected at most 7 other m '::' in %r"eC}.oAEError(msg,W x9 ipess.IPv67(%T1:2:3:4::5:6:7:8=repeated27A)2one`permitD$n3ffe::1: 1::2::3::4:52001::db:N sK#::&$ #n/1:L' :'0db8'[leading0LJ ':' only d!as2 of~tn:) : )(  0T@"z7) ::1.2.3.4% !v4/_iBadAddressPart(addr, v4_error):  with self.assertAddressE+("%s in %r"@ , P FQ ipess.IPv6H}%) se3Bad Part("3ffe::1.net", "Expected 4 octet'?'")L27.0.1",. k>m?2.3g%O.2.3eO.4.5i)@m!1.pq Only decimal digits permitin 'net' " )su0 def test_invalid_characters(+]Vg, part'qmsg = "?hex#%r@ % (DE< re.escape(msg)>0)@goog(, -0*/-08(+(+(!-1P1P1@.4::) .'1234:axy::b', "axy"/_length/At most 4 L 2msgj& c%0::0G1&. 02001:db8-80::1 8\ickle!.p_!('Q~'|weakrefD..factoryL) class NetmaskTestMixin_v4(Common"""Input vb$ation on interfaces and networks is very similar"""0no_} Equal(str$,c')), ' =/32&rsplit_nDiaddr = "1.2.3.4/32/24" 6with self.assertAddressError("Only one '/' permitted in %r" % addr): LLfactory(a  mdef test_Pess_ec s(0)C'3BadG, details-q 37w. c"/", " cannot be empty")98:%Pbogus=PExpecv4 octetsq google.com<110/r::1.2.3.4q1decimal digi ;256", re.escape("256 (> 255)"))Avalid_netmask@Equal(str$'192.0.2.0/255.U0')), 6&4'Pfor irange(0, 33## Generate and re-parse the CIDR format (trivial).net_str = '0./%d' % i'" =:!onet), 0 expanded: j  P.0/%sCnet.)Zero prefix is trea/3as  "0i}1hos. The ambiguous# cases (/0&/32) are s"ifk(32, 0|fA(32 - i  P0 :JdN;m msg = "%r!a )s @lKmsg)r>p`"%s/%sip13Badh"(">(/-1*+* assertBadNetmask("1.2.3.4", " 1 ") _asser+?0x1+/33*B254._5.256701.a/ P1.1.1b?xyz340.255.0.0f_4.12850 27lhpudding/Q::") def test_pickle(self):._'('192.0.2.0/27'') 31') # IPV4LENGTH - 1d8 ; class InterfaceTestCase_v4(Bas#, !Mixin_v4 factory = ipaddress.IPv4UgpNetworkDe5S subnet_of# containee left ofrFeFalse(@('10.0/30').y 371F4'))oinside ?TruF0 OrighAlarger thanF G)'_supere{Td-.92L@).supernet_oKf( self.factory('10.0.1.0/24'))).# containee larger thanr*PassertTrueq m0m.supernet_o9!30}def test_subG_mixed_types({!):*Pwith .Raises(TypeError+/ipaddress.IPv4Network/ B6B::1/128'l)Y)]. + v3Y) class NetmaskTestMixin_v6(Commonn"""Input validation on interfaces and n~s is very similar"""  bplit_n  = "cafe::Q/190"G A#("Only one '/' permitted in %r" % cMs Pess_e 3Bad(3, detailsp 3  c"/", " cannot be empty"98:%google.comBt least 3 partsu 1.2.3.48"0/m234:axy::bq2hex digik`# We otsupport CIDR for IPv6, because expande+~s are notm# standardj.Equal(str>(2001:db8::/32')), 'Nirange(0, 129# Generatere-parse themat (trivial)str = '::/%d' % i self.assertEqual(str(self.factory(net_str)), ' # Zero prefix is treated as decimal.1^/ass'::/0%d' % ixHdef test_netmask_errors!):#'fBBadN+Q(addr9-1msg = "%rnot a valid/4" % e8Wwith lE(re.escape(msg)r>9l`"%s/%si %) s "::1", "")$+'?1::N/-1&+&? 1 M/0xN?129N1.2.3.4+pudding+ <lpickle_'('2001:db8::1000/124'/7') # IPV6LENGTH - 1kp=(A class InterfaceTestCase_v6(Bas#, !Mixin_v6P = ipess.IPv6UgpNetworkDe5SB0sub,of# containee left ofrLeFalse(B0:999::/56').{ 59aaa::/48')) oinside ?TrujAOrighI5?bbbIDlarger thanN O")?per4False(  self.factory('2000:999::/56').supernet_of( 1;aaa::/48')))0# containee insider%MassertFalseo kCright of1?bbbNFlarger than ?TruR$)) class FVFunctionErrors(BaseTestCase): Ddef ,(#, , kind):1"""Ensure a clean Value; with the expected message"""Baddr = "camelotmsg = '%r does not appear to be an IPv4 orU6 %s'Uz.C(p, msg, (!)$test_ip_1ess!v|x#ip1.<3, ""ainterfacec">5, " gnetworke"<3, " a0 @fnools.total_orderingL2stObjectL}a__eq__w, otherWreturn isinstance("), MM/ltM  oSmalle5 NgComparison`s(unit. v4e6 = 9@Addr1]v4net%N%Mintf&I(6s6s6s6s6s6s$v4bes = [@, v4A]$ov" 1+13net(6L1, v$L1L]5&4_objects + v6_o bjects v4addr2 = ip ess.IPv4Address(2)'>net&vNetwork&Nintf'Interface)6l )6v6v6v6v6vdef test_foreign_type_equality(self):*# __eq__ should never raise TypeError directly7other = og(@P0for@ in j.!sq%assertNotEa(obj, WM ,PFalse)? ==+ T.(Z, NotImplementedk@One__@s_mixedq Ensure none of the i<0nal; accidentalu# expose3right setDattributes to become ""J?lhs %r% N1if MKs rhcontinue@lhs,K)SOsameR ?obj s,oOLess+|Greater.ordering(A1..,] ?2),)5net(c'X( P) )yyP y2+ (&+ (r?lhsz)W.N>(<|~(P=Q=RI0ain,~u0v4_Kesse InF4net Q6Q6net)  for obj in self.v4_objects + [6net]: assertNotIn(obj,B/). a6a4a/!) bdef test_mixed_type_ordering()5lhs!%r% )if isinstance(lhs, ~(rhs)) orrl rMcontinue.l Raises(TypeError, lambda: < }@'>@,/<=A,>Aforeign pother =Fect(smallest = S O$Blarg#L "'<BwithT!< K$>K7/<=L7>L@TrueB3 < +BFals,>,W=,X-$< `>,/<=.Z-H=`key=ipNess.4)h '1#.assertEqual(v4_ordered + v6 ?, sorted(self.objects.Fkey=ipaddress.get_mixed_type_key))qY assertEqual(NotImplemented, H (1)) Pdef test_incompatible_versions!):*# These should always raise TypeError. v4' =0ip_qess('1.'\v4net0network06M 1a8::1]6] ,cR%s(", .__lt__, v<g<!7netw?netv:u:vw<x<dv:u class IcUnitTest(unit.fCase):\setUpDipv4 RIPv4AW2.3.4=interface?IA//2D BN20@#hostmaskB 0.t1/0.25566NsM'2001:658:22a:cafe:200:/6_4b!//6U/6_U6U:LPORepr;"/0'1.4/32')"3r]F/')3 {7'::1/128x Ct# issue #16531: constructing P from an ( , q) tupleKS6T XQ# /32+W-ipx92.0.2.` IPv4Network('192.0.2.1/32') self.assertEqual(ipaddress.IPv4Network(('19@', 32)), netH/ip?*3221225985G* W'255.' )~hL@# strict=True and host bits setrWwith Raises(ValueError):,624)a4XA `A /0'&CeN3mOFals onet = X>O0/247-I24), Et)|ee/1' 3B49255.255.0'),/ strict=False), net)C$self.assertEqual(ipaddress.IPv4Network((3221225985,<T'255.?0')BU# /24Zip = A('192.0.2.0'=net117/2444@' 5%/ip|g54gO 24)H(?) GT Interface(21',KE  E157# issue #16531: constructing IPv6 from an (, mask) tupleKdef test6T(!):-e# /128=6=2001:db8:: >&('2e6tAB', '128')= e(4254076641128259285690398495826560, 128>?(ipF/96/D2Pv6Network(   (42540766411282592856903984951653826560, 96)), >Enet)!self.assertEqual(ipaddress.IPv6Network((ip, '96'Z[# strict=True and host bits set(Zip = wA('2001:db8::1'Wwith Raises(ValueError):^ ] ^77c4P1COFals =netGF/!^[ A!1'Di=w?  ID96),+U# /96 Interface(B I$f # issue57def testIntMath(4=A('1.') + 255u A_2.0')d ;1.1') - 256|#0A|6# + (2**16  EOffff:/ -)('::1'))  def testInvalidIntToBytes(self): *.assertRaises(ValueError, ipaddress.v4_int_to_packed, -1)F/BG2 **IPV4LENGTHw 62 F66mternalYip1 =2v4AT('10.'?ip231333231Equal(list()c_find_7_range([ip1])), P[(ip1p61)]l%I3qa, (ip34}52N3v 0128MQ._count_righthand_zero_bits(0, 128)?"IPv4Network('1.2.3.0/24')", reprr.ipv4_n'1)) sMissingEqVersion7Uclass BrokenCBase:.Apassh b9$ =B'127.0.0.Wwith !Regex(NotImplemented"2.*v"v.C? 3Get } 1int$ A.Id), 16909056/stK'? 6ME 42540616829182469433403647294022090752"'2001:658:22a:cafe::f.assertEqual(str(self.ipv6_network.hostmask), {'::ffff1') 3def testIpFromIntf!):SuassertEqual 4_interface._ipipaddress.IPv4I6(16909060)@svipv4 = 7$ip('1.2.3.4')/2001:658:22a:cafe:200:1C ,@int(._&))P6P 6P v6n = 425406168291824694335477624820979466258 2P6 `/&E=.versionK4d .0j6j6 !aPacked$x K!&ip(b'\x01\x02\x03\x04'P('255.254.253.252'L 5pff\xfe\xfd\xfc' } u2 J#20R6\x58`2a\xca'80<o1').ipq'`R2:3:4f:E@f\x0O4' +Pf' + 00' * 6 :W1X\GetIpk26Uip), Y+@+@BJB6| l!w'58:22a:cafe:200::1') def testGetNetmask(self):".assertEqual(int$.ipv4_network.n>), 4294967040)E?strE T'255./0'J6 3402823669209384634449278633580586598 0elfwprefixlen, 64cOZerodJ@zero = ipaddress.IPv4Interface('1.2.3.4/ V  @_T_from string('0'), O_True(Nis_validEB .0/')HOFals!inID_ipv6_ 6?::1 R @ _NetAndHossanet = GT$b^net._T7;:G128.>B} ?O.127C-?255C BFh/('A5pxt8<>6>6N NGP('1271.0/w /u2uGetBroadcas b@_), 16909311eMMQ QQiG 42540616829182469451850391367731642367) self.assertEqual(str(ipv6_network.broadcast_address),CJ'2001:658:22a:cafe:ffff1') Cdef testGetPrefixlen!): X ipv4_interface.pFO, 24 D6D .64Supernets;().3 4I\1.2.2.0'pw{#ipd.IPv4InA('0.E/0'){  ENU CdrhE6EIE:Q 6D?::0@ NMLIV3)31?B3/0! 6" # 8:#4Raises(ValueError, . x4 p_diff=2, new_=|6j/25= 93len !(#2)/ 4esW|  new_prefix=65)  self.assertEqual(ipv6_network.supernet(?len_diff=2),GOGA2)) Edef testHosts!):Rhq = listU.ipv4/()254, len(+* ipaddress.IPv4A ('1.2.3.1'), C?[0]oE 6254G3-1]w9 = G"6N ('2001:658:22a:cafe::/120'0U.+ 5+!6+8"R /ffD# special case where only 1 bit is left for hYs = [z02.0'3 E1')]fpstr_argi'RE/31' 4tpl (!V', 31^,!$ip$(u)N)NRGN ] ? 7.o', 127)\FancySubnettingJf Uasorted' qsDs/3)N?27)Raises(ValueError 7 self.ipv4_network.subnets(new_prefix=23)) 2assertRaises(ValueError, list,,3>pllen_diff=3F Q 7Equal(sorted(6 ?4))N?68)N(q?p /- A8)) Hdef testGetS!):?.e))[0].O, 25MAstr(Qpt|fV_addressE '1.2.3.0'C?1].C128'jj#65N ForSingle32sip = ipCb.IPv4N(4H4/327(P1 = [x) for x in ip%)]22 23: DH1, [] #, =2?128 6 B::1/jh* ,s  9:ipss0/26', )64:128 92]Y/v6 Y*v6['2001:658:22a:cafe::/66', '2001:658:2'O4000,8,c,1]) def testGetSubnets3(self):s = [str(x) for x in *.ipv4_network.-F(8)]Aelf.assertEqual(%J[:3] ['1.2.3.0/32', 12/])^?-3:_0253Ea;2545e 4lenc), 256P1Dipv6 = ipaddress.IPv6N)(g:/120'yct.8_:1/12)2)R !fdR @ V/fe*f* HEFailsForLargeCidrDiffXRaises(ValueError, list\{interface.'9)Mn4dO/6_/65>He`opernet/W  kjjj#65!Negativh/-1 >e'  self.ipv6_interface.network.subnets(-1)) -1assertRaises(ValueError, list,,0 >oe:def testGetNum_Addresi=!):$V.aEqual(Tipv4_]Tnum_a@_, 256?Dj))[0].R ?128ksupernet()ce 512) i:61844674407370955161U#922337203685477580v u 3689348814741910323@YContainsQSIn(ip:d.IPv4I('1.2.3.128/25')?Notk o4.1/24i? l# We canR es and string as well.T&J1 = ?37'1In(@, issue 61, bad  comparison on like-ip' uobjects # with identical broadcast'<[FalseN1.0.0/16').__c/5__(yj #B0BC5'))~?Nthy1str$c[5]), 5~SIndex.__getitem__-#4 '2001:658:22a:cafe::n {1 << 64UG5 # http://code.google.com/p/A-py/s/detail?id=15 72.31.2555 ?240W128,.prefixlenMt_! =PP )'1 ',5F6[0] self.assertEqual('172.31.255.128', str(addr[0])) self.assert9'439_list[-1?$: c , 3 sdef tes!):QTrue(ipv4_interface ==/3 ipmess.IPv4I3('1.2.3.4/24'3OFalso p3pG6/::*? ''I ? []4"2) 6 p 2001:658:22a:cafe:200::1/6t;t p!  4/Now!  ko'n.p3 3 #4_ u tAddress5l h11 2 != - ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/64')) <self.assertTrue(dipv6_iL5 !=/3s 3s,w 41.2.3.4/2n ? ''? []352) Kjz x A#('ng11 def testSlash32Constructor{/): Equal(str(6W/255.U')), 332' ?128*w0128x'/- 0*/!0. /0.Collapsing# only IP  es including some duplicatesZip1 =4@1.1.12/ 1?ip3/ ^4/ 3^5/ 4/6/ # check thatSare subsumed properly.Pc)edk_(2[ip1, ip23456Tlist(^9d),VZt4NetworkO/30'6  6 4/]fa mix ofRand nx ip4 = ipaddress.IPv4A @('1.S3') z#ip5 = 0Interface2J4/30565 check that es are subsumed properly.collapsedp_H([ip1, ip23&4]self.assertEqual(list(G5d),q[tNetwork05]) A# test only IP n0s 9ip1 Ug0.0/24o?ip22 1232 2242 329 42# stored in no particular order b/c we want C to callC# [].sort.ip U2U#^5is ?ip6O$   =twowpernet' "T?3')Osame_ 81/3FK1[ip( ?2]) '1sf@4essF1iC.ip_b6r2001::/106222  2$96< # test that ipv6 addresses are subsumed properly. collapsed = ip7._es([ip1, ip253])Bself.assertEqual(list(Bpd), [ip12# the toejam testo_tuples = [& ($ipA('1.='),22_::1')/aIPv4Networkbo0.0/24e EIPv662001::/120m"/32m"8m]Dfor 1 in$m:%jRaises(TypeError?ess%PD1]) r1defSummarizing(~)9#ipB\l#ipnet&n&sde)Ne_range69ip10F1.0' ?ip2. C255'  jps only 0 & QPclass"7A 6?e@%tyH||versiontreturn 78ip_invalid5IPv'R))>lDValumKU =(&2)#ks that axPy ove4 & ip6 fails ;9(8a /24 is'iz{xo2))[0]H V8 F an!4 .Tisn't on a D byte boundar~&8T [ 9j> 78')e# all! ?0U '| ._ALL_ONES) self.assertEqual([ipaddress.IPv4Network('0./0')],  list(summarize(ip1, ip2))) 5fip1 = h3ip_sw('1::')*2*_ffff: K# test an IPv6 is d properlyyIself/[0 nL1::/16') range that isn't on a @ byte boundar/ip,2V(3ip_: :2W28')]+ exception raised when firs! greater1on lastR:s(ValueError,  "(.1.1.0')E *E0E 1and@ are"3IP /es?Typ,% E  not same versionJ ('  1defZA5Comparison(!):%S0Tru.Se1') <=;?I81.1WtT2t/::"775 P ipaddress.ip_ !('::2')) def testInterfaceComparison(self):'+.assertTrue(]i@A('1./24') ==@D@)>~e16') w&'w}'?}%1 }%_::1/6i$<:a ; 80Y1::2&!O2/48K"u! 1/$O u)$u\95Network# ip1 and ip2 have the same n= +2=NCIPv4i02/2 2632'?ip32 #2.de:1 < ip3)  self.assertTrue(ip3 > ip2) $ Equal(ip1.compare_networksG), 08# if addresses are the same, sort by netmaskm2), -1)8 213p3pKpe1._getH_key() < ip3ip1 = ipcb.IPv6N('2001:2000::/96')?ip261636 Iffffqd1#: [r'r# Test  ing different protocols.# Should always raise a TypeError+R&%s(%,P 7Dipv4? >6>Mipv6Interface('::/0T,v4/4/!0. 4z  .__lt__, 68g8 6p4p8p4P# RegPion t8for issue 19 $ip('10.1.2.128/25q@FalsT$$  |o3.0/24zO22y2$yHk2G:Um 33Hk% /28%0.10.0/31twork('10.10.10.0') ip3 = ipaddress.ip_network('10.y10.2/314441sorted = [ip1, ip23%4](un(#4#23(./(self.assertEqual( Ded, Y+fp2k:Is(ip1.__lt__(ttU0')),NotImplemented l2l@# <=, >=~JTrueU .1F') <; ;tI?2')tOFals 2Z?::1p!7U5/::M!6m !) def testStrictN s(!):"FRaises(ValueError), '192.1688/24N`::1/12}OverlapYotherCIPv4('1.2.3.0/3Q425 :2.05 / j2.64/26NaDipv4i$.oaj < 2=x]2m+3)EmbeddedIpv4string =A0.1'Y$ WInterfac+2v4_Cpv4compat_ipv6=6='::%s' % e FAint([pat_ipv6.ip), int(ipv4.ip)) 'v4mapped_ipv6 = ipaddress.IPv6Interface('::ffff:%s' % Hv_stringKself.assertNotEqual(_A.ip,;7vRaises(AValueError@,P'2001:1.1') 3# Issue 67: with embedded#4 r not recognized.@def test<TooLarge(!):'# RFC4291 2.5.5.2).;83ip_FFFF:192.0.2.1') D c000:201' 2 (part 3) x::d.+Cv|Versionl RO".v:?, 47676BMaxPrefixLengthiga.max_pElen, 32@;128oPacked.p9pb'\x01\x02\x03\x04'GIPv4h255.254.253.252').zff\xfe\xfd\xfcz a#20R6\x58`2a\xcay' A1 (R2:3:4:*@f\x014\xJfQ + o0' * 6R::1:00n|' ]IpTyp9netip_network('1.2.3.2 3?ess36e /::g6Sg5:IPv4Network, type(ipv4net)) self.assertEqual(ipaddress.IPv4A %, ?@6Network@666def testReservedIpv4(!): #"" ns' fTrue, ip_interface(7S`'224.1/31').is_multicast]LFalsfa('240.POr%%) -q192.168"17private%S9Pt'10.255c 11/.0M@_72.31;S2  p'169.25sB0/24klink_localo_00.20. PE?5.1v  *O D'1273/32oopback)vh4?/16cd@'128lOP00.64k//1F4R.0/10').is_global) self.assertEqual(True,&#ipaddress.ip_network('192.0.2.128/25').is_private)Lk9b3.0/24igs# test /es  6A('0.dunspecified OP224.1QmulticastOoFalse,P4/.0PO 1Ooreserv \# Vt239.255 nO-6168^|P 9P\D '10c 1=P72.313S5.Mp 16p4.100.20mlink_loc @ oop#5pQq=(Z#7.F203.0.113H:$273.25loopbackW127.4+O P8,O  '\1defRQPIpv6(/): cqbffff::FTrue, ipaddress.ip_network(2**128 - 1).is_multicast) self.assertEqual(True, ipaddresN'ff00::'LOFalsM?dffM$%ecMsite_local## 'feff:ffm nbmc5 |cprivatei6[ijf 4'fbVP-eP$%eaVOlink= OcL  7d.O'fec}interface('0:0::0:01loopbackQ::1/127O*'$H21I-Junspecified-M#::vL2v O B200180:h gHglobs# test %es`qual(True, ipaddress.ip_ ('ffff::').is_multicast)  self.assertEqual(True, iL2**128 - 1N1_'ff00OFals?'fd"E'fec4site_local5#qq 'feff:m nbmc5 |T6'fcprivatei6[d jf 4'fbP4eP$%eaVOlink= OcL  7d.}0:0::0:01Vloopback#?'::HI L'::2%":0Junspecified  L# some generic IETF reserved %es/1USnetwork('40KR1/128Pdef testIpv4Mapped(!): hs"':*192.168.1.NQpv4_mh,  ipaddress.ip_ ('192.168.1.1')) * self.assertEqual(>::c0a8:101').ipv4_mapped, NoneO OffffT ?def testAddrExclude(!):RI1 = Unetwork('10+f.0/24'4246434 ?2.1h44}6ess e512001:db8::0/3276754G 3sorted(list( 1.Sess_ezU2))),} [ o64/26'@  128/25')]Raises(ValueError, , 3DJ?TypI4I55Io1)), [A6)O0/30(4b" O6/31~(O8/29?(_16/28@(_32/27@(`8LHashxy\h% interface FED ),  hash(ipaddress.ip_ ('10.1.1.0'))) 3U# i70self.assertEqual(O .2.3.4')),@V@4?intnX._ip)oip1 = o?ip2/6::'dummy = {}=[&Dipv4\] = None(6( ?ip1B=ip2~1In(!, "05ip2"def testIPBasesQ!):anet = Dfunetwork ^2!'10/24', net.comp&ed W/6_W0RaiValueErrorV_string_from_ip_int, 2**128 + 1) 2v6NoHelper  2001:658:22a:cafe::/6with_prefixlen0G[ffff:/:'hhsnetmaskq:n}q?hosr"*str(net)44@  /;C55.20FuD 0.8255@DAW8CopyConstructor  ,z?4 141,3]interface('`200::16 F4Ft3.5.RIPv4A ('71.1@6161' T01, 2'3'4' '5,d5)) self.assertEqual(addr6, ip ess.IPv6Address)) def testComp)aself):'+'_Qees = {'1:2:3:4:5:6:7:8': j/128',62001:0:0:409/:87 p79 90<3`0:ffff55:810:5q&m:6Ll7Kf\%#/0+0 )1'1Sx658:022a:cafe:0000F/66'n:98:& ^::1.2.3.4o02:304k:7 D::7:6:5:4:3:2:0z 6U 606 j :: 606 6}sfor unc,Fed, in list((.items()I\ Ij, str(Interface(F)ExplodeShortHandIpStr(};1 =/s'lE:1')}323b1 0:5ef5:79fd:0:59d:a0e5:baI3INetwork(IK:/96|434|192.168.178.j r]n }x 21.ejd$qlq2'::<)# issue 770 f  2m rp addr3.exploded) self.assertEqual('192.168.178.1', addr4.ex:;def testReversePointer(N!):"`;`1 = ip ess.IPv4Address('127.0.0.1')23632001:db8::5w Y`27.in-TS.arpa21.r"_pJU8.' + @'b.dS2.ip6321IntRepresentation 16909060, int.`.ipv4_nOess)42540616829182469433547762482097946625,  r6r2ForceVersbip_network(1).oion, 4=_IPv6N>96) }WithSta fX!face.with_prefixlen, "1.2.3.4/24"KnetmaskpbC55.20m"?hosn1C255"?q_ipv6_#|= '658:22a:cafe:200::1/64VduMs[ffff::-# this probably don't make much sense, but it's included for# compatibility N b":'MElementCachingn'b# V4 - sure we're emptysNotIn('@1', ._cacheVFbroadcastH,L populate andP!4  ipaddress.I Pv4Address('1.2.3.0')) self.assertEqual( ipv4_network.broadcast_aI,>E#ip$..Iy?255{hostmaskr 0.r # V4 - check we're cached"MIn('1', # "_EUE< # V6 - make sureUempty%0Note 6H?populate and test! `Uh^62001:658:22a:cafe::h6_interface.>F/6ipv   q Zffff:% :y~ o)@q3f]<  E>!F91defaTeredo!):# stolen from wikipedia server = V65.54.227.120'oclient8192.0.2.455tA = '0000:4136:e378:8a63bf:3Gdd2'lf.assertEqual((server, client), ipaddress.ip_ q(teredo"). )C1bad = '2000::4136:e378:863bf:3fff:fdd2'9self.assertFalse(|_yo1:0001}MU# i77RIPv6AQ(1:0:5ef5:79fd 9d:a0e5:ba1'TgEqual(EIPv4S94.245.121.253'  C5.26.244.94')B def testsixtofour(!):jR' =f 2:ac1d:2d64::= 0=jO p172.29.Q/00M .- if __name__ == '__main__'<@unitY. () """Test the interactiv preter.""" import sys o U subprocess from textwrap Eddedentast.sup^ cpython_only, Supp@pCrashRe);.script_helperiRkill_M T spawn_repl(*args, stdout=Q.PIPE8errSTDOUT, **kwa"""Run=P REPL withgiven arguments. kw is extra keyword$s to pasopen. Returns a PJqobject.  # To rout using a terminal,  "qcommandW# line option '-i' and n@ set''# The directory ofv[0] must matc+ $Qexecutable for~p() callzto succeed as)ZLpath may be used by Py_GetPath()MBbuildefault module searchJ!_f P= os.ed.join( 0dirV(sys.C), "3"Acmd_s7= [W`, '-E'1i']).extend()b# Set TERM=vt100,6 raae2 in1Q() ofi#.support.scri,pt_helper. env = kw.setdefault('env', dict(os.environ))1['TERM'] = 'vt100'"return subprocess.Popen(cmd_line, executable=sys.,Ahstdin=X?IPE3out=stdout, stderr?err: **kw) class TestInteractive preter(unittest.$qCase): @cpython_only@def +_no_memory(self): # Issue #30696: Fix the i| } looping endlessly whenO2no j. Check also thatXfix does not breakoLm` an exception is raisedIuser_input = """Eimport sys, _Icapi"91/0print('After}".'XP2_no*(0&t(it vdedent(L6 = .encode()p = spawn_replwith SuppressCrashRe(!p.o.write2outoRkill_z&(pi.assertIn(bM", G7p# Exit  120: Py_FinalizeEx() failed to flushbpout and #er_ "p.([P, (1,`)) if __name__ == "__main__"'p3() Obuiltins`collecdatetime#functool!K4lib"uinspecto EcachLos from os.path K normcas'e_pickl dshutilc%syFtype textwrap(0uniCGdata T.mockwarnings try[concurrent.futuresThreadPoolE2or ! IRErrorJ+ = None '@.sup_Drun_ , TESTFN, DirsOnSysPath, TKMISSING_C_DOCSTRINGS< U.scri2PZ_ok, 6ure9;_fodder as mod' 2(2)-@_i_Cy_to` # Fions tested in this suite: # ismodule, isclass `method function traceback Bfram5Aode,Iabuilti+aroutin generator6 XgetmembersFgetdoc, getfigetsourcecomments0EAtree argvalues, formatargspec # current!stdatadescriptor # NOTE: There are some addi8 al tests relating to interaX with # zipimport in the<_A_supS `. mod =0.__ P__ if P.endsi(('c', 'o')): t <,Q[:-1])Plize  names: on Windows,wcase of$compiled #ules depApath usedQstartOpython executable.@normp() def revise(0, *return (<'`),) + *S git=StupidGit() ^signatures_B_lexicographic_keyword_only_paSters(~1"""fYields a whole bunch(s F S- S,Iwffthose w`always9 ally sorted order.IEP= ['a0bar*Adeltpephraimpmagical @yoyo1z']WPfor irange(1, 2**len(hz~Rp = [:b1JNjNH-if i & (EC<< j@p.apF[j])pPn_tex "Yfoo(*, " + ", ".join(p7"): pass_symbols = {}P"(fU#, # xy s['foo']"unj0_fnthrow, outq, baby,V_: @the_;sthwaterB/ A = 'C_ baXR'.splc IsTestBase(unit.DCaseredicatecpset([inFt.isxX&, $c&\ U<EA=)@8#co, inspect.iscoroutinefunction, inspect.isasyncgen, F1]) Hdef istest(self, predicate, exp):&qobj = eval(7.assertTrue(A(obj), '%s(%s)' % .__name__fgfor other in \Qs - set([]='ifd7 ==generatorU or \>& =R<! ^) and{ o continue.aFalse(SGnot +__example$tisrange(2yield i 8 T _Z, `f return 'spam' @types.< Egen_N  Xclass EqualsToAll^a__eq__H,8GG" ETTestP@s(IsfBase):_excluding_shaglobal tb4.builtin, 'sys.exit')3[].append4code, 'mod.0.__'__92try=51/0jexcept Rtb = c_info()[2]3C@framatb.tb_8traceback, 'tb3if hasattr(l , 'GetSetDescriptorType'jugetsetd>B0 'u().f_localsJelseIBR# k)<kfinall# Clear J!all the s variables hanging to it.6Non" 4StupidGit.abuse?method, 'g3=rgu3istest(inspect.ismodule, 'mod') self.istest(inspe-datadescriptor, 'collections.defaultdict _factoryYbgeneraT(x for x in range(2))B1fun5, 'V__exampleOasyncgen,'_`/(1D4genk$5') with warnings.catch_5():(0.sifilter("ignore" ,coroutin> k N_b V if hasattr(types, 'MemberD[Type'm: datetime.delta.daysDJelse^]assertFalseE b(`)@def 5_isf(`@gen_4 =  8&(11-4r.$O( ) cVN~9_True(*bU)5 1 ?( ,-J)_*J.close(); # silenceawaitable$gen(): yield4 M: 0 =  a u3ro))  class Future: def __await__()(Epass2 self.assertTrue(inspect.isBRable(fO()))7OFals8 5)) 72NotS): not_fut = "(s. = lambda: NoneeN oro.close(); gen_c # silence warningsptest_isroutine(yd1mod.spamb 5[].counth is+0, 'StupidGit'w:E(lis^ CustomGetattr(object)2__g#!__ , 0 )-oreturn($y|_slot_members}F/ C_;s__ = ("a", "b"7Wx = Cx.a = 42tu = dict3get/(xIn('a', 's0Not'b'zisabstract from abc import ABCMeta, 1bmethod'AOCExample(meta=F&):8<@U= 5t*revise(*/[0][1:]),U Mfile, 16, 'eggs', ['Tst = )\n'], 0)x1x 9, 'spamw(b + d, c + fu 2u 43, 'arguew(a, b, cz 3z 3p z.| #  named tuple field@record = b2Is()../fr Xp.lineno,,V, __/__8tunction2KIn('3', code_context[0]A#Pindex3hotr), 3n -@z[' eggs(b + d, c + f)\n'], 0)) self.assertEqual(revise(*git.tr[2][1:]),18 (modfile, 18, 'eggs', ['q = y / 0m=def test_frame(y!):6args, var kw, locals = inspect.getargvalues?.frL['x', 'y']+zONone( & , {'x': 11, 'p y /4}dWforma0varl T@'(x=y=14)') up?ous=.f_back0['abcdef?'g'f'/'h% s1'(a=7, b=8, c=9, d=3, e=4, f=5, *g=(), **h={} class GetSourceBase(unit'.TestCase%Q# Sub1es must override.fodderModule = \setUpswith open(Agets/.W)) as fpb.7 = fp.read(fBrang, top, bottomI@lineQ.split("\n"preturn a.join(9r[top-1:VA]) +!ih_, obj!  (O(objz B1)  RetrievingYCode(*f = mod8A_getW!es7a OamemberM,g!is,tC= +esf[('FesteringGoHmod.:  ('MalodorousPervert',.H ParrotDroppin D StupidGi8 T20tre{{([cls[1] for cls in es]) self.assertEqual(tree, [(object, ())( [(mod.ParrotDroppings, ?= >FesteringGob, QMalodorousPervert  /))O ]h StupidGi%PG .M/ / ]N  ; ] = inspect.getclass([cls[1] for cls in es], TrueGRZdef test_getfunctions(!):!M ypmembers,$is.m#s, [('eggs',o ` ('lobbest<?Cspam< A)]) P@unit.skipIf(sys.flags.optimize >= 2`"Docsts are omNd with -O2 and above"#= 2, "Docstrings are omitted with -O2 and above")Bdef test_getdoc_inherited(self):%j.assertEqual(inspect.9(mod.Feste}OGob)L'A longer,\n\nindented d".'/{o.abuse inothers containingOtabs(/()u.radiction The automatic gainsaying 0@unTst.skipIf(MISSING_C_DOCSTRINGS, "V requires sy|finddocp4 = i_!(int), int.___L4.to_bytes=F/()H3Y.fromS.real >K_clean1P'An\n/.'t >:6 getcomments04mod), '# line 1\nuStupidGidK)20L+# If the object source file is not available, return None.<co = compile('x=1', '_non_existing_Opname.pyOexec Is\6co) has been defined in Conlist))lmodule# Check actual %"r + ),8Tclass (uses __0__ attribute2h.h method (nos, falls back to/name) s0elf.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod) # Do it again (check the caching isn't broken7s}4Cpa builtin`str), sys.3s["F6s"]"# dfilename overridelANone9FCAdef test_getframeinfo _first_line(!):0v(_)7 = 1.fodderMv.fr, 50S =U.code_context[0], "# _ 1\n"C 1C 'A9ule docstring.'P]sourcS!g, 29, 392 , 21, 516lobbest, 75, 76) normcasex?Rspam)/M%Nfn = "_non_existing_p_used_for__A.py"co = compile("x=1", fn, "exec3 ``(co), 4S!e.e[co.cob] = (140, ";:", $L6tryM coHfkfinallW1del8By<70-1!._/__4_class_without_m' y$ CM(type5@property_Nk__(cls7%raise AttributeErrorFtQ(meta ;=CMDEpass0 R]Rs(TypY < ;C __reprJReprM7,__9Exception('xyz'Uer = _(,er) def test_getmodule_recursion(self): from types import M2EType% name = '__inspect_dummy'!m = sys.n s[17] =L()1.__file__ = "" # hopefully not a real +A9...CbloaderE" # pretend the: is understood by a >Qexec("def x(): pass", m.__dict__D.assertEqual(.getsource(m.x.__code__), ''J>del9WZ(compile('a=10','','single')) 8tproceed_with_fakeqF `'''doc5 monkeypatches linecache to enable Vion''Bfn, (', 'N&\n10get^6s =f??(R", _globals=None7&ifV== fncreturnR.spli(keepends=True4OelseJLW# =z:trykn+%{}! , F, nsy4{2(ns["x"]'kfinall {2_onlobjectyHS7Nmod.eggs=, 12, 18) class TestDecorators(Get@4Bas bfodder_+d2wrapped_dI#2.=, 14, 17}replacing^#gone, 9, 10Z\ unLP, 1302Z3olambda_Qfunc1y13, 1150OneDN"_o?_# p a one-~ ? FtionO2.oll, 25 5Athre$@,q# wheresecond a1ird>s are _not_ indented3. self.assertSourceEqual(mod2.tll, 28, 30) 2def test_twoline_indented_lambda(O!):,a# Test inspect.getse with a two-H ? function,Bwhere the second 1T_is_ ~i, 33, 340oneWregular oneEz@, 37 manyargs% K[Uarguments are oncs and _noti @Abody7 aUlast f, 40, 41B!is"wo, following0 li'ndcontinuedBqhe nextG by a \\, 44, 45 :@_in_Gdefined in a,xa[1], 49 anonymou  a to another@, 55) classBuggyCases(Ge@CBasefodderModule = T G%@_com K8, 58, 59[PmultiO_sig] 9[0], 63, 640nes`P69(). A71, 2@one_"r_xed_by_non_nameqB77, h dec"Qcls82B83,  i_instead_of_docstrin<@88, 9`methoddynamic_class(self):  rself.assertSourceEqual(mod2.method_in_dynamic_class, 95, 97) # This should not skip for CPython, but might on a repackaged p"c whereOunicodedata isRan external module, orMQpypy.9@unittest.skipIf(not hasattr(T, '__file__') or= =.;.endswith('.py'),G"<cbinary!")E@def a_finds_((!):& Raises(OSError, inspect.getC', iC D7linecaches = ["x=1"]Ico = compile(%d[0], "ally_created", "exec;D/co P:.a[co.coname] = (1, None, ,:s, #6try b(co), 26,0)M@ ?6[0]>0finr 1del25out 6f3 in ['', ''] ,q'x=1', ; ,+IO,P?O>B_on_Y  CyQWithMP, 1189o1nes#?uncgcls135.func136, _  TestNoEOL(Ge2CBase_setUpu tempdir = TESTFN + '_dir'+fos.mkdir?.0> open(os.path.join-]'>_fodder3%spy' % os.extsep), 'w') as frf.write(" @X:\nTpass # No EOLDirsOnSysPath3BdimportEmod3"%M  =>!ruper(). arDown(self):#  shutil.rmtree(self.tempdir) %def test_class"!):B1assertSourceEqual& .fodderModule.X, 1, 2) I _BrokenDataDescriptor(objecta1"""i1A b,u data d.. See bug #1785.-5__get__(*argsUraise AttributeError("e"?__sPbRuntimN<Oattr0 ;oMethod=m/?N g A?get !V # Helper forAing _2ify_n0s.  _wo_objs(clreturn [t[:3]L in inspect.Q>]PTestC esAndFunctions(unit=.!3ase_newstyle_mro6!# The same w/ new-B MRO%A9Apass  !oB(A): CdD(B, C5O exed = (D, $S, A, (Ugot =C0get%D) 93YW, gott]qArgSpec+, routine, r_e, var e=None,l rvarkw_e* defaultsformatted!Wwith Warns(Depreca7ing3{ 5kw,w *,Cpec(4*'w3/_e-  )4X ifID is not ;N$;(E )% h OFull>t  C`kwonly_e=[], kwonlydefaults_e=None, ann_e={}, formatted>%):?args, var kw, defan, kwonly uann = \Linspect.getfull9pec(routine),self.assertEqual(* , _' -_varkwV  /  !3^7; Qann, ?&if is not Wwith jWarns(Deprecation7ing76J?Sa* ) Qted) def test_getqArgSpecs(mod.eg%['x', 'y']P'(x, y)'kL Ospam D0['ambcde?f']A 'g,h', (3, 4, 56 w'(a, b, c, d=3, e=4, f=5, *g, **hRaises(ValueError,y S mod2.keyworded, []Xo9tannotaton9_WC_arg >IFull] B_e='arg1' @_e=[;2{?<@?:1}~@='(*?2=1 1t"={5 : list!>rkeyword_only_arg, [], kwonlyargs_e=['arg';formatted='(*, arg)') wdef test_Ypec_api_ignores_wrapped(self):0!# Issue 20684: low level introspection API must O$ _P%__K@functools.ms(mod.spam)#ham(x, yEpass(# Basic check.assertArgSpecEquals(ham, ['x', 'y'], %l'FOFullJE ppartial) # Other variantAi=_method(o fJMR< zF,, vclass CO<'@Z H% Jmham = h0__call__W 6C() . /() /.p; J_new?new(}Oinit(?)@z\tgetfullcsignature_attr6( #A_par!int .P`eter(' =', .POSITIONAL_ONLYI6.__5_ =@S(td0s=(e#,)is-gC }DOnnosE"a: ) -> 'ham': J'ec g($F.__annotaPs__, .def test(): pass# spec = in t.getfullargf(test),elf.assertEqual.__annotations__, :.!) BP@unitQ.skipIf(MISSING_C_DOCSTRINGS,+"Signature informn for builtins requires docstrings"@def y__;_methods(self):FullArgSpecs(_pickle.Por.dump ]P_e=['a', 'obj'],matted='s, obj)'?<1(io.BytesIO())pX os.stat3kpath']ekwonly$`dir_fdAfollow_symlinks9defaults_e={'=: None, 'C{: True}{R, *, K=I H=F@cpython_x grAfuncimport _MAcapiJ& =.t_with_sC}ar (@.V[0], 'avocadoB~6_no64S{ QRaises(TypeError{,Xt`defini,_order_preserved_on_ efn in EsFlexicographic_keyworIly_parameters(Eo&fnjl = list(<. +psorted_2 +(l!F2l, I_I#un7only_parameters_fn) l = list(signature.kwonlyargs'self.assertEqual(l, unsorted_keyword_7_parameters) fdef test_getUpec_method(V!):&class A(objectGm2EpassGVqArgSpecs(A.m, [' ,']}ify_newstylel!qYs(): s = static{;_c(cls>Ac = z=c=Cgetpp = property(*AX> )m1^ atablob = '1' dd = _BrokenDataDescriptor(Z)m)M +q@attrO_wo_objs(A`In(('_b__', ' H3', f!, N,e'missing JlBinitmf P.s$A)M cQOP #OpO]?', KGmG2E Splainr: %r' %k1lLV'JdP F md@% d= Ot Ke[B(A):?ef ";" =vBBfm1In(('datablob', 'data', A), attrs, 'missing 3) self.assertIn(('md@Pmetho B descriptor'OdE K class C(A):`def m(u): pass3c " =_wo_objs(Csrstatic W $QcQJCTplainmIpIpropertyGmG1)m1J9?blooD(B, C1DB>' DJ'YQtest_ify_builtin_typesO# Simple sanity check that all <A-in = can have theirEsibutes xEied.!for name in dir(_Us__):'jrin = getW -,G?2if isinstance(@, \.snspect.y(_js=) oFboolp__new__M T!, 9 'missing __new__') *self.assertIn(('from_bytes', 'class method', int), attrs,BI'k ;p&tonh"Tplainhp__add__gLngObool7 fdef test_Tify_DynamicCAttribute(!):3. Meta(typeUP__get!__=\, nam)-!if == 'ham'ereturn 'spam' super().|v1qVA(meta = @/s. K|1ham DFeggs should_find_dca = inspect.o , 'data', VA.__dict__[] a\` _Ws(VA)Ig?,H /gaf^ overrides_ w NoBool(objectRT__eq_[other%L!) FHA aise NotImplementedError(KOb"This does not `ify a mean value"_HasNB4d =8de!, ?.ddZ O)Z  fish = 'slapzsXr|3['___module __i m%']Pw Epass6f# VirtualAttribute(self): class Meta(type!def __dir__(cls"return ['__K__', '__module3nam eBOOM']Ce`getatti , 3p!ifA =='KK)42isuper().__x(p/ CQ(meta=' Epass6 should_find = inspect.Attri|, 'data',wV, 42)Belf.assertIn(P,O3ifyp5!s(1)) IQBtest"+uVirtualb_multi /es1S?one4J 1" /__2S?two4J ) 3(12)Klist(sorted(set([three'] +.! +2&))7%!__+t 311x <24:1, 3@1 F1, 1UB2B B82, $f3B  DF3, 37cca;( _Swfor sf in 81,  Kof, cca_with_buggy*/ Mef __dir__(ckls):  return ['__class__', '__name missing']<)q C(meta +=MZEpass/attrs = [a[0] for a in inspect.B3ify.6(C)oself.assertNotIn('!, .!) ldef test_getmembers_descriptors(Hx A(object"dd = _BrokenDataDH!()m%m)iMethod+,pred_wrapper( u# A quick'n'dirty way to discard stand ibutes of new-stylen!# 9es.o Empty< ;d(x 'if5dir(x) and has(tD, x.^HLJFals>*(x831ism 0 = A*boisdataD (dEqual(xO(A, ,[('md', A.__dict__[6])]l jdj1dd'jR;B(AE&BXl+ qklB?f*(=In(('f', B.f),FC/B)<< RNWb = BbbI9YC VirtualAttr# bkM(typeO_?__(cls,  (!if == 'eggs'#'scrambled'# su().|1Ax@ s.DynamicClassAttribute  def eggs(self):  return 'spam'-.assertIn(('B', 'scrambled'), inspect.getmembers(A))Dj?Q())) BVtest_^_with_buggy_dirclass M(typeM_4k__(clsA['__H __b__name missing']4)q C(meta +=MZEpass/attrs = [a[0] for a inF&C)e No'!, R ) _global_ref = object() TestGetClosureVars(unit].0Cas0)resolutionl# Basic , of the 4 different : mechanism ff(nonloc 8!/g(|Vprint"(, N', , unboundEgH_argA]!va%{"`ref": 9}G-,6ref3builtin_41": (M${"( exEed =ap#,  dfgEqual(4cu0(f(BD)), nerator_8 4Uq3YyieldIkomethodhUCJ}  + &nd_ref)  return g _arg = object()nonlocal_vars = {"`ref": 9}/Hglob-_,3vbuiltinaprint": (unbound_name](expected = ins .ClosureVars(#,  $, 9self.assertEqual(Bgetcup(C().f(FD)), !) def test_(\!):"# More complex1Ts of 5 resolution4Z VfSW$4f).`s4Wmake_adder(xS[add(y;oUx + y:addhcurry(func, arg1TP`lambda!02: -(,22feless_than(a, bOVa < b# The infamous Ybinator.\KY(leR,g(v#e(x: f(f)(x)a)Y.g_ref =A;g(gcheck_y_comA `  *unc), {'f': }jginc = 1zadd_two 2 qgreater_five = 7, 5m ifx': 1}i8 <2< %),  {'p': 5, '5': u-71y: OO)(3) 3l.Y(*t l_empty-foo(): pass.D{}, Gset( : True), oG7foo>Lrror{class TRaises(TypeEA, ^', C@surevars, liSst) *self.assertRaises(TypeError, inspect.getclosurevars, {}) Bdef _private_globals(S!): ecode = """.f(): print(path)"""*uns = {}Pexec(?F, nsreturn ns["f"]test_builtins_fallbackf50 = .jns.pop("_S_", None% ex$Eed =0C-pVars({}0A, {"!":"&"}JoEqual(T(f), v as_dict'[](:1bath":1Iomodule:'os0os.: class TestGetcallargsFunctions(unit."fCase):%crCallArg, func, O_params_string, locs=1 = g 0or F=r1 = eval('(%s)' %jep?2?(S/, T f gr1, r2c:PExcepmf;:56tryrF uEe [ as e\x*;els"$ffail('IPnot r>&d'N  HJ) Is(type(ex1), &2) ,3str. -pdel ex12@make#ab, signatur fCreate a that returns its locals()""" code = "lambda %s:'%return eval(1% signature) 'def test_plain(self):i@f = .makeCallable('a, b=1')($assertEqual+Args(f, '2)?, 3,/a=W_b=3, 02# expand *iter / **mapping_*(2,)O*[2],_(2, 3[?, 3^*{"a":2}m*602, 4Ob":3j1-, UserList / ODictcollections.;FO([2]iB~E*FO(a=2C[F/b=7/b=HaHYO@varaQO, *chUo, 3, 4/?3,4O[3,4~4 v/kwyuEO, c=O;ai50c=4?, "C2@9v3, "c":4c=4)') 6self.assertEqualCallArgs(f, '2, c=4, **collections.UserDict(b=3)') K ?b=2H1a=3iM Ldef test_varkw_only(^!):## issue11256@f = )P.makeable('**c'(?a=1+_, b=20c**{"a": 1, "b": 2}?1a=1eA+Mkeyword*, c, d&?a=30a?c=404.PExcep=V) S ,dN dcmmultiple_features&a @, *fgDO3, 7/?x=81, *[(4,[5,6]), 7]B0x=8?93, B_, y=9GD82, G]D >aList(','[}){"y":9, "z":1022, O[3, PfHy=9, z=10 x9  self.assertE qualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]') self.assertEB?93, B, y=9, z=10MJM]J&collections.UserList(','[ ), q=0, **{"y":9, "z":10}2gO[3,  Q?DicA)') def test_errors(!):%Pf0 = P.makeIgable('/f1#Ha, b'2''=1)# f0 takes no argumentsPExceph(f0, 'K+ xx- *1,/C# f1exactly 281, H*+7a=2PX 7b=3-C# f2at least 12* ~for f in f1, f2q/t/at most|6 4421, +a?96k4, c=5r# XXX: success of this one depend dict orderv"##_, a=1~ f got an unexpected keywordtW c02336i:4, wn**{u"\u03c0hb9": 4 C"# Gmultiple values M(1l '1, **{"a":2W}') self.assertEqualException(f, '1, 2, b=36 # XXX: Python inconsistency^# - for funcUs and bound methods: unexpected keyword 'c'H+un<multiple valuesmEaEc=3, a=2# issue11256:Qf3 = OmakeCallable('**c<!\3].1/f40, a,0d. 5 #20816: getc$rgs() fails to iterate over non-exEtIkwonlydefault? raises a wrong TypeError6def f5(*, a): passBwithRLeRegex(I,/) 'missing 1 requir-&')0=0ins. Uf5) n757< 6(;, cU "'a', 'b'K'c'"U(6)bpo-33197Z V[variadicparameters cannot`s' have ?%Pd("foo", kind= .VAR_KEYWORD y6=42v)9" 5 is not a6id &T("bar$5,0;'name must be a str,?int31234) class TestGgM](F"):]`setUp(VFoo(objecti x;.cls = Foo1Binst(As 6(, signaturej '"'"&in)i mkLupers, self).makeCallable self.cls.method = mk(', ' + signature)3preturn $S.inst; class TestGetcjrgsUnboundM_+s(1): _udef mak(e,:'\superO m,*).R  assertEqual@CArgs`func, _params_string, locs=None)9z*!f._getAP( /))Exception_{@#>/, )  '' not in  = dict( por {}, @=E _g,f+) zattrStatic(unittest.w0Casia_basiching(objectwBx = (Gt1@ = T(7E(inspect.get"_s@r, 'x'),E/.xF)!, LAwith.Raises(AttributeError 'y' `y', 3)inherited+ROther Bpass3 soging = 9I  Pance_"2Q__init__O;, x'x>3A@Adel .m%2t0property class Thing(object): @propertydef x(self/:$raise AttributeError("I'm pretending not to exist")]t@ = T(k.assertEqual(inspect.getattr_static(@r, 'x'),EA.x) _test_descriptor_+s_mfclass 6)___get__(*_?l$}( =1x:%e5 bU (K(Z  Virtual'@types.DynamicC'Mm/aeturn )_x8_ >__dict__['x']]inherited_ X+Ta Other( )Bpass3U _slotsy = 'bar'_NQ__ = O UP__ini F'foo]:eqG@, 'yJ/EAdel !.Y Ameta0(} U OH o , A= Fh0, '22n_ sub(r *$;subF3ic(OtherThing, 'attr'), 'foo') class OtherfThing( %):+2Epass# this test is odd, but it was added asPexposE bugA self.assertEqual(inspect.getr_static@, 'x31def_no_dict`slots(ap1(s, None)/No oq, 'loweQ_instance_member# returns descriptorwith open(__file__)jhandle<p, 'nameyRtype( ). inherited_ gobject_U__ = ['x']V__init__9 2x ={i(  ould be nice ifworked...# we get the Pead o:e UibuteB1(.,.xC . p$geo,{, owner?h% 3kOFoo(d' =0(J`foo = 9# for a non data<~zkRfoo._O_['d'] = 1pfoo, 'd51& 1s a-s!sh_#=@.__s = lambda s, i, v:2 F") FQ_meta__fn( de` ? , E= J "^`,U ~ a~_as_propertyY class Base(object): foo = 3 class Something(Base4executed = False<X@propertyadef __\{__(selfT;.]:Tru\%rreturn instance =)[assertEqual(inspect.getattr_staticG, 'foo'), 3E.,q i r4test_mro_as_Y ?V Meta(typ Yi7&,)lq Ta, metaK= DFpassrN)()P9H F Odict 0 = s9W.call= P Foo([ aD Ah f &{}@foo.4.ifoo, 'ab rcustom_ _ = CY|1geth, key, default=Nonzkpsuper()(SF _$S__ = WB  fkTB )*o__init spam = 42@C, "spam"), 4C2) self.assertFalse(Thing.executed) *def test_module(6!):Hsentinel = object(aIsNot(inspect.getattr_static(sys, "version", T%),gk $ etaclass_with_mdict_as_property:P MetaW(type@; %!__^_T69]y = TrueE%preturn J(spam=42%, = 1 = .L(G CFpass7V :Raises(AttributeErrorB|0, ""6 TestGetGeneratorState(unit.0Casf\setUpnumber_gL(Bfor $ in range(5$USyield*v.[# = n` o RY0.<Y_createdQEqual .4), xGEN_CREATEDc~suspendeBnextY "~SUSPENDclosed_after_exhaustion~i~ ))?LOS immediate_excepyoRuntimwy.throw(0 3|runningl`# As m-oned on issue #10220, checking the RUNNING U onlyp# makes( se@ide 41 it3The followf*yswis by us#QIWure'sIreference to K and[K`helper5hodK._+q% _generatorstate(), inspect.GEN_RUNNING) yield numberself.assertEqual(_generatorstk54 = running_checkN(2# R$ up to the first Bnext`E_afterEcdef test_easy_debuggingr!):#O# repr() and st Uof a  ) should containEnameN Ps = 'CREATED  sSUSPENDCLOSED'.splitG@for O1 ins}= getattr(1,,H+ 0In(T,D)-,\5get)llocals`+each(lst, a=Noneb=(1, 2, 3v:lst6if v == 3ac = 125 v >[]Ik.N%),`y`{'a': , 'lst': u}vONX, 'v': 1e 'b': 23@, 'c2:tryTexcept StopIt:ion8Opass+B {})t>o_emptyA[_one(;% 1Rone =h/:,K(aG(qual(inspect.getgeneratorlocals(one), {}) def test_+_error(self):-1.assertRaises(TypeE+, inspectxO, 1)D/lambda x: TrueQ0?setF0(2,3)) class TestGetCoroutineState(unitj.fCase):\setUpk@types.cH@unumber_(Bfor $ in range(5$(Syield*aQasync`Sawait8D)?5 = (|larDown >h.close8ss^0hreturn~0Z st_createdQEqual .)CORO_CREATEDdsuspendfp.send(N [~SUSPEND]d_after_exhaustioQwhileyB:try`&except StopIt>ionLRbreak,5[OCLOS immediate_Gith bRuntimithrow(0,easy_debugging# repr() and st Fof a & should contain theEname Xs = ' rRUNNING '.split(0ame[ = getattr(t , ,F|*0In( ,D)-,z/Zd 0gen? & 0qfunc(a=#: b = 'spam' await gencoro  = func() self.assertEqual(inspect.get2utinelocals(%),;s {'a': None, '$':}uI`.send(-Wc, 'b':>}) class MySignature !):# Top-level to make it picklable;&used in test_sW_object_/e+FpassParameterKETestOP(unit.CCase@staticmethodEdef (nc, **kw1*dsig = i-K,return (tuple((p_.name(... if +default isempty else" Q@anno+onT]3strkind).lower()F| 2forAsig.&ns.values(){2_Z; T"))Nx @(,TSRPNb.L dS S '()'*(po, pk, pod=42 d=100, *args, koD  @po =V['po'].replace( =P.POSITIONAL_ONLYBdCdDkC5k']h/pkf'kd$H&k(ko"w3Jk&']%S(4'iWwith RaisesRegex(VError, 'wrongH;{ order'u!/, u8parameter order'): S((po, args, pk, ko, kw5)) +,with self.assertRaisesRegex(ValueError, 'wrong parameter orua , {uXo}32 =.replace(name=';/')duplicateRk2follows default_umentydgCjkkkNkgTrue(repr(sig).starts(' {42:'ham'}: pass foo_partial = functools.0(fo#=1sig = inspect.+K.qfor verRange(.HIGHEST_PROTOCOL + 1iP:ssubTest< _ver=ver, subclass=False?C3sig4Cd = {SloadsL`.dumps,?lREqual,Y # that basic-ing work{H8!myd = MyPQz', kind=!.POSITIONAL_ONLYPs = collections.Ol`edDictSs, a=F%My%()s:0s.vEs(),z\return_annota]=sig.isinstance(mysig, 8  P['z']HhS( 7ver (mysig, sig_pickled) self.assertTrue(isinstance(sig_8, MySignature)F%.parameters['z'], 4MyP>1)) :def test_s_immutability(!):+J/'(aEpass&sig = inspect.Z(ix4Pwith a=Raises(AttributeErrorhsig.foo = 'bar'M?TypHKa'] = NoneSon_noarg $QEqualE , ((), ...on_wargsBs(a, b:'foo') -> 123* @ a((('a' "positional_or_keyword") 4('bE/, GH ?123: _kwonl*, a:floatE1strC?intCU|"7_<[str, <1 O int2 complex_s`=10, *-:`, spam z', ham=123, **k:\U?...X F v, "var_3OCV  Pham',k3intE/")o  @out_(f): # NOQA=D N pass  class A: @imethoddef test_!(*args): # NOQA1OYpass @statica "b f1 = functools.partialq,((Y), 1)/f2@__only>3>A4A!kw&1)fself.assertEqual(signature< @(((')c', ...'var_positional'),))Fq .AB ('lkeyword')oA.f1),v@EOA.f2xd3xd4x0 @cpythonZP@unit_ .skipIf(MISSING_C_DOCSTRINGS.$"S information for builtins requires docstrings"tD_on_9)import _Fcapi:Hunbound_5o>"""Use this to 3 3Ps (th that should have a A)"""6P = inspect."(o)BTrue(isinstance(4,G\ F)FlistA: ameters.values())[0].name, ''ureturn [callable(US@or n$l E gdon't ex= f signature = inspect.signaW(o)  self.assertTrue(isinstance(4,GSG)F5if ..parameters:kvoNotEqual(listm?.values())[0].name, 'B'~freturn w = test_callable(_capi.docstring_with_3defaultsr`def p(<): {[##].Aqp('s'), 'avocado,b,b'bytes+ d+F3.14Ri'5% n%ONone' t'I' f'OFalsO Plocal,3P !syCsys.maxsizXNotIn('exp',/); /gobject# normal methoda# (PyMDescr_Type, "' _dfiptor"kunbound_)(_pickle.Pfr.dump2Kd = "Q(io.S7IO(]dIlstatic 7str.maketran  %X'abc''e_classd dict.fromkeyd'{}#`wrapper arEP slotW +atype._ &__ int.__add)6(3)#_79 support for '%-''k7min% # This doesn't work now.!`(We dohave a valid3"w" in 3.cF hRaisesRegex(VError, "noQZund")26WorksNow R5ype H"+# Regression'issue #20786+R __delitem .property.20ete1` 5_testcapi.docstr"ing_with_signature_but_no_doc) @cpython_onlyunittest.skipIf(MISSING_C_DOCSTRINGS,+A $"Sj information for builtins requires docstrings")O@def yon_decorated_Cq(self):4import _<Ecapiffunc =.s 'defaultsZ0or(Ow!@tools.wraps$#Dper(*args, **kw ) -> int1preturn ^ 5 ^)a6D; = *M.assertEqual(inspect.62n0ed_)m,]_likeU pass t rfollow_Fd=False)B;r\ un -RaisesRegex(ValueError E'no h found'6k&no z3str1non  3Typ 'is not a callable objectV/42EfromQ_V c(a,b,  kwr=True, 7req Qclassw *# Has to be, and have correctKM# __code__, __annot>s0nam) A`F__kw, attributen__init__+, *["__r! ='. ... 5 <= func.__default[s__  self.__kwdefaults__ = func:)0 "def __call__(e, *args, **kw )):1preturn /.Z(3d@sig_# = inspect.Signature.from|Pable('):Olike>+G)assertEqual(-$, ysb> )k)# If object is not a duck type oftion, then#F will try to geB for its ''Cemethod#fl"del fl.__bU(fl),-? @((('gc', ..."var_posi?al"A B ('Ckeyword")A G...)# Test with cython- builtins_orig_isdesc"is[eriptorp1K(obj]if hasattrC, '_t[mock'-GETruecRunittest.`.patch('3', 2! # Make sure that our ~` setupyworking7doFalse((.\= = Dts$F!)2_1gda_class# We only wantV>~s#V6es.;E(a,b% kwe= ", ?req=FpassRdVne__initgmarker( Vh__name# TY__cod% %`annota1 t  3%R9ults__ = func.__kwdefaults__ 0self.assertEqual(str(inspect.signature(funclike)), '(marker)') Hdef test_0_on_method(a!):(sclass TestD__init__(*args5!EpassJ6!m1da, arg12=1) -> ine3D2t`__call?, a du-(u().m1),4 @((('c', ..."positional_or_keyword"H ! H_2', 1F G Cint)2U sFvar_?"),C P @Wwith 0RaisesRegex(ValueError, 'invalid J 1'rLO" wrapped_bound# Issue 24298 )@_`tools.s|2m1do, **kw&   x?m1d1rh  1on_-'w@4kbqfoo(clsTA1, * ] /xAP! =oe().foo?ethe>_only") ew  ('arg2', 1, ..., "keyword_only")), a...)) !def test_signature_on_staticmethod(self):.Rclass Test@5.dfoo(cls, *, argP"Bpass|! =ge().fooR.assertEqual.(: ((('cls'8=positional_or_K"G   G9 rSpartifrom functools import -.Parameter = inspect.'{(b} {a ~(q)), (()LSRWwith IRaisesRegex(ValueError, "has incorrect{uments"?, 1}i)a=fAa, bKc, ds* k a#bE1cE  O ('d<  0 I__, c=2Y :2Uonly"),  ('d', ..."keyword_only")), 8e...)) !self.assertEqual(signature(partial(test, b=1, c=2c Z((('apositional_or_" ('b', 1 ('c', 2:"Yd0\?a=1k&#IEb<%d6@def (a, *args, b, **kw %):Opass%:rgsFvar_Q%ij *h1~35 ,W=True+  ((('args', ..."var_positional"), -:('b>keyword_only</kwE/")} e...)) self.assertEqual(signature(partial(test, 1, 2, 3, =1, b=0o -60i+ @C_or_ LA_g1def(a, b, c:int) -> 42:Gpass(Aig =95.____ = inspect.-d l)@coint, "ET /42S! ?, 2,!psA, 1)Pjfoo(a)?return aTt_foo = Ofoo, a=10)520)1Q |O', 2= )) # che)ck that we don't have any side-effects in signature(), # and the partial object is still functioning6self.assertEqual(_foo(), 20) &@def a, b, c):}sreturn J$ =((foo, 1, b=20)3j U ((('b', 30, ..., "keyword_only"; c ('c'7<= U...)) W0c=1"(1?10)do, *, dj 5, dqmtd=20, cp`10, d=v: ua:@posilcal_or_~; d0%ba = inspect.Z.bind(a=200/11H *ba.args, * kw A), (B 11c_=|3_ \c=13) # (aP*S'13(H, 13t7/12d&?w#/b=y`u+L, 12 mf:(0t 0, d'$ Epass8?sig6foo,params =. eters.copy('R['a']1ams .replace(kind=Parameter.POSITIONAL_ONLY) params['b'] = .replace(kind=P'eter.POSIJfoo.__signature__ = inspect.S(b.values()7sig1GG(foo%(elf.assertEqual(str(sig), '(a, b, /, c, d, **kwargs)') sAnppartialve, 1)),:0((('b', ...'positional_only'? _ ('c?r_keywordEdE1+ J'va O...)d&?, 2g(?, 3+O, c=3x+u "<'i0Udef test3on_pmethod(%):from functools import3<class SpamAx(YEpassn2hamhb(@Pwith RaisesRegex(V8Error, "has incorrect arguments" inspect.signature(Spam.ham) `class :def test(it, a, *, c) -> 'spam'-1IpassBham = partialmethod(RW, c=1self.assertEqual(,_t((('it', ... 'positional_or_keyword')F_ ('aE1Tc', 1z_only') \)!()|x: 'anno', x)r gqog N*rM t__on_fake_G~8foo(a): Jfoo.;# =8L tr(inspect.(foo)), '(a)'w decoratedimport functoolsI70or(!7@5b.wraps$#Dper(*args, **kw >intBareturn 5 ^)a:Foo\@ F1barUb7.Foo.barb #""H E$b9  4...54&/()( %, follow_wrapped=False)?, ((('args', ..."var_positional")Ao ('kwCkeyword")A ...)) # functools.wraps will copy __annota?s__# from "R`" to "Rper", hence noEgreturn| 5# Test that we handle method ms correctly8def decorator(%):@$ #Dc (*yB, **) -> intTXd\(42, 9 bsig = inspect.signaturenew_params = tuple(sig.eters.values())[1:]f5.__bP__ = Areplace(I=k)GNclass Foo @ FU__call__(self, a, bJFpassf+.assertEqual<3DFoo.X  E_or_L bE /))/(), Rpartway down thee stackEQd_foo ( -4.__MB 4NJGtest1on_U* C@f__init4|q CJ4G :kM(typeqkcls, a" OQ(meta ;=CM4Vinit__(self, b):+ Upass self.assertEqual(signature(C),, I ((('a', ... "positional_or_keyword"),G @&))class CM(type):def __new__(mcls, name, bases, dct, *, foo=1;return super().J )zQ(meta ;=CM^ainit__E;, b#~<b~? M a !('I1?dctG1tfoo', 1_only") x}rcall__(\@m, bWtL&(n))(, <=_bar=2MC00m1/bsF1dd self.assertEqual(self.signature(C), ((('b', ... "positional_or_keyword"),G @5)) hclass CM(type):def __init__(cls, name, bases, dct, *;r=2;?return super().J E)uQ(meta ;=CMY @;, b#|Fpass(O.assyM3 z} !(';I1?dctG1tbar', 2RD_only") H@unittest.skipIf(MISSING_C_DOCSTRINGS$"S informa for builtins requires docstrings"5y_EA_on_;_withoutj'q# Test )3es + user-defined  or __new__9A C: hgtr(inspectr), '()'>POD(C)S#%D)SL-`( U O RaisesRegex(ValueError, "callable.*is not,wported"!N;Wf, NoneVc$D)}V%  gs_pickle.Pr) '(file, protocol=, fix_im`s=True0Z,P(h 'EmptyTrait6P2("?, Pb$P,=True)')  self.assertEqual(str(inspect.signature(P2)), 1'(file, protocol=None, fix_imports=True)') Eclass P3\:_def __init__(z, spam)&*Epass;*q3)), '(SMetaP(typepcall__(cls, foo, bar) 4(P2, meta=j <"4Utest_@_on_able_objectsbJ FoooM_=a6o_(Foo(Y ((('a', ... "positional_or_keyword"), @)|JSpamWwith URaisesRegex(TypeError, "is not a Z Z"V(@Bar(, E`J`gWrappedc"B.__w,__ = lambda a: GM O;%"# fr loop g DValuh'e'Xdf J  (8 a=10: a^/105e float: I_Falsefoo) == 42)76!6"1== `sToAll'w !B def bar(a, *, b:int) -> float: pass self.assertTrue(inspect.signature(foo) == _bar))JOFalsK!KeEqual(eOhash?), %) IOdef $/in" #m "?Not%Y@?=42j*c# GQspam(!?, aH)IKHa def foo(*, a, b, c): pass pdef bar"c"a"self.assertTrue(inspect.signature(foo) == Ubar))lJOFalsK!KeEqual(eOhash?), %) If<!=1>/=1@Ppos, E )J  H  ?NotM$args, a=42R`, **kwL:int+<B< ( r spA0Utest_*_{Pable(%):l&S SXPParameter 0foo|>(Ccmanual-4S(pes=[P('a', P.POSITIONAL_OR_KEYWORD)]2*PjYyk =  +Y.replace(return _annotation='spam'))) def bar(a) -> 1: passself.assertNotEqual(hash(foo_sig), inspect.signature(barhfoo(a={})fWwith k RaisesRegex(TypeError, 'unmable type'):( 42: Upass  sig = inspect.signature(@)&sig.replace(return_annotation=None2elf.assertIs(: 2+, 3+e_emptyj8o/42h_Equal4 ,n)1def_ _on_mangled_parameters(self)class SpamP1foo/, __p1:1=2, * W2:2=3F2& [@Ham(_ .**&Ae.foo),3b @((('c', ...P"posiial_or_keyword"H P ('_', 2, 1, I,Q2', 3L"_only") C...)&&DY1HamXfF from_callable_python_obj5MyS 1): ndaW class TestPVObject(unittest.aCase):n@def _signatureSp_kinds(.P = inspect.fL- True(P.POSITIONAL_ONLY < R_KEYWORD < \HLfP.VAR_LG9X$%) LN>strF), '`T' + in repYk olpl('foo', default=10,3 = 1p.name, z( O, 10( Is(p.annotation, p.empty-},uPwith M RaisesRegex(ValueError, "v '123' is "B> "not a valid ."9 v 9=+:' '21', qM 4TypY' must be a strONone8O'is M*$M9^/.aD1 'cT have>?ues'W?=42$ >  kind=inspect.Parameter.VAR_POSITIONAL) 7Mp = /('a', default=42,/7 uq_OR_KEYWORD)L%with self.assertRaisesRegex(ValueError, 'cannot have v!Es'):Op.replace(True(repr(p).starts5(' "O "is not a valid Parameter"m Wt(q__ONLYv >def test_signature_p_positional_only([o 3Typn pmust be a strf^(X .+@cpython implicitE'e arguments pad as '?' or keywordY,HL-O'.0'L= = (^U`,x<H%, #0'\ mutabilit6p_'spamb <$(Ap.foo = 'bar'K#z = 123 +TTestSMBind(unitd.CCase@staticmethodUcall(func, *args, **kw 7sig = inspect.signature(func)  ba = sig.bind(*args, **kw 'preturn <P(*ba.(4ba.+Sdef test_signap_Y_empty(self):)-(m542 +:.assertEqualK`.call(oV), 42Wwith 3'RaisesRegex(TypeError, 'too many positional arguments'Pr?, 1p], spam=10y<S "got an unexpected keyword 'jF'"):F &2=1)% 1varO+ polgk ((), {})/4 o, ((1,9B, 2)< wfoo='bar'C}q'foo': *, NP&}s_': 102 D 4< gPjust_mwa, b, cte`, 1, 2, 3  WS?, 4zL "missing a require$"Aa $i/W  a -N( >Z?10)=1, b=2, c=3 b, c  self.assertEqual( call(test, a=10, c=13), ( 2, 13)) 2C =<Ab=10< , |<y@def _signature_bind_varargs_order!):15 (*$preturn  2  b1, 2, J )m &_a@a, b?3, &,#, `, 4, 5( C)?0b=12Co, 3, (CQ1, b=AAHwithRaisesRegex(TypeError,/?"multiple values forument 'c'"t?c=4. pjust_kw5)"**! v_), {} foo='bar', spam='ham')J{'foo': 5'68} <; )", Q&@/{}7=(8?3, G 0b=2~?1, qa qWs;c=4am='ham'),  (1, 2, 4, {'foo': 'bar', 'spamham'})) Aself.assertEqual(call(test, RAfoo=N%),>Frc=5, a=4, b=3m 4, 3, 5, {a@def _signature_bind_kwonly!):*.w(*, foo`return1Qwith #4RaisesRegex(TypeError W'too many positional arguments'uu1), 1) 2a, {=1, barxL"missing a required" 1foo ;W bar=2), F9d=@}X %9e "got an unexpected keyworBB FM , ,7=10-  c,?, 2Q= /F9#=2'>DP{, **binU, bin[L@[yD E (1 , 2, {'spam': 'ham'})) self.assertEqual(call(test, 9=7, foo=1, bar=2),DK/(1v Qwith j{RaisesRegex(TypeErrorak "missing a required argument: 'foo'"):y/+P, bin0/10bin': 1,  10~@def _signature_bind_s1 (a, *args, b, z=100, **kw0DApassn sig = inspect.w1ba = sig.(10, 20, b=30, c=40,~bs=50, s6=60># we won't have 'z'0 in the bouns object, as=edidn't # a it to>'' tuple(ba.I.items() `('a', 0 ('J', (20,)), ('b', 3 2 (''@c': +J : . 0: 64 2ba.L"`{'b': 'm.(3s, 1)) -m positional_onlyPaParameterRV(a_po, bbc_po=3}R42, *3|return EC=zPnew_ps = collecs.OrderedDict(a"+scfor name ('@', ''~[9L] = .replace(kind=P.POSITIONAL_ONLY~96=!ps.value '.__7sigT[ &A4, 5/=6 .E6, {* $>_03, d]a b"=45o m "but wass a keyword"):  self.call(test, 1, 2, foo=4, bar=5, c_po=10) 4q with ;.assertRaisesRegex(TypeError, "parameter is positional only"):PXO |4{\a0, b2}@def $_signature_bind_ _P_arg(  # Issue #17071: one of the spnamed "?r1(a,m7, b[4Epass/sig = inspect.)&ba = sig.(3.Equal(ba.args, ,- L>o=2, b=S cpvararg_$ a3$* "return a, f9, '{%Pgot an unexed keywordpument '' F2a=0#=1~e`, **kwI"fvP=1), ((), {W: 1})>  Yi sz(':}@cpython_IS ;implicit 9611: get  should workt comprehensiony|make_set( {z * z for z in range(5)}.0set__code = P!.___.co_consts[1]6func = types.Funci(X4, {Bsiterator6Dter(%Xz$, K40F4, 9, 16q class TestBoundArgP(unitU.CCase?S:;_unhashablefoo(a): "!Cfoo)` Z''C3(baYew?ity: self.assertTrue(ba == ba) self.assertFals#!#EEqualsToAll()P .ba2 = inspect.signature(foo).bind(1\?ba2# 72) u3u R D3vD#ba3.arguments['a'] = 1Be 3def bar(b): passa?ba4?bari k44foo(*, a, ?sigr1 = sigwa=1, b=C!b=2, a=7 1E!1 9ZUtest_u_bound__pickle(L%):9, *, c:1={}, **kw) -> {42:'ham'}! 20, 30, z={}for ver in range(.HIGHEST_PROTOCOL + 1%Pwith .subTest<_ver=ver/3#ba Cd = jSloads;.dumps(ba,>=o:+VZ OrepryaRegex(ba), r''apply_defaults  X[*argsh&207;ba.P3Plist(?.items()),([('a', 20), ('b', 1 0', 0 ('c', {}"kw ]Wm # Make sure that we preservve order# i.e. 'c' should be *before* 'kw'.  10d *arguments.items()), [('a', 10), ('b', 2 args', (30,)ac', {} kw 'd':1})]) R+# Make sure that BoundArguments produced by bind_partial()C arBpported.def foo(a, b): pass sig = inspect.signature(fooZba = sig.z(20".apply_defaultsself.assertEqual(}Nlist(ba.a?.ito+207Test no vY// [Pa no-ing still acquireDper e='spam'3p class S| PrivateHelpers(unittest.%aCase):_`_get_b80am(z.kggetter;D F@('($`)'), ' '4_, obj9gcls, /;Ccls'A  _strip_non_python_syntaxv, inputVclean , 6 eter, last_positional_onlyKcomputed_I\o( `'w: = . D B  .8 "($modulepath, mode, *, dir_fd=None, " +:"effective_ids=False,\n follow_symlinks=True)"'$"(|2t0, c 0) self._strip_non_python_syntax('. "($module, word, salt, /)",(' $032%x, y=None, z & B 7 l/"( $' \n) ` z = W/ m @  /#:L) class TestSignatureDefinitions(unittest."aCase):Sp# This ( case provides a home for checking that particular APIsGdhave s{s availablBintrospec#@cAonlyE@ skipIf(MISSING_C_DOCSTRINGS;" informajbuiltins requires docUQngs")z1def_,__(3p7cs all :A calqs in CP NtG\A few  can't yet hand`so we "g thoseMsince they willW to wait until PEP 457 adds*dG  support to0!in G6S.Pother!so~been convertedUvarious 3Hreasons, Galsothe time being, but deH%!es@failPorderindicate when it nee8o bQupdated.W&nor = set(BQTheseLiRgroup%$h_ = {"range", "slic 0dir{getattrpDP"next+1ite3ovars"}!|=s|%V or a0 ch?aacceptIsemantic_;Ooundneeds_semantic_update # These need *args support in Argument Clinic6.Qs_var1= {"breakpoint", "min ax!pr>{"__build_class__"},no_signature |=z&simply weren't covered the initial AC conversionD@for tin callables Bnot_7ted_yet 1ope@__im6 C] types are expected to provid@trosion infoI9V_with8s = set()&# Check _4s wom ber+nHSvars(sQ;name, objpsorted(ns.items()):~eif notgK(obj"&vcontinu,A havCbeen4lAC yet|isinstancez , Fp) and (!insNP# Not0at this also skip lIp exceptmXA.addb##if8in / O^; self.subTest=j,assertIsNotNone(in.]g)g_ that!doulaim a Tis ensurestest will start failing as moreFgKadded, so2aff can be movWt%scope of2J`regrese Fabov3. (-nv.__texta__) o NTimesUnwrapp`def __40__(7, nV.n = B@_nex @propertyWl#edZW"if}bn <= 0traise EH#("o many t"iP0is W f.n - 1VbreturnZL1P(unit.bCase):!_us_0#func(a, b|Qa + bRP@r = 7 tools.lru_cache(maxsize=20)(func) self.assertIs(inspect.unwrap(bper), 56def test_%_several(J!):#\'6W(a, breturn a + b1m! =mfor __ in range(10M@f`tools.CsCsKper(AEpass04NotR2.__C4d__= 4HOstop>1? 12 F2F G Hj._here = 1_8oped = q,,[] =(lambda f: hasattr(f, "y6")) 12) v(_cycle=): 1"Wwith RaisesRegex(ValueError, 'ak loop' 1h1(2 82^H_cE unhashab( BENonevclass C __hY__ = -dL( Is9 T C(0recursion_limit0objaTimesUpeys.get>=G) + @Abobj) 7TestMain(unit.CCaseonly_sourcPmodulnimportlib. !_m$('^'rc, out, err = _python_ok('-m', 'z' mplines =q.decode().split(# ignore the final new&b%`Equal(us[:-1],[getsource(module).splitlines())  self.assertEqual(err, b'') $ def test_custom_getattr(8!):#J'Gfoo(Epass$foo.__signature__ = 42Pwith WRaises(TypeError[inspect.PC(fooP@unit.skipIf(ThreadPoolExecutor is None,!'t)s required to0 __0namfor source files'Pv+% -rc, out, err = ~_python_ok('-m', '''concurrent.fub.s:B  =.decode(&# ignore thpnal new@#Hos[:-1]C.get+ j rbuiltinsmodule = importlib. !_m$('G5_failure$d 'syPG =+ ;, ["Can't get info  Cs."];odetail53args = supip.optim_ _from_interpreter_flags(, *G/, 3#oE-koutput'# Just a quick sanity check on0A22In(2.__Z]6put/w_/ocached1 F class TestReload(-.bCase):'psrc_bef$= textwrap.dedent("""\ Y"0priBBla"3"""L@afteKmOh no!NxbI2Xs, path,``ed_src!:Popen(S) as src $s@src. ^True)E 0 ) def test_getsource_reload(self):%)# see issue 1218234with _ready_to_import('Ip_bug', O .src_before) as (name, pathjnmodule = LBlib. !_m:)3aassertInspectEqual(^", 7 2Copen$1'w'6src[src.writeZafterS% wSmain(run_unit(TestDecorators, RetrievingSBCodetOneline)BuggyCases,QInterpreterStack= Cl@sAndFunctionpPredicatGGetcallargs2kMethod tUnbound'`Getatt2ticqGetGeneZStateRNoEOL*SignatureObjectBBindPParam( "BArgumentYPrivateHelpk 9%bDefiniF "GetClosureVabUnwrapBMain R >oroutine\) if __R__ == "__]2__"V(a# INI as many tricky partspossible # Most of them could not be used A 3.2 4This will'0par)rthe following op$9# delimiters = {'='}0com_prefixe#aO_no_valu: True [DEFAULT] go = %(iolate)s [strange] :X that are indented # and end3Shash s other = 9do continu;@ in@C st2hav9% #Ma mixeds|4 a[corru;Bis actually x3ere holds allse weird new}+1but0for- "+# n(Da"an = # emptring yet %p# None!8P[yeahG@ canW^ ed@well !esmean = anythfthey subseT`= Falsif you want"use XML lets some Unicody片仮名] even ifl`like t5= seriously yes,applies t( "g!" E to"be people with configurations broken as this? beware, is going to be a continu> of the value for key "K too" even if it has a = character dQstillK `your editor probably highlightsV wrong but that's life # le se#is sof reno error # when gettall items0sec/: interpolate = anyth3wrdo [nojs here] #Bere'd `go` in DEFAULT [tricky aAion] vd#islets = %(go)0[moPgo shoppiH;Timport unittest from weakref WeakSet 0strN*Bcoll?s.QUserS#yDustr9$gc extlib class Foo:DpassRefCycledef __init__(self) .c,0 = YCTest(.bCase):[\setUpX`# need"keep referencesAthem[0= [1(c)fc('a', 'b4c') .8/2 9x4yz91ab_<;K'ab'i_abcde3 '<bisdisjoin)BTrue's.1b,2)A&UE) def test_and(self): @i = .s.intersection'.items2)-)assertEqual&rs & set 3?, i7ofrozen=uPdef tdifferenceg % for c in0let  0'i,8d and c notLGXs, WeakS,)(utype(i)7+Raises(TypeError,&s., [[]]) T?subM( - #/- symmetric_/ :()Wd) ^ GG(1lenJ) + 2(f2.pop(gc.collectWt% 1xorK./z^#^ ub]_supe*2Tru.ab_weakset <Tabcde~?,B0> EFals?defA#A Bt('a').issub\'abc'2$4pADi#3g?cbsg3%5 h l self.a ssertTrue(self.ab_weakset < 4cde3) >EFals?-B?def@*=|WeakSet() < !) def test_gt!):>Ob?#|/ >c.# Create a nest of cycles to exercise overall ref count checkH% =u Foo() for i in range(1000):@elem!s.E = sb`sub = &'et[%] subclass_with_custom_hashBug #1257731m=3 H(pMl_O,__Q return int(id%r & 0x7f'Fs=H(0f=svf.add(s!vIn(s, ff.remove0 Af.discarVh<>ini>mj@s.__._.itemPEqual$C2cDPt2qba2Raises(TypeError, , s, 2);8;1);nconstructor_identity3sBk - 2NotK), id(t)o1,sM]clear"s. (,-/[]1lenim.s), 0-opQ0dup7f .c!?dup& \Sa0 7elfx = ustr('Q'`sxFIn(x|S Ns, dup) self.assertRaises(TypeError, self.s.add, []) fk(Foo()PTrue(len(/k) == 1+F#;objI def test_removem!):x = ustr('a']#s.3xvtNotIn(x$3:Key2Y/, Z6i7l|discardHa, q,QBaa$s.>q>7> _Raises(TypeErrork?f, [[]]Esymmetric_Odef test_isubbi0s -t ;!; ?bo=(5aL) ^ 22%KG2Tru.s != setKXitemsq&1 2a1^2 weak_destroy_while_iterating# Issue #7105: (%ors shouldn't crash when a key is implicitly removed# Create newPms to be sure no-one else holds a referenceD) = [ustr(c) for c in ('a', 'bEc')]3s4?P@it =6r(snext(it)# Trigger internal8Uationj2# D\0 anm!de0Vms[-1gc.collect(n`# just6cas# We haveR either the first consumedvs, or ano%&onJIn(len(lis@), [!&, V - 1]C# Thal has been committ{QEqual~(s)j and_mutate_ustring.ascii_lettersz@contextlib. umanager[R(6trycp# Start$Fratojyielded = ^b *# Scheduleal and rec%it;ugbo.pop()j5if >= uPR stilGp5.,Nadvance it (i 20006).1)  / w) uIofinallN9;#B all:2als(Awith`< as]NotIn(u, +DRaises(KeyError, s.6, ucu2_.add(UIn(u, s) t = s.copy()  with testcontext() as u:!(s.update(t9 self.assertEqual(len(s), &t))bWclear`10) 1def_len_cycles(5)aN = 20.items = [RefC1() for i in range(N)]/+WeakSet(;Adel -i^fiter(s'6trynbiFexcept StopIteration3Epassfgc.collect*An1 =vz8 28Q# one may be kalive inside th"UratorbzIn(n1, (0, 1"1On2, Lrace # Extended sanity checkss)face of 3ic 0;ionddCleanup(gc.set_threshold, *gc.g(3 tho4g1, 100w {0$ R(th,  )t\)&emdC# AlP will I`ed at  garbagec J W( $& z) n sGreater1#+FLess(N( S O+S2, n1) if __name__ == "__main__"@@unit.(() {(u'/home/gbr/devel/python/Lib/sre_parse.pyi1 __get|__(i5g+ٱQ?g˶ֈ`\?h)hacompilj`ju jp_info(lgh㈵>g>iRbPig iTd;?g64DE?bcdbsimpleerg?̔?ghUMue" e2fPigSb.A?g"L?,(u'/home/gbr/devel/python/Lib/sre_parse.pyi4u _sub(i\g}r?gq@H?0g4g distutils/fancy_getopttptcheck_alias_dict(igh㈵> {{,{set_negative"es~gTqs*> },z} }t>g mDh`r_init__Wg,C6> WePuK;]iY &4 qtokenizStopT2ingi(1#>0~iE!6X7}?anye!iu?g?̔> ) collectionsznamedtuple  posixpathfJ%@normdi d3PsetupEPuBmainAЁ#>f+ 0logeu/Lo r X* aconfigr NoOpRError7R:. eMTDByteCompileag4KXl/python/Lib /sysconfig.pyi>uget__var(igTqs*>g>{(usetupL uPyBuildInstallLib(JTO0O$/home/gbr/devel/python/Lib/getoptk}_>Y1\>gfLg?4b distutils/fancy_r r r'r posixpath#JT@normkig&|>g]/Meoeqabsd vh㈵1 : ` 7>g,C6>7*o `parser:qARawCPA>gu t"0~i! Xp&Mtranslate_longoptBgy2>g,B  Dped\\P _bitem__X>g{>``8set`iЉ&zset_aliases6K%>TAU_command_lineIt; h]]"/i"@_lib!S>g]E~ F.*F.Qerror^PLinkE SgNq)KX ython/Lib/distutils/errors.pyiQuCCompilerEt(i#g 0{(:" ~i u!(S]O 0X'/home/gbr/devel/python/Lib/posixpath&_get_sep jg_>Y1\>g'eRC>ee expanduserư>Gf#Bjoin`gigW#> ` =`Bsabsa aa abasenamed>gTqs*d ddirccT(TtokenizeScd UnrV.V") . .diTDCw^%3X} sre_pars"etPig;OnR?g_":vy?`Pur>gfLg? `ub|gͮ{+R?gǟlXSy?$4Pfancy0optS1 pRindex:&|>v&+v__init__Jr1extensionmo vgenexpr>hi| 3allGLL 'rfind' of 'str' objectsixІ  g>g,>(u'/home/gbr/devel/python/Lib/posixpath.pyi1basename(ig[ 0e,e distutils/corej"j gen_usage(fgTqs*> ?>{k$;k]Rsetupg"0~i<+h㈵>g *+ configparser)quRawCPoMPuBmaini>gyؘQ? B=uAF) _weakrefsetDx __contains__"%> !k 0abccccinstancecheck__ci_ Z Asre_n4 nB_subWgbDC?gZKgPufbg3ۃbRabBJ4A?gՎu?+  +class_escap%jg!>@?g{.!^ic.` `errorshduD M?E" Cug"gMP$sYsA t}gt-Pspawn [fgd?H"? jXW ju.(igמY? 2{(u4/home/gbr/devel/python/Lib/distutils/fancy_getopt.pyi> _grok_option_table(ws 0|'| sre_parseooXbsident gh㈵> ddSCsnam^iZ % p_abcollPuabupdateig F>gZ H?)a ^ ecse(r_init__bgp~i?#eqtokenizigư> L$ Lacompilfj $R_infokibk/>k!k chtn=g_>Y1\> built-in Crepr!&' Kۼ@ DdtupiPsetupPuH<@s l; HH]Bmain@ B"]<@.di? 9[ uPyBuildInstallLib=>gTqs*|"!? __d_class__pXJ qAu_#ili7g`?gq_! gC_coddg W(d! i"i"gIӠh^?gMc{-轁?1dsetatt=g]/M?g])/M?{(u'/home/gbr/devel/python/Lib/functools.pyi1pdate_wrapper(ig> j,j distutils/ oxj__init__i9ngIӠh> 0j)j sre_compilegggidentityPion(kPig!? Dppp_charsett?%? !noptimizeoPTigמY? Np~iH11i #>1& qwarningtxtdfilter,ej?PsetupL PyBuildExtj! __!d_?__>X; genericpath!Rsfiley_>Y1\>gTqs* 1o pzsysconfigm-.  h㈵>g F>P0uRfind__srig?̔.Qerror]uD}@ArgE[`:"*  p7rجDuplicateOptiong4KX `collec  d3xprVVL @'join' of 'str' objectsRiWX  uXOFile- vqX0(u0/home/gbr/devel/python/Lib/distutils/dir_ .pyiu(ig&|> !{(4_+/n0cmdiW idn` 0i,ij#__init__>g jx=j aj%pj listcomp?̔>g. ?%l Distribution( n90~iC"method 'clear' of 'dict' objects *#>4fancy_getopt_grok_opl_table|">{&S{J_build_indexuJJCSt-in S3ord=PigJ8 ? =-Qwuxx  5' sre_parsefM"g! ? bbSescapgTqs*> c chclass_iig 3max^)+getwidth}`ie install_miscV! _az"_>6\X  os _setitemSISFcheck_envir~Я*>0(u$"/home/gbr/devel/python/Lib/getopt.pyi&u GError(igư> 0{(7"0~i !(S]O 0X/% p_abcollju __contains__ig_>Y1\>gfLg?'g posixpathi expanduser>g?̔>,f distutils/kk check_environnAgh㈵>g,C6><getframe>'0') pections۾)namedtupleiOF'strip' of ' objects#>setupPu3maiU Bf Di bu  qthUMuW) X<1ng>u^modulTqs*>g4 ;aMexec M~tokenizeSqS_compileOgd>g[鑱dd<*i_d#replacei~44i%> $,get_platform0:Ц.T G0s/eYPuSr |5-in method __build_class__>(igư> "0(u$/home/gbr/devel/python/Lib/getopt.pyi3.B$([eW`2>{`4` distutils/fancy_]ppp'p sre_parsecPuOv3o?gTUh ͌?c4cB cB_subbilgg0 :@dep_Du_>Y1\>g ,nj aj&j qtokeniz#>g?̔ff 4 d4Ppuhandle_display_optionsx4>g xA_command_line kt+ jPs/logEU set_verbosityVF?(?g ĭ(Z t1sysconfi-_6 th㈵t#   oO4*igC8 !?gBus)E !ilCaf0cmd 1gq4GV~9?g3/@1cor j  jjju(iXƖ?{(u,/home/gbr/devel/python/Lib/distutils/core.pyi6(eoj0j0~i?#?ethod 'isalnum' of 'str' objects_gh㈵> ) collections.pyiu sgenexprci_ $@mbdecode\bytesjig>  oBqyW\.\ QerrorjJTDTemplateE$ ]g!1built-in : __d_class__6KKX. r._compile_typedUg W(?gA 3mʚ'6 functool//wrapper_id`configu/g}F?g'H0z? j: sre_pars: _setitem__g4 ;? ^h ;{^iZ Z ]r mk_bitmapV[*T7S?gϹTi6ioptimize_chStp* pr|qv !>@?gυ^w2 a lDj DR_infoMP$?gɩajK]ll_)d1 xtension.pyiu Extension(igư> p{(u"0~i !(S]O 0X1/home/gbr/devel/python/Lib/distutils/eP.pyiY__init__?̔>g_>Y1\>4PsetupFPuLmain B' posixpathaouabs Tqs*>ghUMusysconfign }ix) pgenericRsfileJ`e.e PrrorsjZj@LibEg"A) sre_compiligt"?gӆ@ * r]]^b_typed_dVPuLPyBuildInstallLngn4KX| nApars+bappendPigti0?g[5kcrc_vj`cgRG.?g F3?b4bbB_subfig{,cputenv- o _setitem__a TPreprocessg{(u~i !(i6g: 0XXisinstance>(SPig 0*X?g:8؛X?0'/home/gbr/devel/python/Lib/sre_parse.pyiu fix_flags(kgTqs*> e posixpathe6 expanduserfgư> f& warningseeDlteri` i 4j __getitem__gP5iguB? g4 distutils/fancy_0optpttcheck_alias_dictzEi` z z oD`uRncode[Pi3">[1[ extensionYT_initC%n p_abcollbSupdatig?̔> "?  urget_sep2 24=2&55grok_option_tablig_>Y1\> )? < ecVpnamedtuphh#mp: f fZLS__nexPig[[%XL? b, L 1cnalizeO J7@norm7NSd !| r]_b_typedcig'eRC> H79command/W)(iig{?g Om?{(usetup.pyi(iAF0F,/home/gbr/devel/python/Lib/distutils/corejjAegMV?g9 {៰# F0~i"(gTqs*> O)  sre_compilPu ofg> nxnx__init__in gi# Ptoken`J8S `4` 7fancy_getoptqp_check_alias_Piq %z p_abcollkpRpdate`i#>bhc et_platformwfLg>gמYnnB @renviron">=9= command/build_ex#Uu  w&|>oTASt-in Cexec+3Udt@B?g#G:3pections0 namedtupl iguB?ga2U0*C? ai1sta1b rS_ISREGZ />rgenericpathfNisfi e&jphget_attr_AigtJ8 w&w pgrok_opD_tabw|zm ccb_len__cPigI? c1 distutils/extension4Ym4T_initn#g n%n p_abcollb2gCpdat1igư> ` posixpathb] expanduser4i ffcdirnam)Z c4) fancy_getoptpjgrok_option_tabl{:{gTqs*> {){  ecVsppFDdtuphAF#@f hclass_FGiC ikk<pmize_cht*Rg&|? o omS__nexbP3iglXSYD? bH_urgصݒ?g{(?b 3jdWR_infok?ofg_>Y1\>k o(1yi f43B_sub~g4 ;?f??0g  __>g?̔>{d,  0find_config_files #>ݣ$2sys_wBXn#>@#>E ~iAu (# Z# >devel/python(/Lib/distutils/fancy_getopt.pyi u(igư> 00(4 4/home/gbr/devel/pythonrmwg5w\&?g4)^X?{r,rX j0~i#ethod 'isdigit' of 'str' objects>(l ig< ) collectionsۂ namedtupledn` 8i #command/__init__x 9#>I_setupFXARF& tokenized"TRError""!built-in m __d_class__TX* configparser]u CP p>g8j33- X' posixpath= Osabs?*bouabsvHd"allocate_lock4Vfunctool~decorating_!?ion .>;goӟHY?gӁV_}<9 "!ex8e # tIӠh#"?|AV g1]a8?gR%Rwg+ mdhgJ8 ?gC8 hbginstall_libx5G 'eRC>gPG1 /distutils/extension.pyiu(QigZQf?g F?(3,/home/gbr/devel/python/Lib/distutils i6iigrQ-" ?g3ۃ i.i`errorsk kkg=\r)=?gH'=k&k tokenizecc<gصݒ?gm77Mcqstring>`| hUMu>g&|E1 |text_fil n qwarningyL1ig$D?g?̔MS3O>gIӠh>+:0loghgfLg7hcommand/installt)Ets! t$t `getoptaa'eRC>gF=Qconfi@4>gtk4 ffancy_aigTqs* ?oqPsetup!*2?0F* `parserh uInterpolationDepthE(?hgư> {w0~i!built-in method __d_class__ XX XO'get' of 'dic rbjects>fgmO? )& sre_compz g 'f_escapecjcg_>Y1\> x1cor;kfefxf __init__(iigg%(u'/home/gbr/devel/python/Lib/sre_parse.pyiI1 opengroup(igư> e4e distutils/fancy_getoptrr_grok_option_table{3{g&|> {){ `collecVspp namedtuphh? hHf class_escap(ighUMu> iysconfig>uget_B_var;i 0k+< !loo?set_threshold(in$?>{n#Enverbosityn.QerrorWq CompileE ^ ~i u!:XXXgetattr>gh㈵>  functool_update_wrappe_kgTqs*> ,hxo7r_init__$i`i/>i$17finalizeysqq0]1extensionLus {(u,/home/gbr/dC/python/Lib/distutils .pyiuparse_command_line(oyk 0t0~i#0_gTqs*> ' Asre_T closegroupbi^  g re```bompile>gEB?&] warningsccfilterjj>gA#?9i /build_ext|`!ubodule>v>g[[%XLv*v aconfigrguSafeCPyro>gz.o>gOʤ6;i qtokeniz;>gX+>c"; @glob3_ i>gdC_qysc>gkc]O ,am2k#q~Rawnc ^sn4 LPfancy!opG J(Y-VTg F?g!>@gmc.9QerrorgETDInternalE$vk"!8OSt-in  __d_class__Qư>gư>0(u~i #(i8g> {Z&/home/gbr/devel/python/Lib/warnings.pyifilter/(j )j collectionm(m__init__igh㈵?g'eRC?*g nfigparserYuh0>g{?8'g functool~decorating_!Tqs*>gIӠh?>p Asre_pgetwidth<g XrT?gd< X< epcompilegc;bsimplefg. ? :eje ezR_infokkg<#?g?W5  i"gQ?gfvTB qtokeniz28Rmaybeeij2>g#>a )_d_d Xprocessop rrkMdef>gk$ %3gPsetupPu7=maiB2NoS0_Error~<J!Jbuilt-in S __d_class__A6Hr posixpath'9}basenam #>;,u distutils/corq u sen_usaglk">j;4 wf6/> ython/Lib/configparser.pyiuError( Qigh㈵> 0{(1"0~i !(SX0X*/home/gbr/devel/python/Lib/coDuplicateSectionư>g 4OX, distutils/ `upistribuMetadata?̔>g 4OX9command/0ext)E  &|>gמY?4 X4fancy_getopB Tqs*>gӹ0u_W\_lineO t.es:PlatformTr' 2sys$A_\_vars#>zlm>ul  k "llۤ namedtuple@fg;?gMLbGH&@ tokenize?X ummodule dZ&P FsGr B- XX Q>j1cor"7gen_usagk0devel/python$/Lib/distutils/__init__.pyi u(i#g 4{(4PsetupFFF 0F 7/home/gbr/devel/pythoncommand/installuxu 'eRC>g  ~i u!built-in method __d_class__>(OX" @statS_IFMT>g ^1^|S_ISREGV_#  'update' of 'dict' objects) Z' functoolsw_wrapperk linecachek Ln1?geN?& qwarningU d K d Bfind?str D#>  posixpath  expandusgtext_fil qTextFileTqs*>g f)OXX<(_local}})8 collection;namedtuplei.i Qerrorn5nTD%SE! 9 /W"TXX $ad e54dii bUnknown ~iu!<built-in method __d_class__>(i#g 20(u4/home/gbr/devel/python/Lib/distutils/fancy_getopt.pyi> _grok_option_table(wg%?gXj0?{|,|B p ~i cu.<;'__contains__' of 'frozenset' objects>uig> )Q `collec,sF namedtupledii sre_compileiimize_charsetgxB?m?gu;ʃtpppojio*H PnfigprXuMissingSeHeaderError"&!&Xj1Interpola5oSyntax/>4 X& qwarning RWmMessag( jL#bappend =lisPigǺF? ,_mk_bitmapPigmO? Bh fP7ig+,/? f' j4B_subfagמY? f9f command/Ad_ex Uu ww w9C_codccc@ posixpathaJa@normi gv>g>(u4/home/gbr/devel/python/Lib/distutils/fancy_getopt.pyiu_grok_option_table(iig?̔>g?̔>{'{ sre_parsenI opengroup(e0eg_>Y1\> eeappendbPigh㈵? b)acompild7optimize_chtoog{? o7o command/installFx}3s#g sPuDb gZQf? bDjd DYR_infokjg,C6> k!2k PigמY? 0o`~iXu(ig&|> {N,u get_platform*in)[r__len__ghUMu/?g=Զa4?d\cg+ٱ!?g5&?4\71igTqs*> kBlen>}gfLg?g4 ;4 0B_subfJff?g]E~?r getfilesystemencodingri   os2Sdecod=fk; [[[i &+T_initei:#>#>)5BC_linot㈵>gfLg>0(u~i (ig5w\&? {L'/home/gbr/devel/python/Lib/sre_parse.pyirgetwidth(e 3chrg>  __next^iZ  functoolsuc lru_cachezigTqs*> %z pfnmatchd dx^c,c distutils/jj check_environ?̔>gמY?oyo 0ufind_config_files s& qwarning/uFAg}r$?g[Y"&X j(j4 7s/fancy_getoptIwI dictcompPtP>gh㈵>t& r.Qerror@TDPExecE g 5!) 5 __d_class__dKX) A!ilCcSsimpl-Gg1zn+1?gJ><f /_{Obig%%dhasatti]xr_init__#!gfLg> M p_abcoll+bupdate`Wi w">`g ,_platformmmmsetup.pyiu(igư> %0(u'/home/gbr/devel/python/Lib/sre_parse.pyi1match( QigW\9?g XrT?{buuPigvꭁ2?gVDׅO?b4b bB_subf+g!?g}r4?+M0~i g_>Y1\>,b distutils/ l0efind_config_files@s.s]u PyPIRCCommand! __d_class__X* ruSafeC9P8 Tqs*>gIӠh.'- X& qtokeniz6Rgroupg%>gjau` 7igfLg>">c7gfLg>(u /er\\Dql_typedc?̔>g{>0dp~io%(/g? {\4 distutils/fancy_getopt0E_longopt'eRC>g z,j  get_attr_namevg F? M!M@lowe@IX@%> I,IOA platformiie &n qtokeniz}0hP TBInfoVi\ x+built-in  __d_class__>6Xt&t8option_orderrpars0mand_linqt!uSoduleji:-?g]pX:?j"co jj"'DsettFproperty< K#>* aconfigr-IParsingErrorl4g!>@@&;]\setup gG2vgTqs*ٳ+" X^_ u fix_flags(Si@g!>@?gfLg?{(u'/home/gbr/devel/python/Lib/sre_parse.pyiup$(]gb0b.b distutils/errorsi (lghUMu>g+,?4PsetupFuFiF"0~i"ethod 'encode' of 'str' objectsgh㈵> m  ouogWiS ,\ gmP{ujMixin2to3f>g  ! built-in m) __d_class__>6}O __init__ F?gLn!#e b?orstrip?igTqs*> x posixpath  Fxpanduser">ffrdirnamec  #<9_'join!Wg?̔>g'eRC>!& tokenize 6VRgroupay )` collectioncSdtupl ! )h4h fancy_getopts<ogoJx@normmd,V+0logi iR' )6n qwarning !6catch_<q)ass__>(iPig> %0(u'/home/gbr/devel/python/Lib/sre_parse.pyiI1 opengroup(a0ghUMu?gfLg?{fuy$(^ihc)acompileR_codeig#Di ?gV`ddCxaif% p_abcolldb2getTqs*>g%>-^ distutils/debugfTuk"0~i6? built-in method globals># Ptoken a$ 'endswith' of 'str' object_ wh posixpathG2NBjoinmiX  3pectionsc9c e_setitem__%?gEn1  functoolhhrwrapperdoPsetup |gͮ{+c?gD9 Mexec M ~ o&deYig_>Y1\>g?̔\\g\a4 fancy_getopt|u Op=RDummy)] O"! __d_class__ X+/lo @>g,C6 @ | F.QerrorG,7TDE" >{(u~iu!(igư> 00(M2;/home/gbr/devel/python/Lib/distutils/command/install_lib.pyiE g (|Tqs*>g {|")OX!qstring>u TokenInfo_>Y1\>g 4OX%s pfnmatch]Xu|module>hUMu>gm77M?"c 1glo ` 6 `*` configparserAh__init__&|>g#Di ,h  jYjA}_l_files t't functoolsopdate_wrapper>g?̔>k~fdecorating_g3OIj!is3nceeNS6kLsJKbJpa&g+,?gg]/M1<extensionY ɘ">)ne/gbr/devel/%python/Lib/collections.pyiu namedtuple(igh㈵>gIӠh>0(6,/home/gbr/devel/idistutils/corel;6setup( igg%>gA ]L?{g1CPuBmain=GB"0~i~ ) `9v __setitem__jg> i(i,d__initfi]f4 fancy_getoptr_negative_aliasesNz#>W#>NEv uparse_command_lint' posixpathoGqBjoinNS1a sysconfigk-k +F_d- ">-H0Hfind_b_filesr9rGAdebuusY1\>g QkL jeaj functool<ejrwrapper=igC8 1?g@iQH2  -]$piY^7 sgenexpr%*>g FV VBall>KGiLv~decorating_#iohUMu>g Wafnmatc  I cW@arch9` r ) +Wevel/python/Lib/distutils/cmd.pyiu(ig F> 00(4 '/home/gbr/devel/python/isre_parseeu_escape(v i9dg() ?gd?H"?{dddw^hc, 0 x1__init__1#Di ?g!>@ j1cor6;j*Rsetupg* aconfig#r InterpolationMissingOp \Errorư>g 0~i!Vbuilt-in method __d_class__oOX1 text_filC> _>Y1\>g! w$ FF 6ag4KX+WCommand??/>4?X) Ccomp7L0_chtg fhg@fg;%?$k _fg70@?g=z}v?AeSisnam ig%>g'eRCc^cx $5$g9̗?g+i7>^^ Xi]& qtokenizc(iPiJgصݒ,?gBZc ?{(u'/home/gbr/devel/python/Lib/linecache.pyiu(`e0e1e distutils/file_ o] ooh㈵>g +o0cmdiW i{d` ,ijYuparse_config_ s(okgz-t@coret;]osetup(g os[ __getitem__pighUMu>g4 ;y posixpathh expanduser8">z% p_abcolldd]j] )contains__fsi>g3O>f 1ufinalize_optiondtA#>ArxDinitz j" ~i!u0Yethod 'disable' of '_lsprof.Pro+r' objects>mEg2>gp3>{h2syss kgמY?g?̔"9w s/command/build_extwe w  w N&NstartswithQ-stDT[g%> GBjoiniqtokeniz#_Y1\> vf) s!ecnamedtuple3E<3ython/Lib/po sixpath.pyi=uisabs( gư> (0'/home/gbr/devel/python/Lib/poaJunormvddgTqs*> 0e)e collections move_to_end(i2>{j functoolhhwrapper_d& qwarningcScp _OpRErrorg" ~i u!6iO 000-BEGIN PRIVATE KEYN- MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC3ulRNfhbOAey/ B+wIVYx+d5az7EV4riR6yi/qE6G+bxbTvay2pqySHtDweuaYSh2cVmcasBKKIFJm rCD1zR8UmLb5i2XFIina1t3eePCuBZMrvZZwkzlQUSM1AZtjGOO/W0I3FwO6y645 9xA5PduKI7SMYkH/VL3zE5W1JwMovv6bvNiT+GU5l6mB9ylCTgLpmUqoQhRqz/35 zCzVyoh+ppDvVcpWYfvXywsXsgQwbAF0QJm8SSFi0TZm5ykv4WE16afQp08yuZS0 3U4K3MJCa4rxO58edcxBoHQ29K3iINM8enRfr5q+u5mAAbALAEEvyFjgLWl/u 7arxn7bJAgMBAAECggEBAJfMt8KfHzBunrDnVrk8FayYGkfmOzAOkc1yKEx6k/TH zFB+Mqlm5MaF95P5t3S0J+r36JBAUdEWC38RUNpF9BwMYYGlDxzlsTdCuGYL/q+J o6NMLXQt7/jQUQqGnWAvPFzqhbcGqOo5R2ZVH25sEWv9PDuRI35XAepIkDTwWsfa P6UcJJoP+4v9B++fb3sSL4zNwp1BqS4wxR8YTR0t1zQqOxJ5BGPw1J8aBMs1sq5t qyosAQAT63kLrdqWotHaM26QxjqEQUMlh12XMWb5GdBXUxbvyGtEabsqskGa/f8B RdHE437J8D8l+jxb2mZLzrlaH3dq2tbFGCe1rT8qLRECgYEA5CWIvoD/YnQydLGA OlEhCSocqURuqcotg9Ev0nt/C60jkr/NHFLGppz9lhqjIDjixt3sIMGZMFzxRtwM pSYal3XiR7rZuHau9iM35yDhpuytEiGbYy1ADakJRzY5jq/Qa8RfPP9Atua5xAeP q6DiSnq9vhHv9G+O4MxzHBmrw9sCgYEAziiJWFthcwvuXn3Jv9xFYKEb/06puZAx EgQCz/3rPzv5fmGD/sKVo1U/K4z/eA82DNeKG8QRTFJCxT8TCNRxOmGV7HdCYo/B 4BTNNvbKcdi3l0j75kKoADg+nt5CD5lz6gLG0GrUEnVO1y5HVfCTb3BEAfa36C85 9i0sfQGiwysCfGuus9k8cgdct5oz3iLuVVSark/JGCkT2B+OOkaLChsDFUWeEm 7TOsaclpwldkmvvAYOplkZjMJ2GelE2pVo1XcAw3LkmaI5WpVyQXoxe/iQGT8qzy IFlsh0Scw2lb0tmcyw6CcPk4TiHOxRrkzNrtS9QwLM+JZx0XVHptPPKTVc0CgYAu j/VFYY5G/8Dc0qhIjyWUR48dQNUQtkJ/ASzpcT46z/7vznKTjbtiYpSb74KbyUO5 7sygrM4DYOj3x+Eys1jHiNbly6HQxQtS4x/edCsRP5NntfI+9XsgYZOzKhvdjhki F3J0DEzNxnUCIM+311hVaRPTJbgv1srOkTFlIoNydQKBgQC6/OHGaC/OewQqRlRK Mg5KZm01/pk4iKrpA5nG7OTAeoa70NzXNtG8J3WnaJ4mWanNwNUOyRMAMrsUAy9q EeGqHM5mMFpY4TeVuNLL21lu/x3KYw6mKL3Ctinn+JLAoYoqEy8deZnEA5/tjYlz YhFBchnUicjoUN1chdpM6SpV2Q== -----END PRIVATE KEY- -BEGIN CERTIFICATE MIIDYjCCAkqgAwIBAgIJALJXRr8qF6oIMA0GCSqGSIb3DQEBCwUAMGIxCzAJBgNV BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u IFNvZnR3YXJlIEZvdW5kYXRpb24xFTATf"BAMMDGZha2Vob3N0bmFtZTAeFw0x ODAxMTkxOTA5MDZaFw0ycB/ V  CCASIwDQYJKoZIhvcNAQEB BQADggEPADCCAQoCggEBALe6VE1+Fs4B7L8H7AhVjH53lrPsRXiuJHrKL+oTob5v FtO9rLamrJIe0PB65phKHZxWZxqwEoogUmasIPXNHxSYtvmLZcUiKdrW3d548K4F kyu9lnCTOVBRIzUBm2MY479bQjcXA7rLrjn3EDk924ojtIxiQf9UvfMTlbUnAyi+ /pu82JP4ZTmXqYH3KUJOAumZSqhCFGrP/fnMLNXKiH6mkO9VylZh+9fLCxeyBDBs AXRAmbxJIWLRNmbnKS/hYTXpp9CnTzK5lLTdTgrcwkJrivE7nx51zEGilZh9Db0r eIg0zx6dF+vmr67mYABsAsAQS/IWOAtaX+7tqvGftskCAwEAAaMbMBkwFwYDVR0R BBAwDoIMZmFrZWhvc3RuYW1lTA4IBAQCZhHhGItpkqhEq ntMRd6Hv0GoOJixNvgeMwK4NJSRT/no3OirtUTzccn46h+SWibSa2eVssAV+pAVJ HbzkN/DH27A1mMx1zJL1ekcOKA1AF6MXhUnrUGXMqW36YNtzHfXJLrwvpLJ13OQg /Kxo4Nw68bGzM+PyRtKU/mpgYyfcvwR+ZSeIDh1fvUZK/IEVCf8ub42GPVs5wPfv M+k5aHxWTxeif3K1byTRzxHupYNG2yWO4XEdnBGOuOwzzN4/iQyNcsuQKeuKHGrt YvIlG/ri04CQ7xISZCj74yjTZ+/A2bXre2mQXAHqKPumHL7cl34+erzbUaxYxbTE u5FcOmLQ>END,# Adapted from test_file.py by Daniel Stutzbach import sys o $ioEerrn @unitY ccarray G tweakrefRproxyfunctoolsbwraps YA.supV(TESTFN, _UNICODE, check_warnings, run_?, make_bad_fd, cpython_only, swap_attr)collectionUserList=_io # Cplementa1F of C_pyio # Pn+ class AutoFileTests: # s for which a is automatically set up @0defUp(self)U!Q.f = vIO(TESTFN, 'w') def tearDown(self): 0if &.f.close().os.remove(TESTFN) astWeakRefse # verify weak references=op = proxy:&.fr p.write(bytes(range(10))"assertEqualC.tell(), p 2fIf = None_Raises(RError, getattr, p, 'v'PSeekTL|/.f2-20\seek($ +!f.B1C ,DK5, 1F 5,F-G G2b  pAttribuexpected ,a existIc>".f>f.mode, "wb"d, FalseyR8theare readonly!or$P in 'yA', '/d'(AType %),as:!f,|, 'oops@qBlksize stest private _b'Jy~ = io.DEFAULT_BUFFER_SIZE)# try to! pDred @from stat.sto, if availabl7`if hasp(os, 'f7'fst = os..f.fileno(,=Xffst, '$',1i&f.X:6#Ainto@ReadByteArra^[1, 2, 0, 255],f(@a = abb'abcdefgh'BwithcFileIO, 'r') as dn = f.6(baKba, b'\x01\x02\x00\xff 6Cn, 4._/Memoryview0" %Fp.moduleF X)j4del'^!&/fdlSF bug u3u# "fileu` faultw>/) 1& f7'r+@data = f.read(1if 0!= s+5):,`("Read!edscupdate0 %r@`Iif f.tell() != 5:  'self.fail("File pos after read wrong %d" % f.tell()) Ef.truncate()%if3i != 5:C}fTLclossize = os.path.get}(TESTFN+$!%:trybug8016311kfinall)os.unlinkCdef testAppend(F)b of3penEj, 'wb'f.write(b'spam_VaVOeggsV$rV`d = f.?N/f..assertEqual(d,  MifexceptBpass:InvalidInitRaises(TypeError, IO, "1", 0, 0r]WarningsZwith check_w#quiet=True) as woB$w.:J, []J- :gOValu!r/some/im/name", "rt" |!UnmadFDOnEf@os.o__file__,O_RDONLY`_&, |&fd5#osfd) # should not !OS[(EBADF) `COtherjTests(`, unit.CCase{2IO = _io`module = '_io'@cpython_only*Z"Fd_overflowh<# Issue 15989<import _Dcapi self.assertRaises(TypeError, sFileIO, _testcapi.INT_MAX + 1) ,I!@IN -I class PyOthervjTests(`, unit.aCase):2IO = _pyio.modulename = '' def Ic_main(F# Historically, these's have been sloppy about removing TESTFN.t# So get rid of it no matter what'2tryFDrun_`(CAutoZs, Pyf6 C. O0fin{if os.path.exiwdos.unlink(p if __\@__ =_O2__']a -BEGIN PRIVATE KEYq- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDH/76hZAZH4cSV CmVZa5HEqKCjCKrcPwBECs9BS+3ibwN4x9NnFNP+tCeFGgJXl7WGFoeXgg3oK+1p FsOWpsRHuF3BdqkCnShSydmT8bLaGHwKeL0cPxJP5T/uW7ezPKW2VWXGMwmwRaRJ 9dj2VCUu20vDZWSGFr9zjnjoJczBtH3RsVUgpK7euEHuQ5pIM9QSOaCo+5FPR7s7 1nU7YqbFWtd+NhC8Og1G497B31DQlHciF6BRm6/cNGAmHaAErKUGBFdkGtFPHBn4 vktoEg9fwxJAZLvGpoTZWrB4HRsRwVTmFdGvK+JXK225xF23AXRXp/snhSuSFeLj E5cpyJJ7AgMBAAECggEAQOv527X2e/sDr0XSpHZQuT/r9UBpBlnFIlFH+fBF5k0X GWv0ae/O6U1dzs0kmX57xG0n0ry6+vTXeleTYiH8cTOd66EzN9AAOO+hG29IGZf9 HAEZkkO/FARc/mjzdtFnEYsjIHWM3ZWdwQx3Q28JKu6w51rQiN51g3NqOCGdF/uF rE5XPKsKndn+nLHvsNuApFgUYZEwdrozgUueEgRaPTUCNhzotcA9eWoBdA24XNhk x8Cm/bZWabXm7gBO75zl3Cu2F21ay+EuwyOZTsx6lZi6YX9/zo1mkO81Zi3tQk50 NMEI0feLNwsdxTbmOcVJadjOgd+QVghlFyr5HGBWMQKBgQD3AH3rhnAo6tOyNkGN +IzIU1MhUS452O7IavykUYO9sM24BVChpRtlI9Dpev4yE/q3BAO3+oWT3cJrN7/3 iyo1dzAkpGvI65XWfElXFM4nLjEiZzx4W9fiPN91Oucpr0ED6+BZXTtz4gVm0TP/ TUc2xvTB6EKvIyWmKOYEi0snxQKBgQDPSOjbz9jWOrC9XY7PmtLB6QJDDz7XSGVK wzD+gDAPpAwhk58BEokdOhBx2Lwl8zMJi0CRHgH2vNvkRyhvUQ4UFzisrqann/Tw klp5sw3iWC6ERC8z9zL7GfHs7sK3mOVeAdK6ffowPM3JrZ2vPusVBdr0MN3oZwki CtNXqbY1PwKBgGheQNbAW6wubX0kB9chavtKmhm937Z5v4vYCSC1gOEqUAKt3EAx L74wwBmn6rjmUE382EVpCgBM99WuHONQXmlxD1qsTw763LlgkuzE0cckcYaD8L06 saHa7uDuHrcyYlpx1L5t8q0ol/e19i6uTKUMtGcq6OJwC3yGU4sgAIWxAoGBAMVq qiQXm2vFL+jafxYoXUvDMJ1PmskMsTP4HOR2j8+FrOwZnVk3HxGP6HOVOPRn4JbZ YiAT1Uj6a+7I+rCyINdvmlGUcTK6fFzW9oZryvBkjcD483/pkktmVWwTpa2YV/Ml h16IdsyUTGYlDUYHhXtbPUJOfDpIT4F1j/0wrFGfAoGAO82BcUsehEUQE0xvQLIn 7QaFtUI5z19WW730jVuEobiYlh9Ka4DPbKMvka8MwyOxEwhk39gZQavmfG6+wZm+ kjERU23LhHziJGWS2Um4yIhC7myKbWaLzjHEq72dszLpQku4BzE5fT60fxI7cURD WGm/Z3Q2weS3ZGIoMj1RNPI= -----END PRIVATE KEY- Certificate: Data Version: 3 (0x2)#Serial Number082:ed:bf:41:c8:80:91:9d;Signature Algorithm: sha1WithRSAEncryption/OIssuer: C=XY, O=Python Software Founda3 CA, CN=our-ca-serverHValidity]Not Before: Jan 19 19:09:06 2018 GMT1After : Nov 281)271tSubjectL=Castle Anthrax fakehostnameW Public Key Infok?rsac 4-Key: (2048 bit#zModulusp00:c7:ff:be:a1:64:06:47:e1:c4:95:0a:65:59:6bB9* a8:a0:a3:08:aa:dc:3f:00:44Bc^4Bed:e2:6f:03:78 d3:67:14:d3:fe:b4:27:85:102:57:97:b5:86:16:882:0d:e8:2b 69>c3:96:a647:b8:5d:c1:76:a9:02:9d:28:52:c9d9:93:f1:b2:da:18:7cq78:bd:112:4f:e5B 3f:ee:5b:b7:b3:3c:a5:b6:55Pc6:33Ob0:4Ba4:49:f5:d8:f6:54:25:2e:db:4b:c3H#64#bf:73:8e8@5:ccb4:7d:d1:b1_20:a4Pae:deA 4143:9a:48d4:12:39+?8:f 91&b:3b:d6:75 !625:5a:d7:7e:3610:bc:3aP46:e3c1:df:50:d0:94:77:22:17Ba0:51:9b:af4:60:26:1dA04:aO06:0 57N 1a5 4fP19:f8iP4b:68 P0f:5f.0EAbb:cP84:d9 b01d:1b:11B54:e6:15!af*2b:6d:b9 5dp/01 74Z a7P2b:92T e2Y 13x 29<]92:7bExponent: 6553710001) X509v3 extensions: !X5 Subject Alternative Name: .9DNS:fakehostname!OKey Usage: critical'Higital Signature, 7Encipherment4[E1ded-d (\TLS Web Server Authendtion, kClient MuBasic ConstraintsCA:FALSEHg IdOfiereF8:76:79:CB:11:85:F0:46:E5:95:E6:7E:62:5E:4E:AA:EC:4DxQority6z keyid:9A:CF6E:EB:71:3D:DB:3C:F1:AE:88:6B:56:72:0308:A7:481DirK/C=XY/O=Python Software Founda CA/CN=our-ca-s Oserial:82:ED:BF:41:C8:80:91:9B 0bInformfoAccessvCA Issuers - URI:http://testca.p C.net/pycacert.cer}OOCSPLZocsp/CRL Distribu+"Po .tBFull  Qrevoc/B.crle@ AlgOhm: sha1WithRSAEncrypy6d:50:8d:fb:ee:4e:93:8b:eb:47@ba:38:cce1:9d:c7e:1f:9c:22:0c:d2:08:9b:ed:bf:31:d9:00^Paf:8cU78:92:d1:7c:baP81:7f?1f:f4:68:99:86?xc6:cb:5Pd3:b9d12:fa:75:53:fdP32:21af:6b:4c:b1:34:36d1:a8:25:0a:d0:f0:f8:d58:6e:af:e3xc4:32:879:d7:cd:ad56:f3:15:27:10 f9 59dO5d:4d:07P7a:e5@ 97 bcb4:f1:17^33:55:2866:7b:70:d3:a5:12fed:e6:13:20:2dP9e:ecLP64:cf113:14:1bba:64:ac:c5:51:b6 13$ 93F@ fd:43:09:a0:0b:44:6c:77:45b ed b2[ dc@4a:5b:73:5f:c1:fc 631 f8ca:3c:98:06$ fd @Pd1:e4 61P09:8f 18= 98Pcb:3fd7 3@Pf5:a725:63:1c:ff a6P8c:e8P84:3dP38:0fAe0:5kf9:18:05:23P39:dePce:8ega6: 6e:f5:4f:c3 -BEGIN CERTIFICATE- MIIE9zCCA9+gAwIBAgIJAILtv0HIgJGdMA0GCSqGSIb3DQEBBQUAME0xCzAJBgNV BAYTAlhZMSYwJAYDVQQKDB1QeXRob24gU29mdHdhcmUgRm91bmRhdGlvbiBDQTEW MBQGA1UEAwwNb3VyLWNhLXNlcnZlcjAeFw0xODAxMTkxOTA5MDZaFw0yNzExMjgx O5MGIQRcwFQHDA5DYXN0bGUgQW50aHJheDEj MCELCgwaUHl0aG9uIFNvZnR3YXJlIEZvdW5kYXRpb24xFTATBgNVBAMMDGZh a2Vob3N0bmFtZTCCASIwDQYJKoZIhvcNAQ9ADggEPADCCAQoCggEBAMf/vqFk BkfhxJUKZVlrkcSooKMIqtw/AEQKz0FL7eJvA3jH02cU0/60J4UaAleXtYYWh5eC Degr7WkWw5amxEe4XcF2qQKdKFLJ2ZPxstoYfAp4vRw/Ek/lP+5bt7M8pbZVZcYz CbBFpEn12PZUJS7bS8NlZIYWv3OOeOglzMG0fdGxVSCkrt64Qe5Dmkgz1BI5oKj7 kU9HuzvWdTtipsVa1342ELw6DUbj3sHfUNCUdyIXoFGbr9w0YCYdoASspQYEV2Qa 0U8cGfi+S2gSD1/DEkBku8amhNlasHgdGxHBVOYV0a8r4lcrbbnEXbcBdFen+yeF K5IV4uMTlynIknsCAwEAAaOCAcMwggG/MBcGA1UdEQQQMA6CDGZhaP ZTAOpHQ8BAf8`CBaAwHAR0lBBYwFAYIKwYHAwEGCCsGAQUFBwMC MAwIdEwEB/wQCMA=LOBBYEFPh2ecsRhfBG5ZXmfmnLEl5OquxNMH0G A1UdIwR2MHSAFJrPz27rcT3bPPGuiGtWcgPLCKdIoVGkTzBNMQswCQQGEwJY WTEmMCQ_ECgwdgQ0ExFjAU W91ci1jYS1zZXJ2ZXKCCQCC7b9ByICRmzCBgwQEEdzB1MDwG zAChjBodHRwOi8vdGVzdGNhLnB5dGhvbnRlc3QubmV0L3 RjYS9w eWNhY2VydC5jZXIwNQj MAGGKWh0dHA6Ly90ZXN0Y2Euce dC5uZXQr29jc3AvMEMdHwQ8MDowOKA2oDSGMmQ R Qs3Jldm9jXuY3Js( )TA4IBAQBtUI377k6Ti+tHVro4zIDhncfhnh+cIgzSCJvtvzHZAO6vjFZ4 ktF8uk6Bf4If9GiZhpHGy1fTuUES+nVT/SIyIVCva0yxNDbRqCUK0PD4gX1pWG6v 49LEMod5182tDFbzFScQDPlXWVMA7a9dTQeGeuXzl4i8hrTxF0YzVShme3DTpRK5 T8ft5hMgLfCe7Bdkz/0TFBt2umSsxVG2zRMKk7H9QwmgC0Rsd0VDC+XtcLJ23AhK W3Nfwfx/Y3D4uco8mAZf/ZjR5OZhXwmPbBiGmJzLP3N7Pzj1pwkg7qVjHP+LptGM 6PSEPZk4D8zgUgP5GAUjdjneUs6O+6Zu9U/D >END # Test the windows specific32reg module. # Only>functions not hit here: FlushKey, LoadKey and SaveKey import os, sys, errno unittest from  0sup8?threading*platform.machine # Do this first so test will be skipped if module doesn't exist support.im!_m$ ('winreg', required_on=[']) # Now 3 everything from ;* try: REMOTE_NAME = sys.argv[ .index("--remote")+1] except (IError, Value )ZNone # tuple of (maj8minor) WIN_VERRgetwindowsversion()[:2] # Some tests should only run on 64-bit architectures where WOW64 will be.p64_MACHINATrueachine() == "AMD64" else FalsStarting with We 7 andServer 2008 R2, ~no longer uses # registry reflectionG`formered keys are shar=nstead. #u ;M 6.1. Due to this, someYfVvalid up until7 HAS_REFLECTION = 9< (6, 1)5Use a per-processprevent concurr s (buildbot!)  # stomp~on each other. 50_key_base = "Python Test Key [%d] - Delete Me" % (os.getpid(),)D1namDSOFTWARE\\" +wc # On OS'es that w0a!t]|Classes?data = [R("Int ",2 45  REG_DWORD),KWQwordM0x1122334455667788[KQK0Str2ValB"A sRvalueK%SZH`Expand5"The path is % %JHwEXPAND_ObMulti-8["Lots", "of"3s"]OXMULTINRaw DataJb"binary\x00 NeBINARYBBig 6"x"*(2**14-1) D LHBHbIG  H Q# Twothree kanj>meaning: "Japan"# Sese")Mese 日本^ Q語",o@] ca BaseW`s(unitJ.qCase): \def setUp(self# Make sure"th?`is abssTwhen S>s%s._!.dC _tree(HKEY_CURRENT_USER,')ef delete_tr ee(self, root, subkey): 6try hkey = OpenKey(7, 0, KEY_ALL_ACCESS)Iexcept OSErrorT#x does not exist<xereturnwhile TrueK <2subp = Enum6, 0) # no moresYbreak_.delete_tree(zTCloseD<m!) fdef _wri]est_dataD_keystr="sub!",> PCreat= # Set the default value for this key.]@SetV(y0, tkey_name, REG_SZ, "DO"pJ1q`assert (handle !="# V aE-key'# =#~ Kpa# Give0subG` some dsk(2 ,,_type in) S3Ex(9qTHG2# Check we wrote as many itemswVoughtnkeys, n_ s, since_mod = QueryInfo*cEqual(Gb1, "NoKcorrect number ofJs IK &I`07Alen(#= !# \ Vway..# (but befwe do, copyas an integer -FVallow q# us toB tha>really gets c&d)}Cint_o =c}_(  [3Qfail("It appearsk) function""A"@`actual!x^ 8pasDr... and(GCPfway :-7(/try: QueryInfoKey(int_key) !self.fail("It appears the key.Close() function "=H"does not c3A`actualH&!"uexcept OSError:PQpass def _read_test_data(Q, roo, subkeystr="sub", OpenKey=)a# Check we can get default value for this.Rval =IV'(key_name.assertEqual(val, "Dm%",ae  "Registry didn't give backWccorrec"")0ATkey =a# ReadS@sub-KEwithJ7keym@) as{p]aI`enumerate oveYegs[5index = 0|zwhile 1`>try"r = Enum!, b- Ybreak |1in  o, TrueG""DP P?6" =I + 1 /`, len(VQ) znumber of items  dily access each7 {K,* Xtype dE_l 9typ5Ex(l <NX7; a"CouldKrJ 95}8typ}=#Ozur mainszf.0WO1, "g wrong# r1rHWas able toa second when I only have oner/odelete , 0, KEY_ALL_ACCESS)  &sub_key = OpenKey(key, subkeystr, 0, KEY_ALL_ACCESS) 9"# It is not necessary to delete the values before7ingC%(although}Q must\exist). WB[mEmanually j4to prove we can :-2forc_name, Ddata type in test_:iDV(>:R%) .nC2, n, since_mod = QueryInfosGself.assertEqual(KB0, "Impty[/e"E G"v.Close(_ 2:try<# Shouldn't be able/it twice!Bph2afail("1ingZU succeeded#except OSErrorEpass?key@rootF,41key],#^sP now  ,c CgQ openAnon-Fent keyP # Us`@is e  this timeq$Qdef _2@all(&, @str=+&")n.r._writeCu(>Q3Oread24 cd_argswith CreateKeyExK=,=, reserved=0,mM  acS=~{ as ckeZ2PTrue(".handle != 0-o" class LocalWinregTests(Base"):eutregistry_workHQCURRENT_USERWS*, "日本-"W_extended_function# Substitu0vregularHA and?Key calls Utheir=$# l counterparts.!Note: DeleteKeyEx is not used here because itplatform dependent cke = lambda key, sub_key: CreateKeyEx(, 0, KEY_ALL_ACCESS)Pself._write_test_data(H/CURRENT_USER,^e=cke) AoOOpenLREADOread U)=oOdele Adef named_arguments(H%):.*sM@key_'# Use the regular DKey to clean upp# Ex takes Rd args andmed separately@^5 connect_registry_to_local_machine_work!Q# perminimal CIRHg which just invoi3=l2 SetValue(key, 'changing_v', REG_SZ, s) Dthread = VeryActiveT+()$h.start*rywith CreateKey(HKEY_CURRENT_USER,R test_key_name+'\\{) as kesEfor _ in range(1000)&num_subkeys, s, t = QueryInfo6key;mimEs8w = Enumia1+A6[0]1kfinall y = TrueiW.joinhODele  eK}2defc key(selfF# Issue2810,q2.6 and 3.1 when the  was exactly 256# characters,Key raised "WindowsError: More data isAavailable"s&mt 6'x'(6, 0_y B'\\'|(R,&))\K @ GpdynamicCJ ;C is :Q generated,_sI#43  ) 8 !h.PERFORMANCE_DATA|except OS |if e.errno( .EPERM, WACCESet|.skipTest("access denied to registryq;"(are you runnQin a non-inteive session?)"3 "ExS%#""!# Reflection requires XP x64/Vista at a minimum.doesn't have Bthis stuff # or DeleteKeyEx so make sure their use raises NotImplementedErrorG.@unittest.skipUnless(WIN_VER < (5, 2), "Requires Windows XP")B@def A_reflection_unsupported(self):+6try with Crea(HKEY_CURRENT_USER,^key_name) as ckDHh.assertNotEqual(ck.handle, 0) /key = OpenKeyv <k?keyl5R.(N)DisableR^2key~"c*/EnbM_QueryI kfinallKIsetvalueex_l_range# Test for Issue #14420, accept proper <s'@SetVX1Ex.q# Py2Reg, which gets called by 3, was using PyLong_As,LAthus+&OverflowE&. The im<a@ now]sB[Unsignedc ttch DWORD's size hD1a(ck, "q", None, REG_b, 0x80L<q2Fex_returnUOb6759, 5# u int from QoReg2PyQ5S`1!a rgenerat@FromR7TDWval =2&~z None, REG_DWORD, test_val) !re , type = QueryValueEx(ck, "@^name"Bself.assertEqual(Jp, REG_D6?valfinally: DeleteKey(HKEY_CURRENT_USERD@key_!) 92def@setvex_crash_with_none_arg()l!# Test for Issue #21151, segfault when None is p d to SetDx+trz_ Creaf as ckU#Nock.handle, 0Qval =N 2, 0cBINARYm]c^Sread_string_contain Onull[i[a25778:7SZ should not I F charactersY2"A Q\x00 a"ko/SZkj/SZg1/` @unit#.skipUnless(REMOTE_NAME, "Skipping remote registrys") class R`Winreggs(Base+):7P_Pl_works%key = ConnectR __0_alP_key) WIN64_MACHINx64 specificWWin64Ld#]ument*s# Clean up and also exercise the VB argD Ex(key=HKEY_CURRENT_USER, sub_key=test _name, access=KEY_ALL_ACCESS, reserved=0) 8Adef Oreflection_fun s(self):)d## Test that we can call the query, enable, and dis  PIon a key which isn't onK list with no consequences.LOpenKey(HLOCAL_MACHINE, "Software") asuTHKLM\& is redirected but not `ed in EOSesH-.assertTrue(QRW_key))5IsNone(EB8Dn9 P@unit .skipUnless(HAS_REFLECTION, "OS doeesuppor/Bion"i_reate, openUPeletes{a32-bit# area. Becauseare doing thi8}0get&edP#adifferza of 32 64yabeforePafter7?ion occurs (ie. whecdLvclosed):tryC6RKeyExCURRENT_0_z0& 00 D50 | WOW64_32KEYGW O NotEqual(1P.hand&4A# Th should now be availPi3iE W+ke?key Write a value to wcurrently. on@SetVF(Ex, "", 0, REG_SZ, """+isguntil DH?Aversf4t>yetM_fail = lambda:  +A$ O?IREADJ 64J $Raises(OSError, open_fail) # Now explicitly) the 64-bit version of9key@*with OpenKey(HKEY_CURRENT_USER, test_reflect_key_name, 0,F EALL_ACCESS |WOW64_64KEY) as key:Cself.assertNotEqual(key.handlv)3# Make sure original value we set is-re?ro"32KEY", QueryVE_, "")~Set a newq, which will get ;ed to 32 1Seti$Exka REG_SZ, "6"Ruses a "last-writer wins policy, so A# on"6key should bY@same%DDIREAD>>9 f/lDeleteKeyEx R3, 0P@unitc.skipUnless(HAS_REFLECTION, "OS doesn't supporWBion"2deftdisable@ion()n30useagets redirected and+tr-OCrea2H B:LKc{d>#- Key returns whether or not3is GdL/ =Y(3Ttype(Q~), bool7# HKCU\Software\Cl#s^by defaultwGFalsr KD> .QTrue(8@lQ# Theis now closzwnormallyt #area, but let's m!`at didJyhappen.Ce = lambda: =H  KEY_READ | WOW64_64KEY) #self.assertRaises(OSError, open_fail) 3# Make sure the 32-bit key is actually)re9with OpenKeyEx(HCURRENT_USER, test_reflect_key_name, 0,HG 320 as:?NotEqual(key.handlr&0fin DoDelete 3, 0s2defexception_numbers()\ FileNotFound)6ctx:QueryValueLASSES_ROOT, 'some_v _that_does_not_exist') Smain(support.run_unit (LocalWinregTests, Remote)g Win64+q) if _(__ == "__2__"if not REMOTE_NAMErprint(" registry calls can beed using" "'!_wq.py --r \\\\machine"'"R0() # These  are used tow floating point binary-to-decimal conversion.NyE baF onB TCLNpsuite (ps/expr. ), which8" #2data from: # Brig Verdonk, Annie Cuyt, Dennisschaeren, A preci and range # independent tool forq-arithmetic II: Cs, # ACM Transacs on Mathematical SoftwX27:2 (March 2001), pp. 119-140. 0E0 -1E0 15E-1 125E-2 1P3 106Q4 103a5 1015q6 100787 "39.8 219529B09766!10B4882;!11R24414@!12S12207w10006103510003051751000152587816 +8E153 -1+9E306 -27E-304 -3E-49 +B3 -69E43 -9E44F!30F)0287G-204 +2E-205,-47 +34E195 -68+85E194 -67E97 +93E-234 -19E-808 -38 -69E220 +18 36+61E-99 -43E-92 +86`-51E-783E85 -566`+589E1P839E12744z@+930 @5 -1G+604E175 -302 p+755E17"51 66r13 -408w510E-75 +6782E55 -2309EP7963E@3391@+790 6 -7611E-226 +4907E-196 -55411 +5311E241 - 3 +5311E242 +9269E-45 -8559E-289 +869 J76 -8085E-64 +74819E201 -82081E41 +51881E37 -55061E157 +77402E-215 -33891E-92 +38701E-215B*139E-76 +75859E25 +89509E140 -57533E287 +46073E-32 -92146 +83771E-74 -34796E-2M584169E229 +164162p-328324 +209901E-11 -419811 +940189a2 -892_02137803E120 -252601 + 1 -505202P9708164 -654860 +289767E-178C9534 8823691E130 +9346704-1168338 `606336 36P@6542i 25P83893E-127 +2572231E223 -5144462 +1817623E109 +6431543E-9`444097p +80769121 -9997640 +50609263q0589528-00E187575437E-31>s3135572P85900@177 -84863171E1u68761586E2`50464086 +27869144J 5738294E-248 +70176353E-53R555086-491080654E+526250918j-245540327-175150874+350301748-4378771 3B458117166E516234332+229058583-525789935E98Q29268z2a6585376672841130 -9712126c126 +998139<PE-18235231965E-156 +86@6048`637114 55 18488827E79 -3981006983E252 +79620e6-4713898551E261 +871538E-58 -9078555i0423338424CT4667684902e+23792120709q5 -785640215171812054888 -3031116363`1803914657E26314223356E-P181577"78@-4530919D 10 8380362293E218 -685763015652918668151E748357443505E32486500490869730009818 97015418417E-93 -915654049328 +1785L 6339E169 -742522891517E259 5709731267863113521449172+P901815E217 -1556760724 18w9787850756X9 24Q0291579 +362371457 `0092@9832@00 +p8579205 59360849E94 +(845954547E49 -*691909094+556032250192^78128784892674393985330.256 -27801613<87605699161665E155 A21133 +821810136350170 63P3116215 +35593959807306C-533909397109171187919614612(08899518265E2(70036656188 7340073312377k 2 +61602932495116E-72 -308R01466247558E-72 +834735494917063E-300 -589795149206434E-151 +475603213226859E-42 -294897574603217+ 850813008001913E93 -2034g 2043339E185 +406898344086678-813796688173356.+6045338514609393E244 -5145963778954906E142 +2572981889477453&-6965949469487146E74 +6182410494241627E-119 -85103094F6985E-277 +6647704637273331E-21215901545757777+3771476185376383E276 -3729901848043846EC,7 -9977830465649166E+8439928496349319E-`-82042u2070882E-59 +8853687955327427228855D04 +36149023611096162E1. 7 +18074511805548081E146 -7 +9733877413 42>90 -8813380980495vP8 +94@5590268239I46910027326548815 +52306490527& 14E49 -26153245263757307 +55188692254193604E165 -5865317742005E164 +2717625800531916 61 -73169230107256116E-24 14v763407014?54352516010Z8261 +586144289638535878E280 -601117006785295431E245 +29307214481926793909531847132)`6652E2!9058290366539E-281 -55703p1898546_294 +210 --4100507554@-238$2104041512242479E19J16312124536727437+544208083024484958-79264492 378159E78 -67940645013297917TM63 +T 0E-262 +740025369568292019k550063423920730049E215 +370012684784g1098 -9250317119603650245E214?9609430056977960252(07665085003296275 +701533006592562E-75 -4 +7185664951919351E2036052020756c`395E19`178999y`451517`184 -8;894862015671028 +43455447431007835518 -43579983706903034N+5982526734912461E177 -6225914h57791E47@3801d7038565599E2|3 8 -33584377202279118724E-f 57;P63479q50E204 -143712q99038387024369920847601776241373984169520355248354E-+992577632277-87336362425182547680 +7E289 -3E153 +6`-5E243!-1_0E-1q8E-63 -3 +8E126 -4P+5E12 @8E-1,2E-163 -4E-163 +51E195 -37E46 +74-56E289 +69E-145 -70E-162 +56 1 -21E-303 +34E-276 -68 0+85 P7 -87 4 +829E102 -623E100 +723I2 -457E-B+914 !-3P35 +1^302E176 +921E90 -6048-p206 -46U 14q4 +9968s|0E99 +1246+6676E-296 -834`97 +160333I96 +3257E58 -6514 S+24160063 04E-*A1617 0-6453418E111513E160 +2670999447E166549E48 -25098 `+50196 -62745E47 +83771E-73 -97451W0663q03 -75554 +473806E8/P47612 +292369Ei 58# P+9335140 -72091p +53500j49 -89052548057E814p6181E88`0997E1320681E638609E-261 -3022A1511z 4691773Ep9383546 p+305994@43 -611989!43066213 -4877378E-1 773E223 -5452869 +4590831E156 -9181662 `371443P61 +46430062 -7428872p+529421b30 -27966061EG+26471073E15593212295412548E-99 -4770p+23853178493654 1 +65346417E29 -51083099E169396333E264 -84863171E1#a5954085B442652 +1488520]P29770-251 +982161308E122 -245540327p+4910800+52dp622E-31Ip71837113`085808P53p6272631a 10&3091487E2093777767E273 +84211625 41 02`950724 `84 -95J2 @0E12Mr6778560~ -35737968KP71475'0981f0181) 68P35E276B10681307555534299067111149533557P90 +5c 42p-"@7476v0191a25968419j0932Gp7727E-4112984209 #47584241314 -79360293406E9 7332259349E225 -5720232611y6860597053E-5382701064F@1074?6?7636765E2508006109412E20`54003054706+561029718715E-Z897647546E-71 +1122059437~ 71q3947086a236 +80918470V@E1163P17422+286556458711952805821491E-259 -132189992873E-44 -1736960394 +183113275759= 07Y 55P879958 +732453103039c(2773388949) 8188292423973E287 -5672557437938E59 +28362787189 9995153153494E54 +922478 6422069E-291 -31422131649874 +6284426329974<-8340483752889E-301 +67039371486466E89 -62150786615239E197 +33519685743233E'<52563419496999E156 +32599460466991E-65 -41010988798007E-133 +65198920933982)82021977596014E)80527976643809E61 -7471261150520y8 +53390939710959E2(69277302659155E225 +462e2337E-72 -23438635467783E-179 +41921560615349E-67 -92404398742674E=`+73854(`647197E124 -972708181182949E117 -837992143580825E87 +609610927149051E-255 -475603213226859E-41 +56300280067102351206426453718E+80541643265hE202 -530658674694159 +94657417p918E208O8753318553E113 -90E-73 +369617594970696O0+36:6212014994E233 -1833078106007497+8301790508624232E174 -10377238135780290+7228805811386 -51061856989121u 276 +7487252720986826E-1374362636049341P65 +3)`0100250 -75461`020051!0 +4321222892463822E58 -7793560217139653E51 +265!39b681E11a5198781362 +7871414247907E768839359596763261E105 +187181318024670656 -149745054419736525 +734293960046400=8483921078P83E57391519190645203E<82783038381290406+5876704370267@63 -6231831231#-129 +6440Jp7698616-427432277771E-19p76592356619258326E27`53184713238516+899810892172646163E28029167076x13E147761278967534 -306447982054294M80 +9261453446107000125 -95850793189651196z46 +27210404151220E20b92644927852378159E}544208083024484950`9963218105E2#0305`391668o2E-219 -15278716955c11P7833302 76o847917025255E-220Q39550220920702E13751104603993 58' 9976150998265E157 -7@9051x@9597bd3507665085003296281i`-70153,00002562 6687622782559561088416166048"16t870732932839"32^P+443981608558002p8780435{0711E`+22195l080427900@+33039519049M 2E52524140903677624E100E11403066034001318512x4E-73 -17538325425016481405E-74 +67536228609141569109E-133 -35620497849450218807E-306 +66550376797582521751E-126 -71240995698900437614E6p3E24 -6@+6E2-E25 +1E-14 -2!+4!-8!+5(@8E27(Q27 -4  -7E-20 +56I1-70\ 515 +7X7 -31E-5 +62`-94E-8G2-8124E23 -54G+63E-22 -3 +43E-4 -86@+942_A-471."80@6 -4A21 +818E-2197t!53A-857v12694B6 +959E-7 -P6 +377 -746E- 4034e P3 -81UP4 +8215 -4147= 35 -44 +@2690+@2152C+172:B7979y06887; 18r817 -55684 7885819Q2620  0E-16 +89309HP75859- '04253 -28514E-23 +5702h 3 {85E-24 +344863p-951735 q+200677@4013:@39601 -209901 +419801 -53773r4 +910308@2275Qp6 +4551Q6-A1013P96301DD@19823 34\@3117tR96136-9191316+4595658 -2297829 `167920,1 +337922q6758446`544409;P399967 +83664866 - .S50606q6521238sp+55544913P10409p9958576k72 -Fq09783939`674881a900533_-8195678 87105552Hp+108881Vp21776381 +635806667p-670026z335013307{5d`179061V4 -375 +7435812-5 +2024644`049289%`978537+`0549841>a825790aa082476*a8 -291V4q37100000127161333%522964699.96 +7 +4429943(859887228p221497141768870+400349500 -GP90163J3 +8723803276b0069900 +72835110093641755504Q+8427>0-`4 +212!64q7 -6646156692 +6480835553-849326796X19 +6520543009406835 34^260271504;6266220342Y878444467P8 -503"031 +29392222-18 -755t303293749590629p642485720 -38782415A@9249A2472 -775648301398E-23 +547075707432E25 +683844634290E24 -136768926858"!509802033730E-22 +101960406746E-21 -815683253968+7344124123524Y"9180155154405E23 +6479463327323E27 -18360310308816+4337269293039E-19 -4599163554373E-J91983271083 +4812803938347]@8412ZQ900119625607876694$473996882824996971838916n-7368108517540 +5146135816142Z-77192037242133E26 +<5 -97 +43999661561541O-87999323123082+48374886826137E-26 -5768424656711<@3 +8@805960-75+130059136423311058748177577471133384j48485919458365E-356908598265716 +58972229462052835804449289EM-656415363936203 +57933674958574g5 -3812927649808 S965265859649698848925235434882+53617761222249p-424462Q17441(27600927988897 -60892710369W52018559777977 -425678377667752 +8013702A7119 88626279620~-506800790{0162*-737971479982840s114538064016107 -368985P91420O57595485181547&+33957009417395284115535701963 -823107155516392655024669619087,@6 -60464039867+43566388B8364`871327q1567286488105934215 -83852770718576667+9948296741820oE-25 -6 4466699699946137233349849973L +5-1  -4@+2E-aE-6 +4 g20 +7+-001 -02 -u1" 97f+14 -C4 +7!83&!50 250-99p+97E-10pE-20 +9L3f6T@-388C+521)<>;P867E-1"+33-66P13 -9802E-D-8 +45742860 22?b6 -481q6529E-8'&`1 +155P2 -25W1K9'p16 -305S@2 +9- 7711 +5433k@-624u`5 +328X@7 -8 1638Gp0 -1596p0193a0 -798\19301-251988 -9@+810p8 -4314S5 +405018m67J`+72091p4 -6297#57P-8478B6544R73653#g R52998`+382928a3 -633X2165479E27 -8661916E27 +4330958 -9391993E22 -5767352E-14 +7209190E-15 -1441838p84789903+1473062E24 +8366487%-8399969E-25 +936673 2 -9406141E-13 +65970979A-65060671E26 +5492300263846927EN0958E-21 +67488159-6900533O+8195678p-409783 7 +77505754E-12 -3875287+82772985 -9559351720003698m772686455 +859139907E23 -400073978+56901432c4 -79426386j5 +39713193s38039895- 67> 73f-3374407951+13497631f-269952636t93208059`0 -3312 5 -413864905E-16 +8539246247|"-5"79610501014X-3090745820+3470877773E-20 -6136#87 +8917758713E-19 -69417555460Q+91945-h@9801I6 +73559204283677960214+847363434\7 -8870766276 +44353831|691129+7156349676P-8945437095 +178908741 -3578174838257973447849 -28986723929 +768227113976994668 20p7486567G7 -193948409t4 +387896819t48743283815432376388Q7 -589871938b271618819'27 -930426480389 +52083105907 -76812$0394+3840621321976533774985 +7943689127=`9416206+7816527)Z91007719006 -45503859502P71897551090 -90669"1885412800393GP81461zA6299(708330240314M54165120157+839492064929[5 `575675273834002228-6842292502785-210956888425 +84382758421913776hP20014x8$25 -865568932260@2 +6}83579682@-883JP634491 +194282170752=8856434150577128683011719203724213y7+760E-23 +1531595151350Mp7878376 p3 +4937l@92525 -50940527102367@9875Q85040u-9958939754489r-Kq8598265RX974706956996735851901247(0154r744842603084c!53n+91099038198527174242416920j@43483X`7 +162>083356P92545 00]@/306262A3241 13P24 +918290414P4 -10P05420B0828p3966696+7 -280276135608t777E-27 +212839188833879E-21 -113817196531426E-25 +9711553197796883E27 -2739849386524269E26 +5479698773048538E26 +6124568318523113EUj`977798p 071E-24 +632261230312801l955864564844615 -9994029144998961E25 -29712383240220871656055679333934-144548870915026 +55824717UQ85172B6978089687485646584161538867545199p7912358CP42586B+U1112462926335 -1264522460625603822491366370462748744482874657535642836832753303E24 -71285673665506606+43723334@9730L6 +1018241P537964 -93501703572661982E-26 # A value that caused a crash in debug builds for Python >= 2.7, 3.1 # See http://bugs.python.org/issue7632 218316701231211312.23538020374420q92e-370cnotherdesigned to testorner case of's strtod code. 0.9e+23 import unitgsys from}A.sup'._fresh_module, run_G TESTS = 'V.datetime er' try: pure_Os = X(I!, l4=['J', '_strpW1'],MQ blocked=['_I!])<Ofast#?w  ) finallo# XXX:Q) is to leave sys. cache untouched$R but it does not, so we hCto cleanup ourselves.for modname2 S cs.pop(K, None) O[&, ](qsuffixe)"_Pure", "_Fast"] (gb) First all the - s,n>. You might ##p believ?Ais, Aan spit^ trickerybning a}! #e last willPa mix and native Z stuff lyMround. allb_class3] -Hzip(h,_!2es)" ORP, clsMh.__dict__.items(D2!if:isinstance(clu7ype&*continuegif issubclass (cls, unittest.TestCase): _classes.append9)%elif issub& VLSuitWsuit = cls(Kw p0extpPtype(`) for @ in D= = sorted(set6), key=lambda{:.__qualname__Oe0clsdZbcls.__3 += suffixV#@-emethod8def setUpCpJ_, module= cls_._save_sys_$s3ys.[.copyes[TESTS] =i('datetime'-.{=\_strp>8tearDown o.clear0.up`>V$ 9 = *Hall_J.5est 'Smain(Drun_,(*Je) if `== "__?2__"Q import socketelectorstelnetlibhreadingacontex#S from^ upf,` HOSTF .server(evt,  s.listen@evt.2tryonn, addrcerv.accept:#c.close ex".6outSApassgfinallmJ  GeneralG$s(VKTS(self0.evtoX.Even%.2et(.AF_INET,SOCK_STREAM4k1L (60) # Safety net. Lookqe 11812APbind_ r T (target=Ver, args=G)QDaemon(True$=tarIN0wai 0.jo3Adel FC out any dangling objects. Cv|stBasicw`# conn.,oG!.T (QA0lf. 3.sock.close()  def testContextManager(self): with telnetlib.T p(HOST, +.port) as tn6=assertIsNotNone(tn.get_socket())h .+,TimeoutDefaultNRTrue(p{d1t?`() is K.set,&30%:try#/ =,!kfinallH~ Belf.]bEqual(.?), &close() Wm T#(, having otherEDy#, =4hf* 0Val =m=ALOpen=$ .o? a[|Gettersc# Test! g% methods&?\R", CW6fileno()2.;.qclass S&Stub(object4`''' a et proxy that re-defines sendall() '''~__init__v, reads=()W\ = list( ) # IntentioR make a copy.a?writes = []block = FalseDl, dataQ.append(">CrecvGsize;sout = bRwhileR and len(out) < A rD'+=3W.pop(&ifA> size:  self.reads.insert(0, out[size:]) %Qout =:]`return class TelnetAlike(t Blib.!):9def fileno(l raise NotImplementedError(:Sclose9U passTsock_availXB(not+f.blockY1msg8, msg, *argswith support.captured_stdout() ass .c ._messages +r.getvalueXvrMockSelector ds.Base1): f@__init__+f~keys = {}0@property>resolution@R 1e-3=mqregiste!f,obj, events, data=NonePkey =@Key(7A0D[,b] = ke!/un7_D.pop)s, timeoutx = False4for 0 in f. Sif isinstance,vWq.~'Ubreak1if <  [Oelse$P(key,. ) .Fs()]Jqget_mapK} @contexti manager Ptest_1et(Nnew_conn(*ignored jSocketStub>6try1oldF.q.create ec.5V!4 = ,`yield gfinallxL9 =(), cls=B''' <2 a 4d) object that uses a , /}w queued up to be A ''''xs\ as type(x) is bytes, x7g { =('dummy', 01!x= '' # debuglevel1putprJ5 ExpectAndReadTestCase(unit.VxMsetUEGor =v_w "7 = r def tearDown(self): telnetlib._T Selector = +c.old_s class ReadTests(ExpectAndCCase_def test_read_until~5"""&eVed, timeout=None)+V the blocking version of H5til/fwant = [b'xxxmatchyyy']," =(5~Adata!:.o!b'Q'+BassertEqual(<&, }', msg=(i.cookedq, 6raw AsockoEs)) s`' * 50` y] = b''.join(CV[:-1]2st_)$" &") 1/al/$ Q all s EOF; may-.9 EF< zH0I6"D C: returnHOsomex%Jt least one byte orP#?< 'aA'hh %True(lenkf) >= 1J?EOF 2|Ab'',Qeager, func_nam. 2_*_3available aly queued!on%85et, without?ing'x5100B0B = getattr O..0 = !ca&() GUFalseH&b'Qwhilen:try@!+=(y`except^Error<Ubreak [ , C6 :]t##B andBvery7 make the same guarantees  # (they behave differently but we only test theC)Dself._read_eager(' ''Bvery8,p# NB --vneed toIAC block which is mentioned in# docstring3not#q module  0Adef Plazy(!):0want = b'x' * 100Ptelne)_ ([0]assertEqual(b'', -.z)7Twhile'Asock,sFfill_rawq(@ddata =A h. , >L%Raises(EOFError)\\buW'jKTrue]*ryrE~hT+*"+=b "0if E!sHktexcept DYbreak|(.startswith(8/ , 6) class nego_collector(objectIg__init__a, sb_getter=None(lKseen6& =B#>0do_~ock, cmd, op ~ += +!F!if== tl.SE and v ~0sb_+1WC+7E tl4libkWriteTests(unite.4CasJT'''Thh `that w:P doesCreplace eachf1forrtl.IAC+;'''IM_sample = [b' Xout IAC',c 34' ++ b' oneC Ya few8 AFiacs3Eb'']1for4g $st/f #.\I tc.join(2"es) self.assertEqual(data.replace(tl.IAC,+), written) class OptionTests(un0st.Case): # RFC 854 commandscmds = [tl.AO, !YT1BRK"ECL!GA!IPQNOP] Hdef _test__p(self, """ helper for 1ing IAC + cmd """P-telnet ='_ )#__len = len(b''.join&'pnego = _collector( \a.set_oL_+0tiaX_callback(1.do=x.read_all]|U.seen!PTrue(cmd) > 0) # we expect at least oneGIn(cmd[:1], ^l-C1:2]?OPT-k,j2txt)3sb_getter = N# break theB => pf cycle@D_IACCsD>3N&in/ E_].b'x' * 100:, b'y'*100DCBP# allJoncet<() +])L/SBK`5, subPs por#nd#ptl.SB +-%E,1[) 1: SC#Rb'aa'eKLb'bb9B Ob'ccKLb'ddS]= Fsend90sb_3CuX0txt0'Swant_  UL) v@.sb_e(, r 5Cb'', ;(= debuglevel_reads(self):  ,# test all the various places that self.msg(...) is called B given_a_expect_b = [%# Telnet.fill_rawq(b'a', ": recv b''\n"),$CprocessFtl.IAC + bytes([88])V`88 nota~ognizedc(AVtl.DOI1HODO 1;/NT=/NT?OWILL?~ /WO~?]hfor a, b in:&t! =<__([a])&.set_debuglevel(1%!xtH read_all($assertIn(b, r._messages/qreturn 2def~p_write(Q)O$stT!\fb'xxx'>ed = "send !1\n"O.13 _accepts_str_port# Issue 10695AtBwithsocket([]"# =Alike('dummy', '0/U = ''oMDg'^cRegex(Ms, r'0.*7 class EbTests( pAndReadCCaseOy ?&"""ed, [timeoutdR untiS. string has been seen, u G5 is2 hit (defaultw$no(); may block.20wanX[b'x' * 10, b'match' yS E(_,_,data)'$([\`Equal(;|p'.join(][:-1])) if __name__ == '__main__'@unit.P() im contextlib$os %sy tracemallocQd from c.mock ]p. {0supu.script_helper-(_python_ok, zfailure8interpreter_requires_environment)R try8_capi except ImLportError: _testcapi = None EMPTY_STRING_SIZE = sys.getsizeof(b'') def get_frames(n, lineno_delta)fas = []vWA_get2(1)or index in range[Mqcode = 80.f_<+/Ds.append((K.co_filename)aJ = 0KyEback"if1 isjPBbrea,return tuple()lallocate_bytes(n( = tracem)_r_limit(@q_len = G= - +Ydata = b'x' * \#,T 0cresnapshots( Q = 2 a"# MBs() ~s a list of (domain, =,B])}"s._aN%Jju_numberE3raw (0, 10, (('a.py', 2), ('b B4)))-CH1, 25-Q2, 66.01),"A3, 7!', 0& S(5<)"2X2Xy(2, 500 C4, 4/c0?578d )e2f($, 2(iL~~_Frame(2P!(*[sKIB_.nokq) +L{07class TestEnabled(unit. CCase\lsetUp(self7)ifZ!ish4ing; self.sk)ipTest("tracemalloc must be stopped before the test") 7.start(1def tearDown(self):69op(4wst_get_[|_memoryGdata = [ate_bytes(123) for count in range(1000)]wsize = g.w)4elf.assertGreaterEqual(L3, 0WRclear's(MOize292~tFLess02, tSobjec{Lbackr@obj__ = 12345<Pobj, E^; = =%-  6obj:?x s},l_limit0Raises(ValueError,G4, -I>F 0Aobj22wA2sxAlen(}G), 1 -) n   BfindGsnt] sV"ifS[2] =D{._frame.2breturn6CfailU not found9Is"?i( +2 = s@10?IsInstancev, tupledbdomainTo@ Q)tEqual(traceback, obj_trace._frames) malloc.stop()self.assertEqual(,B_getYss(), []Tdef test r_intern.(Z%):i## dummy wrappers to get more useful and identical in the YRate_bytes2(sizeuzreturn *)K3"KuL4Lv# Ensure that two s are not duplicated& Vart(4TNe = 123OAobj1q1+ =^$4(> P2929s2s ={(` <uple(reversed()II @1 = R.findXjs29 |9domain1, "1,8;V1,2,2,y,2,,"IsV61 "d_memoryVPythors some P0alsects, so est must tolerateP# a s" difference betweeFexpectedp\real usagJmax_error = 2048KC one7024 * 1024Roc.clear s1obja `_a, peakk:rGreater R0|L 8FLess_ -?%, rk9h! - :i# destroy3eobjectobj = Non2ABR g / -ssertGreaterEqual(peak_size2, C)  # clear_traces() must reset d memory counters;zmalloc.E#self.assert42getw"d_c(), (0, 0)bate another objecte@obj,Mtback = 5_bytes(obj)6" =:rGreaterRj1# stop() also\sn]>OU,def test_U%):dT6123O| I:z$IsNotNone(CO W L#722:!is@ing(8CFals,R OFart(z8?TruOsnapshotnsource@# take a L /_(O# write on diskH.dump(support.TESTFNddCleanu(unlink, 8_# load fromx @S5.8 !2.%s,2 $!be'4ingions toJ.Wwith < Raises(RuntimeError) as cmS  Wtr(cm.exception),0 2"the_odule "J& "u _save_attr  G`a new 1Uibute /.Ov = "new# elf.addCleanup(support.unlink, TESTFN) # load() should recreate the attribute/ snapshot2 = tracemalloc.S.N nl self.assertEqual(O`.test_ps, "new"def fork_child(A%):iif not0is_Ging()return 2obj_size = 12345XPobj, Keback = ate_bytes(=)6- get_objectP?:"ifjvis None3# everything is fin0/P@unita.skipUnless(haso`(os, 'c'), 'need os.2()'?_ # check thastill workQafter3Vpid =p:pidm5ild(qexitcod :try> .]%ofinallB@os._t(y8;elspid2, statuswaitpid(pid, 0<t True(os.WIFEXITED(E)2e@os.W+dSTATUS/ `e? class Test(;CCaseVmaxDiff = 400h(C_ 2raw  [(0, 5, (('a.py', 2),))]with contextlib.ExitStack() as]*ckss.enter_9r(patch.(6, '4)',0~ hp_value= * o_limit*5+_s*)U" NFtake>  D.:?, 5: 5len>Zs), 16V: = gIs[0]+ 8."0b2ck[0].filename, 'a.py') self.assertEqual(trace.back[0].lineno, 2) <def test_filter_- s(K!):"asnapshot, 2 = create_&s(NA1 = Qmalloc.Fd(False, "b.py"4Y40Tru3"j3j 657original = list(5#s.9# exclude "ED"((61,)h <35, [l(0, 10, (( @, ('', 4))),1]H1, 2/5) A3, 70', 0),]{BQ) must not touch the l kDi ronly in@two RPs of m254 =*3.22, 34 #No0: jduplicate, u5u tdFIsNo5 .5<5+<Raises(TypeError7CR1_domainS2", s&=1= !^% 1\q', 4))),   (0, 10, (('a.py', 2), ('b d4))), -1Q2, 66bU=1),VA3, 7$', 0)5]) # include domain 1snapshot3 = .filter_traces((F1,))7elf.assertEqual(<"3.6.>5, [5#tdef test_: _}u(self):A,2 = create_&s(\A1 = rmalloc.DFs(False,,=3<a<9Tru;I# exM2MA1, 2"5"   {!23!_group_by_line .Dtb_0AbackVJno(' Utb_a_ 22,-5_-5-%b_ Z_c_578\cT9578stats per file and CT k.istics('+6no' `1&AStatPr(tb_b_112a_2, 30, 320a51 ED' (stats2 = snapshot2.statistics('lineno') self.assertEqual(.Us2, [#*tracemalloc.SP(tb_a_5, 5002, 2),4c_578, 400, 15a_2, 30, 325]) s!#  diff per file and '%c = sna%compare_to(/, /O3KDiff7 502 ADIAb_1, 0, -66047;?, 0def test__group_by_(&):, = createC&s(qtb_0 = AbackVname('$/Ja.py*b*b*c*c*'s1 *810b, .0a, 32, 4M J0, 76 (2 2   5c Ka5?#dy}yxkp& tbj!('RM1 ('5A tb25), ('b.py', 4))  tb3 = traceback(('b.py', 1)) #[ tb4%', 0*stats1 = snapshot.istics('g'\self.assertEqual(1Us1, [;malloc.StatS(tb3, 66,/1, 30, 3)/O4, 7]J2, 2.5]) !# per file (2;tb5bc<578_2_2`$2``2, 5003j5, 400 6Ediff;Tm2.compare_to(/, xLuDiff(tb 50 >',/<p3, 0, -1;4;7:=@Raises(ValueError2  , cumulative=TrueXdef test_A_group_by_1(%):5,,RecreateI(s((_0_fname(' /a/a *b* * a__lineno('T), M9_a_P -5Z b_Z;Ytb_b_ Z-4#$('W2', E$(, 98, 5(0a, 32, 400&G */no>_1, 66, 1),  tracemalloc.Statistic(tb_b_4, 32, 4), -2a_2, 30, 320, 7, 1/ja_5, 211]) def test__format(self):!snapshot, 2 = create_5s()1M% =/.Es[0]#c.assertEqual(str('), 'b.py:4: 10 B'Xqback = ,YY']WTframeS&2 LNsR5QsRus('lineno-?tatu- K1: size=66 B, count=1, averag'TZ__diff E2.compare_to(/, Ma55002 B (+5000 B)"f2 (+1)'A2501 /_licesw.T'Zs[:2] =/&0]31])32n m"0]41 B )~~Y.Z0geth(filename, 'no(return ' <%s, %s>' % 6with unit.mock.patch('dlccache.'side_effect=7 /tbP9elf2tb.l(A ;[' File ""=/ 4'=<4O, 4>/ff270 <4T, 2>'| self.assert Equal(tb.format(limit=1),  [' File "a.py", line 2'7 'U<4, 2>']) hself.assert-b44?, 4most_recent_first=TrueBTqIA/, jY /c. class TestFilters(unittest.aCase):2maxDiff = 2048F@def ,!_f=_attributes(Y:#( default valuesXVtracemalloc.(, "abc"),Y f.inclusive, 3, filename_pattern` IsNone(f.l/noX all_frames, FalseiocustomD0, "_W?123 C  p8 _, 123( @# pa/t pd by keyword'=,, =9=@4iW f 8 K,read-only Raises(AError, set7l, f, ""!R ^match without line number  f = tracemalloc.Filter(True, "abc") + self.assert (f._match_frame(.O, 0)2521e]Falseo12356"5 5 8dCe ! 33g 344 e1# f with line number > 0&h?, 5 Ve 4Y)"ji j 7ei34 hf0V j8 kXrue(f._match_frame("abc", 10))  self.assertTrue(f._match312356", 4!5h def test_filter@ilen!):*.!fn(inclusive, f/, pattern37f = tracemalloc.FlB8j7{return -m50) 0 bo#, /dFalse(68"{) u168p_joker(w4DHqM7C Gr# empty stringL1CQ'abc', ''} -*1-Y,V)**e# no * :!,  0dpa`10def0?# ahl0b/Aabcd2 b *c / 0dcxOa*cx3 b10Ccdce3d5b*c C/*ex bbdefegz_bd*eg9 2cdd6cm4nf8n # replace .pyc suffix with'7]?.pymatch('a.py', 'a.pyc')) if os.name == 'nt':## case insensitiveself.assertTrue(fnmatch('aBC', 'ABoJ31cDe5Ib*dE<8 PY7.6 mXa.PYC6OelseOFals 4 97 "normalize alternate separator "/" to the standard%\"jr'a/b', r'a\b5 \5/5D/b\cl//9\9Mthere is no: v 6 6: # as of 3.5, .pyolonger mungedE5.py5* lo py4def test_fi_p_trace(L)t1 = (("&", 2), ("b.py", 3))Ox"t2(4(5(3(cC5('', 0-2 %,Af = malloc.F(}$, all_frames= .wback(t1020aKa1\/(fpy", all_frames=True) self.assertFalse(f._match_traceback(t1)121{a30unknown)) Af = malloc.Filter(, "b.py", all_fra<:> E<4C?, " z % 0l)1 class TestCommandLine(unittest.Qase):U@def _env_var_disabled_by_default(>0PQ# notsing by (Q!code = 'impor*e; print(!isuing())'Eok, stdoutberr = _python_ok('-c', q6# =?.rstrip(!dEqual(h!b'c'r@6 skipIf(interpreter_requires:ironment(), @'Can5arun -Er s when PYTHON env vars are [2d.' ignored_with_E2"""V*W_is must be G-E is present."""^VFE', , TRACEMALLOC='1^ = stdout.rstriSp() self.assertEqual(stdout, b'False') ,def test_env_var_enabled_at_startup(L!):/^# tracing at $code = 'import*emalloc; print(=@.is_uing())'EDok, stderr = _python_ok('-c', q, PYTHONTRACEMALLOC='1'# =Vo.rstri/?Tru.^limit and set the number of frames-1get.beback_~6?0741IcUcheckdqinvalid<1, nawith supB.SuppressCrashRe(,/failure(4E}'pass',WCstr(BJif b'ValueError: must be in range' ^Oereturn^ #: G `X.(f"unexpeced output: {o!a}") -3for(-1, 0, 2**30&ssubTest]=d 2O4 sys_xoptions|s ('Z', 1)* /=1"5#5F= )];lFX', fN% 0.enf('ascii')_Qargs = ('-c=%s' %", EB* if b'V"alueError: the number of frames must be in range' stderr: ereturnif b'-X tracemalloc=NFRAME: invalidm\self.fail(f"unexpeced output: {a!a}") def test_sys_xoptions_(N)Qfor n(-1, 0, 2**30&Pwith >.subTest(8= .2-_check9P@unit.skipIf(_ capi is None, 'need *')apymem_}0# Issue #21639: C that PyMem_M8A(0)  enabledm# does not crash.code = 'import; ._U); 1'D assert_python_ok('-X', 'P-c', pO) =#`class UCAPI(3asemaxDiff = 80 * 20g\setUpk(if@.is_Cing(QD q ("&<stopped before@Fdomain = 5H^ iz:123aobj = ate_bytes.size)[0]a # %/type "object", id(obj)paddressNits memory block"q# This JiDkygarbage collectorPptr ={tearDownmbZ.R(*1get\eback98s =_<.,)2ptrGie#U >ToPOelse?Xr, release_gil=False,'=1.i0 =  6, 2._KG a,w$ unz- "d_ Q# Get~0ed I snapshot =Ttake_(>`_filteaZ!.DFS(True[4DWot = snapsho t.filter_traces([domain_C]) return sum(+.size for  in snapshot.1s) =def checkck(self, release_gil):(hnframe = 5Lmalloc.start(%^6=*1getoed_memory()[0]3h@s = 'k($, e-(assertEqual.guback(),3 Tk2)Oelf.h,?i2tesh[_False;_withoutG# that calling _PyM_ Ck() GP hold'uthe GIL%# works too ?Truqalready22posVtell(=s" J[1:]U1fp.:pos;nj class TestCRN(GenericUnivq = '\r'Q" =#CRUCGV,l`, unit./ase): passF!PyHIG$LFn#LFUV1(H&CR2/r\L _.P 7 _None)  vu)#))k R}3 LUMixed(b, '\n'aSMIXEDc d  4 N if __name__ == '__main__'eP() im_ filecmp$os shutil import tempfile import unittest from  0sup# class FileCompareTestCase(?.): def setUp(self.name = aq.TESTFN8 #/_s(P + '-'2MdiffZ22data = 'Contents of  go here.\n-Afor Ein [%, m] with open(K, 'w') as output,0p.write(%) Ls_, 'a+W S'An extra lin)`Vsdir = t0@.get Cdir(tearDownos.unlink_B" zst_matchingf fassertTrue(bcmp.cm%),|"2ing!Pto it!v fails".u, shallow=Falsebxdentical- +0st_>_erent+,KA"Mis!ed2s c1_equal0z?dirt and directoryv cache_cleardfirst_=< nGosecondO O_(5len-o) == 0 Q not ed after callL$")2Dir&(?tmpr Le)os.path.join(?{, 'dir'dir_same = os.path.join(tmpdir, 'dir-same') self.dir_diff = os9!5') : # Another dir is created und_l , but it has a name from theLignored list so1should not affect testing results.@G  H'.hgcaseinsensitive @normv('A') =\aSdata = 'Contents of file go here.\n'#fo@1n ( B%, %):Oshutil.rmtree(PFTrue%os.mkdir "ifa4andO }\ fnPFiLe' # Verify S-TcomparisonOelseWJ?`with open(fn), 'w') as outputYp.write(]'/2'l h'An extravdef tearDown.=,  ust_default_[sassertIn('H,cmp.DEFAULT_IGNORES[0cmp'T (%O 01, [s '] <(&@, []/),,""C ngectory tv fails"*. NP# Try_shallow=Fals c ~N it+&9Add different file32 +with open(os.path.join(self.dir, 'file2'), 'w') as output:CJ.write('Different contents.\n') 3_assertFalse(epcmp.cmp s,dir_same,Cv['_]) ==;(+2], 2' /])j"Comparing mismatched directories fails") def test_dircmp);# Check attribut@Bor ceson of two identicall1lefba, righ 4 = 9, C6@d = mxI)0PEqual(d.0 , + -"ifcaseinsensitive& }[~_list, d.`2],['FiLe']]p?els]6@ ] d.common`'-Lonly, [* +:_sEdiff1expected_report = ["9 {} {}".formatK a%"I# :6']"]nL_2(d.+, zr(vL(zOzuEDF*vvjQ2s }+ pOnly in[=2']d_<Zal files : ['file']", ] self._assert_report(d. , expected%) 86# Check attributes for comparison of two different directories (left)Nleft_dir, righ 1 =  _N6shutil.move(os.path.join(<!, 62') 2-^) @d = Xcmp.dircmp 0hEqual(d. , 6+ - Rqlist, [']9 f_:1 ecommong- Donly0/2'1 2+ Psame_s]\ I1\ E = [)"9 {} {}".formatb, c"Only in=:=2']F 7Identicalo$s <>7AddM2with open(\ 'w') as output:HC.write('D contents.\n'hK4! l!+F (HI"<;ingW+tdef tes_partial_closure)?dirI~4oH ,P c?ful`._same  d = filecmp.dircmp(left_dir, righ 3) expected_report = [# "diff {} {}".format(self]$, z_same),:Identical`s : ['6']"*]4Ls_assert2(d._full_closure, !) EKdef @T", T >_lines):Dwith sup.captured_stdout() as 26 e(ai# =?.getvalue().stripplit('\n'A.hEqual(R0 test_main(run_unit! (FileCompareTestCase, Dir) if __name__ == "_]2__"N() from lib2to3.@s imWa load_  a'a'a). print("bse"sY.rPverbo is_android, check_warningsdlocale%sy)UcodecG class BaseL;@izedU(c#|#2 =@for s using a real U#@0amethodG`setUpC8(clif sys.plats'darwin^Z!osT tlocs = ("en_US.UTF-8", ISO8859-1"0if @os.uB().release.s.')[0]) < 10wS# The work fine on OSX 10.6, I (ronaldoussorenP# haven't had time yet to verify ifcsd_5K(10.4 is knownEnbe badweraise @Skip !("*ex0Macis minimalM+elp.startsc("win"[ EnyEnglishS*ses4 sUS-ASCIIwIu:tryt2old# =0.seBale(.LC_NUMERIC`4ploc in 3s[ p[l,T r:dexcept^Errorx)continue-Ybreak,elA<t("Test locale not supported " "(tried %s)" % (', '.join(tlocs)))Kcls.enUS_locale = '#finally:+0.se+Cale(LC_NUMERIC, old!) <def setUp(self)Q)2 = 2Y,.V_typeaddCleanup!, "<  rH#if verboseU print("testing with %r...O#, end=' ', flush=True) class BaseCookedTest(unitX.CCaseJ#e#/ :@for +@s uscFdconv() values< *_override1I" =mb_UVtearDownR ${}C 2 A |C "C"A = {'currency_symbol': '',decimal_point.frac_digits': 127:grouping': []@int_uqW Mmon_!|thousands_sep=n_cs_preceden3_by_spacen_sign_posnqegative# vpv pv pSvOposiv qOEnUSt_en_USx)$ y2_3, 3, 0~ HUSD z`C " # ,  0 -q : q 7~!,'} class FrFRCookedTest(Base): # A c$, "fr_FR" locale with a space character as decimal separatorJand a non-ASCII currency symbol. (n_values = {'1_1': '\u20ac',%~`_point#,frac_digits': 28grouping': [3, 3, 0]@int_|HEUR \#`Omon_ " #thousands_sep n_cs_precede0n2A_by_J': 1ign_posnegative_sig('-pqpq pPqIposiqp} class Formattingdobject0# Utility functions for:b tests-Pdef _!_f`:c(self,7!, a, out,YB, **-S_opts8.assertEqual(j[9U Je) Eqcheck_warnings(('', DeOa"W);   :=Q.0 _string #  3  KE @EnUSNumber # XXX there is a  + padding bug when'  is empty but+Karray contains)s (e.g. Solaris 10QsetUp92Ssep =.conv()['{&']V("%f", 1024,!=1f='1%s024.0D' % )RQ$02NC?-42C/-4C%+f", -42, grouping=1, out='-42.0') def test_g,_and_padding(self):)-!._/format("%20.f", -42, Dp'.rjust(20))I1if L6sep^b%+1c)00eP;('-4%s200' %f)12 -q2lqjuintegerrfid", 42CTrues+O +P"-  /10 ! ij.osimplesG10240 EDC  k+D^E-L$00NNf 7M'+_deprecation7BwithassertWarns(D17ingrlocale.`?("%~ C co"x_<tA# Spaces in &q string ._!("One million is %i", 1':a1%s000'<R.sep,27sep (;_# DotF self._test_format_string(".%f.", 1000.0, out='.0S.') # Paddingif self.sep:.q--> %10.2f", 4200, grouping=1,FJ5' + ('4%s2E0' %}).rjust(10)Asterisk s]*"(2)0,' 2%*.O10, "Q('1%sTest more-in-one int %i float %.2f str %s",(,VlX'str'_'cg 1.00lG% %j(Fsep,') class F PatternArg(unit%.RCase)#/ handling of p6 argumentf @def K_onlyOnefVwith check_warnings(('', DeprecationW)7;# Issue 2522: accept exactly one %, and no extra chars.H+assertRaises(ValueError, locale., "%f\n", 'fooH"rH53 %0g2^G36f%%LS"""GeneralJs onR;"""percent_escapeziEqual(mU('%f%%', 1.0), ! %J d Mbd', (1R)$'%#& %$h(foo)s %%k{T: 'bar'}q7('%-; % .)R0map.Kcale.format_string('%(foo)s bing.', {'foo': 'bar'}),  /, %0)0self.assertEqual(locale.format_z't class TestNumberFgtPBaseL}@ized"l, EnUS(!):#E! nF G with a real English  : t_type =LC_NUMERIC%def setUp(!tc .'`& ) -(OCook 0cG "en_US" #  )Jtest_currencyRa*._#50000, "$ K.00"0@,0001, grouping=True@eUSD 50C O, internationalcC((CHe CEh/("%.2f", 12345.673t, out='&')3 i_and_padd5u9vw7MFrFRZ]:_fr_FRadecimal_pointf!W0,67*( 2345ed512 L 6w.7H8IMUself._test_fo,rmat("%10.2f", 12345.67, grouping=True, out=' 12 345,67') self._test_foO"-6OM I7I 8J 9N:Adef zinteger_(!):% d", 200?200Q ?4@4[1') _and_padding4u5C//10D.rjust(10), 0-0-l currencyeuro = '\u20ac'5 ;0500"p00 " + AD7 @8 G# XXX is the trailing space a bug?reEUR ",5Drnational) class TestCollP(unit.3ase#(@ strc0P funcWsp0str% assertLess(locale..'a', 'b'), 015_Equal6a6}Greater8bn 8 # embedded null characteraRaises(ValueError, c, 'a\0hB&@\Cstrxfrmf.''b'/7]) class TestEnUSCollation(BaseLocalizedTest, !): # string c?P funcHs with a real English lY!e B s_type =r.LC_ALL!def setUp(selfx|enc = codecs.lookup(N.getpreferredencoding(False) or 'ascii').nameP0if S not in ('utf-8', 'iso8859-1 wcp1252'<raise unittest.Skip/$('~ Wsuitable')u(!=g and (sys.platform == 'darwin'is_android orMMp.starts('freebsd')0wcs /wcsxfrm have known bugs D.@3iskipIf oaix'),'bpo-29972: broken s on AIXH@_str__diacritic^m.assertLessZ=@('àb'), 0)j&=$),}2strb')) class NormCCase>eQcheckOSg, expected+eTEqualfnmA)Bb, msg=}a_aliass3for:!, %5.<w.items(>8 0sub=X U?:$l0 \emptyA''s 'c3C d'posix!lUe en;en_US.ISO4/EN,3en.a&d?_us/#GB//GBB.UTFQ"1utf?0:"?, '1.ISO8859-1', 'en_US.ISO8859-1') self.check(&US-ASCII', 8[15"565Sglish2/EN1_uk.ascii:)GB:def test_hyphenated_encoding()!):(;8az_AZ.iso 9eb9/9E '=, 'tt_RU.koi8cqoKOI8-Cm #9, 'elo_LA.cp1133faIBM-CP7 ?ibm:$a?, 'uuk_ua.microsoftcp125uk_UA.CP <-=ka_ge.georgianacademy.ka_GE.GEORGIAN-ACADEMY-?, 'Ecs_C22 &<, '!) &euro_modifier  `de_DE@/} 5@ @gEutf8:lUTF-8'_latinabe_BY.F@6\sr_RS==ny< valenciaDca_E9g+@=&:1 devanagariSks_IN;-@A*>+ ') self.check('ks_IN', .UTF-8') Fself+(Rsd_INJ@devanagari<o-A+>+ +(sdef test_euc_encoding(!):!ja_jp.eucQPja_JP /JP//jp1Pko_krS/Pko_KR /KR`//kr1Pzh_cnS/Pzh_CN /CN`Pzh_tw"/ TW /TW/ .tw1Pqjapanesem FfF.jis,OJIS7Ija.s,OSJIS,_?aje?eucG7iso-2022- 0iso54 SbFjis7/fmscode1 O.pck.).uFutf8 +[ >.-`d_p_ class TestMiscellaneous(unit.CCaseTgetpreferred# Invoke - to make sure it does not cause exceptions.enc = locale.Ucoding()  if enc: 1# Ioding non-empty, make sure it is valid;codecs.lookup(enc) def test_strcoll_3303(self)|## crasher from bug #-G5.assertRaises(TypeError, locale.f, "a", None)@#bAB"etm_category$.s)(fLC_ALL(OTIME)OCTYP*_OLLAT,MONETARYsNUMERIC#A7419I!  Bs, 12345c5get=_issue181^I #`: settSand g 3theB under a Turkish2old# = ddCleanup1LC_;%, i6try4G, 'tr_TR'Ddexcepto T# Unsupported( on this system skipTest('k needsB6loc>gif verboseCprinswith %a' % L,), end=' ', flush=Tru>6locQEquald!. !in=_~_format_in\tupleQ K[ALL, b'fi_FI'iterable[p(b'not'"')) class BaseDe1izejL@ized&):r_%_d2Q,wue, out2XK>bvalue)9 eOatof_!8Y iY$*i(Y class TestEnUSDelocalize(EnUSCookedTest, Base): def test_d>aself):#,._%'50000.00', )6,78Patof(xu", },w- sis "i(s'po(o) class zC/(Cd r" FEKfrFROFrFR"R,N 0007 YJz~w- sk oo if __name__ == '__main__'3@unit-.A() #\s for the correctly-rounded string -> float conversions # introduced in Python 2.7 and 3.1. import random  $re 4sys 0sup@ if getattr(sys, '_repr_style') != 'shortdraise qP.Skip/('!->Z! ''not available on this system') # CY YVsin pureB,comparison. strtod_parser = re. ile(r"""# A numericconsists of(?P[-+])?7# an optional #llowed by(?=\d|\.\d)50# az ber with at least one digit@P\d*AP# havfa (possibly empty)beger parF0:\.AfracLE# fo *GEF1exp P?\d+)J d?rexponenp\Z """,VERBOSE | IGNORECASE).match # Pure Pytho!n version of correctly rounded string->float con.. # Avoids any use@&0point by returning the result as a hex^P. def tod(s, mant_dig=53, min_exp = -1021x1024): """Ct a finite decimalYou represent!anGIEEE 754 binary64 A. R 'inf' or '- n overflow.BThis functSmakes no arithmetic atHCstage.""" t# parse0int@pairrintegers 'a' and 'b' such thatADabs(value) = a/b, along with a boolean 'negative'0m =~Atod_Ar(s)Zif m is Nonepraise VhError('invalid numericMBing'E2fra-= m.group('!')h'jntpart = int((int') + 0qR/ )3expP0') - len(5 sign') == '-Ba, b*10**max(exp, 0), 0, -exp)Squick  for zeroswf not aAl-0x0.0p+0' if eelse 'ccompute exponent eis ; may be one too small inAcase#60ja/b lies5a differg+pde fromTHd`.bit_length(tb(+= (a >> dqd >= 0 a << -d)b.eEax(dW.approximateQnumbe/form q * 2**e; adjus.dqcessaryp"-eb+q, r = divmod(9if 2*r > b A== bVq & 1aq += 1MEIif q0+8-uq //= 2=eP# double check(q, e) has@ight1m2lassert%<=e-B=BAor eAB#/ews'lif e +A> ma(brWpRq;v ja , shift so # bits after 3iqmultiplS4hexdigs = 1 + ( R-2)//"UY= 3 - %@ = qshift, e - sh ift return '{}0x{:x}.{:0{}x}p{:+d}'.format(,0 '-' if negative else '',!q // 16**hexdigs% *Te + 4A) TEST_SIZE = 10 class StrtodTests(unittest.aCase):def check_s.(self, s,"""Compare the result of Python's builtin correctly roundedcDstring->float conversion (using ) to a pure\@ Z Rimplementation. Fail5theEtwo methods gdifferentfs.""" 0"ry%Bfs =5(s)'except OverflowError8got = '-inf`s[0] ='  QoMemoryOm ep'=?lse~xfs.hex(pected =L8tod.assertEqual(ex.V, got ?"Infor {}: " J "w1 {}zD {}"s4s, "))_short_halfway_cases# exact % % with a small numbersignificant digitsk in 0, 5, 10, 15, 20p# uppers\ est integer >= 2**54/5**kX32-(-"#$Z# lowY4odd\39 \6\!3/# \#if]0% 2 GI+= 1^ierange(># Select a random =[y#6). Then n * 10**k9s a {.;cn, e =.,r, 2), kp# Remove any addi@al psq5rwhile n % 5_nk5+%L 10i(1, 3, 7, 9K'S# TryR pS2**p2xPe, p20Wuntil4ahas mo]nan 20 g on = /.! < s = '{}e{}'.format(digits, exponent) self.check_strtod(s)# Same again, but with extra trailing zeros.j = '{}e{}'.for * 10**40_ - 40m *= 2 # Try numbers of the n * 5**p2(e - p5), p5GR>= 0, :15 <.20 m= n, eYbwhile .O:'sXfJ,3R -= 1def test_halfway_cases(n)x#$ $ $7?`round--to-even rulfor i in range(100 * TEST_SIZEf# bit patternca8dom finite positive (or +0.0) float%0bit prandom.}2047*2**52)t# convertCto a. -vm * 2**Ce, m = divmod(,%kFif eZm, e = m +49- 1e<074add 0.5 ulps2V 2*X1T #decimal string* /<<y9= 0T?els $# a@ = ( c5**-e) wB-# (H ;Mb?ariJressed as triples (, u), wher@# n*1 e is an approximation to^y value and%6# u@E1ulp5 ie [50 , -19, 1110), # a power%#2 O[y (1. (17976931348623159077, 28O 99oOoverflowK2.**1024(22250738585072013831, -327, 4941), # normal/sub (2.**-1022) ,(0= i# zero8] for n, e, u in boundaries:#H'j!range(1000)"&digits = n + random.5-3*u, 3*u9exponent = exQ'{}e{}'.f"t(i$, 8Rself.check_strtod(s%}n *= 10ruqe -= 1 0def test_underflow_= y(}#) values close to 275, the Gy; similarp #7f_~scept thaex error doesn't scalZ# with nYL2-40` Pbase :5**-7 //E1075W[:TEST_SIZE '1 = `Bx , '7|bigcompPndigs05p, 14, 1 6, 17, 18, 19, 20, 4Z1, 508Sdig10MP~fibC_10 * Cw ~h6=9>4007mE|parsingm# make '0' more likelye chosenn other IIQ = '0123456789'#@sign('+', '-"')# put togea^` shortid stringsR# \d*[.\d*]?z  H"0.choice(intpart_len 52s += ''.join(dN ) _d)P$if_[True, False] u.Ofrac;T / Gelse fracpart_len = 0 if random.choice([True, False]):1@Ls +=7'e', 'E'])3_signs.texponenrange(1, 4:''.join(1_digitqfor _ in8ge(=)) eif intf7+ fuAelf.check_strtod(Oelse??try_floatPexcept ValueErrorHMpassDbassert@, "expecteds"C@test.support.bigmem`(size=  _2G+10, memuse=3, dry_run= @def 6P_overD!d_bings(self, max# Input string whose length doesn't fituan INT.s = "1." + "1" *^!Pwith y.vRaises(> Rdel s1 q0q0qwBXdlarge_P# Verify that the clippS!of;J`Qaffec6P# outvsuqpositiv'(n%""" LongF 1.0 and En"""s=return '0.{}1e+{}'.format('0'*(n-1), nOnega2-[1{}e-nhbEqual(N ,10000)), 8:2:&3: K : : [aicularNx0# iEs!produced crashes or incorrectly rounded results 'j# previous ons of dtoa.c, 1var freasonstrings = [  &# issue 7632 bug 1, originally reported failing case ? '21831670123121312.23538020374420446192e-370',@# 5 instances of2.)'12579816049008305546974391768996369464963024663104e-357u$'17489628565202117263145367596028389348922981857013G8487398785991994634182916638542680Q1359048227G#320028642005810331343587246751980445274693667739288"9439343119318069694284183708503364791322414853985 G7360827899896F34582465350013678787643600595795 G!6477447883641729949171843523461129933628808213601370494013412657453487864187694798087888451169  46'45774047060960624497964425416610480524760471G #A for4introduced by METD in r77451 (attemptedQ# fixB,Np2), and $edI982.?'286390971782617631784897591073213920849182530+114 # two numbers demonstrat`a flawthe bigcomp 'dig == 0'# correction block ()3)3K'1.0K1e44& 6=# dtoa.cX just smaller than a power2 ##49448766546555N717039532578546e-4Yoff-by-one error f tC83 (cleanup),M)907p'965437E336549317990355 1997118345570045914469' #.. 62033504169007991306908470147322020121018368e#inQ lsb det\round-half-to-even when# bc->scale != 0 +6)$1043084852419839906667134017080721757731650342786850826176229240933092)75170240465819787231912N@0365Sp7435319878397589904J094758667307945844895981012024387992135617064532141489278815239' #... %'849108105951619997829153633535314849999674266169258G#92894069223968477159006502702583580486358545487249$320500023126142553932654370362024104462255244034053$203998964360882487378334860197725139151265590832887G433736189468858614521708567646743455R05935595381G$852723723645799866672558576993978025033590728687206G2963798013630240940483272739130796124699825O4824G156000783167963081616214710691759864332339?873G065690656486646@83450809073750535624894296242 0720101957102760730420367985245955618354119901G0652571123898996574563824424330960027873516082763671875e-1075', , # demonstration that original fix for issue 7632 bug 1 wasY#gy; the exit condiSwas too strong7 '247032822920623295e-341e similar problem to1: crashk# with 'oversized quotient in rem' message6990374857002456831028050434373469652480296012Qk1e-373'9961763983374386316110P16288406769510558457G0885 02S345295743515631798401305@1462G2`059944"0935  042769690930905148015876788Gp891497969368270421829889y5625405976032710 #1 5:Kfollowing 2@@ingsZvert differently?'10Le-16<[0e-17= 799163379318915 L0e-3x# And another,`, fail/halfway case4106250198039498 ;8: produced 10.0<10.}123456789 5', ; # two humongous values from issue 7743 +'116512874940594195638617907092569881519034793229385' #...G`228569L 9154189084656466977171489084883987920G$473321268100296857636200926065340769682863349205363G 47637660671783209907949273683040397979984107806G461822693332712828397 4603623958163297658510063520260770761060725~0412314438457161207373275477458821194440646557259102208197382844838602556287G85183174541939743301249188486945446244[895047499G 4365519746497319171700993877{0102e@5829V?343G76193341216682148401588363162253931420379o49798213003874124295756733024613803865965011874G006257527709842179336816728187984503912352c8844448336815912 @5229\916993546388956561526187535204208236074787F@9460&2830869374G0528766344140353394885390898399055004119873046875e-1075', P52544352955266109603582028A12589849649189225652784975045218257059713Rp7425143!/61=@443259988700016365751744735599222585294=016668660000210283807209850662224417 522649953663151200775385580B@3730215773875280084030259u2370502479105305382500086822727836L81816280407u6531214924364088126680234780012059254322340397M@8524@78850722958784640528O4309G!111498801734246927500699910451962094643G6714796649548507772687838176778993472988`56195947036638938396333146685137903018376/088p3197053s84769252 7136513970 73@1471031G9912528110505017@5232077609130304371'15719129282!7614046876950225714743118291034780466325' #... '085141343734564915193426994587206432697337P_11527G$278968731294639353354774788602467795167875117481660G473879125685367569054383782215866825e-1180', # exercise exit conditions in bigcomp arison loopB''2602129298404963083833853479113577253105939995688e2',C,096e o9601e-0517E/926\z# 2**539007199254740992.07`1024 -A970: exact overflow boundary. All valuesi # smaller than this should r= to something finite; anyN MTgreatMor equalDY5ones#179769313486231580793728971405303415079934132710038269361737789804449682927647509466490l7NO70963302864166928;5555478519404026306574886715082068190890200076762738548458177115317644757327006985557136695962284291481986083493_19074168444365510704342|5969950809304288017790417449779wy - tiny 'c[1.999"+303415079934132710037' #... %'826936173778980444968292764750946649017977587207096G33028641669288791;555547851940402630657488671505G$820681908902000708383676273854845817711531764475730G27006985557136695962284291481986083493_19074G168444365510704342|59699508093042880177904174497792.001',f# 1 - 2**-54, +-tiny!+'944488848768742172978818416595458984375e-54kJ#4Q6!501Q## Value found by Rick Regan that gives a result of:99683 # under Gay's dtoa.c (as0 Nov 04, 2010); since fixed@# (F some time ago in PythonZ).)}1'0.1$b05761291134237854299716904211912140?5437#0871477631781497629568689916922898699412466580731951982237l 82039897143840789794921875q]Pfor s<test_strings:vself.check tod(s) if __name__ == "__main__"=@unitS.() import ` from ! 0sup")usmtplibocket ssl = ,.;_module("ssl") requires("networkCdef sl_verifiy(host, )pcontextlsl.create_default_(_awith s)connection([A) as*d\6try I3 = c`.wrap_0et(, server_~= ?except E:ion]return FalseJelse'ic.closeZ@True class SmtpTest(.CCaseKS@ = '.gmail.com'premoteP a= 587 <oN_starttls(]get_attribute(ilib, 'SMTP_SSL''_BSSLC (ssl.PROTOCOL_TLS_CLIENT:}+ =Ua.ayemCERT_NONEAupport.transient_internet(self.testServer): s = smtplib.SMTP4!, EremotePort)D:tryU`Y.starttls(context= BiexceptEion as e`if e.args[0] == 'STARTTLS extens:not supported by 'O@unit)e.skip(^ )?elsYraisesZehlo(J quit() class SmtpSSLTest(CCase@ = '.gmail.com'~q = 465 @def <r_connecT,.get_attribute(``lib, 'V_SSL'Dwithd.transien~+bKe _default_(y+using_ssl 'rsl.SSLC (ssl.PROTOCOL_TLS_CLIENT:.check_hostname = Fal*'verify_mod$^CERT_NONE#, ;_=, uq'Python8's'product_>81.03PSF)kreturn db, class MsiDCp.1): E_view_fetch_Ys_none(self$n0db_q, =KR&properties = []e = db.OpenView('SELECT P3y, Value FROM'[C.Execute(Nonewhile True/record = <F(6"3if %0is U A#Ubreak.append(D.GetString(1)h}0ClotH> 4) & 0xF] + h[i <return r URLohttp://www.pythonnet/hashlib/{}.txt"read_vectors("S_nameurl = URL.format!~6tryhdata = support.open_urlresource(url):except (OSError, HTTPE3ion FaiseSkipTest("Could not retrieve {}"ijTwith u@linexz = r.strip(Q$if@artsg('#') or8o1continuepA kplit(','n$R[0] =j.fromhex( /ayield  class HashLib?UCase( w5ed_s = ( 'md5', 'MD@sha1iSHA1', s'sha224/ $56 E$38E csha512E E pblake2b2 s&3_03_2 &3_/3_shake_128 O!) o{^)})2# Issue #14693: fallback modules are always compiled under POSIX _warn_on_extension_im` = os.  == 'posix'COMPILED_WITH_PYDEBUG*_conditionalK_c(self,eB"""Ixa"@ anda reference to itNone on failure.""YO 'Blib. 4MONotFoundP as e 0if .U /dPings. ('Did a C r? %s' %~s_init__y*args, **kw algorithmw7set&+! 4es.add(.lower()~_6Oelf.A'+3if ms.update({'blake2b', ' ss'}) self.constructors_to_test = {}'for algorithm in %s:%SP[?] = set(# For eachY!, the direct P and 5use# of hashlib.new given'}e name.3 ,bs.items()s.add(getattr(,%))7Adef w_S_via_9_new(data=None, &=*, **kwargsZ0if 9@ is < !hreturn<(cY 3 n9 ! # =lf._conditional_import_module(','e4if  # These twos should always be present whS2is n #gcompiled. If not, something was !f wrongWrassertTrue:B, 'openssl_md5'G>Lsha1?;4 = ''+H(if  pMoadd_builtinL(! HE, "__getM"")O %Ss[{]9u:md52'<_(t) qv+>w?256y7256=osha256}7224BK![.?5127512=?512/38 nstructor('sha512') if _blake2: add_builtin_constructor('-sC/Eb') __sha3 = self.] ditional_import_module(')i<+G_224B 0/560/38` ~ oke_128Ake_2nsuper(HashLibTestCase,}).__init__(*args, **kw @propertyNdef hash s(),s_to_test.values( return itertools.chain.from_Xable(K0sup7.refcount`Q@unitnskipIf(c_lib is None, 'Require uB_refleaks_in*_< gettotalget_attribute(sys, '/xAsha1l5 = `.new('*refs_before = Sefor i in range(100 t m.assertAlmostEqual(v7 - , 0, delta=10^l_arrayQAa = .U("b",)?SscUVons(aDif c.nameI[shake>*c.hexdigest(16FJelsep 2 algorithms_guaranteed {uOlib.>,yPset(_( + !in .C!edo_s=A B.islower())QavailhAPTrue( /)._issubE bunknowhRaises(VaError,unew, 'spam OOTypeN1P3SS' attr(hashlib?,  '__get_builtin_constructor')G _cache = getattr(hashlib|O '_z\self.assertRaises(ValueError,Fw, 'testGEtry:"import _md5except Ib 4skipTest("< module not available"?# This forces an]' "" statementsQsys.me0s['s'] = None## clear the .2( !y 7md5xlfinall|"f in locals()k'Nelse=Odel A:?TypW31/ *('v7Is(C,F.md5b-Equal(sorted(), ['MD5', x1]) @def p_hexdig\s@for .sb1h =0Aif h.nameH[shake=*e^IsInstance(h.16), bytes7;@hexs=V), h.:16)H4Z())5_M`ibute(?VL }Z, str% up61ed_ 8 "n(!, }sA uONotIV}o4 , slib.new) large_updaaas = b'a' * 128t2beeb7cc6dd 2048 # HASHLIB_GIL_MINSIZE for cons in self.hash_constructors: Pm1 = +().update(aas?beecdif m1.name in [shakeargs = (16,Jelse/*) 220 + 0 + > + assertEqual(m1.digest(*Z), m2 3?aasr43r # verify copy() doesn't touch original/4 2m4_Z = m4 R_' 4 z#D  %, def check(= , , data, hexm!, =False, **kwlength = len(8E)//2(& =Zg.lower." ==_to_test[]]# 2 is for $1lib(...) and0ew(; , @.rGreaterF), 2tox_object9+m9(|d8computedi.Q() if not <' m K i"q )"Hash algorithm %sed usingreturned"P1 %r`%d bytJ1put@ tha0oul!veed to %r.P#% ,6  ) )U-<! =s.fromhexV ", I )  M\_size@_no_unicodeK _q)n2# U) Qs are ald as input. constructors = self.c _to_test[algorithm_name] for hash_object_=G in %s:5<kassertRaises(TypeError,R, 'spam') K@def _no_unicode(W)jh.check%a'md5')D%Osha1&?224(/56(/38P4512 @requires_blake2 'Lb)sOsha3+_h?3_2j_l"3_n0Yshake_1284+#blocksizem# , x!, _=0, digestF,length=None( 0?m =(i(Equal(m.7< : 9$ifV*L blen(m._(_=?)), P 2 0o2hex9r "2*; tOelse/))RB  @ m. +# split 7p512 / _ .  `0In([.F("_")[0], repr(m){WW, 64, 1612/2023484 self.check_blocksize_name('sha256', 64, 32) self.check_4384', 128, 48545125A64) k@requires_sha3def testx!(!):(1_22_44, 2"3_?136_/04"3_ 72L`ke_128O_68, 0(ke0vRzl , ( , capacity, rate, suffixconstructors = @_to_[P]ofor hash_object_GG in s9?m =9(E*assertEqual(# +O16004 4m._7V_bits925 1]e*_extra! 3448, 1152, b'\x06'5 8+512, 108887/83o1024, 576op256, 13/1f  9ablake26 #F(Y X1bY$6s case_md5_0`('md5'`', 'd41d8cd98f00b204e9800998ecf8427e'c1c0abcf900150983cd24fb0d6963f7d28e17f72f2f84b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', N 'd174ab98d277d9f5a5611c2c9f419d9tP@unit'.skipIf(sys.max < _4G + 5, '$ cannot run on 32-bit systemsp@bigmem/(E=C memuse=1, dry_run=False)  def test_case_md5_huge(self, size): .check('md5', b'A'*&, 'c9af2dff37468ce5dfee8f2cfc0a9c6d') JP@units.skipIf(sys.maxG < _4G - 1, '$ cannot run on 32-bit systems')Q`bigmem/(E=Cmemuse=1, dry_run=False7uintmax!28138d306ff1b8281f1a9067e1a1a2b3# use th+ree examples from Federal Information Processing Standards# Public'180-1, Secure Hash/, 1995 April 17>http://www.itl.nist.gov/div897/pubs/fipYB.htm 6asha1_01(")1"",xK"da39a3ee5e6b4b0d3255bfef95601890afd80709">1?abca9993e364706816aba3e25717850c26c9cd0d89d2+b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq84983e441c3bd26ebaae4aa1f95129e5e54670f13 b"a" * 1034aa973cd4c4daa4f61eeb2bdbad27316534016f:22002 August 1Fcsrcph2"s O.pdf#?224%>224')"d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42Uc .0  2 "23097d223405d8228642a477bda 32aadbce4bda0b3f7e36c9da7; C |41*"75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525 = ?)"20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad6c%+56} self.check('sha256', b"", 6"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") Ndef test_case_o_1(self):qZ.chec:abc4ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad") t2?- b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq2248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" 3a" * 10 cdc76e5c9914!81a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0 5 t_384_0 ?384438b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da"+ "274edebfe76f65fbd51ad2f14898b95b)  2cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"8086072ba1e7cc2358baeca134c825a7    "R b"4*4.424@opqr@pqrs@qrstJrstuR0093>3f71147e83d192fc782cd1b4753111b173b3b05d22fa0BIf712"fcc7c71a557e2db966c3e9fa9174\  \ @9d0ec)716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985 ?512?5122cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce",2"47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3eq  0ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39*192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa5f2_2(self):  self.check('sha512',  b"abcdefghi!ij0ijkpijklfghm?n"+P&!no-nopjklmnopqr!rs0rstXrstu"2"8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb68890186"501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909") 7def test_case_X0_3(m%): | b"a" * 10 2e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"#"de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e46217ad8cc09bAq_blake2, constructor, salt_size, person 2key >0digE9max_offsetCassertEqual(w.SALT_SIZE)jfor i in range(G + 1bU(=b'a' * iN?3 = &NtRaises(ValueErr&g=V)S?cPERSONf $+ (+D=MAX_DIGES:71, 'o(*=?B&-1 C0B.N/+1j3KEYg d!a ?key^7key[IP!e6keyx Mb().hex!(()#b9b'';W o0, 256iofanoutm$= hf.assertRais es(ValueError, construct fanout=256) for i in range(1, : 'F(depth=i)!self.assertRais </-1=(0<(0 Rnode_#A$B digest_size + 1)Qinner)$A$B'+1Bleaf!(1<<32) Overflow4lD1offset=#Bmax_.  N'F7Xstring=b'',>keyNsaltnpersonH:=17_1 :2560?512R Plast_VU=Truedef blake2_rfc7693(z md_len, in?0teq(length, seed(umask = <a0xDEAD4BAD *B0 & 7 +Yb = 1out = bytearraya  (J(a + b)}#0a, Ib, t`out[i]pt >> 24FI0xFF*return ouAxouter =[(n&32`outlenb "#in! !Pindaty 7, inlen)   key = selftest_seq(outlen, $) +unkeyed = constructor(indata, digIOize=Bouter.update(O.9.()qo key=keyx Vv`returnder.hex @requires_blake2Adef ? b(P!):6c.check6(hashlib.1B, 16@64, (1<<64)-1 b2b_md_len = [20, 32, 481]l&$in&%P, 1289, 255, 10241assertEqual(K_rfc7693t , )),J4"c23a7800d98123bd10f506c61e29da5603d763b8bbad2e737f5e765a7bccd475")Ccasef?b_0"('xb', b""4"786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419"+("d25e1031afee585313896444934eb04b903a685b1448b755d56f70/o9be2ce 1:abc4ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1"+ 72"7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923 all_parametersq# This s that all the 5 work in general, and also2#4 byte order doesn't get"fused on big endian platforms.M :foo920568b0c5873b2f0ab67bedb6cf1b2b. _s(169Yb"bar0Psalt=z`person9ingfanout=2[xdepth=3Bleaf4node_offset=5H RinnerI70Plast_No=True))0_ve *for msg, ^ mdEread0@Rs.fromhex(key%p!mdt b(hashlib.blakae2s, 8@32, (1<<48)-1)  b2s_md_len = [16, 20, 281]&$in&0, 3, 64, 65, 255, 1024/self.assertEqual(Ivblake2_rfc7693(hashlib.6s,  ~)),J6"6a411f08ce25adcdfb02aba641451cec53c598b24f4fc787fbdc88797f4c1dfe") @requires_fdef test_case@s_0(!):#<.check('>xs', b""2"69217a3079908094e11121d042354a7c1f55b6482ca1a51e1b250dfd1ed0eef9 1:abc4508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982") Wall_parametersq# This fs that all the 5 work in general, and also2#4* byte order doesn't get confused on big endian platforms.M:fooTbf2a8f7fe3c555012a6f8046e646bc75.0digyxsize=16Ikey=b"bar0Asaltz`person9ingfanout=2[xdepth=3Qleaf_4node_offset=5H RinnerI70Plast_N_=True6cn_vecto*for msg, key, mdEread0Qkey =s.fromhex(key*%p!mdt=4Asha3 SO_224T &U$b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5amMe n mhS'iD$,-md#/56</56<2a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a"D&/56Dmsg, md)  @requires_sha3 def test_case_384_0(self):$(.check('=&u', b"",$6 "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2a"+Nc3713831264adb47fb6bd1e058d5f004") /lvectorfor msg, md in read_*sH?512r?512r4a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a6"+ 2"15b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26h $,oke_128'27f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26"TQTrue)  "y2", 34 ke# % O_256?256246b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762f" "y!&% 1.0'c oscrypt$1N Dfor I=P, n, p, expec"inDzvectors ! =2(c=@, n=j=l"=pv" n?Y0# this vs should workn"Y0 n=2, r=8, p=#$A andd must be bytes-likep6yo+ 9@ key_ args48\.scrypt(b'pas sword', 2, 8, 1, salt=b'C') for n in [-1, 0*eNone]:#*with self.assertRaises((ValueError, Overflow2Typ*))LPhashlib.scrypt(b'pas, n=n, r=8, p=1r|2rpjpjemaxmeml)1,j = Fdkle =) if __name__ == "__main__"unittest.() from support im%check_no_resource_warning, findfile, TESTFN, unlink ;d]YBmockwPaudios$opbyteswapc$io 5sys TtructDaifc s class AifcTest(hx .APWrites] +&QWithS CFilemodule = close_fd = Truev_unseekable_rea  @PCM8l(p4Casys = 'pluck-pcm8.aiff'w$frames = 3307nchannel2sampwidth = 160ratQ11025n8!48pcomptyp&bb'NONE|`b'not bressed!H.hex("""\X0 02FF 4B00 3104 8008 CB06 4803 BF01 03FE B8FA B4F3 29EB 1AE6 \D,EDE4 C6E2 0EE0 EFE0 57E2 FBE8 13EF D8F7 97FB F5FC 08FB DFFBD&11FA 3EFB BCFC 66FF CF04 4309 C10E 5112 EE17 8216 7F1%12D 49&20D EF0F CE0F E40C 630A 080A 2B0B 5N8B11 B60E 440A \ """)  class AifcPCM16Test( , unittest.Case): sndfilename = 'pluck-pcm16.aiff'%frames = 3307nchannel2sampwidth = 60rataQ11025(n8!48pcomptyp&bb'NONE|`b'not bressed!Hbytes.fromhex("""\X< 022EFFEA 4B5D00F6 311804EA 80E10840 CBE106B1 48A903F5 BFE601B2 036CFE7B \P8B858FA3E B4B1F34F 299AEBCA 1A5DE6DA EDFAE491 C628E275 0E09E0B5 EF2AE029P0575#21 FB35E83F 1376EF86 D82BF727 9790FB76 F5FAFC0F 0867FB9C DF30FB43 8117EFA36 3EE5FB5B BC79FCB1 66D9FF5D CF150412 431D097C C1BA0EC8 512112A1EEE21753 82071665 7FFF1443 80E8F 49A20EAF 52BB0DBA EFB40F60 CE3C0FBFP4B30CEC 63430A5C 08C80A20 2BBB0B0@4A0Eb BCF1139 B6F60EEB 44120A5EPj""")  24(/24032lD65FFEB9DA0F00FA54 3C304EE2B 80DCD608430MCBDEC006B269803F2F8!82401B07D 036BFB'%5D`B85756+ C9-055F3502B1830EBCB625CA7E6D99A<A 3EC BDE5EBE27884I 5AK6CF EF2929O%22<QDS1067U57E83E16Y7BFEF8402]!C5_2x978F16FB7745m865FC1013q0635s"4EuCE117FE0FA3438}6B8FB5AC37A3FCB2F46DAFF5F3`CF13B9N!75q69097A8B600EC74E 5120B912A2BEEDF641754C0001664B7053F0001294E6,499C1B0EB3B273E0DBCA02B20F5FD8vDB0FBE1E4B49C0CEA2D4A80A5A7FE0A1FFE9860B0A0, 51486F0E44E1 8BCC64113B0504EC 363170A5B48/32,/3204Zbytes.fromhex("""\ 6022D65BCFFEB9D92 4B5A0F8000FA549C 3113C34004EE2BC0 80DCD680084303E0 \LCBDEC0C006B26140 48A99K3F2F8FC BFE8248001B07n036BFB60FE7B5D34L`B857563EC920 B4B05500F35029983000EBCB6240 1A5CA7A0E6D99A60L4EDFA3E80E491BD40 C625EB80E27884A0 0E05A9A0E0B6CFE0 EF292940E0292280Lp5758D80;06700 FB3557D8E83E16377BF00EF840280 D82C5B80F7272ALP978F1B774560 F5F86510FC101364 08663 B9C4E20 DF30FC40FB40EE28117FE0A0FA3438B0 3EE6B8*5AC3F0 BC77A380FCB2F454 66D6DA80FF5F32B|PCF13B41275B0 431D697A8C00 C1BB60}C74E00 51203w12A2BAA|EDF64C01754C060 8207:1664B780 7Fp14453F4` 001294E6``499C1BvB3B270 52B73E000DBCA02 B2B2E00F5FD880 CE3CDB400FBE13E4B49CC00CEA2D90 6344A8800A5A7CP8C8FE1FFEE0 2BB986C00B0*P514863E44E190 8BCC6480113B0580 B6F4ECEB3630 441317]G5B480 """) class AifcULAWTest( , unittest.aCase):sndfilename = 'pluck-ulaw.aifc'$frames = 3307nchannel2sampwidth = 60rat`Q11025(n8!48pcomptyp& b'|"b':bytes.fromhe8 497C0104 307C04DC 8284083C C269C$3DC BE8401AC 037B684FA24 344 2A7CEC04 19FCE704 EE04E504 C58wp4 0E3CE}vEF04DF8P557CE204 FB24E8G02FC' D784F744 9tB64 F5C4FC2p3CFBA4 L:!FCP3E7CF5BA84FCB4 657CFF5C C[41C 417C090184  517C12FCP216F.15FC 7D7C13,[1EBC>Mp F0040FYDDP5040CBC 6|A3C 08BC0 s2C7C0B3GE3C 8A84m2457-pif sys. order != 'big'# .Bwap(:, 25A5,a5m"5$30FFE8 4ALF8 310004E0 82000840 CB0006A0 4A0003F0 BE0001A8 0370FE78 \ -BA00FA20 B600F340 2900EB80 1A80E680 ED80E480 C700E280 0E40E0"F8 P#56#`FB20E8G380EF80 D900F740 9kB60 F5C0FC10 FBA0 DF00:211836`FCB0 6GF58 CF000420 4200091000EC0 52001EE801780 8P7E001,7>P0DC0 0FYk5FC0`0CC0 6| A40C00 2"B42P 8A00m2460-A""") if sys.byteorder != 'big':frames = %Rswap(, 2) class AifcMiscTest(audiotests.A ps, unit.)RCase)imodule = aifc |@def +_skipunknown(self3#Issue 22454This file contains chunk typesb doesn't recognize.@c#.f.open(findQp('Sine-Hz-300ms.aif'))`close_<0ed_:s_on_error@non_'6 = l pluck-pcm8.wav', subdir='`Rdata'with check_no_resource_warningu2assertRaises( .Eh0`# Try ing a non-AIFCo!, the expectation that]E1# `iK` will fail (Cout raisdRWH  Uc, 'rb'1#_write.initfp() wo  in normal case. But some s# (e.g. Memory?, KeyboardInterrupt, etc..) can happenx mock.patch.objectc2, ')',Bside_effect=RuntimeP 6 t5f9TESTFN, 'wparams_addedR  Owf&f(Rf.set_U((1, b'NONE', b'=!f.(# Q<k%.gyPbEqual(0.nchannels, f9/()=sampwidth==Crate==ual(params.nframes, f.getnS()) self.assertEqual(params.comptype:;8nam;;wdef test_write_header_b_sampwidth(!):4Dfor & in (b'ULAW', b'ulaw AaWG722'GKut = aifc.open(io.BytesIO(), 'wb'#1.setnchannels(1!bOrate!( njclose(f @fout5J), 25$initfp(None) S markers_values|1dc[0set!P(1, 0Gfoo1 $1$2$z P(1), ^:*; 0ers[>]?ePread_Kl<0 = . lTESTFN'W.aiff!2set(11, ANONE"'30x7oddS #2Leven$s(b'\x00" f rR1), :, (L$I72[ p8qRaises(SError`, 3) class AIFCLowLevelTest(unit6.kCase):cL', 0);,b28OFORM8q4) + b'YBxO, b15!2 no_comm_chunk OAIFF{ Ossnd/b'eQAIFC'b += b'COMPhlhhL"38E, 8,<@0x4000 | 12, 11025<<18!>zMNONESB', 1not compressed+JhRegex(_  and/or SSND p' missi t()x}ion_typ b C-23   0x4000 | 12, 11025<<18, 0) +b += b'WRNG' + struct.pack('B'+self.assertRaises(aifc.Error, open, io.BytesIO(b)) ldef test_read_wrong_number_of_channels(d!):2Tfor n in 0, -1 $ b MFORM>L', 4) + b'AIFC'Y9?COM:PhlhhL@638,,)8,HL:MNONE1not compressed+ob'\x00@SSND# 8:I * 8Pwith  YRegex'bad # of '(sample_width h11le 3MmarkFd z :OMARKhv3, 1, 1 Warns(User ing) as cmE6f = Equal(str(cm.warnY3, 'd :  chunk contains N 'only 0 ers insteadp&1' Sf.get5(), Nonecomm_kludge_Tname_evenun`nO<<18, 0)  b += b'NONE' + struct.pack('B', 4) + b'even b'\x00' ;?@SSND ?b>L', 8@6E * 8: with self.assertWarns(User ing) as cm:2p f = aifc.open(io.BytesIO(b)))VEqual(str(cm.warnY3, 'd: bad COMM chunk size'Jf.getcompname(),!) ~ def test_read_comm_kludge 4P_odd() b OFORMDMAIFCz6PhlhhL18, 1, 0, 8,F0x4000 | 12, 11025<s(4f(egb'nameaEqual(g7), 17), 17), 1F), 0/@tell)g0*_ 6M6 WF^s(b'\x00' * 4 *7get4)) 4  _bunch>p = (1, 2, 3, 4 >2set/(p+7), .Hinitfp(Noneheader_r9%<MVclose]I|i1 s $r # in (b'ULAW'eAulaw AaWG722'1!( 4,6markersC/ut ises(aifc.Error, fout.setmark, 0cb'')  self.assertRaises(aifc.Er?1, -1, @)0, Noneg17rinitfp(Qdef test_write_aiff_by_extension(!):,sampwidth = 2filename = TESTFN + '.M'$`out = P.1 = 9Topen(A], 'wbmddCleanup(unlink, 0 setparams((1, 1, 1rb'ULAW';rames = b'\x00' *getnchannels() *Q .;fE(\Ogclose(rrEqual(f.getcomptype()GNONE8$f.tp if ____ == "__main__"@unit.() """Tests for the asdl parser in P /.py""" import lib.machineryos from os.path+@ dir&7sys dconfig # This is only relevantk -source builds of Python.rnot sysbQ.is_p_-(r xP.Skip ('.9 irsan installedj') src_bas( __b__))) fd_dir =,d.join(I2, '^p class BAsdl(CCase@.amethod`setUpCGC(cls*v# Loadsmodule dynamically, since it's Sin a realAablejQpackage.s1.T into an ast.Mtqand runcheck on itIQThere need to do t(Beach1@, heM"sy0.in3(0,Ploade!.S}@FileF5er( '*',!, !V.py')t2cls%"= .!_m'a(`mod = j.[(TrV^r@True$#.smod), 'validation failed~tearDown0del0A[0] B # alias stuff .r conveniKself.asdl = TestAsdlParser.asdl self.mod = Te':mod&types = 3. %def test_module($!):i.assertEqual w.name, 'Python')2In('stmt',{w*Oexpr*;mod)~definitions9def Adfns= IsInstance(33[0]_.Type 7h.value=BSum)|tw/['withitem'Product I_aliasFAp] =AH!']@ 11tr(2)),'([Field(identifier, i>),  as, opt=True)])'Zattribute   @len($.VO), 2%}P tC (_>incompleBRaises(SyntaxEd , B#, Sd<0[="u<)y*0>,?)U(UyertRaises(SyntaxError, eval, r""" '\U00' """) self.assertRaises(Sy>?-@.A/B0CFdef test_j_str_invalid_escape(c!):,ufor b in range(1, 128 $"if#b"""\n\r"'01234567NU\\abfnrtuvx"""X8continueqPwith Warns(Deprecation;ing;6`Equal((r"'\%c'" % b), '\\' + chr(b)) |xwarnings.catch_(record=True) as w(.simplefilter('always', category="'''\n\\z'''len(w), 1$$ w[0].filename, ''4 lineno, 2#Ke" *cm]  xc = cm.excepkqXO, []D?excw3 vd/1)8 w8w/81w>w?0x8z6u18> ' ~-,[ 0xTU0001d12'1 ] Vbytes_normal[b[  b\"""), byte(1C)) self.assertEqual(eval(""" b'\x01' """), byte(19r:8:?0x8=Raises(SyntaxError, ,yK {dr'\u183,Ar\' + b'<@:U0001d120B#'\N@def test_=_s_incomplete(!):*o2'\x=$ ?valid_escapfor b in range(1, 128"if#b"""\n\r"'01234567\\abfnrtvx"""5continueWwith !Warns(Deprecation;ing;6 b'\%c'" % bL ytes([b]))C~warnings.catch_(record=True) as w(0.si filter('always', category= D("b'''\n\\z'''"len(w), 1$ w[0].filename, ''4 lineno, 2$Kez#G*cm^ !xc = cm.excepsr}_w, []E?excx3 w?rawXO#r'Hx 4/rb4rm') BrB <: {:bu "\\" + b"x81") self(.assertEqual(eval(r""" rb'\x81' """), b"\\" + b"x81") CselfBRaises(SyntaxError, P,C7 brP? ? p?u18 Fw/F =TA A U0001d120x N3N E E2bb';/rr;&b<)bx'/rr(+,def test_p_str_u()!):;8^y2u'xw_, 'x'j 2U'\u00e47/ä8u'\N{LATIN SMALL LETTER A WITH DIAERESIS}Y u(uI';'u check_encoding$, , extra=""modname = "xx_</.replace("-", "_ufn = os.path.joinj.tmpdir, Th+ ".py87pen(fn, "w"=vJ6tryf.write(TEMPLATE %6)mfinallUfclose('__import__(del sys.modules[!%] Qfile_utf_8omz = '\u1234';  ord(z) == 0x1234\n" < self.check_encoding("utf-8", extra) def test_file_utf_8_error(self): %5 = "b'\x80'\n"AnassertRaises(SyntaxEI,/, 8kiso_8859_1J@iso-/?-1"O_latinL,I 9H9 if __name__ == "__main__"@unit. () """ Tests for the threa module.$q import @.sup Y from &(verbose,_K, cpython_only,!  requires_type_collecting)t.script_helperq k_o+k,failure drandom4sys _5ing4ime ]tweakrefoUsubprocess Plock_sz # Betweenk() and exec(), _# async-safe functions are allowed (issues # #12316C#11870), 0for[pa worke%! is known to trigger # problems with some oper`g systy #3863): skip9AaticSon platformmbehave badly. !A_to_J = ('netbsd5', 'hp-ux11') 5Avial mutable counter. class C(object)6__init__value = 0/?inc*E+= 1+/de+ -+"%iVAma, &, Ks.append(t!IsNone(t.iden'Regex(repr(t), r'^<\(.*, initial\)>$xt.start'sk@ing 8hto completQ$t\.sPt.joip AFalss_alive()+2NotX-+, LWWtZ5stopped -?\d+`I =Ju01st_#c_of_no]Fw = The ident still must work for the main thread and dummyCs. self.assertIsNotNone(7ing.currentTH().ident)>def f():V$.appendK:done.set(bSone =HEven!nU = []with support.wait_ls_exitctid = #.start_newf(f, ()XLaEqual([0], tidD0# K"immortal" _Dj7del_active[X!] )a# run a small(ish)9 stack size (256 KiBtest_various_ops_@_4(if verboseqprint('a|B...'w+:tryD{_v(2621446eexceptZerrorGraise unit.SkipTest((y'platform does not2 changing.d=/0)^largel_ (1 M 9'_x!@0x10#tforeign# Check that a "."_`can us`fmodulemwf(mutex\`# Call4)ces an entry #to get made '.fF map f.release(@ GLock5!p.acquir:5Z9i,e# WaitA to finish BPcn(tid,tZ'.sInstanc1@[tidEing._DummyThread3) #Issue 29376"self.assertTrue(threading._active[tid].is_alive()P;Regex(reprA), '_DummyTa'GOdel v 3# P5.State_SetAsyncExc() is a CPython-only gimmick, not (currentlyq# exposed at the : level. This test relies on ctypes to get81it.1def,_$!):.K= import_module(""")*Pset_ac_exc =!.pOapi.tm CB.arg2= (o.c_ulong,]w_objecteclass qExceptionFpasse&\(Le# First check it works when settingXAfromCsame?Stid =get_ident($IsInstance(tid, int(rGreater%06try]result =9d3e# The , so we might haveAkeepVM busy untilQ itFices`while    . *:lsepis codeunreachable butreflectsintent. Ifkwantedto be smarter5above loop wouldn't#infinitedfail(" raised" :$bEqual(, 1) # on sw modifiGUnboundLocalError13was too quickly for u @0# `RPer_st> d`aset byIqit's inside a try/Nblock waiqo catchJhronously? aw^ upl'at6ion^ *Ev+1r@Workl *@run(J h.,00sheVFalse try:  while True: worker_started.set()-time.sleep(0.1(except AsyncExcvself.finished =r2aw_Y3ion0Qt = Wt.daemon]& # so if this fails, we don't hang Python at shutdownb._if verbosWpprint("W32ed thread") Vs# Try a id that doesmake sense.3wtrying non<Ficala"Presul:Pset_aaU(-1, i.assertEqual(?, 0) # nodstates modifiedNow raise andz in the&@wait:forF to get  H>F(retQverifh1 haPexite$iuFalse(tqaattemp $tojhn  Ot.id 1) # one  = o say it caught6)_s3Q(fout=10Y~}%ll OK -- join}  t.6}P# elsH8 is still run`P, and@have0wayk$"itydef test_limbo_cleanup()# Issue 7481: FailureL9chould D~VF mapr^R_new_g(*argsp !Qing.TWErrorL# =4 'X $! =T6&ry%K(target=lambda: NoneN6^.,R,s(D2, tV>\t3ing._limbo,  0"Failed to cleanup _limbo map on failure of Thread.start().") Kfinally:t/Qing._3R_new_= =  =def test_Size_runnning;f(self)j# Issue 1402: the PyGILState_Ens/ _Release functions may be called|# very latepython exit:deallocaC a Cing 7forLexample.import_module("ctypes")rc, out, err = assert__("-c", """if 1 @a Y, sys, time, @k/ # This lock is used as a si event variab< y. e_N(,.acquire(1# M globals arered before __del__5runP?So we savein class dict5C=Ne3=C.{Mapi.X Q<re=  > ]s0 = . m*Celf.(7 yrrwaiting(YF_x = Cb_ <v.sleep(100zL(J, ()YuHq # Be Tother3is N@sys.:(42]'""_`Equal(2: with_traceq1733757?# Avoid a dead4P whenA.setK steps intoOfhutdow'/ok" A-killer,""pr5the Psuite'Phang &ve (6Oio b>Q print('program bQed; abor'3Aos._  O7t =nrtarget= Lt.daemon = Trutx!is 3@(fra_, arg#scurrentg()  return func sys.settrace()B""")1def test_join_nondaemon_on_shutdown(self):A# Issue 1722344Raising SystemExit skipped threading.X9 rc, out, err = assert_pythk("-c", """if 1fimportbX!from time +Rsleep$ gchild(8*(1L# As a non-D we SHOULD wake up and nothingO# should be torn O yet.print("Wo]!, tion is:"cT(target=).start(Wraise ^a=.Equal(out.strip(),7b " lnerr, benumerate_afterTry hard to trigger #1703448: ais still Ued in#&v1() x it has been U()ed.<0/ =A#old_interval = getswitch:try@for i in range(1, 100YsYi * 0.0002t ]lambda: None:v"t.%m.NotIn(t, ly+"#ed %dals: %s" % (i, l)kfinall]5yno_refcycle_through_ class RunSelfFunc{(object^__init__G,__ . # The linksTthis  NP backe pcleanedwhen the completesW.  s1&O_runzRargs=D 1!kw?p{'yet_a@er':}I1. def _run(self, other_ref, yet_anK): 0if 2.should_raise&5 SystemExit Lcyclic_object = RunSelfFunction(\u=False)<\weak_Aref.ref(8 .thread.join($Idel (vassertIsNone(s 5(),0 msg=('%d references still around' %=Jsys.getrefcount6)))f:ingn c ..rNotIn('G0', U8(t)0 = dDA*El_param72(t.N a% kN!xMP@unit.skipUnless(hasattr(os, 'fork'), '&p needs 2()'fACummyYq_after_)# Issue #14308: a d91 inVW list doesn't mess up#*j-j mechanism.$0codz"""if 12simport ,Ping, FtimeqQbackg<8G(evt(# Creates and registers the _DummyThread instance t ing.current_-()+evt.settime.sleep(10) :bevt = UgLEvenDt.start_new(background, (evt,)lse};os.5"""_, out, err = _python_ok("-c", codekRself.*aEqual(A?b''#Qerr, #z@unittest.skipUnless(hasattr(os, 'P'), "needsb"e@def @`_is_al`after_7() # Try hard to trigger #18418: A() could somes be True on{#s that vanished ~0 a .. old_interval = sys.getswitch4.addCleanup(0s0(, VRa# Makebug more likelyPmanifq?q.suppor G1e-6^for i in range(20a [(target=lambda: NonG6Vpid =1if /= h11 if t.Pelse F)wt.join(pid, statusZApid( 5mK(os.WIFEXITED(I  6b010,W9fSTATUS=Cmain  p,W}'.name, 'Main 2Xident F."y %GAget_'()+f(~2NotKo,M? )thm6f-th)th. 3) @unitt'est.skipUnless(hasattr(os, 'waitpid'), "test needs os.()") def "_main_thread_after_fork(self):+/code = """if 1pimport HEing :"Ppid =[1if := 0W5 = W.(H/`print($_.name! xident =]ucurrent`.$FAget_9*();Nelsefpid, 055"""G_, out, err = assert_python_ok("-c", ?@datawPut.de().replace('\r', ''..XEqual(err, b"0_ #b, "MainTBd\nTrue"")P@unitmIf(sys.platform in Ps_to_, "due to known OS bug OgF3ILM _from_non^Ma(R, sys_'f(T`  !3 %2#J;# stdout is fully buffered because not a tty,:# we havflush before exit.4x.24u8 e)th(target=fLth.startwth.join$-1) during_shutdown# bpo-31516: ) should still pointAthe ;T# at icimport gc, threading amain_t2 = ing.current)()5xassert <'is=() # sanity checkclass RefCycle:gdef __init__(self)$( .cD0 = g#K?delJ print("GC:",H+8 isE 3B!enumerate() == [R*])o gc.collect5x =D5"""1_, out, err = 1_python_ok("-c", codeZ`data =70.de[.FEqual(err, b""? #P.splitlines()[V Truec"] * 2;=test_tstate_lock# Test an implementation detail of Tjobjects./started = re.allocjofinish)S.acquireMC+f(bHhreleasH Ltime.sleep(0.01b# The K K4None until t+3is -tS(target=feXIs(t. , n,!t.e%/ed&X1(t.is_alive()Rcan't be kd when@runn?# (or suspended)3> +gFalse(6out=0), &;# WQends,"@ cansuccessfully# \L 5f# But WQstill: we hold  now, whichpreventsNfrom knowing's end-of-life CKis doneB)Le@find{f \release()  self.assertFalse(t.is_alive()) #"# And verify the thread disposed of _tstate_lock.:aPIsNonb*dt.join() <def test_repr_stopped(N!):!VCat "&" shows up in @!(T) appropriatelytarted = _d.alloc(ofinish)sS.acquireC'f(HhreleasHL3t =Bing.(target=f!t.`/edS|+CIn(")"",bt.#0uld0earW a reasonable amountcFtime # Implementation detail: as.his writing, that's trivially trueJ3if  is called, and almost: 0+7 isL>c. Thea we'reing hereh L"all on its own"LOOKING_FOR =E<Pfor iNrange(500\8if D-t'iUbreakZsleep(0.01T (a* # we waiu0at t 5 secondJBoundedSemaphore_limit (traise ValueErr&#f d too ofteniIcML1, 1O)bsu ~(C(E8[y$bs ;?_h]#t#gsDD 8/f? = tRE&s(FU, bs.~@cpython_onlyTframe ~tracingIssue #14432: Crash when a generat`s creaLiC destroyed wh(ile the generator is still used. The issue was that a #8contains a frame, and\ kept a reference toLPython state of destroyed C threa crash occurs when a tracePfunctioneetup. def noop_5(, event, arg):+p# no op#9iongreturnM eY(S wh|1hluyield "9"QcallbackP4if 1.geNNone` &=/()Hext(3&0 = n2old\ = sys.getk@s!:try# Install  )Oing._ ,P# Creqa  iOq which exits after Jimport _testcapi.8`_in_te0bary_c_g)G0# C 1difN#t <Ir, check&thNZ didn't keep}X @for 3{range(3tGijed her:wkfinall L|) class T<JoinOnShutdown(BaseTestCase):u _run_and_join(self, script = """if  sys, os, tiG2ingl#,m wam]he main program7zerminat/0ing(6qo.4 "print('end|'## stdoutfully bud because notty, we havUflushK# beforeo.p.@s\n""" +arc, out, err = assert_pl_ok("-c"q`data =9 .decode().replace('\r', ' #.Z`Equal(?3, "=m#\n 3\n"B!_1oT_on_sX#usual case: on) , 1 0a non-daemon2= """if 1:  import os  t = threading.T (target=joiningfunc,5A fargs=(Lcurrent_Y(),))Et.start(ime.sleep(0.1print('end of main'!5"""cself._run_and_(script) $%@unittest.skipUnless(hasattr(os, 'fork'), "needs os.2()"u AIf(sys.platform in Ps_to_e, "due to known OS bugO@def !_2@_in_oped_proc!):u# Like the8 above, but from a @ interpreter=  = """if 1W[childpid =;!5if $J!= 0?"os.waitpid(*2, 0: 5cexit(0}}3}Kork() was calledcworkerrSA# In,  object must be marked as stopped.D U  S(5%9&=,AE7N; %(%) # Should not block:Pis alyIw@ wR'74_daemon-s( Check that a daemon thread cannot crash the interpreter on shutdown # by manipulating2 nal structures that are be#disposed of iLrmain thread.gscript = """if True:import osorandom/sy1Otime/Iing _has_run = set()$Bdef Z_io() '''Loop for a while sleep2: tiny amounts and dosome I/O.'''XJ2in_f = open(os.__file__, 'rb')O3@stuf4;.O(200+Inull`0devO, 'w_ _f.write(l\.#( .() / 19957_oclose(#! R.add(ing.current_/() cM = 0x@_ inE_ge(40C3newy# =GTQ(target=(?_ioD`.daemoA qP.star M+= 1F3lenDIA) < 7-^^0.001# Trigger processIsys.exit(0 5"""rc, out, err = assert_python_ok('-c', Rself.,False(errx%@unittest.skipUnless(hasattr(os, 'fork'), "needs os.2()"` A0If(platformA Ps_to_e, "due to known OS bugO_reinit_tls_after_v# Issue #13817:k() would deadlockra multi# edgram with]# ad-hoc TLS implementation.b!do_and_wait`a# justq a chilwL45 it~0pidc 0if >> 00os.Opid(pid, ;elsm~ !# V a bunch35VAwill*()e1E= []Qi in range(16):  t = threading.T (target=do_fork_and_wait) 96s.append(.start() 5for t in::Wdt.join0@unittest.skipUnless(hasattr(os, ''), "needs os.2()"@def @r_clear_s_states_afterf(self) # Issue #17094: check that DQ are ]1ed P #+rt a bunch ofDU = [])i)range(16+ lambda : time.sleep(0.3)>wVpid =e1if 6= 0Db#:have been@O:if len(sys._current_frames()) == 1j4os._exit(0Oelse.1.* _,2tuspid(pid, gD.assertEqual(0<  class SubinterpingTests(Base bCase):m_K:# Non-daemo should be 34t szreter shutdownC# (i$F8808DBr, w-Vpipe(.addCleanup(os.close, r%w%code = r"""if import os?ing2imeK2S'f(?0# SUTit soe is still running whe=C# Py_EndIjis called./ &05os.write(%d, b"x %f)'""" % (w,i!re+ upi.run_in_0(29ret;E# Th74wasproperly K0os.d(r, 1)6s ._2Same as above, budelay gets introduc/% t'bPthon returnedNPbeforPe!Xdelet# To achiev.is, we regisa]-local object which @a bipen deal3ted. r, w = os.pipe()  self.addCleanup(os.close, r%w%code = r"""if 1:cjimport osthreadingIime class Sleepergkdef __del__()#'`time.sEj(0.05)detls = {.local(%j/f(`# a bit so that theR is still running when# Py_EndInterpreter:}called./ Drtls.x ='er&os.write(%d, b"x"#T(target=f).startR""" % (w,F0retXpest.sup.run_in_subi(I2.assertEqual(ret, 0!6# TYwas joined properly) K0os.zd(r, 1)X@cpython_onlytest_daemon_ s_fatal_erroro_RMake sur"e U1I ,_=TrueVHPscripRv _Jcapi%h Pwith fSuppressCrashRe *rc, out, err = _xfailure("-c", PIn("F! PN>or:;5: "82"no0las "0.deb()) xingExceptionTests(Base CCasep# A RunE  should be raised if P@# multiple Fsm_ul_againsBing.q$xdR(s(,;7M/ing_current  imeError, current_thread.join); def test_ing_inactive-q(self):,0C2 = Qing.TV%()$3 .assertRaises(RuntimeError,; daemonize_.o.startesetatt2, "v", True`8+()`releasOunacquired_lockO ML%eK @.neP@unit.skipUnless(sys.platform == 'darwin' and.support.python_is_optimized(), 'k macosx problem'\recursion_limit# Issue 9670i# that excessive J within a non-mainWw causesH!anAption ratherWn crashing the interpreter on -Ilike Mac OS X or FreeBSD which have smallVault stack siz fo^script = """ifkuq im2ingrk'e(creturn>e=_outer;:try2okDpt REJpassw\qtarget=\hw print('end of 3(5"""expected_outpu@&\n1p = subpro.Popen([executable, "-c", ]]xstdout=UIPE, stderr8( = p.communicat]@datah .decode().replace('\r', '%Equal(p.a:, 0, "Un: eS: " +c3elf2R$, D~d_n 6:! = Twhile=Lb .sleep(0.01)  @1/0 t = threading.T (target=run)-z.start(while not running:5jtime.sleep(0.01@6 = False=kt.joinq5"""%rc, out, err = assert_python_ok("-c", scriptwRself.,aEqual(C6b''#Perr.decode>In("Exception inL"M 2Traceback (most recent call last):A ZeroDivisionError00NotUnhandled e5M @requires_type_collectingdef test_print_C_stderr_is_none_1()z = r"""if Trueimport sysjIime L Grun(idglobal RV % > !Bsys.j = Nonm26 N~e t.join() 5"""rc, out, err = assert_python_ok("-c", scriptFRself.,aEqual(C?b''# NotIn("Unhandled exception"x.decode()) def test_bare_raise_in_brand_new_thread(!):372(G`class Issue27558(TQing.T^ ?exc = NoneDHuexcept O/VError<!if"MQraiseG=if \I'E$ (ifine)') else:   if output and limit is Noneresult !='#: 9if verboseprint('no')4raise AssertionError("%r %% %r ==!9" %:V (formatstr, args, ,)}# when ''specified, it determines how many characters# must match exactly; lengthsbalways#.92ex:c=5, '12345678')#esG___'5 (mainly for floating pointmat tests which anXKcan't be guaranteed due to roundZrepresenta esI/el66not:(yBlen(0)!= zC) or![:2]!=)_w!1"%shshs}%s" % \0 (a)\0pr(g )t,elyes') deffcommonn=,W overflowok=False>@# if&/!a 8@ abytes, aarray;# otherwise, !s+y)if isinstance3strt$[&, "b_=& =.encode('asciiv 7&baQ(/x b_Q = []40if  d, tuplt1 = 8+, L-Z"b_V = ba  :,V%G* ` <Pci", e+>7n,!@[N_excPexcep, excmsg36tryK~EAL0 as A ifP(exc)jF,R"yes"q1C print('no')  &print('Unexpected ', exception, ':', repr(str(exc))) @$: if verbose: U2no', iB7ion&QraiseTFelse^ TestFailed('did not get Sp: %s' %msg) def test_exc_common(formatstr, args0exc9#; str and bytesRK1.encode('ascii') class F P(unit.qCase): h_b(self)Bthe ! identifiers that work !same acros@=,arrays (integer, float, oct, hex("%%", (), "%""0.1d$ 1,&1&*&sys.maxsize,1), overflowok=True) #8: A.100Rx/'0'LP: _J.1'x e#.117x=<'0xgz. J51',; " 80f".0.#se are trying tolimits of'  rnal magic-number-length#&tL@buffiA2at 3p change= enZ!sess)le=effectiv !*g09, -1.e+49/3.//10/#:100_some ridiculously large precis&I '%12.*f', (123456, 1.0))p# checkep validaB on 5thexshould no longer ca use overflow in Python # 2.7/3.1 and later.testcommon("%#.*g", (110, -1.e+100/3.))0G0f0F0 # Formatting of integers. Os not ok@x", ?"a""0, "174876e8005oW/12# W0X3510355640[d[~# [7 big = 1234567890 - /e0big> @-A-vB5C//31D02D $(-3FE  0FX-G2 4?-00$!03H++H+& GF +{ <F.6. B 30C+FC$232.F G$float(big)_e", 6)  &0x@aabcdef # 21 hex digits7 /6UF79stcommon("%5 x", -big, "-1234567890abcdefC") testcommon("%22;'3; w(-2=< 0=0->={5?-00}!02?0>+?+? >O +u{I=.f91p:"t223.w >-?>bBX", x)aABCDEF#8!0X*:a&0x:<#:v< 27>P@-A=X10A"#./0x ?@A)27/ -DB /#0D++ A  C8+0XF0# next one gets two leading zeroes from precision, and another 5the# 0 flag&the width #+027.23X", big, "+0X0001234567890ABCDEFC") testcommon("%# 027.23X", big, " E # same, except no 0 flagf+e-Ex8+0xaabcdefT !- E E big = 0o_$67e  # 32 octal digitsD yoS B--D%5E1/33F24F &(-3HG*0H  r-I 8 6!-!03J;0I)+J+J( IL +  8 H .2m# 4 D3E2^234.H I&-JI`/#CEGG(&38yK(-LH 5670 ")  testcommon("%#038o", big, "0o000012345672") J* L:.34LJ---L&)38/ N*-OM/ 30O(++ L6++ +-PO,- :P+Q PP# next one gets leading zero from precision7.33# base marker added in spite of (different to Python 2tofreduceY, andis alwaysG#.32o   , plus tw"0" flag & width:035T  shouldn't change the size{#|M# Some small ints,+Dboth 1intflavors).< d", 42, "42q #-$-% O42.0J `#x", 1C/x1n$#X$X$HHo$ ?0o0lG0, "0") testcommon("%d", 0, "0")  !$#x"x$X$X$Gx42, "42m%"-0&-'oooL %"-0& L # alternate float formatting'%g', 1.1, '1.1'*9'%#&u0000') Pif verbose:pprint('Tes exceptionsgS_exc_'%', (), ValueError, "incomple f B0 %s D "unsupported- character '%' (0x25) at index  } d'Kc', Typ|%s: a number is required, not str r?b'1s9_bytesu xxZ: an integ!tO3.14\u&"@def #R_str_:f(self)"%r", "\u0378 "'\ '") # non Eable Aa75 A4A4/ #~=>= #  unknown 6mat=us, etc.='1('abc %b b'625#(unicodez0\u3c,'raw--escape'), 1u#n ?c  "must be realRF C('no"all arguments conve=`during$Vc', -1, Overflow %c]in range(0x11u)K'%c', sys.ma xunicode+1, OverflowError, "%c arg not in range(0x110000)")2#test_exc('%c', 2**128a P O3.14, TypeIrequires int or char CO'ab'C,?b'xCif maxsize ==U31-1:r # crashes 2.2.1 and earlier):try>s"%*d"%(ef, -127"except MemoryAFIpassNelse'raise TestFailed(' should fail') YAdef bytes_and_ array_format(self)v # %c will insert a single :, either from an256), or|#(<s0ume:f length 1,OU str.=common(b"%c", 7, b"\x07s &@b"Z")Z& 1yte(0)1 5~ 65%AZ-*A+*L# %bZeries of! ^ type that support/ # the Py_buffer protocol something=qhas a _@s__ %odhclass FakeB&w(objectJB 4!return b'123'`Gfb =_( b abk b"* Adef" x_ fb7123&mSview(6 # # %s isalias for$--only be used`Py2/3 s*5&"%a0giv e 2valp# repr(_obj).en ('ascii', 'backslashreplace'Ba",  b")Qb"ghiRob'ghi'- A"jkl,O'jkl+ b\u0544.\ 2# %r is an alias focr %a  testcommon(b"%r", 3.14, b"/"))`b"ghi"+ob'ghi'- A"jkl,O'jkl+ b\u0544.\ 2 # Test exception for unknow mat characters, etc.=if verbose: pprint('Z6ing]*s'._exc(b'%g', '1', TypeError, "float argument required, not str#LbM_bytesO noxmat', 7 "5alls converted dur jROtingu xVytearray()T"%c", -1, Overflow 0"%ch in range(256)RW?256XC_**128[B_b"Za"| s an integer  or a single &/"Yq\W`b", "Xfl^bp1s a2s-like object, "4 "en" that imple@s __x2s__@'str:0 ;0"%s/Wd Uif maxsize == 2**31-1 # crashes 2.2.1 and earlier):try s"%*d"%(e&271"q MemoryFEpass5lQraiseFailed(' should fail') def test_nul(self):  # test the null character" common("a\0b", (), ' /')'!%c'/0,)format("a%s)b'c\0d'. bYb1b24b'a31def_non_ascii\u20ac=%f!1."11.01") Z3?.assertEqual(Iaabc", ;07<5"), "abcK"07".G<123E2123?E.F6?12.G&0j4E"0j'+2E8Eb(1+2j)C`>`?`E?1232`>`lG>A)I>A/0j`^` EE`^`ZG`^`ZI`^``zmlocalew&ryxLoldloc = 0B.set (v.LC_ALL5,7, ';dexcept_Error as errskipTest("Cannot se;c: {}".Ferr)tFconv(:5sep&3['thousands_sep']x.[point0decimal_&']10tex0123456789, "n@*In(sep, = )lf#p.replacp~5, 'j':g17 = /.501In(lf.assertEqu"al(text.replace(sep, ''), '1234' + point + '5') finally:locale.set (.LC_ALL, oldloc) 5@support.cpython_only def test_optimisations(self)q = "abcde" # 5 charactersc6.assertIs("%s" % <, )/.5+/10,1*{0}".format) O{0:s2/.54 /105132O % () 'X+Sprecisionqf = 1.2. cEqual(f, ".0f"), "1"030G.2004Wwith  Raises(ValueError) as cmE0%sf (sys.maxsize + 1)/c = complex(fc7+0j 3Y+0.00;*` _c_limit`from _pcapi im INT_MAX +*P%kx* U x if __name__ == "__main__"@unit&.(() <&Aead>U` 
from-\N#"toL//_d0">f1nO2">2h "1.Beautiful"isybeTTer*Bthan Uugly.T/ttE3">3F| Rsub">2Explicit.tt"im,.N 63?E4">4 u3Se wcomplexlass="diff_next">
  
3)nowrap=""> y3.bSimpleD"isbbetter Bthan co*"x.g/tr> =5\2td :sub"4.C sicated.E4">4D  e4 335OFlat,=nes+4B6">6&12o$`?O7">7I`?O8">8I`?O9">9I`?o10">10Iblass="diff_n#ext">11-nowrap="U">123Ind/tobg/tr> =1Ab@_4">14Jb@_5">15Jb@_6">16a%_a href="#d2">n17 h "1.Beautiful"isybeTTer*Bthan Uugly.c01U/tt*U8">18J Rsub">2Explicit.tt"im,.ff_next"> =19wh "3.bSimple "isbbetter Bthan co*%x.eto0_18">18F"my3.% 20:sub4Csicated.%f   e4 55OFlat.=nes-4yb21">2122Ab@73">Ab@_4">24C="to0_24">24123g/tr> 118td  header" id="from0_25">25-rz Id/tob@_6">26Jblib_chg_C/_2_7">27Jb_8">28Jb@_9">29Jb?o30">30Ib@_1">31=3_a href="#dtop">t32 ;h "1.Beautiful"isybeTTer*Bthan Uugly.e2D class="diff _chg">tter than ugly.
33^td nowrap="0">< ^Rsub">"2.Explicit"isNbett"im,.5EU4">34 w3Se scomplex#/to.3.:add8%@_5">354Coicated,f   e4Nq(55?Fla=nes-4_6">36&12Ddub@_7">37Jb@V8">38owrap="nowrap">123header" id="to0_38">38+nowrap="bg/tr> ?39z(b?o40">40Ib@_1">41Jb@_2">42Jb@F3">40p'4b@_4">44Jb@_5">45Jb r (` 2Bd>  Added  -AKchg">ChangedA>
Deleted
& <8 border="" summary="Links"Te 3h=d>(f)irst change> 8On)ex7 Ot)opf /

Cont!(f within numlines=5(default))

}Dnext">
from
f1#nowrap=""D2H@0  O1">nO2">2h "1.Beautiful"is0be< }chg">TTer*Bthan Uugly._T/ttE3">3F| 2Explicit.tt"im,. 63 class="diff#_next">4+nowrap=""> "3.bSimple "isbbetter Bthan co*%x.eto1_3">3D Y =5:suby4Csicated.$`   e|4a g z35OFlat,=nes+4oE6">6  9&12o$`?O7">7I`?O8">8I`?O9">9I`6d="from1_10">10123class="diff_next">header" id="to1_10"bc/tr>  !11Ab@_4">14Jb@_5">15Jb@_6">16 1_a href="#d2">n17 h "1.Beautiful"isbeTTer*Bthan Uugly.:0U/tt&U8">18J Rsub">2Explicit.tt"im,.next">19wh "3.bSimple "isbbetter Bthan co*%x.eto1_18">18F"my3.% 20:sub4Csicated.%f   e4 55OFlat.=nes-4yb21">215123u$b@U2">22 1b@73">Ab@_4">24I24">24123  25^z d#/tob <!lib_chg_/_2_7">27Jb  _8">28Jb@_9">29Jb?o30">30Ib@_1">31 3_a href="#dtop">t32h "1.Beautiful"isybeTTer*Bthan Uugly.e2U/tt WS33">3W f_sub"> c; "2.Explicit"isbbetter Bthan "im,.34ow3Se complex.eto1_33">33F< Radd"> %@_5">35:sub4Coicated,f   4N36$ =&12@%b@_7">37Jb@_8">38Jb,_header" id="from1_39">39123class="diff_next">header" id="tobg/tr> 140:b r

Context (first j after numlines=5(default))

38h@br /h>F375456PB)0f` vE8">8 0`??9">0`?_10">10b@_1">11c1_
n header" id="from2_12">12-nowrap=""> "1.Beautiful"isybeTTer*Bthan Uugly.7V/ttg/tr> =13J?sub2Explicit.tt"im,. 65@U4">14 w3Se complex  .3.:add8%@_5">154Coicated,jf   V4 555?Fla=nes-4{R6">1616+nowrap="R">123g/tr> =17^2td rz db@_8">18Jb@_9">19Jb?o20">20Ib <! lib_chg_$/_1)o22">22Jb  43">C2b@_4">24Jb@_5">25Jb@O6">226+nowrap="Dg/tr> =n27h "1.Beautiful"isybeTTer*Bthan Uugly.H7V/tte U8">28J_g Rsub">2Explicit.tt"im,. 65@U9">29 w3Se complex G  .3.:add8%?o30">304Coicated,f   e4N  31-nowrap="U">123d /tobg/tr> /U2">32;b@F3">3Ab@_4">34Jb@_5">35Jb <!Xlib_chg_/_2_7">37Jb  i_8">38Jb@_9">39Jb?o40">40Ib 41-nowrap="Fa/to_g/tr> a href="#lib_chg_j_top">t42h "1.Beautiful"isybeTTer*Bthan Uugly.2 4U/ttU3">43L Rsub">2Explicit.tt"im,. 65@U4">44 w3Se complex   .3.:add8%@_5">454Coicated,gf   e4N "5.BFlat "isbbetter Bthan nested. 46^td nowrap="U">123d /tob//t>U7">47;b@_8">48Jb@_9">49Jb?o50">50Ib r

Context (numlines=6)

<+^ lib_chg_to3__top"2cellspacing="0" Dpaddrules="groups" <Ah_@br /h>310H nheader" id="from3_2">2+nowrap=""> "1.Beautiful"isybeTTer*Bthan Uugly.CT/ttg/tr> /3F?sub2Explicit.tt"im,. 63?E4">4 u3Se complex   .3.:add8%?O5">54Coicated,^`   |xT4 35?Fla=nes+4 kB6">66)nowrap="R">123g/tr> =7\2td px b`?O8">8I`?O9">9I`?o10">10Iblib_chg_/_1|o11">11Jb2Jb@C3">16C1b@_4">14Jb@_5">15J5">15123  16^tza /to_a href="#lib_chg_j_2">n17ksh "1.Beautiful"isybeTTer*Bthan Uugly.c01U/tt U8">18J Rsub">2Explicit.tt"im,. 65@U9">19 w3Se complex  .3.:add8%?o20">204Coicated,cf   V4  eader" id="t o3_20">20 "5.BFlat "isbbetter Bthan nested.g/tr> 121^5123d t@b@U2">221b@73">Ab@_4">24Jb@_5">25Jb/lib_chg_/_2d_6">26Jb@_7">27Jb@_8">28Jb@_9">29ap">123 header" id="to3_29">29+nowrap="R">123g/tr> =30^2td rz'b@_1">31$3_a href="#?lib_chg__top">t32 h "1.Beautiful"isybeTTer*Bthan Uugly.e2 3U/tt C3">3Rsub">2Explicit.tt"im,.  Q5@R4">34^53Se complex 3 .3.:add8%@_5">354Coicated,3_34">34 "4.Complicated"isbbetter Bthan c/Pex. 1355)55BFlat. onested-Bfrom3_36">365123d@b//t 2xU7">37 1b@_8">38Jb@_9">39Jb?o40">40Ib@_1">41Jb r

Context (numlines=0)

<+8"^lib_chg_to4__top"2cellspacing="0" Dpaddrules="groups" <A < # 
from-N-"toL//Ubody>d2 id lib_chg_to4__0">n2 "1.Beautiful"is0beTTer*Bthan Uugly.08T/ttE3">3F?sub2Explicit.tt"im,.j 63?E4">4 u3Se complex t .3.:add8%?O5">54Coicated,^`   |xT4 4_header" id= "to4_5">5 "5.BFlat "isbbetter Bthan nested.c/tr>  !1n17B1+Beautiful0uschg">TT.NUugly. 2:V/tt 1 U8">18J ?sub2Explici"im,    5@_9">1953Se/complex  / .3. 8%?o20">204C=ica f   ' 5'rap="nowrap"> "5.BFlat "isbbetter Bthan nested.  !yt32td nowrap="-1-Beautiful2wschg">TT0PUugly.4>V/tt'/t5  U3">33L?sub2Explici"im,   j53_4">3453Se3complex  / .3. 8%@_5">354C=ica f   L' 5(f_add"> c; "5.BFlat "isbbetter Bthan nested.
r

Same Context

5<# class="diff" id lib_chg_to5__top"2jcellspacing="0" Dpaddrules="groups" <A
from1nowrap=""= D} /to  H O2">21Beautiful.TTUugly.e: \jff_next">3 "2.Explicit"isbbetter Bthan "im,.honext">/toag/tr> =4hp 3pSEePn complexm.\j?O5">5j4jC@koicatedo.at?O6">6t&12j$`?O7">7I`?O8">8I`?O9">9I`?o10">10 10+nowrap="R">123g/tr> =11^2td rz db@2;Jb@C3">1Db@_4">14Jb@_5">15Jb@_6">16 I_@U7">17 "h "1.Beautiful"isbbeTTer Bthan Uugly.e"%]n@U8">18 n2nExplicitOm.ttm"im,q/td> "2.Explicit"isbbetter Bthan "im,.  19^2td  3Se scomplex#/to`n?o20">20n4nCDooicateds.cx@_1">21x5123J 2b@U2">22 1b@73">Ab@_4">24Jb@_5">25Jb@V6">26owrap="nowrap">123header" id="to6_26">26+nowrap="bg/tr> ?27z(b@_8">28Jb@_9">29Jb?o30">30Ib@_1">31I$3_@U2">32h "1.Beautiful"isbbeTTer Bthan Uugly.e"%]n@F3">3tn2nExplicitOm.ttm"im,q/`t@R4">34}td nowrap="nowrap"> "3.bSimple "isbbetter Bthan co*x.header" id="to6_34">34+n"="Ag/tr> ?354nCDQooicateds/bx@_6">36x5123%b@U7">371b@_8">38Jb@_9">39Jb?o40">40Ib@_1">41Jb=6_42">42123header" id="to6_42">42+Zbg/tr> ?4z?td %b@_4">44V(b@_5">45Jb r

Empty Context

<$]Clib_chg_to7__top"2cellspacing="0" Dpaddrules="groups" <AhG@br /Mh>3
t

tabsize=2

(< B" id92F cellspacing="0"Dpaddrules="groups" 1col5>fIz_"erfrom9_1">1Lnowrap="" D /to }c_ c O2">2IspanARchg"> Lin"1:%preceded"byR:[tt]to:[ssss]]F E3">3T|< M 02-sst  ?O4">43p; &nbsp;
Line 3:preceded"byfrom:[sstst] tossss]header" id="to9_4">4)nowrap=""">n< f:chg#)?g/tr> ?54 2has-h Rafter):$?E6">6(5  t>end4sub~$L  xr

tabsize=default

`<&/[lib_chg_to10__top"3cellspacing="0" Dpaddrules="groups" <A1 1 5  e/>tE2">2   ?p;Line 1:preceded"byfrom:[tt]to:[ssss]tAheader" id="1E2">2*nowrap="y"> Lin0g/tr> ?3; 42.-ss0t1 !  9U&@O4">4&eO&3&sWY (!E?@O5">54P.2hasQ( DRafter):G?-@E6">6*5 ss] at&nbsp;end&  6Enowrap="b">Line"5:2has from:[t]cto:[ss "atc/tr> r

Context ( column=14,numlines=0)

K<9@lib_chg_to11__top"3cellspacing="0" Dpaddrules="groups" <An4[>21%Wadd">Iadde  f vU>Xd:1 2 4^Nchanichg">gBG5eICdQrEr4 id="from11_7">7line 5 header" id="to11_7">7*aG/rg/tr> 1 >"ed)td?r.4from11_8">8 6 gYg,gO4e1IWEr R\<!l0lib__2">n10X 8subM8Tsubtr$T19add  ` P cty 8  J3 otop">tR2">12 ap">1234567890 t< 0add2 g/tr> ? B>I5689B~  b f$5lfrom11_13">13B?td Rshort}Oline+sanother3ong 5*u$ `2iner3tha_needsob ?pedA*U4">14 *3jus>fitTchg">Ein!!O03/S: 34DU5">15D st6+& }owrap="nowrap">just fits "int  nowrap="B">woqlines)Ryup!!\S &r

column=14,splits()

i<1B" idjlib_chg_to12__top"3cellspacing="0" Dpaddrules="groups" <A
f10$P-1 K E2">2 1234567890 'o |l4O5689$`1&5?XE3">3 %i2O1">n"from12_4">4line 2B,next">n4i 9addIaddeg/tr> 15 -3$ki2E6">64Nchanichg">g)td51gBG 5Id>rEr5&2"w6E7">75u ,,ate,?ff_chg">ed  8]td nowrap="">line 6 RZOerErbE9">9  b7$Pia href="#On10 8sub8_TsubtrT@1d9addo nP ctS Yw W4b11">11_ uNmkotop">tU_2">12U1234567890 3[ 1234567890 nowrap="0">)89~2td u}b //td0 id="from12_13">13BaRshort}Oline+/to!sanother3ong 5*u`H2iner3tha_needsob?pedA*U4">14 3jus>fit7Tchg">Ein!!O03/S: 34DU5">15D st6+&}.4NwV Zchg">s
&nbsp;yup!!header">nowrap="">wo lineS)g/tr> ?162the5end% n/tol! r

acolumn=14,split^s(True)

7<5q"lib_chg_to13__top"3mcellspacing="0" Dpaddrules="groups" <A
f1i 0$P1 K E2">2 1234567890 '|l4,O5689$`1&5?XE3">3 %i2f="#difflib_0chg_to13__1">n4<,nowrap="y">line 25 -3$.ki2RE6">64Nchanichg">g C1gBGd  Id>rEr5&2"E7">75u ,,ate,? class="diff _header">>ed9g/tr> 18]line 6 UchangY/to/a O20lib_/_3h e)td:rErbE9">9 b7$Pia href="#On10 gVsub">'8_TsubtrT@1d9addo:nP ctS\j8 4b11">11_ u3Qkotop">tU_2">12U1234567890 d class="diff_header" id="to13_12">12Ag/tr> 1 Rsub"> 12)89 c~ b f0l@fromnR3">13BanRshort}Oline+sanother3ong 5*u`H2iner3tha_needsob ?pedA*U4">14 3jus>fit7Tchg">Ein!!O03/S: 34DU5">15D st6+&}.3">>wo lines)yup!!header">Sg/tr> ?16 2the5end%9 n/tol! r ! _compat_pickle import (IMPORT_MAPPING, REVERSE_ bm NNAMEB#) pbuiltins$io collectio+dstruct!%syDweakref unittest 0sup .%$er'AbstractUn_Tests4P_2oModule8ersistenttr=IdentityPE)x'rObjectDispatchT9bBigmemy0Q try:chas_c_implementaQ = True except I RErrorG4False 7 Py(1)Sdump = scmethod([ ._) s' s(Oload'&N'NDr =  1): TuWt)r"bad_stack_ea(Index,truncated%N2ing1B EOF _ Attribute(S Valu 4.', U)Adef v(self, buf, **kwds%f = io.BytesIO(bufuEelf.@(Creturn u.m() class PyPic klerTests(AbstractPickle): p3r = "._%r.un UAdef dumps(self, arg, proto=None):Ikf = io.BytesIO()@p = =.m#(fB#.dF(argf.seek(0return bb(f.read())Dloadbuf, **kwds6buf^uC u.m() class InMemory_$, h+,`J gBigmemXbad_stack_errors = (c.]@ingEq, Index truncated<1EOF:Attribute(S Valu qstruct., ImportK!v zD;IdPi>(Py~DBDumpR_Load 2(Py r {&&._OszC{WTaObject^$@.> *aptest_issue18339m'.e(io.BytesIO();Qwith 4assertRaises(Type/].memo = o5$ # used to cause a segfault'~OValu{-1: None}\ {'(z| 0 2Q6)tchTableTests(AbstractDispatchTableTests): pickler_class = ".P'def get_dL _tMW(selfMTreturn collections.ChainMap({},a I!) j@support.cpython_onlyaSizeof(unittest.GCaseqcheck_s.5 = VqI_r@baseOM`alcobj('6P2n3i1P')ZCp = ZU(io.BytesIO().P.assertEqual(object._t__(p), =!MT&truct.calc[3nP0n/ME/)of&(p) + d+ 8 * + # Minimal memo b .Dpsys.getof(b'x'*4096))Fwrite bufferHfor i in range(6@p.dump(chr(i,328 ofrequired to# save references to 6 9s;0$Wpis clea{after every /).*/un,(q2P2n2P  i5 3n@+2ifCUz "P !P'iZentrynBnB3arkBF! uencoding|'ASCII', 'UTF-16 latin-1'>Qrrors<`strict3replace3;Eu = M ~,G,= 1, e= @uET/(uO ,h/P M:Dlen() + 1 + 20std% =34 |_Qdata,"lq, marks dump = pickle.dumps(data) u = unpickler(io.BytesIO(dump),0 ?encoding='ASCII', errors='strict'qn.load( check(u, stdsize + memo_ 0* PDarks9n) @_0, 32, 0j# 20 is minimal non-empty mark stack s.] [0] * 10e2f1128gemo tableU required to save references100 objects chr(i) for i in range(100)], 128, def recurse(deep):#M = 0 g?C[K , ]Nareturn  /0)/1/ 02`*58,151O64, 1;134.Ps('a' u 232 2 + 1) ALT_IMPORT_MAPPING = {('_elementtree', 'xml.e ".ETA('cP|*'StringIO&ioc}ONAME_builtin__L@base!ngs 6strgexceptionStandardE,SE+>PUserD8, ' ecollecW`socketb_  S%@Typer0} mapping(module, name:if 4. >8 = %[DRelif 5U  W: = ![:Kreverse_REVERSE_ h? = -8 ga )2get6tryi?sys.modules[module] except KeyError:6try __import__(module),EAttributeK0 as^ E`if supG.verbose iprint("Can't t r %r: %s" % ,c)@qraise I ,?exc|preturn sys."s[] def geta4Rname)Pobj =&6#rfor n in 0.split('.':>dr(obj, n<5obj_@ionsgGe0ameh7diraX ,e"if isinstance(&, type) and issubclassQBaseE3ionGQyield_ , I! : CompatPickleTests(unittest.4CasNrW(selfeds = set(IMPORT_MAPPING.values(j/|0REVERSE_8 /{  ] 7eGDNAME}}P._s |= E =FxrTqi 2get- @w S$Qpass _mapping#3,2' nw.items(uPwith @.sub(S)37 3 ( #if3[:1] != '_'L3assertIn:2,  ;[Equal$2]w+3)w 343),2(2) c.ifR== ('a', 'OS<Q8 0]True(xj;/el attr = getattribute(module3, name3)  self.assertTrue(issubclass(I, ImportError)C_else:Y}| = mapping22Q2if >3[:1] != '_'f/cEqual(ed3),  v?tryd _!hexceptEdOpassKe !) fdef test_reverse_i_W)3for#2, 3 in IMPORT_MAPPING.items(8Pwith P.subTestK)372get!yv as excc`if supo.verbo0print(excv?if @ not+JALT_/A andX{REVERSE/D.getp, None) 2BS (m3 | 2)eONAME Hr3 a2) == em?_breakfail('No W from %r to %r' %aI24 = +  -h, =,IRsM13  Aame2 /"[{sbC$ =kMPV ](3)c a, name), (module2, name2)) bmodule = mapping(5self.assertEqual(0#, 3XA3)) ydef test_exceptions(L!): ['4', 'StandardError'),AE ('builtins8Ez' u=qbCompatu] if has_c_implementation.extend([CA<, CC/ C>BDumpR_Load ', C= raObjectD4/ CzInMemoruaSizeof]9support.run_unit (*s!0doc() if ____ == "_2__" -3() < """ Unpack tuple r>>> t = (1, 2, 3a, b, c = t*aqp1 and b 2 c 3%ETruegFlistflr4, 5, 6 flAP4[f5 f6% f= 0i < 3: return i.raise IndexError!<GSeq(-d$2=Single e! uing, with extra syntaxjs699,osM9100I7= sw9fb, = sfb! 100 Now for some failuresing non-7L`Traceba(most recent call lastR ...11ypeh: cannot unpack non-ite2rable int object Unpacking tuple of wrong size >>> a, b = tTraceback (most recent call last):'Q ... ValueError: too many vas to u (expected 2)lh\sequenceZshort1, c, d = Seq()/not enough= 4, got 3D Jlong7%a where the test for[ raises a differqkind of eZclass Bozos(Exception0...Q pass=RadSeq/def __getitem__(self, iUZif i >= 0 and i < 3K%return i!elD/==:A/set:QIndex; Trigger code while r"6an 8# (,B)Dq, e = Be%"._.\ JSAllowempty itesTq() = []S[] = S 0(Enon-Zr shouldnB Typ q!42qoPP: can] Zo an  f 2[42"S0) """ ___ = {'docTs' : 0} Q_main(verbose=FalseUBfrom import sup~ LQ!-.run_doctest((test_unpack, verbose) if __name__ == "__main__": 6(3=True) """ Test the implementation ofPEP 540: UTF-8 Mode.< import locale$os %sy textwrap@unitQ fromM0supU..script_helper/assert_python_ok, failure MS_WINDOWS = (sys.platform4'win32') class UTF8!$s(.RCase)[DEFAULT_ENV = {osp'PYTHONEl': '',cLEGACYFSENCODING-COERCECLOCALE#0Q!} Xdef posix_S(selfSloc =C.set&.LC_CTYPE, None)R6return (>@= 'Coget_outputm, *args, p=False, **kwkw = dic5.>+}$ifKix_out =(tI5eout[2]Oelse\/okW1W6 out.decode().rstrip("\n\r")@SvskipIf(, 'Windows has no POSIX'B_ C = 'sys; printflags.utf8_mode)'2G.`'-c', U, LC_ALL=20Equal(out, '190xopf;Z:PX', 'A$# undocu ed but accepted syntax: -X f%=1^ A/=1(^0^06if  #"#  disables0_Q# andxpriority overI 0 jl =94env_var:= self.get_output('-c', code, PYTHONUTF8='1') self.assertEqual(out, #$aout = *_get_o^ 0^#^# -X utf8 has the priority over3PX', 'K =0 ' if MS_WINDOWS:A#cLEGACY#FSENCODING disableUTF-8 modeD?andw ,P/ B=F G# Cannot test withPOSIX locale, since1 enG##Q0if cbposix_Z/() should be ignored if -E is usedv{Es pD.zinvalid1xxx', failure=TrueDIn('nenvironment vari value'Cout.rstrip()) 91def_filesystemencoding( = textwrap.dedent('''J;import sys print("{}/{}".format(sys.get|)c>eerrors())N3''';2expected =-8/surrogatepassJelse;rescape'r(" zM/7   ='/ctH-mbcs/replacehXstdio(self):  code = textwrap.dedent(''' import sysprint(f"stdin: {sys. .encoding}/rrors}")E6outF?outGH 6errH?errH HU''') out = self.get_output('-X', 'utf8A-c',G,89 PYTHONIOENCODING=l eassertEqual(splitlines()^!['t : utf-8/surrogateescape': :u;#h;backslashreplace']I,#  has the priority over'EUTF8MLw"latin12V/strict3{3| @MS:nameF=gUTF-8/aJ7N7Mdef test_io($%):F+@filelys.argv[1]]#with open(-v) as fp'8{fp5ZP = __ /__  2,F='1'5.2, 'w*5l_check_io_Mw, module, @=Non 3# E explicitly set}args = [%ify }+.append(f'{ 7!r} GE "1={e At& from %s import open filename = sys.argv[1]#Awith9(-, %s) as fp:+Yprint(f"{fp.encoding}/rrors}")4''') % (module, ', '.join(args))0out elf.get_output('-c', code, ]PYTHONUTF8='1') /tif not  = 'UTF-8'8 64fstrict5sassertEqual(out, f'{iA}/{e>}def check_io_'(I", @)~.._/),="latin1; ="6replace>6",  qJMtest  8'ioZF%?_pyIlocale_getpreferred":"; FHFalse), $ fTrue))wGXy@utf8U   Jf, LC_ALL='C'r!P@unit.skipIf(MS_WINDOWS, ' specific to Unixh>cmd_line0argh\xe9\u20ac'e('utf-8I@arg_B = arg.de'[ascii(~surrogateescapebQ *,/p"%s:%s"R 1), o(0:])(U4(_opt, expected, **kw1 C3argJvI = out.partition(':')[2].rH&p('2 C ),S[]\ if\ .platform == 'darwin' or supS.is_android"c_?ZOelse+,a=0', [V]4.im_level(self):  !# CPython: check that Py_Main() doesn't incremenOptimizeFlag G, # twice when -X utf8 requires to parse the configuration7(8Mhe encoding changes after rea K,^D h!is: again with/E newi%).>code = 'import sys; print(sys.flags.o%)'7out = self.get_output('-X', '!-O@c', g)>8assertEqual(out, '1'#abE2')  ignore_environE if __name__ == "__main__":unittest.3() tcopyreg&q from 1`pickle 3er 7ExtensionSaver class CkTpass WithoutSlots(object)':&zWeakref%0__s:b ('__w%X__',)cPrivate= Gspam8_vL3UnderscoreAndM"/__}|SingleString='Inherited(F[ 6AeggsopyRegTestCase(."):1def_(a.Raises(TypeErrorX.=,5rC, Nonelynoncallable_reduceDtype(1), "not a v" constructorM?intLboolMBTrue.)()e_registrylmod, funcL%`junk1  2', 0xabcdL O(g2try1<# Should~dbe in F now0LValuremove_extensi_on,  mod, func, code)/copyreg.add_extension(3 # Should be in the registry.\self.assertTrue(li_9[rO] ==LinvertedKF)7n't_cache`NotIn(\G5= fRedundant!uation s?*OKp" 3 #Dilow upz# ConflictingN hNRaises(ValueError fJ + 1tfremoveYw. module nam8H[1:]| Tx UQTw @# CaO one that isered at allP!ife@ not_:CZ2modh r%) zfinallye.restore(* :there anymorQ7_ R# TheUS*may*V<, though, if # we happened to pick on a. So docheck forH .31# C%Qvalids flimits!1for!r1, 0x7f pD = EQSaverntry:  copyreg.add_extension(mod, func, code) 7oremove:finally:Oe.restore() # Ensure invalids blow up.(1for in -1, 0, 0x80 l self.assertRaises(ValueError ,h  +0def test_slotnames(|)dEqual(S3WithoutSlots), []?{Weakref>expected = ['_gPrivate__spam']h@4), \nLeadingUnderscoreAndB"U)0___T'>rSingleStringKzI7eggs', '%$f.sort(<result = VInherited3 I Zp if ____ == "__main__"@unit .`() docs = """ # Tests borrowed from or inspired byWgenexps.py >@## A simple loop with conditional`>>> sum([i*i Ai>range(100) if i&11vj166650bvnestingTl[(i,j)R3jd"4)c [(0), 123 11, 11, @2, 0 12, 2 2 ]  thS0ner0res dependent on "_outer 4i 333] Make Pinduc variable is notFosedai = 20 @32833i= 20 Verify that syntax e's are r5dlistcomps used as lvLs![y*y(1,2)] = 10v##  : +IGNORE_EXCEPTION_DETAILTraceback (most reccall lastW"..S : H>>> [y for y in (1,2)] += 10 # doctest: +IGNORE_EXCEPTION_DETAIL ,Traceback (most recent call last):'a ... SyntaxError:6 # Tests borrowed from or inspired by _generators.py A-## Make a nested list comprehension that acts like range() >>> def fn0... return [i f3 in?5n)]@<110)4[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Same again, only as a lambda expresinstead of a funct`defini l$ =E?n: 2(GB canfother :Qg(QGxGS?}qyield xY(\/5)q#] Bsure`None ifTvalidVvalue['i#10 , $]h various scoping corner casesR&s us@e itQBableSdefault argumentitems = [(Q i=i: i)5z2[x( B pthis ti1clo'4{R] Anaway toUE/thAis local-&heW'ei = 20Pd confirm$a Cjump over ! V2: yy2] We also repeat eachQaboves idaG%_(  Uu ) * 0 func(): @... items = [(lambda: i) for i in range(5)] ,4Y = 20return [x(>x>\;>>> test_func()<F[4, !] )8def-:} ysy F"62, ] """ ___ = {'docTs' : 5} main(verbose=None)import sysAfrom  up!r_listcompAs0S.run_('#, )y#ify reference countingv if! and hasattr(sys, "gettotalref5"6!gcG#uU] * 5 {Blen(/)SE1gc.collecthP[i] =./Tprint if __name__ == "__2__"ycTrue) @unit# xdrlib class XDRTest('.0Cas;7]xdr(self*Bp = O.Packer(b'hello world'Pab'what', b'isahapnin V3or'4pp.pack_"42 =-17u09Rbool('E`]False5uhyper(45float(1.iodoublestring(sNl(#, +uarray(a%TP# now[5ify0datpQ_buffu Unu0er(3W.assertEqual(uMposition(), 00 u\8), ^ . /5.\P) is # remember L po  oo4pAwind e again"tup.set_7(poGs!4z_1AlmostEqual(up.unpack_float(), 1.9) self.assertAlmostEqual(up.unpack_double8 2`string2sh 0Glistqquint), range(5))IWarrayJF), a?up.done(Raises(EOFError,  class Conversion( Tenittest.qCase): fdef setUp(j!):~.der = xdrlib.Packer()<yM|, *argsT2(X::g_A_int^W O+@2, '}'bM8c%Ad_`%Bab)Ccouhyper%+C c if __name__ == "__main__"uL() # This file is marked as binary in the CVS, to prevent MacCVS from recoding it. import hPpPEP3120:(HC ep.bim"Питон".encode("utf-8"),*b'\xd0\x9fb8\xd1\x82e%d'8N?\П\a(9falLbadsyntax2tryis6.6"_pDU&except ST":msgMmsg = str(msg).lowBQaTrue('e',4r:lse]:fail("expected ion didn't occur") ;BuiltinCompileBsC# Issue 3574.Qllatin1N# Allow c_ ()`read L0-1 sourceM_`q = '# c:1\nu = "Ç"\n'N"H Rh, '', 'exec'H except SyntaxError: $self.fail("compile() cannot handle Latin-1 source")@uns = {}exec(code, ns'cassertEqual('Ç'#['u']) if __name__ == "__main__"unittest. () import _dummy_thread as  Dtime Equeu drandom^` from h a0supi'mock DELAY = 0 class LockTests(2.RCase)0""" lock objects.""" Idef setUp(83# Create a:-'.L=.allocate_&()ZQ_init;bMake surebqs start *edpQFalseUed(),-"@ is gialized unLed."Srelean L.( W.acquire(821didd properlyType_context_managereEwith5(!uEpass"%2 "A;d2 wad"im_" #k"e of an raises RunR'('!, d TScond__success@the 3itional :0ingl works.8Tru.??e(00 OCondp 1% :!ed returns  'J0Kad%incorrectly " "/ed)un* 1 )( 1? U/uncond_acquire_return_val(self): #Make sure that an unconditional locking Cus True.?N.assertIs\.1.acquire(1),2,2x/"Uosdid notwD5.")Fx w!) 2def test__ _b1ing7>Aof a!!ed Qsydelay_unl3(to !, u"""Hold on toSfor a set amount of time before Yqing."""I&r.sleep(l .release(-;_{Ptart_]p = int( .&()&_thread.s.3newy2w, DELAYBif support.verbose pr}r"*** Wait@SB the_)"\ "(approx. %s sec.) ***" %-" ?end _"doneGreaterEqual(r"- qS{B%+by`failed|@mock.patch('fb'i@e1out , <_"""Test invoj<() with a positiveout when!is alu#y CVd. EnR() isr"edgUgivenM/n2andPFalse9 """b} retval = %waitflag=0,"=1OVb{(Dv.called+1_"`_once_M(YE!,  *_representa@In("NPed", RH1'MO class Miscf`s(unit.CCase0"""%ellaneous1sU 2exi9 Raises(SystemExit, .: XOidenO IsInstance(GBget_7 ), "_thread.get_ident() returned a non-integer") self.assertGreater(HQ, 0) 4def test_LockType(B!):TQIsInstanceTallocate_lock(), mO,IM1 is not an in of what "M &is"%by "set_sentinel_;) JA did/ aB8.0rrupt_main#Calling start_new with a function texecutes V # should raise KeyboardInte upon compleV.:Ucall_Z(E.!"R-s( a 4 * stuple()"inN lstack_size_Nonretval =N0(0rbEqual(;cCO_notwierror) as cm"d/("cm.excepyargs[0]P"sett"0ck >supportedr class TTests(unit.CCase0""" Vc{ion."""arg_passingMake sureparameter 1j works_Per(queue, arg1=Fals 2 c"""Use to5 1!()| esVs properlyG{`.put((2%Aing_)1 =  .Q&(1 9, (M@, Tr)Jresult =z(%?(5[0] and 1P"Argument'Xfor thread creatio_n " "using tuple failed") /_thread.start_new("Xarg_tester,^.(){'queue'::Aing_, 'arg1':True 2 }result = <e.get()self.assertM(5[0] and .1]"Argument pas+Bfor  creatio`okwargsaF( , o?argKBbothZ1defc_multi_(%):%.ya_mark( w, delay&time.sleep(D9S.put(r_ident()>P_coun5E 2 = QQ#(5Lif support.verbose0pri~c"*** Test(g "(will take approx. %s tosec.) ***" % 'cDELAY,Eain range 1if P galocal_ = round(random.V(), 1,4,elA J0M "R^] v) f'done'6 "ZEqual`.qsize)"Not all 3s executed properlyp "after?JEH{06__R_not_l&""G` invok ) with a non-Mp value "g%".Expect TypeError<meaningful epmessage$be raisedG~R,%s(cz) as cmthread(mock.Mock(), []) 4self.assertEqual(cm.exception.args[0], "2nd arg must be a tuple") Jdef test_kw4_not_dict(`%):o5""" Test invoking start_new_thread() with a non-L value for "g%".MExpect TypeError=meaningful emessage tofraisedG R,%s(cv) as cm .Tmock.<=!,3r% SystemExi2@funca that >skQEThe Pp shouldydiscard|h6 = 5side_effect=h&()?try],A ^ O lfail(" d;.@ patch('traceback.print_exc'@eE?,_3O, . and the %ed6via((p|<wIPTrue(b.called) # SimpleR suithttp/cookies.py import copy from1A.suprun_unit) , 0doc ?Ce ;l)pickle class CP$s(D.bCase):cQbasicZJcases = [{'data': 'chips=ahoy; vienna=finger',2 'B': {30':'5B', '73':'9}:repr': ""E`outputJSet-D(\n"},+keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"FU' : 'IGED';'''T=Qe=\\n;'>''',( 8'output': 'Set-Cookie: keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"'}, U# Check illegal cU s that have an '=' char inunquoted valueO`{'data)',&P 'dic#{''R' : '+},repr': ""8. m "# _s with ':Aactetheir name. Though not mentioned inPRFC, servers / brows allow it. 1 Bqy:term=g H -I1N@'='=T=<}iissue22931 - Adding '[' and ']' asQ0id krsq %#)0ues3Bdefiy RFC 6265,{Oa=b; c=[; d=r; f=h`' a':'b', 'c':'[ Pd':'r Pf':'h\`'a='b' c=d='r' f='h'q\n'.join((u ?a=b '?c=['?d=r'C )))}]for caseUases:&4C =.([pC.load(I[]!self.assertEqual(A(C),}[4 "C.(sep='\n'?'A@k, vUsorte].items()) QC[k].eB, v)?def test_3J95p'CustomHWILE_E_COYOTE"; Version=1; Path=/acme'O''X' 'C[? [';ion'], '18Apath5"['6)N [* B.js_,(), r"""
Alien sex friend[2:250:6] )o905100P>1989_48:14W4570808'90OX51/54Y4572929NuColoniaO3:12"   $Flotas (max. 9) Ph>Num.Espionaje(F)- bZSonda de ea: 3 ">3< 7[2:250:6]Wed Aug 9 18:00:02 7O42:57 17> 3
Metal-80Eo/3.965M )p
<1 <$ 519" border="0" cellpaddingAspac1
[2:250:6]<Wed Aug 9 17:59:557O42:17M8:017w{R@ Nueva misin: elegir navesN.DisponiblEph> one new dict #self.assertEqual(ChainMap({1:2}).maps, [$])7q# 1 arg`Qlist Ydef test_bool(c!):7rVFalser/))%o{}, {}+7TruO-W)|missingclass Default5 #__J!__L[, key(,return 999=d =j(a=1, b=2),(b=20, c=30!for k, v in&6*, d=999).items( }d[k], v  # check __get]S__ w//77.get(k, 77) 0_) w/ _o"c=!d=k H__containsA.pop('a', 1001), 1, d\ 1MO1002e: 9(), ('b', 2)^ _44Wwith hRaises(KeyErrordL order_preservation@z(0 O@edDict(j=0, h=8/),+  i9A4444?3335 Pf=666222, g=777:@  Be=55^) \_, e=56  ''.join(d), 'abcdefghij'3$(d k[)2q('c', 3xp ('d',  = ('e', 55>qf', 666 g'`('h', 8>0i',94|j', 0)]o_coerc Map(dict(a=1 , b=2), dict(b=20, c=30)) self.assertEqual(+d41a=1D8.items()@ydef test_new_child(!):'Tests for change issue #16613.'.c = ChainMap(c['a'] = 1*1['b2m = {'b':'c': 30}fd = c.m_ ;.maps, [O30}, {'a':1, h }]) # check internal statex]qIs(m, d]U[0]) % # Use a different map than%ct*class lower7ictosP__get!__[, key(,if isinstance(key, str)-Pkey =I.areturn./containsi.1  ?C]`in 'abAn d9yR, v i(fBC=30, z=100)M:Sy&get.get(k, L, v) #<Q Named Tuplesd: `NT = nhtg( NT', 'x y z')# type used;apicklek2s NIP(unit.bCase):e_factory[Point' (0.__Q__, '2Pslots3( O.__module/l!, l?fields, ('x 7y') Raises(ValueError,,%Arefg ghi 7has non-alpha#rself.assertR#aises(ValueError, namedtuple, 'class', 'efg ghi') # type has keyword  self.assertR^ O9abc] ^starts with digit e!d% # field_non-alpha charg(Babc 5*g+,89_, e_ed +leading underscore/(jn# duplicate('Point0<Qx1 y2# Verify that numbers are allowed insS_NQa b cN?~# Test sLaD1t =eC@('ntXthe quick brown foxfk# check unicode input_NotIn("u'", repr(nt._5s))1nP('the#') 4"4Typ._make, [11]# catch too few arga, 22, 33iaBmanybdef test_defaults(q!):8 qdx y', ;=(10, 205# 2$Xg[aEqual(U, {'x': Z'y': 20}E(1, 2), .+0jZ+)$<20,!d # 1$#!PV4# 0  self.assertEqual(Point(1, 2), 3) with self.assertRaises(TypeError):+2L%) A8 # catch too few argsa;w6 uOmanyv9?, 3}=wdefault = namedtuple('', 'x y', 8=(10, 20, 30)=non-iterabler/10=another &WFalsey_None)y#>@ is %}._fields_F, {}>5 IsO.__new__._81__,p<qF#PL>#y[]}q# allow"I gMP'x': i'y': 20 Em!(1 ,+ rH(wxrRplainn5torcn @unittest.skipIf(sys.flags.optimize >= 2,. S"Docstrings are omNd with -O2 and above") def test_factory_doc_attr(self):%)Point = namedtuple('', 'x y'P+:.assertEqual((!._\2_, 8(x, y)') cP@unit.skipIf(sys.flags.optimize >= 2,.f "Docstrings are omNd with -O2 andwritable?x Alias for field number 0:)5T = 'd:!'lC,Bx]_fixespec, re&ed in [`[('efg g%hi'), `_1')],&#non-alpha charh0abchPclassi#('hhas keyword`8"9g@('_0q_ bstarts~\digitfm?), f.leading underscorelk%,  _2# duplicate^7x 0V is a spac]< 8XNT', =True)._ms module_paramet+NTi0['xRy'], B=collections RNT.__2I__, 5[instanc)Ap = 2(11, 22#p,* x=,_y=22)/-V , b\*.`*dict(^ , j)7Raises(TypeError@, 1)e# too few args-[o, 2, 3a[Omany\EevalMQXXX=1)', locals()q# wrong keyword argument +self.assertRaises(TypeError, eval, 'Point(x=1)', locals())A # missing keyword agEqual(repr(p)^1, y=22)')NotIn('__weakref__', diE0g1p, ._make([11, 22] q# test 1 classmethode._fields, ('x', 'y'b 3e8 attributee qreplace1, (h 8 asdict()[c(c8bEtry: 13p._0, ei&=2except Valu @5assQJelse_fail('Did not detect an incorr wuname') O# verify that #@ strcan have comma\0 = Krdtuple(.Gx, y2p =V}U! 8Pspec be a non-vsequence m?1defo_=Pness( ) /'xbUIsInstance(p, x(pij# matches a realdE c (larcoercable tohAlistgR +# hD1maxa/22p`# iterW *,Xy# star-XO = pi&U # unpacks likpc(p[0], p[1])[p# indexeI1p.__getitem__,c 3)  self.assertEqual(p.x, x)! Oy, y!Raises(AttributeError, eval, 'p.z', locals()def test_odd_sizes(%):Zero = namedtuple('_', ''$@(), j Z %._make([]- Prepr(2Q()), /()._asdict/{}._fields;Dot0Dotd PDot(1?1,)z4Dot1/(1).d, 1U// ?d=11 $)1)1_'d':16 4replace(d=999?999 o0'd'1sn = 5000%ames = list(set(''.join([choice(string.ascii_letters"for j in range(10)]) i'n)@len(b;Big%QBig',<'b = Big(*onY "2b, u, -3BigH.?2posenumerate3 ngetattr(bBW), po b); # a sure 4) doesn't blow-upVd = b_expecte!2zip,  Ed, dDa"b2q!**][[Q[1], -5], 42)]%b2X%P[1] =V -5%42 $b2U1i lpickle p = TestNT(x=10, y=20, z=30Fh`modulee(J,b@loadUm11, 'd-Odump- -protocolB-1, d.HIGHEST_PROTOCOL + 1uq(fD(p, W`* hl(p, q)  self.assertEqual(p._fields, q ') 2 7NotIn(b'OrderedDict', dumps(p, protocol)) Fdef test_copy(H!):X p = TestNT(x=10, y=20, z=30for copier in y.L, @deepUY0q =Vier(pJ ?, q#  $name_conflictsp# Some %s like "p", "clsPtuple itemgetter", and "property"r# failed when used as d!. X to make sure these now work.N1T =6dv('T', ' Q cls )'6t(1, 2, 3, 4, 56 rt, (1,2,3,4,5))0newIt._replace( %W@=30,B=40,'=5:# zb}0,20,30,40,50 # Broader of all interesting(s taken fromU code, oldS# templatean example"ds = {'AliassAI'AttributeErrorQBuild Aypas+Create',Oa'Encou+qExpecte F@FP!GoihHelperDIronPython.J 5Key@Make`Modify *No Q'PoinpQReturZ 1TypOd"UsQValidf 'ValuVariableLaaccessiblW8add2addR1all-1lsoqarg_lis2argTrgumentsGutomaticallbmb 1tinA!buPb(@cann}aclass_1pacGQmetho!clHcollectioWxconvertc< idebugging)RdefindQionar1doc0Tocstr= cduplic@effeO@eithk 'enumer)cnviron`4 'e-u1exe}frf_globa+ LcformatIfram:1funX4 75gen!ge*g0 'gbh@help)identifierUQindex  @stanH in#ti-n~`intros&ish', 'isinstance', 'itemgetterArabl@joinwkeyword Ss', P'kwds!le.1lik>@list3map&amessag"metadataMQmethok 42odum B_namBuddO2tup>_` "pa2nee9newKQicely8sum_fiel'2umb<Qobjec of(qoperatoXhoptionPparticula%Bpick 0ingG2pla"po40osiM)alOrotM4regX reLCrepl dHreprN1_fm `esentavF3sulJuse_CS se%1selSsequez!seD1sidspecifieBspliHtartsPswith1ste!st3str bubclas yatarget1tha!thAtheiS2thi opL _$2typ=%ypsunderscorunexpect`unpackXu8use#us'saAvaliQvalueDvariPverboBP 'whepAwhic11worqxv.z Uzip'}/@T = 3d`('T', %s)## test _%__2 = :range(len(?)Art = T(*1).assertEqual(t, $;*dict(zip(T.,iREmakeg ._(Uexercise __F(&(t asg"._#@(), +[2newv*10 for v in0new. t.olace(*X) N&, ,~ &~2I_getnewargs P9t._*} !) T1def r(@!):%ANAq&x'0 A(1)), 'A(x=1)/ # p shouldQw the1 of sclass B(A):  Spass  self.assertEqual(repr(B(1)), 'B(x=1)') 0def test_keyword_only_arguments(L!):+_# See issue 25628HwithzRaises(TypeErrorEINT = namedtuple('NT', ['x', 'y'], True1 0abc30def5 reT=<7 NT._fields, ('B__1'))=\YFalse _subclass_gl_24931!v Point(;1('_ J)z+3a =GF3, 4 4a._asdict(), OrderedD![( 3)L y'F'])ua.w = 5rZ_Y__, {'w': 5}) #<Q Abstract Base Ch esm:" ABCTestCase(unitj.&):validate_ar_method, abc, *s$ptubs = D.fromkeyss, lambda s, *args: 0# everything should work will all required k are presentC = type('C', ($),2W)C(instantiationfail if a~ is missing|1forG1 ins( =f.copy('Pdel s+[c]^. E A, C,"is!cep/ =Dobject,)U__hash__': None}setattr(,K1IsI@ce(C?abc(|(Z+(?Notr comparison opj@['ltug!le n or0andxFsub'YoperatorN%{}p op+op = '__' + op + '__7'  operators[name] = getattr( , %) 7class Other:Sdef __init__(self) $.right_side = FalseH#eqF0, olM:TruLt}return __lt__ = __m ?__g/le8n?rorUOrandx< 8sub<1for, op in s.items(rif not has instance kcontin" =?%()6op(U) <`assert(#M0,'RY Ypcalled Z%s.%ssu% (type)1) test_genryield  TestOneTrickPonyABCs(ABCbCase):AJIAwaitable*"fn@s.coroutin?1 @`async -Onew_1BpassC/Baa 5< {KMinimalCoro( =Asend#`, valuIT Q@SthrowA1typF=None, tb uZsuper().=72 a/__non_samples = [qint(), , object()]x> rcNotIsIE(x, l 3a(issub (x)<d, repr)0Bar2 Bc = a`# Itercs (gen  with CO_ITERABLE_COROUTINEEflag don'(Eve '' method, hence ca%4be sG&ofA. Us&qpect.isnto detect them.@ stance(c, Awaitable) c = new_coro() self.assertIsInstance(c, AwDB c.close() # avoid RuntimeWarning that a was not aH'edlass CoroLike: passutine.register(*True(isi-((); @subch9Yu = Nonesupport.gc_collectEKill to clean-up ABCMeta cachedef test_e(%):f"Ggen(GyielZp@types.F ?@ `async l)qW8J Bar%A!__,__F KpMinimal ^AsendY{, value#`breturn@SthrowA1typF=A, tb Rsuper().=72_anon_samples = [0intQ, obj],q5()]for x in E M(No!x,gQ3@Falsd)f8(x)<s, repr()w+x $P`# IterH's (generators with CO_ITERABLE_COROUTINEEflag don't have '' method, hence ca%4be F# ofA. Us&qpect.ismto detect them. cG D?/Bb 08$,  JJ26 Z%(Coroutine))  self.assertTrue(issubclass(CoroLike, utine)) 8! %%: def send(_, value)#'Mpass8Qclose92__await__6@Falsinstance*()</test_Hashabl# Check some non-h) non_samples = [bytearray@list!seudict()]Zfor x inZD dNotIsI4x, )P  wtype(x);s, repr()K YNone,Q inAfloa co%?x().?strPtupleFbfrozenLq , s, object, , &s( Raises(TypeError tdirect 5ing#%H(<  __return super()./_`Equal(Q(H()), 0'w(int, HT validate_abstract_methods4, ''j=%isW 7. AsyncIter P/AIG_aiterH1elfq  AI  9KOAI, 72_/[]@     (M @  G FM= Stor(self): class AI: def __aiter__(self)!,preturn  =casync COnextCaise StopA5IterationP].assertTrue(isinstance(AI(), 8Oor))91sub?(AI7non_samples = [None, object, []]`# Check some non-,Uables#for x inU FdNotIsIxUy7@Falsmtype(xs, repr((# Similarly to regular tors (see issue 10565cN AJOnlyD '| 1- validate_abstract_methods(@`, '__a2__' Q__') QQtest_ _B"lzv??%D#@ test_CollectionAsome non-c+s%Gnon_@ = [, 42, 3.14, 1j, lambda x: 2*x]>for x in_G dNotIsI6x, 4Yytype(x)=s, repr()M Mable"_i0gen4a(b''),?(bytearray()), 5(x 1?[])GI3psamples20set,cfrozen 1dic1s0strotuple(<1lis4<A.key:Hitemvalues(YO yeck also Mapping, MutableMapcetc. 'self.assertTrue(issubclass(Sequence, Collection), repr/))J{IH O z?Sett@tGN L# Check direct 5ing7(V:Odef __iter__(9) $preturn %g(list( D?lenC0|contains=,hmUFalseG`DerColu): pass  REqual2))), []i<1` 0s`/Bfloa1  :f24 validate_abstract_methodsQ, '__O' E__',u6'__a'>csized #per non-p^ (which is notH)) pColNoIterA P 3xOSizexY$):F(L  :OCont1u(n <instance{/()>q>< z<z .assertFalse(issubclass(ColNoCont, Collection))  self.assertFalse(isinstance</()># Check None blocking\` SizeB:|def __iter__(): return 6([]0contains4 a__len__ =OIter8 0AITrue0 ~8|<<>zz <z4D in :ColImpl>7NWlist( C,*m)f `NonColg <&__7U 9  ,Ptest_Catornon_samples = [, 42, 3.14, 1j, b"", d[], {}, set()]GPfor x P TdNotIsI4x, :2wtype(x);s, repr(3bytes())Pr(str /Ptuple")#r(=0dic,>'kcfrozen3TG.keyAitem> Bvalu*__gen()5(x /[]$j% validate_abstract_methods(p, '__next__' B__')=# Issue 10565LzextOnlysV nRyield 1 return  self.assertNotIsInstance(NextOnly(), Iterator) 8def test_Gen(G!):Yclass NonGen1=__iter__7 EC,Mnext,MNone,TcloseUMpass"Qthrow", typ, val=LA, tb 1): :;2yCsendtvalue):IG36j ef non_samples = [~W42, 3.14, 1j, b"", [], {}, set(),<ia(()), D[]),:2 E3()]Afor x in @?5x, )Q3False(issub(type(x)<d, repr)I3f ag+PMinimalGen(i  H uS Rsuper().=hcGgen(7vyield 1/, (lambda: (- )) 7), M (x/ 0?Tru w validate_abstract_methods0, 'A', ''tq# mixinimgen =;0Is(*J )(.(0), >3Equal(2, V92* IsRK.(Raises(ValueError, mgen.throw, ValueError) self.assertRaisesRegex(+, "^huhu$",5< Nmgenlx ("K/")(StopIteration, U E()) class FailOnClose(GenDEor):&def send(0, v): return 0@1P*args1.SY S N0).c eIgnoreOExitNOpass bRuntim?/,  htest_AsyncFNonAGen1__aiter__9e }__anext-MNone-a|W a1typ/=NA, tb 1): ;_ 2} 3>m ko%non_samples = [T42, 3.14, 1j, b"", (), [], {}, set()ua(()), T[]), ; 2 E3()]for x in F'NotIsInstance(x, 4.8False(issubw(type(x)Ad, repr9:Gen{a 33I )O7&pMinimal( -mjG Y await super().athrow(typ, val, tb) async def gen(): vyield 1.samples = [/0, G6, MinimalA]Efor x in 9 _ self.assertIsInstance(x, AIterator)N4 ?Gen5 True(issubclass(type(x)t@d, repr) validate_abstract_methods(G, 'asend' gthrow'|vArun_[(cororesult = None`while S#>tryb.(Pexcept Stop}ion as exPex.args[0] if ^ elseiYbreakrreturn Vt# mixin tests1jmgen =xY(+ , .__aiter__(.20;), q__anextOO~}Equal(29V/2)(mxaclose(4Wwith oRaises(ValueErrorPm/ FailOnCz  [H,pSue): v78*O8 '%).V[eIgnoreKExitRFpassoRuntim  ip_Sized(Cnon_, 42, 3.14, 1j,_U4$5(x 0?[])L_ c+Nof/OFals*8!$bytes(), str(Ptuple#@list!secfrozen 0dic9A.keyiCitemct().values(N), ]for x in samples:6self.assertIsInstance(x, Sized),True(issubclass(type(x)7d, repr)Go validate_abstract_methods(u, '__len__'94isi3def test_Container(|)Cnon_ = [None, 42, 3.14, 1jX4_YOgen(|$5(x y/[](T+No3 3OFals<<)bytes(), strPtuple#@list!secfrozen 0dicA.keyi@item2GC  _s;?fBcs< allable7P"", b[], {}, { ;:!;9lambda: j!E, int, object?lenist.append, [] i./ ^-:2, A+?all'7"tdirect_~TestCollecABCs(ABC4ase# XXX For now, we only some virtual inheritance properties.o# We should also?$th* behavior of c Eas real base es or mix-in.UbE`sample[set, frozenset]m;#QIsIns(>@(), P1 6441validate_abgct_methods(S6'__d`', '__"__ 'S0 My Pyx"2& Dx?<089 %6([] )comparison( _9OneTwoThree$'CZ.ents = [1, 2, 3]'6ain%qx ]Q~~Oj%KtK(D{a, b = -), GaTrue(hash(a)! == hash(b)) def test_isdisjoint_Set(self):#'class My7SetE__init__:[, itr%)V.contents =&c I!EainsMxKreturn x in WQCiterMJ%)K?lenJlen([x for]VCs1 =T(1, 2, 3)2x4, 5, 631elf.assertTrue(s1.8(s2I+MFals,*equality(e#A H3, 44;  8g2 > s1 !o1 < s2!OO2 <=D #3F O1 >=iE(s3, s4D3Not$\2, s3arithmetice 8, 5qs1 & s2:23, M(3,)pMutable;<IsInstance(set(), 7i5Qissub16 457Notiofrozeno?p=vt)) *self.validate_abstract_methods(MutableSet, '__contains__'Diter 0len ' @'add*discard') def test_issue_5647(!):A&# {.__iand__ mutated the set during Uation?s = WithSet('abc{W7s &`cdef')# This usifo failX/assertEqual(set(s), ('gO4920 bpop() w did not work{class My3__slots__=['__s']?x__init__,items=NoneI/ ifZ`ms is #C[jP.__s=$&)Svreturn v in VKE%j"E1len"D1add,asult=v?.Ov  reP rOo__repr"p%s)" % 3Q(list)*[5,43,2,1] .W?, 1=875Wempty=^Gfullrange(10u.<es -= saF!, y2 L^L8&L }|1pR16373J# Recursion error compa 0 ann`# Set instanced/COE9;Set;, x'krUFalseD908!%'([?Non(self, x):  return False def __len__(self):+<08Oiter9%O([])@#le>?, xzNotImplementedGtG Hcs = MyComparableSet(n ?Non#9q.assertb(4F< csF#BTrue"=#F>#F>Ftest_issue26915# Container membership 6 should check identity first_class CustomEqualObject7E__eq_othercSequence( Ej6ini;seq%_seq = seqmEugetitemOindeQ[)]RW1len.%) Fnan = float('nan'L^obj =9([nan, obj, nanc [Iseq,ItemsView({1:H@, 2:U*}))_Value*R5Efor 6 in s[)Ielem$ ##lf0In(1,SKQ(seq.(nan), 0,obj), 1, ScountX2,X21Sam, s1, s2# coerce both to a real set thene1ity] 54Set`t(s1),=C(s2)4 _Set_interoperability_with_sQ_sets Ie: 8743}Y@List7Set2r)__{ents=()-1.data = [jIIH*0if !@ notvX.2#q.append#sui > def __iter__(self): return iter#i.data)'def __len__#F1len"EOreprF'Set({!r})'.formatUr1 = set('abc'$r28bcd3WabcdefJ@Listy NfN RfR VlV2lis7cbarlVhbcddcbVS"ed<target = r1 & r2.assertSamef#Bf2, 5&,r,r2 & f1XlX|/| OOr2 |/| Hfwd_-7reve2 - r1-V Si0 1?2, `Or1, `r``r!`f`l^^5f O^^# Don't change the following to use Less or other  # "more specific" unittest7ions. The current<ZRTrue/ False style makespattern of ZAcase combinatk clear and a@s usknow for sureAexact operator beinvoked. - pr%f subse(f1 < f3"1"2"ere"e " ef.assertTrue(r1 < r3) self.assertFalse"1"2"Wwith IRaises(TypeError):ovf%l3?"1?+%2 @# any subsetPTrue(?= f9"9 E: gg "g #gDrgrg /= +?= l *9= l proper super _3 > f /f1"2"e e" e"erC4 e > +>+>=\";Of2 >#E r3""g"g#Eg/= Dgr#  ,/>=*>equality = /1 " f"9\##rF #f.assertFalse(f1 == r3) self.assertFals#l#1F52) j# inequalityO!= f\ ?r1 # f#rF1TruE"g"f"MfDllKdef test_Mapping(C%):Rfor sample in [dict]1IsInstance(4C(), Y 5issubclass:89j validate_abstract_methods(i, '__contains__'Diter 0len '__getitem__'r3 My[c =D!__W ?return 0u8x<;, i^?aise IndexErrorGDA%6(() Scomparison( .Ras(Type, reversed,0)fdutablePm0 `Emt ?@<{ 8r*Bs5delU_J7elf^p# Test kae 9214Fmymap = UserDict(['red'] = 54 /P.keys6SetJ1KeysView6h2CItemjAz = 8 | {'orange'}ZHz, s!flist(zXa['blue|7# Shouldn't affect 'z'uE((sorted(z), [", ^wmap['red'] =C 5 z = mymap.items() | {('orange', 3)},self.assertIsInstance(z, set)&flist(z^['blue'] = 7z# Shouldn't affect 'z'OuEqual(sorted(z), [, ('red', 5)]) Bdef test_SequeP!):for sample in [tuple, , bytes, str]15D GD(), m 6True(issubclass(;9:l?(10m3 i8hmemoryview(b""n>s ?str3 validate_abstract_methods(y, '__contains__'Diter 0len `'__get?__'@_mixins(dGS*j__init__JCKq=()(,i.seq = seqHK_indexJtreturn Q[(]RNG1len"-# Compare .h() behavior to (b]|str)n_C_same(seq1/22, Kargs:tryexpectedJ1y*E{/cept ValueErrorRBwithPvRaises(3 WOseq2>lserbactualCk? "W$, #R, '%rc%s' % w,D ty@1 bnativety('abracad'aes = [-10000, -9999] +(P(-3, Yj) + 3)L2seqs7 `letterFset()J'z'}6bseq, (X,@vPstartu |@etter, startO)) for stop in range(-3, len(nativeseq) + 3):?Rassert_index_same(+/X , seqseq, (letter, startQop)) G def test_ByteString(selfPample[bytes, jarray]=.IsInstance(s@F(), h 28True(issubclass= ;< str, list, tuple?Not%OFals tmemoryview(b""> wA  MutableSeque 7%rsC q ',, AB 0, d n> @= ; validate_abstract_methods(9, '__contains__'@iter `'__len3tgetitems6del in'8 |_mixinsD# Test the !< of by creating a minimal concrete!#  inherited from it.#! SP __init__ lst = []I?IB!, {, valuep5P[(2] =*ZZS{return ZRNGK+IP?delkJ;.5B/\mss =rmss.append(00ext(1, 2, 3, 4)) self.assertEqual(len(mss), 5) s&mss[3], 3$mss.reverse(:1$:?pop6 48wremove( r<&mss += (10, 20, 30XB6& -1L_clear_0) #<Q Counter _:t class`1SubWithSetItem({!):O# Test a c# s3 that overrides __setitem__9def __init__(, *args, **kwds`.called = FalseC.K .qtkey, valueq?TrupJF?GetB%3getv<\!, 4default6dreturnV.K7R(unittest. asq_basics4c =o('abcaba'%c,. {'a':3 , 'b': 2, 'c': 1})?a=3, b=2, c=14IsInstance(c, dict[ 'Mapping*4(is{a\3h6T)c). xasum(c.Yos()), k jsorted00[1,}/3]82keyfA['a'<?), 5.r ![(3), ('b', 2 oc', 1) `c['b']0] _@c['z$ self.assertEqual(c.__contains__('c'), True) oself.a4z4OFals5 get('b', 10), 2a ,z,/10- , dict(a=3, b=2, c=1)1repr(c), "Counter({'a': 3, 'b': 2, 'c': 1})"G c.most_common(), [('a', 3), 2 c&)]Jfor i in range(5):kroi9i),/3  7[:i l''.join(sorted(c.elements())), 'aaabbc'c['a'] += 1a# incr8 an existing valuec['b'] -= 2:;sub1 to zero9del c['c']8 # removepOntry. make sure that Sdoesn't raise KeyErrorHOc['dfrom a misse'] = -5# directly assign> f^4>oadd to5 c"4"0, d=-2, e=-5, f=4. Waffffp.pop('f(4<(PNotIn"6, c! *3*, cnt = ccVitem(?3 d5&wc.clear84%F, {}2 R'R)R\ s("mpZ!edh#, ;.O@keysn kwHCType>Ihash<c.update(53!/7p * 50 +_ * 30E)m # test case with no argsd`__initp!a'^_*)cdx.D"55 33 3% c.setdefault('d', 5), 1l !$ VeV5V 0e']~ @1def_A( Rlist(r(self=42).i tems()), [('self', 42)]) .assertEqual(list(Counter(iterable=42).iMQ%ONoneSRaises(TypeError, 2o(), ()6.__init__) ndef test_update(R!):d4c =(i'c..^0?c~% zj n:r&t> #()a;f{}, {}w |copying# Check that cv`s are 1{f, deepRpickl5andU #have a repr/eval round-trip%Wwords'which witch had es wrist watch'.split,cG(dupmsg = "\na: %s\n| @" % 3!, ^9bWIsNot)_, msg.=dupWl.& ($for proto in range(e.HIGHEST_PROTOCOL + 1)Qwith subTest(K= , `TloadsmRdumps,)("(!_!o ZD](=8!_subclass'4 MyC !Fpass' =1'slartibartfast'Rd = cOd, clen(d), cw HAtype* +L{_conversion1# Ct to: set, a, dictF!s = 'she sells sea shells by the core' !self.assertEqual(sorted(Counter(s).elements()), ?s))C8_et(s)= Gdict~;), P.item eDsx def test_invariant_for_the_in_operator(!):2-Dc = a=10, b=-2, c=0@for 0V in c<@OjUTrue('> '!In%K, c)multisetLionsp# Verifat adding a zero c will strips and negatives% +Uc>) a = 'abcdOiLrange(1000<# random pairs of !-p`>bp-2,4)) x{L.update(e=1, f=-1, g %qq8qqhqiqjqop, numberop[g.__add__, lambda x, y: max(0, x+y)),= ?sub=-= /or</x,; /anAmin(A ]result =vop(p, q%\xJL' (p[x], q[x]), w [F (1x, 7# vds exclude non-posi u1x>0Q`.value7/ef   with no repeats are exactly liktO0, 2LC?set_aset.__ r.__or__, set.__or__), (Counter.__and__, se/ 0-]:?c>_result = op(p, q)16set-setop(set(p.elements())((qIlf.assertEqual(z^, dict.fromkeyseA1)) def test_inplace_operation16lf) = 'abcd'AMfor i in range(10008"#e dom pairs of multisetsK-Cp = ( (({,>bp-2,4)) x{=)(p.update(e=1, f=-1, g=0%qq8qqhqiqjqq, regular_op[1iad!  50sub55 0,@i44 hE = p.copy(c_id = id(c;Oop(cy22+sei2CA*d(D0), subtract(BTca=-5, b=0, c=5, d=10, e=15,g=4%c.Oa0b=23&-34 20%30, h=-5< lP(a=-6-O8N0f=-NT'50-(MP'aaab#s}6ce'  1ad5e=-'Xxc6=42 list(c.item0[('%', -42)];biterableq:uRaises(TypeError), 42) & self.assertRaises(TypeError, Counter().subtract, {}3) A?!) 8def test_unary(C!):U5c =za=-5, b=0, c=5, d=10, e=15,g=40Equal(dict(+c), > ?@ -@La=5)repr_nonsortable 2FNoneu@r = E&(c In("'a': 2", r#@b': Y&Hbhelper_function # two paths, one for real6Us andother mappingsgelems = list('abracad'0%1d =R( _c^_?ents(d, s" 1, {P5, 'r0, '2, 'c': 1, 'd}|m = OrderedDa m%m, Y[('a', 5), ('b', 2 r Qc', 1d ]SK# fidelity to the pure python version*SubclassWithSetItemeWTrue(c.called"y8 w62 }L-Ge-~H? #<QA Runsa:% main(verbose=>NamedTupleDoc0doch .DocTestSuite(module=colles*_Ee<[2R&, ^ , OneTrickPonyABCs! *Co(`KChainMapCUserObjecth]support.run_unit (*()(,ob) if __name__ == "__2__"]1) #sVxml.dom.minicompat imT copy dpickle+Fc from S RA*  EmptyNodeListTestCase(unittest.TestCase): """s for the EmptyNodeList class.""" .def test_e&nodelist_item(selfUY # X  access on ana.W0M_N* =#"()|%d.assertIsNone(7.jE(0))R--1)) # invalidkWwith CRaises(IndexError5[0]E'2-1]sllengthuE# ReadingWEqualUg6, 0Wh# Writ@xml.dom.NoModificationAllowedErA.uo = 111 __add__4 + (,/?__r}[1,2] + <A) eP(unitE s# First, use4(pKUr^S# Now.' sZ2.append(111 3999geC,yP1uH > ]?[0]j ,V-1], 5  \f[1, 2]"2@h de_list = No deList([3, 4]) + [1, 2] self.assertEqual(node_list, No>!, :1)) =def test_10___radd__(T!):&f!R# =~+ +\%]).=", pickle_roundtripq# Test 'ing and unEof a.for proto in range(4e.HIGHEST_PROTOCOL + 1 =w# EmptyX+~'k2d =xe.dumps 5e7Sloadsd.eIsNot(?%, 3G3# Non-e.append(1v 2 ,fNcopyU"% =s(%AcopiV.I& 7 , , '[1(2v0 = V"@x, y!Bzip(0050Is(:@deepD__Y *|K.c# if __name__ == '__mai`n__': unittest.main() from __future__ import annotations USING_STRINGS = True # dataclass_module_1.py and A_str"re identical # except only the latter uses string3. b$estyping T_CV2 = .ClassVar[int]36I6YW.Init: IV:!8 @  2 CV{4|Ocv0:Q = 20=cv1#D = 302: b2-33rnot_cv44 # When usah, this field is not recognized as a X. I IV$esai$i"?"IV!iv&IVi0#n .egetpaso sl$iodBytesIO, S TextIOWrapper0>6Bmock0supR tryn)termios iIRError' } = None??pwd;4pwd7 @.patch('os.environ')GGetuserTest(.qCase): @def _+name_takes_env(self, l)*expected_> = 'some 'b$.get.return_value = ?1m.assertEqual('#, Q?())priorities_ofzs   # in case0re' <Z   +.call_args_list,([D"(x) for x('LOGNAME', 'USERL /)]pfalls_back_to_pwdi9+  if<)Qwith +getuid')Wiuid, \760pwdN%pw9wl uid.return_value = 42 getpw.retu([expected_name]5self.assertEqual(0,0 t vass.getuser())4#we_called_once_with(422Yelse:@Raises(ImportError,~) class GetpassRawinputTest(unittest.qCase): m@def _flushes_stream_after_prompt()# see issue 1703I< = mock.Mock(spec=StringIO4 = !('~Fing')AdQ_raw_$c('some2', u!, =?.) !usderr_as_defauljE9 = 5 1patch('sys.st~b') as jg4Ho.write F@ #in:/'in.:,F\.readline 2ih)ifferent_locale5 = TextIOWrapper(BytesIO(), encoding="ascii" "HasÅ‚o: "6 =0,=x Gw#r_on_empty"Qj ;EOF $  trims_trailing_new|'\ A'#'(# Some of these-s are a bit white-box. The functional requirement is that #G Bword  be taken directly from*tty, and>p it not0echoed # on(screen, unless we0fal; back to/stdin. might runVplatforms out termios, but playsafe. @unittest. skipUnless(termios, 'tests require system with $') class UnixGetpassTest(unit>.Case): def  _uses_tty_directly(self):&*h mock.patch('os.open') as 5, \.21io.FileIO3ofileio5TextIOWrapper<ftextiok# By setting',turn value to None the implementation will #  code we don't care about in this<. We can ;outPfully if an alternatorks differently.Ff0.re_= %gc.unix_ )()#Hassert_called_once_('/dev/tty',5dos.O_RDWR | jNOCTTYw.yj, 'w+'DDcF)sresets_3J2 .tcgetatt@s@ S I = 3Pfake_s = [255, ]3 Vlist(Q  #tc !3,h.ANY, efalls_back_to_ $if0_raises7JQ ?io.< K3jy@ XGI N{BytesIO$side_effect =Aa.errory  xSPassword: U  textio.return_value) def test_flushes_stream_after_input(self):/3# issue 7208with mock.patch('os.open') as 5, \.G1io.FileIO')+TextIOWrapper2termios.tcgetatt3s3 SI = 3Q" =Mock(spec=StringIO)3getpass.unix_ (=O 5..assert_called_(alls_back_to_stdin8 s_ Asys.^:',  XX.side_effect = IOError-={.fileno/Attribute6support.capturedAerr(jstderr:3elf`cWarns(.GetPass7ing1;-  readlinekDonceT+CIn('sA.get+()m8_word:: if __name__ == "__main__".@unitO.P() imf =libT.util&os Hhsys fromN .!cript_helperKwarnings  .c_(.simplefilter('ignore', Deprecationnwp_imp  requires_load_dynamic(methv"""Decorator to skip a f not run under CPython or lacking7Iimp.dQ)."""n$ =S1.cpAR_only&@ C.0If(0hasWx(imp, 'f1'),=' 3d')} class LockTests(bCase):"""Very basic$ ofzort lock funcspverify_#a_state, expectedmPEqual.9fheld()5 4 "]Bbe %r" %c LOOPS = 50  6# The import lock may already be held, e.g. if the test suite is run Is# via "N(P.auto 0". "f_W_at_start =.%()-self.verify_ astate( D%) 4for i in range(LOOPS):imp.acquireWrvOTruehereleash{original p shouldyrestored now= Rif no x :try ) except RuntimeErrorDEpass:Nelse'jfail("rr withou"yraise "X\"") class ITests(unit.CCase)def setUp(\2modrortlib._module('Lsencoded+s'$_strings = mod.zCpath* __ "__< z modname, +Aing,0str2s  %.'? 'G@_' +<;assertEqual(@str,/,4fin__d(!, )[0] as fdZ4fd.1 p = [os. @.dir3(__file__)]|>R?s(Syntax\ Abads._pep3120', vqissue1267f4@fp, r, info . :, B?/fp #NoJNonec/fp,8tell(), 0gline(), '# test %s encoding\n'  %/%) .!fp, filename, info = imp.find_module("tokenize")9with fp:self.assertNotEqual(bFNone; *'., "utf-8n3tell(), 0^readline(),[ R'"""Tation help for Python programs.\n'Kdef test_issue3594( )@tempP_jB = '/0mp__&ersys.path.inIv(0, '.'6tryWZopen(e+ '.py', 'w') as ;?.write("# Q: cp1252\nu.;'\nBG jclose(FR(7ile*'kfinall#Ddel X9[0]support.unlinkD 2c=560# Test cannot coverload_compiled func.# Martin von Loewis note what shared library^have non-asciiK character because init_xxxzD4be AAand 0 neqhappens8dynamic OsBut sources ified to follow generic wayJprocessing #&s.# the return could be uppercase or 4fs_z! =&0getdsystem('Qvers  Windows ANSIEue pagesfB# on{space symbol from 1y0/ (http://en.wikipedia.org/`/Code_bknown_locales = {M'' : b'\xc3\xa4' L0$/8C 1 /c0 2 3 1@4 `5 e 6 7 8 }m!if)platform == 'darwin'an#, c OS X usesNormal Form D decomposition 0# http://developer.apple.com/mac/library/qa/qa2001/qa1173.html J special_char = b'a\xcc\x88'sUelse:> 6known_locales.get(fs_encoding) ;iif nott X)elf.skipTest("can't run this test with %s as filesystem m"l )% tdecoded. 8temp_mod_name = '_imp_helper_' + A])package> FPinit_Cos.path.join(dQ, '__4f_.py')*ry# if the curdir isRin sycb fails whenY)# ./python ./Lib/6P/regr 1.py6 7i.insert(0, os.ar@ ope0+ 'd, 'w')- ?@.write('a = 1\n",k, info = imp.findIule(is asIsNotNone(+ B+2Tru&[:-3].ends  G `Equal(B[0],0111r+ `12],2PY_SOURCE63modX?loaXmod.a, 1w2 warnings.catch_.().simplefilter('ignore  [sourc+), :  Udys.dont_9A_bytC0compiled() ,'cache_from_\MN#WnexistsY(os.mkdir- _name, 'w') as {file: .write('b = 2\n')&with warnings.catch_.()R.simplefilter('ignore\package = imp.load_T(test }_name,  self.assertEqual(KV.b, 2+zfinallydel sys.path[0]for ext in ('.py', /c'support.unlink(temp_mod +G 4Pinit_51nrmtree* c .'__pycache__') 2def]issue9319(MB = o"@.dir"(__r8Raises(SyntaxError,n@find/ule, "bads<_pep3120", []9from_source# Verify that theo module can correctly KP and P .py s# XXX (ncoghlan): It would be nice to use xpCleanImFhere, buat breaks beca<dthe osregisters someE@andlipy_reg onw Since doesn'tDSreveriqration,(m$ais lefa brokenCstate after Osion. ReialisingOxcontentVsBjustAt1os.environSits previous ris an OKworkaroundPorig_7 bgetenv  EmentVarGuardx=V("os" $!ddup(x[0].close(cnew_osSSJ, *x/WrIs(os, A& -2ANot(R*7@requires_qdynamicV kR15828%Pexten9sI - picked up@adap|qbetweenj0oldA APIxx#iPlib cQn't hH C50exa = "_heapq"/B?@_ = :!ifW_ is not Non$G %?mod, *x) 6 self.assertEqual(mod.__name__, example) @requires_load_dynamic!def test_issue16421_multiple_modules_in_one_dll(x!):;Z0# I8 9 : _ing several A from the same compiled file failsQ`m = '_dimport'"5obj, path , description = imp.find<(m)<v.close(Cmod0:"&(mf -1-__foo'E2E?barE 0+1+C2C CHwithRaises(IWError\` 'nonexistentO_z_P#1559549 added `xp` and `7` attributes to W# in order"provide better detail.N`#10854lemented thoseLp on*1ortKures of extensions on Windows.BkRbogusg!Hv as err) d#f0In(,JQ.exce.0 U7err3 #m__y_is_None(EWhen&an-G@ is G, open on!on+`behalf 8)e#15902J Cound1=a@if f)0[0]1not " Z>r2][2] !C_EXTENSIONHskipTest("WAdoesn't appeaEfbe a Ck"7mp.(,1, *WO[1:] R24748ESs_sysn|s_check .imp_dummyS:try del sys.gs[name] except KeyError: Epass:trymodule = importlib. !_me(name)@XIspec1util.find_('_testmultiphase'?XA.load_dynamick , Dz.origin9self.assertEqual(J0.__@__, 4g0__.39"Raises(Attribute, getattr, , 'dummy 5int_const, 1969rIs(sys.i s[]x5kfinall" 3Mdel Q & C3P@unit4q.skipIfdont_write_bytecode,.<". meaningful only when 3Ding 5"@def 5_bug7732(R) with sup.temp_cwd(!wPsourc-)TESTFN + '.py',os.mkdir(5}qRegex(IC'^No'>2imps,, ["."]) le_calls_to_get_data # Issue #18755: make sure D D0 toD) can succeed.{#era_LoadSICompatibility('imp',.__file__OPopen(A)w. ' # File should be closed?Will needcreate a newly 0ed _"CFSoraryx since =)Fifie# ts like __IUer___0modR = f"tmp{d(}"#q = type$s[* ])E eswap_item?5 ?;DValuX'embedded null'F?{$, 9s + "\0"@@cpython_o Zi.^31315DTher[0n't^2an ion failZ!in=)#.name is not a string. create_dynamic = support.get_attribute(imp, '-&')Flass BadSpec:dname = Noneorigin = 'foo'with self.assertRaises(TypeError)^ (A()) Rdef test_source_hash(^GmEqual(_imp.142, b'hi')\xc6\xe7Z\r\x03:}\xab P3HP85\x9765\xf8\x9a\x8b9'pyc_invalidation_mode_from_cmdlinecases = [ ([], "default"),"--check-,-based-pycs"5A&palways"@ Qnever> =]for interp_args, expected in  C%( =3+ +37J"-c", im. 4r; print@Dp_D_D)BLrscript_helper_python_ok(*y8 qres.out.p().decode('utf-8Q) cReloadTests(unit5.bCase):N"""Very basicXs to make sure that >rO() operates just lik B."""\  # XXX (ncoghlan): It would be nice1use.aCleanI # here, butbreaks becaA he os module registers somtp# handlVopy_reg on?w Since doesn'trirT, thepis lefta brokenCstate after Osion. ReinitialisingOcontentsD2andAt1os.environXits previous ris an OKGworkaroundREQmentVarGuard(WNo.2,osPexten 3 |('time'z | ~builtin|marshal _deleted_parent # see #s18681 from html import parser = sys.modules.pop('%')'def cleanup():e;[71] =s'self.addCBJ_Rwith &ssertRaisesRegex(IrError, a imp.reload() class PEP3147Tests(unittest.CCaseH0"""@s of1 2Q.""" Ptag =>.get_tag()@PskipUnless(implementation.cache9 is not None,\@ 'requiresMJ!beM_r_source(\p# Given the path to a .py file, retur!itN# defined<c= (i.e. under __py5_).6rP= os. .join('foo', 'barzcqux.pyexpect =}'oW 'j{}.pyc'.format4V.tag)G!.a`Equal({n, True), 4s!toEbe ''tSH_S1PEP2(e # ot. This sAgoodS!f QlQKBNull!er `If(sup.TESTFN_UNENCODABLE3"Need ancodeableRname",7Dunen% 20? = os.mkdir(3b;tryhB =3*, PkfinallTVos.rm|p if __9__ == "__main__"+ JBThe `A foring vari@Banno/ s. Empty lines above are8reason (Efor correct lin&e numbers) """ from typing import Optional __annotas__[1] = 2 class C: x = 5; y::@['C'+ONonecTuple x: int>str = x; f: !P[int,#]ssM(type)y A'123x1123 o:e = object (pars): bool = True\QD(C):72j: q'hi'; kv= 'bye'$es1Anew_" h5 = ('H', (C,)) j4J')#F(zdef __init__(self, x*DpassC3Y(F 52super(F, M%).\5123DMetao4P_(meta, name, bases @spac/rreturn ng>SeW0 = x = 'something'&y@ elsEfoo(r#10Nbar(y: List[str]m2yesg.#) ,unittestH4est0supN/_urllib G$os $io dsocketTarray %sy0tempfilepubprocelP.requ# The proxy by< G#oded below has logic specific to the OSX #Cconfig data6ucture but is able on all platforms.2 (R, OpenerDirector, HTTPBasicAuthHandler,2PasswordMgrWithPriorA0, _!e_ H $_1_macosx_sys: AbstractDigestx)1url(Terrorhttp.client # XX: # CacheFTPm` (hard`write)arse_keqv_list, s_X=  TrivialTests( .0Casac___allb# Verify whichTs are exposedEfor module in ' ', `sponse  , Qrobot"r'N`contex%{}gaexec('z%C*' %#, B)>4del['__builtins__'](#ifH0 ==' and os.]+ntdu, p =g.pop('url2path:%').pop('pathname2url') self.assertEqual(u.__module__, 'nturl2path=p= for k, v in context.items():vfurllib.%s' % ,E"%r is exposed|'<but defin_%r" %G4(k,g 1)) 0def test_trivial(d# A couple "/s>1Raises(ValueError, request.urlopen, 'bogus'L# XXX Name hacking to get this work on Windows.; fn6P= os.@.abs(@__fi.).replace(os.sep, '/ ifJT=Z'Fpurl = " :///%s" % Oelse:9:0f =. >(qG_url:vf.read(4f.close($parse_http_list Us = []('a,b,c', ['a'Jc']) ('t"o,l"og"i"cal, example= H!Na, b, "c", "de,f", g, h'z 0"c"X""d5ghaa="b\\gbd="e\\f="h\\\\i"l3="bf2!,fjg2ei"'])]@?string, rf G* S)T 1URL_reasonstr6err`e.5"('6D`In(errnPson, [0errO class RHdrsTests(unit.bCase):>_headers_dic5"""S4Theg.4 4`ionary7not a document%terface. ItJshould stay that way, because the cote set of pare onlyKaccessib*ahrough@C.get(), .has_PM&inpHowever<-s pre-dates those methods, and so real codePwill be usT'he0.The introduction02.4 j was a mistake ,6samsE:\previously saw all 2 user)-provided headers in . now sees only a subset. *5""" url = "http://example.com#self.assertEqual(Request(url,I={"Spam-eggs": "blah"}?)[@#],A)A6sOEggS9def test_rA__methods(!):,HNote the case normalization of names here, toI`.capit1@e()-B. This should be preserved for:backwards-compatibility. (InAHTTP,Dtitl{ is done by urllib2 before sendings.client)at e.g. r.hasW&(")ucurrently False, and_r.get: returns None, but that c9xchangedgfutureM r.removeh~ items both from unredirected_hdrs dic Uaries>hreq = zTrue(req)5U6_ u(), [('=@', '4F')])63addQ("Foo-Bar" ?az"pbsorted w)0[('b1baroaz'), @ytPNot-t"! Is|77 X6, "default") ^a\5 7("U-E<yD) 1O=ndpassword_managerSmgr =.%.aPasswordMgr()  add = mgr.add_password  find_user* 01add("Some Realm", "http://example.com/0joes/")D ni??'c.P:3128C3c d:04d5 e5o5:Ee") # For the same r9$, A sethighest path isuwinner.Kself.assertEqual( 5"),F('joe', '&')pt/ni~h{h/|T Ospams6/,# You can have differenuYs forFths.c0foo8 0bar8!ni:;b  0foo niq/q 2barq s #w, newer(hould be consideredbHPfirst Lblah9 `second:~W' r*r # No special relationship between a.example.com and exampC: add("a", "http://'15a")1self.assertEqual(find_user_passME/"),E}('1', 'a'))k'a.m `None, ow# PortsSome Realm'c |o)_:3128t '3cccr   0 (yl dZ '4d m em?0('5rer?def test word_manager_default_port(!):2H5""" The point to note here is that we can't gues#e Z Z5 ifJt9 's no scheme. This appliesaboth add/B ,.mgr = urllib.request.HTTPPass7FMgr(Gadd = mgr.zZ v* T0fg 801j7g7h71k4hi-:d2l0ij0 13m-^  ?100 m#j8i 0'10 j  F?WqFGo/g.example.com"), ('10', 'j'))&"self.assertEqual(find_user_pass("g", "h.example.ceP ('11LkL,o:80"),O*ittp://V #h i `None, WM 2ZlZOh  V  o i j 0'13mLmsi$ ! %l class MockOpener:addheaders = [] def open(, req, data=/timeout=socket._GLOBAL_DEFAULT_TIMEOUT)a3G.F K!, K& =e#, Serrorproto, *argscZ 3 =  BFileCread`Qcount^.Oline2Bclos/ UHS(dict(3getqCname ^return list!.values())Response(io.StringIOFf__init__C, code, msg, }\, urlR.H $[` e_url =6urlAinfoGU1g+l3 `CookieJa/*Qadd_c_aP'4uesrach_req!sextractNsHR ecQB \4>FakeMethod meth_name, action, handle): self.meth_name = #9# =B action =  def __call__(gw, *args}preturn .a),W@ class MockHTTPResponse(io.IOBasEinitfp, msg, status, reasonqfp = fp*0msg!*sgJ# =S _# =h 0cods62003Aread(&'''Oinfo'&{}'gbl)=urlQC_$ C@level = 0req_headers = []data = Noneraise_on_end?KFals)OsockBw_tunnel} host, timeout=T et._GLOBAL_DEFAULT_TIMEOUT<:ostO$ =Y8set_debugJ!, r" = A=p, port=b#, J U0?ost!P! =W$if\.+.9~]?Oelse9.clear()srequestod, url, body E, *,w en_chunked=f ]UethodDselector =}q is not%$+=K.items()Pl,W.sort !ifah N : = -"if o!y OSErroDgetra File(), {}, 200, "OK"QcloseQJpassr# useful for testingr machinery# see add_ordered_mock_rs() docstrin .H = 5)__R._define_( "7,(odOspec in methods:  if len(spec) == 2: name, action = + $Oelse6i, None<meth = FakeMethod(n, self.handle)9setattr(!__class__, ?W!) 1Bdef A,R, fn_%, *args, **kwds)[parent.calls.append(I@>$if3!isY[areturn&el5C== "$">> responseBs = MockR!(200, "OK", {}, ""?ress]questr!Re("http://blah/k.startswith("error"ccode =i[.rfind(" ")+1:]0:tryIE@int( except ValueE@6pasQ/re\$.r&0", [0], res, :N"rai urllib.cA.URL ("assert FalseLQclosejoBadd_(", 0# =??xV = []c__lt__[WotherZif not has2, "mr_ordeFC# No$", leave in original ;. Yuck.6Tru }1 < q4 :hed_mock_;s(opener, _"""CreateH*rs and add them to an OBDirector.PO: list ofs RtupleKstrings defining0ods[$onGrs. eg:e![[_p", "ftp_C"], Einesf.,?!().C() on onez, 6Y%"anyu These^just recor0 irnQumentLP. Us!a " instead3"a *p causesg1 toIperform someI (seO()),E9I,.r`;")]M.http_error() oa Request object. F1"""6as = []count = 0for meths in a_spec:class MockH1Sub()04Bpass?h =@v)i#h._order += !add_parent(&er>+ 3F + 17s.append(h5E.W|]s def build_testCer(*8_instances [ = OpenerDirector(}uhq ?IB!1 c3TTP(urllib.rS.Base# useful qing red@ionsQ authL# sends supplied header&code as first response8`200 OK%jsecond&___init__(self, T,fP.df=:rreset()uT c_T)CoR_IMW, reqRimport email!py9 Ucopy.deep (L:10if c.6= 07!  ,*pname = .client.!s[Gi80Rmsg =.message_from_string.:VXu.error( &""E,rFile(), , V, msgeOelse Preq = h P"\r\n"aR(200, "OK"2, ".get_full_url())S AbstractHM># Uthe Proxy-Authorizationby verify"th3# properties of6con debuglevel=0 h.ITdDconn<@TTPC$st.O&do(`\1 PCheckO Jsting auth  # sends supplied code response #checks if auth header is specif7in request4def __init__(self,Y!):V.m= @has_l_l= False &]QresetZ T;http_open?,D if.F|('Authorization',. 2Tru>$pname = y.client.b%s[ ]0return MockR0 , O,File(), "" .get_full_url()) class-PasswordManagerLSadd_phMalm, uri, user, !realm = Purl =D 0ser:serc% =nPfind_%),d 8f#,)def test (; [?s[2[([97'Z 500)/(j], 0)]kclass Mock1Sub(fFpass?h =H |#h.= *s.append(hK o.%=Z#{r1se mpanks tovrir sortm Z1[0]:7s[1f515,0]\raise # g@URLE[ stops processT  Y , / Mself.assertRaises(urllib.error.URLE , o.open, req)  self.assertEqual(o.calls, [(handlers[0], "http_B", (req,), {})]) Mdef test_(|(]!):of# XXX _default! =s are a special case)o = OpenerDirector(Pmeth_7E = [3)[("i 302")],*"_400", "raise") 8 Z8eturn responB^J303"~m"b ] = add_ordered_mock_E(o, 2,class Unknowna__eq__w, other%rBTrue%q = Request://example.com/"oD lene) == 2)x52_f,,+0(),RA, "" ) for expected, got in zip( Iod_name, args =O w  D)F[:2][ >k,+jprocessors R# *_r! / mods get ed appropriatelya,} _S3"e0:/rep,%# on *all* that define theme# not justd first8 7Es]q :1\q+6), K6")]i0&, p, kwds)enumerate gif i < 2\ self.assertEqual((handler, name), calls[i])  <len(args), 1/ IsInstance0[0], Request8]else:y# *_response 42 k8$# from opener. is None, because there's no##  that defines http_M#to"= it>0if 0[1]u1notyn1], MockR) def sanepathGP2url( )_2try \.encode("utf-8"kexcept UniE"VError< raise unittest.SkipTest("U\able to utf`1url'= urllib.r. =`if os. == "nt" and=1.startswith("///" j-A[2:]T # XXX don't ask me aboutq mac...(dreturnl class H%s(qCase): = P_ftp(HFTPWrappe`>__init__>g, dataD&[.! =#~HretrfileH P , 0typ,V */! =:$B=io.StringIO0), V)BclosFpass3NsNullFTP(^ O!i5uconnect@, uswd, host, port, dirs,5Atimeout=socket._GLOBAL_DEFAULT_TIMEOUTAWz ) = {+ ' =2z?irs!Bftpw! = <?C!imeftplib>M = "rheum rhaponicum""Kh = +5>h.parentO'(0for oj , _,name, mimetype in [ ("ftp://localhost/foo/bar/baz.html",1% "+", ftplib.FTP_PORT, ""I8P["foobar"], "aq "text/n)ouparrot@|-P<2%25`7%Q?"42b8S< 5:80 v #80D+ ", None*gif;type=aW 0A8[$5gif # XXX really this should guess image/gif)]:req = Request(url).timeout =  = h.ftp_open(req?#" authentication not yet implemented by FTPHandlerc self.assertEqual(h.user,  n+passwd, /, socket.getpbyname( )A`port, +`dirs, +ftpwrapper.file$, > , _;headers = r.info(^0(("Content-X"), mime D Cint(x[Dlength"]), len(data)) def test_() imy email.utils4ph = urlrS.FileqoPparenMockOpener(NTESTFN = sups.n`urlpatt@sane 2url(os.@.abs(:Y towrite = b"hello, world\n"` "P%s" %i, "file://%s" % urlpath, "#% (socket.gethostbyname('local4'),I)J]XEtry: l>addr = ` s%))Ceexcept:aierrorc%'';5if } 1urls.append(4%) U0for0 insXf = open(TESTFN, "wb" f.write(to K![inallsf.close( h._Request(url}*data = r.read($qheaders'Oinfo'qrespurl'ogeturl)f rw@stat0os. modified = email.utils.formatdate(?E_mtime, usegmt=TrueOos.removeself.assertEqual(b/,  ,j["Content-type"], "text/plainDalengthF/13>TLast-O= & {v[2:80 /does_not_exist.txt"^anot-a-d-e.com//dirH9!%s`  osrcwd(), j somerandomontheinternet"%s v(`] <Ft`RaisesAlib.ZP.URLEc B/, C 0h =ar.FileHandler o = h.parent = MockOpenerC() # XXXX why does // mean ftp (and /0not@!), WwhereG is file: scheme specified? I thinks)really a bugOIwhat was intended to distinguish between URLs like:C/blah.txt (a"/localhost-$ftp.example.com3T6URLfor url,XU in [#(" U@/foo", False),89%pAsomeMh/g<].req = Request(urlg:try0 h.b_open(req2`exceptlib.error.URLE Kself.assertK(ftpP'ls8Is(o.req, *PEqual.type, "ftp"nX .2 ==0v!) ;def test_http(<"):z4h =r`.AbstractHTTPHandlerUo = h.parent = MockOpen$pVpurl = "r8://5"$!method, data%("GET", None), ("POS b"/") K, {"Foo": "bar"}?req.timeoujadd_unredirected_header("Spam", "eggs:WClass8[<"do1 # result attributes r.read; line # wrappedRFile \ ;@info;0get` # add3code, r.msga200, "OK"v adAfromy.getreplyhdrs = r.s8 ; &.__contains__k4 gives dict y4l'*`url(),  /. 7level, 0z,v,2 selector, "/") self.assertEqual(http.req_headers,  [("Connection", "close")7 ` ("Foo0bar"), ("Spameggs")])xs`data, %) /# check OSError converted to URL.aise_on_endu = True(R.s(urllib.ee.X, h.do_open, \Y, reqCfor Type on POST which is str.req = Request("\ ://example.com/","badpost"=vrS_Hadding of standard $Go.ad9[* in b"", None: #U, GET,w67 = MockResponse(200, "OK", {}, ""02newj( !ifm ,vQNotIn%tent-length"m.unredirected_hdrsJ OtypeH6elsd _ b>req[[], "0GO!]/ "applicae/x-www-form-urlencoded# XXX the details Host could be better tested P" KKS# don't clobber exist -Jadd_\K"fooA1, " =? 27zv/, req,dif notLPself.assertEqual(aR.get_6$('-6'), NonepP :9'),|I'c'}Oelse?int230)Pdef t<_body_iter(h)0# G4ic "ere is no wayed,#_Fall o  (yield b"one"?+11a ea ] Y5LU#QM I? 11$empty_seq%RZero-w) Y be treated like any other/-u  6()) O8reqx"S"), ""IsertFalse(re6q.has_header("Content-length")) def test_http_body_array(self): $!# . Iterable - X! LX is calculatedc?h = urllib.request.AbstractHTTPHandler()1o = h.parent = MockOpen$%i( =("I",[1,2,3,4]ZBfor s in {}, {f": 16}7rreq = R ("/://example.com/", ,hJ2newMSh.do_Z_(req(self.assertEqual(int(=D.get'c')),16 hf_debuglevelvgxDirectoSL&=1co.add_p((hBopen?s://www.D"* 'h.?, 1doubleslash# Checks the presence of any unnecessary D E"url does not{p# break=thing. Previously, aEdMly after8hosMcould cause incor~P pars\vGCdata = b""eds_urls = [foo/bar/baz.html",3/4 3h4 ] s ds& , @$i whether determined Ply if re!no proxy5np_} 12| 6?R.unreed_hdrs["Host"], " &aQ.set_a("some :3128", None+>;@full_setterWo ensure that components are seQ0ings$# pqv object'http://example.com?foo=bar#baz', 'http://exampl.&spam=eggs#bash9"%] f0# testing a reusable request instance, but the url parameter isH5ired, so just use a dummy one toRUtiate;Rr = Rr(%')*1for in%s:3pr.full_= qparsed  V(url)Aself.assertEqual(r.get_V0(),W4$# @ setuses splittag  into components.#1Asetsjfragment as N>Awhilo@s itb)''NM`or '',Dsed. @1urlt u).queryPV1def[@@_del6(`)Gwww.Fdel T Is/(%&h&selector, ''ixpath_in_weirdurls# Issue4493:E@lib2supply '/' when? 0re W does not# start with'/'h@lib. est.AbstractHTTPHandler(Ph.parc= MockOpen kRpython.org?get7reqBv2new$Sh.do_V_(req$5.host, '8/@url_PAout_v/=  A? = c ]error<4E-Processo;o? "%/"c # all 2xx a svthrough@  Response(200, "OK", {}, ""$_r7freq, rJ`Is(r, 8False(hasattr(o, "proto")) # o.q called r = MockResponse(202, "Accepted", {}, "", url) newr = h.http_r=freq, r'self.assertIs(r, 8!False(hasattr(o, "proto")) # o.error not called 6, "Partial content# anything elsesA(and Opener returns None, hereV 5Bad gateway [(m3Equal(o.0, "" <rargs, (H/, 1)) def test_cookies(Q!):Acj =5C FJar(0h =lib.request.HTTP+Processor(cj3s.parentV(qrreq = RO(://example.com/"N 200, "OK,7\(%mrcj.ach_J/eq'f*req.originX_host, "=unverifiablxMPcj.ec?, r &7SredirectTfrom_url = qa.html"L/to-b-RhHandleo6 # ordinary behaviourfor code in 301, 350303 7T,@data,&, "blah\n".2method = geth _a_%s" %~8 U , .p.timeousocket._GLOBAL_DEFAULT_TIMEOUTgadd_header("Nnse", "viking=withhold:!if1 is ) gC-Length", str(len()$une@Spams<try:  method(req, MockFile(), code, "Blah", ,5Headers({"location": to_url}))> except urllib.error.HTTPE :/w# 307 in response to POST requires user OK?self.assertEqual(>307o0IsNotNone(data/+[o.req.get_fullP??tryX), "GET"UaAttributeYgbFalse( L# now it's a GET, there should not be h regarding contentP(possibly dragged from before be>ah= [x.lower() for x*$]{sNotIn("-length",y<Htype:w /0["N_nse"]v  "viking=withhold ySpam",  8unredirected_hdrs) # loop detec req = Request(|8timeout = socket._GLOBAL_DEFAULT_TIMEOUToDdef 0(h,,\=s _qh.http_uN_302?302 0 # Note that0 *original* @ shathe same record of=#Pions M@sub-ests caused by1.1# infinite. of a URLc itA", _req_host="example.com@coun0Q.- 4zwhile 1."7:///45+ 1[# don't stop until max_repeats, be cookies may introduce statew 1untHJRHandler.xeats) ' # detect endless non-repeating chain of redirects 'req = Request(from_url, origin_req_host="example.com")?count = 0req.timeousocket._GLOBAL_DEFAULT_TIMEOUT5Etry: zwhile 1(h, req, "http://q/%d" % >" =E + 1y except urllib.error.HTTPE self.assertEqual(V,Ki Yrm[R Hadr.max_aions) Sdef test_invalid$()/ =qa.html"TMschemes = ['N!',s','ftp']/~1file','imap','lda1)Vb4h =}$(o = h.pareMockOpener$D Bfor K in dTurl =5+ '://' +#a:esRaises(B @, h._O_3020%File(), * "Security Loophole"?:Headers({"location":Surl}) % l #! (That's fin o.Gget_full_@relative5PC/"/Z5 parse.urljoin/ -_cooki "# ! s shouldn't leak into redirected requests  from http.cookiejar import C:Jar-Ptest._7_7interact_netscape @Fcj =W%() 4`(cj, "a://www.example.com/", "spam=eggs"Fhh = MockHTTPHandler(302, "Location:TqcrackerT@\r\nO deQsurllib.:.\DefaultErrorhr7Redirect3_cp = iProcessor(cjgo = build_opener(hh, hdegrh, cp1.$(V*self.assertFalse(hh.has_header("2"))Adef r_fragment(N%):!ed_url = 'index.html#OK'H'J' + q'w>f o'.^Equal(fp.geturl(),.strip(|no_path# Issue 14132: Relative^ Xs original Ereal_class =q.clientK`Connec0psponse1"p/1.1 302 Found`?query"FUi" =p@fake-3(rex ]ddCleanup(setattr,!, "wL0urliter(("/# &").4def(conn, method,', *pos, **kwZ url, next(b.m _>p# Chang: for subsf0nt 8"._0__.JdataF200 oHello!$ =@Y9urlpython.org Z iV @%encodingrSome chaKers in thkD target may need special hing, # but -most ASCII characters should be treated as already encoded class Handler(urllib.request.HTTP%):3:def http_open(self, req&*result = %6.do2.connection= b<3last_bufC6M.buf4# Set up a normal response for the next @td = test_@fake(8 b'2/1.1 200 OK\r\n'+Content-Length: 3-  >123d)v`return5ulth% =:Ser = Qbuild3er(A6/Js = #(b'/p\xC3\xA5-dansk/', F%C3%%),S8spaced%20path6 6 4?(?p'l\T[locaA] in?s>BwithsubTest(repr(?)Gg4%302 RedirectW Ld: ' + _ + b'7 )"= h. ('^://example.com/'>Pexpecq= b'GETrk 4 = LZ qassertTrue(;p.starts()$pr#1)) N  a_proxy!o = OpenerD6or(.phrPF`(dict('!="^.,v:3128")Nco.add_6(phmeth_spec = [0[("_F", ":H9")]/gvordered_mockUs(o, {.urreq = Rzx://acme&/"PEqual.host, "87oiK d >[gs[0], N*)]?[tup[0:2] up?o.calls]+def test_proxy_no_proxy(self): os.environ['$'] = 'python.org'. = OpenerDirector()ph = urllib.request.PtHandler(dict(http=".example.com")Iso.add_h6&phrreq = R] ("L://www.perl&/". .assertEqual(req.host, "43`o.open)G[{5IOdel  def testFOO_allS*Js3so:3128"meth_spec = [Y" [ s_", "return response")]0 %@s = 4ordered_mockAUs(o, x)vsNQ7 T` $[(Q[0], I5)],8 [tup[0:2] for tup in o.calls]*d\authorizationpF''p = MockHTTPS v 9%4theader("(-A;gFooBar6 8User-Agent/WGrail. req.host, "www.example.com") self.assertIsNone(req._tunnel_host,`o.open!# Verify Proxy-Authorization gets Ked to request.# httpsconn _headers do not have the^,G butO-req will?lNotIn(("", "FooBar"),Y._handler.D.req$yvUser-Agentm_Graill[si OsNot PEqual.@, "p4_:31289=3get\a'")] ]`@unitt,skipUnless(sys.platform == 'darwin', "only relevant for OSX@def KQ_osx_P_bypaQQelf):qE = {'exclude_si*': False% eps': ['foo.bar', '* ` 127.0.0.1 Z0.10'Ir'10.0/16']} # Check s that should trigger% ;#7X in (?www I! !W"TYTrue(@_mac sy f(,m 'expected/` of %sT0be j1' %w5[9Gabc.0E4 XproxyOb hPVqPdict(!="no:3128" &pho ~%&Networks{%A7, '}@"%s"{R*, password_manager,  "http://acme.example.com:3128/protected"H]proxyB8!) def test_basic_and_digauth_handlers(self):3q# HTTPD*RAuthH( raised an exception if it couldn't Sg a 40*Presponse (python.org/sf/1479302), whereR shS insteadK turn None to allow anotherr (especially;B )EDthe .BOAlso7027, RFC 2617 sec!1.ge mustBtry  first (sinc0's Pstron  scheme), so w8cororder of calls Bto checkiRcomesoclass RePingOpenerDirector(Z__init__?  A./*!.rved = [] rpk, info( H.append(,PMTest(urllib.request.4 % w_error_401*args, **kwds5cparent"("-")!. J{ D SC $ B:A @??om/ =password_m} = MockPM(1C? =  XAB @ +(?realm = "ACME Networks"trgg((401, 'WWW-enticate:  j="%s"\r\n2' %kD.add(* digest_handler)  opener.add_handler(http 3) ) # check basic auth isn't blocked by digest J failingCself._test_F_F(,Yy, "Authorization",F xrealm, , password_managerE "?://acme.example.com/protectedC0)tXpwas trilRefore3 (twice, because> l called .t1() 9oassertEqual.recorded, ["A", "C"]*2%Adef unsupported_4(g%):aer = ODirector(# While using DeHJhVm = urllib.request.HTTPCV(NoneqB@Mock7p(q401, 'WWW-enticate: Kerberos\r\n'_ u0 )Z.Raises(ValueError, w$, 8www"  B+98 f c@@NTLM  Q  ,?ead* j-e_url, Y imA5e648Fuser = "wilexcoyote"l() fed through to eu D L=.8  >?url< _manager.useCr)  self.assertEqual(password, _manager.%) ?popener.(request_url"# should have asked the^ ^A forusername/omtarget_realm,  ?url, protectedexpect one  without authorization,n( len(http_handler.W_s), 2_False4[0].has_header( )Kd_ = bytes('%s:%s' % (), "ascii">Tdr_value = ('Basic ' +`base64.encodei^z).strip().de( @[1]., trunredirRhdrs[Tp]{ @# if+can't find aW +e won't#OAHTTPe error%% =a)u = NoneA Fset(I  j 1Y8%Pdef tbq_prior_auto_send(l!):/# Assume alreadyVenticated!isCF=Tru1#APIs like Github that d return 401\ = "wile", "coyote"0'://acme.example.com/"e,xp = Mock8HCheckAuth(2004pwd&0 = 1P7MgrWithPV9do<=-v(_? T.add_(*, O/,  . {@V (6^'A = OBDQ.orI/ BQ/) op ener.open(request_url) # expect  to be sent with auth header5self.assertTrue(http_handler.has_5_5lPdef tbasic_prior' send_after_first_success(f%):u`# Autod ;entication is Gful onceuser, password = 'wile', 'coyote's3'://acme.example.com/protected:0alm4VACME'|pwd_manager = HTTPPMgrWithPeAuth()N2e<BL-!Ha|(_? T.add_t(realm,*, $3i7 = l.*edm87cFalse(7_ OpDirector " ( Rp = Mockw2e401, 'WWW-U!: h (="%s"\r\n' % Nonel* .k-LPCheckF(200 FY2MQ 0# A\ getting 200 from wV# Nexs in the 19m^lclosedOq"""Testdconnec9cleaned up wheresponseYP5"""for (transf[Pdata),("5("Ch!: FP", b"/;"),,TO-Encoding: chunked54:0GContent-Length: 4>9,g@ = "+A/1.17 OKd {}".format)FV" =urllib.fake(b .e`e() + @3 = >.Abstract; req = Request("http://dummy/") req.timeout = Nonewith handler.do_open(conn, req) as resp:5_j.read(pself.assertTrueL.fakesock.closed,N"Connection not ( {!r}".format(transfer)) Edef test_invalid_:()"""Test the kis cleaned up after an Lqonse"""m>" =taurllib7(b"}U3 = 'request.AbstractHTTPHzDrreq = R,5pRaises(.client.BadStatusLine' ] ") class Misc`s(unit.0Casnser_has_", ,_V rany(h._(Z__ ==;rfor h inv.sQbuildH!er8 My 9BpassK4FooC HCBase HT#fo$ ^l3BarQ(l1bar h l?< Ho = (&, .? X6o, ;/^@# can take a mix of es and instances2/()34subof default2s override  2[# a particular caseeMing:0be o'edJin explicitly  Z5has_handler(o, urllib.request.HTTPHandler) o = build_opener(5&()7Rself.2b_has_hX(v w# Issue2670: multiple Fs sharing the same base classC MyOther%):>pO 'MyV,j F2 !) `@unitt#skipUnless(support.is_resource_enabled('network'),A 'R %Sires 3 access'@def ' _i`16464(QTwith transient_internet("http://www.example.com/"DU, = />est4R| .assertEqual(None,uCdatav (, "1".encode("us-ascii"<9 kLb"1"k) 1 0 get_header("Content-lengthy 234567890#?0dRErrorbLface5"""n 13211 reveals that H didn't iAment}1URLfIn even thoughFis a sub4of B.Cmsg = 'somethpbad hap%d'3`url = S = fp = @hdrsGLF: 42C6err!e:3,_p, msg, QF, fph True(hasattr(err, 'reason'0LBerr.',osp(?, 'mexpected_err  %s: %s' % . , 6msgD s;), _4 yqual(repr(er&r), expected_errmsg) def test_parse_proxy(self): $_,cases = [#'!('>.example.com'," (None, 5*))7Y_:3128^":c/',*# The authority component may optionally include userinfo# (assumed to be #(name:password&jo@'joe', 'V k -m  ,rA w"#Es with URLS7('http:///+' ch%='n ulw% X{C # Everything after tUis ignoredf. rrubbish| 0ftp"# Test for no trail@'/'  I `5'))u]W,&tcyO in Kk8~.assertEqual('tc 6Raises(ValueError, C, 'file:/ftp,unsuppor60algl,hmhandler = AbstractDigestAuthH( S ) as exceU.get__impls('invalid'fself.assertEqual7( str(exc.exception), "Unsupported digest authentica1 algorithm 'invalid'"D) class RequestTests(unittest.aCase):3+3Put.(method = 'PUT' 7def setUp(self-d.get =("http://www.python.org/~jeremy/")Rj=?pos> >Fo"data"$ headers={"X-@": "++"})", :{='HEAD'M pu~,cforce_2L v"POST") _assertEqual(=!, =) 9CGET"8?get7Y89%PUp/pup| v!;9QFalse F..(3GN = "spam"~?Tru}_7get# issue 16464f we change we need to remove content-length #er@(cause it's mprobably calcula*for previous valueGsetting__should_}_}_} /NotIn("Cunredirected_hdrsv$Jadd_(W+42?l#42T PLdrs[]K6  !7485 same @dele.*oQ'foo' h", 3)  self.assertEqual(3,get.unredirected_hdrs["Content-length"]) 6del:EdatadlNotIn(Fs !) Hdef test_get_full_url(Z!):! "http://www.python.org/~jeremy/",;? L q)selectorv(?Greq = Request("0"/", req.\ BOtype>"6 OhostN X@X}_unquot(6%70* 7_proxyBFals.3Bhas_3)3set"0erl1", ?Trua _ rorigin_req_OE!8 [wrapped P2url_fragmen /?qs=query#G_=true 5 a|O#funn ej# Issue 11703: get/) omits in the ual URL.Dsurl = 'HdocsD library/urllib2.html#OK'? ;url I1), 2N0ull /urls = ['*/B/ F!']0forE IY) if __name__ == "__main__": unittest.() """Script used to  os.kill on Windows, for issue #1220212 This sA tarted as a subprocess inW_os and isnthe CTRL_C_EVENT%SBREAKsignals, which requirejcustom handler to be wr@n in1he @target. See http://msdn.microsoft.com/en-us/library/ms685049%28v=VS.85%29.aspxa similar example C.\ from ctypes import win, WINFUNCTYPE 9Dmmap sys # Function protoW4the# f#. Returns BOOL, tak>DWORD. H>Routine =(.;<) def _ctrl_R(sig)s2"""\ig eventr" 0wrminate 91"""`if sig..fApass0/el2O6'serint("UNKNOWN !")_( 2 = rD( ) utConsoleCtrl.# = .windll.kernel32.Se/ @.argSs = (Y,q)A0resA* =/ if __name_R# Add our cBtrol5ing with value 1Jif not (]3, 1OPnable>?addE5exit(-1) z# Awake =@m = i.(-1, 1, sysbBv[1]m[0] = 1M Dohbut wait]while Truiasyncoredselect$os UsockeQ5timMUerrno26truJthreadingC0sup$ioqBytesIO #B.PGOAVraisemSkipTest("Ys- helpful(@PGO""TIMEOUT = 3 HAS_UNIX_SOCKETS = hasattr(Q, 'AF#') class dummy_init__(selfH@.clor= False52 1lfileno2-)42channel( =( f): +self.socket.close() class exitingdummy: def __init__(:)Upass &handle_read_event/raise asyncore.ExitNow}M?Rwrite@3 = Tn% OexptO_crashr.error_d = FalseExceptionl_ True # used when tesE& senders; just collects what it gets until newline is5 t capture_server(evt, buf, #tr`.listeLconn, addr =;0.acr!()Ke {timeoutGFelseqn = 200Bstart = @.^while n > 0 and$2 - :V< 3.0_7qr, w, e80.se ([C], [20.15Jif rKen -= 1pdata = T.recv(10N%# keep everyt& 6ufor theterminatoriAbuf.(s.replace(b'\n', b'')x1if @ in 6Ybreakp.sleep(0.01),7lfinallE"7pevt.setbind_af_aware(;a"""Helper func@ to 5# ai accordingits family."""if HAS_UNIX_SOCKETS=m.,3 ==N1.AF* # Make surepath doesn't1st.gsupport.unlink(*`_unix_(etJ %.4O_FTests(unit2.CCaseGjQ;? A_exceptionFG# check that an )` other#n  in the object handlerKmethod causes+$s_error to get called>tr2 = crashingdummy( read(tr2 PEqual.q_~d, True) lwOmQr*#6+ constants0sel`modulet!# are not present0Windows systems (se3ih:; http://mail.python.org/piper/-list/2001-October/109973.htmlo# These should be as long as poll is available@unittest.skipUnless(hasattr(0, '=R'), '. required'@def I_X@"f)6# CLAcorr_sUF by Dibutes = ('$', 'exptt `closed 'KexpectedIect.POLLIN, f/),%4PRI&bOUT, ''cERR, '(?HUP(ONVAL)Qclass6obj__init__ c = False."# $ " O+ o_event+;KL(! =xM  " 0' P "{ for flag,  in expected:  tobj = tes 7()  self.assertEqual(getattr(,, expected), FalseAasyncore.readwrite;iflag) m# Only the Qibute modified broutine we~k to beIcalled should be True.%1forg1 ino)s:$  !),B)== check that ExitNow exceptionsobject handler method# bubbles all-way up through s s  Etr1 = exitingdummytRaises(W.,i, tr1, &an` othern!in  #q causes/4T_erro91geteGtr2 = crashAtr2.^_kd$r2R Za'1def_closeall(A)._p(= A_defaultI g{S, useR6# C7_!) s everyta given map@al = []<map = {}iBrange(105Ac = {channell.append(c c.socketi0[i]c'if#Uj_ $:try=5 ? .K!ofinallh& =", Jelsek Dlen('7, 0+clh C  __compact_traceback3 r6$ E("I don't like spam!"k  preal_t,3l_vtb = sys.exc_infor back() else: self.fail("Expected exception") -(f, func, line), t, v, info = r,U&assertEqual(os.path.split(f)[-1], 'test_asyncore.py')C|7compact_traceback= t, real_tav$v$q, '[%s|_]' % ) class DispatcherTests(unit.RCase)def setUp(=Bpass#tearDown&Eclose_all(6st_basic8Ed = <d(d.readable(), True- Jwrit-Orepr0God), '< at %#x>\id(d)?log# capture output of E.U) (to stderr( l1 = "Lovely spam! Wonderful"e l2,I don't like"with support."d_tS() asjd&l12!3s =E.getvalue()1 !, ['log: %sIl1, #2]r@log_pBZout via prin$Have you got anything u7?`Why caPshe hAegg bacon and sausage>3aTHAT'So^v in it!d{5out?out~GEGGS4#23, 'SPAM';%?out%el@= [' 2n%3],.i$, _TunhandledUd.ignore_@typee! ?u %V_expt d.handle_read() d.handle_writeconnect() =lines = stdout.getvalue().splitO expected = ['warning: un~ d incoming priority event',q B568]self.assertEqual($, ?def test_strerror(9%):H# refers to bug #8573err = asyncore.Ferrno.EPERMif hasattr(os, 't'p[ err, os.1(_`&-1%]@TrueK != "") class dispatcherwithsend_no(#_$_%S-LableNreturn False.y_ 4EpassDWithSendTests(unit.GCase_setUpVntearDown&close_allx@support.reap_thsPS 0:!pobn -= 1u@evt.t$=7capW , &*2zfinallyjoin_thread(t, time:out=TIMEOUT) @unittest.skipUnless(hasattr(asyncore, 'file_wrapper'), '1./ required') class FileWLUTest(pCase): _def setUp(self.d = b"It's not dead, isleeping!"G2with open(support.TESTFN, 'wb') as x1a.writeA.d) QtearDown_kunlinkn @|st_recvAf?os.os.O_RDONLY)Ow = z6(fd&os.close<JassertNotEqual(w.fd, <&ileno(),OL13),"c7Aad(66/wARaises(OSError, w.r1Lsend!d1XCome again?F!d2I want to buy s*vcheese.+ WR1 | fAPPEND)w'd1P.(d2&r& 7r`d + d12xdispatch{ 6)6st_#  data = []\DT#Cqhandle_JG #'tata.app.k629)1s =q SNloop(time7 0.01, use_poll=True, count=V.Rb"".join("1), ! K source_warning# Issue #11453df. YFATchecks(('', ReW)|ENonefmPgc_collect(%R_twicWONLY)  f = asyncore.file_wrapper(fd) os.close.fd) # A dupped fd1with self.assertRaises(OSError):)wfs%) ;Equal(f.fd, -1# calling  twice should not failQd class BaseTestHandler(dispatcheAdef __init__(, sock=NoneB.7K.flag = Falseohq_accepttirN0 ExYion(".supposed to be+3ed"b a/edcebeoconnec//ex',]a"-_e_' OServHa"""A s& which listens on an address and Qs thew0ion5"a U!r.6""" qfamily,`,7=`( "pcreate_s2et(n #set_reuse_(bind_af_awared.H)0+(5 $ = @property"U}1esshbreturn~@.get _name( m:(LGY~Client(7ess D  V(X! Ipass<BAPI:tearDown_all(ignore W=Trueloop_waiting_for_R, instance, timeout=5 = float(q) / 100yycount =Vwhileaet_map2> 0: $asyncore.loop(timeout=0.01, count=1, use_poll=self.7) if instance.flag:)ireturnbY -= 1U.sleel`fail("g not set") C def test_handle_connect(7)# make sure * is called on ?^class TestClient(Base a* ] &6r = Trueprver = f Se E.family, ;Faddr#cK'4H.66ess9% _waiting_for_g(Te_accepd))erwhen a `psoListenerqH6r):.3__init__,$, 2\Q.>+'create_socket(a+bind_af_aware.2!, T\l.(5P:Ress =Q@.get Sname(UH  (0b$0s!edf ?ed(dispatcher. %  , w #P.clos=0lagTwS 6rea # mak!e sure handle_read is called on data received class TestClient(Base %):&-8def^[(self#'.flag = TruekHrl{ Nq__init__nk, conn&tH.6 5send(b'x' * 1024)server = ^S .family, AQaddr,@icQ^4Ab.CEess)9%loop_waiting_for_T(T!Stest_Qwrite$Z# mak( "N va _KRTOclosR(R when the other end #s#oectionA^# in order to64 be(Pwe ar-ipposedmq#Aat least oneW1v()E 3[recv(`PEG=!Crp  hup_after_|_broken# Check that ECONNRESET/EPIPE-orrectlyXd (issues #5661 an# #11265).*a= b'\0&28 &):'&1yg E $;expt(self):  self.flag = True !close() class TestHandler(Base&):-KQdef h+`_read(W%):P#.recv(len(data))% ?fwritablecreturn Falseserver = S A.family, Xaddr,`clientFAestC Ab.C6ess9Yloop_waiting_for_(Tw#@unittest.skipIf(sys.platform.startswith("sunos"),9# "OOB support is broken on Solaris"Lo_Aexpt# Make sure'W`calledWp received.# Note: this might fail6Tsome Us as H'isAtenuouslyed and rarely uspif HAS_UNIX_SOCKETS- == socket.AF* +("Not applictC to 6E3s."}8if l"darwin"use_pollx !E may0macOS; see issue #28087~ # -S1024,.MSG_OOBN/7.tWF__init__k, conn*X.61 send(bytes(chr(244), 'latin-1')N[G ArrorP4 qP?u1.0 / 0*t<eE :tryBNraisexcept ZeroDivisionED6pasUOelse/s! EcRion("nion not d4_.T server.addrcess) self.loop_waiting_for_flag(client) ,def test_connection_attributes(G!):*Yserver = BaseS #.family, 0V.addro4C| 4U6n# we start dis%ed mssertFalse(.*+5Tru*Paccep*'# this can't be taken for granted across all platforms#j +X execute some s so that c Rs to ?asyncore (timeout=0.01, use_poll=, count=100"ar<U1/4C the%f_lose(W /edAstop5ing/.c2S =reate_socket55 = dispatcheru-.cASEqual(s.ps.type, SOCK_STREAM<  73getEO(), " get_inheritable()Lbind<if HAS_UNIX_rETS andh4 ==!AF*lf.skipTest("Not applic+6E7s."11%1.d.listen(5port = s1>name()[1]22# EADDRINUSE indicates<{et was correctly bounRaises(OSError, s2!, P[0], `set_reG2L ETS and self .family == socket.AF_UNIX: self.skipTest("Not applicable to 6EUs.") ACwith.e(P{A) as r:try>@.set@opt(et.SOL_SOCKET,J_REUSEADDR, 1)Gexcept OSErrorgunittestF("SOL not supported on this platform"i>lse_Y# if Usucceeded for we expect asyncore#ydo the sam!5s =>.dispatcher7>  eassertFalse(s/.g L.)oclose(!rcreate_P sQ_reuse_addrP?Trua@x.reap_threads@def _quick_connect)# see: http://bugs.python.org/issue10340S1if 4in ?PAF_INsdgetattW3, "p6", obj'))[XQ specificC@ and\i6Tserver = BaseS ,@# ru"e < 500 ms:A should be Eqed in 2*3t =DQing.T(target=lambda:yloop(timeout=0.1,G wcount=5wt.start : 3CK_STREAM:,6(.2[ !voLINGER  struct.pack('ii', 1, 0)\y #s.(3.>ess R2pasr kfinallCjoinC(t, 5=TIMEOUT) class PAPI_UseIPv4S s(9LD = (|@HOST(9 @Unless(support.IPV6%_ENABLED, 'IPv6 support required') class TestAPI_Use)Sockets(Base): family = s#.AF_INET6addr = (g*.HOSTv6, 0) @unittest.skipUnless(HAS_UNIX_SOCKETS, 'Unix]s )mapfileur'http://www.python.net/uni/h.TXT' _EUCKRQoeuc_kr#cEUC-KR/# A4D4 HANGUL FILLER indicates the begin of 8-s make-up sequence.Gpass_enc0 = [(b'\xa4\xd4', '\u3164')]-/de-b_JOHABbQjohab' mapf\ileurl = 'http://www.pythontest.net/unicode/JOHAB.TXT' # KS X 1001 standard assigned 0x5c as WON SIGN. 4But the early 90s isonly era that used johab widely,t most software implements itoREVERSE SOLIDUSvSo, we ignoreoBhere'pass_enc = [(b'\\', '\u20a9')]'/de' if __name__ == "__main__":C@unitf.() import ` from !0sup" *cTxtlibdsocketurllib.reques$os email.messagestime l=ires('network') class URLTimeoutTest(.RCase)# XXX thest doesn't seem toanythingQful. #TIMEOUT = 30.0def setUp(selfdW.setdefault1out(.K)EtearDown HINone@stURLreadCTwith Ctransient_internet("a0exaW.com"Jf = .urlopen("B1/")2>!f.@Ns1"""!0 usAhese s not exhaustive. Assum<!at) OQfiles! a0goob overall of some|abasic Tface features. TLGs exercioptional 'data' and 'proxies' arguUB. NsLAfor parent redirecL have been wrnFalways construct anO!tor Q sincre a fewVMajhuObaddres=makri&pensive enoughwarrant minimiz7unneeded3cons2"""kZ'(@. qmanagerbn, *args, **kw Cresource =2s[0 ;N7r 42try byield ofinall-r.close(y_ 1# S @ expdrwith self.urlop en(self.url) as open_url: for attr in ("read", Hline s `fileno yclose",MXa "inf*geturl")y,assertTrue(has(,), "object rKned from "}^p "urlM lacks the %sUibute" % )I A9.(calling '' failed") Gdef test_Es# Test both %E and !s.JQwith M 0XIsInstanceV_bytest did no a string"F sOlistsD 1~''i,De_obj =_.( )=, email.message.M 2by 1 is/an'&? ofdEqual(.get_content_subtype]"htmlMake sure same URL ed 2by D,Bgott [<, ~getcode+!) QfancyVPer to# 404 error .s%={ + "XXXinvalidXXX(^support.transiinternet(URL*2HPWarns(Deprecation;ing7;8 = urllib.request.F0URL"Per(). }A>try4  ofinall?j 68Z,w bad_addresproper excep-aised when connectLto a bogu## c.Z# Given thaB VeriSign and various ISPs have in &# the past or are presently hijacking various invalid>domain name request' an attempt to boost traffic> toir own sites, findt(a \gto use;for this test is di] ult. RFC2606 leads one to<believe that '. ' should work, but experiencz`seemedcate otherwise. Single characterxATLDsd`likelyC!re@0, s0is es- bchoice. TheW il20'.'wvents axrelated problem:7 normal DNS resolver appends;as fromsearch path ifHre i<0no Cend and,.o53ose:bimplem '*' rule a!ulreturned.However, n_tis will1;"faCC ISPTs all8!. Treal solution wNb}p be abl >parameteriz0e f with a mockcbogus_= "sadflkjsasf.i.E.d."kEtry: socket.gethostby(V)/except OSErrorG$# I0aietoo narrow, since getaddrinfo() may als # EAI_SYSTEM/ETIMEDOUT (seen on Ubuntu 13.04),Ii.e. Python's TimeoutA*6pastLelseT_hGth some overzeal> providers such as OpenDNSself.skipTest("%rn4not !toO" % .ure_explanap= ('open %anURL did iDaise9; ' @'cancaused by a broken90ser7Gb(e.g. Ps 404n`s page)'r0passertR#s(o, msg=)surllib.@.url("http://{}/".ft) class urlretr+0Net`s(unitv.CCasez0"""9 {H0 usnSQ.""" @context; SmanagC8def(!, *args, **kw urce = args[0]  with support.transient_internet(resource): 1-file_location, info = urllib.request.urlretrieve(*args, **kw )N:try_eoyield i ;ofinall?yunlink(H!) Ddef test_basic(selfq# Test P funcaality.>>9elfI.logo) as {,gG1 assertTrue(os.path.existsA@), " ~ returned by"W " is not a valid q"Jopena, 'rb'f pf.read( ing from the I" by|failed"specified_Make sure that /ya&ofto write Oorks ,  aTESTFN_ xg;\Equal3V w Yemporary!oheader " `as 2nd"ueOgood IsInstance(, email.message.M) @3n iX? ofU = "http://www.python k.net/"Rdata_K m!FI%Nsdatevalue =&.get('Date'0format = '%a, %d %b %Y %H:%M:%S GMT'ktime.strp (X , c {except V_ErrorBfailvbin %r W9' %e reAhookU0records = []9Ging_>blocks, block_size, total_size):  records.append((blocks, 1,=%) >with self.urlretrieve(logo, reporthook=fFing_e) as (Ofile_location, {headersexpectedw = int(.['Content-Length']s0r =#r() # For use in error messages.assertGreater(lenF, 1, msg="There should always be two "N "calls; the first one beforetransfer starts.")OTEqual[0][0], 0+ -1-,X . _` can't0>c%s" % Qoz I2], 7O-1][8.Vs = {j for __}C X{#,}Ds7 5sma%s mus;e9 @ 90]* Onumber of2s *  NB" >=F9?in  if __name__ == "__main__"unittest.() # Test module type imy .weakref from G1sup*1gc_collectpquires_R>ing>.script_helper L_python_ok Qsys MaType =(sys) class FullLo@amethodQdef mCRw(cls, mreturn "<& '{}' (crafted)>".format(m.n}HBare}Tpass Tests(^.4CasY]_uninitialized@# An" has no __dict__ P# and$oc__ is Nonepcfoo = 0ypeVew__(OTrue(foo.}Z.Raises(SystemE&, dir, foo12try|dOdfail("% =,Vpr(s)[except Attributem pass  self.assertEqual(foo.__doc__, ModuleType0) 7def test_uninitialized_missing_getattr(^!):26# Issue 8297I the text in AttributeError of an n! mIZfoo =fnew__()-RaisesRegex(  2, "u has no  'not_here'",F, foo, "+"N@F %o("foo"7_'foo'D nonstring[Regularly $,2doc< !@name;.KONoneg#Ist`loaderY,apackag-1spe* 0ictB{"__1": 3, "0": L24"__<ME2"__:}J_ascii/ oASCII ,?doc+A51.a^d) i 0unicode U#o\u1234|)d4o.ne,  "__spec__": None}) %def test_reinit(self):1# Rialization should not replace the __dict__; foo = ModuleType("foo", doc\u1234")0.bar = 42d = foo.^0.__+__ZT.assertEqual(Lbname__.4doc-?doc0 vbar, 42.,nb {"__!":*1!__, "bar": 42B "__loader,zpackage ' CTrue7\ is d>dont_clearGSee issue 7140.'f(r;S$/M`return5gc_collect(D%()g[_C], 4@requires_typeO1ingeE_in_ref_cycledestroye![]Cm0(m.7 >s = """class A&7, lla.l = lF.\del__*.append(1) a = A(A)"""Dexec(s, mPUdel m*fS, [1]t|weakrefM wh:.>m5Is(wr(), Bu m_getattraimportT.good(u as ggaEOfrom&?+Bp, "TherG gga.x, 1.S#7y, HwithS RaisesRegex(AttributeErrorO "Deprecated, use whatever instead">?olo"FBsys.0s['D +']\+ _es )bab ,ttr2  self.assertEqual(bga.x, 1) #ad_getattr2,HwithTRaises(TypeError):W^mEnope@ Idel sys.modules['test.b0%']u=if X2' inB _A2'] a@def |_P_dir(R aimport&E.goo]q as ggaG.7 Lgga), ['a', 'b6c']f _es RbAfrom ,26bga@!2I*2ek|_trickyf 3f# these lookups should not crash)OAttributPO3.onM3del3,3repr_minimaly # rs when  s have no __file__, __nam or __loader__Qm = M%j('foo'$m.D5 r(m), "< '?'>")._  {}A_and,&f = '/tmp/foo.py'( F D}M_onlF m? .9*/?' def test_module_repr_with_loader_as_None(self): m = ModuleType('foo')assert m._GP_ is I$Q.)`Equal({(m), "") 5def test_Dbareibut_no_nam1del:!__r# Yes, a class not an instance.( q= BareLB"Q0 = (&< A7 %?' ({})>".format(i)<Ofull<#Z'_. () will fail because the $0 ha6Ie. This exceptionJget suppressed andp0eadXJ!'sM<wbe used ;OFull&f17: kRcrafted)1and_file 7# Bo0(),v K LS8!.___ = '/tmp/foo.py'[PNJfromDWLW Even though6[4an VD w ` . m.__loader__ = FullL# m.__file '/tmp/foo.py'#'self.assertEqual(repr(m), "") ?def test_m(_:_builtin(X!):(g9sysiasys' (C?-inj lsourcei@r = P(unit)tarts_with =*' from '"26end0__init__?>$v[:len(snG)], ,` '{!r} does not5 '.format(rP)  [-U):], ?endL) @requires_type_collecting 4finalization_at_shutdow@1# Me globals and )ins should still be available during Wrrc, out, er2_python_ok("-c", "F import ?_a"sFalse(errplines =la.split(! ?Aset(%E), {b"x = a"b.4b<len = lenVIil.rmtreek #"} descriptor_errors_propagatpclass D10Mq__get__g, o, tU%raise RuntimeEo8]"M(>KType@@meloR_(s(`, getattr, M("mymod"N #P1zennamespace .Qs areDbed in elib. if __7= '__main__'&.() # Copyright (C) 2001,2002 P` SoftwpQFoundr # csv package S2s T copy 4sys * !#io0 Sto"IO@temp TeEtaryFileK4csv $gc dpickleF$stB0supitertoolsapermuts#textwrap"bdedent%onAOrderedDict ;T5CsvP.4CasI""" 0 thFPderlywC_@rserways that apQriatePFhigh level interface. Further tests o#f this nature are done in TestDialectRegistry.1"""def _test_arg_valid(self, ctor, arg):*R.assertRaises(TypeErr+1)+o, None1arg, bad_attr = 0>delimite?0O'XX' Gcsv.Lo, 'foo7 R7=6#@1 }quotechar== lineterminator$ E ?ing# XQUOTE_ALL, 3'o)Bkreader  9j, []) S wrES 9, StringIO()[qdefaultsW*argsQobj =(# Check LsEqual(obj.d#.&O, ',5Qouble_, Tru8Qescap$ 7 , "\r\n"=O, '"5Ping, MINIMALvskipinitialspace, Fals(mstrict4# Try deleting or chang ibutes (they_-onlyAAttr:0delM', &5, '(CM?setM O, ':RteError, delattr, obj.dialect, 'quoting') self.assertRaises(AttributeError, setK@Ge, None) ,def test_reader_S s(~!):!B!._'sdefault(Bcsv.9L, []SOwritS"9, StringIO()[#kw@, ctW*args# Now try with alternate options kw: = dict(delim=':', double e=False, escapechar='\\',I.lineterminato+Ar', I;*:%@ing=aQUOTE_NONE, skipinitialspace=Trueastrict#YQobj =0(/B, **$T}gEqual(.O, ':5D!, Enj , k7 zo, "\r";{O, '*5Zing, s  , =3  -  PQ 9-derivedcclass &A='-':  :='^9 y:='$(]>='# 9ALLv & " 3+ ( ,^  &O, '-(X(^o O, "$!#o ALL) self."assertEqual(obj.dialect.skipinitialspace, True) _self.=trict, False) 5def test_reader_ip_attrs(O!):)a!._/ (Bcsv.AL, [][Owrit[*A, StringIO()) _, fields, expe**kwargs with TemporaryFile("w+", newline='') as fileobjq@r =  ()%, m73.-2ow($Cz.seek(0{-w9(),mM  2 + OterminatorTXerrorZ6exc_W^Raises(exc @7 ''C'l_arg_validlWE{\, Non0`A((),vQ![Av], '""'R'x8squotingQUOTE_NONEL# Check that exceptions are pd up the chainclass BadListB|__len__2return 10;Q:sgetitem>7, is&if i > 2zrH1 OSb7',EJIteml3str#@[Bado/()A_big ]# This exercHbuffer realloc funcUalityAbigs = 'X' * 50000 :2, %s,%s' % \<G (2%, &Vb& 'a',1,'p,q'a,1,"p,q6 F# \UOTE_NONE)  self._write_test(['a',1,'p,q'], 'a,1,"p,q"', 3 quoting = csv.QUOTE_MINIMAL)6k?"a"m%NONNUMERICp?"1"#/AL `\nb',1C"a\nb","1DeA@def pescape(S!):!/\char='\\'QRerror2E&, =_"q"']2' kNone, doubleOe=False~ m\\"q\\"n z z? = |O '""g*!o/\\n 1ONONE_p\\,q yI jiterabll)B 1, @)A = ]<7+'V/""-e>>=<- ?$, E_',') nLrowsclass BrokenFiles7W, buf"raise OSx8r (h+()passertRK#s(L", 8.`ows, [#]]iith Temporary("w+", newline='') as fileobjZ )fz ATyper.writerows, None) rwriter.ows([['a', 'b'], ['c Jd']]7fileobj.seek(0self.assertEqual(-read(), "a,b\r\nc,d1") def test__with_none(U!):( TemporaryFile("w+", newline='') as {9=c = csv #G?, '? ?ithb/'a ;0'""a'j1, [9'@support.cpython_only legacy_stringsi0t _>BcapiPJ6c =.unicode_NF('a'Yfcc<TZ_~"> , input, expect, **kwargse2#er( (6.jresult = list(.W /?A_oddn M[ '[b$pRaises( qError, a, p['"ab"ca6 , c1# cannot handle null bytes for the momenti2Oab\0 m(bc']], doublequote = 0@1)b'")  1eol "a,['a','b']])  self._read_test(['a,b\n'], [['a','b']]) -? 0r2b assertRaises(csv.Error,", Arc,dQ HnH4(r\J=@def bl@eof(K!):^ "/ ' %"a- ^(], escapechar='^'@], strict=TrueP'O2ei "['  C :S\\b,cw`a', 'b;c']v,\\/9\IFb"b\\,c]H?,\\H3Lc\\"" y"b,c"\\k ,cquoting1,",3,",5l10,3,5 <":3 D, JNoneE }3@ing=QUOTE_NONE'# will this fail where locale uses comma for decimals?z5",7.3, 9', 3, '5', /]]@ {NUMERIC "a\nb", 7u| _Valuer['abc,3n ddef test_read_bigfield(self): '# This exercises the buffer realloc functionality and KW sizeIulimits.q = csv.1_1_%()'6try& = 50000&bigstring = 'X' *#@line!%s,%s' % (8%, 7._read_test([bigH@], [ w?*]]A 'h.AassertEqual(y!), |**-1)d RaeqError, * , + ,ICTypeIo, None E1Hkfinallg(!) w@def %ge=6 it6r< "nonesuch"~ "un5$er= =C"  AG0o, 0, 0a M oument=squotingo/[  *myexceltsv( Jlimiter = "\t":@nameDexpected>s =$`() + [G]U 9f.sort( g(D&, /ddCleanup7B 6fvlqC).def, '\t'@%go!ed| %&()3s (, W!) 4 _er_kw = 'fedcba'<O7=';RPu[['X', 'Y`Z']], [dreader(['X;Y;Z'], ,))3incomplete%Z'08tBspacect(self):   class space(csv.excel): delimiter = " "quoting = >QUOTE_NONE%escapechaBE\\" with TemporaryFile("w+") as fileobj.write("abc def\nc1c1 benzene\n")f9jseek(0Aread (0, dialect=%):self.assertEqual(next(C@), [", "def"];@Ddef compare_P_123(, expected, *(args, **kw/):, newline='', encoding="utf-8geO ODrow([1,2,3C.  -&()%) REtestOQapplyQ0(A0&\t1=B=:<C<|<?Uni>g\u039Bregister# (' AC', :try"-\r2a\t2\t34zAz;4:2:96=/B(<|2|C<;2;C)A,O=';'u2p3Uni0kfinall*/un,>n5badOl# Unknown parameter+Raises(TypeError,er, [], d0att# Bad valuesX#v = NoneD/-1C.<100c2cop): for name in csv.list_dialects(): ! =+%ge*(C),self.assertRaises(TypeError, copy.#, T!) >def test_pickle(FfEYPprotobrange(.HIGHEST_PROTOCOL + 1KUdumps!, q ) class TestCsvBase(unit.3aserqreaderAZQEqual% , input, expected_result9 with TemporaryFile("w+", newline='') as fileobjq.write(l !jseek(07 (01 = Dfields = (B c<o3hI^v   4Orows*.W/()2DaExcel(gP = 'e#'n^_sing~ 'abc', [[ ,]]#OsimpM1,2,3,4,5S1','2','3','4','5'aPblankb[ bempty_I,Jo['', 'FoquotedR#""SOa_left_Z __righ_,,__ ["eRsSUV inPBa""b Ual('a"b"c', "[['a"b"c']]) def test_quotes_and_more(self):$(.# Excel would never write a field containing '"a"b', but whenF@read# one, it will return 'ab'.,./erAssertEqual(\bBlone QP"Q VO "b"!8* ,  _space*0 "a1[[' X"d#O1,2,3,"I think, therefore I am",5,6',[['1', '230? 'q<5g6xz""I see,"" said! blind man","as he picked up his hammer and saw"( p? 'H,nlFinput = '''\ : : : 9,8,7,6'''k@4 'k.\nln*\n/'] ['9','8','7','dubious2,12,1",'1T' =nuly l[], ''rsingle_/ PJ@['ab!,_c\r\nX/mpXB1, 2U', 3, 4]abc,3,4lXse0"bcW3, 4]], '1,2,"a&""bc""",3,4\r\n') def test_quote_fieldsep(self):#'.writerAssertEqual([['abc,def']], '""cnewlines]1, 2, 'a\nbc', 3, 4gQ1,2," class EscapedExcel(csv.e `ing = QUOTE_NONEe:char = '\\' SITestWsCsvBaseYdialect = fcg-Pabc\\vg_read_i) Z), )D_Unix( k'unix'mrsimple_Q'#bcv01",z "tt/'"[1v 5']]$QPd6sNUMERICc / <* (li) hz QDictFP(unit.C ### "long" means the row is qer thannumber of *QnamesEWshortFre are fewer elements iKbX Jc_Ldict with TemporaryFile("w+", i='') as fileobj^&W(-, = ["f1", "f2A3"])JN"zheader(!Wz.seek(0]aW-2 (){p1,f2,f3"A~Prow({@: 107@3": 2*"}5e2 #  @10,,Or\n"nPmultiM_row  = StringIO] obj, fieldnames=["f1", "f2c3"]) qwriter.vheader(self.assertEqual(fileobj.getvalue()W1,f2,f3\r\n"=SZprows([{0: 142": "abcu: "f"},=2=5 3FWxyz"}i'"fp1,abc,fp2,5,xyz 1") @def test__no_fields(!):$6 = StringIOd Raises(TypeError, csv.DictW#, J}r_not_inMnamewith TemporaryFile("w+", newline='') asm;r =1eldx? = z N# Of special note is the non-s- key (issue 19449bBpDVE*cx:Trow({"f4": 10Yspam", 1}zexception = str(cx. *AIn(""?", 3O'f4'-0Notc?'f20-@typoOextrasac!_r _e,, ['f1', ]$ !="d ,_  6dictrow = {'f0': 0!1'70: 2a3': 3}c  Y", #, vX+oignore,Wp-/ V(Z^?1,2Pread_b P("1,2| fileobj.seek(0) reader = csv.DictR@(fil4,-8 fieldnames=["f1", "f2:3"]pself.assertEqual(next(@), {?R: '1'DA: '2 3": 'abc'}) def test_<_dict_no_(j!):, with TemporaryFile("w+") as -1 .write("f1,f2,f3\r\n1,2,abc "5k I(- P76er.1/, @Q# Twon$ cases to make sure existing ways of implicitly setFm continueK work. Both arise from discussion in issue3436.M^_@_q@/))P /@ D|I-\chainit itertoolsfirst = ;qfor row.[=3], s = *H/ow'Llong-o,4,5,6;81  None: ["abcr456"]}) def test_read_long_with_rest(self):  TemporaryFile("w+") as fileobj-4 .write("1,2,abc,4,5,6\r\n")\/jseek(0er = csv.DictReader(c,IM fieldnames=["f1", "f2"], Qkey=" .assertEqual(next(@), {JR: '1'O_: '2'xp: ["abc45a6"]}) /deF_no_=Pf1,f2I.(,  @OshoriO @.tQ"1 2 3 4 5 6".split()*val="DEFAULT$1"2 23 ?abc494C5 5 6 ?6'}v?!Br "=\multijsample = [q'2147483648,43.0e12,170def '0/ ^I,170\ ]NDW}="i1 float i2 s1 s2i- "b=  "i2": '17', 0"s15?abc6kqdef'}) ndef test_read_with_blanks(self):% er = csv.DictReader(["1,2,abc,4,5,6\r\n","=A=]fieldnames="1 2 3 4 5 6".split())y.assertEqual(next(Q), {"GQ1', "2 3[!454?5 5 6 6lu! semi_sep;2;abc;4;5;0delimiter=';' class TestArrayWrites(uniti.CCase\Pint_w, import aMMcontents = [(20-i) for i in range(20)]/2a =A.Gd('i', D W0 TeraryFile("w+", newline='') as fileobj=##r(), dialect="excel":.4Jow(a expected = ",".join([str(Ba])+x[z.seek(0X -!D(), y"odouble*O*0.1dOfloa`+f with TemporaryFile("w+", newline='') as fileobj: writer = csv. (), dialect="excel"):4Jow(a expected = ",".join([str(i) for i in a])+"\r\n"[z.seek(0Xself.assertEqual.read(), y!) Tdef test_char_(D)import array, string<(2a =. D('u'$.ascii_lettersp4pwith TeWaJclass TestDJValidity(unit.CCase|quotingR#my(\BSdelim*";``escapeu = '\\':Poublee = False skipinitialspac%:Tru$xterminato_' hb3ing|QUOTE_NONEm< #d.L,KI,f = NonVaRaises]uError, >Rd2 9w5ALL *"5+?ALLCv_, '"'+7(d.J&''|h&cm(Y0cm.uption),XD %'"" must be a 1- ac'4f, not intk*m lineterminator = '\r\n'  quoting = csv.QUOTE_NONE%d = mydialect()self.assertEqual(d.delimiter, ";") ,@# = ":::"$Wwith UpRaises(Error) as cm:1Y str(cm.exception),DH%'"" must be a 1-character string'?b",, not bytes44intdef test_linetermi(W):WclassdD& ;`escapeZ\X`double^e = FalseY>skipinitialspac%:Tru$ fJ p,/ + 5 J,t B invalid_Gsscreate_((field_name, valueJpassuetattr(X., r 2 7for<W in (\6, "@A", "*"wsubTest= 6 self.asse&rtRaises(csv.Error, create_invalid, field_name, "") self.asseM?abcP9Ob'x'85) class TestSniffer(unittest.aCase):Hsample1 = """\ Harry's, Arlington Heights, IL, 2/1/03, Kimi Hayes Shark City, Glendale 512/28/02, Prezence Tommy's Place, Blue Islandh3.Sunday/White Crow Stonecutters Seafood and Chop House, LemontR!19Week Back """2']'s':'':'IL':' 6':' E' 'S K':'G;4':'2' '1':': #''+''2':'\!5':'"'#`header( '''\ "venue","city","statdperformers" '''eA3 = B005/ 3??5/0  -Z6$42147483648;43.0e12;17;abc;def   8E;1706 l5aaa\tbbb\r\nAAA\t 2BBB 6/@|b|c#Pd|e|f #7#'a'|'b'|'c' 6'd'+2 # Issue 18155: Use a delimiter that is a special char to regex: +'J'+'+'!+"'/+"'8+S+ IL+++5++ 3y+Rp%+ on90'+ $+ /+ `'+' ILD  +=!$+ 12/19/02'+ 'Week Back' """ def test_has_header(self):#sniffer = csv.S&() elf.assertEqual(1.S.sample1), FalseB @1 + Q _True)_regex_special_delimitN8.2?8),guess_quote_and'Bfor  in (";'123;4';", " "eCwithrubTest(Z '+dialect = m1f, ",;"`25G._, ';'9B@charr 5Is(oQouble< :skipinitialspace? C< TGkh ?L'",G}D''"}1 2h/":/"'1gs 3  # given that all three linesp3 are ev# I think=0ny acter could have been 'ed' as the%# , depending on dictionary order3&Inb,Q{Os="?'"?p/p/psniffer.sniff(self.sample4) assertEqual(dialect.delimiter, ";"1 = sniffer._5._/\t`6`|_7_(quotechaO'86'+'19.  _1 pdef test_double$8!): Mer = csv.Sc( vheader1.VFalse.\2.\8\?Tru)[C-\@ class NULwrite(s, *argsApass"lines = p @unitQ.skipUnless(hasattr(sys, "gettotalrefcount"),Ok 'requires sys.7C()')TestLeaks(~CCase_create_readdelta = 0`lastrcW(for i in range(20v`gc.col6gc.garbage, []-(er(["a,b,c\r\n"N&9:2rc-3U = rcA# ifN0) l , - Pshould be 3 or more@ 93P< 3, !) + 77NUL c.collect()  self.assertEqual(gc.garbage, []) , rc = sys.gettotalrefcount((csv.writer(s/delta = rc-lastrcW# if ) leaks, - Pshould be 3 or more@ 3< 3, True) +def test_read(5!):435= 0rows = ["a,b,c\r\n"]*5afor i in range(20uygc.collec>Qrdr =l0er( 1row&dr"Epass; during ,55x[1,2,3] 7NUL:  >ows73 owD C$X  "class TestUnicode(unit.bCase):1@name["Martin von Löwis", "c André Lemburg$Guido van Rossum!François Pinard"]u2with TemporaryFile("w+", newline='', encoding="utf-8") as fileobj(",".joinD.Q) + " 9jseek(0*er0 ) Rlist(?A), [ ?]) %;s&<d (N1rowH Jexpected = ",".join(self.names)+"\r\n" fileobj.seek(0);assertEqual(-#read(), expected) class KeyOrderingTest(unittest.qCase): c@def #_o/_for_the_dict_aer_and_writer!):<resultset = set(for keys in permutations("abcde"EI+with TemporaryFile('w+', newline='', encoding="utf-8") as 6ectRdw = csv.DictW0,21dw.gheaderC#'drzRI7tkBtuple(dr.field-kV fN, ktUX.add("# Final sanity check: were all unique? Elen(k), 120, "Key V`: someo [not coll$ (B?)")(ed data = dedent('''\;FirstName,La Eric,IdleGraham,Chapman,Over12YiUnder1;John,CleesS''').split#s(BYDist(E9)),h[ edE([('@', 'd'), (';')]I I  K'L(None, ['@ ?2']e ]I G']!, restkey='OtherInfo'@del G5[0] # Remove the E rowj", ames=['fname', 'lname'])), [OrderedDict([('f', 'Eric'), (:, 'Idle')]B BkGrahamDChapman'E (None, ['Over1 ?2']}0Und; VB0Joh_Clees]) class MiscTestCase(unittest.!):}@def __all__(selfextra = {'__doc____version__'}F+support.checkOP, csv1csv?1), \=Pif ____ == '__maic () from xmlrpc.server im DocXMLRPCS http.client4sys threadingYP* <make_request_and_skipIf(condition, reasonU# If we 'A the},have to R3 a T becauseg#2created in setUp blocks expecting onQcome in.Cuif not ]return lambda func:7decorator(:  N-a.("GET", "/")n(,getresponse(&draise P.Skip(xR%! u(, =j(("localhost", 0), logRs=False) k6tryzp# Add sdocumenta;*prv.set_xer_title(" BP;DjCs: ("This is an XML-RPC yYer's 8X, but"Ican be used by POSTto /RPC2. Try add, too."\1# C and register edesxEC@s(objectUq_method[, arg(,1"""+1s. $ truly does very little.""N@rg =oG4rv.q_intros0on_30pstance()Hadd(x, y0"""btwo inEs togetherfollows PEP008, but has nothing %to do with RFC1952. Case should matter: pEp008 and r( TOsPhat startUAhttp64ftpTbe auto-linked, too:E5://google.com.9"""return x + y def annotation(x: int)i""" Use func&1?s. hdpclass CUWithAo gwmethod_self, x: bytes.decode()yserv.register_U(add)$lambda x, y: x-y1+instance( &()6fexcept,.per_clos rraise rDocXMLRPCHTTPGETServer(unittest.TestU`setUp(tU# Enable u feedback!ib._send_trace(_header = True!lf = make_`( .thread = Qing.T(target=&<Me_foreverG.v%{PORT = Er_address[1]$client = ..bQConne!("localhost:%d" % egtearDownja.~_# Dis3UFalseYv@@hutd<Ljoin8ZZst_valid_get_response request("GET", "/"@}4getassertEqual(%tus, 200]/2get("Content-type"), "text/html""#  Rs an ion if we don'1to the data?HX/inZ,Ospam^H?404^2Xplain_  c0""" tz#tionality stays the same. The output produced currently is, I suspect invalid because ofRunencoded brackets inQHTML, "". subtraction # method is tested.15""" self.client.request("GET", "/")(response = 34get&()#assertIn((b'
'sK*b'3#(x, y)'),Hs.read()c@make__and_skipIf(sys.flags.optimize >= 2^"Docstrings are omitted with -O2 and above[1def_autolinking(>%):"""Test thae server correcd=matically wraps references toLAPEPSBRFCsv!s,b0it 0ifi;ext starting0Khttp or ftptocol prefixesdocumenta0ford "add"rcontainb materialO ?add,ddb'Add two Pinstatogether.BThis 0b'follow\ntd Arfc-editorrfc/rfc1952.txt0RFCBCaseaSshoul[rmatter:bpEp008 #an3r[W.Ts#ha $! O%c2ftpb K-#edBtoo: Mgoogle.com56://$?
'OS b'(D_Y0)\n# cReturn(aQ+bstring ucontaindocumenta1#2for O2thespecifiedK0./Gk/dl>\n P Signature  S}Y-">R )h[double, S3intBint]+ Blist OudescribP9"of (.Q'Ij2theCabovUexampQ#ad SkYCtakea1argsPnprg rresult.6S3Thi}Sserve $do2NOT@csuppor% S6 #D'),  def test_autolink_dotted_B s(3%):r"""Testdot values are made  Smatically in .Eb#ry[s5add60too,0Rn Y2nnoM Na) works as expected "F2doc = (b'' if sys.flags.optimize >= 2 else  b'
Use function`annotas.
')Oself.assertIn(m(^l>
#'N b'(x: int)
' + docstring + b'
\n7, , Rbytes9'), response.read()) if ____ == '__main__'::unittest.0() """Test suite for the cProfile module.""" import sys from tG1supDrun_c, TESTFN, unlink # rip off allpPeresteestuff W"_pty' ~ , regenerate_expected_outputF.script_helperO|_python_failure, ok class C( ){r-=e.+%y &3max = "{built-in S ins.max}" <|def get (g[return _O2B# Issue 3895.Tbad_counter_du8_dealloc`0_lsFw# Must use a {Aas SIO doesn't trigge2bug?orig_stderr =. `2try.with open(q'w') as~ ,03sysT! =#[ ccobj = r(lambdax M8.enable(Y1.O.disP o.clearpkfinallE >)dQ21862?d_path_op9 \ #  -m switch 8s`'Gthat,needs an argument~0 ('-m', ' 3-m'7g0\not-existent\f", 'random_mO_xyz{successful runj/ok, 'timeitn', '1') d ef test_main(): run_unit(CProfileTest) def ,if '-r' not in sys.argvIME^]Felseregenerate_expected_output(__wK__, + # Don't remove this comment. Everything below it is auto-ld. #--cut-6# _(O[ = {}['print_stats'] = """\P 28.50.0 /01pe.py:110(__getattr__)K 92270B A1.00 K025(CfuncGB23/3>!155S0.007YH057 G35(factorialH4 2? )01HV48(muB" 2x$040K6Y0.300B55(helper" 4E2116 2029 1N*03E#73E1FyS50.17F#84F2_indirectO$31X34a5O8O F#06#00X$0821Fc98(sub#?"""gcaller N"<-w P  Nj  :1()e ` e#01tI130 D%20` i7i j&"!HDx P i j B9P ji]P ~[pg/&~g8(helper2)  #<-6R0.234 300 profilee.py:55(helper) "$28R0.078 1g#84g2_indirect) c98(subEh#06+08$88q) {built-in method ins.hasattr}mh_z 0.004@#73h1A*h8h sys.exc_info 8{/ 'append' of 'list' objectsmh"b""" _P$Output['print_callees'] = """\ :1()#->1P0.270 01.0k25(testfunc110(__get+/__q)->Nq #01q+1335(factorialj*4<0.6 2 @20/3#!0.9:147 P|(20 j48(mul 44 11lR  k <}U  U`DA} |sL0'5 j388(helper2)  #->8S0.064 80 profilee.py:98(subhelper) >j 1690.0 P110(__getattr__) {built-in method pins.has%}Sm2m m """ if __name__ == "__main__": P () # line 1 def wrap(foo=None)(per(funcCpreturn SFDper \7\xreplaceD[pinsteadD([print('hello')^1b@13 @v#() )w 4ped\Fpass739 @,Ogone)24 oll = lambda m: mFH27 tg: g and \ - 32-iKCd: d.Sd*60one  !39# manyargs(arg1, arg2, arg3 :4):6!4365twoYCm): m47 a = [,Cx: x]!52c1set globals()["anonymous"] =E1gx, y: x*y)ZMwith_comment(): # +FworlH61 multi@_sig'e\s"+yBNone !68$69/class cls707J'$71' v9 extra74 = 747H7<(,8, stuff78) = 'xy'E9Ustop'I581 "82+83Z#84Z*84Z/85Z$88## ]%909$f0XgQ"doc"RZ!42"X e_in_dynamic_a= f().g #2 10keyworded(*F#=1s25annotatedwo: list/a_only_arg(* 2 : |Y4114 C115 C~QWithM[D@S(selfj3Afromwtools import!s decoratosrg5fak9a %wE29 @`nKreal20 #line 134 class cls135: def func136() 7never_reached1E ,2 # Test case for DynamicClassAttribute # more tests are in _descr import abc 4sys @unit: from types 1n c~ PropertyBase(Exception[pass )HGet(5+S+?DelV 2s(objecty__init__(self._spam = 5 @/K- G5"""}.getter"""N7vreturn miK!.s/, _, valueH~deleterIB9del2Sub7"):Z5 = .__dict__['"']'@  4"""m/ 'EaisepG2)j3rSoS> M MM0Doc7 j A_get S4Ji/ =(Lq, doc="-,")eDocSubV/8=The decorator does not use thisy stringB oqSubNewGL(y /0new5l l#original d 8\WithAbstractVirtualQ(meta=abc.ABCMeta@.aTemethodOXcolora{  vtmethod @DynamicClassAttribute def color():ppass c. PropertyTests(unittest.CCase6G#_p/_decorator_baseLS(self1g# see #1620{-q = Base%()>.assertEqual(,.spam, 5' _(>F = 1f /10g)qdelattr0, ""GTrue(not has23&")4n 2)Odef ?subsub = SubtRaises(Get, get8_, subj =S=s=f, NoneF/ CSDel,  @9skipIf(sys.flags.optimize >= 2,. "Docstrings are omd with -O2 and above[L_doc{}asub.____.__dict__[' ']toc__, ".getter") y  0DocY5L 8Sub>elfT x&+NX*w0_override92new&BqqSubNewGw ? /am'].__doc__, "new docstring")  newgetter = PropertyNewG((self.assertEqual(9.spam, 8,__class__.__dict__['@ ']Ooc__def test_p___isabstractmethod__descriptor(!):<for val in (True, False, [], [1], '', '1'48 C(object!colPqreturn _* @o__initw< = 'cyan'EZ J .e%"()',wW2W self._color = 'magenta' with self.assertRaises(AttributeError):07Okay2.colorCaEqual(%"()',z) # Issue 5890: subcl~s of DynamicC do not preserve method __doc__ strings H PropertySub(O"""This is aN""" a_Slotsf8 that defines __s` __}{_ = ()Tests(unittest.qCase): @skipIf(hasattr(93, 'b1'),;"<blready6nt, will have no effect")I@def 2doc_copy_exception(Xx:try Foo(object,0@Lspamn -rying to t<r?E an Dreturn 1print('\n',.j7B[  EpassYJelseEe"Lk$?d")3sys.flags.optimize >= 2&$"Ds are om!d ~-O2 and above`   0"""| wrapped in g$ 0Foopict__[' '] Wmpp_setterRies_g__init__;_<+ =[ r @. `, valu;"""gnored"""  self._spam = value foo = Foo()/assertEqual(foo.>6, 1&O = 2;2; a@Foo.__dict__['x ']Yoc__,*" wrapped in DynamicClassAttribute subc"Sub(Foo):YXy (@)y.setter@def (,t d"""another ignored docstring"""S0Ne'eggs'$bfoosub6 ?subE = 7[A oHmFooSubW1l@unittest.skipIf(sys.flags.optimize >= 2N$"Ds are omNd with -O2 and aboveRo_property_new_g 1): m{(object%#@PR5Sub48sa 5 ZL return 1W p?newt0 J "a dvIOBaseMo2_ g  if __name__ == '__main__'kJ() """Test date/time type. See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCasesW` from .support ims_resource_enabled tertoolsebisect Dcopytdecimal%sy5o dpickle#drandomdstruct Tarray kDatorlt, le, gt, ge, eq, ne, truediv, floor mod from test import sup# datetime as r_module=AMINYEAR, MAX &S_delta_zinfo/im{U?zon,4_ _capi # Needed by)_H-"Q_strp# pickle_choices = [(%, }roto) Pfor p in range<.HIGHEST_PROTOCOL + 1)] assert len)xC) ==p<An arbitrary collection of objects Dnon- types, !ing # mixed-* comparisons. OTHERSTUFF = (10, 34.5, "abc", {}, [], ()) XXX Copied _float. IND ("inf") NAN =at("nan") #9s class TestMP(unit.qCase): 1def5_constants(self):R=U2.dEqual(4.b1E.{, 9999)name_cleanupif '_Pure'a!__Q__.__;_@skip('Only run1`Fast C&plementam'= tT@set( Y ein dir$Zpif not 1.startswith('__') and7endNallowed = #['C', ' %','+#P_CAPI4 ! It2&']ACs - ,]divide_and_round3c Python r,._ dar(-10, -3), 3)*a5, -2)T# four cases: (2 sign'Ia) xb` 7?, 2' -(-) 7-2) self.assertEqual(dar(-7, -3), 2) # ties to even - eight cases:&(2 signs of a) x bA/ odd quotient)B/seR10, 4 (-)/-2R-S*T+6({16, y)-*/ #9 # tzinfo tests class FixedOffset( "):-def __init__('1, o(, name, dstF=42);if isinstance("W, int$ = timedelta(minutes= SxVY\2.__s# =  __! = T& =%BCreprBbreturn_r.lower(;2utc~dB @(u tz7&5?dst2@PicklableI NR=NoneS d4W.N__getstate ddict__v_TZInfoQ 0atew_modulerrandom.$()aCTestd@unit.0CasE_refcnt_crash_bug_22044qdtz1 = Rtd(2014, 7, 21, 11, 32, 3, 0, tz17BwithbRaises(TypeErrorzf.non_abstractness# In orderallow subPget pw ed, the C implementation3# wasn't O;Qaway ehaving r=DNotIY!ed.puselessgWwTdt = fE.max5m Ed#, \.?, dXRaises(NotImplementedError, useless.utcoffset, dt)  self.assertRaises(NotImpF#ds@Adef test_subclass_must_override(]!):+o# NotEnough(tzinfo!%T__init__A$, Kname.2f2.__&# =/v#'E0 = #True(iss#, <Gne =3, "NotByALongShot",cIsInstance(neW dt = datetime.now(G Pne.tz"/ne.,?ne.)anormalfo = FixedO(K_ThreeB&foBfor dt inFf, None,Equal(fo`(dt), delta(minutes=3)EB"52dst2tB42))$"vpickling_basm# There's no point to 3 objects on their own (theyp# carryGdata), but.`y needV"beYable anyway elseDoncrete Zes can't =5ed.0corig =.__new__0&Is(type(9Z*en Pproto)_choices#rgreen =er.dumpsj!, A derived = uiq.loads(I -@J NP# MakiPre wef/S an iU of a:imeF-300\o}`, argsN[ (P2, (, 'cookie')),8 zo$,# "EST"))] (*o.!3rig<(. & \V 0 2]X ;self.assertE qual(orig.tzname(None), o 7) for pickler, un proto in_choices:=Hsgreen =(qr.dumps}!, E p3derived =qq.loads(M1self.assertIsInstance(G, tzinfo7 E(typ4 4 EGf.utcoffsetMBPdef test_issue23600()oDSTDIFF = DSTOFFSET = timedelta(hours=1) Qfclass UKSummerTime()V("""SimpleN zone which pretends to always besS0u, sincevRthat's what shows the failure./6"""<o G, dt %freturnG1dstJA]?'h'IJtz =1u = date(2014, 4, 26, 12, 16=tz4tz.fromutc(u$Wt - t), u) @TestZone(unit.bCase):QsetUpEn4ACD6(p9.5), ''')ES:-;9min=-?.ax?>Yconstructo XertIs(timezone.utc, timezone( delta(0))) self.assertIsNot(1?, 'UTC'F_EqualF#for subminute in [microseconds=1)%]:Ftz =Z%3Notzoffset(None) %Iq0N# invalid :s :1, +1)Raises(ValueError,| = -%) ^with }2Typ|!):}#:"&42raZERO, x"@~+'ABC', 'extra';def test_inheritance(G)t2Ins%N{, tzinfo46EST02utc rdummy =!DT61h{0, 1.5, 12Q = h * HOUR=APL/() (NH--IJT7EST&''yB#25) KACDT, Eastern]0utcH" =+DT.replace(tzinfo=tz1local = tzD (9#- .,B2utc()CxRcomparisonN#NoV0g(ZERO)VGHOUR<9)9!\-5 * >w, 'EST'`& <%!InA{G}82Tru{:A != hMFals13== 23daware_ #U that instances can be used by^bU5t =@(1, zF.minG.max;utc%+z/t) t= gj#@mOdst(g t.repla!ce(tzinfo=tz).dst()) def test_pickle(self):for tz in b.ACDT, EST, timezone.min&axCGaUr, un Pproto^_choices=Atz_copy =>r.loads(:r.dumps(tz, U%))@assertEqual(UF, tz.Ftz =5utcH nl&I'De.(;e1d Adeep2? nLh. / #9 # Base class < ing a particular aspect ofIRdelta, date and # A comparisons. \HarmlessMixedC!# Test that __eq__S __ne__ don'tUPlain mFQ-typemQ# Subvpes mustine 'the!',`@(1, ).Abe a`# legi{nstructor.fh__ Bme =i vS`False(6 = #1Tru"!"E() == me EB() !" hIn(me, [1, 20, [], me]N0In([0/]5?ful4>Raises(TypeError, lambda: me m">mRaises(TypeError, lambda: () < me)  self.assertRaises(TypeErro6=7">6#m/ #9 # timedelta tests class TestTimeD(HarmlessMixedComparison, unit8.0qCase): H2theI=b1defk_constructor(s!)::Peq = UEqual=td V6 # Check keyword args to iD eq(td(), td(weeks=0, dayAhour aminute `second DtVmilli$e micro)]y1zq130, !B$' n,St7t#-24%&-60(*** G?100[i6m6_float-O.0/7 1R.0/24( R.0/60* ,.# .E0.00   2 ` 7B-))mputations3ad(7) # One vbT0, 60!#c#)I-eq(a+b+c7V#, '#!-b!6, 24*3600 - Db.__rsub__(a/ !-aS-p+ /-1 - %`1, 999 1absa- 6td(=), 10, *;l:, bY1*107a:10*Tb.1td(n K210*: c*10, td(0, 0, 10000)) eq(10*c, td(0, 0,"Oc*10" a*-1, -aYb*-2, -b-bcIc+-cb*(60*24), (b*60) !M60*b!010 Aa//7 6b//6Qco; !a!V0, 7*24*36|Pa//36+ O10.5O*14$b/2d~k pa  # Multiplication by float"@us =microseconds=1:(3*us) * 2 ?Peq((5b0.5 * D-, >D)(-}-@!(-;!# Issue #23521feq(td(?a123456  >b611229B ?5)) ~s# Divis{int andY?/ 26s/ 2.0,  [6!|dv~>@!for i in range(-JE10):Ai*us/3)//us, round(i/3J-K-LvL/ (1 / 0..5)S U11576t9, 86399, 0) - 958),H )o7td(AN1, 1WO1, 0Ng def test_disallowed_comput{gs(selfayimedelta(42!Add/sub ints ors should be illegalz*.0,z.assertRaises(TypeError, lambda: a+iS6-i)  self.assertRaises(TypeError, lambda: i+a) .6E-a) 7## Division of int by timedelta doesn't make sense.;by zero/ !5= 0@67// 8DZero $Aa //*@?-?0.0} ca / '' @support.requires_IEEE_754J def test_disallowed_special(!):'#6a =?(42 DValupa.__mul__, NAN6utruediv:basic_attributes days, seconds, us = 1, 7, 31J)td 4Equal(td./(  . Smicro*ctotal_! O=365r R)"Y53600|Ifor ) in [123456.789012, -"0., 0, 1e6]P=g2 /:(),@ # Issue8644: Test that td.B has the same,# accuracy 7d /&1)2!ms'S-1, -  6=ms I^carri9-t1U=100, weeks=-7!hours=-24*(100-49)+0min?=-3#j2# D(3*60 - 12) *F + 1W)t2 ;'x\1, t2S`hash_e =ityYE4*(100-49),  minutes=-3, " seconds=12#Tmicro((3*60 - 12) * 10)^t2 = timedelta( self.assertEqual(hash(t1), F2)) G81 +Hvweeks=7O*t2!wdays=7*" qft1, t2C !d = {t1: 1}d[t2] = 2 Tlen(d), 1xd[t1], 2def test_pickling(V%):eargs = 12, 34, 56Iorig*,{Afor Veer, un proto in_choicess=sgreen =$r.dumps(s!, Ah/`derive7iq.loads(I - WD |compare)t16, 4i  2True(t1 <=T">"AFalsE!#" @(3, ), (2, 4 G3, 5Z &B # this is larger than t1r=C %W2 > t"% l& 2 pL sL&L{= M' 2 'NEVM<2 &1 QM=N=`badarg?OTHERSTUFFJ"= 9!, ~ |2!231 ]Kc2", c Raises(TypeError, lambda: L? >#>> self.assertRaises(TypeError, lambda: t1 >= badarg) self.asse? 9o <= t1?(>*>>+def test_str(!):td = timedeltaPeq = ++gEqual (Ltd(1)), "1 day, 0:0"3$eq)-*-+2T2TsU +-,hours=12, minutes=58, seconds=59v12:58:59BA3@4?2:03:04>weeks=-30, I33L "-210p23:12:3c#fTmilliHr:00.001000Tmicro636o0003")ddays=9&59!559,z |L)))*"6999b59:59.=repname = 'dateB.' +theclass.__%%__ (Y.51A"%s(&`1)" % `_00, c0l2o$ -1p@, 40  4=MI#U/60+l#b0S$ /10 1#wa9#1 <conds=100)" % name) def test_roundtrip(self):" for td in (timedelta(days=9, hours=23, minutes=59,CG asecond)d microV)? -,?999/$, n1:112B3)):L# Verify7-> string ->identity.s = repr(td)elf.assertTrue(s.startswith('date;.')7 = s[9:]Mtd2 = eval(s0gEqual(td, td2% ` via r`structfrom piecesD0td.Gi.  esolution_infoUIsInstancee.min, 8/ax8"r? f.max >(j(F? (, 24*3600-1, 1e6-1= p(0, 0, Coverflowgtiny =W)td#`min + :d@td -Fny # no problem!Raises(OQErrorp__sub__e/nyT;0add;- Max -+0 =lambda: -)da/(1Uday.__mulV_10**9=&e;qtruediv|Oe-20| A1A#div__, 9e-10) @support.requires_IEEE_754def _test_overflow_special(self):&Iday = timedelta(1)*.assertRaises(OMError, day.__mul__, INF;%-<xmicrosecond_rounding(td@Weq = REqual7# Single-field ].@(td(millis=0.4/1000), td(0))I<os to 0> -?+70.5}Fs=0)t-eq-;-< ?0.6v1v;-< 12v ;-<]2**6^ 6Y7Z8o1/2**7k?781-7-8~3# R-@ duecontributions from more than one us_per_hour = 3600e6_5 *2* 2zdays=.4/'2dayxBDs=.2+,V , 0@ {-- XB $# Test for a patch in Issue 886y85), 0.5*.1. 0.5)//td.resol>J "assive_normaliza (-P((td..b C%),J (-1, 24* 9)=boo7_XTrue(A&00, ) 0, 1))  self.assertTrue(timedelta(microseconds=1)) 3HFals4A0)) (def test_subclass_Y@"):(S & T{!):D@staticmethodffrom_td(td7;`return\d.days, td. 8]as_hours(asum = `y * 24 +0F / 3600.0/ 4&e6^round(sumpt1 = T(&=1:Is(type(t1), T#Equal(t1.X), 24g2gC-1, g =-Tw2w 2w8-25x3 = t1 + t2yE3),  t4.H3F4 3 A, t4 NN3 .11 6;Pstr(t 44n1mdivisionvt@9=1, minutes=24(19d < # /d, 5059.0S- .? 3Z $_, 2.5 S7, 2izerotdzRaises(ZeroDError, truediv, t, OA\floorB#NEOType~2y# note: \ \V of a by an integer *is*wcurrently permitted.`remainder y?s=2)r# %/3D-yz ual(r, timedelta(seconds=30)) zerotd = timed)%0)self.assertRaises(ZeroDivisionError, mod, t, K\>KType6#102def test_divmod(>%):tminutes=2, -21sq, r = p2t, 7!Equal(q, 2'r,Gs-"-, =S 9issue31293# The interpreter shouldn't crash in case a0 isuided or<# multiplied by a float with a bad as_lger_ratio() method.Fget_bad_@( .class BadFg(- #'Q x,0`returnuX o7J) / 1 << 100>^(*^6for[(), (42, 1, 2, 3)]WBValu 4 3g- gh"A(?752(pbecause") Hs negativek# remainder{Int(int:q__mul__{, other&^wg Prod(` YOraddZ>SumY_#* 4g(0, -1VTmicroC0BadP&1)|*mhours=# timedelta(weeks=BadInt(1)) #9 # date tests class TestDateOnly(unit.Case): #'s here won't p=if also run on^time objects, so d/F2subvqthis to71o. ,1def _delta_non_days_ignored(selfAdt =H(2000, 1, 2)ID0 = P(L=1, hours=2, minutes=3, seconds=4,AE Tmicro*5k:aysj|.p%.assertEqual,q0dt2At + GQt2, d)Bays)JGCFtC'?t -"- mA = - 32 -21 m4'S0(sub_var = 1 (HarmlessMixedComparison, bshouldfor bothYQs and Fs, except %a_Q# fewas that4Tverrides2thebasic_attribH2, 3, 1i t.year, 200!J t.month, 3N 1dayrroundtrip.adt in .mt+.today() # Verify-> string -> identity.0vrepr(dt3elfTrue(s.startswith(';.')7 = s[9:]fkeval(s0gt2` via r`structfrom piecb6 C$(dd dtordinal_conversions# Check some f values. for y, m, d, n in [(1, 1), # calendar origin @2, 31, 365),- 2m?366+ # first example from "Crical Calculations"v p1945, 12, 710347)]:4d = self.theclass())'# assertEqual(n, d.toordinal()/-or\.3n3 b!d,:ord)if hasattr(O, "hour") # if we're checking someth fancier than a date, verify# the extra fields have been zeroed out43 .:, 02 @minu4osecondh7cro90# CAand last days of year spottily aEs6WwholeFTrange2s supported.$fO1in .(MINYEAR, MAX ]+1, 7V (lS) ->   is identityw M*:n = ,d2S*d2## that movAbacky gets tos4enda*-1i:> 1) *-13 2-p33  L9| >O2, 25 }?52*B@3, 3 AH (0) -  p/3day. - !- Q\- 0 S/ .V/, ^ 0W , 6Y (3^ ),\rtEqual(c - (c - day),3 # Add/sub ints or floats should be illegal3for i in 1, 1.0:Sself.assertRaises(TypeError, lambda: a+i)6 -6!?i+al Hi-a)%QdeltaCte is senseless.gday - # mixing date and (l!orp) via *)//zy*yz6l///m "//IQ4 #l" +0a +5def test_overflow()/ptiny = .theclass.resolutionq@in [7a, time8(1)62)]bD-dtd0min'adt -= V # no problem& Odt.__sub__,M @0add@- 70max+5 %@from\stamp*aimport# Try an arbitrary fixed valueyear, month = 1999, 9, 19Ats =b0.mk,((9:, 06-1)dg &ts,0Equal(d.m' ) 1day;hzinsane_# It's possible that some platform maps._t to double,M#8Athis will fail there. Tn@exempt suchvs (providedCy return reasonableAresults!).  for insane in -1e200,  : !self.assertRaises(OverflowError, !theclass.fromtimestamp,JR!) 'def test_today(W)pimport [/F# We claim that :) is like (<.q()), sovGprove it. Pdummywrange(37n+ =%()I*1s = ]againL sV"if2 == E3zYbreaks# There are several legit reasonsOcould failU`# 1. I-cently became midnight, between the`() and ! () calls@# 2. platform,has such fine resolutioqat we'llhn@ get svalue twicez3zGpooru,~we justwhappened tor,P befoQ quantumLboundary4 system clock got fiddleddIn any case, wait a little whileAtry ` {O.sleep(0.1It worked kt didn't. If ip, assum|#'s~1 #2S3# l ` pass hey're within half a second of each other7p/ !4zAlmostEqual(, p delta=' (cs=0.5)/Oweeki7# March 4, 2002a MondayB(<, 3, 4+i).J), iv6G8isoJ*+1L# January 2, 1956%<o, 1, 2* GQpisocale # Check examples># http://www.phys.uu.nl/~vgent/U/a6.ht dI(2003, 12, 22+Gi) "self.assertEqual(d.isocalendar(), (2003, 52, i+1)?Ad = Ctheclass.12, 29) + timedelta(z"O4, 1y-/5+j%19, 1l#9Pm8P0z3Q!10~4"=4t def test_iso_long_years(A!):## Calculate &Q ISO * and compare to table from=http://www.phys.uu.nl/~vgent//6.ht@ ISO_LONG_YEARS_TABLE = """c 4 32 60 8897j5 931p43 7192S 486P6 5|982 105 133 161 18T 11 39j7 195>16 144 172p22 150 01289*84201 229 257 28n 2035 263 291s212 2408  21z46 2749 24r>*80303 331 359 387:03086 364 39 31p42 370 33*370325r|8N Oorted(map(int, .split()eL = []for i in range(400)b20+i+311,?160/V [1:], d1l w;if [1] == 53L.appendi :L, r)(lformattv2, 3, 2 ntO), "0002-03-02"xc)t/00wNsSat Mar 2 00:00:00 2002") def test_strftime(self):!@t = .theclass(2005, 3, 2)&"assertEqual(t.Q"m:%m d:%d y:%y"), "m:03 d:02 y:05"I;") # SF bug #761337'x'*1000), Jr1556784Raises(TypeError, needs an arg@ , "one", "twotoo manyNsO 42arg wrong type# that unicode input is allowed (issue 278!%m$03XB&# A naive object replaces %z and %Z w/ empty strings.S'%z' '%Z'wY'' ''zmake sure invalid format specifiers are handled correctly#NValuW, "%e98%#oh well, some systems just igno  os 7onen#at least, exercis;@em t Mno crashe#Ggenerated?for f in [$F%#"]`):tryBf vexcept =GpassRcheck  this standard extension workD("%fh-H +d,7, 9, 10URdt.__Tp__(''),C(dt)BwithhUXRegex 'm beB, not int'L q7123h'# .pa deriv@'s _*__() gets call"! A2 }%efF  return 'A'LPa = A|PaO?'A'BE),z_zB_b = Bb6str? for fmt in ["m:%m d:%d y:%y",  & H:%H M:%M S:%S5_%z %Z)]:i!self.assertEqual(dt.__format__(fmt), dt.strftime)C aB.bBQ'B') x def test_resolution_info()# XXX: Should min and max respect subclassing?[Tif isTA.the(`, dateg4 exP1ed_'% =(VFelse40IsInstancej.min, {A/axA+ , _delta=TruQax > a extreme_`\big =HLax -%in_ # 3652058 days, 23 hours, 59+2ute seconds, 9c microNn = (big.M*24*3600 + ,A)*10H# n == 3155378975t999 ~= 2**58.13vbjustas0, 0, nUbig, =) ,X/axE ^ Btupl8Pfor iEwrange(7Y# January 2, 1956 is a Monday (0.d<(3, 1, 2+i,t. K9t, Mi^Z, -1)Ea# Febr1aWednes226M(%7, 32+iPMarchGPBThur13),is the 31+29+1 = 61stA# of(Yyear.O3, 16M@3+i)/61 .tm_year, 19W56)  self.assertEqual(t.tm_mon, 3*day, 1+i-hour, 0+?min*?sec*w(3+i)%7y16isdst, -1) cdef test_pickling(m!):args = 6, 7, 23porig = ..theclass(*.Afor Xeer, un proto in_choicesuysgreen =$r.dumps(w!, Ah/derived =iq.loads(I -QWD,(.__reduce__(), ;|ex__(2)^|compare]-t1Cv2, 3, 4/t2$ ft1, t2E!True(t1 <=" >"AFalsE!#"Z6H!!(33), (2, 4 G3, 5* # this is larger than t1vA& %f2 > t1l) % p& 2 tL wL&L= M' 2 'NE M<2 &1 QM=NA`badargCOTHERSTUFF`JU19!, 24!= 2Y1 +gc2", c  Raises(TypeError, lambda: > >>+%}ises(TypeErr or, lambda: badarg <= t1)  self.assertRaises(TypeErr?>*>>+def test_mixed_compare(!):"`our = .theclass(2000, 4, 5) )a# Our ! can be Sd for equality to othe,%esBeEE-(|= 1, Falses *1 == our*T!T?TruS !S)# But the ordering is undefined('< N601 < ~PRepea1oses with a differentPSomeCFpass+@thei -( ==#i[m \!\<A[ )- G:4However, if!  explicitly MscV# relativeIs@, itpallowedVdo soLargerThanAnythinga__lt__ ,;breturnBeBisinstance(., |b/eqbMg no}#g*a=.= 19so it doe}qspecifyknumberF#ofTif d.l("%Y") != '%04d' % yv/0# Y42 returns '42', {3q)lEqual(tB, '%p =# '0042'hobtained anywayi@4Y")j tbreplac7'(Pbase_} |O3IsInstance(;,4D/<# Timestamp depends on time zone, so we'llEaculateJe6herAts =%Cv.combinP(0)). v@caseD[c('fromA', (O,)),'])/ts&& /]H3for@d_name, `"in 8obj in (!, deAbothrNrod and 7Bwithi0sub-obj_type= ?@K= <" = getattrl1>5dHB"(*_`/#it creates.dright K &q[,dtW= {@'s e1 to~ object>{v5/_dQalledl'l }pickling&):  = 6, 7, 23 orig = SubclassDate(*args) for pickler, un proto in_choices:9@sgreen =$r.dumps(orig, Ah/derived =iq.loads(I -self.assertEqualWD!) def test_backdoor_resistance(B)# For fasting, the constructor accepts a byte string.u# This i(low-overhead . A user can (by intent orEmpke) pasKg directly, which (if it'sright length3# will get treated like, and byinormal sanity`checks&". cc insane objects Vdoesn't want to burn@timevalidate allfields, but D :amonth !stops, e.g.,EXh. ('1995-03-25') from yjjing anbase = b>gif not issnA.the|$, }JUuase[:4]P_in b'9', b'\0rFxff'S;Raises(TypeError, o8 w[:2] + !+ 63:]P# Goo#tebad tzinfoBwithXRegex&'^A1 stZKrg$'~ (nps([1] *e()), 'EST'w65ordrange(1, 13d,`shouldblow up because of alone. If#(implementation chzsEdo more-careful-Vit ma-# BtherRSs are7 .4s([8]) r@isoft)4# Test thaO%)mreversibleP_\Us = [F, 1) 000, 2, 149 25/29@4, 162N4, 317, 5, 30<]apdt_tupli Bdt =(*dt_tuple)   dt_str = dt.isoformat() with self.subTest(6=)):.3rdt_rt =5theclass.fromd q-) ErassertEqual(dt, Z-def test_YA_subp(Ah DateS".+Fpassd <2014, 12, 147) =h.IsInstancem9rt,Qp\fails # i that 01() 1 on invalid values0bad&Us = [0'', # Empty string/009-03-048# Not 10 characterxX'1234567894ja dateax200a-12b3# Ib in year<O9-1a<_month=E2-0ay?day;_01-32;.62-2i_leap 3E0228_Q # VISO8601 output no  ]Cfor L s 7Raises(V\[Errorq 7f`_typeecPwhen ed the wrong Oimport io$!4b'21', None, io.S8IO( %)]XTIU VOTypeU%fO) #9! #Atime2s |L( `sub_va13/TTime( "):-0ateJbasic_attribute y(2002, 3, 10).L , 5( 8?, 3& oday, 1$ @hour& minute, self.ass ertEqual(dt.second, 0) self.ass'Wmicro,-def test_basic_attributes_nonzero(K!):-]# Make sure all 2 are non-7 so bugs in; bit-shifting access show up.'Pdt = v .theclass(2002, 3, 1, 12, 59?800 `year, @ onth, 3& oday, 1$ @hour& `minute( /59( Qroundtripfor dt in u21, u4, 5, 6, 7),U g.now()1)# Verifyi`-> str-> datetime identity8s = repr(dtTrue(s.startswith('V;.')7ZI[9:]dt2 = eval(s0gny, dt2) A` via rQstrucfrom pieces EBdt.m0dt. y  2dt.;f%?LlisoformatR  e &t.] ),"0001-02-03T04:05:01.623"_Io'T'), I1 I %K\x00LO$c`spec='sY?T04*IK?:05NN?:01Q_milliV &Z!GZ1VNauto000123")  @self.assertEqual(t.isoformat(sep=' ', timespec='minutes'), "0001-02-03 04:05") SWRaises(ValueError, d\Ffoo'C# str is ISO  with the separatorced to a blank. _str(t@:01.U23") @At = Dtheclass(1, 2, 3, 4, 5, 1, 999500, tzinfo=)zone.utcEe3\llisecondaTa999+00:00#FKautou"N/mij0dI?cro 02 h2 ),2-03-02T$' $'T_B& B Lz I0imez = FixedOffset(cdelta(=16), 'XXX(z4:164def test_i_('):oUs = [s('05:00hours=5)),+2+2+O6:27V36, ?>=27712:32:3&12;R32, s%>=30G002:-9.123456M4L9c=?)]R}', None?" e &(0)+prefix + expected, timezone(sign * td)) for expected, td in tzoffsets*prefix, sign*[('-', -1), ('+', 1)]6%] dt_base = self.theclass(2016, 4, 1, 12, 37, 94exp8'+-04-01T12:37:09'a_tz, tzitzinfos:Sdt = .replace(*F=tzi{-Pexp =+ )tzQBwithpsubTestNK yPassert dt.isoformat() =cdef test_.)IB04A, 10I5L31|Equal(dt._b__(''), str(dt));RaisesRegex(TypeError, 'must beB, not int'L q7123h# check that a derived  's __str__() gets called&1 A(V }%efF( return 'A'Za = A(20^a]?'A'strftimeBE)", N__specB_b = B"b[ fm* ["m:%m d:%d y:%y", & H:%H M:%M S:%S5_%z %Z]Ve.$Pfmt),YcC 0B MB$'BL,`more_c4 # r fieldsbDate doesn't touch.vpimport N 5"c, 2, 18, 3, z 1S"t.), "Sat Mar 2 18:03:05 2002"T4# Oops! The next line fails on Win2K under MSVC 6, so it's comment*b# out.Mdifference i produces " 2": the day# but platY :0:. According tolv# C99, |irrect here#cN\ mk(t.timetuple())S)) '# So test a case where that difference doesn't matter.?t = self.theclass(2002, 3, 22, 18 u5, 123)62assertEqual(t.ctime(),  mk0(t.tuple())1def _tz_independent_comparing(k%):z?dt11, 9, 0, 0?dt21 1/ 232 c.dt1, dt1PTrue(>## Make sure 5son forget microseconds, and iGdoneK4viaEng a floatstamp (an IEEE doubl have enoughNprecision to span resolutas years 1 thrJg 9999,P'sonecessarily calls some distinct valuesLe)"pMAXYEAR, 31, 23, 59&982Aus =*hdelta(q&=1' = n6+ u 02 -(F, us?(s1 < dt2@strf _with_bad_tzname_replace"# verify ok if tzinfo.44().6) returns a non-stoX  MyTzInfo(FixedOffset "&OStr(str"&L , *args.2( N Myu'3'52C33, FGRaises(TypeError, t.l, '%Z'constructor_argumentsJR# badU z3MIN, 1) # no excep55V #, @-1, * F +C [months C2000}( 4/) >  S$A#13 # bad cdays self.theclass(2000, 2, 29) # no exception4444h assertRaises(ValueError, %, :30)B1B$1B#/19B-?1, (0, 1, 32I# bad hour; 7|_?o}3w W&-17F"&24Fominute 23%?, 5#?3, 4G3, 6t"osecond"/59&-*J.7N2_micro7 N0> @9I m 3a%l 3!10 Efold6K5  a=? 2000, 1, 31, fold=2) # Positional:self.assertRaises(TypeError, theclass,4V2000, 1, 31, 23, 590, None, 1) @def test_hash_equality(j):d =}(b2c3r7e4 wEV(d, eS Q(d), #e) dic = {d: 1}u[e] = 2 Tlen(dic)$5 &dic[d], $e$oJ01, 0, 5, 1J 4 JpcomputaKsa2Ub'M1956'diff = a-bdiff.days, 46*365 + Obrange(W2002, 4))Hseconds, 0* _micro/03, F7, 6\pmillise6timedelta(0, '00yhour = %(36"9day!1fIweek @a + n }y8a EAO + aE*010*LHO3, 3 ?a -6E -F TE.2 k1 l?dayD 1 D 1>9E/- E2, 2, 23, 17s, 6)) self.assertEqual(a + 52*week, theclass(2003, 3, 1, 17H-H1HKH q) - a, /3day. - Chour. / millisec37 -- - / ^ / 0 48Aa - ]/, 00, -^1, -05, - 8N,\!, /%, 7 0+ ( +! +h& +<,= 210, 18, 6, ?000" &&((E)-;2, 22, 16, 5, 59, 999( [! -T# Add/sub ints or floats should be illegalfor i in5.0: Raises(TypeError, lambda: a+i%6-6!?i+al Ui-a) `# deltdatetime is senseless.)0day# mixing ^Rand (t%orp) via *)//'* zhertRaises(Ty peError, lambda: day // a) self.assertRaises(Ty7a5?day7*k## datetime + is senseless+5def test_pickling(!): args = 6, 7, 23, 20, 59, 1, 64**2*porig = @.theclass(*@4Afor jeer, un proto in_choicessgreen =$r.dumps(w!, Ah/derived =iq.loads(I -SEqualWD,(.__reduce__(), ex__(2)) )pOmoreu H0200|16, 48, 37, 444116aMbrange(e.HIGHEST_PROTOCOL + 12.\aYbPsGPL`b.year;/03+month, 2)lday, 7Xqing_sub_=.SRD|compare4R# The1") inherited from Test# covers the eq cases.n(# We just want toY lexicographic orQng onJ@membVN ham!at$W lackm = [2000, 11, 29`, 58, S9%8]Q-t1 /t2" /Wt1, t!True(t1 <=" >"AFalsE!#"\iX@len(V)F0new0 = &[:R4[i]! i]f%Y9 ) # this is larger than t1D self.assertTrue(t1 < t2) vself.as%o2 > t1% O1 <=K=L!L&AFals=M ' 2 'N> M< &?1 >ZA1) # A helper for timestamp constructQests.0 def verify_field_equality(, expected, got):4E2().tm_year1. 5 2mon4_month52day6?day43hou 5$mi_inute62secrsecond)ttest_fromqbaimport7wAts =.8(Qlocal$&ts&agot = theclass..(o :utcUI6g3( 1.# Run with US-style DST rules: begins 2 a.m. on  Sunday in: # March (M3.2.0) and end9Vfirst8 November (M11.1.0)@@sup"P.run__tz('EST+05EDT,c,5'{l_naive} '(1970, 1, G tX(), 18000.0{ ~W]v2, 3, 42c VZ | + 3600 + 2*63 + 4*1e-6e# Missing T-t02201@11, 1}0.replace(fold=. t1K%), At0 -`delta(Fs=1)g ximestamp(t0.timestamp()), Pt1 + ,delta(hours=1))2# Ambiguous  defaults to DST)t = self.theclass(2012, 11, 4, 1, 30W*assertEqual(;P.from&t. u)), t) w4# T may raise an overflow error on some platformsBXXX: Do we caresupport the first and last year?>for t in [(2,1,1),9998,12,12)]:D:tryIs = 3except OED6pasUNelse'sdef test_a_aware)i A19701, tzinfo=Dzone.utc- G, 0.Zh q1, 2, 3t) V3600 + 2*63 + 4*1e-6e 0(9-5), 'EST'  Ho1180<@6.run_with_tz('MSK-03') # Something eKof GreenwichBMmicrosecond_roundingR{>fts} ? p9utcs zero = fts(jG7+./, - 23onex C{2fminus_7-87S1p# localRA(-1)gsis not  edZjWindowg|%J&59@Z |7 T94=%8`0t, *IN9e-7 5t, /N1N  t = fts(-1/2**7) self.assertEqual(t.second, 59/Tmicro4992188) h;1e-~j, zeroy@9@?one?10.940J* a 4~}1I} xK F* C7812 def test_timestamp_limits(E%):# minimum *Pmin_d4.theclass.min.replace(tzinfo=<zone.utc)@@ts =c@_dt.&($6try # date 0001-A 00:+:=-62135596800EIFfromJ, tz,SW 7&dt except (OverflowError, OS ) as exc=thedoesn't fit into 32-bit*_t# or platform :support such very oldh skipTest(str(exc)CZ# maxb: set As to#avoid rounding issueso?maxL/axL G=0, =D;-12-31 23:59:00 25340230074T{_ax_ts{wZ# number ofgreater than 1 year: make sure t z:new# is not valid in,.  Idelta = 3600 * 24 * 400v# too small5in_ts - C# convertGa Python fC can raise a sIespecially onG.%s.*Wwith RYs((Value,e)C< `estamp(ts)  with self.assertRaises((ValueError, OverflowB)): ;<theclass.utcfromtimestamp(ts) 0# too bigts = max_dt.5) + delta(</ i<def test_insane_Vi# It's possible that some platform maps C_t to double,AR# and8Athis{ will fail there. Tgshould@exempt suchvs (provide\ey return reasonableAresults!).Bfor  in -1e200, f  , M   - PP@unit5.skipIf(sys.== "win32", "Windows doesn't accept negative*1s")#o_float BThe  Vz-dependent; at leastmt`w#(like it did before bug 1646728 was fixedA.c(-1.05:a (;d = 2%A{Equal(d(1969, 12, 31, 23, 59, 58, 950000)lutcnowaimport%@Callacess if B)a Q) areV'ina second of each otolerance =(42s=1BPdummyAwrange(3d#rom_now = self.theclass.utcnow()  from_timestamp = self.thecla4"!( .*()Ipif abs(.P!- now) <= tolerance:Ybreak# Else try again a few }%s.*assertLessEqual( ,!) Idef test_strpa(W)string = '2004-12-01 13:02:47.197'H`format+%Y-%m-%d %H:%M:%S.%f(expected = w. U_date", ", g got-.5/=9V, got](Is(type(**),35 U 0: *"("+0002", "%z")offset(), 2 * MINUTEJ-J-K X8@01.03 <- delta(minutes=2Gconds=1, microse3 # Only localC zone and UTC are supported{cfor tzW , tzname in ((0, 'UTC'), eGMT'),:!(-B#, \G[0])uB&ifF < 0@signn-[E = - ?elsR/'+Q PPhours = divmod(//60, 60dtstr = "{}{:02dR {}".(*, ^ M>[ J %Z"**dt/u= K.w }# Can producOconsistent  fm`"+12343*/fm1HOUR + 34-2dt.# yet will roundtrip2@strft(!, '3# P3Unaive, if no %z isV3vid self.ass ertEqual(strptime("UTC", "%Z").tzinfo, None) with self.assertRaises(ValueError): QQ-2400S?z")D%0CDdef test_more_`tuple(!):#a# This*s fields beyond thoseed by the TestDate.[V.P2t = theclass(2004, 12, 31, 6, 2 3)l%t.YO(), B, 4, 366, -1)O (t.year, t.month Oday,2b t.hou2Pinute3osecond6 weekday()' toordinal() - dateh1, 1).!?+ 1N $t gTt.tm_l -0mon F-do t.day,n-"mi.0sec.w2y2-v  ~Qisdst) @strfs:U O, 47 .\ ("%m %d %y %f %S %M %H %j"Z a "12 31 04 000047 33 22 06Yfor (s, us), z in [((333), "33.000123"0F"),]ozPtz = o`zone(- `delta(Rs=2, s=s, micro'usKJ.replace(6=tz<%@z"-0200" + z!|extractdBZ18, 45, "43d te3200F686 p mcombin2d =Wv t = time(18, 45, 3, 1234) expected = self.theclass(20020?4, >|combine=.fSdt = V(d, tvassertEqual(dt, /) C=t, date=dMuP, dt.O/()Os t.~' Wb;Raises(TypeError,3) # need an arg<5, d?0two@sADargs reversedD0, 1Gwrong tzinfo typeK#, 2) # too many!"@", ""?ype&dGt#:=Uumentb f , zone.utcbIs(dt./X=_2I( rt1  XN(def test_replace(5!): tz=< c Bogus3ZButco}): return Non 11dst + 0Sbog =h- obog) ) b=:w)w!OAlso%(^^- XBalso)-$K3lso] Sroken&1L (bn 5dt_^Y  ]qP1subP_date,):!C[ ktheAnswer = 42<"__new__(cls, *{, **kwsH0temp = kws.copy.extra = *a.pop('+"^resulOm C.b1 =  ),oqnewmethC, startE1 + #) Tmonth fsecondkT = 2003, 4, 1@2, 11(83vnv # 3 depends on zone, so we'llaculatee-EhereQ"p&()*@caseK[8>e('from6', (ts,)),&# See https://bugs.python.org/issue324175]L.utcj]('utc `9/@strp * '%Y-%m-%dT%H:%M:%S.%f'qcombine@Aate(>q[0:3]),H3:])>]3forRd_name, n"in@ 8obj in (}!, dHAbothJrod and sBwith{0sub0 obj_type= 3@a= <" = getattrl5B5dB"(*_d/#it creates.dright j &q7/dt3  # Test that it's equal to the base object / self.assertE8A(dt,5 _d.replace(tzinfo=None)) G q calledconstructor:.extra, 7mdef test_fromisoformat_datetime(C%):^ .() is reversible.!KUs = ['@(1, +),?900p2004, 15262017, 5, 30)P]O30,  V, 241000\34567 12r, 45, 2"separator' ', 'T'"& , zone.utc>Y% !(*delta(hours=-5)2 72))!dt.theclass(*,_tuple, *s F=tziqFfor 83 inEates&,W,, zi%~sut6dtsg0sep #'dtstr = dt.,(sep=sepQ'Qwith .0subJ(A=V0rdt_rt =7e.F T>7 tTNU :d@(201 S17456nrtzoffse< u"5)  46, minutes=2 ,-32, seconds=3 92e4794croG1{+= [-1 * td v tdu 4r-0 ?td)  \ !&0   J59?>:#1 dt == dt_rt&, dt_rt def test_fromisoformat_separators(self):-1E = [p' ', 'T\u007f', # 1-bit widths3) 803#ʁ/4240ᛇ18時2737Q🐍'& ?# 46]#.for sep in#Pdt = -.theclass(2018, 1, 31, 23, 59, 47, 124789) dtstr = dt.(sep=sep)kBwithksubTest(==, .B ;assertEqual(dt@Aambiguou@ # strings like (-01-31+12:15 (where is not a time zone  '+5-']Z0f12, 15sjXMspec@datem_basesP(2009P, 4, P7, 45e3456),4.'0)jatzinfolQNone,J.utcQU% !(delta(hours=-5)2 216, minutes=27)1imeT6'. seconds' 'milli%4cro2`ip, tsenumerate 00tzi-m %$dt_tuple) 04 if ==-1fnew_mi = 1000 * (|a[6] // @-[0:6] + (d,<*0:(4 + ip)]), 6O=tzi?=ts6-_r{ tstr)  self.assertEqual(dt, dt_rt) .def test_fromisoformat_fails_datetime(G!):15# Test that 81() : on invalid values<bad_strs = [U0'',# Empty string;2009.04-19T03H# Wrong first separatorDO-04.D osecondE aIFhour'-h:1a:45B$# <WminutS>95:4>| =;15|3Bad?\3:15;G H:4500:00 # HAOzonee:45.23 # Too many digits for milli$ :$ .1P 67O?croOS+24:3ooffsetyz-Nnegative M H0ᛇH12:1gunicod>1/complete  =12: ?  A90:4 A 912:=# Ends with JG&745.JG)7+N Gm#45-J7S05:00# Extra tex ->? A =]X OC in sH%1`@.subW((=x04assertRaises(ValueError): self.theclass.fromisoformat(bad_str) :def test_%P_utc(E` dt7 = '2014-04-19T13:21:13+00:00'SPdt = AN2-assertIs(dt.tzinfo, timezone.utc01sub  DateTimeS&Bpass! @, 12, 14, 9, 30, 45U7390, C=( delta(hours=10, minutes=45))I@dt_ra 6dt.@lEqual(dt, U)$IsInstance(%,LB) fDTestb( i8 = /# Overrides not designed for /P@unitp.skip('.appropriate12es'Groundtrip:Dsub_var = 1' HarmlessMixedComparison, bCase):o basic_attrib G(0:f t.n% /, K osecond& Wmicro+ _nonzero# Make sure all  are non-7 so bugs inh# bit-shifting access show up.'M@59, ?800  X/59 .' Z@, 2, 3, 4y# Verify t -> str@!-> identityBs = repr(tTrue(s.startswith('date7.')3LA[9:]t2 = eval(s' O, t2` via rQstrucv piecesp<Y9$t.#t. /st_comparing(self): args = [1, 2, 3, 4]Pt1 = 0.theclass(*0)"2" ?assertEqual(t1, t2C!True(t1 <=" >"AFalsE!#"for i in range(len(PW0new0 = &[:R4[i]!ei] + 1f%tYW ) # this is larger than tDZa %f2 > t1) % & 2 L L&L= M' 2 'NE M<2 &1 QM=Nu`badargzOTHERSTUFF Jh9!, 24!= 21 +gc2", c Raises(TypeError, lambda: #L? >#>>+d} !?ao> >def test_bad_constructor_arguments#ze hours7@0, 0" # no exception.#23/. DValu z@, -1M j<)24<ominutelass(23, 59) # no exception self.assertRaises(ValueError, theclass, 23, -1)='&60=# bad secondsSr(q`59, 0) 3 5943 *A_microA  1, 9=.E!10!) def test_hash_equality(!):":d =/f30, 17ge&[EoV(d, eE Q(d), #e)ic = {d: 1}ic[e] = 2 Tlen(dic), cic[d], 2dn$o._0, 5- % ,|isoformatxtR!4,I_, 123&t.T), "04:05:01.000123";Xstr(tuMA"00:;= ?001H  /10I%)10elf.assertEqual(t.isoformat(), str(t)) t = self.theclass(microsecond=1000),(assertEq]A"00:0.00:"; #0L"<hour=12, minute=34,  56_23456timespec='bs'), "12V>@?:34CC?:56F_milliKO.123O!Y O4!Cautogo:34:56J Raises(ValueError, ', oonkey' FO99952O999"5/00O0i -def test__Pzone(%):tzoffsets = [('05:00'1`delta( ls=5)),+2+2+O6:27VNs=27712:32:3Ds=32Ns=30G02:04:09B1%s=19s=912s=123]V_zinfoR}', None?+9O.utc&(0))), ]  tzinfos += [ (prefix + expected, timezone(sign * td))58for/d in tzoffsets*b!, N in [('-', -1), ('+', 1)]6%] t_base = self.theclass(12, 37, 94exp,'12:37:09'I_tz, tzi:mBt = u.replace(9F=tzin+Pexp =x?9_tzOBwithpsubTestNK wPassert t.isoformat() =bdef test_1653736()I!# verify it doesn't accept extra keyword argumenNcsecond=1 Raises(TypeError,, foo=3)@strfW {01, ?, 4}Equal(t.Q '%H %M %S %f'), "01 02 03 0&4"G# A naive object s %z and %Z empty strings. "'%z' '%Z'"l'' ''"H&"__Q@__('cstr(t)uUn.XRegex'must be, not int'L't.o$12# check that a derived  's __str__() gets calledU&! A |F return 'A'Zoa = A(PaL7'A'I BE)G__specB_b = Bb ;3 fm % [c%',]t]q';@fmt)2A 0A A$'B^Zp $r01:02:03.~0L0@000)P%10PG4000P.theclass(0, 2, 3, 40)), "00:02:03.C") self.assertEqual(str(theclass(12,R0M"12MF23, 15, 0, G23:15:00") def test_rep!):name = 'datetime.' + 0.__%%__4Y.E4)),:r V"%s(1+@" % mGl0B 00p /t# Du 0v# 2 ^)k# Wl -j/ysolution_infoPIsInstance%PZ.min,$@/ax@*$re , (_delta=TruJax > pickling  args = 20, 59, 16, 64**2eOjorig =a (*7Afor aeer, un proto in_choices"asgreen =$r.dumps(w!, Ah/derived =iq.loads(I -)WD,(.__reduce__(), ;ex__(2)gA_sub_u%SEOTimetZLbool # 5 is always .8 cl?5(cls(1) ?0, #&) self.assertTrue(cls()) def test_replace(self): `cls = .theclass0arg[1, 2, 3, 4]pbase = k*()LassertEqual(+ , .Ui = 0>for name, newval in (("hour", 5),*< ("minute", 6,second", 7,Umicro1'8)D0new0 = &[:*S[i] = expectedRNUEZgot =H0**{-:T}1 gZ, got,bi += 14m# Out of bounds.1CkRaises(ValueError , ?=24=#/=-|$O=100%E 00Ii1subGrass TimeS* Ypb@ctimx ?1Is(type(8Y10)), 3u&):"! CtheAnswer = 42<1p__new__!, H{, **kws0temp = kws.copy(extra = *a.pop(''*PresulN.OC.b1 = rreturn oqnewmethC, startE1 +  ^pf, 5, 6 = $4%jd y,in ((-1440, False)  (-1439, True),  (,40, False)):Zif cls is time0t =!(1, 2, 3, tzinfo=Edgy(offset))R&elTOdateX 26, asassert 0, "impossible"if legitaofs = abs 9 h, m = divmod(1J, 60(tag = "%c%02d:C" % W < 0 and '-' or '+', ZHif isinstance(t, L t t.m>tz(ORself.$Equal(str(t), "01:02:03" + tag;/ellM Raises(ValueError, str, t) Cdef test_80_cl s(C = A.the%?B C1(C6a2utcW, dt): return NoneK1?dst+otzname. for t in (cls-O1, 1 M-LC1()9Y@rtIsN6(t. -' )O3#delta(minutes=  ?>A "a'F7C3(H M n,KB)<; # Wrong types. 4# 7 7v( 0+44Typ?2?dst, lO out of ranget6t ( def utcoffset(self, dt): return timedelta(hours=-24) A/ds;:t = cls(1, tzinfo=C6()` .assertRaises(ValueError, t.3Udst) # Not a whole number of seconds.)class C7(%): E Smicro^6=61GK A'-8BS7SgEqual(F7(), j/61D>v+test_aware_compare4Uacls = 1the}Ensure that) gets ignored if the bands have#Rsame 0 me OperandDependentO*4 t$(.minute < 10N"# d0 and d1 e after adjustment/ i3s=ts u7Oelse2 off in0_weedsw#59jCbase8, 9, 10,=jyPd0 = C.replace(&=3/d1$9$2$1PPfor xd0, d1, d2$!y! % op&lt, le, gt, ge, eq, nw govop(x, yQexpected = (3, y 6SRTgot, L# However,Iy're different-bs, uct=t is notHeaa can't actuallyR an olP-depelzEset,q`ough (@() ps None toX")Kso skip this  Uq if IJo=OperandDependentOffset()) for x in d0, d1, d2:!,%y% )got = (x > y) - :< yr( ifbis d0 s d1) and (y  .1)Fexpected = 0!0lif"s M'L*CG/-1/sedassertA gfRself.MEqual(got, )) # Testing time objects with a non-None tzinfo. class3pTimeTZ(> , TZInfoBase, unittest.CCase2theB=o @def -p_empty(/R.<(Pt.hour, 0$ ominute& osecond& _micro+ IsC2(t.E)\zones esSFixed-300, "EST", 1hutc = *'UTC", -2(,meR6) MEP3(2t1 ( 7, 47,G=est&2&)12&7utc&3&3&(meL4&M'=4/t5"vM31|), )2)SN)3) )4*%#t5$!, w Cutco,Fbdelta( s=(l/2.B 0? 3? 6@Raises(TypeError, t1v, "no args"Kcname()7l-=- -A-"tz.'20dstminutes=1))  #self.assertEqual(t2.dst(), timedelta(minutes=-2)) 9 :3:39IsNone(t4:]Raises(TypeError, t1/, "no args") hash(t1),  #-*-2Z-ot1, t2O!3! O2, t!$No4, t5) # mixed tz-aware & naivealambda: t4 d>)12??utc?o?3?/me~z?20, /40w} 89pt1.strf_ ("%H:%M:%S %%Z=%Z %%z=%z"),@7 %Z=EST %z=-05 /t2!Z y ` UTC + /t3N  MET +01yuck = FuOffset(-1439, "%z 7%%ZQt1 = =e23, 59yKwtA'%Z'vO'%z'x  "23:59 %Z='%z %Z %%z%%Z' %z='-2359'") , # Check that an invalid tzname result raises exception.Cclass Bad4(tzinfo):!lytz = 423defh(self, dt): return 5.tz1t = time(2, 3, 4, h=y%)).>assertEqual(t.strfA"%H:%M:%S"), "02:03:04"=R(TypeError, IZ, "%ZLIssue #6697if '_Fast' i!__5P__.__h&__/..8'\ud800'$OValu sest_hash_edge_cases# Offsetsoverflow a basicCt1 =!her(0, 1, RFixedW(1439, ""/t2E0E 8Eb(t1), '2)23, 58, 6, 100e0-10 J4J/10&d?picklingTry one without a5args = 20, 59, 16, 64**Morig*71Afor eer, un Pproto_choicestgreen =Ap.dumps(w!, Ahderived =iq.loads(I - WD,(.__reduce__(), ;Yex__(M(# nkt@ = PIableU3T'cookie'v 57Z4IsInstance(.S,L  HCAutcodelta(minutes=-300K >), H[more_bool # time is always True. cls = self.theclass t = cls(0, tzinfo=FixedOffset(-300, ""))1H`assertg>(t)M5MO#o23, 59q23*60 +def test_replace(%):)w z100 = k1jV+100"m=zm2) timedelta(minutes=-200), "=0arg[1, 2, 3, 4,y]Cbase*.y.`Equal(+ , .)Ui = 0Xfor name, newval in (("hour", 5),* "("O", 6,second", 7,Umicro1811", )0new70 = &[:ZS[i] =  expectedNE go x0**{]:T}1 gZ, got,fi += 1 # Ensure we can get rid of aW i tz( :2 =D`V=NoneZ Is~"2.-( gadd on%32r=w 3&!IsF3 0Outlfboundsj%1aRaises(ValueErrord , z?=24=#/=-|$oO=100%E 00IIm}_comparPt1 = 5( tlt1, t2< +%F%REqual(t1, t23) t2 = t2.replace(tzinfo=FixedOffset(0, "")3 self.assertNotEqual(t1, t2) X# In time w/ identical _ objects, utcof is ignored.Eclass Varies%):def __init__( $.f=delta(minutes=220TU?, tX +Y1X\wreturn 34v =9/t1v""n./),3@2@4@ .But if they're not6, it isn't#4True(t1 < # t1's "counter still going uptest_fromisoformat# _examples = [O00, *),b23, 599"]Ehh = (9, 12, 20  mmG5, 3sf(4, 45*@usec,0, 245000, 678901 += list(itertools.product(hh, mm, sHsec)DOR[Nonek@zoneA ! !(hours=2)-(156, 77))Afor ttup i ]'!zi& ~" =1the (*Z,F=tziv1@tstr.D4"Bwith\subTest(8=n*Lt_rt.> w=& , Q_~?Abase ( 30, 217456b"tz2 i5# S 4 , ?32, seconds=30 e2w4794croG1123+= [-1 * td d$ 46h timezone( delta(hours=0))] tzinfos += [*3d) for td in tzoffsets7"ziB:SZt = base_T.replace(mZ=tzi).str = t.isoformat()Pwith self.subTest(tstr=)z.0t_r0theclass.from`: 9assert t == E,def test_I`specs(o_Ys = [k(8, 17, 45, 123456),!0,K[UNone,J.utcM ;-5)2 216, minutes=271ime?%'C', '. seconds' +5lli%4cro2`ip, tsenumerat 0t$`_tupleU/ if~ ==-1fnew_mi = 1000 * (twq[-1] //)<-d7 0:9<+ (c,zG Q%(*0:(1 + ip)]), J9?=tsj%A.rEqual(t$Mfailqbad_str 4'',o # Empty string7?12::# Ends on a separator>/30A>>15.>6# Incomplete > ;@=?0:1@ == =a:30:45.334034E=valid characteraEa # Inva lid character in seconds '12:30:45.1234', # Too many digits for milliK7567NK?croKb+24:30P`# Invatime zone offset?56-CnegativB:30:45| # Uses full-width unicode colonh0․j(56RK`\u2024@plac decimal poinaJ # Extra at tend of basic 3' JFEK 8456NKK+12:00:30TO H%] abad_st %s:!6with self.subTest((=)0 4assertRaises(ValueError48gtheclass.fromisoformav)def test_%_fails_typeeg(Ql # Y the 8 8p when pd$`wrong Nimport io$es = [b9', None, io.StringIO()FR ZV?TypU.QrR 1sub Kh TimeS"mv%V3Ztsc ==12, 14, 45, 2037ptzinfo=U.utc)ktsc_rtG 4Ftsc.B)GEqual(tsc, Td&IsInstance+I_rt,[7_$tz>?C4theAnswer = 42>i__new__(cls, *argK*kws|0temp = kws.copy(e = *a.pop(''*Presulz^OC.b1 = rreturn oqnewmethC, startE start + self.hour + self.second args = 4, 5, 6, 500, FixedOffset(-3"EST", 1):Rdt1 =Utheclass(*O)]rdt2 = C, **{'extra': 7}KassertEqual(dt2.__TV__, CS+theAnswer, 42, ?, 7' b1.utco0), ; 2.newmeth(-7;13dt1 -' # Testing datetime objects with a non-None tzinfo. 8DateTimeTZ(G, TZInfoBase, unittest.#aCase):% =|@def 1_trivial(r54-dt1, 2, 3,F^ Q.yearMQd..month,  .day, 3 ?, 4% minute, 5' @?, 6' Tmicro,  , even_more_compareR# The"R) and :) inherited fromE#:*M coveredr cases..6Smallest possible after UTC adjustment.h:21, e=1439, "")to# Largsg(MAXYEAR, 1R3, 599, -;# Make sure those  correctly,y@w/o oFflow-True(t1 < t!/!=" X2 > te1t1,"!!2,d:_ afer }V1V2?c3, 13,/ F3*60+13+2NI`(2# Change t1 not to subtract a 9u1 should be lr0># Change t1 #to subtract 2 minutes, and t1 should be smaller. 2t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(2, "")) HDassertTrue(t1 < t2) k'# Back to the original t1, but make seconds resolve it01,x/=1 >LikewiseRmicroN_}M~t2 naive8$it8Idiff424E.min_N NotEqual( s$!!2,^!#> comparisonEfaillHwith{Raises(TypeError):+Z0t1 It's alsoif it hasR.utco) is None= N@(0 }Fdef B, dt): returnOtd(5, 6, 7k)yz# OTOH, i OKe two ofse mixing @waysWbeingMQ&p1WTry a bogus uctgBc/timedelta(]=1440) # outUounds?22, =107BValu, lambda:!==ktest_pickling( # k@one lancargs =4"2081, 64**2kN = (*@Afor eer, un proto in_choicessgreen =$r.dumps(w!, Ahderived =iq.loads(I -.WD,(.__reduce__(),yex__(2)-w ttinfo = PicklableFixedOffset(-300, 'cookie') orig = self.theclass(*args, **{'tzinfo': t}9}derived<21, :=0, "", 0)Gfor pickler, un proto in_choices:sgreen =$r.dumps(!, Ah/iq.loads(I -assertEqualWD,IsInstance(+. 0, PaHtCButco), timedelta(minutes=T Ktzname()  5K.__reduce__6 ex__(2))  def test_extreme_hashes(X) # If an attempt is made to 1 these via subtracting l#n5"`a date object, OverflowError results. TheF Python implementation usedblow up here.6t@1439&(tQMAXYEAR, 12, 31, 23, 599, x -Jp# OTOH,3OOBt should  25, 4 .jRaises(Value,<, tb>zonY esErv, "EST"jhutc = '7UTC$,meK6%(MEIEt1 =t@(200, 19, 7, 47, (es2776utc/t373n'men_U%t1 )2) )3){k/2.B ^?3? 6@ <A Wm@- `-D- h -<"1) (t self.assertEqual(hash(t1), S3)) |self.as-2-ot1, t2N!3! O2, t! 2str "2002-03-19 07:47:00-05:00"`??"12??+00?I3), ?3?1?d = 'datetime. (, 3, 19, '{3repd + "7, 47, tzinfo=est) ==)12>?utc>>3>!me|def test_combine(B!):T met = FixedOffset(60, "MET)4Ptz = Br(18, 45;5234 qdpM3.d-T Ddt, 5,, th !) 6+extract+#theclass /?!dt"()R 0dt.d6 +;/tz= @tz_aware_arithmeticLanow = (V.now(Ktz550-33west 5:3Itc = now.replace(Tb4now3 Iu.@54Is(N.l!/55-06imeid # Can't mix  and non-.) Raises(TypeError, lambda: -== 7B# And addingq's doesake sense,oor not +.B%= 1Sub2should yield 0 - now, timedelta(0))  self.assertEqual(nowaware - f, time<=# Adding a  should preserve tzinfo.1&=Pweeks=1, minutes=12 croseconds=5678eplus =" +j%Is.o, tz55U22 =K% +^V 2[ `5,b52) i# that -X@be wwe started with, and1!J+"beZ7iffQLIs(diff , 6zR Raises(TypeError, lambda:Cb6,H eMake up a randomFzonetzr = FixedOffset(+.range(-1439, 1440), " om3J"# Attach it top.replace(F=tzr]J7/0!# sure theerence takes adjustments into account7got?xB# Expected: H basq! oj7) -99\ =A=A =?) +; hz-\G e6c9B.utc'() sK)0Tgot, a Try max possibl%amin = Vtheclass(1, {=?-W"min"g FMAXYEAR, 31, 23, 599, ~K"max! =-Z#0max-,.-'inI i( 2*)"`# DifftXQ, butCsameztza = timezone(HOUR,s 'A') tzb = timezone(HOUR, 'B"delta = min.replace(tzinfo=tza) - maxbdself.assertEqual(S!, theclass.min -Aax) def test_{P_now(@!):kmeth =B5now! # Ensure it doesn't require W (i.e., that this(blow up).N@baseFeth(# Try with and out naming the keywordI off42 = FixedOffset(42, "42"Ytanotherr5Dgain;tz=*3Is(K.0, a=S47Butco!),:(minutes=42)E# Bad argument//o }Raises(TypeError, F, 16g/=6eR j# Too manysQK!, p# We doknow which  @ we'!n,Z)chave a!# k to represit, so see1wheg<actuallyJA a conversion is tricky;utc0, "utc", 0for weirdtz in [ ahours=15,kc58), ":S,:H/( Q6),]^LPdummywrange(3#`= datel.(hcIs(now,3;utcb,()>utc?0nown40.asQif ab0 - ?1) <Gseconds=30 ]breaka# Else@code?broken, or moshan 30 b pEd betweenRcalls; assuplatter, just try >Jelse# Three strikes_m6out+Pfail( ),/A(tz)l) may be " @from\stampaimport fromtimestamp  ts = time.3() % # Ensure it doesn't require tzinfo (i.e., that this(blow up).Nbase = meth(tsfTry with and out naming the keywordK off42 = FixedOffset(42, "42"Yvanothert!, 9"Hgain ;tz=#self.assertIs(S.0, aAW4UEqual7Butco!),rdelta(minutes=42)E# Bad argument //o }Raises(TypeError,}, ts, 16k3=:eVH v# Too manysU V?fewU%)  # t1ke tz= actually some conversionastamp = 10]putcdate&4 = .utcfrom=( # In POSIX (epoch 1970ghat's 2001-09-09 01:46:40 UTC, give or tak# But onflavor of Mac, iQnowhere near. So we ca)Ehave # Qidea 5w01ime:>3is,B only tesX'atJPrelatchanges matchdedhours=-15, o39) # arbitrary, bwuot zeroq+tzi`, "tz", 0expected = +X8gotF, tz_SYp, got.replace(SNone)1defM__utcnow(Q%):0 = .theclass~5now$Ge`; for Never reason,)accept aa@< ]$gI2  +Wpimport "@.theclass.utcfromtimestamp Pts = .%()$# Ensure it doesn't require tzinfo (i.e., that this(blow up).Nbase = meth(tsfTry with and out naming the keyword; for whatever reason,`J# ut%()accept aargument off42 = FixedOffset(42, "42" self.assertRaises(TypeError,a, ts, M6T==def test__`tuple(!):%# TestDateTime4ed most ofp. dateBP adds pwist tofJDST flagclass DST(y}__init__, dstvalue*.if isinstance()_, int.2$delta(minutes=o3#.% =%4dstyreturn O E cl@1the*,T in (-33, 1), ( @0, 0None, -1 d = cls(1, 0, 20, 30, 40,=q)tA PEqualjt.tm_year+?mon*?day+ ?hou /mi 0+?sec w!, Uy+Y.fisdst)J#2() pPs wro6ype "V"x"))s_e edgl`91,1pH1439_ () O -P Q0/oof ran*V(40"N<-14Os0utcbIs"'=0G if i sinstance(dstvalue, int): $ = timedelta(minutes=);Tself.4 = )0def(-?, dpreturn "O ERcls =theclass # This can't work: DST didimplement utcoffset.<oassertRaises(NotI2edError,/7rcls(1, tzinfo=DST(0)).p)ass UOFS(DST'__init__,uofs, dofs=None1KDST.5/P 4G0for| in -33, 00, Cd = P2, 3, 10, 20, 30, 40, `>E-53,\)tjtuple(!Equal(d.year, t.tm_ 0Smonth1?mon04day.?day/ #11,hour) # 20mm + 53mm = 1hn + 13mm #13G/micsecond1?sec d.weekday()4wd.toordinal() - date?)?+ 1w #  t# Ensure tm_isdst is 0 regardless of what=() says:0 K#6Pneverpeffect Qa UTC!E |M# For naive, " = Rexcep|K.  t[:-1], d.!()R 5 # Same if{X/ N Z! O|B0ipCheck t3bad4detected8B8 def utcoffset(self, dt): return "EST" d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=BOFS())8h.assertRaises(TypeError, d.utctimetuple) 6# Check that $() is the same as3 asKzone(utc).Y( 20P11, 14, 15, 16, 1718192for tz in [Q_e.min, 7utcJmax]Tdtz = d.replace(*&tze*Equal(dtz ()[:-1],6 6  LA# AtX%edges, UTC adjustment can produce years out-of-range # /`a datez object. Ensurean Overflow ( ir'%d.TCtiny}MINYEAR, 1, 0%37}U}G14390# TEgoes back 1 minute lesKan a full dayw )nyDhuge#AX8?p3, 59, 9 -forward6 Q# More oV case  0ime)w(MINUTEV!UO.maxt-uZ def test__isoforma?;zero = FixedOa0, "+00:00"fKplus(2Eh"+03:4* +-231, "-03:51V{unknownYNone, "" clSvtheclasstr = '0001-02-03'0ofsY , ,Q3s, 9u80, 987001!^^B4, 5'%us6ofsK7g4:05:59' + (us and '.t~' or ''@2ofs?`s not >d.tzname()?zBtail?"+ R + is#&d.E.Aiso,Ne@+ 'Tu?.isoformat('kT')) +self.assertEqual(d.isoformat('k'), datestr + 'k' + tailstrLk\u1234QVZstr(d @def _replace(!):`cls = .theclassz100 = FixedOffset(100, "+100"=zm2) timedelta(minutes=-200), "=0arg[1, 2, 3, 4, 5, 6, 7, ]base = cls(*7+ , .5)) JUi = 0for name, newval in (("year", 2),*2 ("month", 3+day", 4)0hou~5*aO", 6,second", 7,Umicro181tzinfo", )f40new0 = &[:S[i] = vexpectedNEZgot =0**{:T}1 8gZ, got,fi += 1D# Ensure we can get rid of a . i tz( S2UV=NoneZ Is(<.-( vadd oneb32ar=wY<3&!Is* 0Outljbounds% 20_2, 29kRaises(ValueErrorn , S=2001yMpmore_as=zonU# The inheri/ covered some trivial and eW case@fnon0, "LKf44mx44, "44%;m5h%-w0s=5!m3d]o*.now(tz=xbSIs(dt*, '1# Ring with degenerate?! r an exception6dt.q, fnone) # # Replacing with same tzinfo makes no change. 2x = dt.astimezone(dt.5)%self.assertIs(x o, f44m&Equal(x.date(),b . . %) differentdoes adjust=gotOfm5hTIs(go/, (+utcoffsetdelta(hours=-5)gexpected -= in effect, convert to UTCD!+=.B0dt)Dand from there@`local G$= R!.r;"e(=0 # Pattach newjI,[ 6D6-tz8: m%3@support.run_q_tz('UTC'Idef test_\_default_utc(%):Md.theclass.now(X( ANonev2.# Note that  in TZ variable hasb opposite signn4Dproduced by %z directiv{= EST+05EDT,M3.2.0,M11.1.0ReasternV(2012, 11, 4, 6, 30,=mC '[ !, 5$ P.strfu("%z %Z"), "-0500 EST"? 54D>near_fold# Issue #26616 u}1aterB2015O1, 5 u%Is = @7\sDL,ware_subtract clntheclass 0 # Ensure that utcoffset() is ignored when the operands have D# same tzinfo member.rclass O>DependentOk4%):.P7def{self, t$(if t.minute < 10F"# d0 and d1 equal after adjustment}3return timedelta(i$s=s)7Oelser2 off iL]weeds@w E59) 2base = cls(8, 9, 10, 11, 12, 13, 14,=z)Pd0 = S.replace'=3$1$9$2$&11%Pfor xd0, d1, d24!y! 'got = x - yexpected =x13- y >s.assertE2d(got, X# OTOH, hs are distinct,&n'w#m5 EF#KPif (x2d0 Qs d1)'&(y 1|' i0$@elif"s P #O ;FJ(11-59)-  su#0-wmtest_mixed_compare(<t@date(1, 2, 3, 4, 5, 6, 7~t+e kt1, t2L%t2>V=None%F%F.RG, ""Wlace(tzinfo=FixedOffset(0, ""))  self.assertNotEqual(t1, t2) % # In datetime w/ identical tzinfo objects, utcoj is ignored.Iclass Varies(;%):def __init__( $.f = delta(minutes=220TU?, tX +Y1X\wreturn 74v =9t1 = t2.replace'=v"2" n./),3@2@4@ 2But if they're not6, it isn't#t4True(t1 < # t1's "counter still going uptest_sub_!tz)"):)!! CA.the GtheAnswer = 42<@m__new__(cls, *argK*kwsH0temp = kws.copy("Pextra-emp.pop(''*result =.yC.b1 =  oqnewmethCo, starE1 + Dhour Fyear\E = 2002, 12, 31, 4, 5, 6, 500,  -3"EST", 1dm ( dCS, **{qG: 7}KEadt2.__1V__, CS+F7, 4,?, 7S 10; $2.-7), dt1.  -~ # Pain to set up DST-aware%Pes. 1firynday_on_or_after(d days_to_go = 6 - dt.weekda 6if %I9dt $adt ZEROB2imeE0) MINUTE[y1) HOURs=1) DAYw?pthe US,s at 2am (standard@) on6 0 Su  in April. DSTSTART =( 1, 2) # and ends at 2am (DST time; 1am standard) on the last Sunday of Oct, # which is#7fir$n or after- 25. Because we view 1:MM as # being{zpat day,a rejno spell0in localP of #(@hourr(that'spDST, butzaken as). DSTEND = date!P(1, 10, 25, 1) class USTimeZone(tzinfo): def __init__(self, hours, reprname, stdname, dst!):;?2.stdoffset =`delta(!s=)0Z4 = !q3 = d Rqreturn "6 tz'dt8"if4Idst(UFelse' ./2utcChl+), Pif dt@None2dt.  !# An exception instead may be sensible here, in V@moreacases.EZEROyassert :y# Find in April`@star'!_sq_on_or_ (DSTSTART.replace(year=dt.)P.weekday() == 6 andrt.month4M<= 7 in}FoberRend =?END?end!10X>= 25 Can't compare naive to awobjects, so stripzEfrom#d <==z) < end=EHOUR_vc Eastern =S-5, "", "EST"DT") Central4C6, "4C4C4MountainhD7, "aM4M4|PacifichC8, "hP4P4utc_real = FixedO(0, "UTC", 0) # For bet0tespverage,want another flavoCUTC w4(/0s. KfakeS-12*6@TestC Conversions(unittest.Test#Case): # The DST switch times for 2002, in std.2dston = date-((4, 7, 2)$.ff%10, 27, 1) (theclass*# Check ay that's insid@ef c((self, dt, tz, utc, #ff+ .assertEqual(dt.dst(), HOUR*# Conversion to our own zone is always an identity@j as:>@(tz)qPasutc't.(2utc\Tthere_and_back = 4/'tzR UTC and =_isn't d,s# because } are redundant spellings (in local!G) ofCyQ whenvbegins: V clock jumps from 1:59:59Bto 3:00:00,am of 2:MM:SS doegreallyAmake sen1n. es above treatK'as?daylight@n (i"after 2am"), w9aliAZ1sstandar^0latH@formZGwhatc&Vproducesx0if ate() == .!();@dt.hB== 2 p# We're(th0xbcomingB@Pgives# -4< /o+30# Although durawas co30redb ,Zois notGFZEROlyYVAsameFO UTCf j dLOelse?not ? BIwe have aI "( i(unfortunately <0endPat ca"be@ed aEl in#KD. WEwto 1:00MDagai_ haVathen: &Atakej'beO ,N== 0:MM EST, but:is H # daylight time. The hour 1:MM dayl@== 0standard can't be # expressed in localUNevertheless, we want conversion backJfrom UTC to mimic theSclock's "repeat an" behavior.I@next_utc = asn+ HOUR$Xtz = 20.aszone(tz)2if dt.date() == dstoff0andw%0:8(p# We're!&bbeforeqast DSTl Mis ineffablWY[ ]J1$self.assertEqual(0tz,replace(6=1) >-^=_ !c6'JelsewL a - dt,!) `# Check a that's outside>Pdef c)(f/ , 7Futc) cCst(), ZEROz6# C0to 1own is alwaysidentity@j q@ting'xm$n fF toojP=!aGthere_and_NZ,C|'t_between_tzi3utcAn = i .xtzinfo=# Because  onP endstaken as beA!<, #<s no spell.in tz for d0 ofh{Iu# For purposes)Atest+ DK!is, which is s (-LFime)^(ffl/ffm Pdelta((weeks=13)LY?DAYOHOURbminutes=1c,crosecond1"):2X in-(n,,n*ffG#ur91 + 1#WyJz self.checkoutside(dstoff, tz, utc) Cfor )@ in ,n - delta,Bff +::EmLn5def test_easy(7)N # Despite the name of this4, endcases are excruciating.aonvert_between_tz_and_utc(EasternV_real /.c;Pacific;! vOfakev$ ;0# T,pext is ly dancing near5dge. It works because2## S and bfar enough apart thaeir "problemGhours" don't overlap " :a# OTOH<se fail! DQenablm1m. HdifficultyNPedge ps assumCat every =representd+inI"utc" class| is5always true a fixed-offset tzinfoJ@P (lkeAutc_(, but notO or CentralA# Fo-se adjacent DST-awjtime zonesKR rangsed ends up cresbN#on;0are1 4M!intother. s"reason, we would se4ureiK%vss too ifGadded 3*HOUR to{wlist ofIh6)gCm ,p) # ca*J, JK_trick22:00 on day before light startsfourback = RIV(*6s=4ninewest = FO(-9*60, "-0900", 02e .replace(-=U5!# Ou7qUTC == 0EST 3DST. Since it's "after1lA# 2"}!sh~ghe 3 spell1# IaBplug\NDinto, it "looks like stdwH", so its  is returned as -5, and -5 - -9 = 4. Adding 4 # to 22:00 lands on , which makes no sense in local time (theJclock jumps from 1c3). The point here isbx sure wMget the 3 spelling.kexpected = self.dston.replace(hour=3).got = fourback.aszone(Eastern);tzinfo=None@cassertEqual(u, got) i# Similar, but map6\UTC == 1 0EST f DST. In thatI0casB wan: osixutc36, utc_reala# Now "looks like daylight", sooffset wrt 37-4,la^@-4-0-4 givesDK We7ESTO*v1JCo9 ends, w"repeat an " behavior0# ! 4:MM 567PcheckHthes% L!23%01E2:MM9# EDT ! 9'Jwall'N agains@for  ina, Ufake:]n+ tzCE, Pacific(,irst_std_4Aff -~Qdeltaqs=2) #  rJ# Conver at6UTC{#fq-= tz.utc(1# Adjust possibly e as++= m+1mFZIc`; this4a1whe=/ &3tz=b!= "6utcl !tzin (0, 1.2)0ih%ffoM=TpDtQminut0, 30, 59q1u4 = rM=tG A#$tz@/tzu"Castze(tzinfo=None), expected) asutcbase += HOUR ( def test_bogus_dst(self):Iclass ok(tzinfo@utcoffse;, dt): returnk)1f+w`now = A.the.now().replace=utc_real# Doesn't blow up.V.astimezone(ok()) 96~ notok(okENonez assertRaises(ValueError, nowl @Somes In the following, .implementation may0 or depending on# whether DST is assumed to be in effect. qis situn,F&a p should@rWd by )tricky_xif dt.year == 2000  DOelse6 110*`M,dtp(2001, 9 )dt8 #?s|fromutcb4TypEastern.<Q) #-enough args%1datO.utc(+, w) # wrong Q )F in correctDe2@(now>:# df`Equal(O.has righ memberI4Ztoo manyP.today()Tn8ype2Always converts UTCstandard  FauxUSTimeZ [x0 Bdt +12std+FK = ~T-5, " 0", 1ST"9DT" 4:MM 5678E9:MMx# EST 23012Q 3ODT -  5:MM # Check around DST start.  = self.dston.replace(hour=4, tzinfo=Eastern);f<S7/F0or wall in 23, 0, 1, 3, 4, 5:Wexpected ]E0"ifZZ== 23KO-= timedelta(days=1Icgot = .fromutc( )0assertEqual(d, got) 5$+ .stdoffset3%?(# Ensure as zone() calls eV) too#B~!utc_real).T(v += HOUR6endR%ffZDB1, 2 :/ #9p # oddb class O(unittest.TestCase):@def _bug_1028306()# Trying to compa+P datea 9 should act like a mixed-CtypeEison, despiJ6hatJis a sub!of1as_=ftoday(W# .combine(,&()8.5Tru)C != 4H0%40FFalsa=a 1b5b Raises(TypeError, lambda: as_date < stime) self.assertRaises(TypeError, lambdaD:HD#? <=5I$>4H%aE#:% >I%) -# Nevertheless, comparison should work with the base-class (9 # projection if use of a ' method is forced.ccEqual(t.__eq__g), Trudifferent_day = -.+ 1) % 20 + 1o^6 ^.replace(day= [_), Falseo2And_qebother subb esA?u. If a#$ wants to stop this, it's upPVdo so}]s_sc = SuEDateGTyear,f.month?day,?_sc+Z 0PDitto5Is .T80ateZ2, 0/i &  def test_extra_attributes(%):for x in [Y.today(), ^:.utcnow%!_delta_zinfoimezone(D&)]t A4@x.ab18check_arg_typ7sz NumberB__init__m, value|" =% wJIBvreturn Iecimal.D?(10" d ('10.9'),  Number(10)]: self.assertEqual(datetime(10, )),CO COxx, 5)) DWwith "RaisesRegex(TypeError, '^an integer is required 'J~r'\(got type str\)$')G'10'ef10 = U5.9) __int__ returned non-int"_float7f10pclass F=(C Epasss-/10"argument expected, 'sq . MLQM5QM9QBUFYJ]/ #9 # Local Time Disambiguation # An! ri,al reimple$ of fromutc that resPs the "fold" flag. tzinfo2("):%deH(G, dt" in UTC -> l:"."Qif not isinstance(dt,8_-r #("$()5s a= @"bif dt.$| hBValu\/("5X4# Rv7 satisfie#dt + ldt.utcoffset() =G0offBdt.replace(8=0)4.01 = .1. if off0 is None or off1dt.dst()7: raise ValueError ifJ@0 ==16ldt = dt +05Y= ldt.utcoffset()#\ D`returnD8# Now, we discovered both possiblesets, so7we can just try four4solutionsfE in [off0,Y&1]! o ifE B+]Breplace(fold=1F#eh ("No suitaLlocal time1 nd") # Reimplementing sified US-zones to respect the "" flag: class USTimeZone2(tzinfo2): def __init__(self, hours, reprname, std 0dst )\2B.stdz! =adelta(G=K0Z% =e!q$ ={ ]^"6 tz'dt81if 4 UFelse' .Xo), lhl+KE ifC2dt. # An excep instead may be senPhere,0mor#icases.EZEROyassert OFind first SundayVApril`@star8'!_s'_on_or_after(DSTSTART.year=dt.)P.weekday()b6 and Pmonth4M<= 7)lavOctoberRend =?END?end!10X>= 25Can't compare naivex awRobjec a stripU from#=c+ HOUR <Z< endgP# DSTin effectj>tE@elifJV i] # Fold (an ambiguous hour): use dt.fold to dis#gate. return ZERO if4else HOUR-elif start <= dt <+(:)]# Gap (a non-existentreverse the ?rul m {DST is off Eastern2 = USTimeZone2(-5, "", "EST"DT") Central7D6, "7C7C7Mountain2nE7, "gM7M7~PacificnD8, "nP7P7( # Europe_Vilnius_1941 tzinfo implementation reproduceslowing # 6Qransi+ from Olson's tzdist: # # ;P NAME GMTOFF RULES FORMAT [UNTIL]3/ 1:00 -B0CET 1940 Aug 3 # 370MSK"oJun 247nC-Eur CE%sT 4n$ zdump -vP`| grep.1mQ Mon {3 20:59:59+i UTC =3isdst=0 gmtoff=10800c c%00!CEd1d7200 class 8(8)gdef _utc_S(selfuM[datetime(, 6, 23, 21,=8I, #  \X2X]X'2:AUTC Y/lo"3r t / zxJ4, 0^)] !4 _YZutcoffsetG, dt_,z_stop = %._ )N$ <-2art13 *8/op7-(2,3)K#$4 >=%oph25/dsZ0 91/ 0op return 1 * HOUR def tzname(self, dt):fold_start, Pop = +`._loc_%()1tif dt <-6artMQr_'MSK'5/op4(5, 'CEST')[dt.}]G"# ~$>=%opy=fromutcsassert gU == 0Ntzinfo is!.year != 1941 aise NotImplementedErrorB{/ut{%ddt + 3=2=).replace(&=1 K class TestLocalTimeDisambiguation(unittest.%fCase):_vilnius_p_V$ = Europe_5"()Rgdt = datetime(T, 6, 23, 20, 59=%zone.utc lEdgdt.as"(r&OTEqual(ldt.strf3("%c %Z%z"), 'Mon Jun 23 23:59:59x MSK+0300'p ?, 0&QFalse_dst()&?1, R00:00?+02?Tru 2v2Tue<!4 %=x:est$to!m2 | 1GUTC'a 3 gdt = ldt.astimezone( s.utc)  self.assertEqual(gdt.strf/("%c %Z"),07'Mon Jun 23 20:59:59 1941 UTC') :ldt = date[#r, 6, 23@59, tzinfo=Vilnius, fold=1gH_ldt.a[1!j4, 0, p}2:00:00def test_constructors(%%):01, 1 R w t.#',  $d%Wwith *Raises(TypeError00, None, 0lmember 1dt.lj:?tz(<|replaceY0U]?=1)5)t.40i d5# Check that cment of other fields does not change "!".jF; = p1vEasternIh0 ;H1 (: A# Oufbounds_OValu` 2J K  is a keyword-only argu)1+pST comparison datetime(1, 1, 1) self.assertEqual(t, t.replace(fold=1)/_dt, d1adef test_hash(k!):}t = time(0_dAdate XBt), Z} 2d<!) @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0's@from\stamps = 1414906200nddt0 = .Ca(1(g + 360] @dt0./, & 1&1 Australia/Lord_Howe  _l'Lhowe`tm = _6`.local f(1.4e9#if"Astrf! '%Z%z', tm) != 'LHST+1030't6skipTest('zone is not ed on this platformX# $ TZ=P -r 14281587# Sun Apr 5 01:45:00 LHDT 2015^?605^S^ t /18 _t0, t tS (2014, 11, 2,[3Kd,t0~{),1i Gdt1.1-K YZa, 4, 5&45Xs{ (0)cs +1+ fPs0 + ?, sW  as Odt0 = datetime(2014, 11, 2, 1, 30)  dt1 = dt0.replace(fold=1"# Convert both naive instances to aware.SCadt0Tastimezone(Qat/1. # Check that the firsts in DST VA and#`second5STDself.assertEqual(.tzname(), 'EDT'/1/S/ 0 + HOUR, [0# A%s with fixed offset tzinfo's always have 0 %', 'Odef test_pickle_(9!): !@t =  dAdate1W"1,<Bfor _Ur, un Pproto_choicesy}=x%z[t, dt]"4s =_.dumps(x, \z(6y =.loads(s' 3Ox, y'R(0 if| < 4 else x.UB), y  YyOreprr= et.E0, 0 AAdt),K '[ ( hFgap>gap 0gap?gap%0gapN '2 hash_aware  ]R(t), .replace(A8=1) r?2, U(-E6gapD@ SECimedelta(k0) pairs(iterablepa, b = tools.tee$5next(b, None"return zip(@) class ZoneInfo(c0roo'/usr/share/'e__init__?0, uiE6""" :param ut: arrayF&A of transition point estamps1Jti: listIJ (offset, isdst, abbr) tupleK:,IMu uj!ti6l* sinvert(@staticmethod9G *jL(-@('q'a"),= if\U[0][0] // SEC  lt[0][0] += offset Olt[1 for i in range(1, len(ut)):GLjijRti[i-Yo// SEC.61][. ,return lt ?@classmethoddef fromfile(cls, 7obj$if .read(4).decode() != "TZif"raise ValueError("not a zoneinfoQ!")u.seek(32counts = array('i'.E6, 3$if sys.byteorderZ'big'g'bswap()//ut~/utzH?[0]/ut~type_indiceB" n0ttiM%[] '1] 9 .append(struct.unpack(">lbb">)76))I@abbrw#j'2])# Convert p , (gmtoff, isdst, W@ind)cenumerate(: )[ @ind:s.find(0L]~p= (timedelta7)ti = [None] *Y{[, idx 1] =V[idx]self = cls(ut, ti #1Bname ~path = os. P.join(.aroot, 1with open(0, 'rb') as f7clsEPOCHORDINAL = d1970, 1, 1).toordinal@utc(G, dt0"""DraUTC ->W`local B.""",0if isinstance(dt,:c-4Typ) requires a= argumentif dt.tz1!is| ; k5"Nstamp = ((/C0 - d.v) * 86400F+hour * 36& minute * 6L gsecond!if<uw tjFti[0vfold = xJelse@idx = bisect.bisect_right(self.ut, timestamp) sassert '[idx-1] <=0/idx == lenaF) or4( wdelta(0" -!ut61])*Adt +i[!if:return dt.replace(~&=1LOelse4 Kdef _find_ti_, dt, i)6(dt.toordinal()EPOCHORDINAL) * 86400a+hour * 36minute * 6<fsecondlL`lt[dt.60 bi.lNR`ti[maxH- 1)][i]3utcoffse41I\V&0)B/ds<Eisds =(# XXX: We cannot accurately determine the "save" value,# so let's 1h whenever DST is in effect. Since?we don't use )/fromutc(), itCPunlikGthat?it will be needed for anything moran bool(`%).@ZERO if 2V HOURbetzname2@classmetho'@zoneRps(cls, dir=None\$ifJ 7p = cls.6roo_tab = os.path.join(`dir, ' V.tab' :tryef?"pe7O,except OSError7Zijwith f#l^,in = v.strip(z !if P and -@artsrG('#'P2Qyield=.split()[2Cstatstart_year=1^@counoDgap_ H Uzerosmin_gap = 31imeE.maxG4max+3ax_+"MP_datenV5M.min;7 +~T h)Z= max_fold_zone = None stats_sincdatetime(start_year, 1, 1) # Sing from 1970 eliminates a lot of nois`for zonename in cls.Es():count += 1Atz =9yI(B)(ldt, shiftmtz.transitionnrif dt <  %vcontinu#ifpo> ZERO>Ogap_DAif (, dt) > (max_gap, _ 6>+" = $(_I% =0_ = dt.Na.max -b< (minLC(0%el<Ofold A = - P] 40ax_,5)617 w$, M/in)1"/se _zerosUs = (2!, >', @print("Number s:q %5d" % A4):4Q = %dAs) +  K)" %a((sum(N ),A  tMin gap %16s at %s %s; ,$, )_/ax_qj_!inC b/axbbatetime, max_fold_zone)) def transitions(self):for (_, prev_ti), (t, ti) in pairs(zip6P.ut, ?G.ti)CGshift = ti[0] -O5[0]j'yield datetime.utcfrom stamp(t), Kanondst """Find all s with the same value of isdst on both sides)E."""["if < ZERO andKU1] ==L&1]MQ-R0[2]2[2]e@classmethod2print_all_Acls,[ _abbr=False, start_year=1@coun0VUntin cls.'s(;-Atz ="#2(+)Q(Ud , 9tz. iE`if dt.' <6 or(Y!!=aPcontinueM+= 1t("%3d) %-30s %s %15s -> %s" %7V1 (n$, $/, 67SRAE,I 2t, y=gap~&>=~ }Ozero~12not{1 f ZoneInfoTest(unittest.CCaseW = 'America/New_York'BsetU8ys.platform@z"win32"@skip|("Skipping@Pinfo s3Windows"v?tryM.iDexcept FileNotFoundError as err`2%s: L,CassertEquivD}g, a, b@/al((a.replace(tz =N_@, a.<r, id(a.?)),_ (bIbIbI)sself.tz  for dt, shift in tz.folds(): !)x!B[0 */V, 0.5 C- timedelta.resolution]MUudt = dt + xjlromutc(udt.replace(tzinfo=tz))9self.assertEqual(ldt>, 1.ag\imezone.utc).as>(tzF t`ivDate10s(a[>ldt4utcoffse(, ` pNone), U%+ ML# Round trip= ,Hk 9) Nv-R W^&=,S XIB, 0)def test_gaps(1cPtz = 5.tzBZ=9(W>^   Create a localy inside the ga X" -dALessc0=1)8/() ^ A0A"At %s." % nB7D9 I *system_transiH 8if ('Riyadh8'yname or # From tzdata NEWS file: Q# Thes solar87, c8, and 9 are no longer distributed.Q(y were a negative experiment - that is, a demonstration Ntz data can represD time only with some difficulty_error2ir L@ce iy: caused confusion, as RiyadhRcivilwas generally not=fose yearsself.zonename.starts('right/'))1 skipTest("Skipping %s" % O)Btz =%tz TZ = os.environ.get('TZ'7[]EaK:try_v.tzset(Pfor udt, shiftz.transi +s(4 if3.C >= 2037o%# System support n s around the end of 32-bit%_tG#M later is flaky on many sj>]breakTs0 = (ud@date(1970, 1, 1)) // SEC9s{1"C #B}seconds4x`[-40 * 3600, -20* ]1, 0,7@ss -fss + 2CS]_0 + xbPsdt =P.from zstamp(s2O tz5 , tz).replace(tzinfo=NoneN*assertEquivD0s(sm916dt.)bal(s, s1,if ss > 0:?gap2# Create locazainside73 C0) -F?/ 2wt ts%dtfold=1)'`ts0, s<nss / 22 aal(ts17-N 70fin Pif TZ# _7del !;elsU72)TZ8  class ZoneInfoCompleteunittest.SSuitedef __init__( tests = []  if is_resource_enabled('tzdata'): & for name in ZoneInfo.zone+s(.6Test = type('3q[%s]' %O8, (y,), {})zLn! =; %`method@dir(nR2if ,.startswith('test_/!s.append_(F)super().__init__(4)) # Iran had a sub-minute UTC offset before 1946. class4 ( = 'Asia/Tehran' =ACapi=@unit.CCaseBdef setUp(self# Since the C API is not presentc`_Pure [s, skip allid`lf.__cP__.__7c__.end{H z.U('Not relevap{Python') o# This *must* be called, and it  first, so until eitherNrestriction`loosenPQwe'll^Was part ofW%upG_#Pcapi. _datetime_(2utcuse_macro(True, FalYv_utc = |@get_w9fS? A.sub*= 43assertIs($, zC.utcksCZH ,  9_nnEmakeQp1expd0ime (delta(hours=-5), "EST"9 un; ncases = [  ('' , b`/),/0 18_nn42_nn7]Ci, tz_act0expt )==.jEqual(d<.ddt1 = 4(2000, 2, 4Rinfo=C6?dt2:?expu dt1, dt2f+0.tz!()4i dt5? aszone(timezone.ut'c), dt_utc) def test_timezones_offset_zero(self):*.utc0, utc1, nonH@ = _Acapi.geIoEPwith Y.subTest(@`name="a"q0+assertIs("$, .+[ 1[1[" ^ CNot((d$e_exp =(delta(hours=0), ""V<*VEqualqV 4dt1 = datec(2000, 2, 4, tzinfo=<)k?dt27 s 0dt12c'0.tz)(2a`check_ class DateSub (' sBpass p(2011, Jds =P&tDeHV!is P2_0# CP the  that should be valid_NSTrue(o6(d)$t%s% , ~)^!atses do not match exactlyGFalstfa ,s,Y various other things ares at all?0arg`[tuple@list@1, '-01-01',2*1)%(12, 00)]:for arg insO5(x!, ,:arg=arg,x=I9=^@ 6Tim' | _%"&30t LD"D!isy [y8O(T $T % the subclass does not match exactly self.assertFalse(is_time(ts, True)) -# Check that various other things aremCs8args = [tuple(), list1, '2011-0%',2 Hdelta(1),zone.utc, date(>, 1, 1)]for arg in)s:X(!, )(Qwith $subTest(arg=arg,J=I9=8\@^def test_ca_(C^class DateTimeSub(/*FpassAdt =4Y8, 12, 30)% dt f34%is@ = _Tcapi. Tbe ones]should be validgbF(dt)) s* Sthe sk!p*Htxk<Kd qDvH,wAtd =+&(1 tdgX1r<X U8?(td, *W +XLkY*IZ5q,n (True, Falkse): with self.subTest(arg=arg, exact=9H8 assertFalse(is_timedeltaIE1)) ydef test_check_tzinfo(Faclass TZInfoSub(+&BpassYbtzi = )!()p>Q2 FOR4 +1814 STORE_FA Jes) 16 JUMP_ABSOLUTEe18bZBLOCK/20{0 (None-22oE % ( .__code__.co_firstlineno + n.2.&3)1333982(x=[]assert 0, ([s Ex] +A[ Q _2eIF_TRU+26AionError  < object at 0x..., file "%s", L %d>cs3 ('bug8..k'N10 MAKE,015*\ 0 (xZ4/161m4\20 BINARY_ADD/22v =24 RAISE_VARARGSc28 __*(__@&o ^ _BIG_LINENO_FORMAT dKspamO 2 POP_TOP  4 LOAD_CONST0 (None) #6 RETURN_VALUE """ _BIG_LINENO_FORMAT2 = """\ %4d90o`GLOBAL|0 (spamo 2 POP_TOP   dis_module_expected_resultsDisassembly of f: 4 E2E bgb5b:expr_strx + 1" > 1}GNAME L0 (x21/4 BINARY_ADDsimple_stmt(= #zoSTORE_ON8N1*10\@anno05 x: int = 1 y: fun(1) lst[ 60)]F# leading newline is for a reason (tests 2no)\{1 2A0 SETUP_ANNOTATIONS Ue6e| 1 (int1Q2 (__ations__=1/l1 ('x'1"2 SUBSCR 381l3 (funO18 CALL_FUNCt122\2 ('y-2422\4 (ls3w3K3 (0/34w*36 3ME  1 (int) 40 POP_TOP2 LOAD_CONST-|4 (NoneJ,4 RETURN_VALUE """ compound_stmt_str = """\ x = 0 while 1:|`x += 17'# Trailing newline has been deliberately omitted dis_l3 10K0 (0 2 STORE_NAME?0 (x) 24 SETUP_LOOP 12 (to 1843 >>6c d%8/K1 (110 INPLACE_ADDjK1+ 14 JUMP_ABSOLUT6Z6XUBLOCK12Z/20ZtracebackV0%3d0YEXCEPJ4) 4\/ 42M!-- 6 BINARY_TRUE_DIVIDE88 1 P2"12qFORWARD!40r5O4 DU1cGLOBALF0 (Exceptionc8 COMPARE_D0 (e7k match=2YtIF_FALSY*52/22#24-FA r d#281sFINALLY1J,4013Oz %3`@ATTRXU1 (__+__3\1 (tb023004s 24Z44 DELETE_0/c6 END_ %4B /50+ +1 )52j.s-56 % (TRACEBACK_CODE.co_firsttno + 1,* 2*RACEBACK_CODE.co_firstlineno + 3, TRACEBACK_COD*4*5) def _fstring(a, b, c, d):oreturn f'{a} {b:4} {c!r} {d!r:4}' dis@ = """\ %3d0 LOAD_FASTQ0 (a)i2 FORMAT_VALUEK 0+4Z=CON[l1 (' '\61L1 (b/8/`\2 ('4`/104 (with formatj/12j1L2 (c`6|2 (repr22K3 (d`2\/246/, b26 BUILD_STRINGW7W28 RETURN """ % (.__code__$1,Q3g(xByield x async oa %co>5for item in _=Cpass3h(yuf&foG)'''funcdoc'''`[x + z zf!y]"2foonested_0 kCLOSUR; (y# 2JTUPL.! 1~@1 (< object foo at 0x..., file "%s", JL %d>\_h..foo 8 MAKE_FUNCTION810 STORE 1 (foo) ;2k/14h  __/%__@_8' 04, 3is_=1=%s Disassembly of :+ }x}CAD_CONST  2 ('_h..foo ') 4 8 MAKE_FUNCTION8+10 LOAD_DEREF$K1 (yZ12 GET_ITERHo4 CALLs1+6 RETURN_VALUE """ % (dis_nested_0,2__file__h.__code__.co_firstlineno + 1'3'_g3, ) 2 = """%s Disassembly of < object  at 0x..., p "%s", %d>: %3d{0 BUILD_LIST0 2-FA*f 0 (.0 >>3Q4 FOR12 (to 1836 STORE_dL1 (z/8WK0 (x/] ^12 BINARY_ADD 014 0r_APPEND2+6 JUMP_ABSOLUTE'4+1/18 {TpO _ { class DisTests(unittest.qCase): maxDiff = Nonedef get_d (self, func, lasti=-1, wrapper=True, **kwargs):[# We want to  the default printing behaviour, not$5argKoutput = io.StringIO(with contextlib.redirect_stdout(?$ifdis.dis($Oelse:eB6%Irreturn .getvalue()ae_as_s[Y WFalser_p_addressesh\^re.sub(r'\b0x[0-9A-Fa-f]+\b', '1', =(do_fexpectedp gogdepth=0if 54!= O != R 6got]"rtEqual(got,T8a_opmap C`*["NOP"], 9q In.+LOAD_CONST"], dis.hasconst) self.assertIn($opmap["STORE_NAME"],=aname) =def test_op(I!):[XSEqual[+[fLOAD_FAST"]], " fboundariesjEXTENDED_ARGF @HAVET\UMENT]widthfor opcode, 3 in enumerate FJ'if0('BUILD_MAP_UNPACK_WITH_CALL',~8 8^TUPLE: s;continueTQwith subTest(=G ! =A0_OPPi_WIDTHXq ! <. dY+]a+= 1 +4o_OPARGaBLess3len1), P -diJ`do_disPPmbly_ 1(_f+,_fEbug_708901L2bug2S[|1333982\ # This one is checking byteiQs gen~ d @an `rt` statementU# so fails if thes are run -O. Skip t{+%n.if not __de_[Askip^b'need %s,fsout -O' 7FG>big_lineno$func(countspace = {}4A = "@oo():\n " + "".join(["A] * Z + ["spam\n"]KPexec(P%, q "freturnr['foo']C # Tp all smerangesi{(1, 300expected = _BIG_LINENO_FORMAT % (i + 2T(i), Vsome larger _s toor300, 10e G51O2P.) f rom test import dis_module self.do_disassembly_3(,,8_expected_results) K1defj_big_offsets(\!): n$func(countnamespace = {}44A = "@oo(x):\n " + ";".join(["x = x + 1"] * b"\n return x"VPexec([%, |)"8r['foo'];, ws = ['''\[%*d LOAD_FASTJI0 (x.=CON/M1 (1.BINARY_ADDv_STOREwv''' % (w, 8*i, G + 2 4 6{for i in range()]D s +B 38% RETURN_VALUE  [0] = ' 2' + s[0][3:"''h L1, 5\wU(i), >Vi, 4)M::H1249=@*50@ 50 \e_str@expr19Psimpll&mt@ G@annoAF Ecompound_stH 5 Mbyte7_f.__code__.co B#f_l OclaslC[cS instance_method_C(1).__init__i_Ny_H5: = x M Ss 0AOatic74.smt'stC, kf): .self.do_disassembly_test(_C.cm, dis_c_class_method) def ):e_generator(X!):*.gen_func.0 = B.gety(_g) # GF 3ItionHC;(1)F"itF}rtEqual(W , w _asyncaJaAN~PK N_!, coroutine!coCHJ = _co(1,eobject*q.close()Avoid a RuntimeWarning (never awaited)?ba0 GA!, D|fstringB_1 >_no6trydel sys.last_tracebackexcept AttributeErrorBEpass0\sRaises(~9.dis, None E a51/0Eion as etb = e._F%__@kgR = tbQ! tb?~Se_as_*tb.tb_frame.f_code, iD~4pZ 2Typ<)Xmble_recursiv8X check(expected, **kwargsQ.?dis+Gy(_h6 5Mp_addres6dis:a(),nested_0, depth=0R %1%1%2%2%3%None) # check(dis_nested_2) class DisWithFileTests(Dis ): # Run the t again, using file arg instead of print?4def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs): output = io.StringIO()f$ifC3dis.dis(p=JeEOelse?eG/, N rreturn o.getvalue(~ code_info_ = """\ Name:$ n!(.*) Argument count?1 Kw-onlys: 0 Numberlocals: 1 Stack sizz`3 Flag OPTIMIZED, NEWLOCALS, NOFREE ConstantsCQ0: %rv_formaty@1: _#object Variable ?x""" % (('FHted detailsrmethods[tions, or X6.',*if sys.f.optimize < 2  (None,)) @static^ tricky(x, y, z, c, d, e=[]`d9af(c=c)(H<2, fcyield g ?<!939398979VARARGS, VARKEYWORDS, GENERATORR5< 1` f at  " q", line>6B2: '".<O>.f'n2@1: y@2: z@3: c@4: d@5: e 6:es 7: kwds Cell v[edfxyz]*81: 2345""" # NOTE:2ordc above depends on dic+Aary 8!\_%0Bf = 0.__HB__._0_.cpnsts[1]<1Cf,8oNESTEDFoc FreeVinfo_expr_str = """\ Name:  Filen Argument countG0 Kw-only as: 0 Number of locals: 0 Stack siz`2 Flag NOFREE Constants: 0: 1x""" code_info_simple_stmt_st 1: None compound01O 2 async def a_def()7 await 1J for a in b: passwith c as d`[L$MO(.*)D+2D/10EOPTIMIZED, NEWLOCALS, [, COROUTINflw1b lass CodeInfoTests(unittest.CCasen_pairs = [Zu (dis.%, _ $),,htricky%"2co__nested_f.7@expr-& E- 4 |6 8-0)!] \2S(selfv<.maxDiff = 100>x, expected/R,-1 zrtRegex6(x)L)AshowI`apture`dout()joutputx\ F.getvalue(Z+"\n"?. = io.StringIO(# r, file=9 * |_object(self):  (self.assertRaises(TypeError, dis.code_info, object()) ; def test_pretty_flags_no (Z!):*.i`Equal(]: (0), '0x0') # Fodder for instruction introspe!s # Editing any of these may require recalcula'`the exGed output outer(a=1, b=2f(c=3, d=4inner(e=5, f=6!print(a, b, c, d, e, f) Pretur1ner/+'', 1, [], {}, "Hello world!"D@!f cjumpy("# This won't actually run (but that's OK, we only $rmble ita in range(10^i)if i < 4continue':> 6'Qbreak$Felse"I can haz  clause?0whi 5Q -= 1_  Who let lolcatz0o tU suit6tryQ1 / 0except ZeroDivision,@Here_go, h 3...%8Awith i as dodg^Never reachI0finLL/Lnow we're done")VEnd f opiq genera$s _`_line  _offset =Qer.___.co_first/qno - 1 /_f2consts[3]ufg9 = >_' j"@m,J 1u (F1jThe follow%s are useful to rexe=results after # either$is modifiK@byte/ ch)AKqion, updat{referencesG_Yand #Q befo@runn>7 #_A0s =I.get(\!, 3;=O2) #' = [\n ',Q #',.join(map(str, z),\n]', sep='')/() ted_opinfo_f = [\n ', 1#',.join(map(str, _instructions)), ']', sep='') #" = dis.get(outer()(), first_line=expected_inner) #print('bopinfo$\_jumpy $66 Ii 1t~7 ((opname='LOAD_CONST', opcode=100, arg=8val=(3, 4)brepr='4ffset=0, startsp=2, is__target=False)i`LOSUREU!35s^0arg1'a' o2ONone;1xb 4.BUILD_TUPL!02|V06. 3'_object_f(3), 8K4'..f""1C MAKE_FUNCTION%=9 1 =')1/STORE_FA2H&' 1/E`GLOBAL!16' 7!WDEREF3G2arg 4S2/pcode=100, arg=5, argval='' ^repr="''", offset=22, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_CONST', opcode=100,|!=6x1  '1*4.BUILD_LI3p= 640MAPV|8. 7'Hello world! /30.CALL_FUNCTION3 = 3/hPOP_TO=arg/)FA"242f' 38RETURN_VALUE8  ] expected_opinfo_f = [ > Ea(5, 6)/H 3'gCLOSUR'"13=a /  ('b 4Dc  UQ <d THTUPL0= 1&V  code_object_inner, argreprd=repr(code_object_inner), offset=12, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_CONST', opm=100, arg=4val='outer..f '*/=","4.MAKE_FUNCTION'!32!=9 ')D6.STORE_FASD!25y='*8.L`GLOBALp"16Wprint'*205X!WDEREF3a 43 b /c / 1d /OCALLgq 3 wPOP_TOP20arg X=arg4 ##36RETURN_VALUE 8] expected_opinfoO = [ 1 74,: 5 : B^ tion(opname='LOAD_DEREF', opcode=136, arg=1qval='b' Brepr :offset=4, starts_line=None, is_jump_target=False), Instruction(opname=' 2vc 6K3d 83GFAST!24z!=0e /10Jf 2.CALL_FUNCTION3= )1/pPOP_TOPT |0arg~=arg49CON 0  /RETURN_VALUEY 8 2] expected_opinfoA_y = [7SETUP_LOu585GPto 54+ 3!`GLOBALT&"11P'rang5>=/E9A) 10 </ U=/GET_ITERT!68k8/;FOR94344O?TruNlSTORE_K5Ival='i', argPrepr='i', offset=12, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_GLOBALXpcode=116, arg=1val='print'44!GFAST!24p!=02arg 6  CALL_FUNCTION3 )8.pPOP_TOPT0arg-/20.L'25!9CON0!=2 4 )COMPARE_!07z<  2/JUMP_IF_FALSE1&=3   + /yABSOLUT31 36!'7?Tru +63L ('> 3S   /BREAK_LO848* /4uction(opname='POP_BLOCK', opcode=87, arg=None 6val `repr='.ffset=44, starts_line)(is_jump_target=True), Instruction(opname='LOAD_GLOBALW1116|!=1q'print'o6K10, OFals WCONST!00r!=4I can haz else clause?/"'#4", 8nCALL_FUNCTION34;5)0/50.?0TOPT&0arg0=arg2.SETUP_LO2!521108 `to 108  -11:)FA821=''i#  51  JUMP_IF_FALSE19  +/66-12'6/-6 '6 ( /13!5!17 INPLACE_SUBTRACZh7/STORE_FAST', opcode=125, arg=0qval='i' Brepr Loffset=74, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_FAST', opcod4o6/14!9CON0!=36 68 COMPARE_OPW!07p= ('> /80.POP_JUMP_IF_FALSEQ8  + /82.yABSOLUT&=5 /15!'-16?Tru 24L('< 9S   9/BREAK_LOo0arg 7 /9" PBLOCK^8NfGLOBAL1^1h'print1 9L'Who let lolcatz into this test suite?"25", /CALL_FUNCTION', opcode=131, arg=3val Lrepr='', offset=104, starts_line=None, is_jump_target=False), Instruction(opname='POP_TOPU~|K0arg 6.SETUP_FINALLY"22!70"18 `to 18028-20 ?Tru `EXCEPTW2"=1!24 242*10@LOAD_CONS0!=5} 1277v1/BINARY_TRUE_DIVIDE21/P(+1 VBLOCK8/,JUMP_FORWARD1%28"15/ 522#,:DUP #. `GLOBAL1k  'ZeroDivisionError'2/COMPARE_07`'exceph match3UwIF_FALS1EL"15g >yQ3t/bT*Q3truction(opname='POP_TOP', opcode=1, arg=None 6val `repr='-ffset=134, starts_line*is_jump_target=False), Instruction(opna16.LOAD_GLOBAL!16q'print' o8O23, WCONST!00s!=8Here we go, h 7.../"'24", *40CALL_FUNCTION3e U)P/42.,43WEXCEP!8900argb>arg/JUMP_FORWARDb\2"17 `to 1762 END_FINALLYY85?Truyl)FAk"24''iG !5-25 SETUP_WITH21431"17025/lSTORE_ 5h'dodgy/25Never reach this"-"'c6> crepr='', offPset=162, starts_line=None, is_jump_target=False), Instruction(opname='POP_TOP', opcode=1, argKfargval `repr='-"ff42PBLOCKW?87,6.LOAD_CONST2100 p0 8.WITH_CLEANUP_STAR8/70?Tru `FINISH2  .7/END_FINALLYY8} q7 27/fGLOBAL2116q'print'Do 8-28'1"OK, now we're done"\ /CALL_FUNCTION["13/=6 0)3T'8x 184-9RETURN_VALUE!83rgval=None, argrepr='', offset=192, starts_line=None, is_jump_target=False), ] # One last piece of inspect fodder to check the default line number handling def simple(): pass expected_opinfo_simple = [ Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=00.__M__.co_first!/no RETURN_VALUErpU1=83oa. ] classTests(Byte}Case): r test_dq(self):'+actual = dis.get_in"s(8).=.assertEqual(list(DO), e)z_set_to_!&, Ly<_outer3 N&^ Plnestedwith captured_stdout(Af = S(ff+fdoubly_'Vinner8+C y 3+C\) #  has its ownas above, so can rely on it to validate #9object oriented API`s(unit.\`antiat7 # 7 @func$, method, . string andfor obj in [_f, _C(1).__init__, "a=1", _fP]P|@.sub(obj=obj(bj+"MxIsInstance(b. codeobj, types.CodeType) self.assertRaises(!Error, dis.ByteG, object()>def test_iteration(M%):\0for5 in [_f, _C(1).__init__, "a=1", _f.__c6__]=Pwith U.subTest(obj=obje(Bvia_ = list(9%))150gen(or8get_instrucs@>`Equal(Q , ] 5explicit_first_line?actual =(outer, 7=expected_K [6), <RpinfoC asourceYp_in_disLmbly# Use the  @  simple).dis(, .strip().parti(" ")[0] # extract%nour = str(n}2.co&no D>+ anYenumberF ?350F\"350" $ BmaxDiff = 1000x(@Info!s.AZpairsbxdurtRegex(b. ,ed,_fww9*,_frPfrom_\ebacktth'tb.E&tb while tb.tb_next: Tb.current_offset,H_lasti ? [b\F ) if __name__ == "__main__"C@unitW.() # Augmented assign . import 5 class4A-(.CCase\BasicUx = 2 gx += 1**G-= 8.W//= 5G%= 3&M x |= 5  px ^= 1 ex /= 2 self.assertEqual(x, 3.0) " def test_with_unpacking(6!):#TERaises(SyntaxError, compile, "x, b += 3", " [exec"slInListjux = [2]z@x[0]Q*$*J-= 8IZ//= 5J%= 3&\|6 ru ?[0]x_InDicj{0: 2}+vSequences(1,G[3,4% -[1, 2, 3, 4, ]|]Uy = x[bx[1:2]p4yb+= [1]Xe)X-True(x is yCustomMethods1+Dclass aug_yC__init__9w, value'Rval =#`HHraddHFureturn M+MKJ.S# $2(2 iy= z 3.e3 4z3 """Blocks inheritance, and fallback to __,9""""__Dv = NoneH&(1 J&107oQIsInsLJ+.y._not x$5G, 11362(2>}2}?3(3} self.asser tIsInstance(x, aug_test3)  self.assertTrue(y is not x$Equal(x.val, 13) I5x =`64(4>Wwith gRaises(TypeError):Dx += 10 Z@def CustomMethods2(_T=output = []<NQclassB:alli[__add__(KW, valP?X.append("3 called",TrU 4V iV 4Vareturn4?sub3qTr"r4V iV 4V ?mul3q"4V i"V4V/atu m6w#%r\i%\7/floordivQ8{OiC9|%rC|9| bOtruer 7ymxrB8z n self  def __itruediv__(self, val): #output.append("8 called")5preturn X {?modv3qTr"4V iV 4VX ?pow3q"4V i"V4V/or2o!r3T i!T3T/anQ3q"r4V i"V4Vx3q"r4V i"V4VorshiftU6w#%r7\ i%\7\/l/"6w/%r7\f __ilshift__(self, val): output.append("__ilshift__ called")4preturn W x = testall(3Ux + 1$U1 + xhx += 1B-,-,-,*,*,*,@,@,@,/,/,/, - . /%[%[%[* |[|[|[&,&,&,^,^,^,)>>-)>>.+>>/)< i9pow i)or. i*an ix>rir)i 8 > '''.splitlines()) if __name__ == '__main__'@unit.() -- Testcases for functions in cmath. --(PEach i takes the2#m:  -> BTwhereO% Qis a short identifyingy,D ia to beI ed (exp, cos, asinh, ...)H pair of floats separated by whitespace- `repres ng real and imaginary partsOa complex number,) 3Pexpec{(ideal) &ue, again@ed aL ; @listing-point flags required by C99 -- -- The possible flags are:& divide-by-zero : raised when a finite input gives aW mathematically in-uresult.coverflow]rEd whoseq-real or imaginary part is too large to fit in the usual rangEof an IEEE 754 doublevinvalidfqs-`gnore--sign : indicates that!of +$ofis unspecified; i6Gc4 isD@n as,#n both -ind should be accepted aBgcorrecim+KFmay appearany order%Lines beginning with '--' (like this one) sta comment, andd. Blank lV,W q contaiaonly whitespace,CX alsoH fmajority Avalu@were puvRhelp version 2.3BMPFR librmultiple-preci/}floating-pointfbations$ rounding. All outputB5qis file(modulo yet-to-be-discg@ugs)>_"lyaped, proWdCeachCx decimalB 0 be9i`terpre:as a represent@O1spo nearest= iP. Se>#thomepage at http://www.mpfr.org  or0forqon abouGAprojSYA min!tacases `genera  mppP 0.19p100 bitsuracy (()  im1of Gfunc'-- gu;qs. Thesu(@est._.MathTestsE,@well inA!_c5 ;-,acos: In>Qsine 5-R  s =P0000 A 0.0 -> 1.5707963267948966 -0.0111 2121-g1c32dqbranch ss: +/-1J10 acos 1.0 0.0 -> 0.0 -0.0 acos0011 # 1" -#"2"-#>> 3.1415926535897931T32lU3d -- values along both sides of real axis#20[9.8813129168249309e-324> 1.57079632679489662-FG25002_e-305{5j4o1e-150j55j65:9.9_8e-17z8_7E 8`8EP0.001F1y9615634y94h 53RY0.5786v2.1882979816120667v3NBCJ0v9@386886319WBCd*.022.1073424255447014e-083T UT 1T  0.044717633608306849RR %2.}p-1.3169wu69248169AA4/23 @3.82y47133310124BB1P0E-I37.534508668464674Q Q>+14|346.0809111296667O4U U P_1e+29 689.16608998577965 acos0047 Z -1.01e+299 -0.0 -> 3.1415926535897931 689.16608998U8U 9.8813129168249309e-324 S1.5707963267948966n9E F30.0E"50Eo1e-305y)514h24?150h34h44:9.9_8e-17x5D 6DW0.001w"69X628235h1d 2DY0.5786p0.95329467197772655sABC6>0n91.4901161193847656e-086OEF` 2T2.1073424255447014 6pDED .  0.044717633608306849~BB |%2.ip-1.3169.69248168s|1d1|+23c@3.82Y4713331012cl2d27\1v0"->R37.534508668464674s7XA ATL5+14346.08091112966677UE EVu7YEE -- random inputsg#10-3.3307113324596682 -10.73200753086+1.8706085694482339>13986806554613^-2863.952991743291 -2681013315.2571239]573950301699 22.40260784327475#10-0.33072639793l220088 -0.85055464658253055 -> 1.8219426895922601 0.79250166729311966 acos0103 acos -2.5722325842097802 -12.703940809821574`7699942413107408 3.2565170156527325_"4 _42.49523378545958354039320751337161``3.1288E 73153304 4.4424815519735601`5`1.1363818625856401 96425498630376^1.5709141948820049 -9.8669410553254284_6_`2.4398T24157866e-1X3300205189026616570796326818066324305780A7d7d1.352134042552 2.93697379120767729849059192339338 -1.8822893674117942_8_827364706477915 1.035232147557^ `322463@0032^4090688264969^9^0.25978373`03546 10.09712669185833_1.5963940386378306 -3.0081673050196063_"10_0.33561778471072551 -4587350.6823999118`|2536333251 16.03X40257953$11_491334446109984458071422362990011908761712801788]857334581318786%12`2196734507I2.48129654317451`@41406100692 1.Z72609881712.9614262102219.03295695248664 572768319822778 6.082465988501`2.88623652641 -20.3801@2206t4302765252297889 3.718201853147610.4180568075:09 1.4833433990823488345583030420798477D1576252.37611140592471@0139@0p@0.00017618040241_4yP50666~547141637948387.6259656341829289400> 054707883548=-25.1454249898093810.0612266591222A6 0.844723439461515%52402803063697679179897 %81<2.4480466420442959e+2c@1800\20138466x7.353756620564798e-28 -61.45565#996376 -- values near infinity#201.620686@683021e+3080n226285283-> 0.5665083826223 -710.54K7#56I#201.2067735875070062Q1.342917372439j4369390864i4794027498-7.41301451J@9047Q7 1.1759130543927645`2.133246478536 21871115698752 acos0203 a!cos -8.6329426442257249e+307 -1.2316282952184133%8 -> 2.1821511032444838 710.29752145697148 acos0204  0.0 1.4289713855849746S1.5707963267948966 -T4631069738996T5T-U3153524545987432U1634604787539T6TS-9.6229037669269321T7709.85091679573691T7T-4.9783616421107088U 19187157911233U8U1.3937541925739388i"->B2135678707264E9E9.136238896737153"7 F7990195312461"10EP-1.3401224F3.14159265358979311862969887180#11U5.4699090056144284//> V2860327108564"12U1.58807108 5.56384012523399293.503519487773873e-30835187633140583g24972116i13168 -3.0456477710024h2.4370618453197486iP11227S234121T-9.90162240060S4.9570427340789056h2-387946935229461d45407106687413h-4.4233577741497783e35019704672001t9.367462308364 1.52095590i4797v>+3086948449108+108.13202178436.609344579500hbd*4752552227790-3. 93La6651046885639665089DH34480761042687 -1.0577303880953903 -6.45>681573561e 45200719662046 -- values near 0v21.8566986970714045e-3200867567604021 /m7.9050503334599447U38931816251424378/8..m465908125712189U2.465406509721/n-6.101691640819261nV2.47032822920623o2PJ.n'`3.4305v2729e-311 -> 1.5#707963267948966 -3.4305783621842729e-311 acos0225 -0.0 1.6117409498633145+9 -> 1.5Z/Z6ZY -4.9900630229965901e-322Z.Y7Y-4.48892792105928181Z.Z8Z5.3297678681477214T!2  40.0E9E6.20734258972116E3jRE"30E940656458412465/24#31F1.7107517052838  -- special values31001-GC1002-c32{d42_?nan04nan,1-2.3 infbD-infc2111S0-> !&-> 3.141592653#G931 1221c8]1">G"#-> 2.3561944901923448--T78539816339744822.&- ignore-imag-sig16pJI2 2[ !2""Cf9- 2c17c2c> 0.0 inf ac os1031 acos inf -0.0 -> @inf B1032"-#> 2.3561944901923448B232,T78539816339744822425nan 4nanT5"02.3 "6"v"? -1 --Eh: Inverse hyperbolic cosine --NOQzerosRh0000_cgn1.57079632679489662h2-4hKg3h branch points: +/-1121.0 ## o50.0%&3.141592653589793{3 Y5values along both sides of real axi2 -9.8813129168249309e-3242G I!_e-305$6nh -1e-156njh -9.9_8e-17 8C#27qF H8H\0.001}1u9615634}95 l73fY0.5786z2.188297Vd120667zC E^09Z386886319kC Ex.C22.1073424255447014e-08 U )3UV-W1W 0.044717633608306849 STacosh0038 ac2osh -2.0 0.0 -> 1.3169578969248168 3.1415926535897931 acosh0039 a B-C-D%40D3@3.82}4713331012)41CD 2E+107.534508668464674 3R S 4T:9.9d8e+149346.08091112966679 5V W 6X+1.TU1e+29689.16608998577965 7V W 8X9.8813129168249309e-324[1.5707963267948966/49F G-H5o1e-305}5 5lU1e-15 5l?-17E[0.001{"69T628235|2 h4X 0.X6t0.95329467197772655wUC E6R0;4901161193847656e-086cF /1.H t 22.1073424255447014EFG447176336083068lCCk\>0.0DE 50.022Kh48 acosh 23.0 0.0 -> 3.8281684713331012 acosh0069 0 23/4D-0.05#705+10 .0]w7.534508668464674B1BkCD2D:9.9`8e+149pG46.0809111296667F3F sGH4H+1.Q1e+29tG689.16608998577965F5F sG -- random inputsZ$10-1.4328589581250843 -1.8370347775558309e 1.5526962646549587 -2.190250RU35786a-0.31075819156220957b`0772553`839297b0.951391682861937y1.7812228089636479d-1.9044776578070453 -20.485370158932124c3.71774110803596633888745861227bN75642506000858742 -21965976320.873051d24.505907742881991d5707963267983402d+-1.6162271181056307 -3.0369343C9609940705726*!22042954946175020(G3780280298063o001805488 0789>992877058761416 1.8863869950967286-9159468751.5897655 5.80147476642736423.631201197959193 3.141592652956407`7`0.0377391575509P21841357493510.21685844960602488 1.60767351334498d8225991.05083940.2831854300891364S16.61595652042028719164101bp-35.620p0230263313032370050154.2658980 43"3.1328013AT41873196.729939906820917 29345228372365335b 04q5863548,@0030Z9586697284g`0.5965V0 642.041229&`1639781.492300202428783531256842190m109.293841126778215454863061533812d5.387166296 7j4141245154061214e-018.67056519693|6(31649787462.93361809583/5/40267362031871.810164644505268680123451327218554-1997148566285769,@0818 2760150265f 52.56897195025288 0.0011813916065985443 -> 4.6551827622264135 2.1193445872040307e-05 acosh0116 a  0.28336786164214739 355643992457.40485d27.290343226816528 1.5707963267940999`7`73876621291911437 2.882859454110Q@e-20d4.27748209781590670.73955845836827927i8i025865471781718878 37125746064318.492f31.93847898941801268959a2.2047353511780132 0.074712248143489271a1.4286403248698021+3799790497162 -- values near infinity3200|8.1548592876467785e+307 9.0943779335951128-> 710.08944620800605 0.83981165425%54j1j37229680972531R8 -1.033696661787485k8k4543331094759 -0.62T34875z3202j-1.5014526899738939k1.567070037844879266420706795464 2.3348137299106696203j@0939b752139'`416960J279730182863115886 -2.38063614778703204k0.0 1.47606243355958T27873384716929y%665T-U6.207721032622h709.4125645748476V 6VU62189990996830p33544440734'890-8.D6248338391270971018048317X @1.30975249934R8X10.1568668010722K[ 5340214026F833747422926706H1-6.901137599229I709.5184569971$ 3.1415926535897931V|-9.953957|b926973VU> 709.884740958701Xj`7.6449/u1891492>570654076826835009.41731754802518906916769345e-30i1i5.432541:c6021977.806480792Xp27917775 4369851312471974ig-1.1523626112360468 7.061751003886933603117010216909 x1.168502778686259!-5l55835792562!=0450790757143.0236370339788721 1.75=720096417e+308 -> 710.44915723458064 1.5707963267948966 acosh0217  6.6108007926031149 -9.146996822H149e+307 -> 709.80019633903328 -f8f-5.1096262905623959 6.448492678541 f45061713997973 9e2.80809206087358467716118836519368f810.46124P63445/ 2 -- values near 0D#20y4.5560530326699304e-317 7.3048989121436657|L%21n8754274133585331V4A8469p76841995/9.p2p-4.674887600992 9.7900342887557606po3o313687153839923W20 -4.940656458412465g 23q4q0.0 4.343101386649677["14[Z5Z-[6.0147334A2918[M[6[Z-1.288029138708129*/> \-1.440156397653462g] 1.368968057086309W!3 >F1.530434689349437F"2 G3 -3.7450175954766488e-320-H3-8.4250563080885801\sspeciald]4100 5100/3.0inf4100@2.3 +!->2h3Af0nan5nanRU0-> #$-H1-]'3.141592653589793113[3h inf 0.0 -> inf 0.0 acosh1013 a2.3 -> #4#-<$2.3561944901923448V53.20.78539816339744823634nan5nanV7#$8$00.0G G9# #'20#F'21#?0-> #2#>| -1.57079632679489662-05/i 45jo-3.1415926535897931<5o53A43%Y%+K*3/4,3q }3- $}$? - -- asin: Inverse sine --23`zeros 9A0000BtNvsin0001!" D2#I4-> #3#$  branch points: +/-1=141.0_00_{123>d2Je values along both sides of real axi sin -9.8813129168249309e-324p K L!M'Ue-3051)D*+4U1e-15-)5)DT9+6+:9.9U8e-17I7I tJ K8 asin -0.001 0.0 -> -0.0010 167416 0.0 asin0029 )8O9%309H5789`F61750165481717001|/31CkD2EP99989lD1.5707963118937354B3BjCD4D!1.l2j B267948966 2.1073424255447014e-08T5T{U-V 6V 3 0.0447176336083068497R T 8T?2.0 `1.3169u6924816=A C4/23 @3.82{47133310124B DZ 7.534508668464674Q S)9.Q998e+14346.0809111296667W4U W N001e+29 689.16608998577965T U W9.8813129168249309e-32* K5d1e-305'a)U1e-15'P6)64-17G~)q{ fIp '5P( 6l58 asin 0.57(89 6 0.0 -> 0.61750165481717001 asin0059 \ 0.57A-BC$60CP99989i1.5707963118937354@1@gAB2B:1.02g @267948966 2.1073424255447014e-08R3RxS-T 4T +0.0447176336083068495P R 6R?2.0`1.3169/u692481657? A8A3 @3.82w47133310122@ B71H0 5-> K37.5345086684646747O Q)9.A~998e+14p46.0809111296667G7S UL_1e+29 689.16608998577965LS U -- random inputsg#10-1.597955583 083 -0.15003009814595247 -1.4515369557405788 -1.0544476399790823b-t488225895317679 -9.6080397838952743e-13f246024460412851g17423800540040/#10.-3.650808793051624936027527093220152f1.4685890605305874e974227300715203#10=.@23863p23268196113516996364a00.891147275,@3223es0568919#10J-1592.063904555530672362427935018236c34180711751Y8.065933691872922Y@9835W 71312019 4.2131508416697709aEP57778@9935}2.1461732751933171X-1.918471 30213 0.4060330507977923% 1.3301396585791556 1.302Fa231498]n0107 asin -x254495.01623373642 0.71084414434470822 -> -1.5707935336394359 13.140183712762321 asin0108 asin -0.31315882715691157 3.9647994288429866 `0.076450403840916004 2.0889762138713457 b9b90017064284720816 1.25306594859071050.534665097419 1.170281155757^"10^2.1615181696571075 -0.14058647488229523^1.497616632389687134085811039334604"11`1.210474921070779`85732484485298999`0.8391307N`343924a068171925052590$12a705973318512889184032966373156581a1.0510900815816229`P29679t13616523`9.91370850172906875460838397025089 2377048202.995414677560686^4^`117.12`5104145453908091.5334012.147514141139be-08 -23.1127454502&c5c@0.08\187798029227 0.06705434986017319-0946786856771813-2239910606396986e 46.635472322049949 2.38351r8056678519719494001 4.536698960093]7]P3907.z 9619.1440218863901965233083235 8.9637018715924218]1 31 308273 509.0157788355476P0.002{803817829316 6.925629449452470`0.1085c277509224 1.5612d821747|58491014243902621p2970757g1327 -- values near infinity6#20 1.5230241998821499e+308 52289940845257`2201442 892068 710.3728348653596#208.133431769867O9.224942c872451>2259991284020042 -j096245304-P85066B1768Q6.7015445269-0.976375117421945940688748667137R#200-1.f@2988{@3842iP8 -5. 05F1419-1.20593190551605'30396478954626#20P0.0 9809297789743UP709.8P44105c-&@6.80255193975 0 F`504639D3489FE-6.499751645479821F F0458c'#59,#20-1.67674490%52?>0406210180302G5.42427499573789166326794896627765497888902 asin0209> asin 9.5342145121164749e+307 -0.0 -> 1.5707963267948966 -709.84165758595907 LB0210U-7.0445698006201847VU-VU53902780872136 U1U1.0016025569769706U8V9095709697881W2W1.6552203778877204V0.48761543336249491710.39328998153474c3c248571283038486d8 -4.3489311161278899c-d1113557467784c1178428133531255.123452666102434b. b3026464192303)5c31676343130080152939679793528982f6453260239768-6g0.80843929176985907 1.015085182776787z > 7.9642507396113875e-309 O90432835561637h8.2544809829680901 -1.742354814053947 -> 4.7375430746865733h!8 Q44459'52168i-5.2499000118824295 4.665557897751221i761252459249113292j7 121$0399h9904782760833433bP73156ep4781163i2660659419394637i414102757522312 -- special values~4100"->40.0#0-> !tEFMG# 1infcGk4infU2I2.298 A4nanr 4nanboa06 SP2U78539816339744828 12 1T&0 1-21 ->O ignore-imag-sig`1.2TH0?kC`\02aQ 2 asin1022 asinY 2.298 nan ->nan asin1023 A inf!ignore-imag-sig242@-0.0T1.5707963267948966 -infd52?-> A 6As 7"c 181N4-> 9#O2"302U78539816339744828"3133N "32#?> -2 34C -c4%(? -1 --&h: Inverse hyperbolic sine --JKQzerosBh000h!50.0##% 0 %hM%-> %%?qbranch points: +/-i?11/2 3c4 4h 5j values along both sides of inary axi2 -9.8813129168249309e-324P 2.N! O4|`1e-305=+ +,i<-{Q1e-15X%152\,X-X)9.Nu998e-17x-L MP0.001;@0016E74169,:u;t95786H61750165481717001FG H099999989 -> 0.0 -1.5707963118937354 asinh0033 ! -):0.9S89 ->F4FE:1.02D2.1073424255447014e-082679489665VW-X 6X 0.044717633608306849 7T UV8V2> 1.316957896924816E 9C}# -D-E#40E> 3.6882538673612966" #41DE-F2F?1h0> 37.534508668464674 T-U 9W0e+1Q> 346.080911B/67g 4X-Y\Q1e+29 689.16608998577965\ X-Y9.8813129168249309e-324 g4"-L M5*`1e-305;) *e+`1e-150*T5150) *T+G4-17dt ,JKP0.0019 8 165741'5d+8q9D 0.R6F~61750165481717001 <DE646M0.99999999999999989 -> -0.0 1.5707963118937354 asinh0062  '02B2.1073424255447014e-08T267948966T3T| T0U-V4V0.044717633608306849 5RO ST6T02.0D1.316957896924816= 7Az B-C8C-> 3.6882538673612966 9BC-D#70D>17.534508668464674#71QR/-3S 9.Q8e+14E346.080911:/67W 7V-W TQ1e+29689.16608998577965T V-W -- random inputs$10-0.59464028537104234450654890145:-6459775392653022.3825622144153635|'10%1935395804616; 1724793193454i19237926804196651.171741895336792;33117585138955893 -8.5256414015933757h2.8327758348650969 -1.5668848791092411eK1.5184043A3571734912453390732751.271589141976400539204624408542355eY-0.60716120271208818:p2890074KR43654119299421187232474593167811813gk237177865112429 2.8832601052166313.1.72058207724132362026170296309$10{-2.39068123427a63492168485740a9609636249445124 0.814214266057470\027605019787620517 183.85588476550555.9072920005`707813fF4787-0.9908366116440471328006797051617648)0.8750185251283995 0.019894099615994653 asinh0109  -3.0362951937986393 0.86377266758504867 -> -16030714685221 0.26475058859950168c#10c0.34438464536152769 -0.71603790174885029d0.43985415690734164,015037409294324e1e4.4925124413876256 -60604595352.871613c25.52078373861 570796326720768)#12a2.3213991428170337 -7.5459667007307258a.7560464993451643a2%2108561173`0.2129193974168202872042881478440a0.77275088137338266+3182099250896895c4c6.644735`455957\97196191666946996602830695139672*1436824741231996b5bP7.132}655083746 2.15163P27068u> 2.7051146374367212K9051701669%816``0.1884] 905063442 3.47053485853398321.917697875799296 1.5141555933479D7^9065075303281598621681454822201_@0.19 p5078593+0134228096148c2.024200466573{! 0 028164749578n1.497036621289600"30526007B 37.336596461576057 717.291pp1678234!7.269981997945294!87910219; 33 -- values near infinity$2001.0m17500874541e+308 1.1497786241240167P-> 71346055651818185093696179347c$201.1784839328845529R01.6$29586716638k62557836789499631173560,-4.877768224890T7 1.4103736217538474-28970147376992 1.23yfT09644$20P-1.28H8903233101.573239261315569!> l0597xp4290745886571814%E2452 0.0 6.8431383856345372|709.5100171844460"e948966U-VP8.6010q3223805U-V73874482126689sVP0 -5.39606730L 30413698733742  p-7.1507q3462180 558~?705Y 1.60251361A39346p2261076K1.392781985823911010.2206589!89R0 asinh0210 *asinh -6.0442994056210995e+307 0.0 -> -709.38588631057621 >Q0211  -1.2775271979042634H58 -I10.13428215553972J2J1.0687496260268489I1.025561569947696195584521407841 9.5959010882679093e-309i3i050967333370962i-0.87668970114433k89443961168183 -8.7224410556242882l4l-5.716145281486239m7 8.2377808413450122kv 3006540611166 1.441142664)0116k75k8.200904072765331-6.407409526654976k69101513070109 -7.8130526461510088l8l6l 6.4239368496483982 1.6365990C1427V> 710.38197618101287 1.5707963U48966d7dp5.472910882m1227237438144211e00511346983546/f8f-8.345581829741]r31720201820110.25619930551818 9e2.6049726230379@7952q4402270810.474488476856440  -- values near 0E#20z1.294011333966414 6.91691904177745U23s2.384847:874649e-315 -3.1907655025717717n4u=-3.00976436796416216 4.69362363549184m4uI-1.787997087755751.#6228349023414uRW1.2491433448427325J4;K2-P2.50241545380690 M,-2.96439387504747W M=2.939690592755416J2GO!O5.6404293002935G1G3.3833911866596061 M3 -4.9406564584124654e-324f Mt-2.221137922799484(> -2.22113792!27994845e-308 -0.0 -- special values asinh1000 A 0.0!->6G1001#O $ H2%B!->| %3%*& '4'0infp1.5707963267948966252@2.3 +!->262d0nand5nanU7#U0-> #8#tJx>9#J#1F#785398163397448281/31 F Fmi ignore-real-sigN1IN1-m-14yo1- %2 ~/0.2212~(2 J{2>>6l 2Z$G H 3 37 3[&340%%% ^-z atan: Inverse tangent -- 50---U` zerosBThese are tested in AtanSign_cmath.py5w00tan3-- $1  9 &2&L3&+</N along both sides of imaginary axis -9.8813129168249309e-324 -> 0.0 -9.8813129168249309e-324 atan0011 -0.0 -9.,? ->! M2ML`1e-305;)3)v*+4+E8150T4150)5)D*+6+T:9.9U8e-17dI7Id+J K8KP0.001903D5333797b880839"209b95786~660957090286630{2;/0.CD20918.71497387511852KCD d.221.5707963267948966 -18.368400284838552P-Q1P 3.8007011672919218 QR2K/> 00.5614433405489 CD32050041729278491263EF1K  C#3VW *1+1461e-3J K ;_1e+29 y0'3T[\ K + 24 atan0040 atan 0.0 1e-305 -> P0041 * -()2)(7150P4150'3'A()4)P:9.9T8e-17`G5Ga*HI6IP0.0017 03D5333575_66063787_95786z660957090286630w9@iAB"50B D998918.714973875118524570ABP.)21.5707963267948966 18.36840028483855 vN-O1N !3.8007011672919218OP!2.0.54930614433405489AB2C?->  05b72927849126CD61; $6TU )1+14/A61e-Z6H I 3_1e+29 v9Y6RYZ -- random inputs#10-0.32538873661060214 a530461550412578 -1=272842755422769451401598762041c 45863393495197929 -4799.1747094903594c068820623c0002083691605063614 #10-8.3006999685976162 -2.678889025179093461986277181010.034811669653327826 atan0103  -1.88363076829853141441976638861771 ->839984370871612 -0.20630956157312796b4b0.00063230482407491669 -4.9312520961829485f5707692093223147f563867743008304f5f84278137150065946 179012.37493146997b963267685969 5.5862059836425272e-06d 95487853984049287 14.311334-d661322859434561 0.0696760245262320057b1.351325253964 9 6.0500727021632198e-08e0.93371676315220975 2.140800269742656.g8g566254458595795 0.11O71944159823e205564637111,493405387141732c9c058548795408559 0.644389654232128668361089300233124 0.46759762751#49c"10c48.479267751948292 -78.386382460112541.565088877091059227681137329758U"11b1.05753739140560617598801237729698U0.94430886722043594,319156981267031182b4444810.4P7720365655340459394255& 1.961018134231 -2.86437701909e-1@0.01P40508p0009f03293266855028247g.01203-41214776834911.5353585300154911947099346796519R1.3400310739=*299960036074490410.2186945770882 9.9_84254007098584607887644M0100*@8817L0.177832901502443346898636509517668728064286277,`243580T87384>115.757474087615918 383.572621425h!> 6894060369628026026817278826603H10.58701^P533312172023808184343Q1.47681336236019199097383010061a00.807867878120V2301486093595020.714725P534920`1221953 605 -- values near infinityy#20 7.p39701118e+307 8.16S74630-D7948966 6.3439446939604493e-30%205873698696131487l80780367422960641m-2.9279309369781n-1.5844551864825834V1.02906578090986752.88296146 n3 atan -1.3168792562524032e+308 -9.088432341614825,7 -> -1.5707963267948966 -3.5499373057390056e-309 atan0204  0.0 1.0360465742258337Z8ZY9.6520757355646018X5X-Y045063210373196Y9.955138947929503Y6YX-9.51552967157636Y -1.05091364802018 7Y565700490496501 -6.42438161141890718\1.295633938954V/> 40.09D440812624377215EF"10F 63178646193641F K&11Fp5160569BB1069r8G2H1.236162R03838F4.6827953496242936T& "13R7.00051647289721R7 -5.8631608017844163S$05344400333850V8 5.119919726842031U/C!1.39917251814725B3.5687767U8.1252833070803021 6.278295391734382P,1.5927890256908564,1,2.8034285947515167337804977575387%--7.4749310756219562i19-1.4073509988974953 1.677638178596835 {5.960760i364569i^-2.71355515275921192815674455257r7.802944772756532r -- imaginary part = +/-1, realBtiny%30Pe-1500-0.7853981K744828 -173.04045C8333D#301F5ED178.79691829731851;9.9Ue-161U-184.55338102980363V-6190.30984376228875E8886718268302W-368.76019403576692 Additionalvalues (mpmath)|41.79769313485L0192rG-H1348623157e+308 0.0 -> -1.5707963267948966192 atan0402 ` 1e-176;1.04715!939-:-;4;0g1u#096P73459"v5;-.<=6=#0.ea0.7853981633974478100.7B  B`886473`8B4.101419947141.46B9B255.765591500789*57"62 -- special valuesUB1000UI #1#4nan" !K81inf divide-by-zero2D"*o2;-242.2"8AA@4nanq4u$-_A#21 30.010-> 1*1q"n{ ignore-imag-sig\1>d!->Or q1!)?-> . 10?kC0k?2,o 220}!_2r 2`6#Q2IH4|Aa3w67948966 -0.0 atan1031 Y 2.298 -inf -> 1.5707963267948966 -0.A2A-2325nand U4#hm 5%61.0%divide-by-zero464"Q?> - 74)C8C0|494rC#40C/w? -1 --Xh: Inverse hyperbolic tangent --PQs These are tested in AtanhSign_cmath.py6Bh000 h i$-> &&.2000h!> P(QR+values along both sides of real axisDh001 -9.8813129168249309e-324?-> M-N!Oe1e-305+H-h -1e-150X++X,-h, u998e-17h/9.K KxL M4%01 0.!03@533399Uu:;2XY0.5786dH6609570902866302ODnEF0w918.7149738751185D_DnEFx.v236840028483855QQz RS1S 3.8007011672919218966 atanh0027 atanh -1.0009 -0.0 -> -3.800701167291921805707963267948966 JD0028TD2.0 D0.54930614433405489 1.D9DE-F%30F3043505688494814884)31FG 2H+10(9.9998e-17 3W X 4Y<E+149o1e-150 5K L 6MKV1e+29 _9e-30 \] 9.88131291682$24Qe3!, M4(1 5) e+)TU+ |%dI+uKT0.001; >3@53337i*k 89DY0.578,6a0.660957090286630{;BkC52018.7149738751185BKBkCDd72 p18.3684o4838555Ow P5 [5PQ 966 atanh005+6 atanh 2.0 0.0 -> 0.54930614433405489 1.5707963267948966 8G0057B-C-D8D3043505688494814884 9DE#60F+10:9.9_8e-17/61UV 2W;D+149o1e-150 3I J 4K+1.@U1e+29 _9e-30 5Z [ -- random inputs$10-460925980633501 038050126721027:-0.41984265808446974-60354153938352828g-1.693461426982905f48807386108113621f58592769102243281 -1.353783747097589e($467293985 07`478683s5395876e69961624370709985e199445015657007$10D0-5.232418984888 -544551613.39307702d1.893265755a1744J495852351`11841460381263633.2599788998233>001018393654740511.2731614020743833mg073345736950029532 0.358219496709222480.0065004869024682466.P43993f192089-13.866782244320014 0.9541129545860273e71896852055056583227046314093-708.59964982780775 21.02159266675c0D`8779070741d70752584283895d-30.916832076030602 1.36918971388298432292682045743676c6209484711*9}A7461`986175+479744391306e56467464472482765961561282417262e10.400892467374156J1.6322859,0.1063832707890608'040282133532648212119.61676882621v1.5383653437377242e+1Y@8.95XP851830/2i$11756.86017850941641 -6.60640871303223817 -> 0.0013211481136820046 -1.5707847948702234 atanh0113  4.0490617718041602 -2.5784456791040652e-12h25218425538553618f963267947291f"4 f10.589254957173523 -0.13956391149624509c094700890282197664d695407140217623d5d.0171187553160499 0.7076611346535401c55260251975367791 0.96619711116641682b6b0.03164550252775084d0673199837265443943151301834408674267285437670549036g7g 13670177624994517 0.4324t5hep1153893k`017253+1392008145336218c64173899243596688 2.9008577686695256b06568014242415 1.2518535724053929b19313813528025942 38.7996191507418600012820765917366644 1.545029223612 -- values near infinityB3200}5.3242646831347954e+307 1.37403960800841538p2.45192576e-3094707E8966n1n1.158701641"#58U6.55792688733758n6.53653752~B5098no2o-1.3435325735762247q9.89473692596015p-4.825668090658995"0-1.$857522598942p-9.470120470239100g0-> q 53262872645.0.0 5.661418101849(-(@6.982721450139G H -7.497061306031YHg p)28060188031406.>0qP8.221j336000745>P16256`954813{8  1.A51961728089/8> 6.7515017083951321@-1.216263598788-8.141985636053761]1-1.06164277042619364239948x9p 1r`1.2971s101806825.2\452333293P7.70951099832k1.18498609774118517.9781906447459949 ->( 8.4389175696339014e-309 -1.5707963267948966 atanh0214 $ 4029969422586635e+308 0.9U986543663375 -> -7.127599283218073lk5k4.7508098912248211k7 -8.2702421247039908k2.104904264527804l86m8.2680742115769998 8.1153898410918067kO0.0 7U1.25753251462188854746679147661649V 8W-2.4618803682310899 1.3781522717005568W-X9W4.0952386694788112b3376353703W -- values near 0E#20j@3.803659811628e-314 2.P4842390743192r3s1s1.739111073361187s21 -4.35478006725414t3t4u2u-5.96568160813250v17 9.9692253555416261u4u3u6.560667117840023F3 -2.16809364063573355we2.523094440182077z9LK- 5.569490064650L ML12C7249468377Y Mz-3.086110zQ20603N6!O3.1219222884393986!0 /> KQ9.892vp6497619KL M3 4609291815"$12 Mz-9.881312916824930224 M/> !  N real part = +/-1, imaginaryCtinyy$301Ae-15X176.4943332043244p7853981e744828EE:9.97V177.6456082149 0.VWa1e-1616185.70467357630065G F-G90.30984376T816339744828 atanh0304 N -1.0 -9.8813129168249309e-324 -> -372.22003596069061 -0.78539816339744828 -- special valuesmC1000m@0.0 !->50.0#1#0nanz*5nan#2#a-> infJ divide-by-zeroG3GC@1.57079632679489662,12.3r25d26#U72Y282h29221 # # ignore-real-sig1I0-> l-1^1^16-@l`1+4th-m24 2 $L $2'>02'.M29& (2l 22u663Z36S 3636  3%  3 7?1,40lhinf 2.3 -> -0.0 1.5707963267948966 atanh1040 ` -inf -> -0.04? - -- log: Natural arithm --: log00003P 1.0 !->30.01 !2!-A3.1415926535897931/3/E Q1-- values along both sides of real axisY1 -9.8813129168249309e-324f743.74692474082133 {1S-T-U0Ve-30502.28845336318398CBC4Ee-15-345.387763949106845BC6D:9.9U8e-1736.841361487904737R S8TU0.0016.9077552789G69AB2Y0.578,60.54645280140914182PQ091.1102230246251565e-16c2ST.22.220446049250312 QR1S 099950033308342321JQR2969314718055994529?@3&233.1354942z_914973?@1C00000.0 0.0 -(> 36.841361487904734 3.1415926535897931 log0033 log -10P.0 -0O-P4P:9.9t8e+149 S45.38776394910685R S6T+1.U1e+29688.47294280521965H7R S8T9.8813129168249309e-324K-743.746924740821339C DE!40E`1e-305\ -> -702.28845336318398212J34240150K3330.0201e-2J346-17vAvBjCU0.001u6.90775527896Q_1Hd2d>Y0.5786r0.5464528014091418s;@eA580 a-1.1102230246251565e-1CIChD EZ 2 2.2204460492503128iAeBxq P0999530834232AwAeBCv%2._0.6931471805599452/t/Dc01r&23a3.1354942|A9149d/a/Ea016PWu6K>c~?~F GBkH01e+299 0.0 -> 688.47294280521965 0.0 log0065 log 1.01e+299 -0.0 C -- random inputsV6V-1.9830454945186191e-16 -2.0334448025673346e0.70973130194329803 -1.5707963267948968c7c0.9674585302474185784995816228299692a252928113987223874207570438536905a8a1603644313948418`2929942111041835_-1.0965857872427374_0715870859971419_9_59179131684386v 2599251132177a`209347%`249901a1334784232033863a$70a 68907818535078802 -3.069310834761.1460398629184565791640381391_1_`17.26847565589 6.81651200O2.9212694465974836 2.765624508d3164\2\.7153894479690328 26.43405537280263: 3.2767542953718003 1.63554173\3\P8.045S 648936578e-06 0.19722758050208-1.6233969848296075 8371206810104b2.4306442683173 0.6846919750700990.926335920969D2.867016057671833]-3.5488049250888194 0.453240406431852541.2747008374256426 3.014564004511]00.151685151018 2606251883611421287121940344955584408411834}2.7124837795638313.148769067133> 2.59716;A5706q1.36735YS20943R73.6521275476169149e-137820543023170673e-02658136741569x1713843165.0877544Q862233p2834978A8685u1.6576856213076-0.247115/S73848u80.26477986808461512V67659001194187429`-0.319l520799997719777367198 0.16 071962 5.351!60*4p7737117B38295206219261802^Q0.29646215788q002005604504258479~ .2@3366058800676031141686892080.821042305 3.9005387C0331> 1.3827918965299593633304701848A0.27 5358180667 124.4208811094580]`4.82362n268604725878901{2628695916826740580o@5730>P73821]37809126~65360960087values near infinity lo%g0100 log 1.0512025744003172e+308 7.26216697506646117 -> 709.44123967814494 0.60455434048332968 lof1f5.5344249034372126N1.21558591584312758g8562300345679 -1.143553056717973f2f-1.3155575403469408N1.161079354166386475847809546428 2.41848796504974d3d632366720973231.5429944621144zb10.0054523656 -2.3843326028455087e4e0.0 5.9449276692327718.67616191258526 1.5707963267948966Q5Q-R1.120185045902569Rl30970253338171R6RQ-1.62142259334665209.67951255010867R-1.745326979159105S753150560873T8T1.4408605776014 5620058262 0.099A391515176148283B2266WP1327 C1b-1.201354401295298k3l 823023956 3.1415926535897931QMw7043378259768070929198492399 -T;7.2276974655190223"P7 7.9 711369164P8.871p6512104F9A9307aS8e-301:785959371607-6.19562008682=9.31023883080f-5.5279244310803286gk1<-4.667893387447104P7 9.9d22038243433142431388~K01.5~p1245395V+8 -5.311719b375619bP9.608Q7835008\ 7.)7p15044353207037766263562282865085137.1j5.9760325525654778 -8.0149473997349108.97493177248391x-7.88019420o629 1.786184581476744Q~77629046837 -9.88643899385 GP235780747J8.71693946977302 -- values near 22.2996867579227779{# 6`077093Ae-31\-708.3634356771739`002950916622333981526.91691904177745123 -9.041401318894811e2k!39@6796Ep 4944423210001669 log0122 log -1.5378064962914011e-316 1.8243628389354635%0 -> -713.20014803142965 1.5707971697228842 log0123 g2.3319898483706837e-321 -2.2358763941866373h9.9045008332522h6337224766g4g0.0 3.87277010108112P5P23.96033425374401632679489Q5Q-R9.63428009390430762S39.167072,O1752S6SR66099393427834e-308R08.37814861757] 7S-2.11846956737666214.5636103673181K U8U1.13635098543486122 > -741.304577705452069C3.557272650056975D0.1634058023620.0E!30E-2.3696071074040593E12.93865466421641 3.1415926535897931S1S1813Q72669217 H28.88512203138862 -T -- values near the unit circlet#20J0.59j8 0.8042.220446049252e-17 2.2n74355881808b:0.7`j93 0.6` 09a6.1629758@9154.4350110879328448 sspecialu&100VO-inf{ divide-by-zeroG F7 G270->  210012.3'. \V/ :^0nanG3nan M0->  D9 1=blog101/  ]2101Mx m2.3561944901923x*.0.785398163397448252101x+9 x1x y8 1x 2wvg 2W!> =4-zero log1023 log 0.0 -b> -inf  divide-by-zero log1024G?!> 1.570796326794896605032.3o0 60Z1 71b81]  3.141592653589793191g1!301Ua20.0R&31!Q!2!Hs2.3561944901923448R+00.785398163397448212nan0-> 3nanQ-  q ? - 0 -- 10: Logarithm base 10 --> At000eb10 1.0>D"f"Q# Fix G1.36437635384184142j2K# -W4-- values along both sides of real axis\1 -9.8813129168249309e-324-> -323.0051853474518 }tlogt001UV-W:Ve-305005.@1@8~9rzEe-15 r 8r!15::9.9U8e-17/16 GHIU0.0013~ 5m6l2Y0.5786z0.237321436272563832ST094.8216373327664362UV.29.643274665532869 T-0.0 -> 9.64&32746655328696e-17 -1.3643763538418414 logt0026 log10#H0009p 0.0 ->004340774793185929 S7S-T 8U02.030102999566398129A B%30C317278360175928)31BC2D+10?6.03C D4E(9.69998e+149 15/35H I U1e+29?299 HI9.8813129168249309e-324#-323.00518534745183EFG4`1e-305aD 8((C)*U1e-15 Ro(CRRTSIP-> -140.07C7bq892V0.001 %?M LY0.5786Z0.23732143627256383CCkxDE50-4.82163733276643'R5EmF".F@0002EO9.64>DkEZ1F fCjDr v~1Ig 2 -0.0 logt0058 log10 23.0 0.0 -> 1.3617278360175928 logt00592-34#604+10u6 313[4 525:9.9`8e+1498540.0838 d9:4:+1.U1e+29r:29958 dr9 -- random inputs6L-1.9830454945186191e-16 -2.0334448025673346[0.30823238806798503 -0.68218817692092071g7g0.96745853024741857984995816228299692e1098452842228 -1.051321426174086c-0.1603644313948418b2929942111041835a-0.47624115633305419,89967884023059597dd591791316843869925238799251#77f52521304641665956f92655790645688119f7Q 907818535078802 -3.069310D547649771878850664477809953119328823c"-17.2681 7565589 6.81651200146047P26869 8098534 1.2010954629104202_L-1.7153894479690328 26.43405537280263Q1.42307630&751 0.710331-e900530!s-8.0456794648936578e-06 0.197227580575702087050323524498756g6822058934805551R7-2.4306442691323173 4691975070099!0.4257845332595&4512925337489-3.5488049250888194 0.453240406431852540.55359553P41063sm8510886640500.151685151018606251883621Ob960201973291363K@4150=5566043072.7124837795638313.14876906713338P1.127op61331700.5938361664380323.6521275476169149e-1378205430r0673e-0 4.:722398941112y27271711405.087754581386>x2834978326786857199237180642684107321043521x80.2647798680846157659001194187429@138793528168152018649631300228 0. 75+398071962 5.351!6074P28473r 81@682098178033 logt0082 lo8g10 0.29667334462157885 0.00020056045042584795 -> -0.52772137299296806 / 9359659442937261 logt0083 loi82104233671099425 3.9005387130133102e10.689028349361 0.59208690021184018a4a27268135358180667 124.42088110945804a2.094894315538069 0.68123637673656989_5_00262869591682674+p4779580r 57b-0.32060362226100814e7979964816877081 -- values near infinity~3100~1.0512025744003172e+308 7.26216697506646117308.106415626820626255461408256i1i5.5344249034372126Q1.21558591584312758jO106009209)496638782296212i2i0-1.575403469408Q1.1610793541B"640-> 24419052091019 03359777705266iy-1.63236672097323q1.542993144gP351454093 -1.035502492430 5.9449276692327717.7741465750111782188176432075$10u-0.0 1.12018504590gVz0492897706846V6{U2142259334665220989622030174W7W-1.745326979159105X418768020353(X8X1.4408605776014158621959087509D39151517614828CE4348794720007F1-1.201354401295298107967114380773 1.36437635384184141q@7043V 5922282926451624W_7.2276974655190223FP7 7.971136916307.85899996571993 4.7762357800858463e-30t$11\785959371607-6.195620086822114p8.0495269455 -2.400747076796 j_-4.667893387447104P7 9.98C66912092839902m1.510801245395k48 -5.3117197179375619P17920>O1565 | 7.[750871504435 1.532070377662635@8527.6 15.9760325525654778 -8.0149473997349123e+Z307 -> 307.90390067652424 -0.68218817692092071 logt0118 log10 -7.880194206386629 1.7861845814767441e+308 e8.25192633617331 d9d9.886438993852865 -6.19235781080747c79185604308338 -- values near 0#20v2.2996867579227779e-"6.0770939125e-312D-E63833129662572 0.00012815668056362305m1m6.9169190417774516e-323 -9.0414013188948118n21.04249706727144902805353306059l2l-1.53780649629]16 1.82436283893546309.73888878263225429998942k3k2.33198984837068371 -2.2358763941866373l12.65055220919641081445384m0.0 3.87277010108112V5V4.41197828323476|#25U-V9.634280V71618073175 #26WV66099393427834a2-> I4472104545649 #27W-2.118469567376662167397777<21.1363509854348621.944487507098193.557272650056975 22G44888284668453-2.36960710740405930t09.62532365619722 1.36437635384184143a-2.813Q72669'17p16.5507961042 -W Zthe unit circlew%20J0.59j8 0.8049.6432746655328709e-1.9616571575684681a$20:0.7d 93 d 09e 2.`463916P22e-3.p2794689:`75476 sspecialL(10?inf divide-by-zeroJ IB: J:0-> 410012.3+2^3jfF0nan4nan6T0-> "1008 log10 -0.0 nan ->nan logt1009 log10 -2.3 #$10#@inf J0-> 1.3643763538418414U(112Y222Xc40.0T3"S"4"-Ev0232822653813811T52-10.34109408846046035262Q9Q#17"#8# E "2"" 2u-!> - divide-by-zero2DI : J8m-0.68218817692092072* 4 5jeP4n4 3g#3$W$%|I3.3K3 3 3#zF? - -- sqrt: Square root --01 s 7A0000@F!1!c>- D2##E3"'-#  values along both sides of real axi1 -9.8813129168249309e-3243.1434555694052576e-1621Jk-L k1e-305622776601683791e-1539 t; 4WQ0t:9.9T6e-76s58 s: 6: &X8e-17T1e-08q77 98 sqrt -0.001 0.0 -> 0.0 31622776601683791 sqrt0019 q -0.00167%207H57896oD0.76092049518987193y/21B{C-D2DZ99989 3B D4D:1.0241.0u51 t363 d0049987506246/27? rA8A2O1.414213562373095rX1 c33T*23e4.795831523312713D2 f4410)3,: }!<$)9.y998e+14 #S3e+74<3< &I % K TY1e+29+3.@6 _BJ L j9.8813129168249309e-3243.1434555694052576e-16qIJ K4g1e-305 TPe-15388R_ 19 :9 A6e-7p77Q89 bP8e-17HP1e-08 66`78zty nld4M[>0.05jN/0. wFAhB5>0c AGAhB99999999989 -0.0 sqrt0052 J 1.02 0.0 -> 030V1 2429W100499875062461>5>d?@6@02.0V0414213562373095p70G1b823c4.795831523312719c91Id2d"60310919`{U6(9.9998e+149N P3e+742 )H IJJU1e+293.1622776601683796IUAItJ  -- random inputs]#10-0.34252542541549913 -223039880.15076211i10560.300180587592 -96805192a-0.88790791393018909 -5.3307751730827402a.5027154613689004 -1.7737140896343291a-113916.89291310767 18143374626153858b2.6877817875351178e-05 -337.5157669103895-0.63187172386197121g26293913366617694f00570749526,`811254h!87C258185169308906215 -2.354831299043099@.071>34242007.0985752598086966bKP-1.05 4765935896 0.1440031925916069837489270111242f3098775528`-1.16675959475049311159711473953670.051598531319 51`813981705s$29a-0.512372841144990026175433648339085182780268 0.7160355d597614c"-3.7453400060067228@9465&c480963a2799008854169249*9554243814742367_P027736121575097673b3679430008719035603389 752096172651250545c11501.2559699453188G199732520728`38.746047664e9`0154812*$02#11.483007532685050.64100878436755349b1.244712815741096a2574926425843458`2 sqrt 0.0953+95618499734602 -0.48226565701639595 -> 0.54175904053472879, 4509239434231551 sqrt0113 70109185681863277754054037379892561c786817985833238+34349772344520979b4b987798075953678970001984875843722519e99388031770665153 -9.9854872279921968e-05i5i11.845472380792259 0.001005110458150673.44172520A5397,0146018406123464/6d2.3558249686735975 0.25605157371744403-1.537127847738664b832889645757614047`00.7@89419098 1.0496420622076`02007443863908851449287564552_8_1.8961715669604893 0.34940793467158854_ 38m178141161_1263408093506690_9_0.9602537831801 0.6957322486014)`0358710342209998358199165d457 -- values near 0"20r7.3577938365086866e-313 8.11814084651127439z@8.57e3531543516e-157 4.7320876342511c4163p1p1.2406883874892108X0 -5.1210133324269772q1.1140990057468052q5 -2.298275694537s2s -7@P545309502e-322 2.p37924475215758580748028"1.610007724r-4.996324tQ801214 -8.471843 27sW[50582312540437e-16235245941951&0 7.699553609385198C96208481077974^o159 1.B-0.0 3.390082660649941^04.11708796399223O155 ^]`-9.890,710822^7.0323531523sO60 -]0-1."P939369v2.619440719656670158w`7.90505033345994420x@8.899979403099%0.1.8623241768Qr3_@> 4.n6= 57J 55lK3-2.665971134499880 Q 1. 80Q03649TM3Q-1.54F69446724!10uK- 59l0307!55{inputs whose absolute overflowsS419e+308 -> 1.4325088230154573e+154 -5.9336458271212207e+153 sqrt0141  -1.797e+308 -9.96 -> 3.72844764320573N2@3410406899802901g4 -- Additional real values (mpmath)"5069313486231500.01.3407807929942596355lD 0.0L2.2250738585072014e-L49166814624004sh7e-154L2Q5e-32Z27587494\74834e-162;Uspeci3100 ->0!-"0inf4infC3@2.3 !->!4!!5!"6"e7"@f8"1nan!9!%0-> 3nan1N!N"N-DO-P1P"H"QC PB 8101O& ignore-imag-sig$f)8 {f f2f !f c2e_`#f$h2xGi#k:*2mj X9H[e3^3`3c$$dG cF 3c 3b,For exp, cosh, sinh, tanh we limit tests to arguments whoseZinary part is less than 10 in absolutel: most o@libraries have poor accuracy for ()Pe and0ine?Farge,#6theDof these complex funcs@ suffer correspondingly. --Similarly,p{!e/an" ?with relatively small real part. -  -- exp: Exponential function --@Azeros exp0000OA 0.0B-> 1 1-$ !2!A3 %Brandom input44017.957359009564684 -1.108613895795274 -> 7.0869292576226611e-09-@422502377833e-085e.4456149663368642e-15 -0.75359817331772239k0.72923148323917997,68426708517419033e6e0.760086548835164665723548010501b41764393109928666,21035108396792854b7b5.7071614697735731 -2.3744161818115816e-110033220890242068356 -7.8880219364953578e-1i8i0.465398132792705.2236706667445587e-2i62788507378216663 -3.279864842002/9g@3.24 5242295518 1.153562530424395/01579993693145764135644950380024749`1 -3.0651456337977727 0.877653878,2980559562983a88277518085566a2-0.11080823753233926 0.96486386300873106b50979112534376314 0.5512419561562q 2.78& 481963623575470807#7706045285 3900151337173411376813.3201709l83357e-10 1.268407c448726'p2978069#`43488954626100076891860.887672760@3272P1895386895557%2.3859624049858094577155913204442`1.5738333486794742&803075544324.825109113245B08935538267766231.640870234181371.438879484380830.678673 689048 -5.1148284173168825\1.8202794@2033020812040370785722 6.172246289642090K284755888435051^1.727396dA4587_61140621328954944.6067931898m!76 29t6944413Z106034306862995p9815313Q43550@12.8Q5889966629ep18481282`10.28019483029 3.4%22559748535-27721.2833215515P9028.62d4007405129741P21258;d673172 @9774P93353@ 0.203729054447v2 0.027364777!809295172 0.00059226603500623363 -> 1.0277424518"76-6086970181346579 exp0023 exp 0.94356313429255245 3.418530463518592 -> -2.4712285695346194 -0.70242654900218349 -- cases where exp(z) representable, .real) not!30710.0 0.78505803016909637158e+308 1.5790437551806911Y1Y-Z-[values for whichh(x) is subnormal, or underflows to 04O-735 4.3976783136329355e-320 42198541120468ZZx-2.35592-C@5207Da037293C 669018234125[2B -740K4.9406564584124654J46p676 4X02.1"-#5#!3.E#i6$!5.6F#Sz) ovI50inf BA2711AAj01.5A1.5802653829857376#7 U uA6A-6.5231579995501372B6B AA12.8Ak7.48361774174485257 F kAdditional  /(mpmath)(7iQ1e-08^100051Y 31b30004583374L!0.C122140275816Q)841<p2.718284590452357,-$0.u 374010.367879441171442321272.220446049250313e-&!22*B8B-1.1102230246251565DA8889F9F2.302585A9404 72178(@00.0vG782989709.7827Tx.797669956663801W10.0sspecial\Tmwi41000{a-> nan invalid e xp1003 exp 2.3 inf -> nan invalid e040O-0.01 050a 060_7N8 9 @"10 0-> 20.0&11 01.4/ 2 02.8 Ao-a54.2!&ca"05.6"c!R!47.0!cB9>B 3infB  B A2C  C `2B ignore-real-signAimagkE-JARA7(I  5  -2p  3x0> 1oJ3  "> 30a ]3-a 0l"P ""23#VFg4"W !6X!e4!!}! 4n "` !Q-  O- !NS4uD J51E 5r\   nan -  -- cosh: Hyperbolic Cosine --< - -- zeros cosh0000 A 0.0B-> 1  F0001!-&" #2#E#3# G0.0 -- random inputs54585395264297414253 -8.8553756148671958T-1.1684340348021185 0.51842195359787435b5b19.584904237211223 66582627994906177c159816812.23336992 10656776.050406246a6a0.11072618401130772 -1.48482021507324_0.086397164744949503 ?54275637717284b7b3.47648402506817521484 2882752764.325931955190844 7.524205354873795#8`0.5204706360452460a3603805382775585`.065394035468380291932936062524739a1.395189629759900747386xa0702902.141703102723596901415518712296308a1-0.37107064757614728085307856609580601491991b55712531964568587c%-5.8470200958739653 4.0021722388336292a -112.86220667618285 131.403354501#1a170026144485188+`7540130513`0.57208748253577946a141090tE4020a 4497902648783P90479Q139740.50760322393058133396665201081 10.052267552491867299 -3.8889011430644174-0.73452303414639297`3554070483353713 10.980007641771274/1.254882924778409mA4722f`4141611.087942143218033594701222644008^88847899930181280.6327978241931260.06495456681600228q11.381735317837`0.4318b816732229221663374677807383085884934!31568112014846572225576095]91399733125173004+13355123436059512!33062347 4.50249VR23837`04160260626m3.15738221n$61200.57@1920 31@926212957534P0.6980405378381 0.473090674710545222P0.543i2@62596S`648358#46 p9223446IA1934+a341679d845501a0.001477747920331 1.36 81&@7661 0.201210696389954901447518137863219b2.218885944363501 2.0015727395P883687 -> -1.94294321081968 4.1290269176083196 -- large real part cosh0030 cosh 710.5 2.351999c2967465239355998e+308 1.3076707908857333 [1[-\60.6W 6]1.4085466381392499D186402466645023Additionalvalues (mpmath)"501e-150 0.0q $$8#2G'09#05X35`0.0003|5"4593376462320066755619075848353!1.f54308063481524377363-D-0.07%8885951.3169578969248162H4@1504$6-C6 7.32867951399863t6777216A2193+8.7149738751185267108864BA4366B8709.782788.9883497833190073272*"=?-> special LR3100W<3-> !40inf1nan  invalid ignore-imag-signA3A:0-> @9*G2.3 z=9zi0%i%naJM!->X31008!01.4 4infc402.8!- "54.2"'E #!5.$ "17 f1f \16 ,1}S, b1. 1!!!!3101f 1A A2 #-_1022 cosh inf -2.8 -> -inf cosh1023  54.2$4inf#4#05.6#/"5"47.0"mE6#>!->tBnan  invalid ignore-real-signA7A1"-0d A9Iimag98902.39%na[9" ""30"ys-> 1.0 0.0(31#F. '32A0-> @ 9-z>z0$i3 #01.4W|3#$$' -$4-l4#(i 4<5'D#~I~ ( 4A Aqf`$5"h5 ? - -- sinh: Hyperbolic Sine --8 9`zeros ?A0000H!->>!1!=#2#>#3#(,%random input4717.282588091462742b3818794869410354-14867386.857248396 -5970648.65535166395b343.919712031432080172868877771525e-2x1.1518691776521735e+14947792581214689021e+127o6o14.1781222533009W1.938715757935129258440.37909034826 -670452.58500946441`7`.0343810581686239 -1.0970235266369905-0.560708582780927,4098883258046698b0.066126561416368204070461584169961871/01055870093812/557276738637542 sinh0009  -0.37630149150308484 3.36217346921 @ -> *591118119332617?23447115926369383b%10b049941960978670055 0.40323767020414625d-0.0459554821363290.3928878494430646d1d16.64785260390371b0026852219129082098d8492566.5739382561 22804.48067113356($12b.476625314303694 0.89473773116683386_1.2982943334382224 1.79665933677912043_422.36429577556913 0.10366634502308`3400321008920044e+183 1.39416009480455994j0.0910834074564198140408227AP70353k0.083863724802237902-3b71655393560d5d2.0360641320672.6831729961386239a -3~21124363175 -1.7238Ot0002817*6\56167172230633P00789 8622717767`@6.43{5853815869051472264400722137d0.336804011985188 -6.565462297164933`0.32962499307574578a29449170159995198`23774603P4969379246719579923204#0.1444983949060338@8210f053556799c00113882735`0549967619685985uG014605389634999 0.9222939840709880x23.2443870105663755805428755961689c8.870289077426 9.261074859704219]  0658857054738 8206391195-p4442684 23A098129544739707392 4.7252283918217696e-30 9.15564265669-4.5071980Q44404.0.300257307016617120371 678420062251254988753265f,026216732h201231217961 -- large real part,3710.5 -2.39@-1.3k70564885919e+30824394470!98[-\J0.804\0283M601735164E5419399767]Additionalvalues (mpmath)5`1e-100q*1.5002 9T5e-178*4.E9895!9,r6999 79 Y8`3.7e-00:3.7a8885e- :$01rR0.001:!16B7502X860.2620133600254109399895 0.0 sinh0056 @ 1.0 -> 1.1752011936438014569373-3.7e-0880a8885e-!<8<U0.001:;!16B7502[:9:- "6051.4436354751788103{;1.9(07"61B-C-D2D17.32867951&63u6777215@2136#63B8.714973875118524%}67108864.FQ03621`B4B709.78278 8.9883497833190073272e+30"=5=->-?  -- special valuesR31000w !x0inf Cnan  invalid ignore-real-signAu6!->A9lC2.3 z5 ziZ0%0-> %na>M!->X3100!01.4 4infcr02.8!- "X54.2"'EA#05.6# "147.0"f1! 1=6A15D 1 1!!!!S-1f P" 1A= A2 ##2-a2cG#c""ch#/ d21 k 2" 3zc5-> i3|H,L 3A5 3-2.3 -inf -> nqan nan invalid sinh1034 Q -2.3$!->4nan"5"inf -0.0 -> - %6%61.4%4inf%7%02.8%I$8$44.2$#9#05.6#$(40$7%1% >  , ignore-real-sig'42A5-@939OS30.0-40-> g dA= Aqj8T"5$j5 C? -  -- tanh: Hyperbolic Tangent --> ? Disabled test: replaced by`_math.TanhSign()7"an2/_c!"-- zeros A0000@F0001$% J2&O%' L3&+' \ random inputs 4721.200500450664993 -1.697072948034299 1.0 1.9241352344849399e-19U5U0.34158771504251928 -8.0848504951747131M2.123711225855613 1.2827526782026006`6`15.4541447]@3689.23619582288265617`80.93283 -3.4336684248bd36e-14g7g7.61031631196\2g780274832030700Z-f497219438 -4.9064845343755437e-07f8fP0.15372357921263510863273061O>~2324608170356186,7108346743391029d49101115474392465S9723001264886300.45844445715492133,771911585418058881-0.10690612157664491 2.8616128008563951151976162625735884004883556475*1/e1505774192066702 1.5431174597727001.3811098930681140251;966370935X1j5E 36 P7922203549541246459065220499046696953 0. 36921788332369498 tanh0013 $ -1.3540418621233514 0.18969415642242535 -> -0.8823861151387 0.043764069984411721c4c0.94864783961003529L11333689578867717d0.74348401860368,0512710425438552d5d1.9591698133845487029654444904578339e27077696810.000226642400492129336f0949715796669197@247080853"56d81636574501369386,087767436914149954c7c5770428.2113731047 -3.71605803398331611.0RA8A1.55767823213996m1.0357943784U> 1.04030023848953481126347894671469a 0.62378536230552961 2.347139fT56021558249923896036353569473646842869"20a17.400628602508025 9.3987059541979845 -8.0175R20530832e-17c1c0.1502617750987 0.50630349159505472`193675p1827768+3849847858 6$22a57433977530711167p04546265621.085784815926284P69139t5587221&20.16291181500449456069728102C7544614933590755115067910772903467817 -- large real part8307103X40.0"ZQ-711 0-2+1000 -2.31/98dI]p0001e+3FI9.66F(0y0Additionalvalues (mpmath)5P1e-100 y0^ 9 5w8*4.E9895!91e-1999 798`3.7e-0*3. q83559e- :4001 68!079v60.2719737532022oA0114U4D4@7615h 59Q48881R4--P0 80g 620.54930614433405495>83406<-DE 2 tanh 17.328679513998633 0.0 -> 0.9`822364 tanh0063  18.71497387511852%Ch988898C4C0711401.0 d5!1.797e+30>( --special values:B1000:[F1001!0infT@nan  tinvalidQ20O2.3 0}U!->\4nanQQ!nF8-> B1006!7 !7!?1.4!8!42.1!D-0.09"8"1j43.5"C1j!h ignore-imag-sig"1s5"9 |5: 1| 1|!!|!!|T'0 \1~ f 102w  25-0.D#-F#pH2q"H"r"Hgt#0I2n\#a#2~"~ "3pWq r3r H 3-0` 3R"-o1-|V%< %z%> %|%@%3~$B $4D$4%!> %447 84e"->4`: 40d-> -1.0 0.0 tanh1047 tanh -inf 0.7 -> -1.0 0.0 G1048#?1.4#9#52.1#-G)50$8$1$53.5$G2# ignore-imag-sign - -- cos: Cosine --$%zeros cos000030-> ( 1 ! 2 >0.0 3 %brandom input442.0689194692073034 C016802181751734313v-0.47777827208561469/47604015016959715f0.42096273S@7977,823851677425802C2.9010402201444108*0232 04 3617^6^A1.94 630694557 -2.975185739289121^-3.5465459297970985 -9.1119163586282248_7_3.3118320290( 16`878713q9286142!1.3911528636565498 0.16878141KD91708`4.9540404623376872`5794923223902680.28062445586552065 0.59467861308508009`0.45374584316245026 502834483739321.9247665574290578300457220476110}1p2578172 76843 1.2715881615413049 1.M16145948914^97363332|1 -0.13862985354300136 0.43587q77670321.085988`361912n6215754814667227`S0322= 966584 9.9384082307326475e-1 0.99387545040722947P98254*`065479.1.502763366205@e-07069668060249950P00024`912412g469545565660995e-09g4.972864549050305HI74798088609500.2011731975501w/Z0849HS83186fp7.81969*A8671 79gP234458- 0.734882501585063 0.313993308299 12724218807667m746684453087182E 01224443284R`108253s74370054.2396521985973274*21788483#2488 2.1165117057056855 -4.041649qD641411.162220662492729),01154611970_`0.4488E6133703798234699150t1a1.6287620884e-0B1582428979281.17423199957914 1.Tp8394819EB 22.638521260611z 2.9886107100937296 -h> -8.7209475927161417 -4.7748352107199796 cos0021 cos 4.8048375263775256 0.0062248852898515658 -> 0.092318702015846243 .1983430422306142c2c7.991451543385P 0.71659966615501436 -> -0.173754399069365667721704352729458`3`0.45124351152540226 1.699269399381215:2.543477948972237 -1.1528193694875477 -- Additional real values (mpmath)!50`1e-15001.00#f#8"%T1e-09"=0.95V1000y5155093375470.2g8006657784124162892h530> 0.5403023058681397174262-$0.7"8 5852921.047197551196597/',8994062.57079632686B-0.841470984807896473576-D67.2256631032565258778525229247407559,9645943005140901699437494722255$ Uspeci2100-3->  0infHo1nan invalid ignore-imag-sign9-4-> 0i:2.25@xg 6 .i0-> 4100*.39(/3infO:2.7/8/-_004.2205aJ-5.5a61`0187.0!1:>V+1 81BM1-@#naM1| ?^ F  18 Gn2_fRinf -0.0 cos1021 cos 1.39r inf ->inf cos1022/:2.7.8(1> -7030I4.2020/4/:5.5_6/^.5.87.06 4 nan invalid ignore-real-sign878@0.0 -!->0Himag080:2.288?$na^9.^!30n-> 1.0 0.0!31 ? G+ 3- 9 1jOh7 //3/0(-311a4! :s?  4 9Y4_J""x | 4: 4*- z1- 2- 5- 0-5 ~ z: - -- sin: Sine -- !zeros sin/K!->j1  @2!:"B3!&" random input4518691829163163759 -0.74388741985507034-0.2396636733773444,800232311018567515b45127453702459158 -461.8133992071616a!7.9722299331077877e+199 -1.6450205811004628e+200j6j7669228345768921 36993656498751j3.557238022267124 -6.8308030771226615_7_310242855259508574869219939188296*70972676047175209 -1.99850296350426839 sin0008 sin -4.4194573407025608 -1.405999210989288 -> 2.!480800802685 0.55362250792180601]9]1.7810832046434898e-080016439555384379083d-156113185261162786668375k"10k0.8200017874897666 0.61724876887771929e0.874907819594886`448352s0987758_1_1.4536502806107114_3998575534150415_1.2035709929437679 0.61121T16370`2`@2.26G21555060513172760685583777502093809190431 -b@4554682295323b0.02613983069491858 0.1840476659777607,580778863127943-50252539673564b4b1.57430650010546175312557427264201.14445963320927200195375980993520775`7.3833101791283289e-20d164532213242362y> 7.483472067b'42/52755564646691J6g0.34763834641254038 -2.8377416421089562.9188835663 -8.00027180532502247]077105785180421550.09005602731620K0.07734197381447130408990986T52458)3.90632277981423p0.05954: 54 24f03.9: 90v56512e-/7D8598373510.573339179325 8 8.7785221430594696e-06g0.5424402933835 7.374786912530136 622 48281651316P330446207+"85{,P62288K9651 0.3363889671570682@1.43 7302672813618897902843471.337096006094792233613796138716301.1873544034.859723596615055Z 58.919141989603041 26.2370039C5885k20f3078406649192 34.a131209:565548145569.38245 644329685822700.62 -- Additional real values (mpmath)5`1e-1000E 7r`3.7e-0z08I3.69a2001e- 8M6 07!830416[7)2k0.1986693307950612263020.841470984807896506,2--k0 G5-1.- 0058 sin 0.5 235987755982989 0.0 -> 0.50@4642 sin0059 sin -0.5B B0C!60C2.6179938779914944f*49@6018t0!61B-C?-0.D 2D7.225663103256523809016994374946736483@-8.796459430051+877852522924734065 -- special valuesU2100-!->v31000infi1nan invalid ignore-imag-signZ-4-> 0i:2.28xDxg46 .5.i3inf!6!:1.3$9 0070:2.7080-181:4.221`0:5.5a60_147.0 L 1j X1- 1Vk#na!1-0/r  y0]E  8 Gn2_f o2.]+ 0+`2hN 212..3)m ! 3u.z E3j@P `3_73002.7999999999999998 -inf -> inf sin1038 sin 4.202/7090I5.59605a!40157.0"!1!3nanvalid ignore-imag-signZ29-N 9131 -0%> T4##a /in 5:92.2~ > IIr68bt"47#:1.3V9S:2J-2.7221-05-0e5-# |= - -- tan: Tangent --&'zeros tan5 $-> 1 !2!:-]30.0!3!&" random input4556378561833861074 -1.7110276237187664e+738S {5F3.5451633993471915e-12 -2.855471863564059D4.662244130488957.43?02738430939516g2.502442719638696426742234390504221d0.66735215252994995,39078997935420956`7`0.87639597720371365 -55.586225523280206a-1.0285264565948176e-488UP01578596427243 -520.05944436039272V"19C 84643549990725164 2.07490@3963U31412661676959573 1.0033548479526764$10`4361379224856 8.1082741629458 1.3879848444644593e-07 0.88344224011/820906367833114 0.28589924802?>B385737936536_0892693779712451.1477859580220084 1.90216370027080434348450042071196!2p4PS01687_[124655431U3409 3.06068510163448#05125305142903873P7r69945479e-03.75828487175256-692787020.4403893C '12.232196765z10.09006942300816C1.5369846120622643e-1655723759 0.88371172390"245012 -1.1635053630132823 -> 0.19705017118625889+ 0196452280843129 tan0017 tan 2.134741423184926739311339960416831^-0.038663576915982524-0174399993980778`8`5.9027945255899974 -2.1574195684607135e-18-0.39986591539281496150237531679~1i9i0.4481148949082 683216075670.07556r0.0 1.0>!20>4.1459766396075 12.5230172056057=2.4022514758988068e-11P0S11249f!21_1.7809617968443272 1.5052381702853379e44066222118946903^932684517702d#22^1615313900880577 1.7956298728647107^0.041793186826390360[395460347923]0.06701477908945 5.851736157745709_ 2.2088639754800034e-06 0.!836182420061 -- Additional real values (mpmath)5p1e-100  ->l2 7wt3.7e-08833.70q17328e- 8QT0.0016 13p4666875 6*2i2027100355086724948h4\'1.557407724654902230c51-6:g"0143 -?-1. 0.463647609000806K4 @7163I-B? C61.10714871@0904f1975296:bA-B D!1.s4.1014199471(93 6?E1.57p255.765x0078964q6?57079632679489i1978937966095219.053N7.22566310325652.3763819204711701526S08.7Z94300514"?0.72654252803140cUspeciR !0inff@nan sinvalid(}-(32.287Od 3nanVpU .^1-> t3100@30.6.6 1n1007 tan -1:.39 inf -> -0.0 1.0 tan1008 tan -2.1010 /9/7^8/"10/43.5 "11! ignore-real-sign!122  6 r 7V0-> 01]] invalidF'62Y:| 2:0.6$96k:/1j .h]/2.h /h }?1.052*2{..3m !A 3(7 _ W /J-3g-1i0 0\ m14o"4ts4g3Z4#c R4) u4r = - @3- 2c5- 1- 5q? -4 -- rect: Conversion from polar coordinates to rectanguO-- -4 L For cmath.t, we can use the same testcase syntax as for -- complex -> functions above, but herTinput argumentsDshould be interpretedha pair of floating-point numbers ratherD@than real and imaginary partsFaA.Hap'spirit0C99' rule$. First,mPshortversion:Q! (x, t) = exp(log(x)+it)@positive-signed xG 8-9-:Onega:7nant nan + it), except that in-@+-0)  E is unspecified?n0nowEm long : -Tconj("t)Qall xQA-B-0?/+0, +0) returns +00B"7inf#- 0 +- i0, w3SG Z:  n0NaN 7@raishe "invalid"g Aion,finite nonzero xvYinf, x_+-infz.* ("&!fkresult6)Xinf+ixinf*cis(x)|;6NaN= +i @I WNaN, !+ ls (includingn!inDies)^^Z ` ,b( x,=R&;{b? +-y>nal values A1000A 0.0!->40.0!1!+! pignore- iJ2J02.3nan invalid rect1003 A inf!->Cnan 0inv0 ignore-real-signA4AC0.0 A40.0!5!41.4!4inf!6!02.8!-"7"54.2"'#8#05.6#D"9"7"10!  Himag&11902.3|9$na$&12!+> !Bf%f 1~.-{~! Z  ;-!>  1  n fm3I  2u 0q I2<d###$-2G""h D 2-- U2" "3?&!> -3s-Q  3  .3.z 2. 351-> / $ 03#/#"". #/ 4^  ~9,. 4+" [l 4;m4$ Yn+n( 010qAY-Yinf inf rect1049 rect -inf -2.8 -> @inf H1050#44.2#4$1$05.6$ Y%2%57.0%m/ -5 -- polar: Conversion fromangular coordinates to2 /--:For cmath., we can use the same testcase syntax as for Cpcomplex< functions above, but herToutput argumentsEshould be interpretedia pair of floating-point numbers ratherD@than real and imaginary partsF$a A!. V Annex G#C99 standard describes fully bothi~lS (as cabscarg, respectively, which in turnKare defined1erm[QhypotUatan2). <overflow }C0100I1.4e308 W0.78539816339744828 IVial values\%10\@0.0 !->50.0#1$-%2%BI3.1415926535897931X3384-545P X5#02.3 #6#JV73R31.5707963267948966282292 31-1Lf2.35619449019234481/j11334155 5jk:-1j5742 4 /S 2 0n> inf -0.0 po lar1023 polar inf -0.0 ->  C1024%Qnan -*%5nan$5$02.3I0$6$m $7$#8#j9#'30#0-> #31#B#2###cia$a-kaH import unittesttextwrap from  *0sup2, mock_socke6 $ioNTsmtpd asyncore class DummyServer(*R.SMTP): def __init__(self, *args, **kw )- D.: b9elf.messages = []0if w._decode_data9return_statuB' 'OOelse?b@A process_peer, mail, rcpttos, ,(.append((D !))!ifV2 ==  '250 Okish @if '_options' in kw and 'CUTF8[*]e9 " ov rDispatcherBroken(Exce$Epass$ 1clisten3num2Rraise |)iDTTest(.CCaseRmQsetUplg4 = o.K_V_unimplementedh2 = q#(($.HOST, 0), ('b' qcV=Truetconn, addrw0.ac(%`hannel"wMC!(s4&, I., owrite_line(icY].queue_recv-J,Phandl&Uad() #wib'HELO exa' $MAIL From:eggs@. RCPT To:spam, write_line(b'DATA') 6self.assertRaises(NotImplementedError, write_line, b'spam\r\n.\r\n') Ndef test_decode_data_and_enable_SMTPUTF8_rhz!):; RValue `smtpd.\yServer,(support.HOST, 0)>'b' Z=True8 parDown(asyncore.close_all(socket =  class DebuggingTest(unit.qCase): \setUp dRmock_K!ndO, channel, ,, =1FalM(R&"Q.y.queue_recv-(,Phandl&'adWw(b'EHLO exa,ifb DMAIL From:eggs@N BODY=8BITMIME eOelseW@ RCPT To:, HIb'.'st_process_message_withAtrues (/ ()conn, addrw.accept >"FC(&, I/, o lcaptured_stdout() as s4.seK\_I\n\nhello\dUP.getvXbEqual(/, textwrap.dedent("""\K% - MESSAGE FOLLOWS 3 X-Peer: peer-2essB 6u--- END 3O""")f7F,u2]c$end_data(channel, b'From: test\n\nh\xc3\xa9llo\xff\n') stdout = s.getvalue(elf.assertEqual(/, textwrap.dedent("""\T[- MESSAGE FOLLOWS -3'X-Peer: peer-address% !h\ $e-- END a""")) 1defh"_process_message_with_enable_SMTPUTF8_true(self):>)`servermtpd.DebuggingS ((support.HOST, 0), ('b' DH V=True`conn, Rvw.accept 0cha]"C(&, I/, s  captured_\v() as s!4.send_data(m,  omail options: ['BODY=8BITMIME', '*']IlarDown#asyncore.close_allasyncore.socket = smtpd.soc  class TestFamilyDetection(unittest. Case): def setUp(self casyncoreuRmock_ KtearDownN?close_all()5kN-@$skipUnless(support.IPV6_ENABLED, "IPv6 not enabled"t `_uses_, eserverQSMTPS(rHOSTv6, 0), 4q_.assertEqual(]P!.f", .AF_INET6)[,st4% ,)`RcptOpParsingerror_response = (b'555 RCPT TO parametersrecognized or'Onb'implemented\r\n'T/iold_debugstream9DEBUGSTREAM1-' = io.StringIO(bJ`Kelf.write_line, channel, Xqueue_recv() (Phandl"*ad1st_s_rejectedzkb = Dummy`, ('b' conn, addw.accept/C&, I]0H, b'EHLO exa'2MAIL from: size=20Jj/toH|foo=barHalast,  st_nothing_^e=20') - self.write_line(channel, b'RCPT to: ') @assertEqualA.socket.lastM%250 OK\r\n') class TestMailOptionParsing(unittest.aCase):o0error_response = (b'555 MAIL FROM parameters not recognized or 'I0b'idmented def setUp(Ssmtpd = asyncoreRmock_uD.old_debugstream = LDEBUGSTREAM1-' = io.StringIO() 8tearDownclose_all(re2O h %, n|^N.queue_recv()(Phandl"*ad st_with_decode_data_trueserver = DummyS ((support.HOST, 0), ('b' RV=TrueHconn, addPYw.acceptm3JRSMTPC|(4&, I/, oJSEHLO @for HU in [L!b'MOfrom size=20 oUTF8',>) BODY=8BITMIMEL#CUNKNOWNB#body=8bitmimeC]ufI+Q GwJ*b'HAOfalsB.{0-]J,assertEqual(channel.socket.last, self.error_response) write_line( O,.b'MAIL from: size=20 SMTPUTF8 BODY=UNKNOWN'yassertEqualz P501 E:c can only be one of 7BIT, 8BITMIME\r\n  body=8bitmimeeS b'250 OKdef test_with_enable_smtputf8_true(!):.server = DummyS ((support.HOST, 0), ('b' VG=Truconn, addT].accept(0 = d.LC(4&, I/, s .^, b'EHLO j a2? !y za classD(Test(unit.CCase]setUpCmtpdG = asyncoreRmock_ `old_debugstreamDEBUGSTREAM1-' = io.StringIOhvdecode_data 2lf. > <tearDownclose_allPe2  2C  , R>5d.queue_recv(.M -Phandl'Fad()q_broken_!Supported commandsEJMAIL RCPT ' + \ DATA RSET NOOP QUIT VRFY#P_q C;a FROM: <Oess>_unknown e(b'HELP SPASM') self.assertEqual(channel.socket.last,3:$b'501 Supported commands: EHLO HELO MAIL RCPT ' + \M DATA RSET NOOP QUIT VRFY\r\n') ;def test_]_bad_syntax!):$write_line(b'1C:hostnameduplicate example )043 D/parameter_rejected_when_extensions_not_enabled+ded_smtp = False  *from: SIZE=1234lC031 S'FROM:
L)_allows_space_afU_colon6 =  >o250 OK,0 size=20Y&"? b'3_\+cO@W1? hi"yZ dT&"_21 Bywst_HELO_QUIT(self):  .write_line(b'HELO example'))LQUIT!assertEqualj.channel.socket.last, b'221 Bye\r\n') edef test_X_arg_ignoredI 2@ byeAbad_state2mtp' = 'BAD STATE'olK\`  b'451 Internal confusionscommand_too_long&#MAIL from: ' +qb'a' * #Q0siz?mitA @I.500 Error: $P too &K_ limit_extended_with_SIZE`/EHfill_len =+p- len('$ 1 y \=12349X50 OKz7((O 26)g>, ? b'r' rejects_SMTPUTF8_by_defaultu& ^ bbt BODY=8BITMIME !P[0:1]>54Adatater_than_A # Hack the & so we don't have to generatePmuch W.!_rz = 1048, qFKDeggsf J \RCPT To:spam@examsple') self.write_line(b'DATA! QA' * 8channel.data_sizDUmit +_fb'A\r\n.aassertEqual([socket.last,V b'552 Error: Too much mail s1') @def test_MAILparameter{!):( EHLO examF ^ FROM: SIZE=512>o250 OKinvalide/b'501 Syntax: h
[SP <-?s>]RCPT_unknown_3Qham=green2&55  not recognized orihmentedi  /Y< TO>h& _larger_than_default_VJ_limit*o= 1048eOL2096h [message  exceeds fixed maximum #VcAneed}5 ?/HEntto:spamk2$03V]icomman3&!_s_8[h from Qel.socket.laWst, b'501 Syntax: MAIL FROM:
\r\n') 6def test_)!_s6_EHLO(self):%^.write_line(b'& example'))[ from eggs@3assertEqual|.channel.socket.la [SP ]missing_+ OHELO:,AchevronsB<>" b'250 OKoempty_/:<Fquoted_localpart <"Fred Blogs"rO.com3x?, ' $_no_angle.!  >B ,7with_sizeZ] SIZE=1000248^ne@channel.sock et.last, b'250 OK\r\n') self.assertEqual(channel.mailfrom, '"Fred Blogs"@example.com') Mdef test_nested_MAILM!): p\write_line(b'HELO N )O T:eggs3Ospam3Dsock>b'503 Error:  scommandb4OVRFY& !252 Cannot ` user, but will accept message and attempt ' + \b'delivery_syntax !Q501 St:
EXPN_not_iomented63 2 L 0no_!L#D/ Psend o firsteed_RCPTiJOFromODATA / Pneed   !B9 M? to1 -dOTO:  'OEHLO&3! p` [SP ]K1lowercase_to_OK5 self.write_line(b'HELO example') self.write_)MAIL From: eggs@4RCPT to: <3>hassertEqual(ychannel.socket.last, b'250 OK\r\n') def test_no__rD!):!S &? to dh b'503 Error: send o firstdata_dialogL2_To:spam(_xtODATA" b'354 End  with . <%@more." lp ?server.messages,[(('peer-address', jport')-9 ', )['] 'n<')]_syntax^ 1 %Q501 S : M!!&' $[# transparency_section_4_5_2<   R .. ( received_ 0, 'multiple3:eggs@examplSe') self.write_line(b'RCPT To:spam@exampl1h0ODATA data\r\n.&assertEqual(server.messages,[(('peer-address', jport')-u 'eggs )['(,'].'Q')]) def test_manual_status!):"&# checks that the Channel is able to return a custom K L _HELO MAIL From:3: c- .socket.last, b'250 OkishF'LRSET<  K t5foo3B[( ' * [%  ~_m8O 26W_syntax-? hi%Q501 Sk : K unknown_commandUNKNOWN_CMD" b'500 Error: ' "p" not ' + \F recognizedattribute_deprecation0with sup.;_warnings(('', D=Warning)):   spam = self.channel._SMTPC __server 2with support.check_warnings(('', DeprecationW5)):?Gm@ = ''7v1Oliner:UkdOstatUldgreetingTodmailfromTodrcpttosTndOdataTkdOfqdnTkd/peJVk with support.check_warnings(('', DeprecationWW)):  spam = self.channel._SMTPC e__conn3with sur*k @ = ''t:Oaddrr:k @unittest.skipUnless(cIPV6_ENABLED, "IPv6 not enabled") class D%XTest(def setUp(smtpd.socket = asyncoreRmock_ ,D.old_debugstreQLDEBUGSTREAM1-x ' = io.StringIO()7server = DummyS(-HOSTv6, 0), ('b' Adecode_data=Trueu#, |.acceptAl.>&, X,WithDataSizeLimit(cqCase): y  ^# Set DATA size l to 32 bytes for easy 1ingbE!? 32I+~ tearDown close_allS Gwrite_line , >9.queue_recv(.Phandl'Fad()q_q_dialog} wwb'HELO example'H )MAIL From:eggs@3assertEqual|socket.last, b'250 OK\r\n') self.write_line(b'RCPT To:spam@example1assertEqual(Bchannel.socket.last, stODATAd"Tb'354 End data with . <%@more." . ?server.messages,[(('peer-address', jport')-u 'eggs )['] 'nQ')]) def test__limit_dialog_too_much !):4 ]_HELO U )MAIL From:  I uSThis  is longer than 32 bytes'} b'552 Error: Too RQ mails') class SMTPDCq WithDecodeDataFalse(unit.TestCase):]setUpCmtpd = asyncoreRmock_?old_debugstream = sLDEBUGSTREAM1-' = io.StringIO(! = DummyS/P((sup.HOST, 0), ('b' ?`conn, ;vL|.acceptiA,ml6.>&, X %aarDown+ Rclose_allxa{UHb2  , ..queue_recv(.k-Phandl'9ad(st_asciicwine(b'RCPT To:spam@example') self.write_line(b'DATA! plain ascii text- .assertEqual(} channel.received_data, b'hdef test_utf8.I!):X _HELO MAIL From:eggs1oRCPT Tb9 enrichedd: \xc5\xbca\xc4\x87` and some L1  `d (/b'9\n'>j/b' class SMTPDCGWithDecodeDataTrue(unit0.TestCase): eI]setUp@mtpd.socket = asyncoreRmock_ Juold_debugstream = sLDEBUGSTREAM1-' = io.StringIO(server = DummyS ((support.HOST, 0), ('b' vd7Q=9sconn, addrw.acceptg# Set J@ to M?8.`&, z,Bf#tearDownMclose_alle 2O m , s.m.queue_recv(.k-Phandl'Fad()q_ pw(&' M ample')  self.write_line(b'DATA') ! utf8 enriched text: \xc5\xbca\xc4\x87I and some plain ascii1 .assertEqual(channel.received_data,('żźć\n class SMTPDCdTestWithEnableUTF8True(unittest.$aCase):def setUp(cmtpd.socket = asyncoreRmock_ J5old_debugstream = sLDEBUGSTREAM1-' = io.StringIO(server = DummyS ((support.HOST, 0), ('b' ve:_;=<wconn, addv0.|.acceptVn>&, X tearDownjclose_alle 2 2A , .9l.queue_recv(.Mk-Phandl'Fad()q_MAIL_command_s_when_announced1wEHLO example )' from: BODY=8BITMIME'.encodeYRWutf-8).last, b'250 OK\r\n'7process__message#& for mail_parameters in [b'']hb\aV\> ' +n$J(P[0:3]7250rD rcpt to:\i.?354D c1  ,ifpz == b'' self.asser"tEqual(self.channel.socket.last, b'250 OK\r\n') Yelse:K_asser\ ;? }SMTPUTF8 message okishEdef test_utf8_data) write_line(b'EHLO example )`'MAIL From: naïve@Cé BODY=8BITMIME '.encode('utf-8')Dk*S[0:3]'RCPT To:spämXlb'DATA<354@  enriched text: \xc5\xbca\xc4\x87I . receivedf,(b8>\_command_limit_extended_with_SIZE_\Oehlofill_len = (512 + 26 + 10) - len('mail f1 11' +6b'a' * (O+ 1)0   b'500 Error:  too longZ\(/b'+ iYmultiple_esM[r_engthSgfor char in [' b'6c'] I&* {O b'adNN7500 D%7/25rcpt to:') self.assertEqual(channel.socket.last[0:3], b'250Dwrite_line(b'data%i?354D itest\r\n.*n class MiscTestCase(uniti.!):D@def q__all__;bblacklist = {1"program", "Devnull EBUGSTREAMpNEWLINE COMMASPACE",JDATA_SIZE_DEFAULT/Pusage pOptions parseargs", C} support.check, smtpd, = ) if __name__ == "__main__"$<P() imgt codecshtml.entitie%sy e.40uniEjPosReturn# this can be used for configurable callbacks$n__init)vpos = 0.ahandle W, exc2old/:}Breal$3if "<0? = len(exc.object) +3F# if we don't advance  time, terminate on the next Dotherwise we'd get an euss loop-0 <=j.startHr ("", ) # A U EnbError  with a bad w attribute@BadSC(  5.5, "ascii", 0, 1, "bad"O= []Ol /De$oui SNoEnd>5bytearray(b"")Adel 9endb E __init__(seclf): UnicodeDe+Error.__init__(self, "ascii", bytearray(b""), 0, 1, "bad")P4.object = [] # A fTranslatei 'without a start attribute class NoSD(Idef 8 "Adel _n end?EndK/ "?endO` q CodecCallbackTest(unittest.qCase): c_xmlcharrefreplace>q##  unencodable 4acters which numeric entities.qa# For , latin-1 and5 maps this is completely i gmentedIAin C; should be reasonably fastws = "\u30b9 d1e2 \xe4nd eggs"[assertEqual(!s.%e(]"A9"),4b"ス!97514; ä M?", *)2Cname3Ttime use a -5Xy forV7#+s, if onePavail.f7exc)if not isinstance(exc,E 8<raise Typ"("don't know how to handle %r" % ~AlU @c in-zQ[exc.: Fend]8>tryl.append("&%s;Uhtml.*`point2)[ord(c)]mDexcept Keym1#%dnQ Preturn ("".join(l),3endXrcs.register_ez "te st.xmlcharnamereplace", C) sin = "\xab\u211c\xbb = \u2329\u1234\u20ac&a":out = b"«ℜ&r  = ⟨ሴ&eur#Celf.assertEqual(sin.encode("ascii", "te), sout)-latin-1Ao\xa4&riso-8859-15@def HG_uniq(self):## We're using the -as from0uni database this time,EQand wI doI"syntax highlighting" here, i.e. we includeFd text in ANSI escape sequences. ForWit isEuseful thaterror handler is not called for every l!unPable bacter, but6a complet8 of@s, otherwisewould output manyAnecessary 7exc!ifisinstance(exc, UEE( 8< raAType"("don't know how to]p %r" % ~Ail = []xcexc.object[ `start: Fend]Gl.append(.(c, "0x%xvord(c))';return ("\033[1m%s 0m2W.join(l),G.end4cs.register_T( :", SctG80001t1mNOT SIGN, ETHIOPIC SYLLABLE SEE, EURO"CJK UNIFIED IDEOGRAPH-`M'0mg "'A\xacj/1mW 7 0m /1ma5 def tes t_backslashescape(self): # Does the same a "unicode-6" encoding, but with differentMEbase,%s.sin = "a\xac\u1234\u20 8000\U0010ffff"2out = b"a\567!\u89elf.assertEqual(sin.e("ascii", "replace"), sout) 3latin-1*Oxa4\%iso-8859-15def test_name A\23prefers ``\N{...}`` q# sequence:1(b'a\\N{NOT SIGN} ETHIOPIC SYLLABLE SEE2URO('$0 b'<CJK UNIFIED IDEOGRAPH-&}\%')?k[/N{w5?xa4S "deQ_call This is a7t for a 9 9 handler*# that allow4!ofuinvalid";*"\xc0\x80" and returns "\x00" instead of raising an error# All other illegaljs will bed strictly@$relaxedutf8(excdGpif not `stance$2, UgD[ eE 8<Re Typ"("don't know how top %r" % ~ A if.object[exc.start: P+2] =mK"AX" (X,RGP+2) #wry after two bytesOelseW ai3&xcyycs.register_ (".f7",  # all the "\xc0\x80" will be decoded to "\x00" sin = b"ab:c\xc3\xbK9eout = 9p00c\xfcG)elf.assertEqual(sin.("utf-8", "test.relaxedutf8"), sout) # 1" is not valid and a UniDUErroreraisedJ1R<.s(^&, ,\X @def _charmapenu(self):Zc# For # $ ings the replacement string?@mappahrough8F again. This means, that> toJ@ableGuse e.g.F"" handler=e<0has=phave a for "?".1/= dict((ord(c), bytes(2*c.upper(), 'ascii')) Fc in "abcdefgh")Rb"AABBCC 3cs._5e0, "nDct",M)[0]Ag d/, vuwJw[6Q"?")]7XYZ{7DEF 2XYZ" " # wrong type0AOType>?uR`intern Awith.support.check_warn3(('B_C ebeen ' 'deprecated', D BionWp),J?y m $b2""-"$if len('\0'.X5AF== 4 :s_wvK(exc2!if<isinstance,,@@DR p("don't know how p %r" % [Ipeturn (fW1", 1 CJ b"\x00\x0E0\x0".decode("uni -internal", "ignore"), "\u0000"-) self.assertEqual("a(b"  oreplac o\ufffdlbackslashcs.register_error("test.hui", handler_ZP V1\@def PQ_callX(c%):X"W1(exckr = range.start, exc.end)E*if isinstanc.2, U, EnyEm ^8l = ["<%d>" % ordj object[pos]) for pos in r]u/elwDwsr &se>raise Typep("don't know how to[0 %ri return ("[%s]""".join(l)p3Q112j oif notS .   U +1) # skip one characterl2l2lDs = 81\x7f\x80\xff"_sy@asci %p[<129>]q 8>][<255>]&*2|uv b"\\u3042>xxx`escape}.G[<92><117><51>]Relf.assertEqgual( b"\\u3042xx".decode("uni -escape", "test.handler1"),H"F[<92><117><51>]xx"&%) self.assertEqwcs.charmap_^b"abc, {ord("a"): "z"})[0]z[<98>][<99>] "g\xfc\xdfrk".en~("ascii b"g[<252><223>]rk*~, |@def _longstrings(%):#" " # to check for memory overflow problemsBerrors = [ "B ct7QignorYareplac 0xml5refG"backslash'd "name]6# register the s under different >s9#@prev9c from recognizingT;prerr in JG$s._$(\0" +4#, %clookup#Uerr))fl = 1000H1s +e.N  0uniQ[ s*l-s0("x a\xe4") ]B2enc3platin-18iso-8859&5"m`"utf-8> 7 $16 732";{':try4uni@enc,v!except U'EVBpassr;_Aionobjectar{, exctype, W, msgZ# Tesx` subclPs: construction, attribute assignmand __str__/uversionK#with one miss@arguA**Raises(Type *V[:-1]J d\ too muche(fT + ["B'"]1q!of0wro5ypezWVspam", b"eggs 42, 1.0, N. ^\range(len)NkH sP0if (#B) is;[i][_ continue  # build argument array & callargs = []for j in range(len(-=)):+Yif i==j!n.append(wrongarg)OOelseL>[i]Kself.assertRaises(TypeError, exctype, *%) # check with the correct number and >5 ofhs>Texc =a (*Equal(str(exc), msgdef test_unicodeen(A._exceptionobjectx(UNEN ["ascii", "g\xfcrk", 1, 2, "ouch"],0!"'0 ' c can't character '\L'N@posiA 1: QO !L4)s/-3^PQx", 0<0__u01005M naOffff6Mn0U007Q'  dewe4DN AbyteM%(b )! NZ 0xfcO~exceptionobjectargs( UnicodeDeiError, ["ascii", bytearray(b"g\xfcrk"), 1, 3, "ouch"]<!"'< ' \c can't djNs in position 1-2: G!) def test_utranslateeq(self):*.check_excep]?obj TQ2 character '\.'@u0100rk"(CjOffff,Ci0U00-GiRbadandgoodstricts2# "# " complains about a non-; passed in<{rtRaise-OType#"s.w_s %42c) the wrong Etype<%E 9(P# If wcorrect&isV,rM? it Ens"B("\u3042", 0h e>c Br@\xffoes( UnicodeTranslateError,  cs.strict_e!s"E ("\u3042", 0, 1, "ouch")\!) def test_badandgoodignoreexceptions(self):/2# "# " complains about a non-; passed in=L.rtRaises(o Typu%42Ethe wrong EtypeFB([P# If wcorrect&isR,Preturn empty replacementYEqualx c "n/ascii", "aq!b"o2r)f("", 2 u-/Debytearray(b"a\xffb")p (H'$\v32Eu BadObject[ V o# With3, "'" "?" or "\ufffd$]E? self.assertEqual( codecs.replace_errors#.0Uni* DeE% ("ascii", bytearray(b"a\xffb"), 1, 2, "ouch")),u("\ufffd", 2) oself.a3Translate\u3042b"#def test_badandgoodxmlcharrefKexceptions(!)::L=# ". " complains about a non-F pEd inHW&ZRaise2Typ {=cs. ,%42kthe wrong UtypesRM} an only be used for encodingF    wvu0uW wv?", `# Use AvcorrectCbcs = (J9, 10, 9     0A 9J01@cs +kxd800, 0xdfff"".join(chr(c)+wc in cs(E"a" + s + "b" 1, 1 + len(s)m0 "&#%d;" % cR!) U>backslash= -<\ ; <:5 codecs.backslashreplace_errors, UnicodeE("ouch")  # Use the correct exception.tests = [g("\u3042", "\ )R ("\nMx0a"a.61C\x00/00#ff/ff4u01@ }D\uffD #0U00HJ+&10RU9 +# Lone surrogatesT$d8pu Awd #Q800\uL\0]for s, r in : with self.subTest(str=s)&*%assertEqual(H"48nAPasciia" + s + "b";1, 1 + len(s), 0(<((r.L$RTranslat &? DXJ/b" bE /b"* x+ bbytes=be/De`array(O@ + b,"bO1, 22!) 1defA_badandgoodname_ s(C7# "( " complains about a non-@ pd6d iQ.rtRaisesG2Typ J7cs.zN!424 VVwrongTG typr,  codecs.namereplace_errors, 0Uni)E("ouch")  7# "I" can only be used for encoding@self.assertRaises(ATypey  'Deascii", bytearray(b"\xff"), 0, 1, QTranslat("\u3042" # Use the correct exceptionStests = [ee "\\N{HIRAGANA LETTER A}")("\x00", "\ Rufbf9!N{ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH ""HAMZA ABOVE+ ALEF MAKSURA ISOLATED FORMU000e007fCANCEL TAG/S10fff/3U00 # Lone surrogatesW$d8'u A#h ud #B800\sL\0]ls, r in :SQwith subTest(str=s)&*%ZEqual"`I/3E"a" + s + "b"z;1, 1 + len(s)#<((r.$!) 51defD_badandgoodeescapei s(0G )_$ =blookup+('.';# " " complains about a non- p6d iml w !!42(7VwrongG typHD} 9nott/ on)0dc8 # Use the correct exception for s in ("a", "\udc7f ed00"):,3with self.subTest(str=s&*%assertRaises(I#UnicodeEn_rror,(surrogateescape_e+s,T ("ascii", s, 0, 1, "ouch")mZEqual $ "apA80b"2)(b"\x80", 2 k/Dec Dbytearray(b"a")aY/;b?1, cd def test_badandgood5pX s( '0 = cs.lookup)(','/9# " " complains about a non- 6d i.PTypeEQ  u q!42the wronge typesNB( an not be used 4translating e f Ts( 80@Use v 2enc Putf-8 F16le b &32O32be*ewing=enc#? "1 NRa(enc, ]7e {J'$ &Rrror(enc, "a".encode(enc), 0, 1, "ouch") for s in ("\ud800", 3fff `800\ud)):Iwith self.subTest(str=s&z%assertRaises(I#0UniEoError,(surrogatepass_e)s*R("ascii", s%olen(s)*tests = [v("utf-8,", b'\xed\xa0\x80', 3)5M16le800\xd8', 24b4Pd8\x0h4/32h8O', 4p/32px<;obf\xbf8Pff\xd4%164_df\xf44h<x V0<' J85 B>FC BYRJ o]1enc@b, n MBing=>, bytes=b _Equal*, "a" + s + "b"Y7{1, 1 +  @((b.2 =!Derarray(bb[:n] + b"b" n?b(s[:1]n!) v@def b_badhandlerresults( < = ( 42, "foo", (1,2,3), (1ACNoneo",), ("foo", 1, 3), ("foo", NoneS) )  encs = ("ascii", "latin-1 iso-8859E5") Bfor res inUults:e#codecs.register_error("test.badhandler", lambda x:HDd0encd a!self.assertRaises(#PTypeE,"\u3042".en%?enc d(Np bytes)b"\xff")~("utf-8", $ 7$?+x-G ni-internal.L\x00/)Qwith support.check_warnings(4;# uv has been deprecatedL;+ #0.ded"&=1def0_lookup($`Equal(cs.strictG3s, D"("$&")qNbignore8N$NxN $N `xmlcharrefreplac-  ;" "Ybackslash :'Oname5 zd!un4ablbLment/*G(excif isinstance 2, UEX 48 return ("\u4242", exc.end'Nelser ("don't know how to k` %r" %[Wd?B"A }C  "\u4242".encode, >enc"test.unencreplhandler"=!) @def ._badregistercall(self):$s# enhance coverage ofModules/_1csmD.c::V_error()SrPython/2,PyCodec_RE3.assertRaises(Type&#, G pF, 42s@!Mbdummy"N9olookup7;T 5; `unknow7tL, =", q"xmlcharrefvaluesuXMLCharRefReplacXs # and inline implementations*v = (1, 5, 10, 50     0 50A  = "".join([chr(x) for x in v])(cK&Eace"E sYn0encp("ascii", "iso-8859-15">1"rr1 `=. HLs(L err& deohelper"Objects/uniFo_^_b +"&er b"\xff".`&, X  2bad1return1(exc45 42:cs.- Q<",  V"W\&`-escap^)/x0`Mya t.baddecodereturn1") )self.assertRaises(TypeError, b"\\Uffffeeee".decode, "uni -escape", "test.bad#rgWuyyyycOraw-gKdef u2(exc):# ("?", Nonecs.register_e (=2",mIZ 7xff_asciiJE2") handler = PosRj(v 2pos3", F._ # Valid negative position.pos = -1Equal(b"\xff0*("), "027:N out of boundszOr3hVIndexi)/, * !GLargest v:  (one beyond end8Vinput 88 /In LRestart at the "0"6Hd\=g=t class D(dict3Z__getitem__([, key(_JHuJUKcharmap_N., "strict", {0xff:}G 3Val/, ^?D()U #Tssys.max3+1}|`F0_enTahelperfa# enhance coverage of# Objects/_object.c::unicode_encode_call_errorhandler() `# and "5ers self.assertRaises(LookupEE, "\xff"._ , "ascii", "test.unknown") Prdef bad1return1(exc):#5 42cs.register(h Q-",dOType h 2("?", None22I723q = PosR? 2pos3", F.A # Valid negative position3r.pos = -1aEqual(0(), b"0.:N out of bound 3XIndex) * GLargest v9  (one beyond end7Uinput 68 /InI 0class D(dict__getitem__([, key(&uTfor err in ("strict)preplace xmlcharref>["backslash(g "name _ 0Uni 0cs.3map>,, {0xff:}|^3Val/, \?D()S R "\xff", err$, {0xff: 300}) def test_translatehelper(self):$(# enhance coverage ofObjects/unicodeoC.c::0_en_call_errorhandler()e@and "7ers(Unfortunately the Bs argument is not directly accessibleH from Python, so we can't that muchclass D(dict 9__getitem__0[, key(,raise ValueEf.assertR%&s(&, "\xff".V, D()=ssys.max?+1}R 2TypQ-()Nbug828737charmap = {#ord("&"): "&",</lt>g1'"'[9quo }for n in (1, 100)text = 'abcghi'*n#( smutatingderbaddata = [c("ascii", b')2q("utf-7 ?++"O8", ? !16@B/32!  r-escape)n\u123gCraw-0,internal^/]replacing(exccif isinst 2, UD 48Bexc.Y = 42 return ("\u424.0o!FelseH2}@("doknow how to 0p %r" % |Ncs.registern (".5", yAwith .support.check_warnings(,#  has been deprecatedci(Ping, )x  * dY.\o $ X#29b"" $Indle %r" % eSxc) codecs.register_error("test.mutating", 9# If the deDr doesn't pick upmodified inputfollowing# will lead to an endless loop'Qwith support.check_warnings():,P# uni-internal has been deprecated3 for (encoding, data) in bad `dself.assertEqual('.I O), "\u4242") # issue325831def_crashing_U0_ha r(z# better gener one more charac@to flextra space slotx@# sodebug build it can steadily fail1forward_shorHthan_end(exc`if isinstance 2, UDKE 48a# sizec, 0 < } < exc.en<return ('\ufffd',*vstart+1+Nelseraise Type@("doknow how` %r" %_We@v# F$", BD  bnb'\xd8B00\x' 8Z'utf-16-le', '9'),?rx 500'/1/00bvL11\x /326 11%< 5yreplace_gP_long %object = b"U" * 8d) how to handle %r" % exc) !codecs.register_error("test.replace_with_long", %) Lself.assertEqual(mb'\x00'.det('utf-16', 'm9'),@p'\ufffdE'%/32& @def R_fakeRp_class(%):handlers = [,"cs.strictBs"Signord"#backslash,Oname'xmlcharref-blookup('surrogateescape4Hpass2]Wfor cls in UniF!En,DETranslateT FakeU;G(str)_@__ = sn) H.subTest(,=!, lO=clsIDRaises(Typ%, L )gFException}{P   ) 9(4()) if __C= "__main__"@unit9.() # Check every path through method of UserDict from import mapping_Z#s k`collecs d0 = {} d1"one": 1} d2, "two": 2} d33$0hre@W5} d4&@NoneC G} d5 1B1} h .RHashMProtocolPtype2{.Q $0Is(P.),56cNone(m;OFalsQ8$_before_19000@same!%B buta <^??1, 6V=O0001= self.asse rtIs(type(newdt), datetime. 3) self.asse6None(m) result, m = xmlrpclib.loads(s, use_builtin_qvs=False^R,) = KZxSEqual*6 dt>$ wDateTimu 7 def test_bug_1164912 (0%):d_((0_d,Y@ummypdumps((/c| methodresponse=True)qInstanc_d.value, str # Check that the output of ) is still an 8-bitC5ings7 ;gsnewstyle_class T(objectNEpasstWt = Tt.x = 100".y = "Hello"O((t2?t,)t2, t.__dict__H_big_longRaises(OverflowError,Hs, (2**99,)g!adgOTypec{(1,2,3): 1}jrecursive_seqoQl = [C]v[3,4,5,ll.append( l {'1':1, '2':1}{'3':3, 'd':dd['t'] = t. d! 2**31-1F >(j%4)& hMAXINToMININT8'(z +19k-kCd(_write(s. jMarshaller m._.MAXINT, dummy_write) m.dump_int(xmlrpclib.MININT, dum2self.assertRaises(OverflowError, S,gnnAXINT+1pV-pdef test_pdouble(!): %s((float(2 ** 34),)^+M))]2)e_ + 42j -75)) $'(s Fpass.Gm = arshaller(&1n-5 5j":o% :0,P=nonNvalue = alist + [None]=Marg1 = (,=Istrgc8, allow_wG=TruaEqual(`loads(xw)[0][0] CType1, ([ +encoding} = {'key\u20ac\xa4'6',$}V54), ='iso-8859-15'v"" + y." d!, Q.)e(, 'xmlcharrefreplace|!(@ ` methodresponse /0nam'WK methodname=methodname) #self.assertEqual(xmlrpclib.loads(strg)[0][0], valu=H1], |}def test_dump_bytes(!): sample = b"my dog has fleas"% 6&, rBinary()for type_ in ,^arrayA " =A\"7s =1s((7I,)) +result, m3, use_builtin_Hs=TrnC(new]2 = Q d] 1 /0Is(vb)'sJ`IsNone(m-GFalsof/,)P D_unsupportedResponseError data = '!><><5s>'HyRaises(p , zO = (Dp'%2'a"', ' C')  3𝔘𝔫𝔦𝔠𝔬𝔡𝔢 = P0mint>205618394746093.781250AGJ5dGUgc3RyaW5n/w==20050210T11:41:23''<1#b205"i2C9876543210A4', 3bigdecimal.e" ".DC&('D%get_host_info # see bug #3613, this raised a TypeErrorS=transp = .client.TFort(`assertEqual(<.`"user@].tld"bu ('host.tld', [('Authorization', 'Basic dXNlcg==')], {})) H def test_ssl_presence(self):!l6try import ssl$except IZError30hasd = False8?lse*6Tru) -xmlrpc.client.ServerProxy('https://localhost:9999').bad_func&()NotImplementedq.assert(2, " @'s e with SSL sup3"t/OSh g keepalive_disconnectclass RequestHandler( !.s2.BaseHTTP#protocol_version = "5U/1.1"G*hcd n|do_POST<length = in.headers.get("Content-L'&")P=rfile.read(Q(1if + I"cclose_` -mreturnresponse = )lib.dumps((5,), method'=`4 = w.encodeTsend_,Status.OKd7x sd, len(TxAswVwriteO :0 = $def log_messag, format, *args6 # don't clobber sys.stderrFpasssoBrun_l([.socket.settimeout(float(1)) # D{shang ifai fails}M+"_r(BcFirst  and attempt at secondKsRetried6T8 = csn#(( .HOST, 0),addCleanup([_- th2 = Qing.T(target= 5g.start ySV.join<0url://{}:{}/".I*(* ads= url) as p self.assertEqual(p.method(), 5) Oself, ! class SimpleXMLRPCDispatcherTestCase(unittest.!):g=1Exc(Exception""""Raised inside the df`d func3s when checking forfDchained e`Qs""" @def _call_registered_X( Calls explicitly 3]w# Makes sure any- rt has no othe#<Rto itnexp_params = 1, 2, 3:*/H .,Rr = xmlrpc.server.(b$r.D(6Bwiths0) aRc_ctxnZ4r._ $('  ',K}x=!exb.Y.args, (/,)@~IsNone(A__cause__7`ontext9instancec/2"""a3 attributeUa X0edC 'efD/, 9(.N((s0&0eE's `]`1rp_method = 'method' exp_params = 1, 2, 3 class TestInstance:Adef _dispatch(self, b", V)15raise SimpleXMLRPCDB erkTCase.IExc(sB ger = xmlrpc.server.t%()a<.register_i(&()5Pwith .assertRs) as exc_ctxvM OqcEqual([.exception.args, (>JKoIsNoneL__cause__7`ontext93Ttest_aed_func_is_n|6p"""Call;plicitly ; ; which is ?"""Gs(j, name='a'tRegex(E%, 9,A, ('B',))V0_haP[ SAttempts to call {x&ntTHon am]_Je(objectjTNcannot_locateRa=that the  J JF6kW FHelpP(unit."llescape3Clib.1"a&b"), "a&b"_=<=/lt<><g<TFaultLreprfQ`(42, 'W G Sf<,I 42:<>&ssertEqual(repr(f), st) def test_dump_fault(self):#f = xmlrpclib.F#42, 'Test %').s.Vfs((f,)"(newf,), m+vloads(s(.assertEqual81 {'qCode': String':}Osm, None  Marshaller().fO{Raises($,53, sluotted_attribute{# this will rf$ A+Error because code don't want us to use# private methodsh e,*$ .server.resolve_dt, '__add,3elfCTrueBN (str, 'title')) class DateTimeCase(unit.~e9 u with mock.patch('time.local e') as _*-&_struct = ._ (O[2013, 7, 15, 0, 24, 49 v196, 0]xa }.return_valueq k6$(_X %6W/t)- % f "%Y%m%dT%H:%M:%S",X2v = 1181399930.036952dO!k?(d)]_tupld = (2007,6,9,10,38,50,5,160,0' '_0609T10:38:50'@ ; 2e?strgdW@date7_ . o1,2,3,4,52d102T03:04:05dr~ 1val ="" % id(t) self.assertEqual(repr(t), val) (def test_decode(4!):Fad = ' u908T07:11:13 '# t1 = xmlrpclib.DateTime(3t1.^d?ref9datetime. (,9,8,7,11,13)G t1, tref)t2i_XH2H(comparison,dnow = ]G.now d 2@now.wtuple()#WT vs. 2STrue(e_= now,&!= -&Qthen :% +wdelta(seconds=43 C>Z 'y0 < / ?strdP.strf-("%Y%m%dT%H:%M:%S"q0== H'f >_(}J&?str <3 *ome other types`dbytesastr.env'ascii'mdGWwith Raises(TypeError+# == 1970E+2!= G+0== barray(Q"7+< float(*,>*2<*>* class BinaryTestCase(unit|."):# XXX What should str(>(b"\xff")) return? I'm chosing P# for (i.e. interpret(Qthe ba as Latin-1-.dD(text). But this feels very unsatisfactory. Perhaps weEonly define c), and4 r"' ')" instead? def test_default(self): t = xmlrpclib.Binary(). .assertEqual(str(t), '') &def test_string`d = b'\x01\x02\x03abc123\xff\xfe'Edd, "latin-1")odecode' dease64.enLgbytes(/t1H 3t1./de O1), )2l"_bY2Y: ADDR = PORT = URL = None # The evt is set twice. First when the server%ready to . # Second,has been shutdown. muser must clear # aevent aftf&t =Ahe f@time|Qcatch8s}set. def http_r(evt, numrequests, Handler=!, 1ing;class TestInstanceCXl1divuc, x, y:return x // yK8_methodHelp@Kname@0if  == 'div'{GbP'ThisGdiv function'vzFixtureJr@static`getData(#42ieMyXMLRPCSe2(|.x.Simple!Yp_t# EnsureAockealways non-blocking. On Linux, s* # attributes are not inherited likeyon *BSD and Windows.N`s, porQpw.acceptnTs.setG(Tru0 WR +ot1=uR +; = ("localhost", 0)<,<Q - 3logs=False, bind_arctivateX6try'dlpglobal ,,! =.0get |N#connect}IP address directlyis avoidsp.create_;8ionQ`tryingP u0 us 5alln families, which #cau9'''&return Truey(name='addk_(x, yYUx + yZtestInstance = TOClasi5(B, allow_dotted_ s=Devt.set() # handle up to 'numrequests' .gwhile $J > 0iT_@L?B-= 1except socket.timeout[Apassvfinallyq7Hclosf = NonP__Jxer(evt,,H* r=Occdiv(self,B// y %8_methodHelp@z%0if  == 'div'{|vthe divvrA=doNMyXMLRPCSs(xmlrpc .MJHPath$5getFC# Ensure always non-blocking. On Linux,eOF# attributes are not inherited likeyon *BSD and WindowsN0s, 0 = .0.ac s(AKZR]+otw: = xbSimpleuR+ (Urpc_paths = []DBrokenDispatcher_marshaled_d#ddata, v , j 'aise Run:Error("bI3er"; = ("localhost", 0), My,!   logRequests=False, bind_arctivate ) 4 serv.socket.settimeout(3`erver_G(Atry:>Bglobal ADDR, PORT, URL8 = n0getxCnameWN#connect to IP address directly. This avoids Aet.create_;8ionQ`tryingP "localhost" us 5allnfamilies, which#causes slowdown e.g. on vista- supports AF_INET6eer listensT$on*e only.URL = "http://%s:%d"%(P5Wapaths = ["/foo", e/bar"]n@for )1 inscdadd_dispatcher(3, xmlrpc.er.SimpleXMLRPCD+)R@.reg r_introspection_fun s 1multicall-L.getVs[0])vhF(pow=1=lambda x,y: x+y, 'add'P 5"/is/broken", B )!ev5() # handle upS'numr$' .gwhile $J > 0T_@ z?B-= 1dexcept:[2pasgfinall2q8losAu = None# prevents errors like: #/ def is_unavailable_d"e)'''Returns True if the given !isproduct of aE-sidd qAd by8'temporarily sponse some{# by operaasnon-blockRs.'''#H we get a -1f code and/or empty headert if e.err3 ==D5.11 isIrNM@xc_m 4= e>E('X-/w Attributec# Ignore OSfs herexekSstr(e|Oand 4in Ds.lower(* `DmakexskipIf(condi, reasonE@# Ifskip the testJ, we have to make a request because # the server created in setUp blocks expecting onQcome in.Cif not condition:]return lambda func:!def decorator():__and_skip(self)g6try:xmlrpclib.SProxy(URL).my_o!()1except (=ProtocolError, OS n) as eu is_unavailable_V[ion(et3rai unittest.SkipTest(reasonc,!j class BaseXUCase(nHandler = Non>_count = 1sthreadFunc = staticmethod(http_m!) ,sl @# en> traceback reporting:&.R.SimpleXMLRPCu._send_CQ_headBTrueHU0.eving.Event!#$rt-)_h_s_args = c!, m : hj"= Tc(target=Rv , u= JX.star@addCleanup(KS.join%# wait for4`to be y lf.1Bhevt.clear(\tearDown'wt)onszterminat1c{_# disQHTFalse]M(rAst_s1 Bp =  assertEqual(p.pow(6,8), 6**8## ignore failures du*Pnon-bF>socket '0' eZ5G!3# pR;rvide adal informa[y output5I("%s\n%s" % (e, getattr "Os", ""))st_nonascii@_str= 'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t'BhBTIN SMALL LETTER O WITH HORN}n' Etry: p = xmlrpclib.ServerProxy(URL)+self.assertEqual(p.add(start_string, end )),>m 8( +98except (ProtocolError, OS j) as e-# ignore failures due to non-blocking socket 'unavailable' e]sif not is_*_jion(e)~43# pR;vide additional informa in test outputP("%s\n%s" % (e, getattr "headers", ""))) F1defZ_client_encoding(S = '\u20ac> Bxa4'a[*='iso-8859-15's2.$x.M$!s.Pwnonascii_methodname{>'Z8têšt(42), 42gd# [ch] Theo 404 is causmlots of false alarm0XXXL_404# send POST with http., it should returnwE andQ# 'Not Found' messagepaconn =[ ^.HTTPConnec(ADDR, PORTB9.request('', '/this-is-not-validresponse = >4get(Ycclose( response.status,s 404)  self.assertEqual(response.reason, 'Not Found') 8 def test_introspection1(L!):#^ exed_methods = set(['pow', 'divamy_funC0addtêšt',NR'system.listMi@{OHelpK5SignatureOulticallN1Fix?]n6try p = xmlrpclib.ServerProxy(URL8+S = p.(* w?<), :except (ProtocolError, OS j) as e-# ignore failures due to non-blocking socket 'unavailable' e]sif not is_*_Wion(ee3# pR;vide addial informa1 iny outputPD("%s\n%s" % (e, getattr "headers", "")))  2 #/ -`divhel10!odW{B, 'This is the div B<,@make_requ_and_skipIf(sys.flags.optimize >= 2"Docstrings are omitted with -O2 and above"3native docHN yV'1mM/myrmation in test output self.fail("%s\n%s" % (e, getattr "headers", ""))) F def test_introspection4(R!):#l'# the SimpleXMLRPCServer doesn't support signatures, b# at least check that we can try makinggEcallz6tryp = xmlrpclib.Proxy(URL)8+ divsig = p.system.methodSj('div'5.assertEqual(F6, '5 no'edAexcept (ProtocolError, OS j) as e# ignore B due to non-bloc!socket 'unavailable' e]s!if7is_*_Wion(e,3# pR;vide addial informa1 in=HPmulti )U KMkjCall(p/.add(2,3pow(6,8div(127,42"add_result, pow 3div 5 = (= N+2+ .p;6** /x, 127//]9non_existing_ bthis_is_nots  "# $.s contains;'[{'faultCode': 1, String': ':'S2 ' . "A" is=bed'>}]0' &B[0][O], 1 @ltString'],  &':method "this_is_not_exists" ' D 'is not supported')$eW (xmlrpclib.ProtocolError, OS u) as e:8d-# ignore failures due to non-blocking socket 'unavailable' e]sN!if7is_*_jion(e)~pR; provide addi.al informa in test outputPPself.("%s\n%s" % (e, getattr "headers", ""))) F1defZ_dotted_.`ibute(T# Raises an Attr%c because private Qs areallowed.qbassertU(R,*. .server.resolve, str, '__ad7Q.{CTrue@O (Nvtitle')# Get theDCrun faster by sendL`a requAwith-_simple1# This avoids wait;1foravtimeout6Q("pnames_t: XXX also need 7Bfals2 = S Proxy("http://%s:%d/RPC2ADDR, PORTNsdata = Fixture.getData(v`Equal(9l, '42'unicode_hosth2 \p.add("ar\xe9"), "a ~partial_p# Check that a + POST doesn't make'| loop: issue #1400hpconn = .client.HTTPConnecn(96. ('}A', ' ? /1.0\r\nContent-Length: 107byeQ]closecDxt_managerDo1URL yF2, 3Pa2NotW1p('trans@')._' S (None, kh- a E__ R:try,cerver:  server.add(2, "a") except xmlrpclib.Fault: (Epassself.assertEqual(] ('transport')._connection,:K p(None, )) class SimpleSEncodingTestCase(Bas)@staticmethodsdef threadFunc(evt, numrequests, Handler=3, er\Shttp_K , 'iso-8859-15') 3estF_j(Rjstart_string = '\u20ac'D8endBxa4'a2try 7p =VProxy(URL+ p2 ~)O&+ v}(~ProtocolError, socket.ej) as e# ignore failures due to non-blockEF unavailable R%s.Uif not is_*_Wion(e03# pS;vide addial informa in test outputP("%s\n%s" % (e, getattr "headers", ""):MultiPath"58 = A(mP3_count = 2j\path1 g+"/foo_p.pow(6,8), 6**8,+gRaisesH!, l, 6, 82 O/bar g+?pow3is/broken6"#Acase that verifies"a 0 usmthe HTTP/1.1 keep-alive mechanism #does indeed<P subs$ntPs on LVsame O%AKeep\$#a^" h0supsand logs2Ato a#@variNR#stT.!.jXMLRPC)ZqparentC A protocol_version = 'HTTP/1.1' myRequests = []def handle(self):9.;.append([])'reqidx = lenL99)-11qreturn _parentClass.1b_one_rc result =Y@e[]$awJline  aHhCr = $\setUps#clear DA log0 Lu BaseServerTestCase.v #A test case that verifies1a s> using the m keep-alive mechanism #does indeed<P subs$ntAs onLsame connection cQ KeepX 1(WL_twoZp = xmlrpclib.\Proxy(URL#do three. assertEqual(p.pow(6,8), 6**8G:+>p("close")()m #they should have all beenpd by a lruH), 1Rcheck;we did at least two (Athird may be aZkb#due tad schedulingarGreater[-1]), 2) #. special attribute accesp-,Aough__call__ #fun. 2#ask for3f #bed/_count=2 3(5som6qs with S|CVd #thistrigger a new4tn+C[ have all bee&n two request handlers, each having logged at least #;completeDsself.assertEqual(len(RoHn3.myos), 2)AGreaterHO[-1]L72L def test_transport!):p = xmlrpclib.ServerProxy(URLv#do som: with close.M1Fp.pow(6,8), 6**8Q5p("1").I () #same as above, reallyb%V6")(w 1 #AJ case that verifiesgzip encodworks in both directions #(for ap and thXsponse) @unit.skipIf(Zis None, 'Pires ') class GzipTestCase(Base#E0sup#s keep-aliveDlogsAto a#|variable%6(b!.s_0.SijXMLRPC)aarentCA? rotocol_version = 'HTTP/1.1''!|do_POST#store content of last v4c!__3__.<_length = in.headers["#-#&"]Pqreturn Wp.3estu: = ]% T#custom !, Be re  our perusalPfake_r = Fals*dparse_L[0+T=RB.getY(XO, 0)[. KSsend_Bconnk, body"ifU#add a lone  to induce decode error remotelytD5.puC#-E@", ""!'#1tUp 5.se(=def test_gzip_request(self): @t = .Transport() .encode_threshold = None"p = xmlrpclib.ServerProxy(URL, tU&=tVo assertEqual(p.pow(6,8), 6**8+aRHandler.content_lengtht0 #turn on  5ing9bZTrue(a>bp("close")() def test_bad_gziEat.fakeb0 = !$cmRaisesRegex(ProtocolError,qure.compile(r"\b400\b")Bvwith cmIP Jkgosponse +!El!-O #no*rBt.re a0 #always/@# }.:old[p @unit.skipIf($1 is0, 'Pires  ') class GzipUtilTestCase(F+):@1_deeMlimi1max% = 20 * 10240datb'\0' * :'g(Ga.(5d1 Blen(-Breturn 'I am broken'0sup\.j~bn ev?threading.Event# start )handle requests)_args = v.evt, 1-D"= vT(target=_H@er, K= U F.addCleanup(dS.joinQQ# waie_xb7ady lf.1 hevt.clea 2LtearDowndt PterminateI1c {# reset -y..SimpleXMLRPC'.If= Falsu]mA rfdefault_0 = Z0R8HF#r. =4h ^basic]check thaf4 byO: va7 J[,W s`enablei0 re5ingO$r = True);!# Aba call`should0q just a-Amoke0try: p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.pow(6,8), 6**8/except (ZProtocolError, OS y) as e:g-# ignore failures due to non-blocking socket 'unavailable' e]sNif not is_*_jion(e)~3# pR;vide additional informa in test outputP9("%s\n%s" % (e, getattr "headers", ""))) F1defZ_>@_no_v(P# use the broken message clas!.s.SimpleXMLRPCRequestHandler.M?C> = Failing:try@P?O8 and has# The two  -sN  shouldn't be sent back\his case(T sTrue(e.N.get("X-Qion") is NoneBFPtraceF;elsP)('raised'Owith~# Check thats/do/3#3 when flag&se.u._send_Y_0 = !#Wethe responvexpected_err = "invalid literal for int()  base 10: 'I am%'"7` (, t("X-traceback") is not None) Uelse: self.fail('ProtocolError=raised') @contextlib. manager def captured_stdout(encoding='utf-8')v """A variation on support.A) which gives a |q stream having a `buffer` attribute.!1"""Corigr = sys. = io.TextIOWrapper(io.BytesIO(),  W2tryN\yieldegfinall& v class CGIHandlerTestCase(unittest.R}`setUp(.cgi = xmlrpc.server.CGIXMLRPCRequestj1() QtearDownTX1st_cgi_get5Ewith EnvironmentVarGuard() as envGenv['REQUEST_METHOD'] = 'GET'&# if the methodGET and no r_A!isQn, it runs hh T0getout output  =|.data_out0## parse Status headercr.seek(0;]5 = &Zread(%s\=.split()[1]ipmessage '.join(_1C2:4]S}assertEqual(m{, '400',rs, 'Bad [_response = """_)"foodatetime argumentD. P.log = []^expected_= b"my dog has fleas"-hx (2008, 5, 26, 18, 25, 12marshaled = zdumps((%, p), 'foobar'Og(*args.extend(#r.server. allow_none=True, encoding=None,'|.register_func^(*_;_(/Dhlog), y@, mya4 = (#Nelog, [FM]0Is(w(q ), B7 k2),  3cgiWN_has\_flag2 2CGIRH-r( !2(`.8`_1 S(("localhost", 0k use_builtin_types=True) rserver.x_close(lf.assert7('.use_buiU) @support.reap_threads def test_main():y*pun_unit!(XMLRPCTestCase, HelperDateTimeKu Binaryf FaultBUseBT DqSimpleS" Encoding @KeepalivC?1, )2,@LGzip~OUtilrMultiPath7IProxRilingQCGIHandlyDispatch if __name__ == "_2__"() """This is ab""" "tn't a doc string" from __futur^ imc nested_scopes e3f(x^s3g(y!return x + yrg result = f(2)(4) # 8s some corner cases with isinstance() and issubclass(). While these # s use new style ,!es=properties, they actually do whitebox Hing of error conditions uncovered when us)extension 3. :osys 3IsIQExcepe(7.^. to make surat an AttributeEQaccesDthe K!'s#A's bqis masked. 56was"a bug in Python 2.2TJP2.2.14e e@ washcaught but it also beBsclearedO@(leaan "undetected" dedSet up is#@b, cls)-#r-! ia@, or5Iuple%h1 __6D__ ay&k ''5.__!Os noX^ Sounds complicated, I know,^tPmimicPsituaT3 anG @ raitG?its$ iIgotten. In that,~) should aFalse.A bhas_no^S(selfZ+ I(objectH1get$ 9 #Dmust2an OENone __class__ = property(getC)  C(object): def getbases(self $return ():!__5 U.assertEqual(False, isinstance(I(), C())7 # Like above except that 21.__6__.raises an/1ionp# other>n AttributeError CtestG_4t_than_a4 _e5 #/ E\(w Runtimw  eI $ eE6 ?drRQ(s(Rl%, m" # Here's a situation whereu(cls, '2') ( o.P@# Ifmt{ is not~, it shouldget maskedHPdont_?_norI: pass3T/ ,\h?get R#rwhich // a7TyprJ E  /- Rcheckzrwe don'< noasxsee: http://bugs.python.org/issue1574217/h_    > =swc, bool` #  another code paCth class D: passrself.assertRaises(RuntimeError, isinstance, c, D) # These tests are similar to above, but tickle certain code paths in # issub0() ggead oft () -- really PyObject_IsS8h # vs.IA(). ]V Test4Exceptions(unit."aCase):1def _dont_mask_non_attribute_e(<2dm1C(oSPgetbac 9 r !__>__ = property(T%) ,CS(C)x sY, C(), S()Y+ SAp E6Typ i# Like est the second branch, where of#0Parg (@ clMQg) ised. This means:p first 3CmustIreturn a valid o, and it's okay for it to be a normal --Gunrelated by inheriU.)  _in_cls_arg)Bc @o&B)$fF0,%Qmeta !es|creating abstractsA%C V__init__^!, u" =";5;4H;OxVc__callVg+)  F_ kfN. = klass  def getclass(self): preturn  .k!!__-__ = property(C) # abstract )Ces ASuper = CU(bases=()) )_Child)>N,7# normalqy !bpass ]( TestIsInstanceIsSub8(unittest."CCase> # s to ensure that isiD and issI work on(W#.;s. BefoUe 2.2 release, TypeErrors wereFraised when boolean values should have been ed. The bug wasItriggered by mixing 'h'S withC' 1xis case trieEdC allEcombinations. &_d_ assertEqual(True,#2(),I!))|;0Fal<n<$ D, 3$< , ! U ;LL,e e D;K(D1M1C eAQ? : B self.assertEq ual(True, issubclass(Child, C)) self.assertEq9 _Super9 OFalssAbstractB|def test_#_a'(!):&$#  %es* |),  ;JP JB ;  I hJB/I1)) .^tuple+S with a # as the second argumentK #, I)> h<,< [5y# < 7 j." ()EW Fbint, (float, intFA  Ebstr, (1strE]recursion_limitgmake sure thatg raises RBError befo-e C stack iq# blown RO(O,0G!, 6isinstance_A, ''0) 0P(fxn,, compare_to=:# Mcalling +deeply nested9bfor it#c9Bwill eventually._arg = (,}_cnt in range(sys.get{3)+5 S ,) fxn(a+rg, tuple_arg) if __name__ == '__main__': unittest.() """ Various s for synchronization primitives.2 import sys time from _thread $tart_new, TIMEOUT_MAX>34ingweakref c` up def _wait()# A crude /yield funcnot relying on :.sleep(0.01) class Bunch(objectxU30A bB of !s. _init__(self, f, n,_before_exit=False^ZB Construct ap4`n`tP runnthe same2`f`H@If `(y` is True, > won't terminate untilIdo_finish()?fcalledhe.f = f>Zn = nsHzed = []mA_canBP-otY IB = sY.sL/()7.__enter__() &Dtask% tiqing.get_identb(.append(tid%2try fJofinall)cIdW`while =4b}.  pi in range(nAC(MF, ()jexcept ! =YRraiseAfor_q!ed1len.&A) < kn _hG`'a a# WaitT s =x|fNone, ?.^aseTestCase(.G`\setUp \sing_setupdHrtearDow`;cleanup(*fK2reap_childrenkassertTimeout, actual, expectedB# Thqand/or N() can berecise, which#Fwhy comparing to the expected value would sometimes fail # (especially under Windows).&self.assertGreaterEqual(actual, ere* 0.6)8# Test nothing insane happened'_OLessW10.0) class BaseLock^ s( aCase):V1"""s for both recursive and non-Rlocks>?def test_constructor(gE80 = . Vtype(@del  Q?repJbaRegex(D\p), "">_Uk:x.acquirE56'o_destroy|lreleasel3RCtry_QTrue(xKfFalse)~ otendeda~xresult = []tX|'f().Ad Bunch(f, 1).wait_for_finished!(d6[0]=_N = 5 ) Eb = Nb$Ystart#_@a3dlen(b.]F), 0Z q8b+N)ROwithcUG_terr=Nonif err is% <$,Praise+rh # Check the lock is unacquired Bunch(f, 1).wait_for_finished()(self.assertRaises(TypeError, _with, 7# Check the)def test_thread_leak(!): 4# Tjshouldn't )A a T7 instance when used from a foreignMR(non-oRing) ."Y = . Gtype5'f((.,hreleasGn = len(~ing.enumerate()lWe run manyAs in}hope that existing"ds won't# be recycled,5- /ifV != n rea small window dur^which%'sGtarget function has ning, but{s stillL#alive and registered. Avoid spurious failures by @aJbit more (seen on a buildbot)_time.sleep(0.4fEqual(n,g!) 5limeout1 @# CaC@set out if not b;1ingg #DValu$.0, 0q:# Invaliddv:[V=-100ABOverflow E/1eF1TIMEOUT_MAX + 1(# Uis ok(/F*7At1 =Q.>k QTrue(@,Wout=5Z/t2J# Just a sanityfQit di~ractualld|gLess(t2 - t1, 5results = []( eG.append(0.6 S;: cFalse(Y6[0]M%T'@1], def tes t_weakref_exists(self): plock = . etype()cref = CP.ref(% 8assertIsNotNone('1)) Evdef tesdeleted<@del t  class LockTeEBase1"""K" for non-recursive,rs(-(which can be acquired and released from different threads).Aq0#reF *# needs topcbefore re-=2ing_ phase = []3#f(H.`+D.append( *:7with support.wait_<tstart_new&j(f, ()while len(f) == 0u_mmfEqual(Z:, 1{ [1 2#?cab9ez'b = BunchZbfor_finished6ydpstate_after_timeout Issue #11618: check that is in a proper R R! amP0# ([czero) iR-.QFalseeW=0.01 L-c(;Trusb0Aing=Ry(cs*=( @.. E3_un7 8# Cannotg an unacquired lSock lock = self. etype() assertRaises(RuntimeError, 3.release6hacquirM D{. Edef test_N_save_un d(T!):,E# Cannot 1F an 4(2t- mz "different_threay from a 8 8Vx y'f(4.b = Bunch(f, 1, Tru6try F3.GkfinallKb.do_finish.wait_forQed() _is_owneI `False(0.N)B)AIresult = []~ ).append)da&a;[0];A | class EventTests(Base C1"""6Rs for0 objects.% XZlis_set evev[Cevt.JS]FRM/"8;_clear ;H_check_notifyJW, evtS# Allas get -1iedEUN = 5!s1  results2 = [] def f():0res+1.append(evt.wait())(2( b = Bunch(f, N@bR_for_started(_nmself.assertEqual(len(F), 0;7setMjifinishk [W, [True] */2/\test_notify(<j`evt = .eventtyped_checkA6evt# Another time, after an explicit clearR &x t?out\  QN = 5uL;0.0At1 =).]@r = v60.5et6;+(r, t2 - t1LFalsfor r, dt in G ;B*(r @TimeIdt, a# The u is setu^V9c 1Ahset_and_&# Issue #13502: a that D) returns tru:w when tHpa#ed before&Hing threadwwoken up.9B  mW "Eisleep(`z# reinternal_locksa# ensuat conditionstill usca LockXAwith~_] (.acquire(k"_nal_locks()  with evt._cond: self.assertFalse((.acquire()) class ConditionTests(Base RCase)]1"""e`s for y4 variables.#+ def test_wPB0 = . atype();# Be default we have an RLock: thescan be jd multipleN4tim_rv hreleas.lock = threading.7 5-6h.E_True(D -_(UiJnKr9N* \? \M#un pd_wait(DU.Raises(RunaError,R.X/) wonotifyyAZ{r_check_r# Note that thiss is sensitive to timA If:cworkers# don't execute in a<ely fashion,@Cmain>@ mayz nkyLare further along!7ey are. The K+efore issue) statements rymake surpit doesrace aheado Se lyLrassumesc  not subjectito spurious wakeupsabsence of"qan implaU`detail:$ Ccurrent CPyth0butgeneral,Pa guaranteed property_0s a%@gramSHconstruct. In particular, itspossiblt0no 'erLbveniently`shouldK+ir% ever changeUN = 5\gy = []osults12phase_num = 0B'f(x?.append(S $ = cond.wait()' cond.release()results1.append((, phase_num)1LnacquirL4adyI@p1 = HKwait 2c b = Bunch(f, N b.u_for_started# first #, to ensure all workers settle intou before@# we tinue. See issues #8799 and #30727.4while len(ready) < 5:_(g.clearself.assertEqual)fs1, [] # Notify 3 thJBs atun>&(3R J = 1T3  (True, 1)] * 42Umake oawaken  5: they might bu"ir` or sez. 52T+285C + [22 4 *#   Knaa#in#G_all 3+ v(E, 3 afinishdef test_)0 = . 8typd_checkA&4# AAtimeE/1ernal stat  still ok_ Z@out(/cond = self.condtype() results = []UN = 5def f():;Kx.acquirOt1 = time.lp1 = Await(0.5$/t2A8lreleasy\s.append((t2 - t1, )fBunch(f, N)._for_finishedself.assertEqual(len(N s)>dfor dtk3 inus7QTimeout(6 # Note that*ceptually (`"s the dition variable protocolQ@# a )() may succeed even if no one notifies us and before anyMout occurs. Spurious wakeups can.; This makes it hard to verify]l value=In practice, tJimplementa0hass HSFalse!) Ptest_0@for(/0 = . Ostate = 0M/Q >Awith 0!(lambda : b:==4:6Tru(S', SEb = $1kb.Ystart-igange(466.sleep(0.0UU += 1T2.y=_YSsGn/dt,kout=0.iG hQ - dt  (!) {(GNone^v!# Only incr ! 3Rs, so- == 4 is never reached 3#hfO), 1) class BaseSemaphoreTests(BaseTestCase): """Common tests for {bounded, un } semaphore objects.=E 1defC_constructor(selfnr .assertRaises(ValueError, semtype, va = -1)`@&sys.maxsize) K~acquire9m =($m.9m.release( J2J`v_destroy 0delE te7j7k aN = 10m_results = []12phase_nu[ 'f( p.append(se.+i '%se*U2+Ub = Bunch(f, 10nb.wait_for_startedwhile len(8) +b2) < 6$_QEUEqualL3 + W2, [0] * 6ti in range(7/13!so/1)P + [12699J2P# The is still locked@Fals`<)# Final =, to let the las read finishdp0 p, [True(6 + 7 + ,1)5Dtry_R se\.(#lfk R D`,G Yse))  sem.release() self.assertTrue(&acquire(False)) -def test_try_"_contended(H!):*Z`sem = .semtype(4u#m.Cresults = []Iw'f(Z^*`.appen|O'/Bunch(f, 5).wait_for_finished# There can be a thread switch between ping theaphore and"# &,20ref. s will not necessarily beJordered.Equal(sorted(SA), [2] * 7 + [ < 3 e_timeout2hRaises(ValueError,!, #, gO=1.0G 1o0.005)46ib1t =.!w dLO - tT|dt, 0.5default_v  # initial +X is 1 +Eb = 12b1sta_~ $b.5h3(cLwithZHU_7err=None)]#J I[A0lp_ Qq9nif errrN#{4Typo%, y1 class Sem1Tests(Base1"""' for unbounded semaphores. """ def test_release_unacquired(self):'4# Unbounded ."s are allowed and increment the semaphore's valueM`sem = b.semtype(1).c(B class BSTests(Base&'T for P*Cannot go pas2initial.lf.assertRaises(Vk`Error,K3/m.J4_gaarrier7^ OCaseXB2w objectUQN = 5defaultTimeout = 2.0\setUpb_rv BN, tT= h8*oarDowne .abort()run_threads9(, Wb = Bunch(fWlf.N- fb.wait_for_finishedhmultipasfresults, nxMw.parties`!tEqual(m$ i in range(`y[0].append(True?$ gDlen(91]), i * m5 U@y$0y(i + 1)  n_fing, 0#kQFalse.4gbrokenH+,8Wses=1x that a 92 is6 lockstep>N = [[],[]]& 'f(um> f1_10hQworks10 consecutive runFbreturn a,10_0 F+T fromM sn r?Ts.append(r) # self.run_threads(f) assertEqual(sum(results), Qange(EQN))) <def test_action!):v5""" Test the ',' callback#/}U = []!o>(fj/.append(Truebarrier = 4typ", V3jfe9f.wait(,YA7lenA10+ tMObortLpat an a. will puc in a broken statehk1lR2 6try^io6(Sf i =NN//2K'raise RuntimeErrorn1)FPexcepG%Qing.B@BDzW2WG  gBpass~3 NV1), 0+ 2=?N-12n.~t4Orese! '.1' o~a freesFCing  %3ip# Wait lTother are all6ZYwhile4.n_<>N-1m=M.sleep(0.00} Nelse] P O$&"9_p# Now, ni again #l3C?;qual(len(results2), self.N-1) assertEqual(len(res2321) 2 def test_abort_and_reset(G!):$Y5""" Test that a barrier can be < after being broken.=Ie1 = []"23,.Atype&.N'f(6try2i =YOf.wait(J$cif i =,NN//2K'raise RuntimeErrorn1.append(TruePexcepreading.B}BzW2WG M1Ipass# Synchronize andB4the[. Must s)0firoL everyone has left it when w,i"sonLB`enters@pbefore $if2 -Q -yO =3C?`run_th'6s(fE<_1), 0+,S4/ou -nS  O // @# On!T is late!u.sleep(1.N# Default &0outGQ2.0,  iszshorterRl"s(,~NV, 0.5T ASad_xL3's >[7# createwith a lowB -,uF=0.3:Q& 5&rnk  of 0.3s.  time.sleep(1.0) "self.assertRaises(threading.BrokenBarrierError, bV.waitJFBrun_=Qs(f) gdef test_single (0!):"@b = .^ftype(1_bo(import unitgQ fromq 0sup" $gc tweakrefoperatorDcopy bpickle\drandom^range, shuffle4warningscollection5.abitertools class PassThru(ExcepC;`pass c`check_b#u(!r@otyield 1\bBadCmpI__hash__return 1D)#eq's, othertx0Runz9pReprWrapperu'Used to -referential repr() calls'}xt.value)}`HashCongInt(int='int-like object that c,s the number of $s (1 is(edCinits, *argsh.f`G = 0  4#+=QDint.TestJointOpsv # s commonboth set and frozensetRsetUpWCzsword = 'simsalabim(%&madagascar&0letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZNH1theUGPdict.<Rkeys(%Y_new_or_ CAType,~{, [], 2:Qt()._s|__, a=1Uuniquifica `actual[Qorted&.s~pexpectes"d" bEqual(S$, ;+H  E J<[]]1len m$U.s), ,d)LcontainsQfor c int0's,=i> Ds.__[os = self.thetype([frozenset(self.letters)]) assertIn&rthetype 3Q, s) 6def test_unio3!):SAu = T&s. .otherwordyfor c in.gHLHaEqual(0'u,8)d Gh E"s,x )#u);1bas(1Raises(PassThru3, check_pass_thru()E TypeErrorF7[[]QCQ5t, , dict.fromkeytr, list, tuplet ''abcba')C('cdc') t('d'Q YefgfeS?efgU-9ccbSP-)efO#q'), C('O\# Issue #6573xuODxr[1]), xo2[2]4lf.H@[1,  !ori U@s |  ?, i-: v @?try@IvVuexcept  >+/lsH fail("s|t did not screen-out general iterables"a in?ecthq 'x?oio7and5dYpi]?lf.p"w >V(EcQZMVsection(C('efgfe')), set('')) self.assertEqual(thetype('abcba').intersection(C('ccbT/bcV4&efUS4cbcf'), C('bag_ Os = "z" H)if> == frozenr%):Ewgpid(s), id(zOelse9#No <hdef test_isdisjoint#f(s1, s2 'Pure python equivalent of P!)'k1return notc+s1/&s2+for larg in '', 'abc1aba "cde!, {k, 'ef'!1i{rC_CFset,, dict.fromkeys, str, list, tuplJps2 = C( `actual'1.p'expected =  ) i$, B7RTrue(6@ is F or qFalse) Fpass+fail("s&t did creen-out general iterables"odifferencev %:Uc`lf.let+ 901i, qd and c"inQ5m,JTo:ialf.bas1Raises(PassThruLVlf.s., check_g_thru(JKF[[]]`Vtuple:  self.assertEqual(thetype('abcba').difference(C('cdc')), set#B')) NCTXefgfeVcW/7ccbU4Rb0JM0C('a'), C('YNdef test_sub!):Ai = sotherword 1s -6?, i:`frozenX@ 6try-z5lf.vexcept TypeError>Fpass+:lse]"fail("s-t did not screen-out general iterables") Qmymmetric_JY~s/Nfor c inletters0Ai, ( X.d) ^F)Hs 4lf.6,:`ialf.basr1Raises(PassThrun/s.&, check_o_thru(TU F[[]]rCr5t, , dict.fromkeytr, list, tuplX$E{d$_?efgd<2  ef ?xorYP ?s ^ &^Y M z  except TypeError: EpassJelse'self.fail("s^t did not screen-out general iterables") Qdef test_equality(M)`.assertE# r.s, set aword))N1ofrozen7A == Rf, Falsel/NoPother? 9 ? ) !LTruegdsetOfF sBnt = map(, ['abcdef', 'bcd0dcb!fefedccba'] thetype(t.len(s), 3ub_and_supersp, q, rm %o(p < q= ?q < ?> p_Oq >= po(q < r@ =! > A5'a').issub?bc'2$42per64#3g?cbs3%5 hapicklingHfor i in range('e.HIGHEST_PROTOCOL + 1(iCp = .BdumpLi('du*gloads( "s, dup, "%sa%s" % e7dupF1if k=) in25t,  91q.x = 105 0&p!.x,.x5Ator_n_proto!qitorg =^ ionBcontinue[ddumps(it, protocL  1 - *%(3,))$def test_deepcopy(.)class Tracer!ef __init__6w, value='T." =% JChashJCbreturnJBF, memo=NonQ6+ 1;#&102s =W6[t] du:N.&(s#No=id(s), id(dup6for elem in dup0new ]t]2^-Dt , - -!gc1.# Create a nest of cycles to exercise overall ref count checkmAEpass"y`t(A() irange(1000!sR.\Qsub =wesPset([,]1sub_with_custom_2Bug #1257731i=! H..^h_T $@int([elf) & 0x7f6=H( f=0.ad3xIn(s, f-hremovefAf.discarVWabadcmp$lf([BadCmp()s# Detect comparison errors during inwion and lookup/Raises(RuntimeED,%, /, L0.__fains__CH Pmutat op,if hasattrW'add'C=ses(RuntimeE rror, s.discard, BadCmp())  self.assertRaises(RuntimeEAhremove@Adef test_cyclical_repr(P!):"fw = ReprWrapper(}@s = -.thetype([w]pw.value$L)if1 =AtlpRbEqual(), '{set(...)}'hJelseB0namw8.partition('(')[0]f# strip class 2b%s({%s`)' % (>,D1)) GZ_print[Ifo = open(support.TESTFN, "w".:try-fo.write(str(s[fo.closelrl+ Ifo.read(), nfinallkunlink do_not_rehash_dict_keysan = 10@d = ,Q.from0map(HashCobngInt, range(n)< sum(elem.c?P for  in d), n  Zd \.difference(X8if hasatG, 'symmetric_o_update'^h/s.-9-d2Rd8-d3cofrozeni\_, 12358 u;d3,ds {container_iteratoa# Bug #3680: tp_traverse was not implemented5Dset Mu object"C( iEpass*wobj = Cref = weakref.refFDet([obj, 1qobj.x =(/B0del%, gc.collect() V self.assertTrue(ref() is None, "Cycle was not collected") def test_free_after_iterating(self): )support.check_2r, iter, thetype) class TestSet(JointOps, unittest.RCase)v>a = set1basQdMinit*3lf.L!()40.__3!__5W.wordZpEqual(s`+, J_otherO0TRaises(TypeErro\q, s, 2);8;1);constructor_identity5 Prange(3)t#s2NotYid(s), id(t)Pset_lP gt([1,2,3]d{}uOs, tm0_inTion_order# SF Issue #26020 -- Expect left to right I = {1, 1.0, 1len1stored_valueH.pop(5ln e]/atexpression Bevents = []record(objgk1b.appen 8G{9C1), 2 /3)VZ, [1, 2, =[\_hash1 Llf.sWMcleaAN"s. (['t(d)=K0-op0dup?4 .c!?dup& Sf d(01$4lf. ?add s.?'Q'dcIn('Q'[W 0s, =$[L, []oremove'a') self .assertNotIn('a', self.s) &Raises(KeyError,.remove, 'Q'8 OType9'[]8" =thetype([frozenset(Xword)1"In#;0(, -\#R_ 52 O!) def test_aP_keyey_unpacking!):.# bug: www.python.org/sf/1576657*for v1 in ['Q', (1,)]IM:trysA&v1,texcept "^ as eDv2 = e.args[0]AcEqual(v1, v2j/lsZ;_fail(C O==key|G3, 4l q6key =UTrue( is key,"cshould be {0}, not {1}".format(G L) |discard1$s./'aA|B{/, ^z.Sh%' 2 `^d1pop$i#range(le_'s)%>Delem; s.J 1?+'9Raises(PassThruC, check_pass_thru(ySTypeErrorT J[[]]Gcb. s|o=&ssp!t:cbc;, _/t) )&p-t)1and~?s &>g.assertNotIn(c, self.s) def test_difference_update((!):&*retval =@.1.otherword):I.assertEqual(Kf, None'for c in z.D" +nU"if2b1and c notI< ;? (InOelse; ?Not>_Raises(PassThruE, check_pass_thru()"QTypeErrorR O[[]]Esymmetric*, O@p, qp(('cdc', 'ab'), ('efgfec1ccb!ef Gbc')k{XCUset, frozen dict.fromkeys, str, list, tuplthetype('abcba'p`sl(C(p))>BCt(q)p%sdefghih8lf.eCCc'a'|rb cO?), )@FAisub0s -:t%J (/s.; Fl`U m#(clG) ^ h+)iElf.s.symmetric_difference_update, check_pass_thru()) self.assertRaises(TypeError, s.symmetr\F[[]]Ofor p, q in (('cdc', 'abd'), ('efgfeBcefg1ccb!ef bcef')):^C[set, frozen dict.fromkeys, str, list, tupleFJ2s =thetype('abcba'&!oEqual( (C(p)), NoneLdat(q)) def test_ixor({@.s ^t.otherwordl$c$"" +. Aif (3b28) ^9 @In(cFlf.s%?els|:Not> nplace_on_tvs.copy(}at |= tM=t?t &3-3m ^UD|weakref-gallahadCp = @w.proxy( Fastr(p)x'(sk  n#Resprich_compareclass TestRichSetC( a__gt__@, some_setGgt_called = True"return Falsklklk,/gee,klk_# This first tries the builtin R set  ison, which doesn't knowOhow to handleLcustom object. Upon @ing mplemented,2Ncorrespond,0 on*c right[ is invoked.C my= {1, 2, 3}RPmyobjo @!< -V self.ass ertTrue(myobj.gt_called)  = TestRichSetCompare()%aset > -self.assele+/<=f/ge+flf@unittest.skipUnless(hasattr(set, "_c_api"),+mp'C API . only available in a debug build'1def/](}%):aPEqual0().`10), ) class SetSub -LDpass"&*thetype =J4bas4setNJWithKeywordArgs__init__`, iter=[], newarg=NoneSOset.6 "):<kfs_in_s/'lf@'SF (#1486663 -- this used to erroneously raise a TypeError'4"1FrozenSet(JointOps, 4Cas+f:xAs = wX .[sk.other#FW, setNsingleton_empty_4Ff =  ef[,(8[]))().''I@zrange(0|h f]# All of the 2 s should have just one id0len(map(id, efs)qconstructor_identitybF&3)ti;`id(s),,t)9Mhash %.'abcdeb')u7ebecda'))# make sure that all permutations givpe same We valueun = 100seq = [rand<(n) for i in range(n)] results = set()for i in3U200):<shuffle(seq6R.add(hash(self.thetyp/)1assertEqual(len(Ba), 1) udef test_copyQ1dupQlf.s.!`!id?.s), id(dup)dfrozen_as_dictkeqseq = list(Qb10)) +'abcdefg'['apple'pDkey1?Lkey2!preverseq= ] , B#Noe0id(+/0ed = {} d[*e] = 42 &l2], 42N_caching{f=Fcda' lQS(f), qeffectivenesswen = 13H^value5add! =r*Aelemmask@[(i+1, 1<EF = = ef[,(8[]))()E''),y#' < +I)zrange(0|  x), f, Ff5F)]a# All O subclass instances should have different idsK4@len(map(id, efs) # Tests takenmsets.py =! 2_seot() #B," BasicOps:i=repU"ifT is not NonewX C/f.set),DY`check_*@_agaq_values90tex*TPTrue(..startswith('{')g.3end,},[Presul{T[1:-1].split(', 'U(@.sor"edA = [a) for 2 in#sD fU., ;|YMprin:trypfo = opupport.TESTFN, "w"fo.write(stI $Hclos;frffo.read(), ^!xzmfinall.stunlink( DalengthS!lf; Q; _e?ityX.TS equivalentV& Vc}sertEqual(self.set.copy(), self.dup) def test_p_union( !):#result =;Uset | %4.assertEqual(6p_emptyq/?setr'_I_5_intersect[&[6xb+ Etjzksdisjoint(i,)5not  XH .,=?setLTrue}Kx~}$?_symmetric_difference% ^O}$-$>[ -7w*CwO_rev-Q2_iteraJfor v inXCIn(vhvaluesta0 =  !se2.__length_hint__i"leJB picklingd$Pprotoarange(+e.HIGHEST_PROTOCOL + 19Bp = ..dumps(self.set, proto) copy = pickle.loads(p#self.assertEqual(Q>,P[ "%s != %s" % ;o)) #-: class TestBasicOpsEmpty(, unittest.aCase):def setUpcase = "eT*"7"values = []0set%=4\.+lb?dup'length = 0fBreproset()"`RSingletond</ (number)l3mS1mQ{3}" @X1_in BHaIn(3, Kset);?not? yNotIn(2BHP_TupleFt^(0, "zero")m'/')< <9BQ/ri?tU, operator.addS3bONone_S_tringx lf):  self.case = "string set" #values = ["a", "b:c"]&0set5=A(8)'?dup'length = 3 @def test_repr_!):MnQcheck_against_o() #-: class TestBasicOpsBytes(`, unit.CCase_setUpbTQbb/b"aMixedS7_warning_filtersupport. +s( 9.__enter__*=r.simpled('ignore', W ` Oand DCBNS4oarDown9xit__(None, )R/'=: baditer(raise TypeErroryield True39goo4 ExceptionPropaga ({ """SF 628246: Set constructor should not trap aKs"""emanceWithpassertR%s(S,%, ! `sa?outd# All of theseDblesload without e7.|It([1,2,3][1t((){'one':1, 'two':2 hree':3}+{range(3AZ'abc')  changingSizeWhileIteratingj  try:  for i in s: s.update([4])except RuntimeError;Fpass.:lseself.fail("no N ion when changing size dur iteration") #=: class TestSetOfSets(unittest.RCase)@def _constructor( Ainner = frozenset([1?1out,element = 'V.pop(zi.assertEqual(type(4&),r3GAadd(k)# Rebuild set ofs with .add methodGcremoveJ -,R ()q# Verify that El workeahdiscar# Absence1Keyo indicatesG#OfineJBinaryOp \setUp!g=(2, 4, 6)) DT#eq:# SF bug 6431154W2set{{2:1,4:3,6:5}lunion_sub9Presul.|'[2~6| x?perz3?, 8[f3moverla (lf353O, 6]Onon_30intcY & )f )  3 4 empty_set) def test_isdisjoint_subset(self): result = V.set.3(0(2, 4)))2)assertEqual(C, False) )Ndef 0perSB[, 6, 8]1overlap [3, 4, 52Onon_&=Trusym_difference0 ^  @. - [6(, ~ + 2, 3, 5, ?[8]  G? #=: class TestUpdateOps(unit .CCaseMsetUT"se!t(sL, 6)Y_unionD|Ot([2$ .,qrF t-27} 7*B_H|5  .method_callL!.ux9 0int/ctz&z* / z y.set &= set([2, 4, 6, 8]) self.assertEqual(set, set(5A])) 4def test_intersection_overlap=!):)`L2 &=N354z n~empty_set method_cal4.$qupdate(V sym_difference_sub]u" ^()x6 xp tz8} u|2, 3, 5, [  symmetric9,& -6 t v{ z"{! {/ /#=: class TestMut@unit.CCasedOsetUvalues = ["a", "b>c"]#.5 add_presenj.add("c" self.assert%Equal(self.set, set("abc")) def test_add_absent/!):#>.add("d")oasserti/d"juntil_fulnQtmp =hexpected_len = 0for v in fvalues1tmpvN RE+= 1SNlen(tmp), 9S 10tmpmw kremove_preo '?("brH:try1Bset.7 pfail("Ring misselement should have raised LookupErrorhexcept Kpass_B\empty0 = ;4 C -CR H~ddiscard!(7("cRd"I#A.' p \clearJzc <, 0a=": "issuperset", !} 0rev$a = {"=8.==0!"!!<": ">5><O<def test_bset(self):@x = U.leftyFrighfor case in , P, "<"=>&="cgexpected =AvNsw*# Test the binary infix spelling..result = eval("x" +a+ "y", locals())6{assertEqual(G$, /"friendly" method-name, if one exists"if!in Su s.2M 4 = getattr(x,=[I]C# =.(y# @# Now dosoperands *dr) =* gyBO+ "x52if U*y^x"/#-:w class"`Empty(`, unit[.CCaseVI @"t(E 5 = "both e]" sX "/ S?Non$S[1, 2ev_ pairo}'j,Onon-3NE TestSubsetPartial(TestSubsets, unittest. Case): left = set([1])Uright3, 2@name- "one a non-empty proper sn of other"Mcases = "!=", "<o=" #-: class NonOverlap 5 0nei $, containsO #=:OnlySetsInBinaryOps: @def _eq_ne(self# Unlike thes, this is7ing that == and != *are* allowed.eKZ.assertEqualk.=set, Falseo8!ses6D8,:p?Truo! "lf", 7Dge_gt_le_ltJp Raises(TypeError, lambda: %<  DE%>0>3   ?set!DE*D+Fpupdate_9LatorJ2tryD6|TTuexcept o =Fpass+:lse\fail("expectedJ+")D 'ifEIsIterabliGset.DkeVS, Lnion@] |_yD F [@?) elWse: self.assertRaises(TypeError, set.unionqother) Fdef test_intersection_update_operator(G)w6try r.set &=scauexcept =Fpass+lfail("expectedJ" 'ifIsIterablV9Q.) 7P.~,<+r lambda:7 fD9" &F6setG'+ x6 sym_difference8'^8mS%symmetric"Y+zJ' .'|L^vD9 FL()+\ X1-Xm S-Tself.set.dif ference_update(self.other) Uelse:&assertRaises(TypeError,)- ;zset.dif|:edef test_K)n lambda: %Rset - dD9F6setC'if[IsIterablV +y W,_) #-: class TestOnlySetsNumeric(InBinaryOps, unit."CCaseQsetUp  = set((1, 2, 3)w$Q = 196< = FalseRODict i0{1:+?:4} ?TruSOperatorioO.add -W_Tuplei(2, 4, 6Y A-VoStringi_'abc'$ V?Gen>stCase):  def setUp(self): Ggen(for i in range(0, 10, 2&*uyield iQ`.set =s((1, 2, 3))$other = ~IsIterable = True #=: class TestCopying: test_copy3!up lf.#dup_list#orted(dup, key=repr);set);.lf.assertEqual(lenZC0), Rj &)~bn]`[i] islK[i])%Odeep*!.$ M8 ##print typev0), * gWK[i],V/#-:gEmpty(`, unit.3ase3)?) OSingleton;["hello"OoTriple=zero", 0, NoneTu?()S0Nes/[), (3, 4):=Identities( def setUp(self): .a = set('abracad*')$b$lacazam') " def test_binopsVsSubsetsj2a, Dalf.a, ybBassertTrue(a - b < a#b - a < b#?a &F #F _| b > "a #F ^+ <commutativity:&Equal(a&b, b&:#|#|# ^#^#if a != b> 3Not`-=,-asummation # check that sums of parts e the whole3Q`(a-b)|)|(b-a), a|1&1/^b+aRby',u,)/\, a^bexclusion{ inverse oper show non-overlapa, zero8/t(?( "&ag( `a&b)&(, # Tests derived fromitertools.py = cR(seqn]'Regular gen/1or'for i in ,Jyield i class G 'Sequence using __getitem__Nw__init__]l!qn7L:i7Pretur0lf.>4[i]I8ator protocol*Wi = 0g,4nex,"if}ri >= le): raise StopIt"io2vC]oU += 1Fv;g< defined with aEseqn  self.i = 0 def __iter__(!):for val in6Fseqn"Pyield$ class X 'Missing __getitem__ andk'e}3nit} , d.! =7z 4nexJD"ifi >= lenU): raise StopIterationdvu!lf,[r]U += 1return vN\Eor m) CETest propag of excepse%/d3 // 0Simmediate stopApassvG `` from \tools import chain y L('multiple tiers@CatorE(map(lambda x:x, R(Ig(GVD))))2[tVariousArgs(unittest.!uCase): _constructorP78(set, frozenset&*s'"123", "", range(1000), ('do', 1.2)2000,2200,5)PTgTG, I, Ig, S, L, R.2T.assertEqual(sorted((g(s)), key=repr), )OWRes(TypeError, \@ , X^:"N:ZeroDivision|EB}tinline_methodsst('november'Adataz$c, 'decZM__s.union, s.intersectdifferencesymmetric_isdisjoinok A>expected = (Qdactual(g*+if isinstance(co, boolfss, expected)  oelse: self.assertEqual(sorted(actual, key=repr), expected)_W Raises(TypeError, meth, X(s)9"N9ZeroDivisionzEAdef test_inplace_@ods()7!for data in ("123", "", range(1000), ('do', 1.2) 2000,2200,5), 'december'[_zAnamec 'update', 'intersection_:'difference2 'symmetric_ VgG, I, Ig, S, L, R.2s = set('january''t'o.copy(!getattr(s+)(list(g()8Y8t832st-) PL Y>N5Y3Ea class bad_eq=aa__eq__Sw, otherAif be_bad0set2.clear%rO preturn 2 isoChash5'0 Qdict_@Hr+TestWeirdBugs(unit.CCase_8420_set_merge#r# This used to segfault< cglobal,12, # = Falseset1 = {8()}2 uiuY'75-^8Tru]w "1.< 2W  #f: Noneb ?t1.(Siter_and_mutate(self):  # Issue #24581 s = set(range(100))x.clear(oupdate/i = iter(s2 Da = lissa6Asi) def test_merge_and_mutaself):%vclass X>__hash__(1 preturn %&(0?#eq=7, oq!]otherD^RFalse4s{X() for i in %)}'{0.PB) # Application@s (based on David Eppstein's graph recipes = PpowerXU"""Generates all subsets of a or sequence U."""UTU6tryx = frozenk[next(U)]*N+S+ qyield SlA | xexcept StopIt6ion.)gcube(nJof n-dimensional hyper,singleton[X2[x]x1n)]Ldict([(x,1x^s3s7]]0_0hVAline+(G, the verticewhich are edg!G,with two/being adjacent iffOcorresponding;K shWa@%ex=RL = {GyFG[x]nM o#,zqz2 if z != yw8Xny = <y<%y]<x<L8ix,y])]Rnx+nyLaUfaces"'RL!f . Where a4 isrf?an that"'h # currently limited to tria s,squares, and pentagons<fv3v1,in G.items(AC$2 3KG[v2>if v1 == v3:continue:?[v3Z(gf.add(ov2, v3FOelse/4 n r42J% if v1 in G[v4]: f.add(frozenset([v1, v2, v3, v4]))?Oelse] or v5 in if0b== v3 < 2f 9continue%f15  0( D, v5,return f class TestGraphs(unittest.qCase): @def _cube(self~Ag =  3)# vert --> {}b5ices1 = gs.assertEqual(len(0B), 8{q# eightiK\for edgeYg.values()e54), a# each`ex connects to threedsv2$v svpsS 0ertQ2) #zJoriginalLefaces = (g 2D), 6g2six?Q{3a4B), 4Za is a squareoctahedron # http://en.wikipedia.org/F/Cub=# 8 triangularc and 6012 identicalz Sing aV!leN=[c = lineg#(g&:"V(OV1, V2, V3, V4S _), 12)# twelvepgq =ams mfour other d | $,,so ~%!iz collections.defaultdict(int1oTA T[Ou)] += 1 @%s3%3]vx A IssertEqual(facesizes[4], 6) # six square f$"  for vertex in cuboctahedron:%-dedge =,8# CA-Pices yAseICube[self.assertEqual(len(/C), 2P# TwoeVdefine an - S@cubet! y4In(0, g) #=: if __name__ == "__main__"unittest.() import  T.mock80sup2&os T.pathcontextlibDsys ensurepip ._uninstall class TestE2PipVersion(.bCase):q@def _returns_v2) ._PIP_VERSION, J$))pipMixinksetUp(srun_pip_patch =wg?Fch("o_0%")wQ.3 = Q.start(-.P_valuc0SaddCleanup(T2op)Y5# Avoid side effects on the actual os modulreal_devnull = os. "os'osHQed_osWDm0.stMa*|h"os_environ = 43os. `.copy(Bootstrap(f,8tbasic_bBLpingh'  8P_callonce_with(2["", "--no-indexfind-links",9.ANY, "setuptoolsA;pip8]GCfadditional=hH _args[0][1]C% N MZ<lE__root(="/foo/bar/"Iind-links",  unittest.mock.ANY, "--root", "/foo/bar/", 9 "setuptools+;pip%]4jS!) @def _bootstrapping_with_user(self):,ensurepip.1((S=TrueT(7P.run_+assert_called_oncea(V2["install--no-indexfind-links9a=D[opgradeG+JM^verbosity_1Q//=1vIh2I2IJi3J3JK_regular_O)4phQEqual>.os_environ["ENSUREPIP_OPTIONS"], c ?altp(altinstall=True) self.assertEqual( os_environ["ENSUREPIP_OPTIONS"], "altinstall") Ndef test_bootstrapping_with_default_pipa!):3ensurepip.8(/oNotIn(+, _conflictS(Raises(ValueErrors/, QFalse@.run>|.called4pipment_variables_removedE%# x deliberately ignores all pip V V$# See http://bugs.python.org/issue19734 for details<  ["c THIS_SHOULD_GO_AWAY"] = "Z fodder"C<,b2`ig_file_dis_W1theWM MM_20053M CONFIG_FILE os.devnull) @contextlib. manager @fake(version=_[sVERSION3if ( is Nonet=7elsclass FakePip(Ns#__UD__ =aEX;sentinel = object(=@orig = sys.modules.get("pip"/:0%[!1pipe6tryPyieldgfinall5if |4is @8delrQ 2h" UcTestUn$(EMixin, unit.'kCase):u<_skipped_when_not_UY; F`chelper1O@warnfor_wrongT @ "not a validz"2Dsupport.captured_stderr() as  Tvalue().strip()# ,self.assertIn("only uninstall a matching version", warning)DaFalse(Urun_pip.called) 0def test_e.!):with fake>(`ensureWA_helper()b' _`_once_d(r2["a", "-y-disable-pip-`-check^pip",Isetuptools],_verbosity_1/6T#=1~:d/-v@T2@@2@qAU3A@3Arv"/ " pip_environment_vari;s_removedI%#  deliberately ignores Gpip V VK$# See http://bugs.python.org/issue19734 for details<$os["PIP_THIS_SHOULD_GO_AWAY"] = " fodder"C[$q!No!, ,IHconfig_file_|@the |M Mr_20053r/;QEqualX.CONFIG_FILE"],) os.devnull) # Basic testing of the main functions and8ir argument parsing EXPECTED_VERSION_OUTPUT = "pip " + ensurepip._PIP_) class TestBootstrappingMainF|$(E<Mixin, unit.7Case): def$_bL_version(self):&*Awith+.support.captured_stdout() as 7;O .assertRaises(SystemExitg0WS(["--5"])result =x.getvalue().strip(+bEqual(</, :QFalse.run_pip.called)P!V7exit_code =]Q oC_v`_once_(2["install", "--no-indexfind-links",9;mock.ANY, "setuptoolsA;pip8]GCf@addi9al_paths9elfh_args[0][1]CLlen(MO), 233, 0a_error qreturn_E = 2jN9#Una?,uM"._$ @P fakeV(( 7M7>b!-y-disable-pip`-check 4z ^ n alue = 2  exit_code = ensurepip._uninstall._main([]) 3self.assertEqual(D , 2) if __name__ == "_DA__":Dunittest.Z ) """Tests for HTMLParser.py.""" import html.pdpprintX class EventCollector(A.g1): depinit__(, *args, **kw) .e[as = []>append = '.)?.__~Bget_} # Normalize the list of . so that buffer artefacts don't# separate runsAcontiguous characters.2LpprevtypPENone'8 inYD:)&[0\2if &= es= "data['L[-1] = (!!, R[1] +'[16JelseL(E = Lreturn L# structure markuphandle_starttag, tag, attrsmc4(("2".)Z?end]5` &)O)# all otherscommentab+1", 'df?refLoharrefLcI(F?eclF?eclFoentity-P/pi/piBunknown_d?ecl0 0O,\jExtra(L E.:r_text", ()Cgsfail('This should neBver be called with convert_charrefs=True') def handle_entityref(self, data):&*.fail('This should nes class TestCaseBase(unittest.&):get_collector(return EventC% WFalse_run_checkQ, source, expected_eR5s, zW=Nonez&if@ is :+/;0 = .)-parser =Qfor s in a8|.feed(sOv.close(3 = 7%2if < !=  } "received;did not matchF5" +&A"\nS:\n" + repr()5 E7pprint.pformat(J RJ)Gl_extraM184|,, Ek3) bQHTMLPZV( uc| _processing_instruction_only 6" >Y>", [("pi", "0*")]t/ ?v/ ?xsimple_html "" <">&m; sa text 𠇏U2a-- t2I/Html> "" ("$\n%`("decl+0ata+?starttag n]"("0ref O&32$+ O1a\n[ $\n-b_  im`[("srcpBar"), ("ismap",) \n! comment", "comment2a-- --commb"), ("data", "\n`endtagFhtml,1]) Hdef test_malformatted_charref(self):)u._run_check("

&#bad;

", [+/s("startp ]H&("p%])k,# add the [] as a workaround to avoid buffering (see #20288E e["
Hre_pointy_bracket!< >r< bare>N$< O I `_end_b?ary"""" WW (";g"<")]) L>L>L&F_artefac0outN?= [ X1 [2], R a #31V3=h3!'<5>> b='<'", ">"], output)  = [("starttag", "a",b e>")])]3 self._run_check([""ca /W3f b=h53'4 /bpcomment-Oabc"U % ¬-an-entity-ref;!"<6!='z tag'>"[ '

"y'aSCRIPT*'0<\nOJ p@docu.write("~ ); :('\n//<\\/P>\');<]]>1'\n//\nvar foo = 3.142 +\n1sty/leX`\u2603G E# these two should be invalid according to)_j5 specu# section 8.1.2.2#B" !0ele6R')3Pstyle  ATYLE  &M %v% % _lower = element.lower()  s = '<{element}>{cont & ¬-an-entity-ref;=D

>''"""&y3[' +2, ' D ', & '2'\n10 \n F\n']9 I$ =Y.Y().strip(=`:T2.=* /("&=  (convert_charrefs=False)o `html = (I'm a valid'#me too!-->'!/-- 6I have many hyphensK  00a >`middleD and8*--7!8expected = [('_', " 0"b:';',/--'%#--,\--'),  ('comment', ' I have a > in the middle '), 8 ?4andC*--BU! ')]Cself._run_check(html, expected) )def test_condcoms(7!):6 = (''@D@48]>o5n7]>pretty?8)nH = [7""J@*vert_charref# default value for con4 is now TrueT collector = lambda: EventCCsFp.assertM(E<().v6p'"3C" 2x22 Fx22'!#  S l!ofztext/attributes Hstarttagh0a',[@hreffoo"zar')]<0dat5'a"z'), ('endMJGX@'a '.format(MY%, = &() ]!atObeginning/end d&"Ex3A ('y Xdz /X"? W#{0}{0}{1}'.format(, charrefWexpected, collector= 5())!# truncatedas at the end of Efile:html = '&quo &# &#xfor x in range(1, len(35)):C >$u[:x], [/)]L a string with no '%h here' |#g`remaintests were R"tolerant" parser (which is nowGdefault), aneck various kibroken markup<@def w_h_g@ing( < >te>>xt&a<\n#'", [] A"'", [('data', " "$>9starttag', 'a$', []: b;b</=5end{@( A>udef test_slashes_in_,(!):('p"var"/>!('=0foozYvar')yhtml = (''expected = [( Yimg',"1[('902'), ('*')4 (Fq', Noney(ami 1 (' 4re*]/) $, ;M@a / /=1bar><03 #=4bar]OLA#see issue #14538L[`meta><4 /  b1///fQ]~@A)MF3declaration_junk_chars "',  $[('comment', 'spacer type="block" height="25"')]) Fdef test_with_unquoted_attributes(self):-1# see #12008html = ("< >"<U" software-and-i")expected = [$('starttagl', []),&&#(';`'), (')O 'qP0_1000% R tr d$!('YY 7"6/-14Adata 0[('C#FG7E{i;!en54 ('p {'3end Pa1Z-!1/\u , .I6 ('%{']._run_check($, G (a_between V',8 |)2[(' : (',', NoneOAeird_chars_inK^_valuQf bogus|&#()>1Q sinvalid_end_tag&qA colle, of broken end 1 .
is used as separator.lhttp://www.w3.org/TR/html5/tokenization.#end-tag-open-state # and #139935 = ('
 div end tmAd-leaderBoard1

yignored5],self._run_check($, w!) )def test_bro_invalid_end_tag(E!):+2`# Thistechnically wrong ("> shouldn'q G1 inxW'dataP# butPprobably worth fix itP addi q to allNcases ofprevious`, it w require a fullMgsing).I?seeP@'1"> confuVarser;v (/0, 'pb%z?, '):%correct_detecA_of_BsCZ/27style=""r>me rain h2 Cn Sp- K ,0yle,') 2be '), ('starttag', 'a', [('hrefsome_url')]), P('dat.m'rain'5endS ; 8= br}? inEOspanD /Sp C Udiv');] self._run_check(html, expected) ) = '
The U'PcE = [  s '), (',', None 0foo?bar"b FAlIdef test_EOF_i`arref(%):X# see #17802AThis? s that the UnboundLocalError reported"WissueL is not raised, however I'mAsureZ returned values are correct.O Maybe HTMLParser should use .unescape forYsW a&2/a&.!a&$'b' Ocentityb J;J'rW5 O^|_methodPPfrom v0 im 02p =get_collector(Bwith"assertWarns(Deprecation7ing"""f&#bad;k8juEqual(pBE(s),3(s) broken_comments a= ('8   X ('comment', ' not a comment either --'), #('#', ' -- close enough0 M <-- this was an empty: a!! anoTbogus5H !!!9]self._run_check(html, expected) ) def test_broken_condcoms(>!):$# these are missing '--' after ''L = ('aDIE 6]>foo IE)startendtag`', [(' =')](1 ima[('srcV<}b>foo@\b=' [  GG%convert_charrefs_dropped_text)#23144: make suaat allaevents@triggered when# r is True, > if we don'C! .("r = EventCollec tor(convert_charrefs=True) # before the fix, bar & baz was missing0 parser.feed("foo link;@amp;?"eself.assertEqual(OSget_events(),![('data', 'r'), ('starttag![])'He ('end4 05')]~) class AttributesTestCase( qBase): 5def test_attr_syntax(!): output = [D ("", "a", [("b v"'"c d e", None)]p{._run_check("""""", G=Q b = @1 = B? = D\nb\n=\n'v'\nc a"v"\nd ?v\n\tb\t=\tM!tc M!td ;v\tMu lvaluesb='xxx\n\txxxEyyy\t\nyyyN'\txyz\n'Tm [_" F (&A[8")]V"& r# RegressionW for SF patch #669683.e "Y? W![("Abug #921657 href=mailto:xyz@example.com 0ADw nonascii# see issue 7311; i"\u4e2d\u6587�',M[("starttag", "a", [("_U a)A  ("@def test_attr_entity_replacement( !):,i""bc&><\"' funky_namesa.b='v' c:d=v e-f=v!a.v"), ("c:d3e-fM Yqrefs_inlOibutE foo='€j#97;a&unsupportednMq0foo\u20AC&aaG /2r*$>' %[ ;pH&1 x0='%s'>"x_/%sv<\malformedA3357>1N: = -.c 'style='color:red;bad1'>0 - U"SW B+C2B2B o G(d3H3H! =1'JG4' 4Lhexpected = [$(' a''v@', "/K P('datA'7f'), ('endtag', w'a'), ,('starttag', 'a', [('href', "test'+style='color:red;ba2'")]J0datA'7 - bad2'), ('enda 6 O\xa0/d33H44] self._run_check(html, expected) )@def b_malformed_adjacent_attributes(L!):2# see #12629$p''1M[>x> ,3y60('z'o""', NoneeF\_x')])h) 755670 for the following 3s,*   a width="100%"cellspacing=0 "o", "a"?Q [("e*g/l@","0k]id="foo"class="bar"9 idaf!",g )]v pvmissingl_value/v=Cv&javascrip@"/[(uxend_tag_in Lq1745761` 'http://www.example.org/\">;'>spam TESTDATAFILE = "N,a]TEtxt"'0URL&://www.pythonCnet/L/" +mA + "t def check(MRfile)SQhdr =D.readline()qmreturnl in hdr class RangeError(:^BpasssNFC(strX<("NFC", "0K1 K2Db Db1 K2punistr( = [int(x, 16) for x in .split(" ")]Q if x > sys.max#WraiselOH"".join([chr(xY (.4Cas7)S(self# Hit the e)a early":tryL< = (URL, encoding="utf-8",TX =5p Permis P.skip 6(f"- e when downloa' {?} "af"into4  directory"1(OS),  fail(f"Could not retrieve5") AwithDrun__s;3K%+,dpart = None 1_ZV = {}.O# `if '#' ( #0 = b'#')[0"&Ctrip!ifZ'cvcontinu2.p.startsq("@Part" )1 'i k*1,c2,c3,c4,c5o';')[:-1]6# Skip uned characters; # try at least adding c1 if we are in part1 !ifp == "@P#-":%4?tryc1 = unistr(line.split(';')[0])Qexcept RangeError_OpassD?lse7 rt1_data[c1] = continue _# Perform test{self.assertTrue(c2< NFC(c1) 2 @3),   J4>4>5>3>D5D(c?D(c5J?D(c5NFK \h;*3  ?5),> b5NFK$ B6 ## Record 1  ! E  for all otherpc&r(sys.maxunicode+1)eX = chr(c@if XD 7q  Xe3C(X D KKB, c)1def_bug_834676(Yq# Check Bbug &0normalize('NFC', '\ud55c\uae00') if __name__"__main__5@unit3.() # Copyright (c) 2004 Python SoftwFoundation. # All 1s reserved. # Wr[n by Eric Price #Zand Facundo Batista 3] # Tests are built ar( these assumed context defaults. # test_main() restores7 original6. ORIGINAL_CONTEXT = { C: C.get^ ().copy() if C else NoneOP: P+ } def init(m): >not m: returnDCC= m. ($ prec=9, Bing=B traps=dict.fromkeys(Signals[m], 0)L6m.s) TESTDATADI'decimal\data' if __name__ == '_s2__'file = sys.argv[0] 8  __&1__ Vir = os.path.dir\(!@) orcurdir directory =Pdir + hsep +  skip_expected = leisdir(W)}Make sure it actually raises errors whenIXand caught in flags # Slower, sincPruns some things several times. EXTENDEDERROR = False) extra functionalityrthe C version (-DEXTRA_FUNCTIONALITY)` p = True hasattr(C, 'DecClamped')requires__`= unit.w`Unless0, ") Qd with "")/if|/Ifxrregular") class IBMreCases(A"""C.QwhichrD6 Lqagainst1IBM( cZQ.""" 5setUp(self`=.YCelf.-.Oread2ignore_listB'#']T0# Lodividual  idat correspond toM`we're "`ping fne reasonanother.410ed_7_p`= set(X# Skip implementa'-specific scaleb_;'scbx164'65',# For some operati'ons (currently exp, ln, log10, power), the decNumber  # reference implementationoses addial restricAs onX{contextVand operands. These?are not part ofLspecific;SrhoweverTeffec8 [does show up in somec TtestcaseWe skip  that violate h{, sinceSDecimal behaves difaFfromC forWt"so V!would otherwise fail..'expx901',235/ln[ Z YX/ogYZ[ \}powx118/4.40A `?400O4008x/10x15]) if self.dU== C: # status haSubnormal, Underflow9X2@ped__ids.add('pwsx803')151`# Corrrounding (q<_, toom{owx4302n 224d4d# http://bugs.python.org/issue7049dLmx32d w1'6'OB# Ma"0 diito setter funa ChangeDict = {'precision' :c!_ ' ?_methodE maxexponentHDmax_E $in) E/inE\clamp?}# Name adapter to be able to change the Decimal and Context # interface without;1ing= test files from Cowlishaw.Dself.NameAdapter = {'and':'logical_,1| 'apply':'_ . class':'number_4 omparesig':'c _signal';Wtotal=<(maz=_Apbcopy_d@pyab!6 eanegate3py_8D6 4 divideint':' _ 6 Pinver3U7 `scanonf':'is_:Afini3is_ 4#in*m82nan .1ormBis_n 4qZ 0e!is'/edw 5issd d#ubs:Bzero1 0 0maxj_:'maxt3min0/in0nextminus _  *&pl5 4PtowarA_8 'or/or Preduc ?ize2mainderneal#re_ samequantum':'_: quarerooOsqrt @toento_eng_string5)!gru toe__valu$to>Hx':'?Oexac2sci9=sci  'xor':'logical_4} # Map test-case names to roundings.,cself.RDict = {'ceiling' : ROUND_CEILING,8l V'down5ODOWN2 Vfloor3_FLOOR4 Zhalf_k_HALF_p<7eve<?EVE<&up:/UP 3.(050N05UP!he s' errorthe actual E/N`lampeddecimal.C 'conversion_syntaxGInvalidOperationP AdiviN}by_zeroOD!oByZeroMimpossibleP$undefin7Qinexact i[_contexE{NoPoverflowGO `/ed= subnormal}SA 2Und The following funcs return True/False rather than aP2# Dw instanceLFZ= ('is_canon' 1ofinite./in0?nan[qZ0sigZsZ>same_quantum')def read_unlimited(self, v, context): """Work around the limitations of 32-bit _decimal version. TheK* guaranteed maximum values for prec, Emax etc. are 4250,Hbut higher@usually work, exceptUrFcorner cases.IIn particular, allIBM tests pass withHaof 107e00."""0if _.== C and.MAX_EMAX ==FCread._unsafe_set:()~9 Oemax9$Oin(-sbreturndcreate'&(vJelseD=".D`( def eval_file global skip_expected<$ aise unit.SkipTest>Qopen(tZ as fB|line in = .replace('\r\n', ''){>a#printB :try12t =;~(%P Ek0ion(?ionp#-rSpd whereC re shouldn't have been oneffail('U5"'+ .__class__.__name__ + '" z!on-2 '+ HHsE(.find(' -> ') >= 0[:2] != '--'not s.starts#w(' --'Os = (s.split('->')[0]]->' +R+%1]:-:).strip([sr87rQignorqZ_list# $}, 'NotImplemented--', G<1if e i %elif ':'|s*directive(sA b81equ7RfNbfunct,x.lower() x6:')1if D7'Jing'aRingDict[value]# Uelse::tryvalue = int( )4except V&^ErrorBUpass 5 funct = self.ChangeDict.get(, (lambda *args: None)v%Wdef eval_equation(]V, s):x if not TEST_ALL and random.() < 0.90freturnH[.context.clear_flags()$ IPSides.split('->'gAL = &[0].strip()- )id = L[0];if DEBUG pr"Test ", id, end=" "XW[1].lower(!valstemp$*2:1 an G#io1_a (Typeb, AttributQIndex)Rraisekdecimal.InvalidOper,GFFixQuotes` Lval = val.replace("''", 'Single8%')'""', 'DoublPO DC *8 W, "'"K, '"Nif id in9skipped_test_idsb @fnam/'NameAdapterk]3if 6= 'rescale'f7A = getattr,M_F = [pconglom%''qE = 0Rtheir[n4s[x/p] for x:2]X&rSignalsR]moetraps[C ] = 1 #Catch these bugs... s mX i,72enuN7% < if+p.count( % 2 == 1A1 - "if8  p+ ' ' + NR]Iinue+{ Z9val;) #'= bJv = j Ain ('to_sci_ ngdto_eng i_if EXTENDEDERRORTEST:  for error in theirexceptions: ) self.context.traps[E_] = 16?tryS`ifunct(]create_decimal(v))_h OpassG Signals[o] as e\ 0fail("Raised %s\p%s whendisabled" % \b(e, s, /lsDid not ri(?, sk0Iv = 2  3eEread_unlimited(v,\ #vals.append(v) gans = FixQuotes(ansif EXTENDEDERRORTEST and fname7in ('to_sci_string', 4eng)-n 0f^V* ^5-7%7 E#Adl#5above, but add  cumulatively, to check precedenceHordered_1[e P^O@if e% ]_K  l  ; expect9" %6  (type(e) Dr# reset_ for error in ordered_errors: self.context.traps[+u] = 0 0if DEBUGBprint("--", J)8:try3 result = str(funct(*vals)4if fname inZLogicalF2?ion ZReval( ))) # 'True', 'False' -> '1%0'except Signals[decimal] as  $fail("Raised %sq%s" % (2(, e: #Catch anyX long enough to state the test case.'`ERROR: Fr"myy@6get/()-.sort(key=reprdVtheir? '"assertEque, ans,& 'Incorrect) wer for ' + s + ' -- got s,T zflags set|^)FJdef _)=return [ex"ifB[e]]ichange_precision(l , rI == C and_.MAX_PRECA4250^8_unsafe_setp(%Oelse=-! = rounding_method  4 = Ymin_exponentV7expQ(NPemin(tR' Emin = exp2&?maxn/ax/axSclamp  1 =  class CIBMTestCases( GC = C3(Py'4 pP # ThpllowingBssesbehaviour of D9` accortPEP 327ExplicitConstructionP(unit.q'''Unitss:C Duction cases$ of Decimal.''' def test_explicit_empty(self):#'80 = #.dG'assertEqual(!4(),{o("0"))}from_None/Raises(TypeError , a ?int#positive5d =545) .str(d), '45'}#very large ] 50?123d- kOnega--Ezero 00 single word longsZfor n in range(0, 32J#1sig&k(-1, 1!%xH_-5, 5'+iP* (2**n + x"i#i4 ostringInvalidOperation5elf slocalcontext5o#_A50'') 9NaN?int@BOfloaC2.34!45 Iengineer not9#e2TY.5E+3@justQ a numberUBuglyU 1leading and trail whitespace permittedj1.3E4 \nn6+4' r -7.89< x" 3.45679 " ? underscore 1_3.3e4_01.33E+4101_0>+00unicode rn["", ' ', '\u00a0 f205f']E78:  ,self.assertEqual(str(Decimal(lead + '9.311E+28' + trail)), @ 8%) / with localcontext() as c:"Tc.traps[InvalidOperation] = True-## 'y stringsRaises(-T#, , "xyz")@# Two arguments max `TypeErrorYP1234"a'y"# space in the numeric partq  1\u00a023L D Runicode white(s0I # embedded NUL1a 00a G# underscores don't prevent e%s/v0_2_x@cpython_only[def test_from_legacy_) s(p){import _0AcapiA"0 = 2".d".' 'C6s =g.4 Q('9.9'@s)),596 .create_(EFsexpliciO]tupleG Q#zero_d4d =P( (0,o), 0) d'0'T6#in5 X1, (4, 5Z9-45\Ofloa^^, 3, 4), -2Y45.34g_weirdda, 9, 1p5v5w-4.34913534E-17?info), "F"fInfinity_Pwrongber of item MValuX( )#bad sign self.ass+ertRaises(ValueError, Decimal, (8, (4, 3, 4, 9, 1), 2) ) self.assI /0.J5(%) #bad exp1'wrong!'!P/0.J5!'1coefficients_"xyz"$ ONone8(L-/J/10.J7'a'k def test_explicit_from_list(!):'B0 = ".dy.4d =([0, [0], 0]Equal(str(d), '0' HI1, [54], -25b-4.34913534E-17p jp)p>()BObool%N1Is(J (0)), False /1/?Tru.#[Vk 5\4#1)flP #positive&45e*dx e (45#very large t 506123d{D Onega-*-45') #zSero d = Decimal(0)edself.assertEqual(str(e), '0') >@requires_IEEE_754def test_explicit_from_float(W"):@0 = ".d.(r?0.1type(r),+1r),['0.1055511151231257827021181583404541015625'nSTrue(('nan')).is_qnan()93inf9infinite=->6> W5o'NaN')ccIyhi-j'00.0l6-.for i in range(200):B0x = dom.expovariate(0.01) * (ran(2.0 - 1. I2x, x))) # roundtripcontext_create_lV#InvalidOperation0 Re.anc = copy.3getj`nc.pre73Gu# emptyy(d\<;nc.@F # U None Raises(TypeError, t,=S5intR?456IsInstance(d o(45678 3'457E+2')istring'j9  +S.X# leading and trail whitespace should result in a NaN;  # spaces are already checked/ Cowlishaw's test-suite, soChere we just= that a trailing newline results[F+self.assertEqual(str(nc.create_decimal('3.14\n')), 'NaN') C# from tuplesSd = D> (1, (4, 3, 4, 9, 1 54), -25) )=d|-4.34913534E-17'4q{<5uwprevdec 50:1239(1JUj.00E+8more integerQnc.pr%28nc.traps[InvalidOperation] = True0Pfor v[-2**63-1 $31e31, 0,d<22**' %, I )]:4vlRp(isinstance(d,)4=@int(v/3.uRounded%sRaises(*-, g, 1234rhstringth@0E-0n0D"45?=B-Inf? WinityFbNaN123H 2# i argumentb V"xyz"5FValueError@9D5J?TypI"$", "5678# no whitesP and 0rscD ppJ is done with this method"ji12_34"too many| payload digi$g5') se'lf.assertRaises(InvalidOperation, nc.create_decimal, D#('NaN12345')) 0nc.traps[f] = False+%seEqual(str( h , v/')D@True?Oflag %%)/ def test_explicit_context_from_float(N&):0 = ..(,nc#Cd(f>r =$F(0.1#egtype(r), r+*['0.1055511151231 ('nan')).is_qnan():C3infCinfiniteG"-H@  )?>ww I:?y')|&@} -~100.0r-8`nc.pret5100for i in range(200):0x = dom.expovariate(0.01) * (ran(2.0 - 1.0I 2x, Umx))) # roundtrip5unicode_digitse ]K(values = {'\uff11': '1'{'\u0660.3712e-3' : '0.V<372E-nan\u0c68a6:-NaN24009}nput, expected{.items(  (iQ&))S) class CE ConstructionTest(uctionTest):# decimal = C class PyExplicitConstructionTest(+):L#P M/ImKunittest.YCCaseD'''Unit ds for C cases of DS.''' f>#_i|_from_None(selfi<0 = . .N'assertRaises(TypeError, eval, '4`(5) + l', locals()) ?intu#normalEqual(str(45), '50')5#exceeding precision R N123456789000,( ostring?"3"Ofloa?2.2e*"O & -50?ropQ# Allow other res to be trainedinteract withZsF8" Ewsdef __divmod__,h()return '/P ' + -*Wr)XLS + ' >'Y/ltT?'ltgOgO/leeOgO/eq/eqnn..c:G(E()$ 0)( 1@q10), E(@%10[ A(al(10) < E()'), 'gt 10') self.assertEqual(eval('Decimal(10) > E()=l=%<=>/ge{>l>=>/eq|!>n|6@# in3 operator methods and then exercisem9oplist = [('+', '__add__ r +),*-5sub* ***5mul* */*utruediv. 2%2&mo */]Xfloor^ 5*5pow %] for sym, lop, rop in l:%isetattr(E+plambda , other: 'str' +Lq + str()z JruJ<! ++] JuXym + '.  ') syq 102x class CImplicitConstructionTest()dC = CK/Py3L#P MaFormatunittest.CCase'''Unit  s c0theqmat funA.'''b1def*!_fZPting(iMxU! =p..# triples giving avC, a .,j expected resultn_valuespeQ0E-15 e !('%42.3'?2.3) @0E+2Pp2.30e+25 # preserve significant zeroso5000J?000w1.234567891 0e40<+40@y!1. _1.5e+$"0.0%/-1I70.0& 0.011315.O50e+}@, '-+1'), ('e', '0e+0'),  #E1"1".D-"#2E".6AE-15k!.0?e-9- )/+6)19.90 $911+1a-1.23e ?e+5/456789e-3e`234568 f"<R~.!1E-2F/.0#d.00E-8&r'), # loses exponent informationN23.2>3 "/32_3.20E$%'-6!.60 all zeros treated equallyFP[d( ".0&no decimal point2ez"3.14159263(1| (.$4*/41-/597/2_ # round-half-even!8C 91  dgj !3/0eG`"E"D-0x& 4 (''7w?e-7J-}O-0e+!.0I C # 0 sig fig -> 1 X0.0nBsame for 'n'81z (2(5*7-8/9C14159265', '3.14159265'), ('.10g', '$ ), # don't pad ?%<10E1%_ 0 -A /-2B 3!/.0#-4#$ ".3$% # all zeros treated equally@"E11.00C'-(12.3?234Q 1.234567123.457 0, '-)% e4NaN 5fa-NaN12w )+\`NaN4564+ )!.3u!In[InfinityP1.16"-*+#-s ,),11.0 ## test alignment and Kding:0 <%n123 >%J^%KJ(=+&+"#<,BNaN#Q+2-4.?4.3,+XQ0.013c+ ?###[ / /"@>.@ 0#>5#"*!?^*, '?123?%|Q%123%J\B (' &A-45. #/=)/ @#/=T@, '+,/-RO, ' -D\x00i-"^12nfQ4 $# 45z # thousands separator"0(',31aP,234,n +5,('?,34N%v e$##23! (',c', '12G), 1(',0/0'-1234567$p-1,234,- ,n23,456W7W*1)8) *0+&0,, # special case: extra 0 needed/+L+K but not if there's a signH Hk >;+09+ # ... with fractional part...*6('00.56   , O, '0Y%10./ 1//,01 21Q8,.1fP234.5 `  # no thousands separators in~ {.0789d1 R!,%"023.02,345.6789%C(',e2^?e+5,E,E, # issue 6850r('a=-7.X.AUpaaaa0.1t /HL2209I<^+15.20!in<<+Infinity%<<'AsNaN(R=10.1k72 1]for fmt, d, resulttest_values:+self.assertEqual(format(Decimal(d),O)M%) ?# bytes 2 argument [Raises(TypeError, `R1).__B__, b'-020'fAdef n#(T)F0 = ".d.6try5 from locale import CHAR_MAXexcept I DsskipTest('N.Gavailable|make_grouping(lst$return ''.join([chr(x)k xPlst]) == C else lstq get_fmt(x, override=NoneK='n')ifS[ n Decimal(x) .__format__(fmt, override) Yelse:return Decimal(x)N_localeconv=ZI# Set up some ,-like dictionaries3en_US = {"'d_point' : '.',#groupingTmake_([3, 3, 0])3thousands_sep89','U%} _fr_FR,CHAR_MAX_ru_RU+/: 1& _crazy&1 1, 4, 2, 9-dotsep_wide b'\xc2\xbf'.decode('utf-8'Wy'm4m self.assertEqual(get_fmt('12.7'), d3), QB B6,7'LBB*`B0-2&1234567893,456,789CWAo3 456 f0123, -78-9012-3')`, '.6n'0'1.QO7e+8I,I$"I1$I&9# zero padding< $, #037?2341>4>*5>01234') self.assertEqual(get_fmt(1234, fr_FR, '06n')0S') A 5, en_US:5B12,345')AA'70B'8B,D(9D0#10E0R6, crazyS-2345-6DV1D)XD*XE*Y/-0H+1H-2H0I-3I J5# wide char separator and decimal point0D/`('-1.55pdotsep__t2HG'-0\u00b400 1$fIK@run_with_locale('LC_ALL', 'ps_AFdef test____(!):^"# Z f-0 = U.h.M# =r.yconv()['%%']thousands= %=$if}!= '\u066b'skipTest('inappropriateD,H'B '({!a} not )'.format(,);9if  cD,H?c').  C('10@.123>'?1c/%66 bB]decimal_from_flo at_argument_type(self): qclass A.decimal.D'.def __init__0;, a#'a!.am1 = t%a)pa = A.from_float(42.5=ssertEqualh 3, aa/) Y W)CFormatTest( .R = C /&Py%0 #P 1ArithmeticOperatorslunittest.CCases'''Unit s for all aF$ oG, binary and u B.'''/B_additionfc1 = E(Sd1 = -('-11.1'u(d2W22.2'D#two<spadd1+d2,)"('de1O2+d11c#with othere, leftc = d1 + 5 dc` -61c),mH(d1) Jrigho5 + d1Qqinline wE= d2 v ]}O`t _u?subtrac--33.3')B9d2-1-1_\ /-+w-x^/-=v 2-38 `multiplicaal.Decimal  d1 = Decimal('-5') 8 d2E3') D#two6sself.assertEqual(d1*d2,)v('-15')a0N2*d10a#with other type, leftc = d1 * 5 cc_2 cA(c),lH(d1) Jrigho5 * d1Pqinline dvE= d2 s \zN_q ^7r>def test_division(!):0 = ..2"/!2. *2/00.45/ 42 d /1.L?4 /00.8 T lOd1 /@#]//=u 6wa_floor<$ 2 :d2/0/1^Y=., ?7 /(kp[ &?/= qual(d1, Decimal('1')) def test_powering(self):!0Dec40 = ".d.E(Sd1 = U('5')B(d2#2'z5D#two5s1iassertEqual(d1**d2,*@('25B0W2**d10 320a#with other type, leftc = d1 ** 4 dc_6 dA(c),m4(d1}Jrigh7/d1P16807^  qinline "xE= d2 \ w-#\~ _u ^3390yBomodule%K)2%!% 2 +/, /%   `%X/%=k \floor_div_v`(p, q) `ivmod(&d2 p q* d Tp:(,q,  4 qright (p, q) = divmod(7, d1) self.assertEqual/Decimal('1')*5q, *2* type(p), /d1V #q, def test_unary_operators(!):$0 = ".d. (+#F(45)P+45))XO# +D-D-D-DGabs(G8), L@) #nan_comparison'#  involving signal Cnans InvalidOh2ionly# orderN(<, <=, >, >=)]only quiet ^o# alsome:ityp_==, !jSdon'tk, but return False or True respectively.P / 0 `localcontext56n =yGNaN'si7Inf7f62')lqTpairs = (n, n),iiffs<s<s,4s, DDsr0_opV.lt, e g%geL J'eq=&ne#ults when is not trappedhfor x, y in C&+ ?1 op/(+ 04 go10op(j+ exBed =0if bs3@ne e<!4Is(Nm, got,-1".r {0!r} .{1}({2!r}, {3!r}); "P {4!r}".format(2{.__name__,)peat the abovethis timeXwith () as ctx@ctx.',s[KV] = 1sG1@ Q(n+s:  got = op(x, y)  expected = True if op is operator.ne else FalseDself.assertIs(Ro, got,1 "2 {0!r} for "8{1}({2!r}, {3!r});A {4!r}".format(w , op.__name__, ]9)) @ in snan_pairs:$(un equality_op(,lRaises(InvalidO0ion"eqK$neK q/ +_order- def test_copy_sign()vDecimal = ".d.F(1).P6-2)YLE(& ;o-2), d6TypeError, B , '-2') class CArithmeticorsTest(C = CI/Py2JP # The following are two functions used top thread)in the next ! h:S1(clsm = cls   + DivisionByZero2 0Overflow*$?Und%&`Inexac"pgetcont (_local*Gd1 =_A'd33I+Rd1/d3;finish1.set()synchro.waiUAB2 = AXwith () as c2MJ(c2.flags[]sM*> , c2.divide, d1, 0; e Bl3 X3.  5InvalidOperation, c3.compare, d1, Decimal('sNaN')) cls.assertTrue(c3.flags[InvalidOperation]7edel c3JFFalse(c2GC!2 D@Equal(test?0.3B2B 1 = getcontext(Y!1Sexact for sig in Overflow, Und DivisionByZero, _:pKqsig]) def thfunc2(cls):0 = @d.\ r + 4 2 0 *$ %&!In^ $" %(Slocal *d6"(1Ed3 =D3 = d1/d3;FthisgG.prec = 18L2LXwith () as c2 'q9 *tRaises(, c2.multiply+a1e4250r'), 999 M wTx3] .)/03.traps[j@] = #@//Zidivide.-/ QlbX40[@2isynchro.sesfinish2+fY W1bGz class ThreadingTest(unit.CCase'''Unit s for thread locLal contexts in Decimal.''' # Take care executing this test from IDLE, there's an issuePthreadingMthat hangs 5 and I couldn't find it{1defd_Eq(self):LDefaultC0 = #.d T6)if(Q == C9not.HAVE_THREADSvDi skipTest("compiled without %") # -e the "  isolation" of a a. Also c1D~#E , which acts as a template for1ug-local.save_prec = f. (Nemax(LEmax(/in(%in(l_ = 24!eq = 4250({-)*ynchro =v.Event()finish1)2)|tJT-(target=thfunc1, args=&,)*th^=2={X.star5th2)H.wai129u0sigSignals[0]PassertFalse( flags[sig])th1.join K+(] (](in class C0ing( D = C6)Py)7 P7Usabilityl@unit.CCasepq'''UnitWs8` cases arison_operators&):?c7elfZ(!da('23.42'/db <745'D#twos|aGreater(dc, das#_Equal( Less(da, dcH E%!bF7Not$jIEqual(da, dbC) #a Decimal and an int self.assertGreater(dc, 23)#Less(23, dc QEqualA/45uncomparablef3NotIa, 'ugly'n (O32.7&object()*Y sorta = list(map(e, range(100)gb = a[:]random.shuffle(a a.j(Ca, bdef test_dr_float_bPison(>%):x0 = .7.8dg('0.25d73.0WS0da, 3.0!& 0b, K%N* 8?1.5OHarw(3.0, d ) (O, db"' & IoH$1,C ?1')|v?lex~t\w(1.5+0j*&8Q`R($P C'ODdb, ++1r3.0+1j)x'UIs(db.__lt__, NotImplemented9e9$grC9raction 6SF = fH!s[Da3].F~-|ContextT'olocalc, InvalidOperation = self.decimal.Inv C emax = C.MAX_EMAX if C else 9.i]C.MIN_EMIN.-.9/Btiny^0HTINY11272c.ontext(Emax=, Emin=emin)with localc15c):IPc.preRE assertLess(D(0), F(1, /))N ?F(-I , {O @0,1)*"1e" + str(e[) MD("-3Qu=iEqual(D("0.1"/10019 a3?3002NotM`D(1)/3P?1,3z0}3<8 zbF(120984237,9D&"9 ?max rGreaterS-D(9hT(D('inf'?,12=?/99> x-y;w|Raises(M'nan').__gt__O- Is(NotImplemented5p.__lt__WZ"D(Fdef test_copy_and_deep methods(oDj yCd = ('43.24'e.&(dm.id(c), id(ddAE dFRhash_!# ,0ef yGit(d]M1a = b = d.__hash__() self.assertEqual(a, b#return a 9#just that it's ZEable!it(Decimal(23)S 'Infinity'$-%onan123G 0NaN test_values = [sign*(2**m + n9 for m in [0, 14, 15, 16, 17, 30, 31,l132, 33, 61, 62, 6 4, 65, 66]A}n}range(-10h l/2v[-1, 1][.extend([x"-1"), # ==> -2(0(_zeros'00.0)!-"# ?0E1! ~-0E12")010.C # negative exponent@23.0[ 23_Oposi_4.5678E5; A# a  Qwhichc(n) != 0 % O64-1#Python pre-2.6g"2**64 + 2**32 - 1N# selection of"s fail with the old (befor7`# versD2.6) long.__9/__"1.634E1M o90.697'o188.83'_652.9'_56531&'])Zb check\S(d) =qint(d))integralc 7in :"e k1it(:!),;0it(q)Asame'@to a+cN&3)i !:Raises(TypeError$, E#'s<STrue(0WInf')0 y1?# c esa float match whenyCrepresent exactly! Tp.astring'inf', 'a, '0.0^.0e1' '34.0', '2.5112390.62`-0.515 3] for s in test_strings:&f = float(s)d = Decimal self.assertEqual(hashit(f), Ed)) O with localcontext() as c # check that the value of X doesn't depend ong# current k (issue #1757x"123456789.1"Tc.prec = 6kDh1 =xZ2*10323 f33 OZ1, h2%3J1000'1100 ** 1248  :&x)x2defmin_and_max_methods()I0 = ".d.dd('15.32' dyG28.5l;%15l-&28\#betweens+ Is(min(d1,d2), d1~&O2,d1& &axL L&L2 and int llnDax(l las_nonzero%#as falseF(&0)7?tru6ETrue5}'0.372'"tog#Test strSrepr . )str(d), *# >?"ep") # !3_tonum  { ?int ('66 #4Aint(&66$ &;(15i 6^float(d2), 15s.32) e#floortest_pairs = [-('123.00', 123),o3.2', /54?899-2.3', -M@-11.=-11000-0EN 89891211712379812736.1',  W]for d, i in >: ;self.assertEqual(math.z(Decimal(d)), i)84Raises(ValueError, A$, B'-NaN')C*sC/oNaN123 Overflow ?InfE/-FW#ceiling#4A('3.2Mf71|)@+ B B% G-2 Dround, single argument6@-3.5T||40T10I2 &Equal(round(Decimal(d)), i) self.assertRaises(ValueError, round, ='-NaN')>%s>*oNaN123~ Overflow?Inf@*-A>#!two arguments; this is essentially equivalent?to quantize, which6 already extensively tested:_triples = [ ('123.456', -4, '0E+4'),%3%3% 2, '1E+2% 1%/.2' 0&IO23.5o 6& *'0OO5', u4&zG , p g@, -2"Jc314', # ]for d, n, r inK<:%9 Equal(str((Pd), nD1r) <2defRnan_to_float(J)]# Test conversions of d NANs to ;.V# See http://bugs.python.org/issue1554400 = ~.^.'s('nan', 0123N#'-W2468'2f =s"|QTrue(math.isnan(f+aign = "copysign(1.0, fc Tign, -1.0 if s.startswith('-') else 1.0)@OA- E1357X D5d =Rs <, dQeval_ } #@U zero@ (0,f), 0) 0d, P(reprp'#i ]1, (4, 5_*"d = Decimal( (0, (4, 5, 3, 4), -2) ) self.assertEqual(d, eval(repr(d))) ,e#weirdd = Decimal( (1hea, 9, 1qw5x!def test_as_tuple(%):0 = ".d.ith zero;0 .}"),R`0,), 0NE#int [?-45]G5_complicated stringn"-4.34913534E-17"| w%# The '0' coefficient is implementation specific to 7py.HIt has no meaning in the C-versE1and[`gnored&reCp"Infinity&:'F'@lead:sshould be?ppe`` 0, 4,p |B  0ro0), 37l637)E`Y, kNaN diagnostic info s0!'nt) Cu/'Nnv;), 6a$Z6w@ For\4Gies,always silently accep7anyF@l8i - aeJ0, 2, 7, 16@8ainteger_r@ # exceptional cases self.assertRaises(OverflowError,)0 Decimal.as_integer_ratio, ('inf'))DmK-n_Value1O-nan k6psnan123nH for exp in range(-4, 2):!%Vcoeff'K1000&*@sign)'+', '-'L&6d =%s%dE%d' % (?!, o,8mpq = d2(#*0p, 09pq # check return type(vIsInstance(pq, tuple|5_, int2q2normaliz> n: q should be positive;Bp,@rela,ly prime to q.9Greater(q, 0Equal(math.gcd(_), 1) that p/q actually gives the correct v `Ep) /Sq), ddef test_subclassing( # Different behaviours when 7`}0 = Q#.dx3 My(y = None8Gd1 =71)d22We1 + d20Is(5(d))d1.max(dT@Pcopy.'(dC*0d, J`P.deep iE# f('1.0'xdx(x #em~elf.assertIs(type(m), MyDecimal) self.assertEqual(m, dIs(m.y, None) A## T(^5x =mV4x),*(x|t~um.y = 9/1,M NKIs(x/ def test_implicit_context(8%):R" =Qd.'3getA *Check results when @dgiven ly. (Issue 2478Fc = ]( HCstr((0).sqrt()),31c(8#))k<none_args5$Cs 2Tlocal 1InvalidOperationa 9DivisionByZero7 5Overflow/)?Und*+SubnormalU+|Inexact)'|Rounded''^Clamp'Xwith }(()) as cBVPc.pre7j0Ema &99i- 4/V"111":g[e9999"z 0"1eb# e# Unary funcFs"c.clear_flags}cx.exp(=), '1.609487E+48'GqTrue(c.m[]. .tRaises(0, y, C]E(0Is(z.is_ +, False<s9 ?B {Jx.lnX4.709530rtTrue(c.flags[Inexact]) self.assertTrue(c.flags[Rounded.c.clear_$(J&Raises(InvalidOperation, Decimal(-1).ln, context=NoneN T9]) Equal(str(x.log10(), '2.045323'_|bwbaZADivisionByZero? 0)b! S>3ical_invert1111000 0, y\! V.y.next_minus19.9_E+999  w'sNaN')ly/plInfinity5frz.normalizeOverflowI!I z.number_clasB+Sub'B-Oz.sq0E-1005 ]Clampq .e(c.flags[Rounded]) self.assertTrue(c.flags[Subnormal0Underflow0c.clear_V(|Raises(OvE, y.sqrt, context=None> D9]) c.capitals = 0 Equal(str(z.to_eng_string(), '1e-9999' g*1 # Binary functions1 anx.compare(Decimal('Nan891287828'): ans, 'NaN@ 0InvalidOpera%, %, MsNaNZ  `W&_signal(8224!+-1~nlogical_and(101!/10#{[, 123|Z/or&1+/orvx(0 "xp?max]7max-C c.clear_flags() ans = str(x.max_mag(101, context=None)4 self.assertEqual(ans, '111') Raises(InvalidOperation, w, Decimal('sNaN') qTrue(c.[`9]) 8c.clear_.  /in&0$/in}*'w zremainder_near' *y.}.,  Mrotate(2 "/00 "x.vnscaleb(7"o.11E+9"x;000}Z_shift]u< 6# Ternary funcs$:0fma 3 ?225Overflow:7fma(`1e99998}None)  self.assertTrue(c.flags[Overflow]) *# Special cases c.rounding = ROUND_HALF_EVEN)ans = str(Decimal('1.5').to_integral(L=None, context)))OEqual(ans, '2''?DOWa1Z/UP3aclear_(0W Raises(InvalidOperation, JsNaN  { a}b'o_valueh5n! |tz_exactz4z" |zzT)UPN? 0001').quantize(exp=Decimal('1e-3'), rounding=None, contextG)) self.assertEqual(ans, '1.501'+$c.W = ROUND_DOWNOans = str(Decimal(K0M.quantize(exp= 901/UPH7clear_flags(d Raises(InvalidOperation, yI(, F)10 oqTrue(c.[u5]) 8with localW"(C_d()) asm:1n+.prec = 7Emax = 999lin = - 2ctx c:, 7,,.1in,Edef test_conversions_from_int()# Check that methods taking a second argument willD# always accept an integer in place of aG.:^'d. E"(4).compare(3),XX 0'3)i_signalp7w&?totv 6u+O_magy:}10101).logical_and(1001;|C D/or~%o}%x~';567).max(12M  Decimal(567).max(r123))) & self.assertEqual(9P_mag(5,4<\ 4<q/inm%ini!in4"next_toward8y1234).quantize(100) 6u/009768).remainder_near4{<I.rotate(1v1n+Qsame_f umef ;|0k'9.123').scaleb(- 8y@c456).shift(-c1mcU-12).fma45), 67< 67/45xg class CUsabilityTest(!):dMC = C5)Py(6 %P 7thonAPItests(unit .zsCase): q f P_abc( " =.@(7True(issubJ, numbers.NOFals> OReal<IsInstancet=(0)w ?Not= vdef test_pickle(self): for proto in range(pickle.HIGHEST_PROTOCOL + 19@Decimal = V".d. e,Csave!0ys.modules['*']2# Round tripK=V4elf 2Cd = ('-3.141590000')(Cp = dumps(d, 'e'zloads(p assertEqualG*e)Fif C"# Test interchyability*Tx = Ck23e81723._y = P. ]sbC+ 4x4WPWrc*sxdPhIsInstance(r,4 Kr, y\s^ yZy 4 xG c.as_tuple(an9 "s vyyT ~  KTdef test_int  @ x-250, 250 s = '%0.2f' % (x / 100.0 # should work the same as gifloats P(s)),(9nto_integral in the ROUND_DOWN mode d = Decimal(s)r = d.to_integral(I *self.assertEqual(Rint(d)), r) \.Raises(ValueError, int,v'-nan')n<s<Overflow{?infz > -?def test_trunc(!):-0 = ".d.8 for x in range(-250, 250KO s = '%0.2f' % (x / 100.0E&# should work &same as gefloats1 (s9n_f]Rmath. Sfrom_Velf): class My0+ r__init__0;, _#x&y'True(issubx(xd)".60.1_type(r),-0str, \['0.1055511151231257827021181583404541015625'nr.x, 'y'bigint = 1234567890  !U(I]'.is_qnan(FF0infMeJ%K%),g B$o'NaN')p pI/yu+5v-w /4Typ.d, 'abc') for i in range(200): 0x = dom.expovariate(0.01) * (ran(2.0 - 1.0)Iself.assertEqual(x, float(MyDecimal.from_x))) # roundtrip Mdef test_create_d9_9h[0 = .1.U|Context''mInexac'OcOB(prec=5,ing=ROUND_DOWN($yU.math.pi),8('3.1415'p &UP5Q6straps=[]yRaises(%1 :r /X}_repr(_k(-0.0) "_-0')"r/q1p31]quantize(HvalidOperation&*In 4 = `Emax=9, Emin=- 97.335').L.01'.O7.34L; w" 3  i_A"10e["%%, }@1e10C'), %=c)5d =L"0.871831e800}5dfd, exp="1e797"); x8.71E+799')zcomplex Decimal = self.decimal.D3 Cx = ("9.8182731e181273")(FassertEqual(x.real, x$ imag, 0$ conjugate()Ot 1 complex(x), float(1)))Raises(AttributeError, setattr, x, '_', 10CC, H,#__$__Jk def test_named_parameters(/!):%/@D =  N|Context'Holocalc,1InvalidOperationa 9Overflow1Sxc = (`xc.pre1U`xc.Ema i&-1UXwith v() as cS6c.clear_flags(pxD(9, xc), 9*g=2/, value=9j8)xO , D, "xyz"aJFTrue(xc.N[M]4oFalse(8 q,D(2).exp('7 Q, D(8A E0-*lnD('0.7') o-1).ln M8 s0).log10O-inf@next_minusF/-26 ?plus(context=xc), D('-0.9')) self.assertEqual(D("9.73").normalize(context=xIO1E+1I999").to_integralKO9999Z-2000Gj_exactM'N 12[_valu?123J0.0625").sqr`D('0.2#mFhcompar, other=3), -1xc.clear_flags( Raises(InvalidOperation, 0D("sq_signalEwnan'),  K{True(xc.[]oFalse(80.01").max(K010100.0OG2@_magL-0.3 T3o#ink0l OS{nnext_toward $P.quantizeUK1e10 b!f!9.remainder_near[;1.5) 5H 9. fma(third=9p/7)y7yTypeError1).is_canonicHofinite E/inG29nan * self.assertRaises(TypeError, D(1).is_qnan, context=xc) CsC0_igned,JzeroCFalse(D("0.01"wnormal(  ;Tru=?sub@oadjust+conjugate ZradixAEqual(D(-111).logbC?, 2F:07ical_invertA1A'').number_classD4'+S'O21').to_eng_stringP 0.#  '1I1logand(D('10')\?, 0 J/orI-xJ)23').rotate(13?xc.clear_flags(\XOverflow, 1D('scaleb, =1xc.[l]l0jhift(-2.from_float, 1.MH(0).as_tupl`E1).canon O(), 0("-copy_abskyG /ne$-?"x"a, xyz=Bdef test_exception_hierarchy(&):decimal = self.decimal# DecimalException = d.4InvalidOpera4 4_Float2 0DivisionByZero 0Overflow*$=Und%&SubnormalK&wInexact$"wRounded""YClamp" # self.assertTrue(issubclass(, ArithmeticError))H ,, Z/)) F5DType  % } , #, I7S7# /, x88_:q"%"?%)?%'?`Converg`Syntax P$ImpossibleR5_finedQ@$@Context  CPythonAPItests(!):WC = C7*Py)8 #P 9p(unittest.TestCase): def test_none_args(self):"Context = .decimal.'InvalidOperation0 9DivisionByZero7 5Overflow/Sc1 = %()A'c2prec=None, roundingEEmax "in E`capitals$c clamp DflagBtrap for c in [c1, c2]~_xassertEqual(c.F, 28D), ROUND_HALF_EVEN:1, 9-Qin, --9.+?, 1,H:, 0)r_signala, c, 'k_', []11 *, |,x"])@cpython_onlyL|from_legacy_strinimport _?Axc$`0rndbRZModesg$c.-& =i.unicodeJ(rndaO!, .s`&''_[ Raises(TypeError, setattrrC', sw$q o\x00UP}5dpickle[ Pprotobrange(*.HIGHEST_PROTOCOL + 1u(Csave0ys.modules['*']2!# +U tripK=V4elf 2LCe = Tloadsdumps(c, )6 e9- Em e.-@ax, -/ax-1 595 5!e.h/ .flags, e.flgags)  self.assertEqual(c.traps, e )) 0 # Test interchangeability&combinations = [(C, P), (P, C)] if C else [9P)]?for dumper, loader in U:04Pri, _+ enumerate(RoundingModes)7;f;OrderedSignals[]DHtH Eprec = random.rnz(1, 1004Oemin<o-100, =/ax=y0cap 2 _clampt2~# One module2sT Qsys.m-s['decimal'] =;/er< .Context(0 =p, Emin= ax=emax,Cr=O[ri]>capitals=!, j=>oflags= ?[:fPE*ti8: nppickle.s(c, proto9The other?i?$;? Cd = .+s( IsInstance(d F"d.Z  d. , ; ax;/ax;-, L , ?E= R"_s<(a, d, 'R;', T1er]TZ$gZader][:ti]) ' sys.modules['decimal'] = save 2def test_equality_with_other_types(self):.cDOMCelf.N.V(7.assertIn((10), ['a', 1.0, (1,2), {}])oG/NoJ =>Lcopy # All copies should be deep=#|Context'Cc = (ad = c. E(id(c), id(d)*c.flags0 6Etrap6 6!k12t(cQg.keys(#k2!d!fk1, k2c !k#, S)Pn_clampIn Python 3.2, the private attribute `>` was made# public (issue 854L6old>becoming a@roperty wrapp`q`. ForFduration ofEBonlygettable/s via bothCv6 an7; i&3,]Bremoved.'Raises(AError, getb, c, ''/ab ~7(-1 c.,o-1), dCType3^, '-1,dd 2&dd) odd(1, * `21g`dd, '1417 compareY d = c.compare(Decimal(1), 3) self.assertEqual(;01, 6d-\61/, lRaises(TypeError,P, '1'r8 1;!) 9def test_7_signal(!):#00 = ".d\.'|Context'rOCc = (e6d =c B4v =.I ? ?totrr x_A3hf o?)<H&/, O_magp8 F E7|/L+opy_absjq?-1) 1-Npy_abs, '-1') def test_copy_decimal(self):!%D0 = .&.'|Context'pOCc = %()>id = c.aF(-1)(assertEqual(5o-1), d0Raises(TypeError,qo, '-1'onegatem4!;Osignm /-26>_1, -26 f0bn941, <~Q, '1';;12_dividiY  :?1, ,Zf5/2),v27O_inthT >0b9-E$;?modN= Context()   d = c.divmod(Decimal(1), C2)) , self.assertEqual(:1, 2), d,Zf51jRaises(TypeError,P, '1'7 1, '2') 8def test_exp(!):!" ='dL.'|Context'gOCc = (V~X?(10 ,/100exp/0?fmah~8 34  C2, 3, 4,co52jp/4);s 1fma7`2, '3'O7T3, '4b# Issue 12079 for.fma ...b,Z )'Infinity'@)s"not a "}x@snanV1.222j#A and.2(>,'u/1)l'd1is_ethp 2v9|Bis_i&ontext = self.decimal.Context Cc = %()d = c.is_infinite(DAF(10)'self.assertEqual(4o10), d/Raises(TypeError,or, '10')def test_is_nan(v%):0 = ' 'j [ /?nan_ormall2  9qaf 07osignedk 2 9ns 0 ( Asubn<l5 < Ozerok0 is_zero, '10 ') def test_ln(self):Decimal = ".d.'|Context'fOCc = %()>d = c.ln(WF(10)yassertEqual(+o10), d&Raises(TypeError,]^, '10Oog10i.5bkb0ogb?ogbical_andk6), %og?O1, 11d:1'z1, 1? #oinvertpk/00 11a!y%/00/or$p&or?or( n3i)l /'1"; xmal.Decimal  Context = self.decimal.# 'S c = %()d = c.logical_xor(DAV(1), 2fassertEqual(?01, :d1d:1/, tRaises(TypeError,P, '1'z<1?)fdef test_max(F%):U ' 'g ~X /2) 7_1, 2)I)`2/2)dq1maxf)_.4/2'O_magkE ;-\6*B!8/ini/in ?in( `[V/in4k ;-\h6V(in_mag, '1', 2)# !self.assertRaises(TypeError, c.min_mag, 1, '2') 9def test_minus(D!):VDecimal = ".d.'|Context'iOCc = %()>2d =3us(ZF(10)!|aEqual( us&?, d)~us, '10ultiplyi4), 2 <_1, 2)=.^/1)71nz't9 ?nexoZ 3/10:M /plj!9otowardh?1p#:'F <ormalizeia 29, '10') def test_number_class(self): Decimal = ".d.'|Context' (Cc = %()[assertEqual(c.k123), ()L0J/0)H?-45J"))dg?plu_cad = c.50 -1,d[Raises(TypeError4m, '10'OowerZb4), 4 91, 4), p+X/1)41ht/4)'6o1, '4' modulo=5, b=8, a=2), 1!quantize$hO 2' <01, * .^j702z292remaindjX  =/`8'Dremainder, 1, '2') def test_remainder_near(self):#'Decimal = ".d.'|Context'rOCc = %()>kd = c.cT(1), &2)5assertEqual(B1, 2), d4jv=1zRaises(TypeError,P, '1'"?^1, '2_otateid  :,Z5(A7OsqrthH0} -/10q430same_quantumi   2r ;'G =_calebi^  s:,Za8/2)Sv  self.ass2ertRaises(TypeError, c.scaleb, 1, '2') def test_shift(self):Decimal = ".d.'|Context'iOCc = %()>0d =ZT(1), &2),assertEqual(c.1, 2), d+Xd41hvP, '1'6oubtracjM  <.^7(C9to_eng_stringsh `0p 6/10v =Y0oto_scir6=integral_exk;to_& :* A._valuenk.!:.lf.assertRaises(TypeError, c.to_integral_value, '10') self.assertRai@10, 'x') class CContextAPItests(!):mdecimal = C9+Py*:PtsWithStatement(unit.TestCasez # Can't do these as docstrings until Python 2.6#%P! c?handle __future__ s{!s 5@def 1r_localc(bt0# U copy of current 31 inQblockZ94get = U.S.- /_orig_ctx = P()Xwith ; ()$Penter8J0setM_final! 4Is(%, 9, 'did not restore>correctlyWIsNotSQ%thRH(;R, '___ returned wrong:#.?arg1suppliedT2_ , *- /Y2 =3new;(prec=42 5TEqualo.#,  seHF%, J\pnested_h_Z7D]=T ' *-|Clamped[XOverflow = self.decimal.Overflow orig_ctx = getcontext() .clear_flags3new>C;Emax=384Cwith local_u as c1:fself.assertEqual(c1.o$, Z7Wtraps7 71c1.[Clamped] = Truec1.Emin = -383#No5,4 u5sRaises(~, c1.create_d, '0e-999'D& /})2Q2x#, ; h:e:: , c2.power, D('3.4e200'), 2M sFalse(c# V3]hodel c2{[HD1D!V1q;2  3 d 1cdef test__statements_gc1(})H0 = .2.U :5> B 3'F h4J7N4 c2cV/c1D2DT L3LV Tu3u? '_ , getcontext = self.decimal.getcontext s - .with localH() as c1:#Xidel c1bn1 = C}(prec=1)!o+(nv"n1x2x|n|assertEqual(c2.+, m-2,n22%[n[ #()N,n33 8lf.{7333U #c3y1LcL,n44D#g/n46V:848 #c4!d5c4 class C}WithStatement()5NC/Py/DP Flags(unittest.TestCase):m@def  _f(_irrelevant(,# check that the result (numeric!+ J raised) of an# arithmetic operation doesn't depend onbrcurrentQCDd F'B ''mInexac'|RoundedN'Underflow)+^ClampR'SubnormalRws_error(;,A,)ifR == CB.[] = True+4if .Rtraps.S0 GNelse1V_6)$C9, Emin = -4250Vax =  ring=ROUND_HALF_EVEN, traps=[], flags=[]) # operations that raise various 3, in the form (func1, arglist)OM5= [m(context._apply, [Decimal("100E-425000010")]),;Gsqrt92*7add)"1.23456789"), y9.87654321u\multiP(xsubtrac!]:try individuall then a whole lot at onceg ets = [[Inexact], [Rounded Underflow RClampSubnormal]O#, M%, K#, I&, Gafor fnis`:d# find answer andd using a clean  A."!r_(c anfn(*args0;k#P k, vU.items() if v\Rextraz<4:ets-R# set, before call  6&z-*d_error, +Lnew_A #=we expect to beQafter5#edJ = ( !ifB noti"d q.append' ,sort(key=idU/awe actM gotW|bF. self.assertEqual(ans, > c " produces different@s deFns!_: " +cg@ %s,3 %s." % ) [, JU+! "ted %s, got %s" % (expected_flags, new )) def test_comparisons(self):%)Context = .decimal.'mInexac''|RoundedNvCc = c(# Valid SignalDictZassertNotEqual(c.c.traps). %#, 7x3 = JIt+q [] = Truewf!o+"+4%{}fd.updatecUdOdt[? @h ((, k_# Inv[f:False >mu["xyz"]ne:@requires_IEEE_754hoat_operationD KdFloatOE . 5olocalcq(Xwith v() as c#  is off by6aulA)i(h[]7# implicit conversion sets the L0qc.clear|&s(<Zp(7.5),  L0" c.create_;N# ex=does notFECx = 8p.from_f=s>&# 0xD)  x = c.create_decimal_from_float(7.5)  self.assertFalse(c.flags[F0Operation]6Equal(x, [ ?TruZ # set the trap c. 0 = d , # implicit conversion raises)c.clear_(R:(2, Dg6+ 6N# exNis silentQ3.3{ 4def testm_comparison(g!):%}0 = ..'|Context''  . 5olocalcaS*_attr(a, b, ,`, signal=Nonelkpf = getR] #if`J == \lZj, f, bYOelseB Is(f(b),f <h(MGsmall_d =Av('0.25'^:big 73.0A58X663.0JzeroL0LNneg_$-%![50.0o:1u:inftInfinity? (-)%cO'infF!-"odoit(c u# Order6I1for in '__lt__', Ne__'7t$1d, .)-jgjgjrt_attr(big_d, small_f, attr, c, signal) # Equalitypassert_<(JS'__eq__'WKNoneU>neg_zero_d, ?f, D CK?4'?{4inf B20d, 9 _# Ine0big!_'__neDecimal('0.1'), 0.1A >  D = G0NaNfloat('nan def test_containers(Q=:wc.clear_flags()s = set([100.0, ;')]/Belf.(len(s), 1(qTrue(c.} [FOperation] #if3 srRaises(], sorted, [1-.0Oelse\ F#F4b = 10.0 in [j, 1.0] @{A:'a'_:'b'},nc = Contextwith localnc) as c{@Falsu^trapsu5Ldoit? k /c.s0 =  X y  N 6b!T$_oo_default(*)==dV.S. ''Inexact = self.decimal.Inexact  FloatOperation= self.dec-  5context = C %()AassertFalse(-z.flags[S]8Otrap8q`aclear_.[] = TrueD& -E=7) class C[F7( !):3(Py'4 PhsSpecial:s(unittest.TestCaseo0"""S the U templates."""@def ?_$_$(8M}SBasicw y1Extended4 73get f-s--uInvalid> ` 9DivisionByZero7 5Overflow/)?Und*+|ClampedS{_signals(, 1, '%',\8[*, $, %, #, ]M)Fsavew().copybbiprec =.de` 2 Y56f = NonM2try)>? = Ue = 441Z;5forf9 in,E v?(!G !.IsNot(c,O.qEqual(c,.except Eion as eex = e.__%__ofinalleD 9W]Zif exraise ex.tdefault{b,D BasicContext = s elf.decimal.BasicContext ExtendedH = s4 7BgetcJ 2-s--InvalidOperation` 9DivisionByZero7 5Overflow/ *assertEqual(O.prec, 9)/ J23]_signals(q, Default, 'traps',6[*, $, ]9)6ave().copy(d_._+ =^ex = None{Etry: Hc = w Csavehc[< "!i = 961Eb h$, {,s(~)'t|IsNot(c M.6961*except E>Jas ele.__class__'kfinall ^H"D/$Zif exraise ex CSpecial+s()CC = C9+Py*:Pt`InputV(unittest.TestCase):@def "_i  nB u . ]o Y # Ie, Emaxfor attr in ['!@', '#"']\^0set)1, 9  g6)7Rs(ValueError, zA, c,7, -#lf @?Typ?W'xyz'e# Eminp'A', - 5)6 D', \= c, 'Emin', (1,2,3)) )self.assertRaises(TypeError, setattr, c, 'rounding', -1)A+9@,?1.0B,W'xyz'# capitals, clamp@for d in ['&A', '(5']:+TQOValuRU L@!2 ?~[] qInvalidUibuteAAttr$2emax', 100`signal dictb'flags', []?Key=/{}= utraps',w #{'DOperation':0}9s cannot be deletedZ {@precwEWP'Emin@'Ppc.__delG1__,- "sgt'!9vsconstructorContext, h!=9: ?{31?m=8= )r%_=["P"c:S@=["Q:f #  e\uversion#3r__(0,1)@(1,0sclass CY`InputV()decimal = C G/Py1H#P IG1SubYing(unittest.TestCase):@def "_c'_s6N): decimal = self.dec# D3 = ."wContext""hlamped""DivisionByZero) 0hInexact"OverflowL$YRound"bSubnor&=Undm&InvalidOperation  5class MyS(%):"def __init__(, prec=None, r3ingEEmin "ax OS capitals. c CflagF Btrap+ n.)S!if is not L.! =2JN/=UVbR+ = J/axJ0ax J/axJN/$= VS,=<MIMif isinstance(5o, listT& = {v:(v in a) for OrderedSignals[2] +*}VbJ" =( '1if 5&* " =3 = (_@attrr ('D', 'F  axm 1-',T{! 'x''assertEqual(get@(c, 4), d)#1MRaises(ValueError,R, **{F:-1}6c =&(&=1^c/, $ 3, c.quantize, ('9e2'), 0rounding 2 self.assertRaises(TypeError, MyContext, **{'rounding':'XYZ'}) 6c =-((=ROUND_DOWN, prec=13yEqual(c.8&, 91 plus(Decimal('9.9')), 9) # EminuOValu:?':5 ?=-1,7, -x = c.add1e-99'), 2.234e-2000') x4)0., for signal in (Inexact, Underflow, Subnormal, Red, Clamped):<S@True(c.flags[a]y%ax=9yoax':-1z?ax=yGax, x$Ov K/1e "ifGdZ == C8{y ptcapitalsx#>| %/=0$c.'', (screate_.('1E222'N to_sci_string(x), '1e+70# c;?':2t!uEmax=99 - w _I3str/.0 E+: %#=[, DivisionByZero] 1 dc.clear_(vOrderedS#s[v]tOFals Otrapb ^:^ %^If.assertTrue(c.traps[signal]) c.clear_(Bfor - in OrderedS>s[decimal]:GNself.assertFalseu class CContextSubNing()^lC = C?.Py-@P @skip_if_extra_functionality^CheckAttributes(unittest.TestCase): @def _module_a4 ' # Architecture dependent c q limitsW0@JEqual(C.MAX_PREC, P 1DEMAX1 1 qIN_EMIN1 1ETINY2 ) True(C.HAVE_THREADS is N or B4/(PKK^ __version__dir(C), #P)* qx = [s lgI#C.()) if '__'s(not s.startswith('_')]yPPP( Wset(x) - 1y), DX/(93/C.Q( Coverage1adjusted(d00 = .GX9('1234e9999').f), 10002N# XXX raise?=t V;nanP0L7>inf7o$anonical .3getg 58o+E9).c}Cx, 9qFc = [0\cSh]\_repr~pSfault2d.copy( c.prec = A4250# c.Emax = oin = - rounding = ROUND_HALF_DOWN\capitals = 0lamp = 1for sig in OrderedSignals[self.decimal]:1c.flags[sig] = False!Ktrap!"c.__repr__()t = "Context(prec=$, =U, " \Cf"Emin== , kLP=0, c/=1GQ=[], U=[])"iassertEqual(s, t) def test_implicit_c6)MD_0 = n.LSlocalC ,~2Xwith v() as c{& c.e 01i0U# absCabs(("-10")), 106_# addH D7") + 1, 8DZdivid G / 5, 2HO_intLl/ 7, 1M?fmaF.2").fma0P0.01"0HIb3NaNE.is_nan(), Truethree arg powera5pow10), 2, 7 V?expJ @.exp3I_ormalO,4RVAsubn%Y7\P/lnQCa20").l Flog1H1 }Ologb!580ogbJ logical_inver.:] OminuG -;DCmultiply2") * 4H_next_.6(), 9)  # next_plus self.assertEqual(Decimal("10").5D(), '2E+1'))I# normalizea-b6 b/-1cumber_clas8h1'+Nw' +"-1"), -1Dremainder| % 7, 3KsubtractJ-Jto_integral_exS.12345").BI91) # Boolean functionGTruen").is_canonical(_G9ofinite6LBsnan m)osigned7is_zero4%e# Copy with localcontext() as c:"c.prec = 10000x228 ** 1523Ty = -'x"z = y.copy_abs(?z, A@nega ~D1v def test_divmod(x)A0 = ".dW. ,1InvalidOpera` 5 9DivisionByZero7 *sq, r = C912837129+;100-~qf10901935j 5r5 9400NaN7iq0nan"End r c.traps[] = FalsL c.traps[InvalidOperation] = False c.clear_flags()q, r = divmod(Decimal("inf"),  :self.assertTrue(q.is_nan() and r7 !c.)) '?101 infinitev_0), 0sItraps[DivisionByZerod5/11= [+  def test_power(%):P20 = ".dQ.'localcontext,1Overflow-)|Rounded(TXwith k6s c c.prec = 3aRVEqualU1.0") ** 100\'1.00') ]1~Emax = lin = -"c. pQ10000 X("0.5cO'infquantizeU  v &  0E99).T_"1e1" xd6_radix$getcontext = se lf.decimal.getcontext Fc = %()self.assertEqual(DF("1").radix(), 103c(\def test_rop(e!):c0 =  for attr in ('__radd__', 5sub 5mul ptruedivqu=VdivmoL SfloorAigpow__'J7`Is(get <, )("xyz"), NotImplemented)&e-5HG1.234567857Q '10N0S--T10E+8 ~Raises(TypeError,C ("O, "5IL5, 8screate_ E ".CDValu*c.a|, ["%"]%sign(x, 1}class CCoverage( ]R = C +$Py#,mal = P cla&ss PyFunctionality(unittest.TestCase): """Extra f/ in decimal.py""" -@def E_py_alternate_formatting(selfY]# triples giving a -R, a D` , and the expected resultrF)S = P. localcontext!Cvalues = [?# Issue 7094: A (specified by #)@('.0e', '1.0ke+0'),$#%.&1.0fCJG ".#gB1"".0#Cb# 1.0%;?00%E %.&]Efor fmt, d,.assertEqual(w(?@(d),O)Ma) cla7Whitebox2 $A box1 exact_power(Rarely exercised lines2_>. !Xwith z() as cJc.prec = 8`a4x =(2**16) **j"-0.5"' %x,0'0.00390625'))j6j12885819l "256e7" q1525878 :B'-0. < _"0.2" "n q r5**2659 81O 9*5'R/20Ti2**578]dimmutabi`_operasm6Do check that it didn't change inl objectsDefaultC 8set >f.copy(Qc.traps = dict((s, 0) for s in OrderedSignals[P]) setcontext(c) d1 = Decimal('-25e55'6b (d2>h33e+33>}ef checkSameDec(operation, useOther=False):5%if eval("d1." + R + "(d2)"- self.assertEqual(d1._sign, b 52int4?int32exp3?exp32 5?2._22._ fOelseyw] &d1-|1|+t1} &"__abs__ dd__", True &_divmo)/eqN/ne%l%tJgJgJ@floa()floordivOhash /inl _truncB ?mul?negl 0booG/po ?pow/raOrepr rrtsr?sub:checkSameDec("__str__") checkSameDec ub__", True&truediv*adjustedqas_tuple!compare ?max" /in" normalizPquant! remainder_nearv Qsame_Y/um+ ?qrt(`to_eng?ing& integral") def test_py_decimal_id(self):"*DS = P. ?Cd = 6(456ed[ .assertEqual(str(e), '45''#No*id(d), id(e)|rescale# Coverage localcontextXwith v() as c5Mx"NaN")._3, ROUND_UP5"(x.is_nan(]_rounsRaises(ValueError,q"3.1234v8, 0 class CFunctionality(unitb.TestCaseX"""Extra f/D in 2"""p@requires_e2_2sc_ieee_ issue 8786: Add support for IEEE 754 >Ss to  module.n-C&'C.$DECIMAL32 = C. (64 ,64 8128!2128MXt,j(z.clamp, 1WzsignalsZ, 'traps', []7Dflag71c =~Q(+[.prec, 7$ Emax, 96% gin, -95resTrJ/64g 1 /38K !Em6383r c = IEEEContext(DECIMAL128)  self.assertEqual(c.prec, 34% Emax, 614' in, -6143Oo`_rest(U, c) # Invalid values+Raises(OverflowError,g, 2**6t=V^:&-17C1024@requires_extra_functionalitydef test_c_ck!):S = C. $c8 flags=C.DecClamped, trapRounded_D(, E1 a1bonstantsp# Condi3 Zcond = (ConversionSynt%@Divi~ByZero,F!ImpossibleQUndefined=3FpuPmsInexactA>!POpera8bMallocX\Float3BsSubnormal*Qif#`!N#C.go32, 32G*_64, 6H *_128,  C._CONTEXT_MAX_BITS, 512cbfor i, v in enum e(t  wv, 1<DmS = C. ulocalcontext!Cb1 = 10**35;$b26Cv() as cuac.prec>0? i in range(50a =dom.rand)yb1, b2)L-b-1000, 12001x = a ** bLCy = B0(a)$bH.assertEqual(x, y)Tinvalid_constructionIRaises(TypeError,, 9, "xyz"dc_input_restric# Too large to be converted; IPOpera% .C RFR~I+()FS ,,cN"1e9f\_repra# This5 is -only because flags are not printed#4the same order.sDefaultC *ZFloat o Fc.copy(+0425%00iPc.Emaloin = -ProundJ= ROUND_HALF_DOWN\capitals = sPclampy+o0sig=O4edSignals[C][sig] = TrueF_traps "c.< K G"c.C'o1c._K6__(|"(e=B$, 9=7U, " \\f"Emin=~ , L`A=0, U/=1G0=[CvOed, eivisionByZero"LR , Overflow, RfSubnormal, Und]R"l8 "FloatOperation, Overflow, Rounded, Subnormal, UndS])" self.assertEqual(s, t) def test_c_context_errors(6!):%HCS = C. InvalidOper% .& ZFloatJ *SlocalL&8get$"s""HAVE_CONFIG_64 = (C.MAX_PREC > 4250T/c3(# SignalDict: input <8q|Raises(KeyE, c.flags.__setitem__, 801, 0)AOtrapA]Value4del EE 6M 4Typsetattr, c, ' ', ['x']A'@y@ _{0:1} @@ # Test assignment from a al dict with the correct length butIRone iU key.5d =bVcopy(jdel d[]9["XYZ"] = 91283719 :dv<6doIccorner casesint_max = 2**63-1 if @elseE31-19g8"_e=o10**18<9k# prec, Emax%inV@for ` in [''@', ')&']EWQP', X E'Emin', -Htconstructor2 ],*=tA<A,?in=fversio1E (+1lf.assertRaises(OverflowError, Context, Emax=int_max+1) self.assertRaiB Cin=-C/-2C!_clamp+capitalsF+# general Value, for attr in ('prec', 'Emin axo 5'):CC@0setgA, c,p#, CJ$K if sys.platform != 'win32',-/, EI51) S : _unsafe_set,Kemin%axKif C.MAX_PREC == 4250  E[(c, '5'),p%g7 uOemaxu`/inu2Nc/, UYZ'), 0L 11070<s"/ -M8[_4<t |!, ,$['&]R 9S @tr, 2)  self.assertRaises(TypeError, setattr, c, [1,2,3]) >if HAVE_CONFIG_64:%gOValuhZ2**32fG&E+1) # Invalid local context exec, 'with?>("xyz"): pass',M u6s()qOC=get /()p#Ecsaved_8 = h%V ?", 98 hdef test_rounding_strings_interned(O&):Is(C.ROUND_UP, P .FDOWN02 vCEILING58 VFLOOR64 IHALF8p:<7EVE<< (05~@requires_extra_functionality#c _e2sCS = C. G POperae% .Overflow& "&)$"s"" g = (C.MAX_PREC > 4250RcL (put corner casesgint_max = 2**63-1 P elseF31-1o$# Cgeneral f{ <'_allcr', J$-K-jif sys.platform !=Jn32's 9 !I  ?{ for attr in ('_flags', '_traps'): self.assertRaises(OverflowError, setNR, c, int_max+1)J--K*-2K if sys.platform != 'win32'OType pH 51) # _allcrOValu':G', -X@!L?~v[1,2,3] if HAVE_CONFIG_64cG2**3~Go"# ", 1for[] 792C 3'x'G def test_c_valid_context(iq# These,`s are code coverage_decimal. DefaultCWZ = C.*qClamped# 2Und& qInexact SRoundX Subnormal:cJc = c.copy(?| # Exercise all getters and oPc.preS'34ring = ROUND_HALF_UP#Emax = 3000kin = -capitals = 1.c`F = 0bEqual(F, 34`%,4 REmin,( 1ax,' /, 7, 0qEtiny()/33y @Etop*G2967U munsafeif C.MAX_PREC == 4250 2c._B@_set4(} )Oemax)@in(-N S!, ,0 self.assertEqual(c.Emax, 97) >sel0Tin, -019) 2@requires_extra_functionality" def test_c_valid_context1(k!):*DefaultC$Z = C.w+Jc = f.copy(\ _allcr, 1&"c.E = 0;0\round# Restricted input._sDecimal !In(POperaK% .SlocalS*&MAX_EMAX" IN_ETINY int_max = 2**63-1 if C.HPREC > 4250P else'F31-1Xwith v() as c|.traps[] = True-|Raises(7#, g("1.23").__9__,KO --("uJtr@int(?+1)w /C.` y]$(Mf-{OverflowError12 r5.+14oformat5 HAVE_CONFIG_64 = (YKTypec14__, "=10.10", [], 9FMI,/[] OValu #<>zmaxsize h U a456789<eL "=%d.1" % integralX): Decimal = C.D # qInexact localcontex! 'Cx = WE(10)self.assertEqual(x.to_integral(), .Raises(TypeError, :o, '10'h:o10, 'x=&) o_value'@'@(CL(@(@)CXwith () as c:N/"9H.9") h(ROUND_UPTf,l?'10'')I%Mc.traps[] = True^ .u ^&, _Vdef test_c_funcs(_)# Invalid arguments8K3 6Operation% .DivisionByZero, *8get"Jp('9.99eYeng_string(), '99.9E+9'U16pow1), 2, "3">  9).number_class, "x", "yH same_quantum, 3KB "1.2345678k6izeB'1e-e'), []E %uantize, Decimal('1e-10'), getcontext()  self.assertRaises(%,TypeError,1Deck "1.23456789").quantize, %10EcROUND_UP,  with local5e as c:"c.clear_traps() # Invalid arguments re c.copy_signF1), "x", "y"9L anonical, 200;Ois_c>'divmod, 9, 8$Qsame_R!umI3IREqual(str(c.()), '200'Dc.radix()- !c.[DivisionByZero] = True` 5R9).__9O__,  H"c.=->(c.flags[Operation].@| D 7 'J ! O  lc.prec = 2  NV, pow S, 501def test_va_args_excep s()S = C. C 5x ="1"for attr in ['exp', 'is_normal 6sub lnjlog10'NPS'logb&p_invertnext_minus pl B'x1ize/umber_clas?"sqUto_eng_string'];G0fun0get1(x,6A#, H?="x<AONonein ['compare', 'compare_signallogical_and', '$ or23maxA_mag #inGremainder_neaK`rotate<ascaleb yhift']:Efunc = getattr(x, )$self.assertRaises(TypeError, A, context="x"<6"x"AeNone) { x.to_integral, rounding=DR&[]O"/{}M/@[],  o_value< U/S)_exact= U0Sfma, 1, 2Q 1 ?4(quantize7+ F ~G' %CZ(Sqc.powerj2, modc =b?@=@@requires_extra_<tionality"def test_c__templates()aEqual(BhsC.Basic?z._trapsC.DecIEEEInvalidOpera|DivisionByZeroOverflow|l@DecU>uClamped(DefaultD _dict(self):  # SignalDict coverage  Context = C. sDefault#  +InvalidOperation- .DivisionByZero, *Overflow$ Subnormal 7Und? qRounded> bInexac SClamp8  3DecX?nal"&Rself.CTrueSi[sig])|2OelseLOFalsMNJc = v.copy()&)  methodsA vc.trapsc.clear_(Lk2k.keys(qN`[k] = %?v?]valueA v ), ]Oitem\ tvByc.flags.get(1)08Is(-"x"), None.\Equal1@, "y63cRaises(TypeError, rQ, "x"B_, "z"w4len{2), Q = syesizeof2#G #__repr__1et c/;.;1c._6.y[]ax aa j6[1s:# SQ fromoionaryRd*d[ ~8E = d V Ji? %d[3 = d assertIsExclusivelySet(Underflow, c.traps) # Random constructorsIntSignals = { Clamped: C.Dec,!URound!!sInexactB!Subnormal#%%%"Ov$#DivisionByZero) /InvalidOperation1LIEEE} IntCond = [ JsImpossible,SfinedFpuErrorsContext.oMallocH`ConverfSyntaxi]Flim = len(Ordered6E[C])for r in range(lim):!t! %r])XingModesM,@flagr~.sample6, r81 =?dom@t@Fprec?1, 100006Oemin6-4/, 7/ax70m c727capU?0, 2rb3 = (D=!, Aing= p, Emin=. Xax=em capitals=!, =!, 1a=list( ) G$3 )a$aself.aEqual(c.i33ing 8+ , ,3 ax3/ax3[ , \7>Yf = 01T9x(F |= ?[x]Ot_Z?, f'?c._traps, f)3 for cond in IntCond:$c._flags =( self.assertTrue(, &DecIEEEInvalidOperation)>9IsExclusivelySet(5A, c.)Otrap,>Vdef test_i_override(E)tDecimal = C. 6try* from locale import CHAR_MAXlexcept IZErrorD.skipTest('N.G not available'|make_grouping(lst$return ''.join([chr(x) vxsKlst]Sget_fmt(x, $=None, fmt='n'c,(x).__format__(fmtGiE = {1"'d_point' : ',',#= a[255, ;0])7thousands_sep<5','Y} ?dotxo3, 3, .?sep.By<=f == 127: # negative e<Raises(Value>#, z, 12345> uH, 'gHl N3dotInH#3sepHexact_conversionC`contex(C.g*  BwithZ() as c:#V!c.w[I@] =  .# ClampedD x = "0e%d" % sys.maxsize%o s#, 7, x| b'(-d*-1&g* # Overflow x = "1e%d" % sys.maxsize !self.assertRaises(InvalidOperation, Decimal, x) =# Underflowxz'(-|9-1)*"def test_from_tuple(I%):\S = C. localcontext!& * ."Ov& &MXwith () as c:#c.traps[z] = Tru-% &y# SSIZE_MAXx(1, (),bEqual(str(c.create_d](x)), '-0E+9'E0, 1, 2iA,,  N(e/INeLh0-107iLlmO_Errorq+ S" Bh b27 b B# Specials?"N"b#KsNaN?), V@/ 1X)#1'9/ofHAVE_CONFIG_64 = (C.MAX_PREC > 42500) !self.assertGreater(Decimal(0).__sizeof__(), 0) if HAVE_CONFIG_64:"Dx = G10**(19*24)Q 2y252 Equal(y, x+8Oelse ?9*2 14) def test_internal_use_of_overridden_methods()NS = C. To# Unsound subtypingpclass X(floatQ!asger_ratioy(return 1YA__abs__8 YT|[1]*200WOI(inbit_length XZDp(I(1), O)for cls in X, Y, Z9X}+Ba.from_(cls(101.1)),A =9 @requires_docstrings @unit.skipUnless(C, " 2 C version") !SignatureTest(FCCase"""Function s2Bs"""i_inspect_moduleD@attrESdir(P^0if .startswith('_'%-continueEp_func = getG1(P,O c&C&@if (DS == 'A' orQpContext 0.is5()p_sig = 5_4 _c2 # parameter names'!c_ = list(e.6s.keys()M8p80[x x?} if notIx]d m#, _ EUmsg=" mismatchc%s" % c_kind = [x. :.parameters.values()] p_kind = [x[1]. for x in p_sig.parameters.items() if notM\x[0].startswith('_')] 1&# ]:if attr != 'setcontext')xself.assertEqual(c", ,^5 Umsg=" mismatch%s" % p_func)def test_inspect_types("):#gcPOS = $4._PUKind.POSITIONAL_ONLYPOS_KWD9R_KEYWORDu# Type heuristic ( annotations would help!)Zpdict = {C: {'other': C.Decimal(1)Qo'third,x(y(z(a(b(c(?exp*omodulo-num': "1"f': 1.0roundingoROUND_HALF_UP2E C.g?()}1PBPB,(((*-8/P.P}Fqmkargs(ge, sig.G c#kw%{}.cRname,[k7|Qame =lIinuec,n== POSR*.append([ ][-])[Belif]a N? = dc/seMraise TestFailed("unex~"edeter kind")  return args, kw$ def tr(s):2"""The C Context docstrings use 'x' in order to prevent confusionN with the article 'aBdescriptions."""<pif s ==r#: ?'a'$&y'$b$z$c$_s{doit(ty"p_type = getattr(P, ty)c$C$@for @OBdir(X m!if(p.startsPO('_')-continuegp_funcp,\ /c//if inspect.isi(tup_sig =8signature7 6)/# parameter names'!p_ = list(.:s.keys().@c<p[tr(x) xcG]self.assertEqual(Y#, , Umsg=" mismatchc%s" % p_kind = [x.  values()]cI IJ0# '!'%F2Is([0], POS_KWD 66Zremaining_Qif tyDecimal'@[1:]  &A  B ? else: #methods are posipal onlybPC ver. Blen(|0), )Q# RunW_pds = mkA(C, f?tryKVp3(9)s (*Z, **kwdsY except Exception as err: {_ew+)[C ]~ # Dynamically build custom@ def)each fileg # director y and add the definitions toDDecimalTest class. This # procedure insures that new files do not get skipped.;1for"0nam< os.listdir(directory):+jif '.dec ' R&in@L.startswith("."CGcontinueXhead, tail =P.split('.'))if todo_tests isANoneAG'in'|Ker = lambda self, f=9:`.eval_(F + fsetattr(CIBM Cases, '`P_' + , .er7/Py85del*,\4ailb! 56tryrun_unit (*_M&es b^CCfrom docA import IGNORE_EXCEPTION_DETAIL4Rsaved = sys.modules[')']1Jif C{G9I = C=+(C, verbose, op^oflags=II = PtpPpKUgfinall` C.setBext(ORIGINAL_CONTEXT[C]nP* P*0if  mwarnings. 1('C#s AR: no  (3d _1.',9RUserWZorig_sysJ{ `raise v#Failed("Internal error: unbalanced number of chang-?o "O ".") if ____ == '__main__'"roptpars0p =!.OP0r("V.py [--debug] [{--}! |01 [,2 [...]]}]"Pbp.add_#('>', '-d', ac='store_true'?lp='show:e_(o before each$ r', '-sr kip over 90%arithmeticdse(opt, args) = p.<_"() ifT.~z}#(X@=Fal R=True7Aelif_<-;,h=!, Q=opt. ]+seXmain(arith=T\rue, verbose=True) # # The ndarray object from _testbuffer.c is a complete implementation of # a PEP-3118 b6 provider. ItAindependenctNumPy's # and the |s don't require .."IfVpresent, som9check both\ slgainst each other]EMost7Ralso Uthat memoryview(;) behaves in #same way asoriginal. Thus, a substantial part of*' #a is now in this module import contextlib@unit  ,0sup4itertoolsRpermu s,Bduct,drandom)range, sample, choicewarnings syj, io, osWtdecimalXD@fraceF try: I* except I$RError2w = NoneKN0str?>octypes}>Swith .EnvironmentVarGuard()KBos.e1, \ lt.catch_"()$Tnumpy!1as _$ SHORT_TEST = Wo # =2 # R lists by format specifier7 # NativedTchars1ir s. NATIVE = {'?':0, 'cbB h 2 'HiI l 2 'LnN f 2 'd`P':0 }w$@ doe/ t  'n' or 'N': ifBdel Q['n']a@N'] 94{# Add "qQ" if n<Qmode.W.G.pack('Q', 2**64-1)"}q'] = 0QUek@pass0Stad STANDARDp(0, 2),Pa1<<8),'b':(-(1<<7), l 'B':*h*"15+ *$16Ui+"31+%'IU$32+l+'L':(0, 1<<32), 'q':(-(1<<63), b'Q':(04+f+d3102D  } def native_type_range(fmt):"""Return S of a1 1A.""")if fmt == 'c'<Plh = A256))'el+?+)f) ]d4: 8&se#for exp in (128, 127, 64, 63, 32, 31, 16, 15, 8, 7.6tryNstruct.packa , bexp)-1%Qbreaksexcept F^errordEpass6|(g 1 if& 1 else01<<=rlh fmtdict = {'':NATIVE@<':STANDARD">=!#if\ incR['@']s[fmt] =  MEMORYVIEW = .copy() ARRAY~k -vqif not "bBhHiIlLfd"Adel Q[k] BYTEFMT] ;BbcVLXvm'] = 0['@a61bh@ # Capabilitiesthe test objects: MODE = 0 MULP1 capO%# format chars  # multiplier 'ndarray':&(['', '@<>=R!'], 1213'].'D` (['a.R$['7Cnump{76 }nmemoryview':n @mm>nubytefmt @b7b7 Arand_fmt(mode,a, dom item! a specified by a F and a single 3Uacter0x =9$(*I ][]!if ?@Cs([x+ if.xgb'\x000# http://pro.scipy.org/A/ticket/19259 S!1'(^ool(xVf' or7pack(char, x)  x = struct.unpack(char, x)[0] $return x def gen_item(fmt, obj):&B"""R)single random ,A."""%`mode, as = fmt.split('#')![wfor c in/ex.append(arange_fmt([M[0] if len(x) == 1 else tuple(x)@s(n,Jxa list ofs (or a scalar)@if np0FF`lst = 1* ni#(nnKlst[i] =;k2lst< = choice(cap[obj][MODE]K0xfm)Q+ '#'b.strip('ambqnmemb ='2, 10) # numberD +2ersTGor _<fmtdict["])!multiplier23ULT,1+= w * int(@7if >1j =$+rd$ u+!s,Z obj='ndarray', C=Nonx PAom formatZaK@ is N= !if ;Wi=   v/#  ( +AN Piter_a  Iterate through supported /dcombinations[\m$B ing#>Qyield}eg!(n,i, testYX(1  ) all possiblePs and1mat_! |acters plus onecompou2 9ing"t, v$ifE != 5<  ") is_byte_N@ 'c'Yor 'bB' in fmt def is_memoryview_format(fmt): """ suitable for 31""")qx = len;return ((x == 1 or 2 and fmt[0]P'@'))7u x-1] in MEMORYVIEW) NON_BYTE_FORMAT = [cc+ fmtdict['@'] if not is_bytec)] # =2 # Multi-dimensional tolist(), slicing e assignments7 def atomp(lsTuple items (represent structs) are regarded asF$s.rMinstanced , !) z z6/is2@prodGmProduct ofZA ele%!ifg=0o0Gscv vlst[1:]6ax *= v%Ax strides_from_shape(ndim, ,Oize, layouoCalculate Da contiguous array. L9 is 'C' or 'F' (Fortran)!()=U ==U=X( Q) + [Aize]EM1i1Brang`-2, -1([0[i]L"+1OOelsev( +B:-1]] 01, -A_ca(3, sN"""Convert flat to the nestedGQation=m  CR with?H 's']_en(s))"[0w0lstd0] * s/A) // .(  F }@stard"i*WeUi] = e[,:+.A], s73lstfWjp o5O[i::f t def carray(items, shape): if listp) and not 0 in)Rprod(8s != len1FJraise ValueError("5!")|return _caM def farrafsindices*"""Generate all possible tuples of 7A."""`iterab= [range(v) for v]*CjUuct(*:)Egetindex(ndim,i, strides """Convert multi-dimensional0ex to thePitionAflat=qret = 0i+r-Tet +=P[i] *m)[i2rettranspose(src'_T  that is regarded as a matrix defined by: dest...[k][j]q= src[iuk]... f@,1srcm G)s a_from_# , 1, 'C'7d7k[::-1]= es [02srcW nd _fr = cJ+/to+1t@[to] Yrc[fr_sten(lsta3"""lM= []1lstif atompOhI[lst~y[0]) + 31:]X C or ggscalar2 # DSsliceNQlst,  1Gete0Qafter+Aing: esVa^'HuobjectsR O[Alst[Rs[0]])] +u4[0][b9e!M-   [7subtf ]m_assign(l>rlRes, r l slice assignment: llst and r re the operands, rlslices* re lists of  objects.WDmustJ2havdsame structure. !For a two-dimensional example, this is not ied in Python:J [0:3:2, 1] =[1:3:1, ]2Instead we writeLQs = [ (0,3,2),]1 r&0U1,3,100Qmulti4_assign(,#, ,W)i1"""if atomp(!):areturnCmc5, r]E[1:]a eIfor l, rk1zip[0[0];Clst[))# def cmp_d"""Compa<Wz]$].@lshape =_| r (U7(if (len(XP) != ?)!-1 bi_XrangeB32if W0[i]YU2[i]Z 9O== 010>0XF"""Rr after 2ingz=]i( <raise ValueError("lv  different"s"0?lsto # =2 #gRandomv7 # # PEP-3118fvery permissive with respect to-bcontena@@y_buR. In particular:^B - Fcan be zero-Sides any integer, including1aoffset0Apoin6locationLunderlyingj memory block, provided that it!a cple of6itemsize.The funcisjQis se3 teYpverify P in full generality. Avalid iff3fitiFe #  't' (short for 'tu^ple') is fully defined by: # # t = (memlen, itemsize, ndim, shape, strides, offset) # def verify_structureH: """VeI$ that the parameters represent a valid array withinAhe bounds ofCallocated memorylp char *mem: start5physical4d blockd<): length7o82: (y`)buf -e\1"""#ifa% %return False/c< 0 or=+ >b?lenD Wany(vr for v in )@+] <= 0(== 0 and notQtXI0us JRTrue (min = sum(`[j]*(s7a[j]-1)jL`range()<$if1[j]#Oimax_>B> 0)0r +i &ax#<=r@get_(lst, indicesiE lsalst[i] 2lstW#s_index(?3, tY@"""LL0ion!anjunderlyingDory.-VA = t3p =Ep +=3i]* pis_overlapping(0TheF@ 't'3, if at least one d%iopis visiwtwice while00rat# through all possible tuple$ J-R= 1<<bS nd0@#!i y6ory@! biTE1<= 95 anduRS el90/1`[0] * for i in,!ge >9[i]hQ, max"Vmq = len(&)z5tride = 5%dzero_s+1Tru4Rn & 1RFalsea3Gs = [ -1%*0-}8ot  ['=  `-2, -12 *=P[i+1]b (if CnU((1,-1)[Q2)] *?1K0imi<rimax = $0/Dsum(2j]*p[j]-1) j;;*6if C 0 != l - .<3 = +0+ (WK+1) . 8 (-! + 56Z?min ,,Q defslice_from_ len, listlene"""Create a<1om 40 of that fits intoFA.""" ara% -=""st4jbep = (Dn - start) // slicelen if else 1 step = randrange(1, max3+1)#o#vstart +F*=#" =(&`, stop"epD2_, tcontrol0_indices(s, listlen14if +!\Alen:nraise RuntimeErrorreturn s def_from_shape(ndim, )P"""Create two sets o.s for an array x with=! 'D'xJuch thataof(x[l~gs]) ==rA."""@) = [0] * +@n inga1[n]Hv  @l+1) al > 0 053[n]'FQ](blen, lo:ctuple(}2), S)_aligned_s(maxdim=53=16!(l3, r_o4) s8#y[]), where x isJGOx' and y- u':*4dim1minA = 2xn0"00if n >= 95<%el'0'W@all_Tom = True`000)k8oQFalse*;)}s*  ,, @smal0EL9bigA. 0if 1!< g3J,,-!## a_`fits the;er value.66if  r -J.Lv(1,-1)[O 2)1n2yj!s_ L+Q"_,UQom qC#@uZ$I)"ofame lengthNbigg s_dslice_from_slicelen(s , big) if randrange(2) == 0:%rshape[n], l =F{, small.hs/ = s_big, s_4Oelsep7p2y 5creturn", , tuple(l"$s)rB de% items_from_structure(fmt, t)B"""Rda list o:1om =U for < 't' with1mat 'fmtchar'."""rmemlen,Eeize, _2 = :Agen_m(6!//6A'#'+'numpy')|ndarray8!, 1t, flags=0> Q the P Qed byc4)andim, h,*ides, offsety(5=;B=strCpformat=Sb=ND_WRITABLE|0=_4+9/X0buf1ytej, v in enumerateR%.pack_intoqbuf, j*_vT c&(buffer=2Qdtype ) # =2 #jmemoryview castsu7_Texportery^8CNone"""InterpretyBraw y'JV' as Rxmasize 'ize'. If=n,\0new is assumed toGabe 1-DZE n *}6lenZB0giv3EusuaIconstraint contiguous qs prod()gapplies. On success, k)|sFcannot be met@>pa chunkzPbytesi$edNbas NaNQresul%Pfloatvversiongr'nan', h8adlen =  .nif shape:  if prod(shape) * itemsize != bytelen: *return None, 7Beliff == []5if exporter.ndim O0 ork(&se_n, r = divmod(,])e = [n]@if r0P+3Vmem = too"s(d >dmem[i:i+`ize] f in range(0, len(mem)!] h6G;v;c+ = struct.unpack(fmt, v)[0@!if3AX'nan'.s.append( )4s5%) !b else #4[0]& def gencast2s()"""GenerateNs to test -qing."""%nQ#32CUyieldvyd,B4, 61min@ = 13ran$100) > 802tX&@A, 5)_w) ' =O2, 4V_ # =2 #^aActualsu7/slices(n,all possible (a single dimension@Buct(-n, n+1),?ge()m_(q tuples''`iterabb= [genh2[n]n|n *KrL(n, allow_empty=False["omUT0 ofagth n.) If zero=True, thqmay be v, otherwise#dy willBqbe non-)minlen = 0Sn]w1G1D&2"1a_from_  9, nCsD!EG5v erations=5): 4 """Generate random slice tuples for 'shape'.""" # non-empty -s+@_ inHPge(itVaions): ;Ryield\!(r<(]A[n])lnAandim));# possibly w=, allow_X_=True rinvalid&R0,1,0H def rpermutation+ble, r=None1cpool =.O2bler = len(#) if r is <q else r7 Qample1a, r)) ndarray_print(ndz@"""P debugging 6tryx = nd.tolist(except (TypeError, NotIamentedu ESbytesFif isinstance(nd,9boffset TRflags &2 = 'unknown'%> 0"Q(%s, = btrides "ub] Lc "format='%s', itemsize'u=%s)" %@ (x.u u u", r,;p-n!, kr!sys.stdout.flush() ITERATIONS = 100 MAXDIM = 5 QSHAPE if SHORT_TESTi >A3E41genR0s_U3 = :`= @unittest.skipUnless(struct, '  module requiredQthis 9/')F3, '  objectH ') class TestBufferProtocol(0CasBsetUp(selfu# The sps need Sof(void *).IC.__p = get_.{averify|, result,9=-1i0e={1}, fmt+ readonly2`R-1, sC5"ls`;d=False, cast 1V! b{ contents agas expected values. Default# are delibely initialized to :Vtypes"if%w_len = prod*$)*L{ B`if noth : ray has been implicitly cast to unsigned bytes expected_len = len(lst)(else: # ndim = 0P Eitemsize )+# Reconstruct suboffsets from strides. Support for slicingCcould be added, but is currently only neededCtest_getbuf().J6= (if result.":6self.assertGreater(F, 0))00n in range(1,W)iDif shape[n] == 0"&Ybreak<U><>c0 += -44* (~/-1Vs = [Dq] + [-1|v#J-1)]## Not correct q has ocdEthe first dimensionjzof_void_peO0] try item1 = get_pointer(result,U 1525 ?(ls/ f isinstance(12, tupl`x = struct.pack(fmt, *=OelseONb.extend(xnexcept BufferErrorxbTrue # re-exporter does not provide full bT ]breakself.assertEqual_31, 0!ifq# test tos m*.2Y, b) t7X?hexTm = memoryview|th = "".join("%02x" % c cb3 !m.?, h)lst := expected multi-dimensional logical representationpflatten)Tplements}C-order6ff = fmt ifN 'B')] ed0 iyQRules&@'A':[Athe h is already contiguous, retur:unaltered. Otherwise9' aN> 'C@.1or %0['C', 'F>A']c"=  T&#ifW ==QK)6is_, 'A') or \d?? ;/C'3P# ForB@ing x!nd,@vert 3 # /ed0 tolBtran(As = Upose(a", w (K==C,mat=ff,N flags=ND_FORTRAN.V0: #f-tiguous(resu lt, 'F') and order == 'C': # The flattened list is already in C-O.H expected = ndarray(U, shape=, format=ff) Scontig = get_ uous(resuPyBUF_READ,)Gself.assertEqual(K.tobytes(), b:True(cmpD$, )pif ndim0?nuenmemb = lenLro = 0 if only else ND_WRITABLEd### See commenttest_py_buffer_to? anpKexplanation why these Rs are valid.0 To]*R'C', "FULL_RO2 ff2), {* itemsizeDinitlst = [struct.unpack_from(fmt, RO, n*K Pfor narange(/)]!if@[0])q1q*Av[0]vl]y* vlags=ro/mt5 ymemoryview(y), c#0/F'x? = 0F0k|ND_FORTRAN,9[TA[-A[M in'itlst = [struct.unpack_from(fmt, contig, n*itemsize)  for n in range(nmemb)]6if len(in[0]) == 1:-v*Pv[0] lvl/] ;f = ND_FORTRAN if is_ uous(result, 'F') else 0Hy = ndarray, shape=, flags=f|ro,mat=fmt4self.assertEqual(memoryview(y), &))#p_format)@:tryI?m =` +except BufferError: # re-exporter does not provide full in9ionPwZreturRex = B.objinstance2 aP@Is(mNJ, ex}%up.nbytes+pected_len5$, 3-, readonly, _`ndim, +atuple( )4!if(sliced and suboffsets`PstridWf h8h#, ;wPn = 12;0U+lsw l&Wm), nWV6reptolist()f2fmt`}1.to:(< h_rep, mdef verify_getbuf(Z, orig_ex22q, g=FalseAsimple_fmt(exB ex.A['' or%B'gSmatch(reqU(!& (# writable request to- f|D(ex.PyBUF_WRITABLE)) or<P# can4`SlicitDuity 7(/", cC_CONTIGUOUS)VGex.cT HFHfH?ANYJ # buffer needs suboffsets (not match(req, PyBUF_INDIRECT) and ex.>I) orBP# bufhwithout strides must be C-contiguou|rSTRIDES{Vex.c_CrSIMPLE| aFORMATkWRITAB  "ND $bY))): Gself.assertRaises(B Error, ndarray, ex, getbuf=req)DfreturnXif isinstance(:G  is_memoryview_format(ex. )):[Plst =vtolist(yJelse,Dnd =vRvFULL_ROAW_5nd._~,# The consumer may have requested default values or a NULL .Kro = 0 if ) readonly>#fmWitemsize Bndim 0if   R$# W refers to the original abeforeFcastgL equality product(shape) *F= len still holdsH @calc(6) =Jdoes _not_I HS%''  _ex.tobytes() # Issue 128342H+ND~E = 1:! =Dj@BG- verify(nd, obj=ex,E7*= , fmt=fmt, ?=ro=%=!, =,==lst=lst, sliced=)def test__(Ys = (# distinct flagZu$ND  CC_CONTIGUOUS.F8ANY compoundbeRECORD?_RO-D-CONTIG_RO,   ) # items and format_fmt = (5([True if x % 2 else Fa for x in range(12)], '?'),B 1,2,3,4,5,6,7,8,9,10,11,121b1B1(2**31-x)!(-0+x)&l'  # shape, strides, offse0structure0], [], 0?3,1 9-<-11W6S"r-8@3, 4;O-4, y02, [@[4, 4!E8c # ndarray creation flagsE!nd k0, ND_WRITABLE xFORTRAN |$TaND_PIL,8PIL(' that can actually be used asRreal_6= (0, PyBUFjFORMAT4$|3%)  , "in:%Q% iz.calcsize(fmt,U?:urea96r = [v *tQv<W]:g5 *=5 #EU3in : F$if(7C&ND_');continue!bif not$ Z?PILVW_ ~s.[03Tex1 =G(H,mat=fmt,=jIy== = 4Aex2 = ex1[::-2]ONonemmemoryview(ex1aoif ex2m I2I1.ndim == 0 or w1  self.assertEqual(m1, 2[?ex2w vssertEqual(m2, ex2) for req inouests:)<-Bbits.al_flag04self.verify_getbuf(ex1 1,s|Q)sC mB iff@, Gsliced=True </m29items = [1,2,3,4,5,6,7,8,9,10,11,12]># ND_GETBUF_FAILGex = ndarray(T, shape=[12], -==  assertRaises(BufferError,X8P# Req complex structure from a si exporter. In this"# particular case the test object is not PEP-3118lUiant.Eb8[9], [1] .", 0=PyJfSIMPLE0 IoWRITABK2/ND0STRIDESJ0C_CONTIGUOUO1FO;?ANYQ'nd+exI"# Issue #22445: New precise contiguity definitionp[ ,1j7,0,7],Porder, 0,zFORTRAN(  nON|ND_F C(is_@ous(F'F')+48C8F5wr+?^ Ond, <1def_^`_excep s()array([9], [S1]) ndm = ndarray([9], [1], flags=ND_VAREXPORT) 5 # Initialization of a newIv or mutn existing j.Lfor c in (, nd.push m %):/valid typesLself.assertRaises(TypeError, c, {1,2,3}5[57'3'97_(3,4)9!3], shape={"@[ trides={1!BMoffset=[format={ GF-agetbuf oND_FORTRAN is only without sa E= p )# ND_PIL ndim > 0'(=PIL"In"OitemGValu[ <X'XXX'A2, fk:"L"MMecombinC and;' struct.ej_[1000B v1,(2,3)O2}O!+2,!Q" {#3 0n =hMAX_NDIM+1:4]*n_[1]*nE% }_]-!>+sOverflowq{[2**1285q# prod(A) * yize != len( C,4,5e=[2,2], offset=3) # Invalid strides."self.assertRaises(ValueError, c, [1,2,3], shape=[ J=['1'])P OverflowSO91],@ =[2**128]combination ofB and 02,1 1foformat @,3,4~2 3@vO="L":_offse#I/=4 d kK3 #x" I?="" struct.eF(G)Pn>@#$Sping outthe memory boundsitems =,4,5,6,7,8,9,10]L AP-3, -52Con=consumer:  argument i 7Typbytearray(),R>="Q\ original base object: getbuf,[W U=PyBUF_FULLSkvs mandatOfor   %[C"# WRITABLE request to read-only providergcBuffer!nd, b'123',Qm# ND_VAREXPORT can zbe specified dur76ionSnd = x@([9]], flags=]snd.pushHM$Boper0s: PE/pop4 , assertRaises (BufferError, nd.push, [1]3) self.assertRaises:Eop) 0 # ND_VAREXPORT not set: ` /pop fail with exported bsDnd = ndarray([9(m = memoryview(nd+0 m.release(}9op('Single remaining$: %hdel ndget_pointerWCType3@, {}V,2,3]?`b'123'G  list(range(100)), shape=[1]*uOValund, [5]s2r?3,4 p /2,@+3c ~ -? Overflow0Q1<<64sA# to) needs format (ex1&33],0F='L'= ex, getbuf=PyBUF_SIMPLE. 2nd.#b_from_e?ex1 7ex266ex1 2j6nd. [[(1,)*200]gg}9 =MAX_NDIM "nNO1]*n  #)_contiguous D [, 1, 2, 3, 4, 5D$V"xyz", 'CI_2**64Is, nd, PyBUF_READ, 961)  self.assertRaises(UnicodeEnrror, get_contiguous, nd, PyBUFSNU'\u2007'r oValueEj? 'ZK*255, 'A') S# cmp( nd = ndarray([1], shape=[1]%>4TypW, 1, 2, 3, 4, 5@ {}u9 ){}#is: Z# CSr =3201def test__linked_list(W%):for perm inutations(range(5),m = [0]*5B CF,2,3G flags=ND_VAREXPORTAm[0] = memoryview(ndi1_"nd.push([1 q,?m[iu5F@[i]].release(s zcBuffer *opbdel nd format_scalarP# ndi20: "BCfmt,0, _ORiter_S+(0itemsize = struct.calcJ(fmt zJB(), b=7pverify(obj=None,e= P, fmtZ, readonly=1@ (=0strides=()6Blst==1xG%n]n = rand&10d+D(b(0, ND_PILR 5]", I6v5ize, fmt=fmt, readonly=1, ndim=1, shape=(nitems,), strides=(_ize,)J Alst=,!) r def test_ndarray_format_Yq(self):+ # 0 = | = randrange(1, 30)"for fmt, `, _ in rvpt-Pize =uct.calcsize(fmt^,b@stepY[-5, 5R*1if )F== 0continue)r = [lenz0[::N5])])J/#**offset =m*D-1) < 0 else 0Pflags(0, ND_PILSnd = a]Y R ===!, = 90 j.verify(nd, obj=NonewRfrbf%bjLtranc. 1,2,3,4,5,6,7,8,9,10,11,12;/exX(3, 4"){ ex, getbuf=PyBUF_F_CONTIGUOUS|VORMATA assertEqual(nd.tolist(), fNW)tmultidim  _4[v`2, 10)b;I Sprod(Lpermutations/:- c6 VM#ifr= 0 and3 =="A# C   c a/ Oa_from_(^_>'C'm ls5cJ/4 fmt=fmt, readonly=1,  Pndim=, shape=, strides=Ilst=lst) sif is_memoryview_format(fmt):2&# 2: reconstruct:ex = ndarray(items=E'ndE ex, getbuf=PyBUF_CONTIG_RO|FORMAT)Nself.assertTrue(nd.]o == ():!mv. _from_buffer(9sverify(mv, obj=None~7Dize= P, fmt3O, recLbg2Mk # Fortran  ,aflags=|ND_FORTRAN w('!, ize, 'F'qlst = f //nd -2 def test__index_invalid(g# not writable! 3[1]F=[1]OK Raises(TypeError, nd.__set.__, 1, 8;6(ndWQEqual!x/mvxP# canbe deleted!, =ND_WRITABLE5del8L u# overflow7O[gF<<649@E@I self.assertEqual(mv, nd) aself.a!Raises(IndexError, mv.__getitem__, 1<<64=s=U, 8) ~# formatis = [1,2,3,4,5,6,7,8]"nd = ndarray(/, shape=[len3)],Y="B", flags=ND_WRITABLE struct.eWnd.__o2, 300@ SValue@ >1, (100, 200)Emv = memoryview(4Typ = (1,2), (3,4O5,6)'/LQ { b'\x001'def test_ _iA_scalar(`!):)r"#  1/() 0"sxAp[()]; _Fx, 1,_...];,p.tolist%nd @/mvl?mv[l& 88 px0 s ;<z  )%mv)S ndO = 9 _95 k9!ndO = 5l 5l6 m5mnull_stridese(range(2*4))P[2, 4`T ex, getbuf=PyBUF_CONTIG `# Sub-s are only possible full exporters.BufferError, nd.__getitem__, 1) # Same for slices.self.assertRaises(BufferError, nd.__getiU?(3,5,1)) Fdef test_ndarray_index5psingle(h!):1## UPfmt, kps, _ in r_format(5?CSnd = t(5shape=[5],vmat=fmt7hi\range(-5, Z'Equal(nd[i]3[i]+/GIF*-6>5|if is_memoryview1rVmv = -:(nd$ mv )MTQ 3U*mv UBY with null strides'/ex lags=ND_WRITABLE 0ex,Obuf=PyBUF_CONTIG| kFORMAT4   6nd.q_from_b(n1Is(@eq__, NotImplemente 6'& = [1,2,3,4,5] 6_RO1Mj//]gSIMPLE7srassign e value%_?ite.t, flags=ND_WRITABLE) for i in range(5):*items[i] = single_ '/nd$ self.assertEqual(nd.tolist(), S9s) V2 Raises(IndexError, nd.__set:x__, -6, K5J if not is_memoryview_format(fmtAcontinuend = ndarray(s, shape=[5], R=fmt, flags=ND_Vmv = ?(ndz mv? % 7/mv /mv */mv 6 K  # assigns value: lobject = r 1`KDiterF *7_-5, 4 5+1] psWr+ZrVdef test_} _iV#_gKmultidim(_(2, 3, 5An' = prod(*wpermutations+:)_M1andc(j )`$`(0, ND_PILA# C rs` ls%cg  ,l3[0] ?[0]9 N`lst[i]4[i]P))   for j in range(-shape[1], 6): / self.assertEqual(lst[i][j], nd .tolist())Gk2/2]'[k][k]) # Fortran array qnd = ndc(items=", format=fmt,=aflags=|ND_FORTRAN~lst = fr<i<0<0<4 v6|[5Idef test_ _sequence(L 21.19 Raises(TypeError, eval, "1nd", locals@mv = memoryview(ndF\ mv!} )mv} _Riter_ '(5  5H=[5]A7h@i, v_enumerate "v,:[i]UY.QTrue(bD&fif is_f;fmt. /mvO/ 2#mv8lice_invalid = [1,2,3,4,5,6,7,8]C # rvalue is not an exporterJ/xl? [8ND_WRITABLEm:6(xlxl.__setP__, ss(0,8,1)JmJ _ full9/exM%xr = ndarray(ex, getbuf=PyBUF_ND) 2self.assertRaises(BufferError, xl.__setitem__, slice(0,8,1), xr) J# zero stepnd = ndarray(Ds, shape=[8], format="L", flags=ND_WRITABLEmv = memoryview(ndSValuennd.__gO1,0)D/mvD ?2,4+e6(1/0) \n&0)D|n ?Typ_"@%$" <(=3 I9{}): not implemented0FNotI) ? 3 m 2 di&3ing/xlB /xrFbmyq6(xl mOrB_[7:8]MEqual(xl.tolist(), -|zm{z/mrz mz&# 5ize3yt'Indim ndarray(ite#ms, shape=[2, 4], format="b", flags=ND_WRITABLE) xr = ndarray(iteI8F3ml = memoryview(xlOrself.assertRaises(ValueError, xl.__set __, slice(0,1,1), xr[7:8]M Equal(xl.tolist(), [[1,2,3, [5,6,7,8]>NotImplementedm CJm$# differingxN2! sAzAmAz# _testbu.c module functions)W4Typp_indiceo2), {} F&"#O", 1F 0u0), 4) x"?PIL x.add_suboffsetsxey&B"k2`ex, ge=PyBUF_SIMP @def __FQzero_(V%):=I4 = ,,9,10,11,12]k'12L y F9[4:4] = y[9:9]&xf `my c_ml, x @$ml/mr  <R3R~&I4, 3x[1:2, 2:2?3:3 .tolist(), carray(items, [3, 4])) def test_nd&_slice_multidim(self):+/shape_t = (2, 3, 5)ndim = len('}~ = prodAfor 4 in permutations+:Qfmt, T, _ = rand!(nz. ize = struct.calcsize(fmt )Pflags(0, ND_PIL&Snd = 8^=, format=S= J lsSc J ,r _}(,I)1:listerr = None6tryo"a(lst, s9except Eion as ede.__class__V/nd)!nd1nd[ /s]2if ,3or .assertIs(8,6y/lshPdEqual(0.to#()d-redundant_suboffsets96, 2<H.add@ /exk 9Y mv = memoryview(ex@'j Kfv if nderr or listerr:  self.assertIs(4,2)2OelseHEqual(ndsliced.toB(), !) Wdef test_ndarray__assign_single()qfor fmt, items, _ in r_format(5-1lY*1gen s(,r ,0Pflags/(0, ND_PIL):# Af = 3|ND_WRITABLE *Snd = (shape=[5], =U.=fH/exL7mv = memoryview(exi l| = Nonediff_structure. Plst =_ms[:]U6try; lval = lst[%L/r/(/ We6 @len(P) !=  pcept Exion as e.__class__# {$nds[ e:if z4: #| cannot change uQ TValueError_W[ga?lst] ?Mfot is_r;fmtthcontinueS mv# S'mvS/mvSAS'AV,$, Vor)  kelse:  self.assertEqual(mv.tolist(), lst)?O, nd5Is(mverrk?err9verify(mv, obj=ex, itemsize=nd. , fmt=fmt, readonly=0I @ndimEa, shapT , strides! P 0lst.o!) def test_ndarray_slice_assign_multidim()_t = (2, 3, 5Ks = len('~ = prod2for in permutations+:UST, _ = rand!(n/or flags`(0, ND_PIL*_&range(ITERATIONS,4l7Bs, r  a_from_ ( FSnd = (0=Br, formaN5=|ND_WRITABLE: lsc {err = None6try6l Presulsg,yA(lstZexcept Eion as eze.__class__[/nd)3nd[][ ].2if ,3or 1Is(8,6} P'nda o~# construc of valid sZN(0fmtfmtdict['@']"Pize =uct.calcC(fmt4t_2ureWize, True, maxoMAXDIM X1max =MAXSHAPsf(>*t) ifmt, t)  x = ndarray_from_structure(items, fmt, t) 2xlist = x.to =() $mv = memoryview(xGfif is_$_format(fmt):Q} mvoYv{ self.assertEqual(:!, if t[2] > 0{a# ndim  test against suboffsets representation.yv, flags=ND_PIL=yy !, ? [ y]/, b0-]'if numpy_ shape = t[3]if 0 in )Dcontinue # http://projects.scipy.org//ticket/1910rzI*verify(x, obj=None,o1dize=z. -=1readonly=0JT0=z.,<1=z.D, strides OUlst=z 1def_random_invalid(pp# exceps during consion of ; 2s0Pfor _range(ITERATIONS_D(0fmt*fmtdict['@']7^ =uct.calcsize%v  ize, False, maxdim=MAXDIMT 24^SHAPE Eqg(X>*t)70 =  Rt<rnderr =>tryN'$ E_ as eee.__class__1QTrue(41_ try:  y = numpy_array_from_structure(items, fmt, t) Cexcept Eion as e:+?merr = e.__class__ 1if 0: # http://projects.scipy.org/O/ticket/1910Hyself.assertTrue(:R_err)|def test_nd @rand lice_assign(E)# valid s$ $Uments for _ in range(ITERATIONSF(0fmt*fmtdict['@']k%bize = .calcsize(fmt)lshape, rlsUs = \5_aligned_5(maxdim=MAXDIM, maxV^SHAPE#@tl =dVPize, ", DB+ BBgverifyO*tl)7"r7l VOlrr/;xi yxd==r3xl[U] = xr[r.]W`xllist%@l.to (Or%r% Kmmemoryview(xm$vEqual(m", 61, xif tl[2] > 0 and tr`# ndim.: against suboffsets representation.)Hy- , flags=ND_PILOXO .O @y@}DyF = y) 1, yk5o1, y y(by( yllist)  self.assertEqual(mr.tolist(), yr :) 5 if numpy_array: 0if 0 in lshape orr37continue # http://projects.scipy.org/}/ticket/1910LHzl =_from_structure(litems, fmt, tl)/zrE rErEl[lslices] = zr[r` ot is_overlapping(tl) and n/r)S0# S{ assignment of Z sL# is undefinedoNumPy.1[verify(xl, obj=None,2gUtize=zl. =readonly=0O@ndimK!,  Bqstrides6 P, lst1) r ?=zr-G/r.#r. .def test_nd_re_export( = [1,2,3,4,5,6,7,8,9,10,11,12] ndT(;[3,4], flags=ND_PIL'ex7#ndTrue(ex.C< & E% Is)Pobj, NI"Gex.suboffsets, (0, -1)1AFals!c__guous* f*Rx Qzero_  # s @2foro1  ]0u`mv = memoryview(j =n*mv%'nd*[]sS .] O,3,3 m m?3,0mf.assertEqual(nd.tolist(), [[], W]) nd = ndarray([1,2,3], shape=[3,3,0], flags=)>self.assertEquaw *s [ def test__zero_strides(%):s #  2for in (0, ND_PIL9 5 q/=[ mv = memoryview(nd9 Omv, % 61, ]`8?, 1aloffset[ brange(20)):2], ?&=7 /&/, ' _7,8,9u_from_buffer  3 m].v m get_pointfCiH3Exnd[i], nd, [i]) __null!exg T2,2,56 !exbuf=PyBUF_ND| fFORMAT  %exgk?(exOmA., N cmp_contig0vgFalse(,b"123", b"456"}6L(12',4py~ 274,32 Ox, y [1 format="B"Q9Trux, b'\x01')0-4, xdMhashyAa = .c('L', \y aRaises(ValueError, q# one-dimensional   b = bytes(list(range(12))) " nd = ndarray', shape=[12])2 self.assertEqual(hash(nd), b_# C-contiguousDv?3,4w%`/2,(Fortran y"_spose\V4,3])^4], flags=ND_FORTRANE02,33j66# suboffsetR X2,2,3]6PILY`# non-g forma7=O='L'Pnd.to{%s(def test_py_buffer_to_(&): # The requests are used in _IE?.c:Q# to generate 7s without full in$0ion.Eing.D5= (# distinct PyBUF_INDIRECT, tSTRIDES$ND ySIMPLE,C# compound  SDFULLF :_ROG'eRECORDz-D-dCONTIG + interfaceRaises(TypeError, , {}, 'F' scalar, read-onlyk 290(),.wmat="L"bWRITABLE2for orderB['C'e 'A']:g*n, s%)tB(nd,oA<iJ9b, Pzerosray([1], shape=[0], format="L", flags=ND_WRITABLE) for order in ['C', 'FEA']:&-*prequest, s%)b = py_buffer_to_contiguous(nd,o#, A< self.assertEqual(b, b'') nd = ndarray(list(range(8)), shaz2, 0, 7 Bh### One-dimensional ,s are trivial, since Fortran and C'J3he same.:# oc5)f#[0, ND_FORTRANO 5[1] h/f|qndbytes1.to (WQ. --D* 6f, 2, 3< <b< f, non-e inputh 2strides=[ Cm*[PyBUF_STRIDES, KFULLj8-6g[::-1]L> >try1except B_ErrorhX5nue}H5###:_Multi} ### " ### The goal here is to preserve the logical rentation of# Kinput array but changEOphysFif necessary.M  _testbuffer example:!=! 'C KI - < >>> nd = ndp(list(r(12)), shape=[3, 4])B1.to:"[[0, 1, 2, 3],C [4, 5, 6, 7!p8, 9, 1I81]]D Fortran output ->2py__to_contiguous(nd, 'F', PyBUF_FULL_ROY b'\x00\x04\x08\x01\x05\t\x02\x06\n\x03\x07\x0b' return value correspondCthis L forC{$'s   [0,4,8,1,5,9,2,6,10,3,7,11] 4flags=ND_FORTRAN=/ndTw~='^he same,"` memory are now5in Order/_NumPy) cp takes !5initializ `Here's# sequence in D  $V 0Q=byte~ )Uf, dtype='B'`[[ 0, |P[ 4, +88, Yuint8 O)f:.tostring(o?='F-; ? 8= ndarray(buffer=fortran_buf, shape=[3, 4], 3### dtype='B', order='F')9 >o>>> ndarray([[ 0, 1, 2, 3 [ 4, 5, 6, 7+ 8, 9, 10, 11]], Zuint8 multi-dimensional, contiguous input.lst = list(range(12)Y for f in [0, ND_FORTRAN]:@ rnd = nd ;lst flags=f|ND_WRITABLEcAif numpy_C ] naa"1(buAbyte3V(lst)4 ,L  :*C' if f == 0 else = @# 'C' requesiV;J0: #B0 to5 G1xYPspose, [4, 3])l BF'pexpecte@x.toa*s(9/nd:NT sM>try`b = pyvfer_to_@(nd,D,z >except Bu=_ErrorfUMnue Nself.assertEqual(b, )/# Check that output can be used as the basis constructing}a# a C Ris logically ident LV/.LyY![v|v+b]Q5 memoryview(y), ?nd)(  eb, na.tostring( aam i C':9'F'${ w  _b? = ~$[PyBUF_FULL, 4_ROINDIRECT ;tSTRIDES;+NDAe= py_buffer_to_contiguous(nd, 'F', request) except BufferError:$3U=nueself.assertEqual(b, expected) /.# Check that output can be used as the basis for constructingNa Fortran arrayXis logically ident 1 to\ inu/.Ray = nd1([v$v in b], shape=[3, 4], flags=ND_FORTRAN|ND_WRITABLEh 'memoryview(y), ?nd)9if numpy_ e b, na.tostring(order='F'aT# 'A'% if f == {x4?lst)1 = x.tobytes(ENelse{9/nd:F[PyBUF_FULL, 4_ROINDIRECT, ;tSTRIDES;>ND]>tryKb = py_bu}_A: 0R>Rwith f #/fA # multi-dimensional, non- <(ndist(range(12))'7PIL*U# 'C']$C'86_RO*  o #`9 Faspose(PsG4, 3_WRITABLE)  self.assertEqual(b, x.tobytes()) ': y = ndarray([v for v in b], shape=[3, 4], flags=ND_FORTRAN|ND_WRITABLE)P ymemoryview(y), Und)) 9U# 'A'b = py_buffer_to_contiguous(nd,,, PyBUF_FULL_RO _b, nd4W3def test_struction(&):aitems_ = [(9, []), ([1,2,3], [3list(range(2*3*5)), [2,3,5])]P# NumPy style, C-a:y O# From PEP-3118 compliant exporterZ0'ex|Wg=-8m =<*ex/True(m.cP3,]v0ndiyOlen(strides = R_from(;, 1, 'C'rlst = c{ verify(m, obj=ex,J ize=1, fmt='B', readonly=19=,=A{lst=lst *m2m% 21PyMPView_!Bd(): no] 'ndex, getbuf=CONTIG_RO|oFORMAT64nd. 96nd.{(Y ONone cformatWSIMPLb i',{,+rtEqual(nd.strides, ()) m = nd.memoryview_from_buffer() -lst = [items] if ndim == 0 else  2 self.verify(m, obj=None,%C ize=1, fmt='B', readonly=195shape=[ex.nbytes], s_=(1,)Awlst=lst# NumPy style, Fortran contiguous:2for!, 2 in_:H# From PEP-3118 compliant exporterZ!exaarray(eg=^, flags=ND_FORTRAN:(exassertTrue(m.f_, *q = len( I$ =x*(;, 1, 'F'>f /ex[}&zz}( Vm2 = *(m% 2}R# PILye O[1:]iV:PILnIec?ex.# # Invalid number of argumentNRaises(TypeError,, b'9', 'x# Not a buffer provider3: self.assertRaises(TypeError, memoryview, {})5# Non-compliant buffer provider^ex = ndarray([1,2,3], shape=[3]R'nd)ex, getbuf=PyBUF_SIMPLE.B&nd7e CONTIG_RO|ufFORMAT>u-ndim > 64 u[1]*128format='L' OValu66nd.b_from_wget_contiguous, nd, DREAD, 'CKFK(o[::-1]def test_ cast_zero_(I) # Casts are undefined ifis multidimensional andu # =Pains ks. These 6]regarded as C-/l7 byGQNumpya"PyU_GetC(), so theynot caughtH1the F forocity in_5().~items = C<<Q([0,3B[3,0 U 8[L-True(ex.c -cmsrc =:(ex"O@src.G, 'ch# Mono`empty b can be 7 (issue #19014@(fmt, _, _,Riter_V(1, ''-'b'#mO(fmtEqual(m.tobytes3 N"/@list.A[]) check_sizeof = support.)y7 p<L `qv9"npalcvobj%base_struct = 'Pnin 2P2n2i5P P'(@per_b= '3n'e1 = range(8)R((A!, (|c+ 1 * fAa lp[2, 4],?"b"v*a)ttruct + 2 * per_dim)) a = ndarray(items, shape=[2, ], format="b"8check(memoryview(a), vsize(base_struct + 3 * wxdef test_?0_module(self): .class INT(object):Q__init__<[, val%)X`.val =!DC>treturn E /DXO3dex!Sf(): 7values = [_9), IDX(9),= 2.2+3j, Decimal("-21.1"), 12.2, Fraction(5, 2B[1,2,3], {4,5,6}, {7:8}, (), (9,5True, False, NontImplementedb'a', b'abc2yteH), b?bc'yCBr rf, lambda x: x]afor fmt, _0 in"r_[f(10, ''/ex&10fflags=ND_WRITABLE/ndK6Fm = F(ex)k.pack_into(Rnd, 0  `m[0] =m_oassertEqual(){, nd[0]r[3 = }@calc| o`if 'P':fmtOcontinuev467wa_err = Y>try7;/:, v7dexcept_error` m/ T#mv'm0m[1v2`(TypeE0, Vw o) as eAe.__.__#if2or 7SObIsNot( ;]c 7d3?elsI!1]1 cast_zero*Aides(# Casts are undefined if strides contains zeros. These arrays are -# (sometimes!) regarded as C-contiguous by Numpy, but not byEPyBuffer_GetC65().$qex = nd([1,2,3], shape=[ trides=[0])6self.assertFalse(ex.c_*msrc = memoryview(exHRaises(TypeError, ;.cast, 'c') ~def test_R_$_invalid(S!):,L## u format for sfmt in NON_BYTE_FORMAT>Bs9 = '@' +5f randrange(2) else`;size = struct.calc(S-d-d9 ?W 1 'Rlist(F32))/@2//sZ#],n=Q"h  , [32//d.DX, sitems, _Riter_F'(113 61*mt+_!if(isJ 3;OValu\D,"C b  ;"DbytevT) andV9GX Ek/_hH6'h'&d&d& tbB2*2*BjB2,2, t >%=[nhn 7120^G,4,5JmVwcorrect number of args# >N-, 1, 2, 3ACdestF typ .cast, {})   # incorrect dest format  self.assertRaises(ValueError, m.cast, "X")3@4"EY") j# not implemented&/=B/!L4/l4/BI4x5:S# src_ex = ndarray([(1,2), (3,4)], shape=[2],G8="Im = memoryview(exG FNotI__getitem__, 0A"sA?, 8D itolistYU type[ 6;(range(120))81,2,3,4,5]3=Typ$B"`/{} eKso2*3*4*&Overflowcg[2**64B/-1?*_,6,7,K80  [I'x']pN-D -> O [9b _ in 3*5*7*11)]x3,5,7,1F.I with ndim > 64'nd O8O&28?'I'U&nd]'I', [1]*128zQ->lenAa multiple of ?siz @ self*.assertRaises(TypeError, m.cast, "I", shape=[2,3,4,5]) # product($) * itemsize != buffer 3 ex = ndarray(list([9 for _ in range(3*5*7*11)])~%])Km = memoryview(exOselfB&overflow,ndF128)P128],vmat='I'*m1&nd\!B\2\if sys.max == 2**63-1:P 1.I'B',7; @[7, 3, 127, 337, 927g649657;zEValu{`2**20,13z2Iz 1zOelse|E1, 214748364hKS5ufqr3~xdef test_;_(j){bytespec = (90 ( lambda ex: Qex.to2H()))X('b',0[x-256 if x >  x xR]ScSzchr(x), 'latin-1')Titer_roundtrip(ex, m,W, fmt&2src= struct.cal(,< fmt, to_ q:`^mq(' X%Xlst =U ".verify(m2, obj=ex& !=1=, readonly=0A @ndim=&S=[31*4 ],4ides=(1, Plst=lW=True! m37 self.assertEqual(m3, ex) lst = ex.tolist("self.verifyF}obj=ex,JYitemsize=src, fmt=fmt, readonly=0C ndim=1, shape=[31], strides=(W)D lst=lst, cast=True) #` from mt = 0 to 1)m =quct.calF('I'0ex = ndarray(9], format=.Adest& , ! =_(ex, 'B', 1dm = memoryview( m2.7('B ?2,  z11n=/1,1x10HlD[9]*9Q #I'5ize[]Hd'=[>"'Z0'())&.: roundtrip to/Ubytes0for@#, v@_ in "r_Za(31, 'M5'):7m(H)ZUiter_m9fmtX5n(0xflags=ND_WRITABLEAdef test__p_1D_ND(# Cast between C-contiguous buffers. At le'3oneU must# be 1D, a** 'c', 'b' orU.>\!_t`V0gen's(,@char)fmtdict['@']s*0tfmW ('v@')[randrange(2)] + G2tN .n = prod(A) * B $ obj = 'memoryview' if is_byte_format(tfmt) else 'kfmt' for fmt, items, _ in rF n,n-)::Isize = struct.calc(y00hap10[n]Rn > 0/[]1#ts2_ 0+ [c/] /ex = ndarray(B=", =Fm = VO(ex)it]q= cast_P(ex, |0, t!, |=+P2if S is Noneptelf.assertRaises(TypeError, m.>)+Kcontinue!== 'nan'Ip # NaNsDlists are a recipe} trouble.W# 1D -> ND'nd0 ^k m2(# B-0ndiDlen(@ qstrides. 2lst% to((vsverify(m2O=ex,RCize=@fmt=, readonly=1F= !,=Jlst=lst,%_=True1# N1 m324&i0 = &_ = ex5ex. 3 ^*I 4if ctypes(#mat: "T{>l:x:>d:y:}"class BEPoint(H .BigEndianStructure):  _fields_ = [("x", ctypes.c_long), ("ydouble)] Gpoint = BEP (100, 200.1)(m1 = memoryview(8 #2#1.cast('B' self.assertEqual(m2.obj, J,itemsize, -readonly, 0OndimVpshape, nbytes,)^strides, (1/uboffset29)) 6x =J(1.2 x c Fudef test_#_tolist(+&):s# Most )7s are in -.verify() etc.9a = array.a('h', crange(-6, 6)ma g /,  .5, a V[2::3_ y>e"nd 2*3*5*7*11)),  =[11,2,7,3,5], format='L2eE, ex  `[(2, 5u7, 11)]2/lhRaises(NotImplementedError, mb'12345'16"s"3+p"a",b"bcde&f"62,3/'s1IDreprJ 9r0.__A6__([[True(r.startswith(" getitem__, 0(1,2,3)?iiiNotImplemented;,# rangeQlist( 6(7)7qlags=ND_WRITABLEh_; V2**64X< w'2.909#R/-8 98<# multi-dim%al K'12?3,42\qm[0, 0]G%2%%31'&o-1, -1(@3, -zF(: with self.assert_out_of_bounds_error(dim=1): m[index, 0]Afor  in (4, -5:Owiths29~Bm[0,`sRaises(IE , m.__getitem__, (2**64, 0))A10, D?)) BOType00,  ? .>.# Not implemented: multidimensional sub-views6FNotIE B0:def test_memory_assign(&):a# ndim = 0+ex = ndarray(12.5, shape=[], format='f', flags=ND_WRITABLER}7(ex[()] = 22.5t*pEqual(m&,%;1...<3<63.5<b s34.7N# read-only (list(range(7))2&7]D2, 1w_ I6, 9?2=0=1rout of #o-8, 20 <5pack_single() success0fmtfmtdict['@']!0if $== 'c' or*?')-continue u[1,2,3] ?fmt8 Li = rand+V-3, 3M!0m[i8Zi], 8;&Wex[i]v b'1', b'2/3'I'c', E) m = memoryview(ex) m[2] = b'9'self.assertEqual(%,$%) & ex = ndarray([True, False, ], shape=[3], format='?',Aflags=ND_WRITABLE 1pW"1] # pack_single() exceptions:J(ndFb'x'SOc', &ndRaises(TypeError, m.__setitem__, 0, 100 list(range(120))~1,2,3,4,5e1f for fmt, _b0 indict['@'].6s():if (fmt == '?'): # PyObject_IsP() acws anythingsBcontinue ifZ c'Y special case tested abov7P m2`1.cast3lo, hi =2d' '*f' I-2**1024, TQ!= 'PPyLong_AsVoidPtr8negative numbersItbEValuc2dJlo-1GFZ"xyz"G'hi# invalid m 6'c'so`b'\xff'x not implemented|O"xL".FNotI8 [b'12345/"sk# multi-dimensionalw2x03,4z!0,]%42u`ex[0][ &42{bm[-1,-=3= !2]&43=0# e}Pindexwk(3, -4jWwith _out_of_bounds_error(dim=1): m[index, 0] = 0 Afor  in (4, -5>with self.assert_out_of_bounds_errw29Bm[0,` wPRaises(IEM , m.__setitem__, (2**64, 0)D10, GDEOType00, CB .A.# Not implemented: multidimensional sub-views6zFNotIE0, [2, 3]) Jdef test_memorycp_slice(`"):&-ex = ndarray(list(range(12)), shape=[12], flags=ND_WRITABLE)kEFm = j3(ex# zero step0z*HValug*f0,2,0)sCmC, Bbyte i[1,2])`0-dim King (identity function (o,)Nb](; e(1[ vv$/,  qinvalidue tuplei ! /{} H A?{})& rvp is not an exporter 1,$[1]# non-contiguousN`assignrd0, ND_PIL?ex1strides=[-1], offset=115 |?ex2024)4AQm@x1) m2 = memoryview(ex2) ex1[2:5] = m!m2) ?self.assertEqual(m1,I)E&2&1:3][::-1P2[0:2)1]R9m1[*m) *|,Q4:1:-4 /.?def test_p_array( &):*0cmp-( case, a, b, m, singleitem):for i, _ in enumerate(a&bai = a[imm Wjai, miVG\' = "'ifj != ai% x#NoNa, my2 b2OelsezIw/ta M++-ai&miOnLrange(1, 5K"Pfmt, s7iter_format(n, ''CG`lslice71gen ?s(n,0r$0 1ao.('0b4 mbW NOm, a/.tolist(), a ATbytesB Clen(m), /a)z!_err = Nonehave_resize+ ?tryul[)'a"a[+ a[lslice] = a[r / have_resize = len(al) ! /r)=except Eion as e:/ array_err = e.__class__ 5m-ONone%?tryw &m[m 7if t: # memoryview cannot change shapRself.assertIs(, ValueErro Alif 0E or I n<+/ls ZEqual(m, aQ 3.tolist(), a E TbytesF G cmptest(, a, b, m, singleitem)@def )__compare_special_casesJ"):6a?.p('L', [1, 2, 3]b(#7]Q# Ordering isons rai7v =(wbfQttr in ('__lt__', e gg)xGgetattr(v, )(w), NotImplemented}?a?v?]# Released s0e e to themselves'2v.rP(Ov, v5Not"|A"aD Ww kOv, w w# Operand does iP buffer protocolYv e# NaNsrnd = ndH[(0, 0)],m=[1], format='l x d x', flags=ND_WRITABLE@nd[0o0(-1(oat('nan')#(nd), nd Depends on issue #15625:/ struct module does not understand 'u'. a = array.('u', 'xyz')$v = memoryview(a self.assertNotEqual(a, v" ev, a) _ # Some ctypes format strings are unknown to theuct module#ifC:Z#R: "T{>l:x:>l:y:}"&class BEPoint(.BigEndianStructure)\`_fields_ = [("x",.c_long), ("y]~pv% =100, 200Gj5 "b"bH&P'TRaises(NotImplementedError, a.tolist def test__compare_ndim_zero(\&):Rnd1 = nd1729, shape=[],G='@L?nd23L', flags=ND_WRITABLE< )6nd1w6nd2GDOv, wwc>_ ?nd2B 9w, 1nd1"False(v.__ne__(w)&w&#v)0w[()] = 1728bl("+"v$1$4$7/eq7& 7'ndE(range(12)) 12 v|ND_PIL/exL7m'ex8m1m[9 /00  6$#&0: e !("1.2, b'12345'1/o='Lf5s4FhF,^> self.assertEqual(v, w) self.asserOw, vov, nd2!?nd2B wB1B 1# struct module: not e#-nd1 = ndarray((1729, 1.2, b'12345'), shape=[], format='Lf5s'8nd2F-GhG,[flags=ND_WRITABLEpv = memoryview(ndwu#No""$$$"nd&  !f12) xdef test_P_compare_ndim_one(C"):1x# contiguousF K0[-5K576, -625, 6 E729]R5S/@hQLK, YBE Hwk,,/Onon-72-3-* Lynd1FA@8E@h',flags=ND_PIL, struct module-"Wh 0cF,?> def test_B_compare_zero_(&):; # Bs inp900, 96I7=[0 ;-<W< w2E!Bc ; lS@??= hK >~G i  _strides(selcf): # zero stridesnd1 = ndarray([900,  ], shape=[4], format='@L')D2D 5t7=[0BAv = memoryview(nd1]w&2)self.assertEqual(v, > !w!2_ !B! BBw y,uct moduleD (O)]*4? Li@ >W!L hLƖdef test_m_compare_random_ s( ?! single character nativeYU = 101for4 in fmtdict['@m']:#fmt, items,j 0 = ~ fs(n, 'q', '@',\Kor flagss(0, ND_PIL)q*'nde4nQ= nHm#W m.Hi[::-3]#j1#T3om en_Drange(100C7   DW multidim_c C-contiguous, different valuRlist(-15, 15))v3, 2, 5('@'(ndJ_0, 30Ho:nd1) self.assertEqual(w, nd2) !#No$v$H1H5w) k # C-contiguous, different values, struct module82nd1 = ndarray([(0, 1, 2)]*30, shape=[3, 2, 5], format='=f q xxL')J2JO-1.2Mg< f 2QKv = memoryview(nd w2qn> !k}wYlist(range(30))J2, 3LR(ndDDH%21G3, 7Eo! b B E GG7, 3Gk= Qx lS1Dls+ !+L 4v, def test_ _compare_multidim_fortran(():F  w-15, 15%5=E@h',Jflags=ND_FORTRAN) nd2 = ,ndarray(list(range(0, 30)), shape=[5, 2, 3], format='@h', flags=ND_FORTRAN)(v = memoryview(nd1w52) 9self.assertEqual(v, > !w!2_!(NoE$ HHw&# Fortran-contiguous, different values, struct modulednd1 = [(2**64-1, -1)]*6 ?=Qq 9nd2mhqm /qQm Rw-15, 157, 5l q 3q- /0l>? nd2 = ndar%ray(list(range(30)), shape=[5, 2, 3], format='@b', flags=ND_FORTRAN)(v = memoryview(nd1w52) 9self.assertEqual(v, > !w!2_ !B! BBwdef test_ _compare_multidim_mixed(G&):!#  C/Fortran contiguouswlst1 = -15, 15)plst2 = C`spose(5A, [3&5]* ndMAndar5st1-(l':c:2:Ol',  , struct module[(-3.3, -22, b'x')]*30&[5] = (-2.2($e=_d b c%_d h cdifferent values, non-h)ex48 IWBex1[3:1:-1, ::-2] exBb aAex2[1:3:`cs(Nof$i$:v, Osame p[(2**31- 0)]*W11, 2?=ii&k>kHassertEqual(v, nd1) self.assertEqual(w!2!B! Bc ev, w) # different shapeex1 = ndarray(list(range(30)),-=[2, 3, 5], format='b' ndDex1[1:3:, ::-2]b?nd2bO3, 2b D?ex2bv = memoryview(}w2 yX y#NoE$ HiH , struct modul/BkY[(2, b'123')]*3052/3s$eiedef test__compare_multidim_zero_(():Bs inJh 0iD h5, 0, H@Eq nd1 = ndarray(list(range(30)), shape=[0, 3, 2], format='i') nd2 = ndarray(liDJ5, 0D@Ev = memoryview(nd1aw52) ~self.assertEqual(v, > !w!2_!(NoE$ HHwdef test__compare_multidim_zero_strides(Q&): #  7nd1[900]*80w4, 5, 4/@L>;t G0, 0NMs!!Ov, w'1.toE), w  ,uct module(1, 2)]*1G2, 5q?=lQ?< L   flags=ND_PIL|ND_WRITABLE)  ex2[2][7] = (1, -2Qnd2 ="1:3:1, ::-2] <v = memoryview(nd1<w&2)9self.assertEqual(v, > !w! !B! BBw# suboffsets, different shapeex1 = ndarray(list(range(30)),-=[2, 3, 5], format='b',DO ndh@ex1[2"  L3, 2b bs(No0$$?v, , struct modulp[(2**8-Jo1)]*40B$2:U ex?Bb'fss 5 2 Oi', ! p/@Iq6gs2!!b'hello', b'', %2733_5s0sP ]2] = (b'sushi', b'', 1) nd1 = ex1[1:3:, ::-2]  ex2 = ndarray([(b'hello',I]*27, shape=[3, ], format='5s0sP',Pv flags=ND_PIL|ND_WRITABLE0][2 = (b'sushiZ nd?ex2v = memoryview(ndw&2)self.assertEqual(v, > !w!2!(NoE$ HHw# initialize mixed C/Fortran + suboffsets70lstlist(range(-15, 15)0lst\E`spose(5 , V2, 5]*N/'-X@l', HqH2d H GpFORTRANN6PILRsB", struct modulebsashim sliced', 20.05)]*303B[11]TQramenTspicy', 9.45=Y< 10p 9p  0>Plf)def test__compare_not_e#&):# items not " for byteorder in ['=', '<>E!']:/>x 2**63]*12005,2bF+'Q'PNyN,T SO  YC3][1I = 1ax?by 9;a, A #?b, F=Oa, bl&L sel f.assertNotEqual(b, x)  x = ndarray([(2**63, 2**3115)]*120, shape=[3,5,2)],HS format=byteorder+'QLH')0yxV, flags=ND_WRITABLE|ND_FORTRAN[2][3][1p = (1,  )a = memoryview(xby4selaB #?b, FOa, bl&L,def test__check_released(&):[ U.('d', [1.V.2, 3.3]m1a#m.d(/Q# PyM~View_FromObject(9Raises(ValueError,6, m5#O.casQ/G, 'c# getbufferOtoli1 tos#m.2Psequence} eval, "1.0 in m", locals()UubscriptVm.__getitem__, 0LassignmenMsM7, 1for attr('obj', 'nI readonly @size  _ndim'A'j&qstrides uboffsetc_contiguousGf%' '3%):Tv XPibute] # richcompar /m12b{Mfm1, m2'm1Bi6 9$#}*7=0# Many implicitns are alNyjnverify().lt-529, 576, -625, 676, -729) nd = ndarray(t, shape=[5], format='@h')0m = memoryview(ndself.assertEqual(m, .tobytes()*5[t]1o>hQiLlw; _ in range(12)W2,2,3=0!5,E,2],K6<m# Unknownmats are handled: { purely depends on itemsize.if ctypes:#\: "T{>l:x:>l:y:}"&class BEPoint(H.BigEndianStructure)\`_fields_ = [("x",.c_long), ("y]~pv% =100, 200ja5 " a", 7def test_0_get_contiguous(T# Many implicit>palreadyS4.verify().# no buffer interface 6Raises(TypeError, , {}, PyBUF_READ, 'F'+# writable request to -only objectzB|Db'x'~WRITE, 'CFnon-Y p[1, 2, 2trides=[2]6 ,ndAwscalar,-BGfromexporterF 99q6"L"qfor ord Q ['C'j, 'A']f (I\$ [(I~/#  j", flags=ND_WRITABLCE) for order in ['C', 'FEA']:&-m = get_contiguous(nd, PyBUF_READ,I\6self.assertEqual(m, nd$ [()], 9) # scalar, writable request# ndaE = 9= _WRITEJ)10F(O, 10J )Rp# zerosUshapend = ndarray([1], =[0], format="L", flags=ND_?ABLQcRaises(IndexError, m.__getitem__,  .tolist(), [] ."range(8))9z2, 0, 7?pTs(m) []# one-dimensional KVKhKR9%nd [1, 2, 3M b f, non-;( ,27trides=[ &y> .7 GTypesOq3 self.assertEqual(nd[1], 3) nd = nd[::-1]for order in ['C', 'FEA']:&Cm = get_contiguous(nd, PyBUF_READ,I)6self.assert_m, nd$ .tolist()- 6Raises(TypeError, m.__setitem__, 1, 20?21& Y1Y# multi-dimensional, &e inputaarray(range(12)), shape=[3, 4], flags=ND_WRITABLETE"nd%m) cBuffer AEB6'F's |ND_FORTRAN m +X)<#CfOnon-C6PIL{ Ee,xCJG# W[1,2,3,4,5] trides=[2]W'uTrue(m.cdef test_memoryview_serializing(E&):77# CGsize = struct.calc7('iAa = 9.',  &(abuf = io.BytesIO(m = bytearray(5*size)# buf.readinto(b)self.assertEqual(m.tobytes(), b) *# C-contiguous, multi-dimensional*size = struct.calcF('L'x(nd = ndarray(list(range(12)), shape=[2,3,2], format="L"Am = memoryview(ndbuf = io.BGIO(m0 = y`2*3*2*"*0Fortran 0#1 #2$,# flags=ND_FORTRAN#[#\ /#b]@#def test_`_hash(?():s exportersv . |Ab), /m)0 mc.cast('c'F3,4] `cjbj7nonlxle[::-2](xs'30P3,2,5 0*nd0 o slice!0mnd[::2, ::&-1w x8 x with suboffsetsX2,5,3|6PILSe@ity- invariant11.''Boa .xy XbXM'(yX aP~- $(a  ange(12)), s hape=[2,2,3], format='L') m = memoryview(ndself.assertRaises(ValueError, m.__hash__) Nnd = ndarray(list(range(-6, 6)), sh^/12/= #/< %Cdef test__release(&):# Create re-exporter from getbuffer(G), then N  e./a = byte0![1 a hHm) #_ BXedel ndA#m."((1#m,5=PyBUF_FULL_RO, flags=ND_REDIRECT7nd2B?nd1D Is(nd2.obj, mf"7o1, nd2= # chained s-U :Z( m&m1 '2('m1  24o >#?%8z/m2 ]I2%m; tsp# Allow{nging layout while cs are d CUVAREXPORm^nd.push([4,5,6,7,8]Y 5]0mutm  Qxoryview(m1)  self.assertEqual(x.tolist(), m1 3) 2 y = memoryview(m2) NyAE, m2 2/nd2m2.release(Gy nd.pop() # pop the current (  3edel nd'm1(x*# If multipleGqs sharesame managed buffer, implicitJ1 in9scontext<r's __exit__() method should stillLUwork.def catch22(b):Gwith(b) as m2&*Fpass7x = bytearray(b'123' VxV1V&m1:j m1[0], ordj'')"ndrange(12)),pe=[2,2,3], format='l@x, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECTDz = @y@ Is(z.obj, x` JzJI8HU[0:1] , [[[0, 1, 2], [3, 4, 5]]]a # Test garbage collection`2for#H(0, * 7 ;*x/m1  4C yt.y/m2"G 3Z*z"w3 $$ $/ ;52[12/ ; 3[A3; ;/m3<21Q= ndarray(m1, getbuf=PyBUF_FULL_RO, flags=;)  with memoryview(y) as m2:*9_del yz = ndarray(m2"a z32zcatch22(m1 $2$3$self.assertEqual(m1[0], ord(b'1');52[1;2;53[2;3; ;@m1, 5m3 E# .release() fails if the - has exported buffers.Gx = bytefb'123'3Raises(BFjError)1x %eyrvm[0] ==def test_d_redirect("):)D'nd[1.0 * x for x in range(12)], shape=[1format='d Aa = #.o('d', S )qk(nd, a2yx ND_REDIRECT1yD$7m =R'(zL\8Is(y.obj, x $z$m$ ml #y#$[1:3], xQ %1, y-z-:y, #O4from_static_rfmt = 'B'Gw ls [0,1,2,3,4,5,6,7,8,9,10,11]# exceptions@)AType'", >, 1, 2, 3d#5==xR%9(c7(verify(y, obj=x,Ritemsize=1, fmt=fmt, readonly=15@ndim12strides=j lst=lst)  for i in range(12):  self.assertEqual(y[i], i)&Ydel x%y x = staticarray(7y = memoryview(xQyBxQ"ndgx, getbuf=PyBUF_FULL_ROdDz = -y- mzGIs(y.obj, m @verify(m, obj=z,itemsize=1, fmt=fmt, readonly=15@ndim1shape=[12], strides=[1]5vlst=lst, y, z, m4, flags=ND_REDIRECTr@ 5z xg # e==NULL legacy_mode=True yONone~\K!!a 1jC)r?Is(4* Df=PyBUF_FULL _RO, flags=ND_REDIRECT) m = memoryview(z# Clearly setting ".obj==NULL is inferior, since itY# messes up the redirection chain:+self.assertIs(ycf, None #z#y m verify(m, %y, itemsize=1, fmt=fmt, readonly=15@ndim1shape=[12], strides=[1]5vlst=lstdel x, y, z, m def test__getbuffer_undefined(!"):4%# &proc does not adhere tonew documentauAnd = ndarray([1,2,3], [OGETBUF_FAIL|ND_UNDEFINEDRaises(B0Err=R, nd)issue_7385x"x) if __name__ == "__main__"@unit.() # Copyright (C) 2003 Python Software Foundy import H T.mockdshutiltempfile5sys 4tat otos.pathTerrno functool-*4lib 0subRess from  (make_archiveregister&_format, un;getC3s, Rdunpack -R"ryK{ = s}SameFilee)\8tar"zii]g0sup-.!TESTFN, FakeP B2 = + "2" try1grp1pwdUID_GID_SUPPORTGrue except IM/pFalse  _f% reM(*args, **kw )@# Pretendadestin( |pon a di@ent 8qsystem.rh1 OS(getattr(, 'EXDEV', 18), "Invalid cross-device link"){_ @ ,p.wraps(ay sbuiltinib = os.u#8 = J% return func(*args, **kw 3) finally:os.rename = builtin_')return wrap def write_file(path, content, binary=False)e@"""W0# *&p* to a ? located at *K1*. s#If is a tuple instead of a string, os.9.join will be used toKqmake a % Y*[true, the@opened inIAode. 1"""Pif is4anc \x) =(Pwith oJs'wb' ifx else 'w') as fpRW1fp.(U)Hread R;os fromrr&0fp.(qlistdirres = []DAfor {in sorted(os.67pK_,AP%%ifo!is|) and notglink(p\;res.append(V+ '/'Z#r E&IF + nM5+Xres class TestShutil(unittest.!CavXsetUp(self`super(/C!, !.-t.tempdirYtearDown\0_Qwhile{e :d =V.pop(A.rmtree(din ('nt', 'cygwin')) [0mkd """Creat0 orary directory thatd@clea%#upZsR^DA+E q. d #d__works_on_bytes tmTbylvictimttmp, 'killme os2ir(6(p, 'some'), 'fooULfsencode9aself.assertIsI nstance(victim, bytes) shutil.rmtre%!)  @support.skip_unless_symlink!def test_>_fails_on%q(self):,o`tmp = .mkdtemp(dir_ = os.path.join(tmp, 'dir'( os=0ir(1? @B , HassertRaises(OSError, +8TTrue(aexistsk)f .l//ees = []M}!ong(*argsims.append(!< (m#, L=}Equal(len(^O), 1)#Is"u[0][0], isn4]Y7/1]d4IsI202][5%Hworks1Gdir1Ldir2)#2*3*3)for d in Hb, 3BOfilef`write_(w1, 'foo! L',7os.2T0'L3L20 IK>M# make sure s are removed but not followed}VlOFalsG1GFOdir3.)6^e  # 5name is guaranteed1to , = 0.mk FileNotFoundJH# that ignore_p option hoT,@=$L#1ing otmpdirEdir, "tstwf"), "" 8 with self.assertRaises(NotADirectoryError) as cm: shutil.rmtree(filename)$6# The reason for this rather odd construct is that Windows sprinkles p# a \*.* at the end of v w s. But only sometimes on buildbotPpossible_args = [JI, os.path.join, '*.*')]aself.a8In(cm.exception.L g<TTrue(seexistsu)2P# tesat ignore_e1s otC hod,@=h6= [adef on (*b);s.append(!P=Equal(len(bO), 2)#Is"a[0][0]scandir0YU311],|21IsInstancei02][9` Vq;Y1/rm111][/, ; "P@unit .skipUnless(hasattr(os, 'chmod'), 'requir!s.2()' FIf(sys.platform[:6] == 'cygwin',y "T can't be runrC9 (issue #1071513)."~ geteuid') and ()0reliablyHrootE64672_onX( .State = 0os.mkdir(TESTFN*5addCleanup(2$, /I0`child_|_ = 5C, 'ai9?dir8 b8upport.create_empty{.Ry&0ld_0mod1tos.stat&@.st_Gold_r6jDyCpath).st_mode# # Make unwritable. new_mode = stat.S_IREAD| EEXEC-os.chmod(self.child_file_path, L)1 ?dir0hTESTFNST|addCleanup($, 5@old_f8 FM LKhutil.rmtree(snerror=eck_args_to_o# Test whether has actually been called]assertEqualyState, 3,M"ExpectedX5 toz function did not happen.") Oodef ch , @, arg, exc):5yr# test_,_s deliberately runs 6on a directory that is  500, which will fail$a# This isdm8n s8s9 99.9% of the time it initihs7gremove a W1 in:A, soRfirstRwthrough==2os.YpHoweverJme Linux machinening ZFS onSFUSE experienced aure earlierwprocess<at os.listdir. The Cpmay leg8Pbe ei1if F < 2"!ifjunlink"&Glf8*el`_rmdir_ ^/seM 0Is(,R 1In([V]B"> True(issubclass(exc[0], OSE)9E+= 1,elh{T\-*+6= 3udoes_not_choke_on_Ping_l5:try3ori+! =6)raiser(fn, *`, **kw \-n != TESTFN:  raise OSError()  else:&return orig_lstat(fn@1os.1 = g)r Ios.mkdir(TESTFN<write_file( , 'foo') Lshutil.rmtree1Qzfinally@unittest.skipUnless(hasattr(os, 'chmodrequires os.r@supporC!_uD_symlink!@def d_copymode_follow%vs(self)tmp_dir = <GtempPsrc =path.join(4 4?dst+Fbar'=@src_0 z0?dst0 Gquux1=src=dst3os.V(>"A "Btat.S_IRWXU| G1 # 1 to(h;O;assertNotEqual(Asrc).st_,CMH=7dst"Belf.jg'# On Windows) does not  s (issue #15411 ifname != 'nt':#I0rc nTX(), +1IS9GqA'IAbothusv?=l F4_to, 'baz')  dst_link = os.path.join(tmp_dir, 'quux') -write_file(src, 'foo=dst`os.symq>1src`"A "SchmodBtat.S_IRWXU|s G1Q$U$lV', *O[ # 1 to%3os.N Nxshutil.copymodT~:sfollow_9ws=FalseCelf.assertEqual(~!MP).st__, 5x5j&Noml2,L5dstHQ# src2q - use z(>"/, 9 5src?dstD&, Iz@unittest.skipIf(hasattr(os, ''), 'requiresbe missingr@supporOt_unlessq@def p_5_to 2wo_dq(self)::0 = .mkdtemp(ec +3barw07baz00`~' # silent fail sSsC qos.utim< , _%a ! src_stat.st_mtime - 42.0)) # ensure different #3s write_file(dst, 'bar')self.assertNotEqual(os.pU(src)u$, 6dstJ`ymlink9,"Jdst_" if hasattr(os, 'lchmod'):2os.iB , .S_IRWXOrPflags') andl=, 'UF_NODUMPq: s4u =8lb;+# followshutil.copyY$, S,Y"_sfs=TrueyG ?ode'odMs# don'ts!GFalsZ K ifiu  in supports_d  M@for q in 'st_aB!', K'0:# The modification 6s may be truncatedUthe new .GBLess0get1,-),CG C)CI + 19t* pAm W !rc' 7Q# tell to@ butM is not a { | O(abst! -0tatu% < 0A.1) "@unittest.skipUnless(!ch 4 R4errno, 'EOPNOTSUPP:8' "requires&, tB & EG"@def __handles_harm_G_errors(Xtmpdir = .mkdtemp(]1path.join(51, 'V2. 2.91, 'xxx') write_file(2, 'xxx') def make_chflags_raiser(err):&-ex = OSError(BF Bapath, U , *, follow_symlinks=TruecKex.errno = err9 ex{return #4oldc = os.!:try0for~0 inno.EOPNOTSUPP, 8`/ =[{2shutil.copystat11, ).# assert othersors break it, +P {Rself.~R'#s(+, kfinalln  @support.skip_unless_xatt{Ptest_;(Ztmp_dir = .mkdtemp(2srcc.join(4v, 'foo'+Q=src?dstJ?barJbdst, 'Q# no 0 == uproblem!r6dst# common case:aos.set\(Puser.g, b'42,,3,CEqual(sorted(os.lisO)), ) OUOos.g/),. vp# check+{don't affec s^os.remove(MlV@os_emw.EPERM, ' @_on__foo(fname,, val, **kwargs&,!if%q'>BNelse1Uorig_sL  CdQ5> =  -Uf2In(,M# the sourcesystem not 2ing s should be ok, too. & def _raise_on_src(fname, *, follow_symlinks=True): 1if 0z == src([# OSError(errno.ENOTSUP, 'Operation not supported')ereturn orig_listxattr J:try Pe = os._ * =0 )shutil._copysrc, dstlfinall{  d# test that lkstat copies ws20srcP s.path.join(tmp_dir, 'the_twrite_file(6srcSos.se`'user.Kvalue', b'fiddlyS?dst 0;dstB  dself.assertEqual(os.gQ )?@.skip_unless !@unitAU@A(hasos, 'geteuid') and ()P!0,GF 'root privileges requir;{ s(# On Linux, it's only possible to access non-cT for ;# which in  b. Thisshould be expandedNas soon as other platforms gain4@exte? buibutes.K0 = .mkdtemp(* 7foo@src_7baz03 OSd_"Btrusted.J'42p / 4.3'VFalsez 7barv1dstj7qux0 O_?1 =+F'qU3]Rd#s( ,.  os.getxattr(.dst, 'trusted.foo'), b'43') @support.skip_unless_symlink!def test_copys(self):"Gtmp_dir = .mkdtemp()!src = os.path.join(41, '+?dst+Ibar'V_0 z0write_file(srcz3os.1src_qif hasattr(os, 'lchmod' 2os.GB, stat.S_IRWXU |O_# don't followpshutil.R*V=TruePassertFalse( is7_(dst).Equal(read.6),  9os.removeQ#(%ad,o^0).st_mode,  9X4"2 Eflags') and, 'UF_NODUMP#:.%4R 5 _%l &+ 20/, ^, ek=dst+ ifutime in +s_ for attr in 'st_atime', m ;: # The modification *s may be truncated in the new file.Kself.assertLessEqual(getattr(src_link_stat, -),C C8dst>U + 1)B`if hasW(os, 'lchmod') .st_mode, khF6NotI2D flags') and '7 !) @@support.skip_unless_xLdef test_copy2(]tmp_dir = .mkdtemp(8src = os.path.join(4v, 'foo'+?dst+7bar+`write_a Jaos.set Puser.og, b'42Kqshutil.-6dstOos.gm.edst, ')vos.remove(t0sym^! _s;7src@ :dst+ 51-1>u# don't followS!U(5T /lf=FalseVATTrue(  is?2s!ad0 ),Q#re5C#)9jrmtree_uses_safe_fd_version_if_available2,@func|s = ({os.openT un rmdir} <= s0_fd_4@list in^s>+} k=if 6 6) se&lf.assertTrue(shutil.rmtree.avoids_symlink_attacks) tmp_dir = self.mkdtemp(%d = os.path.join(6Z, 'a'+ osDJir(dItry:yRreal__safe_fd5class Called(Exception): pass.def _raiser(*args, **kw )-` Oa $ =d1VRY"s(#, K+, 0ofinall47MJelseEFals30_usnP_funcP '7jDtestdont_delete_file(]# When c` on a ' instead of a directory, don't QA it.uhandle, 0 = I@.mks os.close(3aTNotAD}]ErrorpCos.remove(@copy^_simp 3src 3dst% :emp2, 'destinaddCleanupH#, 0 dirname()A4wri(^0, '&.txt'), '123X\ ;'e* qa456') >i* is(= |Y<_isdirJ )J K, actual = read tbEqual(C Z [f @support.skip_unlesSqs62lnsrc') dst_dir = os.path.join(tmp_dir, 'dst') 0sub /0srcg, 'sub/os.mkdir(!IRwrite_file(70, '`.txt') 'ooe\MlinkZ0, '1@dst_ 1@sub/"5`os.sym(*~507)?if hasattr(oschmod'):?Aos.lB, stat.S_IRWXU |O_ flags') and{L, 'UF_NODUMP: 4uR\l 6&hutil.copytree"Elgs=True9elf.assert isL`oink'))NPEqual@OreadL,&*5&/s"I].st_mode, c  e 2 f!) -def test__with_exclude([# creating dataBc/gexists Atemp0mkd ( :tryH6|(/ ;-estination;?1235!mp 5Z0, 'l' .:;456q 2r/2's1assertRaises(shutil.SpecialFilez,9", 2>yI __$__{znfinallrremove(l!5r@supporh!_ui_symlinkU BB5dirLpubdir =path.join7A, "s"E^  O(,y O dY(2 cIB1{!  4les = e.args[0]{Equal(len(8J), 15src, dst, &@_msgaja"`%s` is a1" %V {;elsself.fail("should have been rWdD)rmqignore_Ws=Tru 6?2, 7jsT_func+_2rc_Dmkdtemp(3dst!6os.e ., 'destination6_Qwrite2((sk0, 'LP.txt'x71231 n ;&')e* qC456'copied = [E5q.append&X,R, copy_function=_copy) self.assertEqual(len(copied), 2) * @support.skip_unless_symlink!def test^tree_dangling' s(k"):Q~D# a & M raises an error at the endh8src_dir = R.mkdtemp(3dst!os.path.join., 'destination'>3os.('IDONTEXIST', M0, 'i.txt')Domkdir(44write_file((^* jg, '456 RB (E?, shutil.%, [&Yis ignored withproper flagO+ =(` u2 X,XV=True{ fNotIn(@listX)4 ifst)3w ~D%):MHG @real GOopen|5 R'w'EpassY%),6G6C2_to9target_is$aectory >os=Fals/6 isB40, '~ TE#[GK ttp5{, methodfname = 'test.txCt' tmpdir = self.mkdtemp() write_file((,, fname), 'xxx'+%1 = os.path.join4WK2xqmethod(T#, / l>l2mtreturn MT12) @unittest.skipUnless(hasattr(os, 'chmod'requiresD@def C`_copy(H!):c # Ensure that the copied exists and hassame mode bits.I0!1,7g.rpshutil.&%assertTrue(.w/2)/PEqual0Astat)`1).st_,2S8]utime5 281andamodification &2_ $2$w515I@for ; in 'st_a!', m ?!Th Cs may be truncatedQ=1newGBLess0get,%),<<<F + 1 iff,tflags')1E $ S> >support.Q_zlib>make_tarballEcreating so ato tarE\root_dir, base _=]Cs(''5*# force B to MCdirectoryos.rmdir`# workwith relative s@$D0dirRArel_M>! ?, 'archivechange_cwd(i7V_Ww0abs(rel_base_namGe) 0tarball = make_archive(rel_base_name, 'gztar', root_dir, '.') J # check if the compressed awas createdself.assertEqual(-%, | + '.tar.gz'9True(os.path.isfileG)10tar*C.is_ 5@with*Dopen$P, 'r:u as tf:DCounPf.getNIs(),15@['.'fE/sub /2';@ './18 2 1sub93']trying an un5one support.change_cwd(work)X V J {/')@def Pinfo( , b=.!*ar =M\#f.sort(return tuple(&S_s<dir='dist'#`someth to0 = .mkdtempV4 = tTjoin(66dir0os.\Pdirs(<, exist_ok=)Qwrite()'1'), 'xxx+2+Ekdir%']'W"!, 3^ '2'_"if+di xKo'outeru*@requires_zlib@unittest.skipUnless(shutil.which(' 0'Ne he7mand to runeA!_vgu_"  3, ' tarball = make_archive(base_name, 'gztar', root_dir, sdir) # check if the compressed tarball was created6self.assertEqual(-c + '.tar.gz')9True(os.path.isfileG)3now anotherusing `tar`cD2 = ^Vjoin('.2tar_cmd = [';z'-cf', 1Edir]usubprocess.PA_calQe, cwd=5 wstdout=RwDEVNULLG&2)yq# let'sare bothGsX_tarinfo/, pKP# tryWan unX5one% =86Cfor a dry_run1,E l=L&@support.requires_zlibdef test_1zip!):!#`someth eto zip$# =_v_Z's(`tmpdirp.mkdtemp(# force shutil toedirectoryos.rmdir(YI@workwith relative 6$ar0dirRArel_1! ?'change_cwd(Vw0abs(72sub/file3',  'outer']) with support.change_cwd(work_dir):+3base_name = os.path.absU(rel_ )7res = make_archive., 'zip', rootw!, Jself.assertEqual(res)@+ '.G|2TTrue(Pisfil/s)-0zip&C.is_ q1<T.ZipFTj as zf:CCoun0zf.ylist(),4o['dist/', 9sub ?2/'901>2L3@ requires_zlib@unittest.skipUnless(shutil.which( 'Need the zip command to run'@def et!_v(@)0 = $._create_"s(U}QmAjoinZ.mkdtemp(), '< S# check if ZIP b was dfo*D)S# now~ anotherusing `zip`E2D>2zip_cmd = ['P, '-q -rY6Edir]zsubprocess.Fc_call(Ve, cwd=5Mwstdout=RwDEVNULL:p# let'spare bothMs5O)9> +O2PQeqsorted(8), 2M6+!un8,d:$@9elf.assertEqual(archive, base_name + '.zip') self.assertTrue(os.path.isfileD5)) 2# now check the ZIP , using `unzip -t`2zip_cmd = ['', '-t', ]+with support.change_cwd(root_dir):+:trysubprocess._output(, stderr=(fSTDOUTGwexcept &rCalledP\Error as excdetails =..decode(e:s="replace"w{msg = "{}\n\n**UROy**\n{}"3fail(msg.format(exc, def test_make_(?\tmpdir = .mkdtemp(R$= 2Rjoin(93, 'YjRaises(ValueH(, s, 'xxx'@requires_zlib _owner_group#{ 7Q and ;,various combinations|# this works even ifre's not gid/uid9if UID_GID_SUPPORTN = grp.getgrgid(0)[05P= pwd'=pwu'Oelse\='g'v_create_s I! re0(h0, '., !, =,X K=4res:N$oDOtar' (.J(A'kjh3g','oihohohX@P@unit.skipUnless(C, "Ry!%pw0tar_v ?dir`3f.mkdtemp(), 'archive')  group = grp.getgrgid(0)[0]#owner = pwd#=pwu#with support.change_cwd(root_dir):Nx_name = make_Q(base, 'gztar', G, 'dist',NR=!, =%) C# check if the compressed tarball was created6self.assertTrue(os.path.isfile()m2nowqsoerightsW8 =}JZ.openO-:tryXfor member in L+s(6bEqual(,v.uid, 0),0g0kfinallcclose(def test_?lacurrenQP = osfK_breaks(*args, **kwDraise RuntimeErrortegister_format('xxx', _`, [],  R  f[N=.mkdtemp()@except E:ion "6pasXOB', ]j?unr# 0tar'_in_curdir(# Issue #212800 = 1"{F @', 'x)Aest. q K'G7@requires_zlibT0?zip)Ezip') %o)7)dR&):RRs(Typ/, EF', 1H*lambda: x mZ[(1, 2), (1, 2, 3)])3 %register_archive_format('xxx', lambda: x, [(1, 2)], u file')H7s = [name for , params in getgEs()]Cself.assertInX)/un E/Nodef check_unpack(, Zmat):1_with_converter(a path:c.LElib.PathG(BFakeC %, root_dir, base 0 = 7._create_z&s(expected = rlistdir(F&.remove('outer'Yp` = os.)Q.join.mkdtemp(), ',3ile;EmakeT# let's try to Pq it nowittmpdir2!7g(;)|(O),oeEqual(X,$, v and again, this time 1 thmat specifiedV3;$3)t=H; Raises(shutil.ReadError,{goTESTFNfO_ValueIKtestA_tari:E('ta@support.requires_zlibl/gzn0p?bz2o bo0oOlzmap xp0pO?zip4zipl _registry(seslf): formats = get_unpack_&()(def _boo(filename, extract_dir %):X_self.assertEqual(2O, 1)' c'stuff.boo'4 [G'xx'register('Boo', ['`, '.b2'],Q, [('T']~#archive(+, x# trying to 0 a o Ger again3Raises(RryError,H , 52',I # should work nowE$un o;&2bz1In(U /O''),{D4NotG uF # let's leave a clean state$ 2[#, f#@unittest.skipUnless(hasattr(shutil, 'disk_usage')"( not available on this plat"K}_9(v2 = .)os.path.dir0(__2__)\L Greater(P.total, 0+Oused* oZOfree/<k 4p UID_GID_SUPPORT, "Requires grp and pwd support os, 'chown($'rO3os.# ed-up automatically by TestS~.tearDown methodAmkdtemp(@0 = 0.mk S(dir=@0QwriteDn'M functionWwith jBQValue?Qj PoLookupQ, user='non-existoZgroupp groupname')3 with self.assertRaises(TypeError):+2shutil.chown(filename, b'spam')X=G3.14Uuid = os.getuid()ggdef check_path, uid=None, g jEstatp  ifF is not M ,$ZEqual(uid, s.st_uidPPgPgP*(QL#GIser=L'ogroup='62dir ' (J"E1 lJ/ K.user = pwd pw5[0]R^` = grp% gru% Qser, B1+Wy TS *RSFtest_copy_return_value(= # #A and r2 both 2 their destination .cfor fn in (Wopy, 2l3`src_di.mkdtemp%?dst%2srcSjoin(]v, 'foo'T`write_'#arv = fG#, E{!0rv,7` ? a?os.7Zbar')7v?  Ctree_s itsn" = ! dst_dir, 'bar')#  src_file = os.path.join(dir, 'foo')0Qwrite2#; $rv = shutil.copy%.1dstAUself.assertTrue(exists(rv),Equal(readPc6), n!) def test_D_samQelf):'$# $,() should raise SameFileError if the source and destinationN2are)Eame.j3mkdtemp(@rR)s(, ,  b# But (work too, to stay backward compatiblNL tree_return_value( ' 'Xs its [ ?diri!0rc_ 0+ " "DddCleanup($ rm#, B , ^?src#w6yk[  ],+rlistdir class TestWhich(unitg.fCase):\setUp.< = q.prefix="Tmp"T V ZR# GivnF an ".exe" suffix for all # It's needed on Windowsnot harmfulother platformsE NamedTemporarygV(dir=1TC,C#g=".Exeos.chmod`.name,t.S_IXUSRpk.close. ^_split} Qbasic)  nEXE in a directory, it#be/&edw,F;dir\2rv,< absolute_cml When giveni`fully &ified path to an executable that exists,  # it should be returned.!rv = shutil.which(self.temp_file.name, path=Edir)CassertEqual(rv,  F!) 3def test_relative_cmdv!):!# When given the - with a directory part to anN base_dir, tail ` = os.a.split.0rel *Tjoin(BR9support.change_cwd(I=z ; >V# But#0n't9searched in PATH{ies (issue #16957)\ C 6MIsNone(rvoZ(Q7# IRd0dir 3. if sys.platform == "win32"E,# Windows: currenty implicitly o<Saos.cur)-)OelsedOther #s:mPmatchg ]{ P@unitk.skipIf(hasattr(os, 'geteuid') and ()X0Df 'non-root user required'Anon_ing_mode: {1Set7 read-onlyask for write%s{2hmo7 stat.S_IREAD ifaaccess 8wos.W_OK8aATest("cas"nH> =} g_3D Re" 8c8?) def test_nonexistent_file(self): # Return None when no matching executable > is found on the path.M rv = shutil.which("foo.exe",+=~U.dir)4assertIsQ(rv) @unittest.skipUnless(sys.platform == "win32",2 "ext checkWindows-only"@def k_-_->ing1qAsk forqwithout" extension,n ensure that# it getSproperly P7Fc A_[:-4]hEqual(rv, <AtempQ.nameF + ".EXE"qenviron& support.E)mentVarGuard() as env~env['PATH']>0elf!&#X%M Omptybase_dir = os.)  change_cwd(79, \ 4]$&'' = )@_no_Q R.pop( , ! class TestMove(]bCase):w\setUpp0 = "w3src)Q,@.mkd (*?dst*TJ~Ajoin.Adir,g==7opegGa, "wb"ff.write(b"spam4RarDowJ%?[d in /:tryvNif drmtree(dnexcept9FpassQ_move, src, dst, real_dst<'/"r20cons = f.read#@w(la~(, f self.assertEqual(contents, f.read()) - False(os.path.exists(src)) /def _check_move_dir(?, src, dst, real_dst):3e~ = sortedcAlist@_'pshutil.^yT Y'BtestAfile# Move a  to another location on the same%usystem.<.QJgP.src_!, %?dst 5_toinside an ing dir<;dir@mock_rename^ P1_fs{ Fy l(]_+  ,H?elf"! r<`= tempE0.mk (6tryy XNkfinallR cg&srmtree(RI#jexceptBpass ?dir!]%5h`,D%Ajoin.' 1basDdir)Lgp4sep$  P% +7sep^-c_dir))) " @unittest.skipUnless(os.path.altsep, 'requires ') def C_move_dir_90_toq(self):+/u._check2$@.src1+ +h!, 40dst,JNBjoinF'EbasenameeA))) Iexisting_file_inside_deu<@# A ( with the same g ;?ination dir already l!s.F7ope^g, "wb"w,Epass9 assertRaises(shutil.Error, F\<. Edont`_in_it/Moving a,! rA an Udst =dir, "bar"]z.J=dstelfalse_negativlos.mkdir(TESTFN6tryfor src, in [('srcdir', / :')]9= = "bar"ddst = Ajoin;.Tdir, :3os.+&V, dst'pshutil.G(dst6dir'`final_,L| isN(Y( E5-danglingD?src V'baz'@G'bar0+rcn=W'quuxS *G 12# On Windows,@reala does not follow s (issue #9949N ifCf= 'nt' UEqualqQ(src)@read_OelseY&.px3/irsh!mk&rcG  return_valueXrv = CqU 71rv,yHp1basWvA))) N #as_)$@@6pecial_functiomoved = []  def _copy(src, dst): moved.append(%)%pshutil.((self.src_file, dst_dir, f_function=uF:assertEqual(len(Tqd), 1) o@mock_renamePtest_*f_specialh)ad = []AEupport.create_empty(os.path.join'child')G'1Ht5 3) class TestCopyFile(unit.Rase):_delete = FalseAFaux(objec{p_entere2_exited_with = Non Orais4q_init__!, *1_inO=c, suppress_at0Tru\C_?* =OZ40 Z- =m6CreadW*argsUreturn ''5_5 3V >x!exc_type, 2val /tbX 2<q"if! M {(r  OSError("Cannot close"a*;U rtearDow Cdel FopenNR_set__ \!.!0 = 0t1 = st_w_source`a_failsf`,(E, mode='r''&4if $ == 'src'* z'z"6*"' 0 # shouldn't reach here.9^ >&VR#s( #, T|,p, 'dest'L!0_w_g KtsFJ?k:{p   raise OSError('Cannot open "destfile"') assert 0 # shouldn't reach here. /self._set_shutil_Z()&P.copypP('src D', 'USTrue(.._entered*xited_with[0] is O<WEqualg=1].args,( U#,)def test_w__close_fails('):+0 = f.Faux(?9 $jn(*name, mode='r'):4if $E ==  &Usreturn E 'F" Gu+Orais'osourceI ]R/#s( l,m= fFalse(,(FNone  _b_| move_dir_caseinsensitive@# Re5s a folder to the same Y,but a different ] 0srcyp = tempq@.mkd ddCleanup(rrmtree, I ,  3dst` os.path.join(  os.path.dirname(self.src_dir), #/Nbase0.upper())8OassertNotEqualcQ, dstl 4Etry: }shutil.mov='tTTrue(disdir(pkfinalltXos.rm0 class TermsizeTests(unittest.RCase)@def _does_not_crash#"""Check if get_term_b() returns a meaningful value.0There's no easy portable way to actu! ck@the _u of thej|, so let's1Uif itsomething sensihinstead.K5""" k#= *{,sGreater0ize.columns, 01Bline/aos_environ_first'ment variTs have precedence"with sup".Ed=VarGuard() as env#env['COLUMNS'] = '777'0del8['LINES']a"ZO777). :888-38884bad 6:xxx :yyy!"-@skipUnless9isatty(sys.__stdout__.fileno()), "not on tty"K haI}r(os, ''jP'need 72()'sstty_matcj &ame results ignor6envAThis will failstdin and  are connected to`differLi!s x s. Neverthee, suchEsituations should btty rareQ size = -subprocess.check_output(['stty', 'size']).decode().split() except (FileNotFoundError, Permission4; rCalledP/)):0self.skipTest(" invocation failed" pected = (int(size[1]), 0])) # reversed order vwith support.EnvironmentVarGuard() as env0del['LINES']PlCOLUMNactual = shutil.get_tF@nal_&()assertEqual(ex", H,def test_fallback(:_T # sys.__stdout__ has no fileno`6 swap_attr(sys, 'Dw', None=;V =(10, 20)H?|jP.columns, 10/Qlines]] i Dt a  on UnixA%or. not in (0, 1, 2)3yWindows6Jopen(os.devnull, 'w'If, \/y fv*_30, 4v3v40) class PublicAPIJ`s(unit.4Cas@"""Ensures that the correct values are expo=!in"p] API."""module_all\ibute.lTrue(has@'_'0tar*api = ['copyH0obj Dmode nstat',I*2 1tre?1mov$rmNpSpecial)*e 'Exec make_archiZ%_formatsregisterA/un3 'ecunpackHsIG 1c ' 'ignore_patternPchown`_whichD>4SameFileErrorC'] if hasattr(os, 'statvfs') or os.name == 'nt':6=target_api.append('disk_usage'),self.assertEqual(set(shutil.__all__), R)) if __!____main__unittest.() import ` from ! 0sup"._urllib2&panepathyT2url Y$os dsocket@k.errorereques*Ssys .Dires("network") TIMEOUT = 60 # seconds def _retry_thrice(func, exc, *args, **kw )for i in range(3"ry$ preturn T (*DNexcept exc as eBPlast_5= e2[rcontinudraise ,wrap_with+=pedK,,5^2 # Connecting to remote hosts is flaky. Make it more robust by ing # the cLon several times. }Gopen@ = _j:0url<,jFP.URLEpclass AuthTests(J.CCase0""""s J2 authentication features.""" ## Disabled atmoment since reTno page under python.org whichHcould be usedKHTTP~P. # # .`basic_("): $http.client>>purl = "#v://www./"E/m"g'_<N G *realm = 'f R'M@user"Z  loDer =.getLogger("1Jnet":.addHandler(ing.Stream"))Q# XXXDprest of9!ses aren't very good -- @y docheck much. sometimes catch major disasters, though.K-ftNurls = [fx!'f\>.net/README',/(0non-existent-file;c None,{.error.URLE )f]ti_s!2s, rextra_h$s(f.write('hiGre\n/"J @/'9 :' + sanepathname2url(os.@.abs);E(F@///n0nseE/etc/passwd',6 )!, =8Zfinally: os.remove(TESTFN) @self.assertRaises(ValueError, urllib.request.urlopen,'./relative_path/to/file')Y:# XXX Following test depends on machine configurations that are internal # to CNRI. Need set up a public server with the right authentic`#tB forpurposes. ##wA def`_cnri(($):!if socket.gethostname() == 'bitdiddle'37Plocal/ (.e.reston.va.us'l/eln.concentric.net}  k/se HNone5if J is not $ Eurls = [='?://%s/etc/passwd' %[,7Bhttp7simple/4odigest4not/found.hl]Nb = HTTPBasicAuthHandler().Q.add_`ord('b6_S_realm',% 'jhylton'0'V'zdD' / ^? %.gc(", rextra_h`Qs()+[S!, ] 0urlDDfrag/_C = "zwww.pythonv/index.html#-"yG[ support.transient_i et#c%):7;\req =R 8 7rY(req).3 Equal(resiurl(),+ lredirect_url_- v % 4/R-/:AB </reR//www.pythontest.net/elsewhere/#frag") def $_custom_headers(self):#'url = "http://www.example.com"'with support.transient_internet(urlUYopener = urllib.requbbuild_%()a3#4R<f 2.assertFalse(C._items()g|.0 !V?TruU4#as{('User-agent':add.A.r,'Test- /erTEqualJ.getl mpP@unitN.skip('XXX: 4@imdb1 is gone' sites_no_connection_closeq# Some 0 do not send C9!: : .> # Verify that those work properly. (#issue12576':URL = '' # manglesg@ ;URL6tryCG .0url(C~ as res9=Epass except ValueError?e=cfail("m aed forYing \ei#""ns<>req res = req.readcm_B_url',s, handlers, retry= imU timeuloggingdebug = Logger("{qlib2").*c O*)w"if }T`_wrap__p_thricep~eHA.URLQ+J!in3 hX y0subX=2if isinstanw, tupleo'0urlq, expected_eru-a CFNone' 6fnuTIMEOUTF  # urllib.error.URLE  is a subclass of OS/ dexcept# as err:+>if expected_) -msg = ("Didn't get=for(s) %s for%s, got %s: %s" %](,, req, type(err),l/))M self.assertIsInstanc>,_, msgJOelse;_raise< ?tryY with support.time_out, \l5socket_peer_rese>!io? buf = f.read(V+pdebug(". %d byte% len(buf?out print("" %`file=sys.stdbef.closeX.sleep(0.1) Cdef _extra_handlers()R = []6Pcfh =request.CacheFTPHLU.addCleanup(cfh.clear_c4setTimeout(1p.appendCtreturn %2 ITest(unittCCase_http_basicSNone(getdefaultapurl = "W://www.example.com" Kransient_internet(url, _=}<u = _urlopen_M`_retry8?)u.%u.fp.raw._8.ge B_L} >Met.s*60|ofinall~eoEqual( , ? no_timeout(self):# self.assertIsNone(socket.getdefaulttimeout())6url = "http://www.example.com"'with support.transient_internet(url):.}s}&60~):try:u = _urlopen_}`_retryh#, = L;ddCleanup(u.close)ofinallymiqu.fp.raw._Gyrdef test_q_J?FV+12/.aQ % oEqual( !, dFTP_HOST = 'f`python)q.net/' ,=ftp_basic(w:` V  a B ^_n1uc? ;"< ku& < , /no ^. <r4)arlopen_with_retry(self.FTP_HOST, timeout=60) 'addCleanup(u.close%ssertEqual(u.fpraw._sock.getc@(), f if __name__ == "__main__":unittest.() import a from !1sup"_module # Skip*`_idle xtkinter wasn't built,is missing, #cl/tk is not the 8.5+ needed for ttk widgets4 or7r0lib8P (Ainstalled). tk = #('') # Also!3s _.Atk.TkVersion <=Uraise,.Test("IDLE requires tk3 or later.")  ')ScBeforeing and executm3of 4Qtell ~to avoid chang/Nenvironment..!Q= TruUv$.libregr 8run_inner # call load_s, when present here, to discover2sBrun.o.FW ''tk.NoDefaultRoot(Mexit=FalkCtk._"_d<_root = 1.! pNone # R casehe select.devpoll() function # Initialare copied asv"A_=T.py" $os drandompRJ.MDrun_&, cpython_only]?phasattrcect, '2') f'qp works R on Solaris OS family def find_ready_matching(r, flag)lQ = [] fd, mode in 1*Z"if&CJ.append(fdqreturn  class DevPoll$s(,.qCase): _10fpu# Basic@ of q objectL/Create a bunch(5ipeR that;c@with-"m.F=p =NUM_PIPES2{MSG = b" Thia(.""_LEN = len(MSG>r6ersMwritr2w = {}V2w2riUange(W_Prd, w<sos.pipep.register(rp.modify(C<v.POLLIN(C4wr,S*:OUT+readers.append(rd) writers.append(wrr2w[rd] = wr8P2r[wr5rd bufs = []cwhile g:*ready = p.poll(z_8 = find_2_matching(, select.POLLOUTGqif not *N self.fail("no pipes3A forJing"Zwr = random.choicef .1os.(wr, MSG)"  # er_ *IN M 7 >assertEqual([w"],F:ers rdAXiers[0]!buf = os. 1(rd:;_LE len(buf)0' tos.close(0) ; >p.unregister1 O " ?r6movr , [MSG] * NUM_PIPESN def test_timeout_overflow(I)p$ ==0dev0w, 0os.(=.w 6(-1.'Raises(OpError, 2Y O, -2<(o1 << 3~)B/640(u 8)A&63"pMe`open_f = !(_w__, "rbN8.addCleanup(-+f2\'no#" < method and d attribute4IsInstance(n.KV, int5FFals0gXY>TruX(ssertRaises(ValueError, devpoll.fileno) # close() can be called more than once/H5H operations must fail with e("I/O *2 onud ...")gself.assertRaises(D modify, fd, select.POLLINI4register.(unQ def test_fd_non_inheritable(#%):2$ = (ddCleanup(". '|Equal(os.get};O()), Falseevents_mask_overflow}I w, r = os.pipe=.>&(w# Issue #17919+: ]O- Uv, 0, -1ZC$1 << 64H!1%A@cpython_onlyw_c_limits`from _capi import USHRT_MAXZu^? + "r L% cSmain(run_unitD(DevPollTests) if __name__ == '__:2__'3() """ UG for time.strf  calendar4sys 1re Z0sup#OJ # helper funct`fixasc4#(sqif s[8] #s[:8] + '0' + s[9:]Creturn sDescapestr(text, ampm]ME# s to deapossible lo v0st have regexusyntax while allowing  Ausedncomparison.<Anew_R= re. .replace(0^, = new_text.replace (r'\%', '%') new_text = .replace,:,:,?,?,ereturnT class StrftimeTest(unittest.qCase): def _update_variables(self, now):&# we must / the local 9 on every cycle<P0.gm @ime(a$anow = V "# if[3] < 12: Wampm='(AM|am)',Jelse"@PM|p"#?Njan1x}0.mk(a[0], 150, r1, 0)))K%6try2#8]$tzmtzname[1]0 +0+except AttributeErrorzD&''F3] >Cpclock12 ow_E- 12(el50 4/y$&122nowQsetUp{vQmport javas9p.util.Le.setDefault("US9KIXHBfrom1e i%A sete, LC_TIMEbsaved_"& =.(-|MC, 'C 3addCleanu% (, vV#_s  ^.(r $[@est1' @2%`if sup.verbosetprint(" , platform: %s, Python versionU" % \d7T(sys.= , 6.split()[0]for j in range(-5, 5V#i#2 $2argR + (i+j*100)*23*3603Mq6argUV,]/1($2$u<K E1imeb for",cL+jn.2# Make sure any characters that could be taken as regex syntax isJpescaped 7strexpectations = (:>('%a', calendar.day_abbr[now[6]], 'eviated weekday 4'),K ('%A', calendar.day_name[now[6]], 'full weekday W'), u('%b', Dmonth_abbrF1Feviated !KBKuKD# %c see belowd', '%02d' % 2#ofas number (00-31)HG3G2hou5/235I5self.clock12, ';O1-12;j;37ppjulian (001-366=m=1=B}M@4@ainute,%/59xAp', ampm, 'AM or PM as appropr_Sr5rseconds of current time/60UH ((B7] +jan1[6])//7 'of the year (Sun 1stmwm10?%@((1+o6]) % 7),T\P WP(T - 1)%7/MoO# %x:X:DU 5]%H:%M:%SyMC`0]%1007iwithout centuryCYCms0";8O# %Z%Ssingle perX sign%) Xfor e in expectations:( # musn't raise a value error):try:>result =P.strf0(e[Inow)Cexcept VbEamjZHdfail("W '%s' format gav: %s" % vP)y if re.match(escapestr(e[li2), )continuecif not5>?[0] == '%'Hm AdoesIsupport stadY(%s)";[2]Oelse Conflict]@ %s m:5ed %s, but gotl", b)Adef Aest2/,unowsecs = str(int(now))[:-1] now = self.now  nstandard_expectations = (%# These are . but don't have predictable output?('%c', fixasctime(. , 'near-) format'),Lx', '%02d/@' % [1], now[2],{0]%100)F'%m/%d/%y %H:%M:%ShZhs\<Ptz, ' zone name6 .ome plat specific extensh :A('%Dq 'mm/dd/yypA('%eS 2d'day of month as number, blank padded ( 0-31)Th', cale9.E`_abbr[``1]], 'seviatedf-K('%k3>?hou/23nB\newline characterr/7:! %(rclock12E4M25],>MampmJIA? %ppRp/04])=!s'secs, 'seconds since the Epoch in UCT?t|\?tab T+&[58"3yN3v  'year without century rendered using fieldwidth&) Pfor e/no:h:tryresult = P.strf B(e[0)Cexcept ValueErrorEC[rmsg = "( '|at (%s): %s" % \peBstr(v),if support.verbose(print(msgCcontinueif re.match(escapeeyB$ u""S/s 7 3 elif not3 or [0] == '%'.0DoePt app$to   if support.verbose: print("Conflict for nonstandard '%s'mat (%s):" % \K^(e[0], e[2])))t Expected %s, but got %sc(e[1], result)) class Y1900Tests(unittest.RCase)2"""A limitation of the MS C runtime library is that it crashes ifa date before v-passed with astring contain A"%y"FA""" @def 2_y_S_SS(self?# Issue #13674, #19634At = (1899, 190, p if (sys.platform == "win32O8or #p.starts(("aix", "sunos olaris"))F0 .rtRaises(ValueError04P.strf (.6, t,el``Equal(9B}, "99")sl Sg(Gx1x, 0)), "00}_after O2013 13if __name__'__main__'#;() """UnitsA __icecheck__ and __sub.timport VpABC(typ] Y`(cls, n)"""Implement isPance( a, cls)zreturn anyN.&(c]0`c in {])1.__7__}NX?sub1O(subPcandij0s =.__dict__.get("r__", set()) | {cls}TUsub.mro(LInteger(metaC=ABCy = {int}sSubInt(@2"PTypeC9s3IsSYULrnal ,)?gerint), True?@floaAWFalse Builtin%isSint,  9o,j issubclass(float, Integer), False) self.assertEqual(issubclass(fl<(=&,)?@ def testIsInstanceBuiltin(V!):%h ei28(42?Tru 8 ;H3.14uv; x>0ActVn(()? B Sg= BehaviorYeYSubIn  <;??), z <t>> =(>|<@ in;y9up-%>K=@;w 8r; if __name__ == "__main__"@unit.() FORMAIFFCOMM8@@FLLR Ustrexc, evalz_Aclass C(objectu@1Ls(abc=1, xyz="haha". *zbooh=42 3foo return 42@C().28), M(&v.abc, 1t'\xyz, ,|HSorder#Hthat3`ppliedthe proper F0 to gOAtheyEing.callnum(numD"""D factory wV$or`placesf{Ued-in with one:9ue of 'num'"""Kw return lambda: num return deco@callnum(2)1def foo(): G%421self.assertEqual(*E, 2,# "Application order ofrators is incorrect") Mtest_eval_6(!):]# Evaluating aQqed funcminvolves four step gr eachG*-maker (theECthat sg(orMT 1: e K `Jname222 arguments (if any# 3: Calln0to  }4=# P Whendre are multiple{@ors,#selshould bperformed iLc above"foR, but we L`iteratbProughy7RpreverserIyJdappearrsource.]aMfs = []X_G(tag;.b@nd('1pdec' + -,QL e( L$PP0N loclass NameLookupTrackobject__init__{, index'." =%t KugetattrNf*N1if A == T' X opK@, re ('V!',@Y;)elo?argdargs', str!)e/sep False, "Unknown (b %s" %  /%s%d' % (%6resc1, c2, c3 = map(+P, [ 1C 3 ]expected_N 21', 0 */1'\ 6 2C C2C3C C3C5  71' ;]@@c1.ov(c1.arg-@c2.make_decorator(c2.arg) @c3.make_decorator(c3#def foo(): return 42@self.assertEqual(*o, 42) %actions, expected_5# Test the equivalence claim in chapter 7 of&Qrefer$umanual.# gU = []?barbar = c1&1&Q @cH Zf(bar)) DD $CQclass?C Ds(unittest.\bCase):_simple(p)):#wplain(xx.extra = 'Hello'41x@FC(object): pass ]Cm,l/Odoub/te %10taadd_fiveO+= 5G@E5ten %,15 _order`applie?rst= 'first QosecondR "S @.2%'_') if __name__ == "__main__"2() # xml.etree 1 for cElementTree import struct from) up ".s !_fresh_modulTTtypesas cET =? 8%('.%',A xR=['_e0'])eo_aliaskl zr&, /'] Edeprecated=True) @".skipUnless(cET, 'rSIres ") P@Misc!0p# Issue #8651i@p.bigmemd(size=_2G + 100, memuse=1, dry_run=FalseV>_length_overflow , T0dat}ab'x' *parser = cET.XMLParsser() Etry: #self.assertRaises(OverflowError, parser.feed, dataMkfinallQ# = None jdef test_del_attribute(y)element = cET.Er('tag')H&.tag = 'TAG'dPwith V Arr4Gdel TLGgEqual(%,xz.?ext{ IsF|6ext} ex6_'TEXT 8 0ext{9?ail?ail2ail/IL8 0ail8AIL -5 (N, {} = {'A': 'B', 'C 5D'}[^I7trashcan2# If this^ fails, it will most likely die via segfault.pe = rooA w'Efor i in range(20 KKD4SubWe, 'xGn|hsupport.gc_collect( _ref_cyclF# bpo-31499: xml0dealloc() cM1ed vaation U when#Elear() was called previously by the garbage 7or,O^&Jpart of a reference .3  BAXMLP# Createn using an excepqto keepUframeLalive, so"be destroyed N cra Value 20 as:  err = exc # Create a parsert of reference cycle2'Q_ref_%()&# Trigger an explicit garbage collection to break thei# and so destroy-~rsupport.gc__"() def test_bpo_31728(self):<# A crash oQasserfailure shouldn't happen, in caseLs a callqclear()j readinge@textWtail,N@whil`setter"B__setstate__() is alTy running.Jelem = cET.Element(''vclass X>|__del__7G.m?ail0 7= XOH.7 # AOail A*YY+ !{'tag': 42})@ause  }/p @unit .skipUnless(cET, 'requires _enttree') TestAliasWorking(ICCase # Q thatXPcET a9r moduleV"iv_##_w] Qej%p7fooo4.qEqual(e.tag, ''"@cpython_onlycceleratorIm0/ed6C a>c was iC@, asQected2'correct_+L_cETFS# SublB funso it retainq3its T`A.__m[__, '8  r*.x"_comes_from_Cs# The type9methods definedPA codtypes.FunctionsType, +# while the type of methods defined inside _elementtree isC 'self.assertNotIsInstance(cET.E[.__init__,s.Function ) @unittest.skipUnlessA, 'requires ') @support.cpython_only SizeofTest(YaCase):def setUp(=.usize = j`alcobja('5P')J5u# extraE?truct.calc;PPnnP4?0`check_ of. )$ u7('akA(e, )i_with_attribu, href='about:# +> childrenfor i in range(5@3Sub$W'span# should have space U$8 A nowQcx % +=A sOu8P')) Smain(Pfrom 50 im. `_xml_eR# Run+ests specific toC=aDrun_e(@MiscrsAliasWorkingcceleratorI&ed!Asame suite asPq module.4$@=cETif __name__ == '__%2__'A7#) \asyncio ucontextlib>Aort manager, AbstractA<C4MExitStackgf=Boolsic* *FBasejN__a(uTq"""Deco#burn an )%r into acase."""@#.Zs\per(*args, **kw }]acoro =j &G%bloop =io.new_event_(hio.set!&%2tryZ0ret&.til_complete(>kfinallB;Wclose[BNoneS|wrapper class TestAbstractAsyncContextManager(unittest.)Case): @_a/_P def _enter(self): 5class DefaultE"}9=a__aexit__`{, *args.2wait super()._60(m* =).assertIs(aW5A.__ac__(), )]DwithR as cg gK,,TbCis_a mMissingA1(mFpassRaises(TypeErrorv t structural_sub?ingFromScratch1\ preturn  DTWexc_type, pvalue, *_ebackcFNone<q<tTrue(is(e/,  K8 : 7  .oJQAe3  0 = 9IFals*c"?xitm ?xit 'l_plainstate = []a@^ =2{woohoo(P.append(1yield 42M 169993klxaEqual(QV, [1]Ki3elf)[x, 42$xeDc, 999]d X_finally @asynccontextmanager async def woohoo():#state.append(1):try-1yield 42*ofinall. _6999awith self.assertRaises(ZeroDivisionError=^ as x\aEqual(V, [1] -_x, 42(/x r (* jr, 999]) ^!@_Q_testG_cona_no_re(e9@9 /QULwhee ,bctx = (await ctx.__aenter__# Calling xit__ should not result in an exception]"jFalse(nOQ(Type-%, ("foo"), None)R#Qtrap_0_af_throw^&~b*g / IdbRuntimTH QT'foo'""nov81if LQ"2-osecond> M _g#non_normalisedO8 [q Syntax9wait ctx.__aenter__() with self.assertRaises(SyntaxError):-4 await ctx.__aexit__(Runtime/b, None!) ;@_async_testP def _contextmanager_except(|state = []C@H >dwwoohoo(L=P.append(1:tryyield 42b ZeroDivision^ as eD ue.args[0]}WaEqual(9, [1, 42, 9996xTK}xu >xrCF(999)ml?"_stopiterH5**@for h in (StopIteration('spam'), Ah subTest(type=(h)4 %h{E0ionced(QeIs(ex,'(?els*Ffail(f'{} was suppressed'e#bwrap_re(:=Scg (f'caught {exc}') from excOG M0V1 / 0f# If the   c?ped,(a ,o# we also unB it, becausecan't tell whether}+@pingLqdone by#0genor machinery or!ityFGM!L`#|_create&|attribs2**kw):  def decorate(func): for k,v in kw.items('6qsetattrJ],k,v)Mpreturn k @asynccontextmanagerttribs(foo='bar'q8baz(spam"""Whee!"""QUyieldAbaz 1Ztest__Gselfi`baz = ._create9.assertEqual(baz.__name__,'baz-Sfoo,  @support.requires_docstrings!3doc(jCe3_, )i!@___instance_given_cm(_(None bwith bazupass # ress warning keywords# Ensure no $ arguments are inhibite~ :awoohooq,,Zws, kwds4_ ,'] ^2=11a2=22d2=33g=44) as targetQ.R%0, (PKF44)) clPTestA{ExitStack(EBase`, unitm.CCaseDKSyncD .@staticmetho]run_coroutine( 7;qloop = 2io.get_event_(O)f*ec_futurZ,.add_done_callblambda f: ^v.stop()7|foreverexc = f.exception!if not exc]f.result({Nelse4 =S$._"__QW>try@Praise@ "68excp3 = FJdQclose1  p&a9^def __enter__(seglf):  return self.run_coroutine(__aenter__()) :def __exit__), *exc_detailsdJ Doestack = SyncAsyncExitSQsetUploop = a9io.new_event_%()!8set!D*addCleanuv.Nc.close!@_RQ_teste callbackexpected = [>((), {}),/1,2), dict(example=1)T%a&]`resultQ(*args, **kwdJ"""Test metadata propagation"""h+l.append((VT%}Zwith Xa() as x 1Ffor L in reversed(d!if5P and T"2f =s\.push *,  D#ellc-W[-/se&ssertIs(f, = ( wr r.(_s Z@b[1].__ ?d__oB=NotEqual(6rCEname@2.__ IjIsNoneG8docF,%, Wac_raisZeroDivisionError_{P_exc(J@typec;_tbU*Is2y5fsuppressh o OTrue*okz?exc#`class CM(object):  def __init__(self, check_exc): #".!& =- +Sasync\caenter^Sfail("Should not be called!")[x*exc_detailshjawait (4 iBwith1ehstack() as a.push_>_4(_expect_okassertIs(<2_backs[-1][1], Dcm = ExitCMh /cm%0.__M__, Ek_suppressQaTI.G l ?elf t E9/t121/01@Atestuqcontextjclass Tesgobject-T/__R result.append(1 I   V"3)Q = []+~YA$SX@Y" # Registered first => cleaned up la f# 4> pNotNone}*it(m.z_zB 2wbEqual(+, [1, 2, 3, 4]0:exception_chaining# Ensure + + matches the reference behaviourK:OPraiseI( gTsaved = None async def suppress_exc(*exc_details): nonlocal saved% # 7 = M (return True :tryqasync with self.exit_stack() as 3a.push_B`_callb6Praise, IndexError)=A?Key?)AttributeE($OValuuU1 / 0gexcept*t:excrassertIsInstance(exc.__context__, /= I9 p# Innerweptions were%edU=Nonz {Oelsefail("ExpectedC, but noQ was &d"X# Check the i* =5[1]%c;/, 5  , ZeroDivision if __name__ == '__main__'.unittest.() import dis from t_module2I _opcode = )#("") class O)dTests(@.bCase):q_effect(.BcEqual(l.C5 dis.opmap['POP_TOP']), -1I!DUIA_TWOM2L(BUILD_SLICE'], 0- P1P<3PR&s(/, , 300003C V6, R"R"R $io*socket import datetime import textwrapunittestfunctools0con44libtos.paththreading from N n0supvtnntplibNNTP, GroupInfoO&3T.mock9patch try: ssl except IRError#ssl = None TIMEOUT = 30 certfile = d.join( dirname(__&__), 'key73.pem') # TODO: # -Pthe `0` arg to more commands)e conditionauth and `usenetrc` class NetworkedBTestsMixin: 1def_welcome(self)/0 = .server.get!()G+!assertEqual(str, type(-+))uLhelprresp, linesv.pPTrue(9.startswith("100 "), 71for^1 ins Olistg /rif len(+_) > 0 Z:F[0])U 3. m_activJ!, 7GROUP_PATunknown_h CsRaises(p.MPermanent<) as cm5_shortcmd("XYZZY" Xb = cm.@ion.Oonse`582new 0# gp gets a^stant influx of new. In order notastresslw #  too much, we choose a recent date0Upast.DAdt =.(.today() -delta(days=7M&dt1@IsIn #ce7[0]T >8\, strpdescrip p_check_&(x# Sanity 'desc, str)  self.assertNotIn(GROUP_NAME, desc) 11 = &pserver.mriptio>8p_check_,(# Another sanity *qjIn("Python"# With a pattern?l6PAT Shouldn't existk"zk.brrtt.baz"kQEquala, '') [def test<hs!):!Bresps6. # 215 for LIST NEWS&aS, 282uXGTITLErUTrue(.startswith("_`") or a82 "),IsInstancevs, dict+!s[]Hg _group;ult*zW5, len(result))9, count, first, lab =B&ul Z(,#b1tr'ins**)BLessR/z R'11RE?ate=;ated-y % , Ttime. 7?# S rGreaterA.year, 1995Hu".G2030@art_0$, <i# Some~sqa fieldo ionary returned by OVER / Xe$v # NNTP has 7 mandatorywsT *V.keys(),1{"subject", "from.message-id"6 "references)C:byt ylines"}e<Ev ina.values(i v, (str, type(None))QxoverS:namr.group(self.GROUP_NAME) resp, lines = self.server.xover(last - 5, 8qif len(9u) == 0:T[JkipTest("no articles retrieved"Op# The 'd'*# is not necessarily part of the output (cancelled?Part_num,Lr_dict =5[0]assertGreaterEqual(=X3OLess0 ,p_check_S\ !) @unittest.skipIf(True, 'temporped until a permanent solution'Lw'Hfound for issue #28971'@def _)!count, first k, name4`group(Bm st=KU - 10"! -",` rangem*x }(Cr, None)H ?end1j&-157 \U0 -XQ# XXX  "mage_id"unsupported by g# 503 Overview CG-ID :zAxhdrDz'subject'W^2 in*}str, typeC[1])dW_ , & 8=?qm`IsInsts6nntplib.AFInfo ifV]\-u.numberV-.sY)v, bytesR{this could excep_ally happen...pTNotIn._s[-1], (b".", b".\nDr\n""FIXME: see bpo-32128.d_head_body , count, fir`st, la name = self.server.group(GROUP_NAME) # Try to find an available article+0for_num in (s0firz e - 1):0b:tryresp, head@(artc3except nntplib.NNTPTemporaryErr>s ekif not e.tonse.startswith("423 "nFrais!# 5pNo such#" => choose another on>zcontinuUbreak5;elsskipTest("couldX suit number"ABassertTrue(  221 "),  7ccheck_ _!?, "k, body2k "0n# Tolerate running the tests from beh q virus %erE blacklist = lambda line:b'X-AntiG'filtered__<Ps = [   !in. s|&(6%)]7rm6pk tjEqual(|%, + [b''] +!) 1def_capabilitiesr[b# The a under4 implementsersion 2 and has aeS# couple of well-known w. Just sanityv that wuP# gotW%m.[_Ggs(caps~_U v['LIST'%\IsInstanceN;0, (B0, t)q <n('OVERVIEW.FMT',sD5mrGreaterk.2"_vU6, 2=18getQ(is re-emitsC commandI  b U06 TnzloginNThis test mu)st be the penultimate because further commands will be # refused.baduser = "notareal"!(pwpassword## Check that bogus credentials Vailurself.assertRaises(nntplib.NNTPError, %server.login,=$, pw, usenetrc=False)H# FIXME: We should cycorrectsucceed, butLwArequire valid details for some  where to inM%test suite, I think. Gmane is anonymous, at least asdk&thm1# oR1s. d@def _zzquit(l!):Ua# This"2 muycalled last, henc6namkcls = typeRQ6try^bq. .kfinall03cls/r = None@classmethodmRwrap_Ys(clsWrap all ! in a transient_internet() exception catcherb # XXX put a generic vers,est.support?5 (V@functools.s$@#D2pedb V#Swith }.zg[_HOSTAa preturn "peq.L;dirt"pif not %p.starts!(''vcontinu[F = getattg,S<&lBableF(b`# NeedTa closure so5 remains boun,its current/# s,O)*_statemen'is_connected(M1has4s, 'filey) lOj.help(=C (OS1EOF Ft3Tru.QCLASS=, timeout=TIMEOUT. v([ ,P +'V TgSS(self.NNTP%_HOST, timeout=TIMEOUT, usenetrc=False) as server: u.quit()self.assert?)(is_connected()) NetworkedNNTPTestsMixin.wrap_methods()EOF_ERRORS = (EOFError,) if ssl is not None1+= (ssl.SSL9 class (, unittest.RCase)mT# Thi supports STARTTLS (gmane doesn't"w = 'news.trigofacile.com'IGROUP_NAME( frp.lang.python'=PAT&1*' Ip@CLASB @k(def setUpCC(cls.requires("n"$Dwith.transient_internetR.\<2tryR Bcls.b0 = > MH  <vexcept VVraise#@Skip'(f"{cls} go@ eC on Ying "m Pf"to QD_!r}")tearDown!ifR_ Fv$% @ skipUnlessg4, 'D SSL /')p@_SSL%st"): # Technical limits for trppublic  (see http://www.aioe.orgj# "Only twopcurrent ions per IP address are allowed and]# 40052day.c-ed from eachP"."Enntp?com #getattr(kalib, 'QSSL',8C# Disabl s it produces too much data q_list =C B7the) will already be encrypted.RstarttlsV@ # #a-n0ed {@s us>@a lop (or so@mockdit). #_SIO(io.RawIOB"""A raw IO objectK< command`receiv5 nd3Rcesse-by a handler. The can push responses whichBthen[aIOP3.""O__init__(z,e.__init__(selCf) # The channel from tUlient&self.c2s = io.BytesIO(F/toD?s2cDdhandler = q.start(2c2s.readline, push_data) ?@def #Aable5!):return True-Owrit-n[!, ya"""Push (buffer) some% to sendtE.""" poss2c.tellvseek(0, 2!e(W97pos)0"7, b)1"""*Fs uskb.process_pendingWlen(bCinto?bufPwants4 a response2b =O(6uf)An = buf[:n] = b@n make_mock_file(sio = _NNTPServerIO"Q# Using BedRWPair instead ofandom ensuresqF`isn't -. ^(sio, sio4) class MockedTestsMixinO# Override in derived 6!es~ _g = NonQsetUp*Yruper().hsE(OtearDownL O3del NlcX, *args, **kw \ L.u_1 = i4 = = nntplib.LPBase(L, 'test.''DUWithReaderMode(Wmspermode=zt2v1HsD"""A for RFC 977@welcp= "200 C e ",>in_body = Falsemallow_post= ._c" =nine self._push_data = # $logged_in = False user_sent # Our welcom6shandle_1() Udef _decode(} , !):return str( , "utf-8", "surrogateescape"Sprocess_pending[U0if m.in_bodynrwhile Truebline ==P_read%()$pif not E! 80.ap(B_ == b".\r\n"gYbreakf+trmeth, tokens_callbacC2"(*2 , ,= ofinallu0ff = Non8i*!  B.  0.endswith("raise ValueError("doesn't end A \\r\\n: {!r}".format( >=Y[:-2]Scmd,  %k.split# = getattrI.Br, " _" + cmd.upper(), H@1if C!is]%{unknown?elso except Eion as ^+command failedn from g !*y *6:V = []aexpectL""""Flag that the cli:2is 6ed to post a requestQ5"""y~| B"""Push some binarye `kO5Z, lit`a0ingHeral` li,textwrap.dedentY#.join(litrs()) + 5)!enD''W self.push_data(lit) def handle_unknown(self):".push_lit("500 What?"BwelcomeB P*COQUIT@ "205 Bye!ODATE> 111 20100914001155HQGROUPIw, group"if == "fr.comp.lang.python";?211 486 761 1265 B)}OelseP 411 No such{}".format(e2HEL5""\100 Legal commands) authinfo user Name|pass Password|generic EKdateIhelpReport problems to h7 _223 0q 30SArticle Foun2NEX 7 <668929   retriev~ `?LAS`4b Ib, actionaq, param #if%g T215 NxPs in " "high low flags".7  0R52340 02828 y9.announce7C1153 m0993 mB}free.itP68002 J1C1254 O0760}.learner>$00O0001Iotw.bbs%30 &elkACTIVE"ifM*distutils*' self.push_lit("""\  215 Newsgroups in form " high low flags"Bgmane.comp.python.distutils.devel 0R14104 / mN6cvsA0 1LY.""")fYelse:?sel+S elif action == "OVERVIEW.FMT"Order of fieldoverview database.zSubjectrNFrom?DatDMessage-ID2References?Byt?LinXref:full[ NEWSGROUPSY assert param is not None`#if!Clang Q8'pDescrip}d"B q\tThe P Puter ?uagD 9*y.announce\tA ments about t (Moderated9./V5{,++   '501 Unknown LIST keyword') def handle_NEW_(B!, 8,ne_str, tim )# We hard code dif t return mLs depending on pd~`# arguA andqv syntax,Aif (` "9#20100913`'w082004"C wasNRFC 3977Wat (NNTP "v2> 230 listnewsarticlesTv2) created after Mon Sep 13 08:20:04 2010 follows 4 R ^Sat, 19 Jun18:04:08 -04008<4FD05F05-F98B-44DC-8111-C6009C925F0C@gmailIhvalf7$ort$1@h\t7103\t16AQXref:8 .authors:57J8\tLookinga few good bloggersOLThu, 22 Jul09:14:14 "\t<#A29863FA-F388-40C3-AA25-0FD06B09B5BF@gmail.com>" "\t\t6683\t16#n# A UTF-8 overview line from frp.lang.python&"59\tRe: Message d'erreur incompréhensible (par moi)"\tEric Brunel .IMpexpect_(9=5R440 P not permittedpIoassertVg kR240 A received OKi5Qosted! =v SIHAVE!me?_id&J I andk == "Subject: I am just a te*Content-Type: text/plain; charset=; format=floweB_-ID: 7""" @This. ..Here i s a dot-starting line.  -- Signed by Andr\xe9."""#psample_<ccle = head + "\n\n" +Bbody9def handle_ARTICLE(self, message_spec=None):)if@ is "!G.push_lit("220 3000237 <45223423@exu.com>")a,elcO== "7w0q%/4"b)h/seN 430 No Such ArtiWFound^ereturn1 m\=.") OHEADF1c/1 M4 OBODYF2c2NAUTHINFOcred_type, dataW_logged_in '502 Already L2F In'n == 'user'U2if uZ_sent '!'482 User CredentialGSent>,el T381 Password RequiredI7_ = True elif cred_type == 'pass': self.push_lit('281 Login Successful')2_logged_in = True#Jelsec raise Exception('Unknown {}'.format( )) class NNTPv2Handler(1)lb"""A h! for RFC 3977 / "v2")""" 3def-_CAPABILITIES( Q#fmt = """\6101 Capability listVERSION 2 39IMPLEMENTATINN 2.5.1{}'9HDRLIST ACTIVE$.TIMES DISTRIB.PATS HEADERS NEWSGROUPS OVERVIEW.FMTR :POS"RN $.?pif not 2.  \4fmt0'\nDAUTHINFO USER')oLS8AMODE7, _ ( sent despitehas been advertised')KVnmessage_spec=None~Return:!_X;5CapsAfter c that allows p only aW l>1b'480 You mustuG in.[super().%  ModeSwitchingqserver starts in transit mode__init__!_s}ed = False 4HcUaq"{}p c"if$a] AV -= g, whatgassert  1and-xqreader'X. B7'200 Posting}1v2TestsMixin: def setUp(self): super().!) .test_welcome5elf.assertEqual .server.4 , jf.handl aauthinfoBilf.nntp_version == 2cIn('AUTHINFO'}a_caps)5plogin('quser', 6pw'0T# if [ is gone from Z we also know that getcapabilities(Mhas been called after as it should?Not9=dat`resp, " =_9"111 20100914001155" 5UnPtime. (B, 9, 14, 0, 11, 55)#LquitdBFals.sio.closed Q"L 205 Bye!?Truv {=help ,  {00 Legal commandsU1, [4' v  Name|pass Password|generic ',Hu Report problems to k Cp?, "j_=rver.stat("< 45223423@example.com>") self.assertEqual(resp, "223 0 retriev Kxwr:") ?las&< 4o"4z  adescri  ."comp.lang.python 9, "The P- >Puter BWuage.@/{x<| esLs/s(Uf'215 Dws in form "p ?".'/As, {F:y ,A}sh* P> .announce": "A ments about t (Moderated)"? }(self): resp, count, first, lagroup = self.server. ("fr.comp.lang.python") O1assertTrue(c.startswith("211 "),|7cEqual(?761%O1265%?486%/, Raises(nntplib.NNTPTemporaryError) as cm:# T Qg.develWexc = cm.exceptionS r@exc.vIonsez411 No such 5"),FF!) 'def test_newnews(z)# NEWNEWS  [20]100913 082004Qpdt = datetime. (2010, 9, 13, 8, 20, 4[, ids"V", dt@expected = ("230 list of articles ( v{0}) "4@creaMafter Mon Sep p:20:04 follows=).formatM.J_versionh.r)jids, [("7"'[+Message-ID: ") def _check_article_data(self, lines):*..assertEqual(len(%J, 9)( WBhead,O[:4], Cbody,<-4:- x[4], b"Dtest# ARTICLEresp, info = sserver.(<"220 3000237 <45223423sDart_num, message_idm! =o;m]"j  >E numB4CI4IY IM/idH3Y0SS0MENon-existent RBwithRaises(nntplib.NNTPTemporaryError) as cm 7"\r\n':Subject: I am just a  e\r\n'  ), ascii(data))  self.assertTrue.endswith('/b'This is just a terticle.\r\n'0P.Here1a dot-starting lin1E -- Signed by Andr\xc3\xa9s 1def`_head(!):e# HEADresp, info =qserver.<7bEqual(9"221 3000237 <45223423@example.com>"Eart_num, message_id,1s =o;mU +]"?p_check_2cle8sg8E num<4Bjz@C4CY CJ/idBS0MS0GENon-existent ORaises(nntplib.NNTPTemporaryError) as cm"7"Subject: I amg5  self.ass ertFalse(data.endswith( b'This is just a terticle.\r\n'0P.Here1a dot-starting lin1E -- Signed by Andr\xc3\xa9s), ascii1)) 1def_body(self):e# BODYresp, info = +.server.<)(assertEqual(9"222 3000237 <45223423@example.com>"Eart_num, message_id,1s =o;mU ]"?p_check_2cle8sg8E num<4BjC 4CY CJ/idBS0MS0GENon-existent ORaises(nntplib.NNTPTemporaryError) as cm"7"Subject: I amh5 ?Tru b'This is just a terticle.\r\n' pb'.Here1a dot-starting lin1E -- Signed by Andr\xc3\xa9s), ascii(data)) def check_over_xresp(self, , qviews):6 .assertTrue(*.swith("224 ")C)7Equal(len(`6, 3,rart_num& =?[0]Q6&57Kws5, {G"from": "Doug Hellmann ",]psubject` Re: ANN: New Plone book 9 strong Python (and Zope) themes throughoutb@date_Sat, 19 Jun 2010 18:04:08 -04007message-id= <4FD05F05-F98B-44DC-8111-C6009C925F0C@gmail.comreferencesNhvalf7$ort$1@Ih#B:byt8L7103:V,16@xrefpFnewsa acomp.pP.authors:57"},A$ w1w-!["], NoneR2R7]O"QM d'erreur inréhensible (par moi)"}1 = Gqserver.,v(57, 59"R O A # In NNTP "v1", tewill fallback on XOVER g f(sample_post = (~`b'FromDemo User" 2b'So: I amE 1'Content-Type: text/plain; charset=UTF-8; format=flowedF5-ID: @def _check__ihave_sub(, func, *args, file_factory):@q# Firstprepared N with CRLF endings4:s x_v1 = 8+ ((A+),u = NoneYaresp =%(*f H("a# ThenGsame"normal" -+y should b# convertnANNTP>Q and .o5.replace(b"", b"\n"Mpreturn    success_3 Wta bytes objectY4A+V =QT.\(, -'# _array=Uq#a9@io.B/IO,n iterable of,!ediU<)%'(bk!(b.split)keepends=True).%f^O" Dnon-*>OFalsihave_sub(func, *args, file_factory=iterlines) self.assertEqual(resp, success_!) .def test_post(8!):Ja.checka_ihave%.server.6 , "240 Article received OK"handler.allowSing = FalsevQwith {Raises(nntplib.NNTPTemporaryError) as cmQample{ l.cm.exception.-Uonse,_ "440 Postnot permitted"gCh7i%35itransferrl"? ("",s?3>too_long_V9dt = datetime. (2010, 19, 0, 0bAData newnews, "comp.lang.python", dt) class ,v1Tests( !v2Mixin, Mocked un0st.CCase0"""As anZB v1  (no capabilities)."""b_version = 1G _=O2v1H 8Lcaps# =-8get(~aps, {}# o4ntp?, 16ioPmentaLk, NoneB222\ 'VERSION': ['2', '3']2'IMPLEMENTAT*0INN,]2.5.10AUTHINFOTMUSER"0HDR i@LISTp'ACTIVEb `.TIMESDISTRIB.PATS' 'HEADER0NEWSGROUPOVERVIEW.FMT'],  'OVER': [], _'POSTOREAD2%})Aself.assertEqual(server.nntp_version, 36implementat=&'INN 2.5.1') class CapsAfterLoginNNTPv2Tests(MockedMixin, unittest.aCase):0"""s a probably <B v2 with capabilities only a~ lQ.""" OA = 2handler_=H$F@def `_caps_n_n_nhwC<, {.Q'mquser', ?pw'In('VERSION', yIhSendReaderMBWith BMode,ASames as forPbut wll NTTP to send MODE aithat isn't in%mode by defaultSwitchingwe_are_in_r$_xconnect AMisc(Qidecode_h |&gives(a, bz~Jlib.S a);u6Ov"" , ""ka plain K", " 2extra spaces 8 >=?ISO-8859-15?Q?D=E9buter_en_Python?=O1DéB en =?utf-8?q?Re=3A_=5Bsqlite=5D_dl=C3=A8me_avec_ORDER_BY_sur_des_cha?="+/F " X@Enes_de_caract8res_accentu09es KRRe: []`lème  BY sur des chaînes de lcères hNéesb=?UTF-8?B?cHJvYmzDqG1lIGRlIG1hdHJpY2U=)de matriceh# A natively p-p (foundthe real world!Message d'erreur incompréhensible (par moi)"<? "B)parse_overview_fm# The minimal () response li= ["Subject:", "From:", "Date Message-ID:", "References/`:bytesB:lines"]4self.assertEqual(nntplib._parse_overview_fmt(=)q["subject_@from@datem idr ")# The minimal response using alternative names7b = ["S L.BKKLK:LVariations in caF4AFROM 2DaTQBYTESB4First example  RFC 3977;o: , "Xref:fullG"Distribu&p, "xref%d("]oSecondc OFULL&A classic?INN M `1]) +def testl(self): # fmt = nntplib._DEFAULT_OVERVIEW_FMT + ["xref"] # First example from RFC 3977&lines = [? '3000234\tI am just a terticle\t"Demo User" '>\t6 Oct 1998 04:38:40 -0500\t@45223423Be<45454qnet>\t1 B17\tXref: news.` misc.:U363',>overviewzdparse_(;,)A(art_num, fields), = 2&self.assertEqual66234Q +X5, {Nsubject': '30 8@date8 1message-id7< 4references4  1B:byt- K,178*}# Secondj; here the ""  is totally absent (including#8header name) and comes out as None1'\tep!['&!],}GThir is an empty string, while ""#!a single space. zv'], ' '~A'') 1def _%$Ptime(B!):#u'gives(a, b, *c!0.assertEqual(nntplib._parse_datetime(a, b),  -. U(*c))4 # Output of DATE command!gives("19990623135624", None, , 6, 23, 13, 5 4`VariationsTE", "XR;"0 ;O2009def test_unaself):%# Test non-legacy mode1) with a ey, M, d, h, m, s,-`_str,  uyAdt =&  J5.assertEqual(h /dth (o(, Falsev+ORu =O20000, "= 1=5, 1, 2, 39`1006059v010203"v9# 2# r(q( 0 //0017"2011") P_6(WS (RFC 977/# ]_, TruL 1;_, "00"(y, M, d, date_str, tim G): dt = date . (y, M, d)(self.assertEqual(nntplib._unparse_<E(dt, True),Bu (2 ugives(1999, 6, 23, "990623", "0"/F2000//00/1/5, "100605]!@unittest.skipUnless(ssl, 'requires SSL support'@def 5S_ssl_(ET0(hasattr[, 'NNTP_SSL')) class PublicAPITests(CCaseap"""Ensuthat the correct values are exposed in"p] API.""" module_all__ibute_A_ target_api = ['TError SReplyA=Temporar,IPermanentBProtocol+AEDatadecode_header']if ssl is not Noneq.append(Fo4set.B0), Q%$MockSocket% ! involving a mock s>r objectU(Qwhere+_ServerIO file.fenoughH2_ = ?E_gcheck_constructor_editions(#', handler\ uexpectedHPtype,:msg5`login=, password"):{,_,_ Preate0nec(address3outWvreturn ,()|t=los\nonlocal _c-dY+! ="@make(/T, mod$* =(/&"_,N = \_cbC2sO #P = False,swith patch('E'*ck E), \O RaisesRegex( (M('dummy', user=login, password= 3) self.assertTrue(socket_closed'for f in files:?F C$f.>'def test_bad_welcome(4)G#Test a bad # messageDgclass Handler(NNTPv1J*B= 'Bad Wt'J} .check_constructor_errorditions(1Uk, nntplib.ProtocolE;,.!) Bservice_temporarily_unavailabl5 5 5b"R400 Sa7ATy8permanent858755028a8AP8qcapabilitiesv ( respons|!h_CAPABILITIES{push_lit(_q = '201;!y~ADReplj7ieslogin_abortedauthinfoyCvt@e.comfpython AUTHINFO{, *argsY%  503 Mechanism not recognized3 2 ,o$, \2) K byBtextA"""Bp encryp4 and actual SSL module"""fmRwrap_el<, *jpreturn %p @unitN .skipUnless(ssl, 'requiresjsupport')MockSslTests(MockSocketTests): @staticmethod def nntp_class(*pos, **kw26areturn'lib.NNTP_SSL-ssl_context=bypassI1 ] LocalServer(unittest.CCaseusetUp(selfpsock = 2et.!()@port up `.bind_ (*'w.listen=k .background = threading.T (imqtarget=7Qrun_sq, args=r',)t7elf^l.start~addCleanu0ejoin) v0 = #(s`HOST, , usenetrc=False).__enter__x Y.xit__, None,,# Could be generalized to handle more commands in separate sAwith_[client, _]ock.accep];ExitStack() as ct X.3=(m%Der =H3.makefile('rb'BV.sendall(b'200 ) ^jy\r\n'vwhile TruePm:0er.Gline$@if c+= b'CAPABILITIESoW3 b'101 Capability p:Y4VERSION 2) rSTARTTLQ.I O(el c [er.clos_T 0b'382 Begin TLS negotiation nowIcrsl.SSLC/.load_cert_chain( eL]`.wrap_0*etd", `_side=d&2g;a AQUITn a5 Bye!4]break?els raise ValueError('Unexpected {!r}'.format(cmd)}@<skipUnless(ssl, 'requires SSL support') def test_starttls(self):!pfile = `.nntp.Isock2elf5^vY# Check that the ;et and internal pseudo-t really wereb# changed.assertNotEqual(@,222 4newQis anq&onkIsInstances(ock, ssl.SSLSocketvdrying Y when it's already active failsRaises(ValueError) if __name__ == "__main__"'@unitD.@() -BEGIN PRIVATE KEY- MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDDe3QWmhZX07HZbntz4 CFqAOaoYMdYwD7Z3WPNIc2zR7p4D6BMOa7NAWjLV5A7CUw6hZANiAAQ5IVKzLLz4 LCfcpy6fMOp+jk5KwywsU3upPtjA6E3UetxPcfnnv+gghRyDAYLN2OVqZgLMEmUo F1j1SM1QrbhHIuNcVxI9gPPMdumcNFSz/hqxrBRtA/8Z2gywczdNLjc= ->ENDCertificateSBData +Version: 3 (0x2Serial Number0482:ed:bf:41:c8:80:91:9Signature Algorithm: sha1WithRSAEncryptionVIssuer: C=XY, O=Python Software Founda3 CA, CN=our-ca-serverHValidityNot Before: Jan 19 19:09:06 2018 GMT1After : Nov 281)271tSubjectL=Castle Anthrax localhost-eccX Public Key InfolRid-ec*Ke -Key: (384 bi":publ04:39:21:52:b3:2c:bc:f8 27:dc:a7:2e:9f:30Bea:7e:8e:4e:4a:cE2c:53:7b:a9:3e:d8:c0:e8B4d:d4:7ao4f:71:f9:e7e8:20:85:1c:83:01BP82:cdfe5:6a:66:02:cc:12:65:28:17:58:f5:4 cd:50:ad:b8:47:22:e3:5c:57E 3d f3T/76e9:9c:34:54J fe:1a:b1:ac:14:6d:03:ff:19:d0c:b0:73:37:4dw%37B%ASN1 OID: secp384r1$NIST CURVE: P-384"X509v3 exten's X509v3 S ubject Alternative Name: DNS:localhost-ecc" X509v3 Key Usage: critical'TDigital Signature,7Encipherment4[Extended-d (\TLS Web Server Authendtion, kClient MuBasic ConstraintsCA:FALSEHSh  IdOfierf,33:23:0E:15:04:83:2E:3D:BF:DA:81:6D:10:38:80:C3:C2:B0:A4:74xQority6z keyid:9A:CF6E:EB:71}DB:3C:F1:AE:88:6B:56:72:03:CB:08:A7:481DirL/C=XY/O=Python Software Founda CA/CN=our-ca-s Oserial:82:EA41:Ci91:9B 0bInformfoAccessvCA Issuers - URI:http://testca.p C.net/pycacert.cer}OOCSPLZocsp/CRL Distribu+"Po .tBFull  Qrevoc/B.crle@ AlgOhm: sha1WithRSAEncrypy3b:6f:97:af:7e:5f:e0:14:34:ed:57de:ce:c4:85:1e:aa:@84:52:94:7c:e5(Pe9:9c8b:ad:b5:4d:16:acdH81:e@b8:a2:e2:50:2e:cb:e9:11:bd:1b:a6:3f:0c$d7:7b:67Qb3:43_pd:c6:87h 6e 47:78:ef:2f:8c:86:e8:9b:d1 43c1:7a:91:304:d6:9f:41:8b4P0b:24 78I11:8a:fc:2b:cd:c9:13:ee:90:4fIp3:51:a3@ 9eX(06@8:f5h 12Pf0:f2 40f5:96:c2:5d:cf:e1R'ff@ bfhPeb:74 c221:3e:27[ f1Raf:2c:623P00:c8eP1b:c3 8d89:e7:4067:1a:33:fb:c0 96 36 25tP82:d8 270f:f7:69 ff''9210:d3:d2:0a:db:65w af@ ebP76:f3d 7a[ 9e 3315:42:06"d6:54:49:fa:84:a7:0e:1d72:ca:19:@ 8eaa:a4:02:3c:f6:1cI8 59Pb0:927 c8 ba.P03:4eC f2 451e3:35:a8:b1:68:58:bP3b:20@eb -BEGIN CERTIFICATE----- MIIESzCCAzOgAwIBAgIJAILtv0HIgJGeMA0GCSqGSIb3DQEBBQUAME0xCzAJBgNV BAYTAlhZMSYwJAYDVQQKDB1QeXRob24gU29mdHdhcmUgRm91bmRhdGlvbiBDQTEW MBQGA1UEAwwNb3VyLWNhLXNlcnZlcjAeFw0xODAxMTkxOTA5MDZaFw0yNzExMjgx OT5MGMB`RcwFQYHDA5DYXN0bGUgQW50aHJheDEj MCEGCgwaUHl0aG9uIFNvZnR3YXJlIEZvdW5kYXRpb24xFjAUBAMMDWxv Y2FsaG9zdC1lY2MwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQ5IVKzLLz4LCfcpy6f MOp+jk5KwywsU3upPtjA6E3UetxPcfnnv+gghRyDAYLN2OVqZgLMEmUoF1j1SM1Q rbhHIuNcVxI9gPPMdumcNFSz/hqxrBRtA/8Z2gywczdNLjejggHEMIIBwDAYBgNV HREEETAPgg1sb2NhbGhvc3QtZWNjMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUE BggrBgEFBQcDAQYIKwY-@HAwIeDVR0TAQH/BAIwADA=Q4EFgQUMyMO FQSDLj2/2oFtEDiAw8KwpHQwfR0jBHYwdIAUms/PbutxPds88a6Ia1ZyA8sI p0ihUaRP/ R o,gb MIGDBAQR3MHUwPAMAKGMGh0dHA6Ly90ZXN0Y2EucHl0 zdGVzdC5uZXQv GNhL3B5Y2FjZXJ0LmNlcjA1i wAYYpaHR0 cDovL3Rlc3RjYS5we5feLm5ldCrvb2NzcC8wQwYfBDww OjA4oDagNIYyRQPcmV2 =d5jcmwwDQYJKoZIhvcNAQ ADggEBADtvl69+X+AUNO1Xft7OxIUe qoRSlHzlzumciIuttU0WrK+B6rii4lAuy+kRvRumPwyi13tncrNDFq3Gh6xurEd4 7y+Mhuib0UOMwXqRMOkU1p9Bi5sLJJt4hhGK/CvNyRPukE8UM1GjxJ7WBkj1QRKv 8PJxQHj1lsJdz+E4/78Q63QvwiMhPif18fKvLGKCMQDIlhvDfo1xiedAtWcaM/vA i5YMNnglJ4LYJydSD/dpzf8rkhDT0grbZe2vkOvbdvOKehOexjNXFUIGE9ZUSfqE pw4dFHLKGY4rqqQCVDz2HCOBellUsJJlcsjlup8DTjDyTUWF4zWosWhYuTsgo+s= -----END CERTIFICATE----- """Unit tests for the copy module.""" import copy Creg tweakrefabc from operator (le, lt, ge, gt, eq, ne 8unittest order_comparisons = = equality&S ;O/+ @ class TestCopy(.$ase): # Attempt full line coverage of copy.py top to bottom@1defw_exceptions(self):_c.assertIs(QbError,]e ).True(issub ;Eo)) # The copy() method def test_copy_basic(self):#ex = 42@y = -.5(x)7.assertEqual(x, y)g:/fclass C(object__init__[, foo%)U`.foo =!D{D?return CdHFC(42 Ay.__V__, x L<y~-DregistryhH new__(clsFbobj = 5.__0Q0objoO5objqpickle_2@(C, \&,)w9Raises(TypeError,', Breg.k V_C, Cl 0reduce_ex <o, protc.append(1-c!""#__b2 i&< fail("shouldn't call this"mec = []b *]aIIs(y.oc, [1]0d'ZmOcant getattributelOname0if .startswith("I"0rx$ Ac|(F"'Zm8.v E # -specific 5xxx s`Natom ^&ic#Apassq (NewStyle 1+f(b "SWithMeta$(m =abc.ABCEs tests = [None, ..., NotImplemented, 42, 2**100, 3.14, True, False, 1j4"hello", \u1234", f.__code__5b"world", bytes(range(256)), 10), slice(1, 10, 2)JNewStyle, Classic, max, WithMetac]for x in tests: self.assertIs(copy.(x), x) ,1def;_`_list(7)Jxuv1, 2, 3x@y = 3RM uqEqual(ym];NotmfF _tuple)5 O#(6#fO, []A ?dic{"foo": 1, "bar": 2}?H{fF /se\FDZ<`frozenv_ {0 H?_arraytfb'abc'iD<uoFinst_vanilla & C__init__1W, foo%Pfoo =!{D%eqB_otherDvreturn K!= +E.fooR=FC(4270q"=t )class C:   def __init__(self, foo): `.foo =! DCcopyD?return CdH)C#eqA, otherH=+SRx = C(42d0assertEqual(.(x), x) =Ptest__inst_getAargszclass C,CQ3z|X,#X?newWK(intnew__(cls = int.__. [&3getBGG@y = } IsInstance(y, C#$0y%PIsNot>x>  xk S!exm*u/ex(), {'foo': VEfoo}lo(;Hfoo=,_state'Hwo{"foo"YJ y(x), x)  def test_copy_inst_setstate(self): vclass C@__init__1W, foo6%M`.foo =!UDwHJ #["foo"]S%eqM_otherMvreturn != +Rx = C(42)0assertEqual(?.(x), x) + ^g^ge_^K'#Li0# S with boolean value is false (issue #25718 60.0# The deep7) method9 a_basicbh~%42V@y = M.6/(xy9\_memon6# Tests of reflexive objects are under type-specific sections below. p!is|s only repeti-$ofY2[Fx, x!bIsNot([0], x[0]cAIs(y"Ly[1]fTbXlXXX Note: e's no way to6 TypeError coming out of'# c) -- this cant happen when an extensionAPmodulfines a "" that doesn't formally inherit fromE3` Meta(kEpass;+aC(meta =72 so(C), C'Ff{2 C(1Y[=NoneswC; eepcopy(x)  self.assertEqual(y.__class__, x ") 1/ 30foo-Qfoo) ( def test_deepcopy_registry(?!):&Rl C(objectG__new__(cls, b<#bobj = B.0&obj.foo =J`returnIqpickle_ 2@(C, \&,)wx = C(42pRaises(TypeError, ).26, x7Breg.o V_C, C':y =E/(xduce_ex #re<!__>{, protoSc.append(1=%""nr#__b_XH fail("shouldn't call this"mec = []b2eIIs(y9oc, [1]o .  buOcant  getattribute|GnameT0if .startswith("Y"04r$ Ac(F2'v}D .vI # 2-specific cxxx() methodsoatomic{*icaApassyNewStyle 1+f(n "'sNone, 42, 2**100, 3.14, True, False, 1j,"hello", \u1234", f_ode__52, CV, max*for x ins1Is(1(x)(=lis[[1, 2], 3IsNot(x, y) se8lf.assertIsNot(x[0], y[0]) def test_deepcopy_reflexive_list(self):,0fx = [].append(x)@y = J.Sfor op in comparisons:<crRaises(RecursionError, op, y, t4(6, y>Equal(len(y), 1&empty_tuple(? #(] ;AIs(x l[1, 2], 3u-5 T_of_immutables6()"? 6[],C+ ?dic{"foo": v"bar": 3}"}3 x['foo'] = xoorder_OTypeXe?ity[;>?keepaliv=memo = { r] , 6@[id(!)]x$Pdont_* *f, 3, 4< # There's the entry @new Q, and V alive.  self.assertEqual(len(memo), 2) U = {}px = [(1']y = copy.deep @(x, <)# rFy, x# Tuples with immutable contents areDfor l.ddef test_?_inst_vanilla(%):Rvclass CC__init__1W, foo6%M`.foo =!UD%eqB_otherDbreturnK!= +XRfC([42]R pIsNot(yo0, xIWJLwP~ xO C(3foo)4/__ Y0getOargs\zJ,?newK(intOnew__(cls = int.__. wt &3getBGqIsInstance(y, C) >KeIsNot(y.foo, x.f%oo) def test_deepcopy_inst_getnewargs_ex(self):04class C(intN__new__(cls, *, foo&*Sw = int.1)d$(`.foo =I preturn &  ,__`E(), {'foo':Qw}V#eqK, otherRF2 ==+ Rx = C(foo=[42]@y = .&(xSassertIsInstance(y, C$PEqualC?Not>0, xe!IsF ']\stateXiDe__initvR*D1getwHo{"foo"Y#/, "s?\w!, *#[]I ;N\  L0# S_ with boolean value is false (issue #25718) x = C([]y = copy.deep &(xself.assertEqual(y, _IsNotp.foo, x!) def test__reflexive_inst(!):,vclass CEpass"nE = x" (y?, yOangeWI(intr@VI(10)4P.stop )IsInstance(y.I:# _reconstruct(_stringT|C(objecWH__reduce__;yreturn "") Ky(+Is5a9onostatP1W(C, (j L!426 1.__ __M RI(M<:R!, __dict__*C__eq{, other) K2 ==0.]/E[42]%^8 <>K/F ate_setuA.upd O x = C()  x.foo = [42]  y = copy.5(x)self.assertEqual(y, 8Odeep<[pIsNot(y!, !) def test_reconstruc flexive(C!):*class C(objectEpass*fx = C(tE = x" 5$Isy!# Additions for Python 2.3 and pickle protocol 2 duce_4tupl_:!return (C, (), __dict__, iter::6\2eq_X{, other)_IA == 32 94.[[1, 2], 3]Fx, y8|(x[0], y[0y*^* NG5>  A>-CNoneSvitems()_dFF)F:("foo", N), ("bar", 3)XK\ B`R~ hb_slots_4 __Z1Is(<!, q @d $sNot(x.foo, #y.foo) def test_deepcopy_dict_subclass(self):+/0 C(%J__init__7, d=None(,if not dYed = {}t._keys = list(d.>()),uuper().d$usetitemPkey, sR60 aif key6in  .append(key0x =t={'foo':0}@y = .&(xWassertEqual(x, W_2, y J[IsNotJx['bar'] = 1 _/No "{Q_% ApassOTV[[1, 2], 3]x" = [4, 5]2mi |B(x),yl'Is(x[0], y[0 " F37n;X> %Ao_tupleu&vu tKE(.GGGy), G!,6Z 0<(M}9 2getstate_exc$PEvilS#w(object!%__G2 $(raise ValueError("ain't got no stickin' "Raises(ValueErrorp, copy., EvilState()) def test_!_function(self):"&.assertEqual(.T(global_foo), <bfoo(x, y): return x+y"^W.bar = lambda: NoneI`bar),  @deep7Gb , M _check_weakref!, class C(object Epassobj = C()Cx = ^.b6obj2y =m&(xgIs(y, udel obj^A2 % :\ AM9QtlOAdict0, _ Gtype[a, b, c, d = [C() for i in range(4)] uou[a] = b) [cd6v =p/(uNot(v, a o[a], b`Ao[c], d"len(v), 2$[$ 515,# The underlying containers are decouple> [xOPNotInEu/ 0key0%Y.WeakKeyDic?aryc_valuee'V?g __init__7, i Ui = i i!=1Q# Key0n't;Qied, gZ%^NotEqual(v, u)   self.assertEqual(len(v), 2) "' $IsNot(v[a], b" _c], d"hD.i, b.i& c]&d&_del cZ11) %def test_deepcopy_weakvaluedict(!):+class C(objectL__init__9;, i#'Se.i = iWa, b, c, d = [C(i) for i in range(4)].@u = ref.WeakVDictionary(3u[a] = b; [cd# Keys are copied, 5n't)0v ="$y.)&(uh)#No,?v, " K$(x, y), (z, t) = sorted(v.items(), key=lambda pair:8[0]Ox, axDaB/(y Oz, c^z^c^t  , }bound_method?Foom4Epass@f = Gf.b = f.m$gGf/ g.m, g.Mp(g.b.__7V__, gJg.b() global_fooa: return x+y if __name__ == "__main__"@unit .() # Check every path throughd of UserList from colles import"!gPlist_#s ," ^VTest(/p.CommonPtype2K& =q_getslicesuper().%fl0, 1, 2, 3, 4.&(l: S-3, 6W=Tu[:i], lJ+!i:+:i:]+yjWyRjS,j]=add_specialsEv("spam"u2 = u + "eggs"02, B-)rAou2 = "spam" + u  self.assertEqual(u2, list("spameggs")) . u2 = u.__radd__(UserL.*YZdef test_iadd(:!):wsuper().! = [0, 1]/Uu += 1\ ,A!, G!) ImixedcmpAu = LPtype2(k]$No$O, 2]E" + [], u.$ 2]?, 1getitemoverwriteiterN# Verify that __40__ 7 rides *are* recognized by __N!__,qclass T`.M%d-[, key(,return str(! + '!!!'q?Pnext((T((1,2)))), "0!!!"@userkQ_copyA6, 8g9vF Ou, v/Q(u), v)) if __name__ == "__main__"@unit.() """Test script for the binhex C modulebAUsesmechanism ofdpython53 Based on an original5 Roger E. M.s importIR from?(0sup02 E`BinHexTCase(9.!): NMsetU#f>1-_.TESTFN + "1"F+_+2+3Vvery_long_file~/__)"tearDownaunlink.1n $2$39 DATA = b'Jack is my hero'2st_qQrf = opef, 'wb'!f.;.occlose(h.4, 21Xhexbi2111rinish = f.readlin&f. self.i hwhile [-1][0] >=8 F6?.po17 asTrue(issub^(exc,yM1]),osivA` of %srK!._u.__> %1]2Cd7Soms require arguments; jukip them}<verify_insinterface(?Typ Mpassuv In` ?set3?xc_Bj=excz ?#kfinall g.closezEqual(leP, 0, ccounted form& pP_testy("length", "args0strbrepr")9Jdef =_driver(self, results)3: (for test_name, (given, expected) in zip(self.interface_3s, results)PW,assertEqualU, "%s: %s != %s" % (QK !) #2defsingle_arg# Make sure 0 works properly when n2 a L argumentsarg = "spam"exc = Exception(arg)% = ([len(exc.args), 1], [@[0],p%],;q@[str;0), b )D[rep#'%s(%r)'[`__class__._f!__k&)]_driver(y_multixrcorrectq<0pleksarg_count = 3s = tuple(rangev)) *zFw6sy/s)'4 + $&4/no that with no!s C is @ _yZ,.exc), ''N%O'()'D- UsageTests(unit.bCase):0""" u,T of eBs"""$raise_fails, object_6"""|6Sing '-' triggers a TypeError.j:tryDen6eptD 4eturn # W%is.B0%("' XzStype()K_catchC'N pshould ge !6DB ) Epass1- /+u +_ :a trKy: raise Exception e (object_,)?Epass40TypeError/Vretura-z -self.fail("O expected when catching %s as specified in a " "tuple" % type1)) 2def test__new_style_non_@ion(# You cannot :q a new-< class that does &inherit fromze# Base; the ability wa:possible until2'# introduc so no need to supportE it.@NewS&CS *?.(_)s(A)^( (nstring@Rais1"a "%s b yl"spam"% {0Tryz"toB an q 2# ivallowed*oni D + . _instance*C4an &Z of aB subwon't work x ~ 9Wis baz p/ if __name__ == '__main__'@unitp.0() 1 im_genericpath 9warnings with .(t.filter("ignore", "|!maup modulezdeprecated", D)BionWFZ2 MacPathTestCase(.+):0abs assertEqual(j.0"xx:yy"), Y\isabsW4 = NuQTrue((`!( ?:"))&EFalsx4foo' self.ass ertFalse(isabs(":foo")) self.ass(O:bar,:-Z4Trupb"xx:yy* )T*Q/b"b%)&-'def test_split( !): = macpath.aEqual((,+M ('foo:', 'bar' Vconky:mountpointGg8w xp:"), ('3:p/") 2k Nbkbl-b" /b'95', zpbq/b'r-b"ACi w=(b'3n8Ljoin5[ E0('ab'), ':a:b'v1:2 Me:4:+ :a1/a:0`_0^]+1, ' 1ZC, 'c?b:c4+   :b/o'a', 'b:'), s'b:')  self.assertEqual(join('a:', * 2 b'a', b'b')O:a:bf?b':5#k:7:- :u#b'4aue 3d0.. ,4@_gc_a:b:c7-?8":buIbbdef test_splitext(&): = macpath.+$ "(":foo.ext"), ('/')=A0foo62DG@ =2G@7EC:1{0barw<Cbb$b'E ; #b"3#b'J,C @<0extCJC:HF=4JA.barFmismoun> l(ismount("a:"), True) self.assertEqual(ismount("a:b/OFals0`]Z1b"a1/1b!b"\def test_normpath(%): ` = mac".$3 "1O":a"K _1::c3ab:b:c:::d7dkxRaises(_error, P, "a:w@!b:C9n(-/b3D 31Z , c (*)@*ASe class MacCommonTest(bgeneri`, unit!.+CCase2 fmodule0 .@_rel"Hs = None if __name__ == "__main__"nP() # w the Unicode versions ofal file funct # open, os. Pstat.qlistdir re Amove $mk $ch rmdir import os %sy warnings fromFSdata FRalize"60supi A[]'1_abc', t2_ascii3_Gr\xfc\xdf-Gott4_\u0393!b590ac-c1 2555417\u0434\u0440\`u0430\2!41 3 43 39435', '6_\u306b 7d$937_\u05d4e>15e7 651.8_\u66e89b9 05J2309\s393\xdf,# Specific code points: fn, NFC(fn) and NFK ll different10_\u1fee#fdZ ] # Mac OS X decomposes Uniknames, using Normal Form D. # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html # "However, most volume formats do not follow the exact sp ation for # these nA0s.  example, HFS Plus ua variant of # in which U+2000 througFFF, U+F9 FAVU+2F8 #D0 artdd." if sys.plat != 'darwin':Afile.extend([D $- a$V0'11 38 3d33d4.!2!0a8\u030Y 3dA 8', # == NFD('+ R)1'13R2'30X 8e9@ab',z$ R/KCS40e9b!c1d cf dddebw0'15{T\ufad#!rk&\uAux 20o "lA2003DA:4='81A'!00C@020'!' n'He0') ==9"# 81830]) TIs it-friendly?9not os.path.supports_u_8G`sencod=r0get#dsystem( 2try6@for 2 s#.D5e(fiLUexcepEfeErrorCraise unittest.SkipTest("only NT+s with "j"3 E @ing"dEclas@File}%s(RCase)Gp = set( s~_q= None 0def/sUp(selfH9 ios.mkdir(r.TESTFN_!OhExistsL pass  self.addCleanup(support.rmtree, TESTFN) 8 files = set()or name in [': > = os.path.joinwg,<Pnorm(.)aAwith open, 'wb') as fi,f.write(++'\n').encode("utf-8"]qos.stat0 w, " =&Adef !F, s)&ifval_formareturn?`alize(D.N/PV.sx_apply_failur>Q, fn,S,=oexpected_exception=FileNotFoundError=`check_)dW=TrueassertRaises(rc4fn(X5excnU = c..-:if `hEqual(\8` "Func '%s(%a) fEed "kO "5bad%Ethe : %a" %H `(fn.__`(__)Dtest sH# Pass non-existing Uni s all over eplace.f"not_" +"A"} ,+,/_chdir0/rm0_emoveaGlistc'pys.plat# == 'win32'# Windows is lunatic. Issue #13366_e = NotADirectory FelsewK ?=f =fwf.closeG#s.O a# SkipA  on darwin, because@ doe!rm21 to# NFD (a variant of-Z). NoElename to NFC, NFKC, # 6D in Python is useless, because darwin will normalize it later and soOopen(), os.stat etc. don't raise any exception.9@unittest.skipIf(sys.platform == '', 'irrelevant 2 on Mac OS X')N1def_q(self):files = set.> Tother!`for nf/9P['NFC2NFDKGKD']nR|t@nf, } ) ] _sx!-=+s0ame3$u._apply_failure(f, name`,/_chdir0/rm0_emoveaGlistc;# Skip the'B_ euses aa differentM5tha@:NFD.:oVs are= even if wesL G'J$ ?sf0#with warnings.catch_(F\.simplefilter("ignore", Deprec^WR @f1 =Support.TESTFN.encode41get<Qystemfing())P/f2L (s)os.path.join(s{3, f'f2?elf.assertEqual(sf0, sf2, "%a != %a" % <len(f1), A2)) / rea QS "3os.=*v, "tmp"#| directory0dirZtG'Gr\xfc\xdf-\u66e89bQ'.-temp_cwd( (c, 'wb') as f6\f.write(/ + '\n')w"utf-8"7os.access8,os.R_OKv() class UniNFCFileTests(i_form = 'NFC' class UnicodeNFDFileTests( ): normal_form = 'NFDG%KC7H/KCI Kdef test_main(support.run_unit!( ,&NF <) if __name__ == "_2__"P() im asyncoredbase64email.mime.text from sessage HE*M'PB*pbody_en>B as _( xTutilsDhmac esocketHmtpd 4lib$io %syU5timUselecUEerrn<DwrapLthreading hAs, mock_H&..`HOST, #v46sys.platG= 'darwin'"# .poll returns aPOLLHUP at the end of sR# on U, so just ignore it#"handle_expt(self(2pasKs.SMTPChannel.67 = 0 Vserver(evt, buf, [ .listen()sevt.set2tryconn, addr =Ed.accep, ex  .6out>Felseqn = 500|ePwhile and n > 0-!qr, w, eV.`([], []0Jif wFpsent = 4.send(buf8&Pbuf =[05:] fn -= 1MScloseBgfinallFs"GvrGeneral.bCase):r n G|OValu\0h  [R1_debuglevelR220 Hello wosrld") psmtp = lib.SMTP(.set_debuglevel(1with support.captured_stderr() as :ovl.connect(HOST, self.F\&Glose expected = re.compile(r"^O0:",MULTILINEObassertRegex(.getvalue(), ^!) xdef tes0_2()mock_socket.reply_(b"220 Hello wos-2^ssg\d{2}:\.\d{6} 1 ",H?re./ # Test server thread using the specified '`class Rging_B(rv_evt, client !(-6tryif hasattr/ect, 'poll'A_fun = asyncore.28FelseX8 4"OE1000EVwhileb_map and n > 0do(0.01,:oa# wheno.versation is finished, it will@7seti,@it'sTn ok to kill B'if?.is_set(oj+.cWVbreakIbn -= 1rexcept @.timeout:pR4jfinall(no# allow some `0 foeiresult3.sleep(0.55vG_allm2MSG_BEGIN = '- MESSAGE FOLLOWS P-\n' 6:END40-- :2-4 # NOTE: S objects if@s be.are creaa non-defa! # local_hostname argumentNIconstructor, since (onsystems)wPFQDN Ookup caused byn ls takes so lon at8! #c@s ouvadfail. behavior of0d.DS   DebuggingServerTests(unittest. Case): maxDiff = Nonedef setUp(self):)-.real_getfqdn = socket.+  = mock_-4# temporarily replace sys.stdout to capture DebuggingServer output Cold_:=GBelf.9 = io.StringIO()$~"= Vj"F serv_evt = threading.EventL*oclient,3# CSMTPChannel dDEBUGSTREAMWmtpd. !# Pick a random unused port by passing 0 for thefnumbero! ((HOST, 0), ('nowhere', -1),F decode_data=True# Keep a note of what er host anPwere Egned}),G. name()[:2]Brv_args = P.8O #[ dTn(target= Y_S@er, s= }PP.star# wait until'|5has/ a .J evt.clear()ptearDown#s Hindicate tR is finish  se j eterminate(NJW.join# restorU%Bg.closesHSrBget_@_without_xpeers)70Hvalu$return re.sub(r'(.*?)^X-Peer:\s*\S+\n(.*)', r'\1\2'&x, flags=re.MULTILINE|re.DOTALL|stBasic# connece0mtppmtplib.7%, local_<!='', timeout=3pmtp.quihSourceAddressrc_port = support.find_unused_port() Etry: psmtp = lib.SMTP(self.host, D, local_aname=')',RV  timeout=3, source_address=m!rc)IassertEqual(.H/, I&', xmtp.quiPexcept OSError as e`if e.errno == .EADDRINUSE, skipTest("couldn't bind to?  %d" % s6 araise def testNOO)wK OHOST ,expected = (250, b'OK' noop(), >0x ARSETOrsetLELHO# EHLO isimplemen^in DebuggingServerE@\nSIZE 33554432\nHELPOehlovXPNNotI&?XPN&{0502EGnot %putcmd(', getreplyELVRFY7O0Can user, but will acAmessage ' + \ b'and attempt delivery2 vrfy('nobody@nowhere.com'pvOveriF.SecondHELcheck that a s) * returns a *%it's a duplicate  $# (this behavior is specific to smtpd.SMTPChannel) 8! ! =1lib$(HOST, self.port, local_hostname='', timeout=3Tf.helo(expected = (503, b'Duplicate HELO/EHLO'1assertEqual(V$, O0mtp.quit() def testHELP(N!):L>00p()0SupNed commands:  MAIL ' + \b'RCPT DATA RSET NOOP QUIT VRFYJLSend# connect and send mailam = 'AY message'WB('John', 'Sally', m# XXX(nnorwitz): Qflakydies with a bad file descriptor# in asyncore. Tcsleep might help, but should re be fixedJproperly by using an Event variable./S.iV(0.01` .client_evt.seAserv!wa output.flushmc %s%s\n%s' % (MSG_BEGIN, m, 7END dgetvalue` lBinaryybzQ (see!in$.decode('ascii')CNeedingDotQuote# Issue 12283"'.p\n.mes..z Jevt.set()  self.serv_evt.wait() 1 output.flushmexpect = '%s%s\n%s' % (MSG_BEGIN, m, ;ENDSassertEqual(dgetvalue(), `!) def testSendNull!er=!):"mA) message'psmtp = lib.SMTP(HOST,port, local_hostname='', timeout=3mtp.sendmail('<>', 'Sally', m(# XXX (see comment in(c.sleep(0.011.quaclient-sepdebugouLd.DEBUGSTREAM.nder = re.compile("^er: <>$",MULTILINEG2~dRegex({UoMIle.mime.text.MIMEText('I_(m, from_addr='Johno#s=# Remove the X-Peer hea`that DNgingServer adds as figuring outK# exactly w< IP/ress format is putl re not easy (andGirrelevant to our). Typic 127.0.0.1 or ::1, but ieJb`alwaysvP same`socket byU). :(@%_3get_without_xpeerrdel m['N%']NW`.as_stZ wpWithAdd/es4m['From']pfoo@barI,Rm['To =B['CCi, Fred92Bcc!: Root , "Dinsdale" U?mtp,) smtp.send_message(m) # XXX (see comment in testSend(time.sleep(0.01smtp.quit(# make sure the Bcc header is stillf3he .6self.assertEqual(m['Bcc'], 'John Root , "Dinsdale" '  '') client_evt.seAserv)waoutput.flush!RRemovdX-Peer! that DebuggingServer adds#_Z1 = h3get_without_xpeertrdel m['n%']:# T should not be transmittedLI#mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), 6END9#, a/d' ousd.DEBUGSTREAM.getvalueper = rerpile("^: foo@bar0$",$MULTILINEsdRegex(", H+!for(', 'Sally @Fred %',P '9'):0kto_addr"^recips: .*'{}'.*$".format(/)u?re."Q5defZMWithSomeAddresses(N5# MKnothing breaks ifaall ofhthree 'to'Nus exist#m = email.mtext.MIMEText('A 'm['From']'iRm['To $, #mtplib.SMTP(HOST9lf.port, _aname='0', Vout=3TSC.har.com$", re.MULTILINE) self.assertRegex(debugout, sender+for addr in ('John', 'Dinsdale'):U\1to_-= re.compile(r"^recips: .*'{}'.*$".format(/)),EI /re'!) `def testSendMessageWithSpecifiedAddresses(S# Make sure %$ s8call override thosemg.m = email.mime.text.MIMEText('A 6'm['From'] = 'foo@bar`'YB['To %, #psmtp = lib.SMTP(HOST lf.port, local_hostname='', timeout=3M.4_(m, from='joe@examplE#!s=7net# XXX (see commentM~.sleep(0.01Squit(|.client_evt.seAserv!wa<output.flush(lp# Remove X-Peer header that D\gingServeNs_Z3get_without_xpeertrdel m['n%']pmexpect&%s%s\n%s' % (MSG_BEGIN, m.as_string(), 6ENDgEqual(#, a/: mtpd.DEBUGSTREAM.getvalue,9er !""^+: /0$",I-NoM B c!YpI h@<Multiple6i%erFs To 0Bernard, Bianca |the_rescuers@R -Aid-SocietyIeep(0.01)  smtp.quit() self.client_evt.seAserv!wa<output.flush()W&# Remove the X-Peer header that DebuggingServer adds.>Rtest_Z1 = h$ge_without_xpeertrdel m['n%']N#mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), 6ENDassertEqual(#, a/d ousud.DEBUGSTREAM.getvalue0sen= re.compile("^:C_rescuers@R -Aid-Society20$",<MULTILINEdRegex(", `+!fo r in ('John', 'Dinsdale'):Rto_addr r"^recips: .*'{}'.*$".format(/)),EI ?re.'@def SendMessageResent(Cm = email.mime.text.MIMEText('AE" mB'+m['From']Upfoo@bar'Rm['To J"CCSally, Fred92Bcc!: Root , "" UR-Date]Thu, 1 Jan 1970 17:42:00 +0000<pholy@gr8?net, Martha , JeffBdoe@losthope.o]!mtplib.SMTP(HOSTlf.port, 5_6aname='', timeout=3T._&(m# XXX (see comment-j(X.sleep(0.01^VCThe 3Bccs are deleted before serializationSYl: eut, sender)  for addr in ('my_mom@great.cooker.com', 'Jeffdoe@losthope.net'): L1to_P@= re<pile(r"^recips: .*'{}'.*$".format(/)),EJ re.MULTILINE)/ self.assertRegex(debugout, !) 1def testSendMessageMultipleResentRaises(Qm = email.mime.text.MIMEText('AS" mP'm['From'] = 'foo@baORm['To XJohn'"CCSally, Fred 2Bcc!:' Root , "Dinsdale" UR-Date]Thu, 1 Jan 1970 17:42:00 +0000<pholy@gr8)hMartha <1>, B - 2psmtp = lib.SMTP(HOST, q.port, _aname='', timeout=3Bwith?!ValueError}c.send_&(mMclose() class NonConnectingTests(unitg.jCase):3Not4,edm # 6 various operations on an unco0ed " object that# should rb excepEa(at pr the attemptNGto reference0nonexistent 'sock'Cribute of$IK`causes2Att1$_ } s(0)ServerDis,I_.ehloE( 00, '[ msg'jNonnumericPortQcheckS non-, As OS'  "R "5", "bogus"$ a(:^2 #)qrespons.0cliIAto asuccessful HELOUk0Bad&k VsetUpt smtplib.socket = mock_# .reply_with(b"199 no hello for you!")9self.old_stdou_Bsys. %1utp!io.StringIO(I72 = V1 E0pord125 def tearDown(5!):gsmtpli q^stFailingHELOeassertRaises(wSMTPConnectError, , RHOST,%, 'localhost', 3) class TooLongLineTests(unittest.CCaserespdata = b'250 OK' + (b'.' *_MAXLINE * 2) + b'\n' _setUpJ,0.evthreading.EventI(et.AF_INEaSOCK_STREAMF.settimeout(15!g up `.bind_ $w1rvargs = 3evt82 = T(target=server, ] @].star'addCleanup(^V.join<qM.wai=evt.clear()#P2 J@<ResponseExceptionsim_user{'Mr.A@somewhere.com':'John A''Ms.B@xn--fo-fka-~Sally B.Frs.C[4esl_kRuth C10} a?= (0, 'password')2cram_md5_challenge'PENCeUxFREJoU0NnbmhNWitOMjNGNn' 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=wBlistC _-1':[/'M]_H2Hi,0} # Simulated  channel & cu P(Z0): O)0SimHCG'd."):8Pquit_q = NoneQOmail?rcp22 = None rcpt_count = 0 rsedisconnec&AUTH = 993# Add protocol state to enable auth testing.denticated_user = None def __init__(self, extra_features, *argQ*kw):5,!._,+ = ''.join('+[ "250-{0}\r\n".format(x) for x int5 ])Asuper(SimSMTPChannel, ~%).!# 70rel stuff. It would be nice if supportthis wereRsmtpdF'found_terminator/K@elf.7_!==.;Sline _emptystr?.received_,s?print('Data:', repr('), file=d.DEBUGSTREAM?`U = []vd:try:Tr_objectv 8except ResponseEion as eR43yCOMMANDZpush('%s %s' % (euccode, jerror)AereturnX`-).") JZ, arg2notseen_gree ;P503 E: send EHLO first' 5if jextended_P or ''!"in 0command "M"Mrecognized r!isJw'%Bad sequence of s: alreadyn  =v.split(lpif len(")in [1, 2]'501 Syntax:l [RSial-r] 3uthR@_nam '_I_ [0].lower().replace('-', '_] ` = getatt,B|Attribute ^34 C?parameterMmplemented: unqIed 'L';[d {!r}'C"I >. j$W0[1])"== 2 elseJ))ed(self, user, valid): 1if  self.authenticated_user = =+push('235 A5ion Succeeded')6OelseoD5D@credaals inNsmtp_state = COMMAND vdef _decode_base64(%, stringrreturn %.3bbytes(+0.enF('ascii'))$('utf-8')q@c_plainnarg=Nonepif arg is G334 Btlogpass 6arg:tryl1*_, , Ksword = Y.split('\05except ValueError as (p.SOting response {!r} intoE and'G' failed: {}'.format(J, e)@ S_i( Q= sim$=[1]?log%#o \d 'Username:DVXNlcm5hbWU6elif not hasattr}'_'^ %Q@PassD UGFzc3dvcmQ # % 2delY " cram_md5w+}\_challengCphashed_  ao#i Falsej_hmac.HMAC(+&p<[1]&,-a AM'md5').hexdigest(self._authenticated(user, hashed_pass == valid_) # end AUTH rel? stuff.  def smtp_EHLO(self, arg):A resp = ('250-testhost\r\n'#'#OEXPNrSIZE 20( TARTTLS#DELIVERBY$ + ._extrafeatures + V HELP)Ppush(:Oseen_greeting =$!extended_N{ = TruecOVRFYc# For max compatibilitylib should be sendthe raw address. if in sim_)s%s %s' % (0d[arg],}`.quoteh()Oelse\550 No such :gD 1list_namepv.lower(6if # _! = s[]]<afor n,`_emailKenumeratezL!7) d_+jgmtplib?T8if n < lencJ - 1a+ -n7], J h h$`X)paccess kyou!')%OQUIT%"ifPquit_onse is Nonuper(SimSMTPChannel,> )._e  w  close_when_done(OMAIL Q c ^disconnect?RCP ?rcpQ ereturnZcount += 1 'A[:<-1]?RSE;Aset_; uCEDATAg): if self.data_response is None: super().smtp_DATA(arg)#:mVserv.1['f?, 'N tos'], [']) class SimsServer(&):__init__, *args, **kw# The base X er turns these on automatic, but ourH#<is set up to mungeI EHLO response, so we need'wprovideMthem as well. And yes,K0 is9D not.O_extra_features = ['?5, ']8AmtpdCRTyhandle_accepted`conn, pchannelel_ k4 {&, e  de"b_data=@ +eenable / 25 process_TBpeer3., rcpttos, LFNone[   rcpt_options=None): +self.last_peer = mailfrom = &jctos = $message = data!4ailo.ix class SMTPUTF8SimTests(unittest.0Cas\maxDiff = ( def setUp(- <real_getfqdn = socket.@k Jock_- serv_evt = threading.Event()*oclient,!# Pick a random unused port by passing 0 for thejnumberqe = SimYerver((HOST, 0), ('nowhere', -1),Bpdecode_o=False9tenable_V=True(# Keep a note of what@was Egned.!= . name()[1]6`rv_arg,.7,Bj T(target=debugging_^@er, s= }PP.star:# wait until =ei' h" a'.J Svclear()LtearDown#O ;L`indicate tR is finish  se   to terminate(NZ.join0st_y@_supgs_extens 0mtp pmtplib.(uL, local_host!='', timeout=3'addCleanup(smtp.closALehlo`assertn8`does_e/ a )!ha0n('-iutf8')%st_send_uniEwithA_via 2P'¡a j ppcontainSP!'.en\('utf-8'uv'Jőhn', 'Sálly', m,  mail_options=['BODY=8BITMIME', 'SMTPUTF8']) 5self.assertEqual(serv.last_Tfrom, 'Jőhn';rcpttos, ['Sállyxessage, mq=In(D/, ?/ua, []) j def test_send_unicode_with__via_low_level_API!):Am = '¡aJ" m! containing XP!'.enax('utf-8mtp = smtplib.|(`dCHOST port, local_hostname='', timeout=3_ddCleanup(jg.close$mtp.ehlo(  F(?', ,E(250, b'OK')yl('János'), <odata(m5q(oNo*`_uses_utf8_if_addrs_non_asciip`sg = ExMmsg['From'] = "Páolo ".!To,'Dinsdale'rSubject$pNudge nb, wink \u1F609;6# XXX I don't know why I need two \n's here, but this is an existing # bug (if it$one) and not a problem  the new funcrhality.P.set_ent("oh là,at I meanf?\n\n"dverts received /r/n to /n, so we cabeasily0Ethat#$are successfully HO&:(expected = textwrap.ded5""\WD/:  (DTo:  /: F609  Content-Type: text/plain; charset="utf-8" .6ransfer-Encoding: 8bit,MIME-Version: 1.0 `oh là, know what I mean?<E""")psmtp = lib.SMTP(HOST, self.port, local_hostname='', timeout=3a:addCleanup(jl.close$ssertEqual%send_message(msg), {}5 jserv.last_mailfrom, 'főo@bar.com'Brcpttos, ['Dinsdale']?.decode(), expectedDIn('BODY=8BIT'w _optionsDOUTF8? } HuR, [])def test__error_on_non_ascii_addrs_if_no_Putf8(P%):ipmsg = EMmsg['From'] = "Páolo <>i.!To,j['Subject$pNudge nb, wink \u1F609';+yaRaises,`NotSup0edE, .e ) EXPECTED_RESPONSE = e$e_base64(b'\0psu\0doesnotexist', eol='') class Sim AUTHInitialResponseChannel("\_9,S, arg# RFC 4954's & command allows for an -Bal i#-r.P# Not7Hmethods sH this; some require allenge. 6M`PLAIN  those, so) t0her5See issue #15014`args =v.split(  ifs[0].lower() == 'z'M pif len(M%2## < > with th 5 64F#d. Hard ; wU;F 1] 5L.push('235 Ok ereturn7571 Bad authenticacSimSMTPAUTHI nitialResponseServer(SimSMTP): channel_class = $ZAUTHIEC*2 ,K'SimTests(unittest.CCaserdef setUp(self.real_getfqdn = socket.+  = mock_-elf.serv_evt = threading.Event()W*oclient,!# Pick a random unused port by passing 0 for thejnumberqz (6(HOST, 0), ('nowhere', -1), decode_data=True# Keep a note of what@was Egnedj!= .h name()[1]6`rv_argP~,B]nj T(target=debugging_@er, s= }PP.star# wait until =e"' h" a'.J OSclear() ztearDown# C# indicate thR is finish  se I  to terminate(NZ.join st<_PLAIN_ij#_r^_login.add_feature('H H'0mtp?pmtplib.2, local_host!='', timeout=15q.'psu', 'doeshKxisto.closeMauth)quser = oPsmtp. @word )'$, .'plain', K_ eassertEqual(c235) @sup"p_"s st_main(verbose=Non64un_rBadHELO swD{General4NonConnectingSMTPAUTHInitialResponseSimTests, NSMTPTooLongLine0) if __name__ == '__main__':WAtest() import unit` from  Paudios0sup>)$op8byteswapb$io estruct$ys wave class Wav(X .AAWrit%, +WithSourceFile)module = t@PCM88(,.4CasEpsndfilei = 'pluck-pcm8.wav'k#frames = 3307nchannel2sampwidth = 160ratQ11025n8!48pcomptyp&R'NONE{@not bressed F.hex("""\V0 827F CB80 B184 0088 4B86 C883 3F81 837E 387A 3473 A96B 9A66 \D,6D64 4662 8E60 6F60 D762 7B68 936F 5877 177B 757C 887B 5F7BD&917A BE7B 3C7C E67F 4F84 C389 418E D192 6E97 0296 FF9%92D C9&28D 6F8F 4E8F 648C E38A 888A AB8B DN0B91 368E C48AD0"""^PPCM16-(/16./2m.g8022EFFEA 4B5C00F9 311404EF 80DC0843 CBDF06B2 48AA03F3 BFE701B2 036BFE7Cn8B857FA3E B4B2F34F 2999EBCA 1A5FE6D7 EDFCE491 C626E279 0E05E0B8 EF27E02DP5754E275 FB31E1373EF89 D72C 978BFB7A F5F7FC11 0866FB9C DF30FB4R8117FFA36 3EE4FB5D BC75FCB6 66D5FF5F CF16040E 43220978 C1BC0EC8 511F12A4EEDF1755 82061666 7FFF1446 80001499C0EB2 52BA0DB9 EFB70F5C CE400FBCP,4B50CEB 63440A5A 08CA0A1F 2BBA0B0B 51460E47 8BCB113C B6F50Eu4150A59Pipif sys.7order != 'big^#%(=, 2B/24B,/24B/3B].fromhex("""1\ %022D65FFEB9D 4B5A0F00FA54 3113C304EE2B 80DCD6084303 <$CBDEC006B261 48A99803F2F8 BFE82401B07D 036BFBFE7B5D<$B85756FA3EC9 B4B055F3502B 299830EBCB62 1A5CA7E6D99A< ED8E491BD C625EBE27884 0E05A9E0B6CF EF2929E02922<#5758D8E27067 FB3557E83E16 1377BFEF8402 D82C5BF7272x$978F16FB7745 F5F865FC1013 086635FB9C4E DF30FCFB40EEx#117FE0FA3438 3EE6B8FB5AC3 BC77A3FCB2F4 66D6DAFF5F3#CF13B9041275 431D69097A8C C1BB600EC74E 5120B912A2B EEDF641754C0 8207001664B7 7F14453F 80e1294E6#499C1B0EB3B2 52B73E0DBCA0 EFB2B20F5FD8 CE3CDB0FBE1#E4B49C0CEA2D 6344A80A5A7C 08C8FE0A1FFE 2BB9860B0A0,$51486F0E44E1 8BCC64113B05 B6F4EC0EEB36 4413170A5B48A""") if sys.byteorder != 'big':frames = %Rswap( , 3) class WavePCM32Test( , unittest.RCase)Ysndfilename = 'pluck-pcm32.wav'}$oq = 3307nchannel2sampwidth = 460rat`Q11025n8!48pcomptyp&R'NONE{@not bressed F.fromhex("""2"BC4#926B8#9C:"40<x>"80@%E0BD$40F0H#FCJ"80L#92N"60P%34LRT#20V"00X#C0Z0\#40^"A0`6b"80d#40f"80h#A0j"A0lEn"40p8Lr0;S06700v"D8xz"00|#80~"80L"00#60"10#64"A0#20"402*A#B0*#F0"805"80B|"80#B0"80$00#00"80A0"C06#80"FF#40"00`T3B27002"E0#804d E13"C0#90"80#E0"C00"80#90"80$800#30]0 frames = b%yteswap(frames, 4) class MiscTestCase(audiotests.A ps, unit.-): module = wave @def +__all__(self.2blacklist = {'WAVE_FORMAT_PCM'}C(support.checkL,l%, I= WaveLowLevel(lread_no_chunks = b'SPAM'7Pwith .assertRaises(EOFError.ave.open(io.BkIO(b))6Briff + struct.pack('n_kia!, h.p.append(&y!Vdict,. 1 d)e!_2[C50c, 4a  Ce1 gh]error_too_many, something, other8 rr~ YRaises(TypeE ^DCb?few \X/d l#"y_not_callable i = "SurpriseC!" c = C_not_callable()with self.assertRaises(TypeError):+Oclass D(c): ...fZtuple7def __mro_entries__(u ^breturn object`^7bEtestay_meta _args = []?, Meta(typea __new__(mcls, name, base s0Ri.extend([:]6Csuper().y A6(A,BPD(c, =Q PUx = 1F`Equal(<A[0],s-1], 'D',@2], -3]['x'], 1/AD.__ /__[,Gorig1?c,)] {[SD, A,]4  s *Z *# Substitution should  happen in direct F g/ C{5! yVRegex,P"MRO qy resol&; 9A"use s.*;()")('Bad', (c,), {}) /` TestCGetitem(unit.$as8#_g/"qP R@__(*.`, **kw _g,", 4ENoneC[int, str !m$T(C, (9) ;2{O1__(%/NPf'C[{#ame__}]' self.assertEqual(C[int], ' C') +C)QC]') (def test_class_getitem_inheritance(G!):.Y)& CG_Dp_(cls, P?. return f'{cls.__name__}[{0+]'yD(C): ... D  0D[D/_2K'Should not see thisQQkSbomethodi@1^| eopatche'!init_sub_,$,6 p1 =   `'fwith_builtinskA(dictipcalled_?r = NoneG VN';B(AEpass%WIs(B.P,wBi:?ints _error?C_too_fewv MfzRaises(TypeE G VOmany, one, twog with self.assertRaises(TypeError): C_too_many[int]  def test_class_getitem_e@@s_2(_H&* CYD_Ap_(cls, M?return NonePwith o"()<eE: ...Uve = E(). = lambda : 'This will not work'EeC_not_callableP"Surprise!"% sLAmetaUMeta(typeN f'{cls.__name__}[{>]'`Equal(5, ' /') I+e'from ra5 C(=vS5w  ICF ) @support.cpython_only APITest(unitM.0Cas f+ Vq_;pcapi imk Generic, QAliasPIsInstance(4Z(int)K#M3Int:$ =oo(5 YT4.__mro_entries__(()), &,)bl 1?pasopC.__bas`\ .Gorig3:_, (C, int, object)>4if  == "__main__"8A() # asynchat # ++4ore Terrno esocket$ys _thread as 5ing%im\.mock HOST = . SERVER_QUI b' \n' TIMEOUS3.0 ` echo_server(threading.Thr ead): # parameter to d mine the number of bytes passed back-3theDclient each sendchunk_size = 1  def __init__(self, eventthreading.T .0)G(>.=" =E psock = 2et.(.AF_INET,SOCK_STREAMa@portF up `.bind_ V1# This will be set ifI wants us=wait before echoinga# datah.start_ree_FNone_1runS;ock.listen(IG.setcconn, != (>h.accep*buffer = b""# collect until quit message is seen2 while SERVER_QUIT not ine* = v.recv(1 !ifC' 9Ubreak} +h*r# remov*WEI.replace(>f, b'')f"if e%.g(P->b entir$of"ed:tryh0# tmay fail on some tests, such as_close_when_done,Zb# sinc>f0s1phannel =` it's B\)I3W ##n !.+![:8]==time.sleep(0.00_"DQ+4elf_5n:] ex8 Q]ya class5_:(asynchat. _ "):Yrterminator, server1G P Pconte6= [pcreate_/etect((HOSiFset_( ('thandle_sV ys.platform == 'darwin'#ect.poll returns aPOLLHUP at0endsV#re just ignG)it+expt(self):  `pass def collect_incoming_data(self, !):+/.buffer +=Hfound_terminatorC =contents.append$R)gp= b"" start_echo_server(^event = threading.E(RHs = 5..T)Y.waitSclear time.sleep(0.01) # Give  !A to Xp acceptreturn s, k class TestAsynchat(unittest.CCaseusepoll = FalsexQsetUpI*_support.vsetup()HtearDownK ;Qnup(*fKGline a_checkX , !,/g_chunk.Sy_size =g$w'Bcsclient(.&.push(b"hello "world" +S I'm not dead yet!,SERVER_QUITHaore.loop(use_=, count=300,@out=l=Cjoin)&(s,sTIMEOUT;_assertEqual(c.44, [N, b"]N`# the ! [s below  receiving variously-?d!# Qs back fromWin order exercise all branches ofGO_.handle_0st_914 # one-charact|skFfor l in (1, 2, 3D f mb'\n', lFy4 2?twoIr3?hre:I;qqq;wnumericg 7len`# Try a fixed number of bytesK c = echo_client(termlen, s.port) data = b"hello world, I'm not dead yet!\n"3pc.push(:HSERVER_QUITasyncore.loop(use_poll=self.use , count=300, timeout=.01E0sup.join_thread(s,TIMEOUT) _ assertEqual(c.contents, [#[:#]]8def test_numeric_!inator1(Q%):`# check that ints & longs bothJk (since type is;explicitlyFaed in )_chat.handle_2_/(12.R6R7one N`# Try ing a fixed number of bytes, event = start_vserver(9c =ONone]) buffer,  simple_producer$_b'\n'/\ng 2p = +m", v_size=8V_withp s| ]", b")"fstringn empty_linebAsB( (bs are d correctly>r() c = echo_client(b'\n', s.port) c.push(b"hello world\n\nI'm not dead yet!\n"6SERVER_QUITasyncore.loop(use_poll=self.use , count=300, timeout=.01E0sup.join_thread(s,TIMEOUT) _assertEqual(c.contents,%[Q", b" #"]l def test_close_when_done(%):ks, event = start_wserver(.tresend_3Ping.EE1* ,c.*1# Only allow the ,2 toAing data back)g afterOAhas d its connection. This przs a race" di!PXwhere es1 ofYefore we can cheghat itNgot any down below.sG.set :6 []#might have been ablew a byte or two, but this# at least 2s t  received somethand didn't just failJ`(which<ld still result in 0havRe1anyd.2 Greater(len(s.buffer), 0+8# Issue #12523: $ ) should raise a TypeError i+P does(geRs stringL@= b'Es\n'h !'-aarray( memoryview!0hR%s( ", ^F, 10R1'unicode'8L(o` # [$', n class TestAShat_WithPoll(usepoll = True  class TestAsynchatMocked(unittest.Case): def _blockingioerror(self$(# Issue #16133: handle_read() must ignore BI0IOEIfBusock = Pmock.)()$.recv.side_effect =T(errno.EAGAIN) ?dispatcher = a. _ j+P.set_0et(elf.addCleanup(40delRGnnelKwithw.objectA3, 'Bna') as 1s0r.assertFalseor.called) HelperFunctionsfind_prefix_at_end~aEqual(lOhat.<"qwerty\r", "\r\n"), 1oMHdkjfO0NotConnect disallow_negative_terminat E1259Pclien  ,t~8Raises(Value1", E@, -1 if __name__ == "__main__":`ain() # Author: Steven J. Bethard . import codecstinspectodshutil5sta$%sy%textwrap'tempfileargparse from io StringIO0sup2Qt$StdIOBuffer(OHpass9/.B\setUpQ# The]s assume that line ping occurs at 80 columns, but thisb # behaviour can be overridden by settPthe COLUMNS environmentIvariable. To ensurrp# is true, unsetW.Lcenv = r&.EnVarGuardAenv.G#(""j-__exit__mpDirMixin(S"):jh0_di s@.mkd +3old*os.getcwros.chdi.@-tearDown  9efor root, dirs, s in os.walkOp , topdown=False):  for name in files: os.chmod(os.path.join(self.temp_dir,D), stat.S_IWRITE)Kshutil.rmtree;aTrue) ,def create_readonly_3,)_? = (;hwith open(D, 'w') asje/%a.write0 L#&K  READ) class Sig(object):__init__*args, **kw u0 = /2 =  u/NStm__dict__.update([c__reprorted_items = s.T&()(^_str = ', 'k['%s=%r' % tup #inVe]Greturn '%s(%s)8B(typy@).__2__,(o #eqw, otherYAvarsQ) == *sArgumentParserError(ExceptionpmessageIdout=Non 3err eMQ_codea.Q V^6err1?&3 = ^ st  erjstderr6 = 0 2Q_to_p-_"( _/, # if this is being called recursively and c0 or 0out1 alby9# redirected, simplyR the funcQ1let`encloszJRcatch#if isinstance(sys., StdIOBuffer)':out'4(3m 32not 7, 31and# use it& @Fold_;1outL_&= =(;<6try result = 1 )s0key%Qlist(F)/if getattr(%`, key)w6out7s8#, (2out)l5errl  setattr(result, key, old_stderr) rreturn ,except SystemExit:< code = sys.exc_info()[1]. *cstdout, .getvalue(+?err+ raise ArgumentParserError("2", qPerr, uvfinally/$ =-5out 6err err class zRaisingP(argp.1): ^Adef _args(self, * `, **kw )++_uper(| , O&).5svA_to_$1r_eH Oexit%/+ &QV,}6TesterMetaLS(typer"""Adds!r tests ueQ the 0 ributes.Ces of this Q should specify?followingCa]_signatures -- a listYSig objects whichZ>%of9to be created9Nfailmzds thatQcauserB0to I|success(initialoptions, remaining) tuplesJZhwhere < ieQe strQBrgs %d,Ck is a dictQmatch`vars()lJ6FV ^)of[, and2ebe anyE3 unQ2"""S __ __(cls, name, bases, body*!if#V == 'VCase'})g# defaultE3Fempte`ot has'r'a2cls$g = SigZ wV / =-a# func for adding optional arguments ?# -2def no_groups(parser,Z_signatures):4m"""Add all-s directly to the O9""";for sig in;h gkFT.add_(*sig.args, * kw%) j2one-under a single .#= e'foo')e \Bmany Eeachsits own$i,enumerate(  q  U :%i' % i\@0T # functions 0ing'J@listPi-p by pas a F |dreturneUss>0sysXpdefault`to sysvpold_sys~5v ='<H = [0j[0]] +]0>try? ofinall@j# class that hold e combina of one opa3`# addi method and41argO5wAddTests(object):P __init__(self, tester_cls,wH,j>(._:s =B{4ius/ ]P_name;elfx!._-__qk"?<_E[0ail&, successes]wGE?unc3V; s_name, parse_args_name Atest = '_'.join(.?s) 1def wrapper(self, CUfunc= /):<$>)(?tryA}!._B__ =Nexcept TypeError[OpassCsetattr(cer_clsu, 2*_get_pars./er!2er.4_signature. kw6! 8^ 8pclass(*TB, **=P._add\ruments(R ersHrreturn ; n<m_failures._>E2 = wG.er~@for q_str inE4er.q&1% =8~.split(]DwithVassertRaises(ArgP`, msg=^M{!s(1:`succesp;B, expected_nsD{Eif isinstanceO, stws `result 4- !r,+.gEqual(%, _Q# add s S each combination of an op 0als/ing methodP# and)1arg$_ vs[no_groups, one b, many *s]F C@listcP, sys 3AddTests( ,j) bases = /bCase, 6 = berMetay'81', K, {}) # =E # OVs$ [-SingleDash(r|0"""4 1a s;S-dashbing"""a = [Sig('-x')]f, 'a', '--foo )x "y'9[:K ('', NS(x=None)), ('-x a', NS(x='a')),  5 -1:--1;!] class TestOptionalsSingleDashCombined(Parser&aCase):0"""D an < with a sCq-dash oX string""" =argument_signatures = [0SigP', ac='store_true'(=yyy*const', ==425zH]vDfail'l'--foo', '-x'x 1 -zVz -x'A'-yx !yzD'-yy3yyzQ {success$('False, yyy=None, z %/?Tru.o^0x`_x`0/ -a/ -cV /42|/ x d#4Sk* 5OLongmulti-character'c) |)Pfoo -'"a'HK ?foo:Kl0NS("|!H"h$fo! fSubsetAmbiguous zs whereqs are sPs of each other C'), YoobarOrab' PfWSb r1, f 1rab $f76o7 foorab=None)C), ('-fooa', NS(f=' foobar=None, foorab ):Ebar >0='< ?rab<Iy4'a'x"] class TestOptionalsSingleDashAmbiguous(Parser'aCase):0""" : that partially match but are not subsets""" C argument_signatures = [SigKubar'), arab')];Dfail0'-f', '-f0'-f.oBo b'FrsuccesswX#('z3 2X+ba3e 3f|4htNumerich %ank with a short opt stringY1', dest='oneP#_P'-1 -~BD1 -y #2L?one1 1?NS("-2/-2 BDoubjd;P-dashp?ionsBY'x1 -x(0 --oF]=r"="R -2.5|Qfoo='YJ ( PKMH svt4ing"& }-badger', ac)='store_true'.t "-bbrP'--b= 4a=4_dge 5e=False, batRbat X1%'XF9bad.True, bat=NoneS)), ('--badg', NS( er=True, bat=None/e0r1$] class TestOptionalsDoubleDashPrefixMatch(Parser)aCase):0"""s when one d=q-dash oR string is a pR of another""" Kargument_signatures = [<4Sig<e ac='store_true'g.]IDfailZJ 0', a#=2 radge 5'>{success)('kAFals/ X/>'X'=.d[V./[ 0fSingle| D an q with s?_- andsyOf', srt=baz@const', 3=42k0fbaW2'-fRP'-bazP'-b BB%f=r~z ]ENS(f0 1-ba4e'/bad r8/r=7 b+42Oba - 2Alternate_Chars sccustomept0 = E _c~P='+:/\rdd_help)S+ ::|/ @c)!-h- +$::/ K  (:'::ba B', NS(f=False, bar='B' z=None)), ('+f ::bar #NS(f=Tru7[/b', 2`j*42ho/ba +f2,] class TestOptionalsAlternatePrefixCharsAddedHelp(Parser1aCase):"""When ``-`` not in p? _c@, default operators created for helpJ should use theGWrather than - or -->http://bugs.python.org/issue9444""" ,p_signature = Sig(='+:/', add_)>argument@Qs = [K' acX='store_true'( @/baz} @const', 3=42K]yqfailure'--bar', '-f b ~ '-%%-oHrsuccessIZ$('W 04e/baX,WMultipleShortArgs_`Verify%t  must be called with4 iroCined>/es-y -x> /+y(P &w'}_'-xyz/+x/-y+Dx, xy z *2ANS(xb/, . >+y 1O^?+yz19OLong a combina of single- and double-dash okv stringT!-v-verbose n_-noisS  +I-x -NNNaR-v x'4 [ ( '', NS(verbose=False)), J('-v#i>2%j + k>|j>Ofaul pspecifyAa de3 for an xkL?=42!x0, yF @$xx#' "y6NS(E/'y4 bNargsD Gnot =the numberGF& _, '-x  4x a/'a1 _1 arg%0, n./=1'7[)433s-3 '-x a b', 'a -/ b*D b c#1, 'c?c']-$4Y>=%$w'A7'?'#%_'?', constL(+(^'spamV.type=int, const='4 2', default='84'), ]failures = ['2'rsuccess'1('', NS(w=None, xy='spam', z=84)_2/-w4! j' ixiO42, xgo5 yg;y yg4o3zei+42izg5] class TestOptionalsNargsZeroOrMore(Parser#aCase): 0"""s specifying 8 for an N that accepts zero or more""" Kargument_signatA`Sig('-nb4='* a { uvNS(x=[]m $" aox=['a') ( b+O, 'b0}O+[]{y{$'y).4 ?One3??one2/+2 +2",  '-|1'a ?y bP2,<Y1 (Choices6Rthe c5 =#4f',J^='abcg', type=int,range(5))"Af d'ag_'-g 6fgKD('-f0f='W%c0f=' %4g 0% g=0)),  ('-g 03', NS(f=None, g=3)), ('-fb -g4&0'b'%4%] class TestOptionalsRequired(ParseraCase):Z0"""cs an o30 ac< that is rBA""" 5argument_signatures = [Sig('-x', type=int,ES=True]2DfailCr'a', ''{success]Z" 14x=1x$42$42A_Store Pthe s(0for2e [!='N"')Oa -x -4foo'   _Const _c.*3y',@T1', \=object(=&yM uDNS(y^A'OFals, _f. 2"zT8!-zAO-z a?zvQNS(z=<<;Otrue*m-apple!X 6=;"'- / b+o 0Gp& 8_Appen ~a)1+ baR+ 0S'a --  / a2?baz~M 0NS(#T['a'].SCbaz y ,F, 'b1 _WithDefaulj@2, d=['X'])] failures = ['a', '--baz %a   a b'] success7('', NS(baz=['X'])),E $O, 'a)/ b1F, 'b6 ] class TestOptionalsAc AppendConst(Parser%aCase):0"""qs the a. _c/! aA for an XA""" 9argument_signatF`Sig('-I(='^1', f`=Excep-;3c',;', dest='b'.f=A'a -0-bxO-b x[=None%=[ pb -cx -yD /0, '?_, 'yzWithDefauloU'X',  4)OCounc($N/')S"x !xp'-x a - 2 xS~dNS(x=1lllowLongAbbrevia1A.q long o[s to be a>ed unambiguouslyD-foo< 'lestore_trueGD -Q! 5 1foolP, foo |le=Fals\" 7h>' =!ba0NS(?p1az=UL|1bl ' g 8'azele=Tru.@Disa1estCase):  """Do not allow abbreviations of long opa'""" parser_signature = Sig(J_Jq=False)/argument1Qs = [O<'--foo'),dle', ac='store_true.4nly]Mqfailuret'fbn 3', r d!d 2 2'CrsuccessDU ('', NS(foo=None, foodle1nly)(z>'=Rnly 72dle & 2' Q2Tru4'7'k] # =p # Posikal tests& class Test/`sNargs !(P"aCase):40""") achat doesn't specify nIo@75 x?a b a8a1bies anf1,5?=1)7W['a']2322$'-/ c & bO, 'bZeroOrMore'unlimited ?'*' /-x B 13Default86 and a dWF!,=_='barU-D XH?One%ecifies one (or more nargs""" argument_signatures = [Sig('foo',0a='+')]2Dfail''', '-x'rsuccessB,b('a', NS(foo=['a'])),* b F, 'b% ] class TestPositionalsN"Opp(Parser#aCase):a0"""Ts an * C? -x?a b KNone4'a'Default" with a dDo value!,C?=42*%$42 G#Converted,>ithat needs to be cpthe appropriate type.8i %1?',IF=int|C'42'^ o, '1 2 11  G two!s Xdon't specify8 /1), ?bar _a b c obar='b1 a"no followed by one1"1 "--''[22 ?non27 4&/ dC& cC!, LcLZeroOrMore8 """Test a Positional with no nargs followed by one&unlimited""" argument_signatures = [Sig('foo'), Rbar',[a='*')]>Dfail3p'', '--5rsuccessQ/q('a', NS(foo= bar=[])),$/ b&>'b')/ c+F, 'c0] class Test8 sN0NoneOneOrMore(Parser(aCase):0"""/ au~or morew++w _, 'a'| XbpW;Can OYW+?WO b c[ V4'b'' BZero[Q$?non*4@[], %'aC[)H)+ , F0cYx w!y?+y !/ZFY!Y??', default=42e/#42 ,'b')), ] class TestPositionalsNargs2ZeroOrMore(Parser&Case): """6 a ; with 2 nB followed by oneunlimited""" Iargument_signatures = [Sig('foo',OQ=2), 5barQ'*')]GDfail<r'', '-->2'a'"rsuccess_4('a b', NS(foo=['a=b'], bar=[])),-/ c/5'c'2]b ?Onea@jor morec4+c!, Hj=6p5oP44?4O c d)ONone4'c'0 Z1g 1m1  6&'+b+4$' --@rsuccess\//((DNone)a$( <*6RM)}-ChoicesStringt set of single-character cEgdspam',3=set('abcdefg')^ @, 'hl 42?ef'oq;gz (?Int%_integ#type=int&range(20!;44'15$15 AcoAppend! athe 'a)1' a78 C#',;=Ke&2/A!, |p/ du !=[Do] # = # Combined o*vs and pHo testsVNsNumericAnd s negative number P whenNs are presentx -wdest='ystore_true'-MO-315 "x=ty=Falsexxo/, #6NS(H;TruG0-4 G&?(y=% oAlmost;aT numeric options are present""" argument_signatures = [ Sig('x', nargs='?'),-k4', dest='y', action='store_true3]9DfailgR'-k3'{success ('', NS(x=None, y=False)D('-2% %a$ # n*')i$[]m(ta [] 0['a/y=%T -- b*;'b'r]q- !a '|% ('a -x b2', NS(x=['b'], y=['a'])), ] class TestNargsRemainder(ParseraCase):20"""s specifying a positional with nJ=REMAINDER""" >argument_signatures = [Sig('x'), 3y',BE'...Q-z')]GDfail<r'', '-z2 Z'"rsuccess_44('X y=[], z=None(_-z Z -:'Z',`X A B 2 ] 'ABZpX Y --fooCY>  OpOLike o)s that may ortnot be s X-x', type=floatbO3, dest='y')@$'* oa'-y2.5""xaB -a'{P'-x - 4@3 -3  /Zb -2.5 `?3 -2da x -11/ 5z=[(?2.5-/_ /0y=0e3 ,-- 3 -,a-zPa -x 191.0?\.@0 3 q!y=8 DefaultSuppress 0 acsgs3Bed dEqn ?'P=argp.SUPPRESS6bar*:@--ba='store_trueFI _ 8kfoo='a2a ba, bar=A ENS(baz=TruF'a #N,* | 9 GDefaultSuppress( ParserTestCase): """ actions with a p,-level default of SUPPRESS""" @) _signature = Sig(argument_<A=arg+.B)?(AQs = [L'foo', nargs='?'),6bar*s--baz',='store_true+]PqfailureB'-x'rsuccess(('', NS()2('a{foo='a') b, bar=['b'])NS(baz=True!'a #lN,*/ a|9] class 4D242(D'/42>/42/--version T='1.0j 42"r=z+42&n8, Euoy+/, = @}E A sFromFile(TempDirMixin,  reading s from a filedef setUp(self`super(d !, ,.83YQ_text`('hellA world!\n)recursive', '-a\n'J%/'A @x"=('invalidd@no-such-path~2@for , 1 inG& = open(26'w'%#p.write(Nclose() m_prefix_chars='@m k(-axy+ L-` 'X @c'@missing']  successes = [ ('X Y', NS(a=None, x='X', y=['Y'])),--a A Y Z4;'A'3L, 'Z8p@hello X jcworld!uX="X ?s E -a B @recursive ?XI Z [*'B T ["-a", "X3Y"]'J.] class TestArgumentsFromFileConverter(TempDirMixin, Parser3aCase):0""" reading aN from a file""" .def setUp(selfC@1supp !, 5.A)Q<bZ_text!('A2',  "7\n']Jor path, O1 in\Ut = open(26'w'#p.write(Nrclose() }(ErrorRaising"):H{gc_arg_line_to sz,:0for9{.split()-`if not0o.strip$(continuehPyield@p`_ /=  3signature = Sig({_prefix_chars='@_8 :C'y', nargs='+.*bfailurp ?# = # Type sion tests 0=0Rep#stC,J!_rtp=.G3('rI.assertEqual("(@", rwM)sOwb_1vfwb', 1Hz ,~ r_latinr', enco!='=/_1 < w_big5_ignorewC92s='Mw', encoding='bi g5', errors='ignore')", repr(type)) & def test_r_1_replace(self): I0 = argparse.FileType('r', 1@%');J.assertEqual("=9", class R:s(objectseen = {}__init__c, name-! =8%eq6Wother71if A in Cy Zftext =[1] Oelse2" =lf.read(JeTg.closeif not isinstance(H, st@0 = .decode('asciiSretur*?# @TestR(TempDirMixin, P.r"4Cas0"""T the 9 option/argument r@for ing files"""QsetUp`super(`[!R,").0P^V_in ['foo', 'bar'])pen(os.path.join.temp_dir,QW), 'wV~Ep.write( (!" qpcreate_Ponly_A$(''@_signatures = [dSig('-x',a=&))<-Ospam/4'r'2Dfailvi'Rnon-existent-R.txt'3{success(NS(x=None, =){:P foo !, 7, ?% ?`bar -xC'?!d-x - -;psys.std r"]yDefaultsAat a1 isBed unlessdZ"Peededq8S ?ile]l'good'ZOV!O!c #, F='no; # should provoke no suchp 1<@3 because default *file is created successes = [('-c good', NS(c=RFile(')))] class Test TypeRB(TempDirMixin, Parser#aCase):i0"""T the : option/argument type for reading Qs""" Ddef setUp(selfY@per(`[ARB, %.1)A,_W_name in ['foo', 'bar'])) = open(os.path.join.temp_dir,Qf), 'w'nEp.write(P("rclose()_signatur6Sig('-x',4P=argpv.('rb')),1Ospam3]9Dfail{n"'' 8,(KNS(x=None, sHh)P foo {tx, ?% ?`bar -xC?d-x - -;psys.stdWhs(object`seen =__init__1 , t00.! =8%eq6Wother71if @ notG text = 'Check thateable.'`if 'b'S`Z.modeT&X.encode('asciiDk e(- XQ.add((;areturn:= # @unittest.skipIf(hasattr(os, 'geteuid') and os.v() == 00 "non-root usequired") W ?? *W g _pPonly_$(''6w2r&, & YU,,?3out9>outWB(TempDirMixin , ParserTestCase): argument_signatures = [ Sig('-x', type=argpH.FileType('wb')),1Ospam3]9Dfail{n"''{success('foo', NS(x=None, s =W) foo bar7, ?% ?`bar -xC?"d-x - -;sys.stdoutx] class mOpenArgs(0""" that open (the builtin) is correctly called"""def test_8 _a^aself):^@FT =( ,ca5(FT('rb'), b, -1, ,0Qw', 12 0errors='replaceq?pub', encoding='big5EF0, 'l1', 'strictD>', with mock.patch(' s.v') as m31for,Qs in  %)m.assert__,0, *)Callable(TQAsomen+stoption/ts T-eggs\wcomplexP #Sfloat!m ma042j-\  /2i (b=42 423=42H42.04"('2 2j -- -1.57#2j7 7x1024.67.H04 @UserDefined a user-d,  Myae^__init__(X`, valu+." =! C%eqAWother%PreturN0), Ua) == (=!, l Y z "{aoK!('P=+a'R-xf gSx=MyType('f'), spam=MyType('g'))), ] class TestC!icp(ParseraCase):40"""1 a :"ic type""" %2 C:kdef __init__(self, valuV#." =! C%eqASother=return (h2elfUC) ===!, largument_signatures = [cSig('-x',#=CMn ]>DfailO{successb('a -x b', NS(x=C('b'FC('av7f g.f. Registration(user-definedQ by r;ering itBtest~ rget_my_t;'%{%s}' % s,pa = arg #.A!()q+. ('}4', c7', 8Dadd_i?2 y1assertEqual(!r.ws('1'.split( (None, y=V{1}')n-x 1 42tl |!42}W # =P # Acn %s'RUserDz  ope/! auO%"alk(M-)e__callr, namespace", |_= 2tryN# check destinC andN2 > :''A: %sC~?Co G -s(DflagE $ Id# whenis beforeR, badger=2,.Ee is after?Fexpected_n0NS(V=0.25"ifk in [0.125, 0.625]0\.N = 2lY?2.0P/84Q/seqraise AIionError('value: %s' % value) assert expected_ns == namespace, (' %s, gotQ J Y(JF_ns,d)except AionError:oe = sys.exc_info()[1]&raise ArgumentParserQ('opt_action failed: &setattr(t'spam',Tvclass PosiS1alA[P(argpv.1): .def __call__(self, +rd@, opW_string=None):tryc =@ is @ A D ># check destina b.('badger', ' $ E# when acbefore< , =0.25, and/F?UafterQ@Db = NS(.=2"ifE in [42, 84]HU.0 = }lT1O?625P 2P1P/se !(' F@#B?arg& ?_signatures = [Sig('-s',= I!=O,6type=float<Qfault)']T S/V0int4args='?_2\{successp0.125',m=", 3=2)YI('42*`)4*-s 0.625 12631\X84 -s`52.0$84-B] TestActionRegistr ation(TestCase): """ a user-defined ac- supplied by registering it""" Aclass MyA2(argparse."):&kdef __call__(self, + r, namespace, values, op0_stqD=NonKsetattr(<U.dest, 'foo[%s]' %S)Atest6 = rgumentP1r(){+."('/u', 'my_  >Sadd_ab('badger',z=IyRassertEqual(Ns(['1']), NS(T= F1]')H/42I!42J[ # =a # Sub0rs es& 3w6Add2@the -s\emethodAQQError, *args, **kw  URaises(FAOR_get_m _help=False, prefix_chars,Rraliases6# create a8 with a nsY)ifwj1 = ):ing(J5rog='PROG', descrih='main'X.y?[0] * 2 +7store_true', } 'tOelse [|o'--fooL0'baitype=float)4bar)}# check that only onera can b%ed?_x = {'required': }03if   H['metavar'] = 'COMMAND'If5Rtitle3commands4BT A3y3# =6(**  *E"#+ first sub-parser  parser1_kwargs = dict(description='1 0') 7bif subAe_help:Z ['"'] = '1 .if aliasesB %E1['1C1', 52']S}& =bs.add_ ('8"**2 argument('-w', type=int,1='w<x', choices='abc'@x@# add second-R 2 2)Z2 `D2', `Q `2`y%5123%yA zcomplex, n5='*JzJoOthirn3n 3n)Zn33n*nQ -3nt-ty; %u'Z5...\u># return the mainp! def setUp(self)super().'.B"elf._get )qcommand#1 = D6 f=True)3tes`_a_failures# check some %* cAfor Estr in ['a 60.5 11','c '+01 -I f2 -w']D2m% =tv.split('$sassertAP*QErrors,T'7 Onon-"iEqual((1 b -w 7')=NS(foo=False, bar=0.5, w=7, x='b'0!r 25 --foo 2 -y 2 3j -- -1j }p25, y='_`z=[3j,@] self.parser_args('--foo 0.125 1 c'.split()), NS(foo=True, bar=2, w=None, x='c'4)>self.assertEqual(_1.5 3 11 -- a 7 b CFals-1.5, t=11, u=['a', 7 --9b']def test_b_known5!):%J0'0.wob -w 7(}01w=7yjb'), [~ _-p 1 1;'-pe-? -pB+L_q -rs00'-q?-rsQD"-W1X Y/ ZX-WXYZKpPdest(d r = ErrorRaisingArgumentP(t.@.add$', action='store_true':2sub=Bs = G(W='bar7*F1 = )8>('1- aW('baz$ 0'1'Hz='2zS  61 2%) _required_,# Should@ the commandX6retOs(['run'] -Cret.N!, .W#Q when|*p is mis#Q 7Q(C, ()k_via_attribute'Vo-|/. = True subparsers.add_ ('run') self._test_required_su9(5!) 0Odef *_via_kwarg(S!):2eC = ErrorRaisingArgumentP(|2 = ;dest='command', _=TrueJALFdefault\`# No eU here6retn)_args(()a)assertIsNone(ret. !optionalKfOFals*VLhelp5*.kQEqual .r.format_usage(),k '#: PROG [-h] [--foo] bar {1,2,3} ...\| ), textwrap.dedent('''\_main descriG Bposi]# aEsmD   ' ' (k`-h, --: show thisJ@ mes and exitZ! a foo4 #L''')Yi_extra_prefix_chars"t# Make sure - is still used forl` if ita non-first V Vz1 = D_getM.\='+:-ZJG*/++ wA(#} o optional arguments: -h, --help show this message and exit:S++fooL 4 #a''')) def test_% _non_breaking_spaces(self)parser = ErrorRaisingAP(Z prog='PROG', description='main%')9fT.add_! Vt"--non-R", acVstore_false',Q =' Bcontaining O shall not 'J 'wrap\N{NO-BREAK SPACE}atFL.assertEqual(Rforma(), textb.dedent('''\u : Uz [-h] [] i oP   .Kalternate_prefix_char R_get_(6_='+:/*() '#+] bar {1,2,3} ...\nwz} c @posi  @comm' (`+h, ++:yR4_ ta72z.I#FC?fooF F "qy1 1 help  2 u2 help  32 3! "optional arguments: -h, --[ show thisJ message and exit:C-foo~ D #a'''))  def test_subparser_title_5f(self)! = ErrorRaisingAP>(prog='PROG',badescriw='main %')LT.add_<0('-P', acW='store_true',4$=' K 5bar41bar>4(Gs = (A='subcommands #='CR`='addiwal textF1 = W=('1-2-2-7.assertEqual(R.format_u/()'# : Gq [-h] [ ] {1,2} ...\nu1(),wrap.dedent('''\\{>0  4pos J F2^ (  " (  _ _,0s_str, expectedWwith :es(z) as cm:gQs(argx.split()1 , cm.exce.stdout}1b'5.0 1 -h'd1[w W] {a,b,c}1 Tx DJ1w WyB w| r q2: se+lf._test_subparser_help('5.0 2 -h', textwrap.dedent('''\ usage: PROG bar 2 [-h] [-y {1,2,3}] [zi...]] =2 description@posial arguments:=7 z z DoXB `-h, --: show thisJ@ mes and exit|1 y2 !R'''))Adef galias_invocaf(self)0 = b._get_(:es=True)h'assertEqual(;._known_args('0.5 1R1 b'.split()),>(NS(foo=False, =0.5, w=None, x='b'), []982>aerror_CAPYEo(r t3b\#*, qmaxDiff = V bformatY)P?"""PJP-foo] COMMAND ...zOmainL+J O nXRb= 2foonz}command"1 ,031 (, 2!1} 2O 2+3+3+0"""A7# = # GroupsQ+s  class TestP?s2(CCaseq0"""s that order of g_ }s matches construc02"""d1nonAo_firstzRaising((@0addf('foo'#l? = +_;('g/p.add_argument('bar') parser.add_argume#z#expected = NS(foo='1', bar='2 Gz='31result = ]_s('1 2 3'.split()self.assertEqual(v", O!) def test_group_first(=!): pr = ErrorRaisingAP(zI eW('xxx1 27foo" #xinterleaveds\] E 7yyy1 Wfrell$L !, 97='4< W/ 4Y$># = # Parentw/s , class Test5g s(CCase0"""Ts thaYs can be creah@withu|Fs"""' , *args, **kw {)f?es(FA{QsetUpgVruper().Znbwxyz_pI yhelp=FalseF b7--w$x< = } 7&(('; (8('-T ('5,Oabcd/F a q +'-b,c'a&>('c; ^3-d'hw/C n kegumentParser(add_help=False) self.z_parent.&argument('z') )"# $s with mutually exclusive groups1Zab_mutexa = ErrorRaisingAkoParserY? = R__4(- -a', action='store_true'6 b6 main_program = os.path.basename(sys.argv[0]gdef test_#le4(%):]p-J  =[<D.wxy]assertEqual(Y._args('-y 1 2 --w 3'.split()),ENS(w='3', y='1', z='2') " _B!ab#.Sr$ V ( ` { BgranBs =  U^q ,=e$z( ;!see.&([]), NS(a2, b )? E'-a'COTrueB bBFCK c0, [@, '-WAG EA/c';&=/'-A(A=emultips(6#cd-,%\D[4.A-d 1-_2 3 41a1b=None, d9w9GNz='4H * f parents = [self.ab_mutex_parent, Cwxyz3] parser = ErrorRaisingArgumentP(F#s=)=WassertEqual*Aser.U _args('-a --w 2 3'.split()),BNS(a=True, b=False, w='2', y=None, z='3') (l', 6 -b8`&b adef test_conflicting s(z!):(".o*es1arg. l $ %=MwF)sJabcd )]@same _n m9|`61 2 PCNS(w]e2e}1subcrG O O;U.add_g&s(-ex$3>('bar', :9Oent]PCaF('e''ubar -b 1 --d/ 4wab'1', dOe='4|[ BV >,U0abcp 7foo[wc_group = M  #(') .7('c"n+/abq G e_args('foo -a 4'.split()),  NS(a=True, b=False, c='4'))5 self.assertEqual(parser._args('bar -b --w 2 3~vbw='2', y=None, z='3', eArgumentPeError(, 'foo -a(6^"  _def test_parent_help(p!): ents = [S.abcd0!, Cwxyz]7aser = zRaising[=~s%2 = c.forma+rogname =main_program5a, textwrap.dedent('''\;usage: {}{}[-h] [-b BA-d D0w Wy Y] a z^;positional as`"9 aq C/opA `-h, -- show this 0mes and exitk J-w Wc- $x$5y Y[3'''(, ' ' if  else '' )))\cgroupshso 1add[Cgd@ent.#_r(title='g', descriW='gd'C :O('-w xm}mutually_exclusivelmlyO zI% "=[ ]F:es(,m ['-y', 'Y -z(Z'g9ry3x X | -z Z]+JYm g*gd!! @O-x X(# ================== # Mutually exclusive group tests # 0 class TestKEJGIpErrors(!Case): defc_invalid_add_argument_q(self):/3parser = SRaisingA3P%().raises = Fp.assert4+es#Q(TypeS", c.m_, title='foo')+ / =M" = 'DValu(`P, '-- , required=True(AObar'0, nargs='+;&1t%1arg+|.PARSEROhelp!prog='PROG17 (action='store_trueq :*, :Mfals;2#2r\soup's;Mnuts; expected = '''\mpusage: q [-h] [ | --barn] < opb4al rs -h, --+ show this 0mes and exit! =bar  5'''0aEqual(r.format_(), textwrap.dedent(M$))MEMixin(objectfailures_when_not_?;Bget_(5 =F!).-e: = ,$0fors_string in9 $T(dA~,Op.split(^#trror = ArgumentParserError for args_string in self.failures + ['']:18"assertRaises(eU0, pb_P,V.split()) Gdef test_successes_when_not_required(d)wZ" =Aget_$r(5=False).pk?|" +PF ., expected_ns;f}`actual$=#((x"0.heEqual(I zW S#?TruR GUj^usage qformat_.'f/" F 6 \(), textwrap.dedent(g Ypb . E|2=NhelpW-. ;G+8%  ) - :p: class TestMu lyExclusiveSimple(MEMixin,%fCase)::_$, @=Non*>Ar = ingArgum (prog='PROG')cgroup sr.add_m$_e_&{ G>au('--bar', qQ='bar |5Pz', n1='?', const='ZKzKreturn parser failures = ['--bar X jz Y', !']4rsuccess5J(, ', NS(bar='X', baz=None)),,k7r Z4 4`Wa>'Y'`zV*Z* _when_not_requiredOYz!] -_usageMA'''\#0': PROG [-h] [wqr BAR |rz [BAZ]31'''?;b^ (^)R^qhelp = Ooptional arguments: -h, --9 show this 0mes and exit7p0 {1  zQ  class TestMutuallyExclusiveLong(MEMixin,#bCase):def get_parser(self, O% = ErrorRaisingA PB`prog=''U9T.add_:)qabcde',!=' :Ufghij: :@grou|m$_e_&( ! Uklmno 9Upqrst9 9rreturn  pAY2i!, ; %XQ Y --/6 X'$2NS(`':_yU>I]1 5 H%=!, F_/K  Gta ABCDEWb FGHIJ[QKLMNO{b PQRST0k0m0*)( ,} show th is help message and exit --abcde ABCDE 1 fghij FGHIJ klmno KLMNO pqrst PQRST  *''' class TestMutuallyExclusiveFirstSuppressed(MEMixin,.qCase): def get_parser(self, required):$ = ErrorRaisingArgumentP=prog='PROG')9group = Ac.add_m$_e_&(x= G>aua('-x',A=arg`.SUPPRESS9 y', action='store_falseO!'yWcreturn:failures = ['-x X -y']@succxC X', NS(x=' y=True)),%U -x Y* *MNone, y=FO _when_not_^ypM]u IE'''\L' :  [-h] [-y&MI %-yeG1 = 8 op4al .s -h, --9 show th -y!o OManyaadd =  add('--spaml5trukCmbadgerE FAladdG1  4 --y6 B'D'--b %>&@P0NS(Z>", l Y= )@0AB E6#, L='B'4E7 >sp- ] usage_when_required = 8notc'''\ ': PROG [-h]1''' qhelp = 59optional arguments: -h, --9 show this 0mes and exit6o class TestMutuallyExclusiveOsrAndPosi(MEMixin,4qCase): Tdef get_parser(self, )  = ErrorRaisingAP=`prog='#!')]@grouAc.add_m$_e_&(x= G>K('--foo', ac='store_true',G\='FOO EEspam1OSPAM2 badger', nargs='*', default='XJgBADGERLrreturn ~failures = [2'0 --H S',( X!X 2 ?Y ZCsfoo X Y/{successcNS(foo=True, r=None, &))8% ;DFals<?'S';B4 pZ['X']rX Y Z',o ;, 'Y', 'ZE ' /('j4'X']E[7/'l! [% |SPAM |}" [R ...]E)MtV#p(pp p " 92EF 2^5FOOdeU SPAM}osMixedvhe x- x5# =N6a abE b help') * parser.add_argument('-y', action='store_true', help='yC') \groupEcE cEcreturn \ failures = ['-a -b', '-b -] ]7rsuccess8 ('-a', NS(a=True, b=False, c x y 8)),@@8bI@ @IcI Oa -xyD 1 Bx -y E <1, yD _when_not_requiredr].A#1 /', I@]Rusage E'''\': PROG [-h] [-xabycU1'''>1 = N op4al %s: -h, --9 show this@ mes and exit6xZx.aabbymWcE class TestMutuallyExclusiveInG(MEMixin,&bCase):def get_t(self, @=Non*|= = ErrorRaisingAGPZp(prog='0qtitled_7# = @(s61='T= =', descri!='uRmutexX6 = g[m:$_e;:(  aDhu('--bar?1bar;z;z;7|0 X 1z YAC-bazBr Y'A6Abar='X', baz "Ze0NS(,2-6'Y'tp  [&('{O P-0M t usage: PROG [-h] [--bar BAR | z BAZ] 1''' usage_when_required = '''\.#S: PRO\(P \)1\DhelpMoptional arguments: -h, --9 show this 0mes and exit 7Titled groupMGq descriv3  *dR3 z class TestMutuallyExclusiveOoalsAndPosisMixed(MEMixin,;bCase):def get_parser(self, )  = ErrorRaisingAOP=`prog=''9T.add_~Q('x',1='x0 p-y', ac='store_trueFyF7 = ~m1$_e2_&(= ! a', nargs='?a :/-b bEcE cEcreturn failures = ['X A P'-b -^'-c X A'rsuccess.(8', NS(a='A', b=False, c x='X', y9)),>t?@None@?Tru? ?H~ !A TA P y5A A U8not [)ee  @ 7 =  ' 0[-y%brc] x [a px:Ra7N"-y -bcO # =4 # * ! i3ento testsf============4= class MEPBase(object): def get_parser(self, required=None):)-parent = super(R , 6').GA )D ser = ErrorRaisingArgumentP-uBrog=z.prog, add_help=False, 2s=[ ]m`return!Dser  TestMutuallyExclusiveGroup!sP(5 'Opassi oSimpled0_OLong].[FirstSuppressedf 9qOManyp! 8oOptionalAndPosi ?}OsMix\v8o EsF <# =` # Setault tests (`SetDef0 s(HCaseEc_set_d&_no_argsUi G.Y(x='foo'% y='bar', z=1*/.assertEqual(NSO), 3, ?[])dPo, NS()jObaz'+jxB/z'q!/2)?q2v&\Bwith{^AA r.a6d('-x',J='xfoox')  self.assertEqual(NS(x='xfoox', y='bar'), qparser._args([]))0aCo, NS()g?baz'ex/z'l1j%'-x 1'.spliti4WoN" def test_set_defaults_subO0rs(?!):, = ErrorRaisingArgumentP(|..\Ffoo'%m3 = 28add- V_a = 8./7('a[*_aT$('aOijoparentg?entg help=False#:ent0x=' %?sera "=[ ]>1$),}2on_d7_an}1arg^.zx  #2!()=('X4 ?Vfoo=1]$2$#G2!0'X'$same_as_aq!&w='W', x='XNY', z='Z" ?'-w"c?='Xt RPy', n?='?\ e,%, fZU#s set previously" Z! # reset defaults parser.set_(w='WW', x='X', y='YY', z='Z'):self.assertEqual(NS: ,;|_args([])) 1def test__same_as_add1ument_group(!):<bUr = ErrorRaisingArg3P(. {3 = @G'foo?1.(O('-w! 4x',O='XX/ Py', nO?='?+ z+dZM#~ s Opreviouslyo~AQB?Z')$r<# =F # G/s ( class TestGetD(bCase):4g+sIsNone(bf"foo")M50bar5BY 1"--\%[4D, type=int3/42qY442,X n&9((foo="badger"c#i- # Namespace 'contains': CCAoSimple\emptyns = argI.TwpNotIn('8sZ!,nsOnon_0x=1]k lf.assertIn('x', ns) self.assertIn('y!No"xB#zEO # = # Help formatting tests0 class Test9F8AMeta(type): def __init__(cls, name, bases, bodydict):. !if#P == 'bjVCase'#'breturne{@ Add0as(objeWX% o,_=, func_suffix, std_C:.-( =; r/O% =Z&2for]Q in [k_,^8 4_print3 j_file]qd = '%s_%s' % (!._7)__P)Q:wrapper(M= A$>P?try!A" =uexcept TypeError`OpassCrsetattr=u A9_get_pars8/er+&a = arg .ArgumentP@*1er.2r_signature.argsW*4 kw6acgXer, '!os', []T.add_:$(* e@ *=Pgroup_Os = ' +,`5in sz ? = _!(*Q *H2;7? 2sub@s' # if subparsers_sigs: subparsers = V.add_/()9Efor %a6 ins :sny%(*Qo.args,}C*E kwGcreturn fdef _test(self, 3er,,n_text)Nexpected = getattr(>L.func_suffixeBiwrap.dedent( ?i.assertEqual2 @j_forma1 = R_get_X02, 'b_%s' %P% rl", B?())Oprin@W_old_streamLBsys,std_nameTsb,, StdIOBuffer ->try% ).getvalueIofinall ( 2lf.  Y_file2I=2, 's* = -{% cBfQ# adds" {,}_{usage,help}8$, @1[('4', 'stdout') ('i:]AddTests(cls, p) base +Case, Help0 = F*tingMetaclass('!:1', M, {}) #?BiggerOptionals(: """Make sure that argument aligns when oIs are longer""" p2arser_signature = Sig(prog='PROG', description='DESCRIPTION', @epilEEPILOG'),argumentqQs = [I|'-v', '--version', ac} v='0.1')Ax4 store_true', help='X HELP7%-y#Y#5foo#?FOO%5bar%9BAR%][group #@usagA'''\4 :  [-h] [-vx-y Y] foo bar31''' 1 = B1 + WX @posiw4al %s: j="3bar coUaa-h, --@show thisA mes#and exitx -v9#! 9dram's number @xp/`k ,0~t=y<10.1'+ class TestShortColumns(HelpRCase)0''' extremely small Bof c=.-? prevents "COLUMNS" from being tooIin the tests rmselvesk but we don't want any exce1rown in such cases. Only ugly representac. def setUp(selfenv = support.EnvironOVarGuard(f,U.set(S, '15!\.addCleanup(env.__J2__)4p8=qBiggerOLals.6BJ K6 N @ N 6T q%! v (xB |'-v', '--#P', ac7&=' v='0.1')Ax4store_true',"='7%-y# #5foo#1FOO %5bar%9BAR%]g (GROUP TITLE'),MQ7bazZ%l-(nargs='+31]husage = '''\F : 9 [-h] [-vx] z Z [Z ...]] foo bar bazFZ!= U" +j%@posi+%als0 n U cMaa-h, --Ashow thiszA mes6Land v9! 9dram's  @xp Kf0k+zQB BA)u3 ! X10.1'p+6P3*,m='USAG:F2ekiefekang=EKI,,8 help = usage + '''\ DESCRIPTIONpositional arguments:3R ekifekang EKI HELP$3barc2BAR$%/ope -h, --helpAshow this message and exitWC -x3Xzv --y Y: Y"2'''version =  class TestHelpReformatting(RCase).6"""Make sure that text after short names starts on the first line""" parser_signatNa= Sig(prog='PROG',adescrie=' oddly.Ued\n'.';$is so long ituld go onto multiple s when wrapped')Qs = ['-x', metavar='XX',7!='? 8 0Z}&')fnym yy(0='n!1l y}7]_group(`title', /='s@'J[p-a', ac='store_true-'#='z'a -a 6/ /Zoagain,$bec_ over'3')]u(!'\w :  [-h] [-x XXea] yyy*r271 = 9+ + tfv$\ { ip  !yyR+ C!XXu!-x=3 G\<`7kak ^ &\ `uSvs* W"@ingSVNUse): """vMake sure that text after short names starts on the first line""" parser_signature = Sig(prog='PROG', description= 'D\nD' * 30) BargumentD`s = [ Sig('-x', metavar='XX', help='XHH HXPJ20),5y4 yy5YYH YH4]:_group(ALPHAS'),pa', act'store_true AH HAC10)]usage = '''\W: PROG [-h] [-x XXea] yyy*1''' 1 = 9" +NO?D D.$\ DWU!n@posi 4al c%s:5 'C\ YH4WP  oa-h, --a.aw thisA mesand exitE\ HX2XS" !-a[P\ HHA2 &*qversion class TestHelpWrappingLongN(RCase)?"""Olongnh='USAGE' Dsv', '--Q S='V Va  9%&25=* X-py7js_?2~&NAH AzzDZH Z;t _yyyyyyyyyyyyyoyyyy  _YH YH%\ *WTR Qoptional arguments: -h, --helpshow this message and exit@v@uversionC@program's onumberG?x Xna _XH XH%\ *WTRriALPHASf?a A_AH AH%\ *WTRPz$  _ZH ZH%\ *WTRP1''' a= '''\?V V.$\ DWU class TestHelpUv( RCase)V0""" basic u' Bs"""parser_signature = Sig(='PROG')~*Qs = [5'-w', nargs='+',k='w'),(x(*(x(aab u2ic% %$'?L]_group(#7'),y?xym(H%-z,3'z*dJ *+e+ +++]  :  [-h] [-w W [W ...]@x [XAy [Y0z Z^a b b [c] [d?Q e [eZ0S=+s%Oposi aBa:7 b bcc$! -h, --help  show this help message and exit $-w W [W ...]w@x [XU] x egroup:q -y [YBF8 y1z Z' zddee1''' version = '' class TestHelpOnlyUserG s(RCase)0""" basic u$,Bs"""parser_signature = Sig(prog='PROG', add_jq=False)argument:js = []I #"(i'xxxx'), [A-x', ='#!a Ea'), ] eOyyyyebDbDy!C e^%'\# : F [-x X] [-y Y] a b&b# =b+ '''\& N5 xE1 aa33b!xYx UHLongProgw s where the \ is longo' * 60z  Sig('-w', metavar='W [ X P2#P'P [-hY0w Wg`positional s=aubd/op5 a-h, --nO_sWrap.bos wrapUW * 25$%%YNJz3Z%bPPPPPPPPPPPPP* [-h] [-w W] \ [-x X]T?y Yn?z Z M5a b`1''' help = usage + '''\ positional arguments:7 a b7/op5 a-h, --xdshow this 1mesand exitia 'g'`'h'Tversion = '' class TestHelpULongProgPa`sWrap(!)RCase)j0""" s where the prog is long 0Y wrap"""parser_signature = Sig(E='P' * 60, add_q=False)<Qs = [G 'aBJ25),bcg[groupm#^%'\h/: LO a/ b Cc)5o'g cHO'HsOROG'-w', metavar='W(-x%X%y%Y%z%Z%.a'@ c$6-OROG AC? [-e_INa b E+ b s c optional arguments: -h, --help/show this message and exit@?w W'?x X'?y Y'?z Z'1''' version = '' class TestHelpUBPosi$`sWrap(!RCase)-0""" u0 s where the pD wrap"""parser_signature = Sig(prog='PROG')*Qs = [5k'-x'),yz|a' * 25=bc]q[group#h!'\4 : [-h] [-x X0y Y2z Z?.a/ bvHc.+=b+ '''\OJag W7x XH-y Y5z Z9dOsm1ss{K, metavar='X"'y'%Y%z%Z%}P] \ [#/[-3`V`  onal argumenUts: -h, --help show this message and exit@?x X'?y Y'?z Z'1''' version = '' class TestHelpUOptionalsOnlyWrap(#RCase)0""" u2 s where tare only oQ they wrap""" parser_signature = Sig(prog='PROG')(argument*Qs = [5 '-x', metavar='X' * 25),%y%Y%z%Z%]P[group# m!'\4 : [-h] [-o] \ [- jY/[-3=b+ '''\T OPosi<pS&`, add_o=False"a9bc8_(a/ b@c.ag cH VariableExpan cthat v2 s e8ded properly insHtype=intA'x %)s %(default 5 /%' ac='store_const', AQ=42, o='XXX'yyyt)s %(const)cs'),  Sig('--foo', choices='abc'$+ help='foo %(prog)s %(default <)^cbar', .W='bazm[1, 2], metavar='BBB}?bar}Odestzrspam', @ Xbadge40.5FH ]]argument_group_signatures = ["W(#7'),%-aaw 26bq%-1B!])usage = ('''\a: PROG [-h] [-x XyL {a,b,c}0BBB 0a A2b BaOco2'''1 = 1 + &positional z%s:! ZkGNone(})*E0.5 */opn a-h, --Kshow thisA mesYand exitU J2xfh int %+y%y+h42 XXX' Tya, b, c/V /vbaz barbB-a A5ag_1b Bb%%-1#1''' version = '' class TestHelpVariableExpan'UPSupplied(#+RCase)0"""s that v?ps are eEded properly wheng= is present"""fparser0 = t ='-#',>',3FOO@^# 1FOOCc=#3NoA6s/fith no@add_b=False 7  Aress A: """Test that items can be suppressed in usage mess""" parser_signature = Sig(prog='PROG',;A=arg-.SUPPRESS)AargumentCQs = [aN'--foo', help='foo :'),'Espam& ']-p[groupv#fq = '''\3positional B%s:! n) E#/op= `-h, --2 show thisq and exitst FOO 1''' qversion class TestHelpSO(RCase)0"""/<;"@add_>o=False2%{9Cm: : &" =&" +w%x~H8]GB/.%HT(Q'), [T--barui]Z }!e[-h] []2F{P:;KLJ_m [-h] [--foos FOO] 1''' help = usage + '''\ (optional arguments: -h, --A show this 1mesQand exit6@-foo0 0version = '' class TestHelpRequiredO(RCase)0"""s that r1 s don't lookRal"""parser_signature = Sig(prog='PROG')*Qs = [<5 '-%',a=True,$$='1'),6X[group^#!'\:p : a [-h] |i#^sAlternatePrefixCharsisplay with different pK characters,>_>s='^;', add_\o=False'P^^fooAcp='store_true'-c;b', ';;bar-1bardZ@] [;b BAR\0[L#" y!, $ &G No8E4the can be suppressedv P=&2L(Espam& '_|*x ] g "~@positR! ]<)y%ONoneuno errors occur if no is specifiedlI Sig('spam')q, ]argument_group_signatures = [#usage = '''\4> : PROG [-h] [--foo FOO] spam*1''' qhelp = 9" +NOpositional %s: R/op, a-h, --o show this 1mesand exitR% qversion class TestHelpTupleMetavar(estCase)0"""+ specifying m.p as a t@A""" wfparser = Sig(prog='l!')($*O5Q'-w', =' nargs='+',=('W1', 'W2'))>x> >*>X>X>y> >3zY< Y2/Y3zB B)'?ZD/w W1 [W2 ...]x [X1 [Xy Y1 Y2 Y3] \ [-z [Z1]KD~S  >w$; -8 x9H yz9 RawText4 Cthe 'ZFormatter/ 84, f?_A=argo.c adescriqp='Keep MRing\n' pexactlyit is written5here\n')( QSig('Eshould alsor0 'appear`given ',i w'(title', |TOtext +',be indented;$ Rlike !! [U--bar3bar]-L[YO BARX!formatting   exactly as it is written $Fherepositional arguments:,d spam: Fhelp?/op= `-h, --2 show this message and exits--foo FOOx4should also/&`appearjgiven Xtitle4T8texkbe indentedrhClikej m --bar BAR F1''' version = '' class TestHelpRawDescrif(RCase)0""" the RawTex9Formatter"""parser_signature = Sig(prog='PROG', f?_A=arg@.j,Kda='KeepTRing\nw' X 5B\n')Us = [ 'z!',L=' z?noto! bretain4oddNVing')&qRp {']_group(P9',  +';$  ! [')3')]-u.&!'\ : q [-h] [< MABAR]6{1 = Er + '''\,[A  Bh qm 2SlADefaultsU 0 ^<l 8ption='description') argument_signatures = [ Sig('--foo', help='foo  - oh and by the way, %(default)s'),Hbar', ac='store_true]1bar] <Espam& 'Pbadgednargs='?', ='woodenF, H]_group(@titlRdescr\'=' ! [3--baz', type=int$42e3baz]Fusage = '''\: PROG [-h] [A FOO 3barqz BAZ] @[XG1'''S1 = V" +k%B@posi%alQ%s:3 p) c ! " L": )oqa-h, --D show thisQA mesDGexit6?  INone9 yWFalse4 U! ) W542)qversion" class TestHelpVA~(RCase)0"""541for^2"""fparser(0 = `prog=' s G'-V', '--~A r='3.6')T#OV/j&'V {dram's anumber (  : SuppressB !at2 can be sGRed ingsY >ZGvGF1.0'DA=arg.SUPPRESS!e+' 'm/-foo FOO] spCam 1''' help = usage + '''\ (positional arguments:` spam( N?/op= `-h, --2 show this 1mesand exits--foo FOO 0 class TestHelpSubparsersOrdering(RCase)0"""# o$ of subcommands inatches the code"""~c_signature = Sig(prog='PROG',(*adescri/='display some!')CmPs = [o'-v', '--version', ac&=' ='0.1')]s&WPname=@for '.0('abcdeqq=q?  : 0 [-h] [-v] {a,b,c,d,e} ...2 N? 5 v9Edram's }number ) `:0.1>+@With&3 _data = (a7/')!('#b3Qc3d3e3)L,=W2]{Sa  Gb ?+ c  c subcommand help d d+ e#e+Woptional arguments: -h, --Kshow this message Hexit9v9version 9program's nnumber@A''' M)a= '''\50.1 , class TestHelpMetavarTypeFormatter(!RCase)"ldef custom_type(string)vrreturn 4parser_signature = Sig(='PROG', descrig'=' %',^ f_A=argm.)NPs = [P'a', _=int)} /$-b08c8float, m='SOME FLOAT')][group#uc  : b [-h] [-b&c pF] in3o!= M" +cOposi0 fB[#\ o8 -Lo # =A # OFal/Pconstructor testsPInvalidAzCT.s( a bunch of i> ? Bs"""`assert Error(self, *args, **kw i0r = .dP(lK.`uRaises(g!, <dr.add_w _ValuePh8%_v_keyworsWP('-x', bar=None-y', callback='foo'3Os=()5LF={})missing_destinaE(self): self.assertTypeError() for action in ['append', 'store']:+2N@=!) 1def test_invalid_ope_strings(I)\CValuF'--'$%uOtypek`foo', 3_='intz3(int, float)"3x', ='i %3?baz#=($, )vparser = arg .ArgumentPVWwith vRaises(v) as cm]Usr.add_aZ("--foo""f-true"kIn('unknown>', str(cm.exce multiple_dest+ S !7r'bar', e# supplied twice @posi al!',P I%no_U tse_constx__falseD\countxAttrswQdict(aint), nargs='+')+choices='ab')&%x''-P, **a 5J"noS"# _!s YEzerosyj% 'C?!#  is always disallowed)B i!# m*B6='*L kmore_than_one#?"]: =02((20/\rValueError('spam', nargs=0, action=G) # const is disallowed with non-op;al arguments>2forg in [1, '*', '+']:(q self.assertValueError('-x',}='foo',9= .{(}7def test_required_f_ s()$HIb'store3PSappenC[c#xs alway )t9TypGM='+'KBsparsers_missing_parampvcommandj'U!')l:, prog='PROGG) _class=arg#.AP^1BposiK   ?\=True\user_defined\ Success(Exce{Fpass4A5(object):1__init__tC_strings)OdestA odefaulB N[False0if Q == '"if5[)1T/3Uraise{Dcall{ *`, **kw  0r = (R#s(!, :dr.add_Q, '--9a#, =Y(=O # = 2 # s returned by $F CTestORN(!Catest_dest(self):# parser = arg .ArgumentP%()+action = (sr.add_a-('--foo'.self.assertEqual(?.dest, '-[b', '--bara -a xay^Ax') def test_misc(!):`)]6, nargs='?', const=42,nrdefault=84, type=int, choices=[1, 2]K help='FOO', metavar='BAR', _='bazJO, '?,O, 42`O, 84- _, int++", ,1'!, (-H!, I0i#, j_ # = 4 # ;flict handlingsF class TestConFHE([ase):@bad_j .#Raises(ValueError, c_3er=g#&ei +  g6 fg#Ospam]o6-kiresolve_hBget_ O)6(prog='PROG}F , w='OLD X1v09NEW0Apformat_e (), textwrap.dedent('''\pusage: [-h] [-x X]V! op al(sx -h, --v show this help message and exit D-x XYNEW X e''')) "parser.add_argument('--spam', metavar='OLD_SPAM'):  "3elf2", ).argument.0 (xZfloat=?/:2.50/`0.5, 1;2.5A[ HH HYO0V M''] Fx', O%r,  J  MV')" % e#%namespace&(ns N'0foo bOspamY"0(", <)X /nsp_starkws_notidentifier**{'"': 'quote'}JW = "" 0/""2?and.]a=1, & 54#valid': Truei+=)a def test_parser(self): a = arg .ArgumentP0prog='PROG')6string = (P"< , usage=None, description"Iformatter_class=%r, conflict_handler='error', =add_help=True)" %THelpF\elf.assertSaEqual(2r, j) # = # Namespace tests$ U Test-(qCase): 1defA_constructo(nsLRaises(AttributeE-, getattr, ns, 'x')_a=42, b='spam60ns.a, 42#4b, J eu. , O # =" #a_knowns2 class TesvK:PArgs(kCase):|s_tupleD2<(()nmrgumentParseSr() qparser._args([]) def testuments_tuple_positional(self):/QGqr = arg A.Arg<Phy5add`O('x' /,)OlistfM['x':"op(s)=W--foo-, extras = |Pknowne1s('8 F --barz'.split(){ .assertEqual(NS(foo='F'),s,![']1', 4z'] _mixed>Pv', n='?', const=1, type=int& --spam', ac='store_falseq<sbadger'argv = ["B", "C v354"]D2ZPv=3, r=True, O="B" (4"?# =" #a_inter}L/s < class TestI?ACCasen\basicE#mFing  V and sprog='PROG ', dest=' 5bar7 required.@?cmd Frest(/*'b = 'cmd A x 14ur y 2 3:< }(W # gets [1,2,3]/pite the foo/fstring`bar='y0md= ',DQ='x',k=[1, 2, 3] {# cannotn''X$K I0["1@23/o = 'cmd --foo x 1 --error 2 --bar y 3'.split() args, extras = parser._known_intermixed_-V(argv@A# un( optionals go intoVk-self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1]), zu J#['P', '243']%) #Tores attributes that were temporarily changed<uqIsNone(&r.usagebar.required, Truedef test_remainder(e%):t5# I~U and * are incompatible4@ = ERaisingArgumentP(prog='PROG'91.ad/O('-z" x! nW='....J = 'X A B -z Z#K fails with K (also 'AX # Gkqes(Type, jlNv) as cmWI? [egex(str(cm.excePp), r'\.'7exclusive7mutually $x group;Oworks fin=0^AE__&( = 3 -foo', ac] ='store_true', help='FOOTEEspam1GSPAM2rxbadger', *', default='XKgBADGERM[ 'Ufoo 2%@=['12$> , =&  /'1xluding posiAal -/.add_argument('"badger', nargs='*', default='X', help='BADGER') self.assertRaises(TypeError, parser._intermixed_cO, []GEqual(group.required, True) class TestIOMessageContent{("aCase):# case where : gives different e" mQ:@is rd by 1sting step*def test_missingument_name_in_X(4FAr = FaingArg=PC(prog='PROG', u'='C1.ad\9('req_pos', type=strp1-24opt2Tint, =Pwith  r) as cm;*(s(msg = str(cm.exceptionxegex(msg, )!) 9 %ONotR,?# =8 # 1 metavar/s : 4AddMA}_EXPECTED_MESSAGE = "length ofwuple does not match"a1do_d5no_P,O`1argp.]/rHs"--foo"a= g=5IABValutl (q.B[0], b# Unit^G forwvs BwhenV=Noneq__q_string 4\3"1"j0k ht/()l1l o_("1",ngs_None_metavar_length2(self): $.do_test_exception(nargs=None, metavar=("1", "2")) @Adef 8._._-o3o1T, "3"ta# Unitw s for different values ofa when /=?o%alostring -no(6"?"'?"1"  m0n  kdtuple(do1o  qs nrvru2*uzeroormorew-*woy"my q{ q xpz  s}wt2+?one~3+~n}"l} p|p| o{ r{vz self.do_test_exception(nargs="+", metavar=("1", "23")) # Unit ? s for different values ofCb when [2...A1def>__remainder_x_string(self):tx2.do.no7...3"1"plength0q,dtuple(&u1u,t2t1x3x5?, "/AOpars/_ n  l p s r  os s}21 1,1dk!bf faik hW eR iMiH22H2H self.%do_test_no_exception(nargs=2, metavar="1") def 1$3_2_#_length0(self):,0.ebtuple()f1f%_("1",e2e 0 hO "2"l3l 7iE, "3na# Unit s for different values ofb when 33ostring 3HdH!bH fHfw eH  eE iE  lH?# = # from argparse import *u > class TestI9PStar(jCase): quname in.__all__z~assertTrue(hasattr( , H J ex s_everything_but_modulesitems = [] ,Evars!).I)()6if not (O.startswith("_") or == 'ngettext'@inspect.is( +]u7Equal(sorted(3), F|HWrappingME\setUpMW r = ErrorRaisingArgumentPt%r(m'this_is_spammy_prog_(_a_long_?_sorry_about_the'H  # O%as trigge library $Pion es due to usageVP# mes matting incorrectly splion the ] chars %inIl = 'Fc.add_a<('--proxy', metavar=me ) def test_help_with_!q(self):&*!ptext = .parser.forma@%()."assertEqual(? , Ewrap.dedent('''\9k usage: this_is_spammy_prog a_long_name_sorry_about_the MQ [-h] [--proxy ]4 optional arguments$`-h, --Ashow 0mes and exit /''')) Smain(support.run_unit!(_"__)# Remove global references to avoid looking like we have)aleaks.RFile.seen = {}W@set(D if p == '__2__'K() # line 1 'A module docstring.' im sys, inspect4$5 74(a, b, c, d=3, e=4, f=5, *g, **h5eggs(b + d, c + f)L!11M"Cx, y2'"A"NRfr, sDfr =.currentframe&sIc.stackQp = xUq = y / 020 class StupidGitFP"""A 2er, in\"edG4"""*#27ef abuse#, 7_nother \tM?!containing!btabs \tDrgue!40p2tryQSexcep! exys.exc_infoz!%t@trac@propertyPradic/F='The automatic gainsaynEpass#53MalodorousPervert(`} Zd9 Ti  ParrotDropping:PFesteMGob(G+, AUQasynclobbest(grenade# It's intended that script be run by hand. ItPs spe0ests on # hashlib fun$s; it does not for correctness.Dtime T creatorFuncraise RuntimeErr,or("eek, creatorFunc not overridden") def test_scaled_msg( , name): iterations = 106201//'Q * 20$longStr = b'Z'* xcalCF =start = time.!()for f in range(ax = loZ(|).digestF;end\]print(('%2.2f' % (end-)), "seconds",, "x", lenlp, "byte(*Ls#e(Z S200003I5!'[i(]'Ozero, <2"" s hName = sys.argv[1] # # setup ourQ1 to the requested hash # if Oin ('_md5', '_sha'exec('import '+.$ =!r+'.new'("ing speed of old", , "legacy interface") elP== '_lib' andS) > 3, !0.%sJ?[2] 86" %2], getattr($,)/==lambda x=~ : x(%r)#0new= !as)h $bt_call__f F8Nd".""se-"|H8G  @6B try{_ze() except ValueError%a pass argument(s)VSrun ahhY on:"F $builtin md5'=shaDq'openssl_' 'fast'TsyNKC,s 8(shaFOO)")  print(" 'hName' tests the hashlib.() implementation if it exists") L otherwise*EusesTAnew(X)).<Hpraise r_zero() scaled_msg( =106201, name='[huge data]'2 1?lar21omediumd 542414*small2 53362325212222&10d creatorFunc().digest_sizex %105Etiny.3# To!attcrashers in@Lib// directory actually # do !4interpreter as expected # # If a+er is fixed, should be moved elsewhere suite to # ensut continues to work corly. import unitCDglob tos.path'@.sup8Q from.script_help_assert_python_failure CRASHER_DIR = hd.join( 0dir?(__file__), "M erB\FILESDDIR, "*.py") infinite_loops = ["0_re*, "nasty_eq_vs_dict] class C "(>.qCase): s@skip("these0@s aro fragile"]@_#.c2AonlyQ1def?_ q(self):#Pfor f8.(./3%if@base=(C)D "si:eg# Some ` triggqn excep ra{ than aFsegfault. Consider( t +cAable outcome.=i/~verboseiChecking2:",I/2 arDownModule(n reap_children(@f __z__ == "__main__"Mp() """ rs commontuple, lis d UserList. 6R4sys fpicklea* # Various iters # ThisPused cRpconstru"! (0and`_deque.py) def iterfunc(seqn): 'Regular generator'for i in ,+/yield i class Sequence!' using __getitem__Udef __init__(self,_`.s! =7L:i7Pretur!lf>4[i]IterFunc"it protocol*Wi = 0g,4nex,1if i >= len): raise StopQationQvJD]U += 1MvB?GenA defined with aXZ2valI8valNextOnly+L'Mis@ and?ter, NoeEor m!)?eTGenEx@Test1pag of excep$se 8 h3 // 0immediate stopApass/}` from \tools import chain yYmultiple tiers-M(map(lambda x:x,t (iD))))XLyingTuple(t __t61BList(list@`Common(unittest.CCaseN# The type to be %!ed2 = None _constructors(self):  l0 = [] 0 l102U, 1] &u = self.type2test()S 'l0 c 1 r '2)~u@uuuuuuvtuple(u)class OtherSeq:!ldef __init__( , Jseq))- .__data =(O3lenNEreturn lenpPisgetitemK?, iN&[i55s =({vsOassertEqual(Bv0),)c "this is also a sequence"vpvp# Create from various iteratablestfor s in ("123", "", range(100('do', 1.2)2000,2200,5)oPgPS, IterFunc EGen,amulti,Kfunc_, xlg(s)),sFOStopQP c cj` Raises(TypeError^NextOnly f%JoLHZeroDivisionaGenExcP# Issue #23757ZaLyingTO(2,) (1QList([2]O4[1]vDa_truthfQFalse y+=Tru* [4HtVvc[0, 1, 2, 3, 4]wiu@u[i][Q &Znt(i)+ q-rG, -1Pal(u[i], len(u)+i) self.assertEqual(u[int(i)], len2.Raises(IndexError, u.__getitem__, -@&-1r@?= _Value}slice(0,10,0)) Au = type2test(b 08$Q?Typa[10, 11]a[0], 1#1## -2$G -HZa9393%@def  h%):wPl = [2, 2, 3, 4]"lX8J 1 0:ZVE@u[1:F 3O[1])6 1-2:Z 838 P1000:O], uc % :-,],)[g :^_:NoneZ1 @/:3B# Extended sBx::04z!_1=?1,  :42, 1, 0} !::![4= 3>?3,  ?3:3z ?3:28, ?3:19%090[!00lz " ; [100:-100:-1], u[::-1])  self.assertEqual(u[-100:Q-1], !type2test([])=2<p0, 2, 4C# Test extreme cases with long ints,=a =0,1,2,3,4 a[ -pow(2,128): 3 01,2kca[ 3: I?45)F!) @def 6_contains(N!):fuW 1, 2for i in u:>MvIn(i, u4min(u)-1, max(u)+1E5NotHeRaises(TypeError, u._/__\_fakeclass AllEq# Sequences must use rich comparison agOt each item# (unless "is" is true, or an earlier7 answered:ASo insta"ofbe foundall non-empty s.a__eq__w, othersreturn TrueA__hash__ = None # Can't meet  invariant requiK9x/()?In(314 a_order 4A in-.}. If avhas sid# effects, these will be visible to~s.later membersp# In th'1estN "kaBa short-circuiting rGPDoNotEq(Exception6pas7QStopC*esU> qcheckfirstq81, ~'(){9fIn(1, J2/la] Z/, |[kW e<, 1h if sys.maxsize <= 2147483647d7-10n;;Typ/ class BadExc(Exception):HFpass3:Cmp(def __eq__({, otherMQ"ifZ == 2Dr^return Falseako, 2, 3c&2, a ,{WCmp()-_jg^(Y.+-G , . ?, - W ZO, -24*sys.maxsize, )V E),-P 2SAq_pickleF??lst4, 5, 6, 7zfor proto in range(T.HIGHEST_PROTOCOL + 1d]slst2 = 1Tloads>dumps(lst,_):K_, lst(#No idX zfree_after_iterating#support.check_2 , B,GreversedKPfrom 0 im T Tarray $io tmarshal4sys @unitP import os import types try: imp_testcapi except IRError)" = None class HelperMixin)Qdef h(self, sample, *extra)&|new = marshal.loads(kdumps(;);Z.assertEqual*6new&3with open(sup.TESTFN, "wb") as f2if,brb &(fXcfinall7kunlink)IntTestCase(unit.,%Q_intst # ; a range of Python - larger than the machine word size.Tn = sys.maxU ** 2cwhile xwfor expected in (-n, n%S1 u}qn >> 1 t.64SimulateAing TYPE_INT64 maxint64 = (1 << 63) - 1n4min!---0basq $, 5%, 4D, -( JKs = b'I' +.to_bytes(. , 8, 'little', signed=TrueJ=gots'h>got,0if  == -1: # a fixed-point for shiftWright\F% 0yNelse34>>=b'I\xfe\xdc\xba\x98\x76\x54\x32\x10' got, 0x1032547698badcf_t01\x23\x45\x67\x89\xab\xcd\xeft-uu 8\x19\x2a\x3b\x4c\x5d\x6e\x7u0x7f6e5d4c3b2a1908tf7\xe6\xd5\xc4\xb3\xa2\x91\x8]-u+9)Lbool\ba{, FalseWcbkOFloam%f<oBfew # small = 1eS-25  n = sys.maxsize * 3.7e250"while n > small:Bfor expected in (-n, n)%)self.helper(float(7)))Rn /= 123.4567 ff = 0.s = marshal.dumps(f, 2K7got"vloads(sassertEqual>6got! # and with version <= 1 s|led differently thenE1 %-<* T ', 8n *class StringTestCase(unittest.1, HRDMixiu@def %_unicode(xs["", "Andr\xe8 Previn0abc "*10000]O_Bs)))sIss_bytesrbb"b"/b"vExceptione3 =new dStopIterasH ), new) OCodeR]co = .0.__=%__8/co $coAQAmanykmobjectW# Issue2957: bad recucount on  @`= 5000r# more than MAX_MARSHAL_STACK_DEPTH< de((Q,) * tFpss_filenamco1 = compile("x f1Vexec"8co2)y# f2 )21, . 2(co(*Q eco1.coW, "f10202") @support.cpython_only def test_same_filen used(self):'+ps = """2f(): pass\ng5"""/co = compile(s, "my_", "exec")*marshal.loads(dumps(co).for obj in co.co_constsif isinstance(obj, types.CodeType0.assertIt\,s) class ContainerTestCase(unitS., HelperMixinyd = {'astring': 'foo@bar.baz.spam',  'afloat': 7283.430ninY2**20qshortlo`20lis3['.zyx.41']tuple': ( J,)*1]boolean': False@`unicodB"Andr\xe8 Previn1 } @.]_dictsQelf.h=;.d)6X6 .d.items())DE !o.d.keyELsetsD`ructor(set, frozenset 9X {@suppor eempty_n_singletonR}$# r) must reuse the J J="(kobj2 =bp7obj ?$) uOBuffrjbytearrayFb = Hb"abWb?new b`Equal(a(new),{smemoryviewsXAa = .l('B', HaH 6newT($gsug_5888452l# Simple-minded check ASF 53: Debug build crashesy [128] * 1000patch_873224Raises(Exception,`, '0') self.assertRaises(Exception, marshal.loads, 'f') oself.a9Hdumps(2**65)[:-1]) P def test_version_argument(f!):%x# Python 2.4.0 crashes for any call topOx, ydEqual(;5, 0)), 5@'1@Nfuzzasimple  that it's at least not *totally* trivia[ from bad U data&.c in [chr(i)?irange(256)]tY:try 9c#eF M?Kpass_2x_codes = b'c' + (b'X' * 4*4) + b'{U2**20: ValueErrorsArecu5D__limiCreate a deeply nested structure.head = lNE= [] # The max stack depth shoulFtch the vC*/cc# BUG: https://bugs.p.org/issue337# Windows always sqsmaximumPon re e and debug buildsif os.name == 'nt'-hasattr(sy1getIrefcount'eA MAX_MARSHAL_STACK_DEPTH = 100Oelse929o7- 2t.append([0]B[-1]z6 # Verify we don't blow outQwith /Z$ =i.#(g~@new_'D s(<'1# D~!us to compare objects, it can \!ed5Dlen(0), )3 P69:n~p!, cexact_type_match# Former bug3:  # >>> class Int(int): pass%type(loads(dumps(0I))))*<'u 'int'>for typ in b%, float, complex, tuple, list, dict, set, frozenset)# Note: str subes are not tested because they get handledKby marshal's routines objects supportingL buffer API.K0sub=2e('', (typ,), {},{self.assertRaises(ValueError,.m,qtyp()) t# Issue #1792 introduced a changem4howG increasessize of it#CSernala; thisJa ensur9!at>new code is exercised 1def5s_large_Y(=tF(1e60Stri= 'abc' * -4Q(0invalid_longs=T7019:#. shouldn't pT unnormalized PyLSisb'l\x02\x00'>*, k multiple_10_and|Z12291#() be callable YR time/`# witherleaved data written by non-0`# Adapfrom a patch3Engelbert GruberVp]R= (1,, b'def', 1.0, (2p', ['b'7c']5int!b')W0123'!milen = len6$positions = []:try/Sopen(P.TESTFN, 'wb') as f6:d#'kZ(d, f#0if L) f.e%.append(f.tell# r 1i, enumerate( kdPEqual+Z'(f(1)Pread(Rs 2_[i], /ofinallMCkunlinkR loads_reject_unicode_strings(self): $# Issue #14177: marshal.loads() should not accept uQ QJie = 'T'v .assertRaises(TypeError,t,aI!) Edef test_bad_readerclass BadRio.BytesIOLCAintoEH, bu%n = super().1+"qif n is(None and n > 4k,n += 10**6Kreturn nfor value in (1.0, 1j, b'0123456789',  }VO~,u](adumps('))_1eofaedata =@("hello", "dolly", F%))irange(len(J)Z?EOF0s, ?([0: i]) LARGE_SIZE = 2**31 pointer_size = 8 if sys.maxS> 0xF else 4 NullWriterqw 7, spass @unit3.skipIf(>w0, "'@ canrun on 32-bit(ctems")QLargesTestCase(icheck_unSlable.*hg ji&, ((@support.bigmem([= , memuse=2, dry_run=False7 _bC qb'x' * 0f8"st,` ;* ?+ 10 5tup(/,)3'Olist[]hsP*12 +`@.get1o:-1): /se3{hARGE_SIZE,  memuse=pointer_size*12 + sys.getof(LARGE_SIZE-1), @ dry_run=False) def test_frozenset(self, N!):$C.check_unmarshallable(9arange(91)) ;@support.bigmemj!=#, /2, bytearray90ize CollectObjectIDs(ids, obj3"""#ect ids seen in a structure"""`if id(A!6ids=breturn&sds.add(+;sinstanceC, (list, tuple, set, i)Pfor eq6objq /eltKdict[Ck, v^w.items(!fk!v%@ len) class IingTestCase(unitB., HelperMixinintobj = 123321uDfloaQ.23452str*"abcde"*3{"hello":@, "goodbye:/}eh3Arsamrecursivem8#we have two sOF = (Z~%]n0 = =), .Ss3 = r.dumps($2, 3T&T>loads(s3q5#same number of generatedelf.assertEqual(n3, n0uif not N  #can compare with version 2d/s22*n**2)<#old format@ mormqGreater(n2(1#if3lex s in there, zis largerH si EbAs2),)OelseGL?"In[Z.q!|"iCTrueIhF$Oj l $ ?Str_) self.helper3(self.strobj) def testDict!):.;Q.dict;"]#F^aModuleE`with open(__file__, "rb") as fjcode = f.read()^4if =P.endsTg(".py"i)Acompile(,;, "exec"X,3Recursion@d = L0d["u "]'RBd, r^vve=TrueQl = [-cEobj]Cl.append(l/*>3(lW class CompatibilityTestCase(unit4.k_A, vedata = marshal.dumpsS%`loads(: O20Tot 0/1/ 1/2/ 2/3/ 33) Interning1, HLSMixinQ = "this is an iLed string"<*Bsys."( He?s{bP assertEqual(s, *_)pid(s), ZH2 = uE2M)/No.O, 2)~#No( O@support.cpython_only @UskipUnless(-capi, 'requires #')_CAPI__write_long_to vfor v in range(sG + 1H3.py.g0x12345678, TESTFN, vR8 )O'rb'0 data = f.read() support.unlink(kTESTFN+elf.assertEqual(data, b'\x78\x56\x34\x12') ddef test_write_object_to_file(self):)obj = ('\u20ac'X ab123, 45.6, 7+8j, 'long line '*1000for v in range(marshal.version + 1rv_scapi.py.Zobj, 6, vzMwith openG, 'rb') as f2F? = >a.loadsl), obj_short_fromw!f.(Vxxxx'1r, p =   n r, 0x1234 $Cp, 2/+GKpRaises(EOFError%9ZdE . EO5678 46 ;#403"4ast9j@adumps(gK+ b'$ l+R+ r with open(support.TESTFN, 'wb') as f: f.write(data[:1])"with self.assertRaises(EOFError)P_testcapi.pymarshal_read_last_object_from_file }munlink+@def rd_7elfobj = ('\u20ac', b'ab123, 45.6, 7+8jfor v in range(.version + 1_[H4 = )dumps(obj, vV)[* + b'xxxx'Zr, p = & 0 M (Equal(r, obM) %ap, len1)) (#/JH9 if __name__ == "__main__"d@unit.b() # # codecencodings_jp.py # C - s Japanese`s. # &0 im? multibytec_   class Test_CP932(9."dBase, <CCaseE= 'cp932'ptstringWQ.load)('shift_jis?sUa# invalid s(b"abc\x81\x002\x84", "ict", None),;/f8'bZpreplace>Qufffdouff44"k D1\x8{H \XNPignor  00>`\xEBxy3 }\uFFFDxyn\xF0\x394 @\xEA9 50'abfd\ue038y'9# sjis vs VP\\\x7"B2(b""5f"61+7c3c\u2225 $0d) euc_common0\xc1\xc}e), (b"abbc\x80c1\xc4", "replace abc\ufffd7956"), (b" B@\xc8;F RL HPignor nurstrict", NonePf\x83U \x82\xFCxy9)xy2L6L 0\xao0S#"L)3cJ'/\\))\\+@8eXY'Q@fdXY(#) class Test_EUC_JIS_2004(multibytecodec_support.)BBase runittes+aCase):encoding = 'euc_jisj'tyPload_X)(Dqx0213')E$0 = dacommon!xmlcharnameA = ("\xab\u211c\xbb = \u2329\u1234 &a"b09\xa8ℜ\xa9\xb2 = ⟨ሴ&r "goXoR+oP_COMPATp' p*p' +(5"5<p("\u203;"' 7e#) shift@0enc.s/  8ofw#yR0def @ff44:), RS %Ag  Pr "1\x8replace", "abcf\ufffd"44 c"), (b"\\\x7e", "strict )),)x81\x5f\"61 7c1;uff3c\u2016\u2212qor (b"abc: 39:`replac 94oEA\xFC4 moFF\x589Xm ) class Test_SJIS_2004(multibytecodec_support.&Base, unittesaCase):9encoding = 'shift_jisT' t7cPload_Z)(F!')B!1 = cbcommonenc1+ (-0xa5$3e -\= fO64bfuL39xy 2>Xxyd@0\x8\2\x84:"k4# v@DO\x88Hn\u5864lFC\xFBA'c95b4y'xmlcharname' ="\xab\u211c\xbb = \u2329\u1234 &a"b"\x85Gℜ Q = ⟨ሴ&r "K+_X0213+<xT+.F10!- Kff44pF/JVP|# sjis vs cp932 [  @5ViPif ____ == "__main__"D() # Verify that gdb can pretty-print the various PyObject* types # # The code for wJ*was adapted from similar work in Unladen Swallow's # Lib/E_jit_gdb.py imgt locale$os rsubprocess import sys import sysconfig textwrapunittest from  +0supD.!Drun_@0, findfile, python_is_optimized def get_gdb_version(): try proc = sub ess.Popen(["gdb", "-nx-F1"],F=xstdout=U?IPE8?err80unial_newlines=True)Pwith 5Qion =.communicate()[0]?except OSError@# This is what "no 2 looks like. There may, however, be other^0# e[0s tImanifest t_way too.-draise .SkipTest("Couldn't on the path") B# Regex to parsea# 'GNU4 (GDB; SUSE Linux Enterpru12) 7.7\n' -> S =) Fedora 7.9.1-17.fc224946.1.1 [FreeBSD])<6.1)](7.5.1-3^318)617.56match = re.search(r"^.*?\b(\d+)\.3", /2if @cis Non#{EOu"unableMD GDBLt: %r" %[return (pa, int(m.group(1))g2))) ,d_major&in. => if<B < 7u\4gdbs before 7.0 dir! "2 "embedding. Saw %s.%s:\n%s8 0% ( eEXWif noB.is_d_build5f only workszqsource D0s ae moment.p# Locat~of custom h< in a repository checkout. _._` = os. d.join( dirname(sys.execut)#B '-gdb.py') PYTHONHASHSEED = '123'igdb(*args, **env_varsrp"""Runs|1--bQmode @addipal argu*s given by [.RHrs its (l, stderr) decoded `utf-8 using replace handlerW"""z4if 2env_environ.copy( env.update(env_vars) else: nv = None"# -nx: Do not execute commands from any .gdbinit ialization filesJ_ (issue #22188 base_cmd = ('gdb', '--batch 2nx')if (gdb_major_version, &in) >= (7, 4)f+g@-iex]add-auto-load-safe-path ' + checkout_hook_proc = sub ess.Popen(ba args,# Redirect stdin to prevent GDBZmessing withN the terminal settingy}w=?IPE ostdout4?err4renv=envo jout, err =.@unic5 return out.decode('utf-8replace')D  # Verify that "gdb" was built yembedded python support enabled: gdbpy_ = run_gdb("--eval-Cand=C!imBsys; print(sys._info)") if _' raise unittest.SkipTest(4/")@can / our custom #s, as OS security may # disallow this>Sout aDEizedH1. _py_errors20'--`0', h"9heen declined" in1X.Qmsg =cuse of1: "nX+p.rstrip()) def_has_frame_select(b# Does.dgdb have: .F6.6! ?/, dX0dirVL)Vmq0e.m(r'.*\[(.*)\].*y kmJ<!"U arNRutput2gdb"c! dim.group(1).split(+""''adir HAS_PYUP_PYDOWN =L BREAKPOINT_FN='tin_id' @]sskipIf(p.PGO, "0useful for PGO") class Debugger%s(GqCase): 0"""|gd8  ! PqB."""4S et_stack_trace(self, source=None, script= /  breakpoint=BREAKPOINT_FN,2cmds_after_=f import_site=False):`5''' Run 'python -c SOURCE' under gdb with a y%. =0Supf injecting commands G the: is reachedDqReturns+stdout from|%: if provided, a list of strings:D# We use "set@pendyes" to avoid blockR# Function "foo" not defined.|(9Makkon future shared library load? (y or [n])Nerror, which typically happens is dynamlinked (theKsDinterest arebe found in 0Whe#$is, we still get5textiowrr_writeEpemittedpstderr V time, alasq# InitiI had "--eval-=continue" here, but removed it to&PrepeaHprin81s w`ravers*hierarch|W dataMPstrucs# Generates}gdb's languageN$O= [''g'g %s' %,# The tests assume that@firs0ameH"%ed G backtrace w 50aingram cou"# znaoweveryguaranteed byt@foren0!toCp addres(f' msh. For exampl H #0@PyObT!_Pb&..D /ad@some Ris can be e.gB#0 0x00003fffb7dd1798*;f'run']Wp# GDB a^ 7.4 onward0disUuish betweYAvaluga variable at entry vs current (,http://sourceware.org/gdb/onl1ocsVYes.htmlI# which leads "to the selftests failing with errors like this: # AssertionE': 'v@entry=()' != '()'1lDisablIif (gdb_major_version, &in) >= (7, 4) commands += ['set print -values no'] if cmds_after_breakpointY/POelse<['backtrace#t# Use "" to generat>e argumentsPwhich%invoke "gdb"Pargs s--eval-X`=%s' % A for3in %s]?\0"-- %",sys.execut <.extend(subprocess._H_from_interpreflags()) if not import_sitg# -S suppressesdefault '6 6~.J"-S"[source/Bc", #elif scrip@8i"M(' '.join(gdb, capturstdout, stderrerr = run_gdb(*K, PYTHONHASHSEED=perrlineMerr.split%()unexpected_/[Ignore some benign messages on.Si/_pattern~(P'FuncQ "%s"1defined. 'Do you need "8solib-search-path" or <'*ysroot"?'T# BFD: /usr/lib/debug/(...): unitialize decom # status"se.O_aranges0'x ; all warning7+: ;0 in ncontinue2p.startsn( N^@.app_# Ensure no 6%orn!.afEqual(4F, []return outpdef getX`_repr(S. &V_=None1 g=False$# Given an input pythO esentation of data,# +# run "python -c'id(DATA)'" under gdb with a breakpoint onC builtin_id and scrape out='s representation of the "op"Eparameter,Everify that.displayssame stringF / VA expectedE For a nes(qucture,first time we hi$Gwillbgive utop-level}U +NOTE: avoid decoding too much@traceback as someA codable characters may lurkre in optimized modB(issue #19743).\cmds_after_/= Por ["E 1"]I gdb_output = self.get_stack_.(source,w=BREAKPOINT_FN,L=Wimport_site= )# can insert addiqal '\n'Ispacin various placesP`in its^put, depen  onV widt$erminal it's connO`to (us`V"wrap_here" funcm = re.match(r'.*#0\s+P\s+\( \=.*,\s+v=\s*(.*?)\)\s+at"1S*Pn /b5module.c.*'y),~fDOTALLif not m:.fail('UnEt: %r\n%s' % (b )dreturn m.group(1),`def asEndsWith , actual, exp_end)'''Ensurebiven "4"Bends"FE"'''|RTrue(>.6(4)` msg='%r didM2endp!%r!R)MultilineM+eswpattern K,?re.  i)uample_scriptfindfile('"s2.py') class PrettyPrintTests(DebuggerQ&test_getting_ wfF42)'  . in gdb_outpu%t) def assertGdbRepr(self, val, exp_repr=None):15# Ensure that gdb's rendering of theB ue in a debugged processI`matche?pr(value)4Dthis.x1gdb,t_output = T.get_ ('id(' + asciiW) + ')')zeif notd0 = A:n3dEqual(v0,-N ('%r did~@ected %r; full was:\n%s'O? %  '))test_intq'Verifypretty-printvarious intB&42h0 /-7 '10* -+<000singletonsTrue, False and 1 L" d Odict4ionarie /{} {'foo': 'bar'}, ""=# Python preserveHqion order since 3.6E a, 'douglas': 42 "<?lis<4 &[]A(range(5Obyte4 'b'@b'Anw for someth@hopeOsameH !st with embedded NUL here \0,Athenf0 moA?extX  is a tab:\t Z 6b' 0slash-N:\n4OR:\r4 PuU 255:\xff128:\x80'H ![bb>]255)]Che pretty-pr inting of unicode strings' Pencod%= locale.getpreferred%()1def check_repr(text):V:tryAext.O!e(6ingU"printable = TrueXexcept UEneErrornself.assertGdbRr, ascii ~OelseH%) j&''[And now for somethhopefully the sameG  with embedded NUL here \0 andLne` more 'q# Test wa single characte\# U+2620 SKULL AND CROSSBONES0'\u0s JapaneseP# (I believe this reads "mojibake", u& 3`s fromG CJKL0Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)J 6587\u5b5P316\uAap outsidVe BMPk 1D121 MUSICAL SYMBOL C CLEF0# T(is> UTF-8: 0xF0 0x9D 0x84 0xA18% 16&0D836DD2 achr(0x)<test_tuples(b'Verifupretty-c2of 5> X(), '() 1(1,'/1,) 'foo', 'bar-z'?set3if (gdb_major_version, &in) < (7, 37a @skip/(">p` needsV 7.3 or later"y set(), "+P['a']0W{'a'}0# PYTHONHASHSEED isq to gettPexactzenset item orderif not sys.flags.ignore_environment > r4, 5, 6 <`# Ensu=hat we handle pcontain<"dummy" key value,G which happens on deletion'W1output = Dget_ Q('''s!t('b']) s.remove('a') id(s)''') self.assertEqual(gdb_repr, "{'b'}") -def test_frozensets(=!):O'Verify the pretty-printing of 9'31if rmajor_version, 6min) < (7, 3os.skipTest("v ` needs\ 7.3 or later" GdbRepr(W(), "7Z['a']<g{'a'})A# PYTHONHASHSEED isq to getQVexactD item orderMnot sys.flags.ignore_environment>O, 'b O|4, 5, 6 Miexceptioni #  a RuntimeErro= output = +@get_ (''' tryYraiseQ("I am an e`2") %R as eBoid(e) ^5 ")(' ',79 division by zero!S a = 1 / 0SZeroDem@ d,('&modern_clas( new-style > instances@F#Fopass foo = Foo() `.an_in42 id(foom = re.match(r''True(m,xmsg='Unexpected `renderP%r' %G( 1subing_list%%an4 a D U-(NC += [1, 2, 3]X7%r' % gdb_repr) def test_subclassing_tuple(self):&*'Verify the pretty-printing of an instance E W'H# This should exerciseWnegative tp_dictoffset code in#Fnew-style support"gdb_repr, output = P.get_ R(''' CAFoo(pass foo = (1, 2, 3))`.an_inS42 id(foo)''')m = re.match(r''assertTrue(m,jmsg='Unexpected +`renderQ%r' %!ni2San , source, corruption, exp7S=None3'''Run Python ulc<ng variables inferior processimmediately before taka backtrace.~ at2j0's `esenta1 is!'failsafe{ 0(a'if $cmds_after_breakpoint=[8'%']mOelseJ >?<\!D  &* $if! if? ==$#' managed to oAvaluAspitpc;0# tv is good (see http://bugs.p.org/issue8330freturnl0# M` anyth1fortype name; 0xDEADBEEF c5 tob# someAarbitrarypattern = '<.*] ??if not mL3(k;gdbg: %r\n%si R()NULL_ptr@Ensu`hat a ' PyObject*handled g/VfullyzE = ( <'id(42)'8/ (0=['O v=0IO '> self.assertEqu&al(gdb_repr, '0x0') def test_NULL_ob_type(self):!%'Ensure that a PyObject* with : : is handled gracefully'JY.assertSane('id(42)',"p'set v->a=corrupt##a ?XxDEADBEEF0expM='42_tp_flags a J J8$->`=z?namIH_/=0-builtins_help the new-style class _Helper in site.py can be'sqif sys.T@.no_1"skipTest("needW module, but -S option was used"mCq# (thisissue causing t4backs in # http://bugs.python.org/>8032#msg100537 )8 output = @get_f%__j _.l)', import W=Truem = re.match(r'', p_/(mmsg='Unexpected render5W%r' %]creferential_listG'1ce loop involvl a @ doesn't lead proxyvalxinto an infinitE6:''T \CG."a = [3, 4, 5] ; a.append(a) ; i"^:EquF, [...]]fy5bab(dict(self): < '''Ensure that a reference loop involving a dict doesn't lead proxyval into an infinitEE:'''"gdb_repr, output = \!Hself.get_$.("a = {} ; b p'bar':aa['foo'] = b ; id(a)") PLassertEqual(TA, "{;2: {P {...}}}?def test_D tial_old_style_instance(#%):ve *class FooNpass foo = () .an_attr = foo id(foo)''').True(re.match(r'\) at remote 0x-?[0-9a-f]+>',W),'Unexpected /esentation: %r\n%s' % pv])?newPs(object   9?`Foo() @ aG7b baSaQ%_zQtrunc r'Verifylvery long C is ;/ed1 #'id(list(range(1000))) "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, "K14, 15, 16, 17, 18, 19, 20, 2d2, 23, 24, 25, 26P 27, 28, 29, 30, 31, 3 3, 34, 35, 36, 37, 38, 39P  ("40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, " B $"53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65P #66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78P #79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91P 92, 93, 94, 95, 96, 97, 98, 99, 100123P 0104&5678N1N1N1N1N 1N1N1N1N1N1N2N2N2N2N 2N2N2N2N2N2N3N3N3N3N 3N3N3N3N3N3N111x 1111111111N 111111111N 111111111N 111111111N 111111111N 11 1 1 1 2 201, 202" 2 0205+678@9, 2 2 2 2  2 2 2 2 2 2 2 2 2 2  2 2 226...(truncated)") self.assertEqual(len(gdb_repr),( E 1024 + /'^A')) 8 def test_builtin_method(t!):#Wn , output = &P.get_('import sys; id(sys.stdout.readlines)'True(re.match(r'<B-in  A' of _io.TextIOWrapper object at remote 0x-?[0-9a-f]+>')U'Unexpected  esentation: %r\n%s' % \>[ S oframesstack_trace(''' foo(a, b, c`pass , 5) id(foo.__code__)'',   breakpoint='builtin_id', " cmds_after_N['print (PyFrameObject*)(((PyCodv)->co_zombief+?)']),self.assertTrue(re.match(r'.*\s+\$1 =\s+, 0x-?[0-9a-f]+, for file , line 3, in foo \(\)\s+.*gdb_outputKre.DOTALL)-'Unexpected gdb representation: %r\n%s' % (|+)) @unittest.skipIf(python_is_optimized(!"P) was compiled with 8s") class PyListTests(Debugger!):Bdef (@ing($, , actual/!EndsWith(%7%) ^_basic_commandcQ 'Verify that the "py-list"2q works'TQbt = get_stack_trace(script=bample_RP G#']5h @P' 5&\n (6bar(a, b, c):9795baz9884(9(z(*args0>107oid(42)i 11.(2(foo(1, 2, 3\S btone_abs_ar}_ne absolute argumenti/ 94twosV>twogN cmds_after_breakpoint=['py-list 1,3'])  self.assertListing(' 1# Sample script for use by test_gdb.py\n'N6 N2(3(def foo(a, b, c):\n',b bt) class StackNavigationTests(Debugger!):KP@unit.skipUnless(HAS_PYUP_PYDOWN, "" requires py-up/py-down commands")R If(python_is_optimized()!"P-@ wasXpiled with <k"c_pyup_(G'Verify that the ""`f worksPbt = D`.get_sIr_trace(=__cmds_Pup',  up3nMultilineMatches(btG= r'''^.* #[0-9]+ Frame 0x-?aa-f]+,file .*gdb_sP.py, s 7, in bar \(a=1, b=2, c=3\Dbaz\s\) $'''^c?_at_bottomhandling of6#" ; oEndsWith 'Unable to find a newer  f/\nP up?top%up?top|B * 5a'_n oldX Sup_then_ followedd4"cript=self.get_sample_script(), cmds_after_breakpoint=['py-up', udown'])Wself.assertMultilineMatches(bt r'''^.* #[0-9]+ Frame 0x-?a-f]+, for file .*gdbP.py, s 7, in bar \(a=1, b=2, c=3\baz\(a, b, c\)k*#10lzlrgs=\(1, 2, 3\)oid\(42\) $''') class PyBtTests(Debugger!):O@unittest.skipIf(python_is_optimized!"P- was compiled with <rations"@def j@_bt(+ 'Verify that the "py-bt"Vmand works'0Pbt = D .gtack_trace(=:/btETback \(most recent call first\0 F""PU;7 6 < 43foo<r< !12=!class PyLsTests(Debugger GJ} _ck_trace(script=self.get_sample_script(), cmds_after_breakpoint=['py-up', locals'])Pr assertMultilineMatches(btx r".*\nargs = \(1, 2, 3\)\n.*") l@unittest.skipUnless(HAS_PYUP_PYDOWN, "" requires /py-down commands" RIf(python_is_optimized:!"P-@ wasXpiled with <Tationk@def _@f0up(>!):Pbt = tack_trace(NS = 1\nb = 2\nc = 3)Smain(if support.verbose2print("GDB version %s.%s:" % (gdb_major_!, &in)@for 1 in(5`.splits. " * 4 +>PDrun_(PrettyP_TestsoPyListS QNavigX'?PyBCP[) if __name__ == "__2__"P() imd types   class j(.CCase init_sub4 0" A0 20ial = FalseC!\ __'Yc__(cls|(super().0$@cls.V}7Tru|;B(AhFpassQ((AUv(g*(B'OdictK( =g!Q kwS ,B, **H b[2 =  class B(A, x=3): Upass self.assertEqual(B.kwargs, dict(@)/def test_init_subclass_error(Hi* AzA_>W_(cls9raise RuntimeEc Pwith qR,(s(- R;B(AN_wrong+, whatever 2Typ A*skippedBaseWithInitB, **> super().50@cls.nialized = cl0out( ^Uass A1A4 wHIs(AE, A) (b 6 n odiamonicalls = []ALefth] ,oMiddlem/{BB+= [e ORighK`cls, r4!=""Le A(", i!, ", "="" 7!A.-5, [I]7:) *jgset_nameDescriptorV<!__>, owner, P 6#" =+#?! =F  6 = (MI@A.d.Y_, "d"XtIs(A.d.owner, A) def test_set_name_metaclass(self):'+ Meta(typeI__new__(cls, M`, base s/3ret = super().= 8.assertEqual(ret.d.uO"d")2 #Is/owner, ret0return 0(tDescriptorG_?#, c#" =+?! =T %A(= fFd = ({BOA, 0Qerror`@'1/qWwith Raises(RuntimeEz) as cmNotGoingToWork"Lattr~exc = cm.exceptionegex(str(exc), r'\bw?\b'sR:06IsInstance .__cause__, ZeroDivisionIX _wrong08~BpasswI3Typ/ollookuppresolveD%[]_n ^_P__get_ d.append('mAaW = No(2NotIn('_ _',7  3@ is ed up in iUc dict'{ :init_sub [ 8ef >M* self.name = name class Meta(type):!def __new__(cls,=`, base s/3self = super().> l=.meta_ownerHAelf. -, +preturn Ainit_sub2cls0 = d ~' PB(A, t= sd = Descriptor()B.assertIs(BE, B)"Equal(B._, 'd'&HMt9test_set_j_modifying_dict(pnotifie![]B a_T!, -aOsetattr(& + 'x', None -.append({ EaIb c  S FkRCount, ['a', 'bcd3e']aerrorsgZ MyDFpassAwithRaises(TypeE_Y]C(=o, otherarg=19=z* s.rA("My", (object,),do  nnprepare_rIe I!__ [amespaceJDkC"gOrarg):  super().__init__(name, bases, vspace) 3 self.otherarg =  *class MyCQ(meta=MyMeta,2E=1):5]FpassGiassertEqual(R}B, 1)/def test_errors_changed_pep487(Jkq# These2s failed before Python 3.6, PEP 487 W(typeT__new__(clFS :vreturn  E=J=@Adict?8Pwith .dRaises(TypeEF  - ?<(=r/ =FA#2elf%@ At = A'New', (object,), {}= IsInstance(t,A'@t.__F__, ghQ=N=T if == "__main__"h@unit.() import #__multiprocessing from. =0supE| B.PGOqrI`.SkipTest("] is not helpful for PGO") . .i!lls_in_module_ (globals(), 'forkserver')''collectionsTdeque(5R, seq4$gc tweakrefDcopy Upicklgdrandomstruct BIG = 10 p( yaSyntaxyield 1 bBadCmpAa__eq__:NRbRuntimGkMutateJJK!, 6, resultT." =%o1# =::Uv.clear(return self.result class TestBasic(unittest.Case): def  _b(s(self): = deque(range(-5125, -5000))'.__init__(2for i in E200, 400hl.append(iY:seversed`-D/0)CHleftG.assertEqual(list(d), T:!en9B600)Cq = [d.pop 6() ;U250)]2X/ft?50) 5^)Uright .".rs( ) 1~ 7u ~81%lmaxlenTRaises(ValueError,, 'abc', -1828i>Citer1&Bit, &=3=it), []'Areprm'[7, 8, 9]e'@h9-d77, 3|d/10FsG, 10C!7F-Pd.ext'w[10, 11`hi [9 /J_[8, 7LK0&(dsupport.unlink(fTESTFN'pfo = op 1"V, "w"'6try~fo.write(stM*Wcloselrl+ tfo.read(), snfinall%d|510){FNone~ $, `Q, 2, 3, 4, 5, 6, ky self.assertEqual(fo.read(), repr(d)) finally:fo.close((support.unlink(TESTFN) C def test_maxlen_zero(self)cit = iter(range(100deque(it, C&=0I list(it), []b 2 = fbd.extendUOwW1lef{ tattributey ").o, Nonen/_'abc'4!4>4o;2;2;0;SWwith Raises(ADWErrordA N[ = 10\countfor s in ('', 'abracadsimsalabim'*500+rMsAs = s s`letterxS defghijklmnopqrstuvwxyz'iU,_"s.QL), ds(s, d, !KwATyperF)t # too few argsrCs, 1, 2)CJmanyDclass BadCompare^a__eq__l, other: Arithmetic[,p/3] UbT% (&Mutating++[d.popcHeturn TrueKm = {: \3, m, 4, 5W!m.(T(~kRuntim7, 3Z# issue11004O # block advance failed aff ro7on aligned elements on right side ofFV[F]*16)irange(len(d)):' d.rotate(-1)self.assertEqual(d.count(1), 0<(None), 16) idef test_comparisons(>!): d = deque('xabc'); d.popleft(tfor e in [d,0/$') ), list(d)]jn} ==e, type(d)== de) andB!==K&e)J!JAnot(EN$Largs = map( , ('', 'ababB, 'x5w, 'cba'0x0\ y #cx == yR x)y), (x,yv@D!D"!=_D(< /< D" <">>">>"BNntai?rn = 200p{Pwrange(ni QTrue(+d (n+1) notSd # Test detection of muta during iter d[n//2] = MHeCmp(d, FalseWwith Raises(RuntimeErrorztn>` exceps0Bad5oextendT&a't2TypB, d.L', _('bcdJ*dw!'a/zHNDHn/adueZ3f?def Ed + pIJTe + f~Ys1e11 bself.assertEqual(d + e, deque('abc')) self.assertIsNot.d.) Ee + )W 7g =def', maxlen=4h&6gh'Equal(g + h0'ef.%) nWwith 5Raises(TypeError):+&9@ + 'Mdef test_iadd(R;dad += 'bcd'e9list(d), \dCd?aq)extendleft 5F, d.P6, 1(Rreversed: VdR NJdcbaRH `range(1000 =?MaSyntax O]fail(|getitemun = 200"n2l =gfor i in  A.pop=50l*(0 ifFdom.random() < 0.5S?d.append(iBljp1-len(lAF d[j] == l[j]0'superman ad[0], 's$ -1%Ig]FInde#__G__, d8,-1 ie GVnV1, 2, 30, 40,Z:, 0* II#L"d.Si), i)OValu4P$n+ # Test detection of muta during iterT:d[n//2] = MPeCmp(d, False"oRuntim # Test detection of comparison exceptions d = deque(range(n)) [n//2] = BadCmp(with self.assertRaises(RuntimeError):Q|d.index(n) &# Test start and stop arguments behavior matches listH2ele/= 'ABCDEFGHI'e3non"V = 'Z Vs * 2X1s =q(3for2in I-5 - len(s)*2, 5 +Y ??op >"RBE 0s + m/?tryarget = scR,&op3iR Valuf>;<gH?lseoEqual(a 1, t&def test__bug_24913(Vkv'A' * 3Gi"Hello world", 0, 4 yto make sure in*tk!ke<sii 7 .2 ( "0(i, i_d), s^L6194h@datav?ABCx, maxlen=8IIhs2, None1p % 3!),Z" :)+1if i >= 0[zOd[i]e>$-1@5Z * n)C0IsNone(d.499, 5001 '0/d Rmin(nK.6_bcdef+Cs$z2('aI[-500:]!def test_mul('bc( T * -5*0)1)'W 2.a314Pt(d *EdjXD0) *rQ //m U-5 * Z 0)1)2.dE314 ", K/=5 x#bc m3*'1|setitemqn = 200,b2hrange(-i- p[i] = 1!iQ list(d), [10*i U]Cl = /P 011-n'-17*i l[i] = 7*i self.assertEqual(list(d), l) &def test_delitem(3!):Epn = 500 # O(n**2)6 , don't make this too big@d = deque(range(n))kRaises(IndexError, d.___, -n-1;$n8for i in 0!en/6n-iE*0j =Ddom.randO#-l/ 20val 5[j]IsIn(val, d9_del d7?Not:X 0reverse>pata = [&]om()   Ldata[:i])r`.   5%d(Z s(r, Nonecd{mEType@, 1)# Arity is zero]rotats = tuple('abcde's(ezs)#d.\ # verify rot(b''.joia 'e't-u t)ua_# check default to 1cYfD '*3geeeD i3vs. n timesTj i#e^ e<V-that it works rk@rapsOwardhOe), U h e.rota te(-1) # check vs. rotn times  self.assertEqual(tuple(d), 9e))1d.rotate(ihHm that it works in reverseArskek$-nm kraps backaroundkue), s) +d = deque(edBIG+17 # verify on long series of}'atu drYHQfor i2Sange(_: g6dr( F?.Raises(TypeError, P, 'x'@# Wrvarg typG1, 10) # Too many argsp(#A an empty"d,"#()def test_len()WF'ab'' <2$d.popleft 818404UIndex?pop-Qd.append('c :/'d> 5Oclea underflow2- QSr7100B-Y'"d.[\1ist&[]J\i!# thl]oremove'abcdefghcij@#d.9 6'abFG#FMGValu3/, e/|# Handle comparison e['a', 'b', BadCmp(), 'c']) e = deque(d) self.assertRaises(RuntimeError, d.remove, 'c'7for x, y in zip(d, e):V]&# verify that original order and values are retained.BTrue(x is y) %# Handle evil mutatorPmatch(Bl, Falsdf['ab']d.extend([M`1eCmY) 1R_IndexP j9PEqualU)def test_repr(0trange(200)Qeval(;dGwlist(d), e+Pd.app AIn('...', e_prints:tryksupport.unlink(fTESTFNefo = open&Z, "w"+d, file=fo, end='Qz.close(=hrh fo.read()IkfEl/fo =ini5TypK, 'abc', 2, 3);S:21); LhashJ 1, *long_steadystate_queue_poplef3Asize2A0, 1 10 7000n r:.#0P, popf@W2.i|P[, BIGx+Y*(iv0x =o if x != i - \ E"qPx, i-0 l (/81BIG;Origh7eversed($ self.assertEqual(list(reversedd))),  6ange(BIG-size, BIG))) :def test_big_queue_popleft(self):&cEpass d = deque()append, pop.#d.R*for i in rhl;&(i]30x =zIif x != iE.assbOx, i Mrigh U!,  ostack_,:I J52 6len(d), 0;1 N7"I;38roundtrip_iter_initF200)+e~d#NoS!idGid(e?*zM+:lpickled',:[, 100@$e.HIGHEST_PROTOCOL + 19 .dumps(d*Yvloads(s1(9Ae), @2 A1Adle3e.maxlen- __recursiv d'abc'){;, 3;d(9* e D self.asse rtNotEqual(id(e), id(d)) self.asser/B[-1]3e3e.maxlen, d !) i def test_iterator_pickle(v!):$orig = deque(range(200{ data = [i*1.01 for i in 9]GPprotoGp.HIGHEST_PROTOCOL + 1# initial X@itor(w Ksdump = o1s((4,1), 6Vit, d7`loads(= '@i, x@enumL e( d[i] = xp type(it), 7orgpI 4Blist4{*# running?0nex<f 8C[1:]8# empty:b1, lenh[bxhaustedfRaises(StopIPion, Y!,  Zdeepcopy0mut&10V[mut]H@e = D.MdAd), Pmut[0%11f?@i*c, lY2I+ 11 self.assertNotEqual(id(d), id(e)) *'Alist) +,for i in range(5):Nfmaxlen$[-1, 6(,s = [random.0() Aj<9i)]`8d = deque(s) if p== -1 else,?eCn.copy( Od, e'.3, e 5 True(all(x is y@x, yAzip(v1)) def test__method(X0mutR&103+V[mut]P2=mut[0] = 11?q4}reverse.s1('abcd',W2000) ZRA)), -s)L_new@klasTtype()(_J/jZgc_doesnt_blowupimport gc# This used to QP-failxA_tra() under a debugEbuild, or run wild with a NULL pointerSa release 4.EE;100d.append(15~gc.collect(cntainer_iterator&# Bug #3680: tp was not implemented' O objectsc3"C( 6pas* 2,{obj = Cref = weakref.refi if i == 0*#co4ww[obj, 1O(z> G qobj.x =.(} $0delE%, L  )None, "Cycle!3ed"#check_sizeoR0sup..@python_onlyF ZBLOCKLEN = 641@base05 = Ypalcvobj('2P4nP') blocksize = struct.calc('P%dPP' % BLOCKLEN)  self.assertEqual(object.__;of__(deque()), base?PchecksG 8aDCq + bloc O-7'a's0D * (H - 1A@ |?2 *4+E F*43G class TestVariousIteratorArgs(unittest.!qCase): X@def B_con0or(!): for s in ("123", "", range(1000), ('do', 1.2)2000,2200,5)LPgP@seq_~0s.SVnce, UFunc,> *?Gen=OStopAitermultiCKfunc" Clistn@g(s)/ <Raises(TypeError, "NextOnlyYK-oMIZeroDivision aGenExcQQ>_with_altered_data\2d =('abcdefg'Pit = H&(dfd.pop(OdRuntimRnext, it)r& _ey_on_empty_xappend(10*D N|Spass pWithBad ) __4,__rn mP1Sub{)lbasics\(625)d.__init__'00`i;s00, 400o#d.[iY:seversed`-x, 0yCWleft(GAd), T:0en(93600qqA = [ 6() JQ250)]B1X/ft?50)  5^)right = [d.pop() for i in range(250)] right.reverse()self.assertEqual()r, list(I150, 400))70)d)98!158pd.clear @len(J10) 7def test_copy_pickle("):!d = Deque('abc';re = d._>_y Atypez e+pd0c A<  [+lVproto .HIGHEST_PROTOCOL + 1):9i3 = .dumps(d, M'@'zloads(s #NoE!idH0id(F.p 3 /  de', maxlen=43_recursiv8\A*=dzy,;, 3uupd.appen$ o. 9+Ae), 2 13"e.d3, d 5dWd.pop~eeRI 0Ge, d$0d.x p }".x| k 9WithBadIterD ;, 2O self.ass:ertRaises(TypeError, pickle.dumps, d, proto) def test_weakref(self):  = deque('gallahad')Cp = 9.proxy(dJ.assertEqual(str(p), &d))d = NoneW:Referenc st strange_subclass(I1 X(ef __iter__8 preturn %7([]1 = X([1,2,32X4,5,601 == d2 # not clear if this is supposed to be True or False, # but it u6give a System 2 SWithKwargsc__init @, ne''=14D.()aOTeste@unitl. CCaseOqp_with_kt # SF bug #1486663 --7erroneously r5 a d nce(seq_s.CommonPtype2- \|getitemW# For now, bypasss that require slicing(_& `5subscriptEpfree_af|\_atingl2P.skip("Exhaustedator doesn't " ao") #=: libref+""" Example from the Library : Doc/libcollections.tex >>>=r import"c{('ghi')>0mak12new8 ` three)!msIfor elem in d:GIae overy!'s8ents ...:`print(O.upper()) G H Ikd.append('j<Padd a` entry.Dright sideI~left('fM/# I2Ha# showrepresenta oeY (['f', 'ghiCj'])Npop("#  and remove the rightmost item 'j' >>> d.popleft() # return and remove P4OfOolist(dK` # #Bcontents ofdeque ['g', 'h2i']0[0]=# peek at gOd[-1B A (iB(reversed(d)!a C in >@ ['ig0'h'#dgsearch*BTrue.extend('jkl' # add multiple elemycat oncE (@, 'jkCl'])qrotate(1m#o '2ion6blNg b-c#a\6, 'm # make a newj order#- 2_cleareWempty57cannot pop from an J Traceback (!recent call last): File "", line 1, -t#Pvel- 3() IndexError:\('abc"# !))s SinputpvcFba" m ef delete_nth(d, n): ...1 d.We(-n))([" = Cdef' o26+Pentry3d[2ad efroundrobin(*iterablesupending$(i) for i5 wh: %stask =  <%*ry6yield next(Ebexcept StopINtionCIinuem ap \Pvalue,j2, 'YHfgh'4Qrint(7 a d e b f c g hNTtree(GGdudN c0len:> 1pair = [N,]#d.7cdprint(maketree('abcdefgh')) [[[['a', 'b'], ['c 0d'] 0['efg h']]]] """ #=: __test__ = {'librefF' : p} def _main(verbose=None): import sys,classes = ((TestBasic,VariousIteratorArgs!1SubO~WithKwa6requence6!) t0sup.run_unit (*_c#es)# verify referH countingI if!  and hasattr(sys, "gettotalref5")-!gcG#*[TU] * 5for i in range(len(/)SE(gc.collect()n_P[i] =./Tprint`P# docO Afrom<$ _du9(#,c) if __nameA= "_2__"5 True) # Also used by idlelib./  config. [Foo Bar] foo=newbar # " v flavors of legal"il future statements functoolspartial .)"dxtwrapddedentE$os re rx = re.compile(r'\((\S+).py, line (\d+)')get_error_location(msgf moMx.search(str:return mo.group(1, 2) P! FB(.0Cas?acheck_syntax(self, err, baseno, offset=00.vrtIn('%s|%d' % (G0), Berr) GEqual(os.path.>(err.fil) + '.py'K:{- 0$_o1* Swith 9q.CleanI"('1'1'2W^-&i"*.result, 62"222 3;e3'):  from test import _future3 $2def3badq(self):#Pwith .assertRaises(SyntaxError) as cm37 }Abads4']ccheck_"eW(cm.exception, "A_", 3)4U4*$4 5U5-_5", 46U6-6 7U7-7?, 5$8U8-8\9U9-9?, 0/10U/10-/10parserhack#n that the *B.c::~_5P func` works^expected# Note: although this]must pass, it's no1ingtoriginalLP buglof 2.6 since1tatement iSoXal anK disabled. If a new keywordOintroduced in2.6, chango refer toNfuture import.# Etry: exec("from __future__ import print_function;E 0")Cexcept SyntaxError_Fpass-:lseself.fail("sC eD didn't occur") B()ldef test_multiple_feaq s()with supq.CleanI ("@.'5"7! -Iunicode_literals_  scope = {}'4 U; x = ''", {}, O@m.assertIsInstance(% ["x"], str) class Annota!sFTestCase(unit.ptemplatudedent(5""" 6ap+>f() -> {ann}9...*bg(arg:*4;Non33var-FCvar20 = ?!getActualS&, _2.format(ann=F"_ret_ann =p['f'].___['return']<0arg)<g<7arg90var415 m~']['var323 24 EqY!, 5121H.s, expected=`, drop_parens=False, is_tupleLSauX:3%ifp1 is E' =u if notW else V[1:-1W(if `u2Not j.replace("(", ""));mj1f$eqbHteq('...')  eq("'some_string'") {b'\\xa3i'Name'*L'Non> v% finisheG1 + v2 - v3 * 4 ^ 5nv6 / 7 // 8bnot great~1M+val+-A~intrv1 ^ 123 |  (,blambda arg: =U;: aXo, b, c%"%q, *, d=v2, e='str': a^<`varargBB, **kwargs: bP'P3x: y: x + yA1 ifI] elseg1str0one)'or0 Tbytes) b#tC(r)z'J "0@x3JRx > 0*-1"l ")D@0/{'2.7': dead, '3 long_livedie_hard}:&{'3.6': verygood}O0**a)bc!6'789@4.0'gilectomy#m'3.10'Ron m({'a': 'b'},l",  , 1A, b' ')- (,()/a,/ b=, c +[]l[1, 2, 3, 4, 5, 6, 7, 8, 9, 10 or A, 11 PB, 12 cC]") eq("[*a, *b, *c{i for i in (1, 2, 3)}@{i ** 2*1, _WX'a'), (2, 'b 3, 'c')l?+ jpjV[ [* B A()(* B AQ{i: 0y :", Mq[(x, y)j 9\a, b)d*( -a,$Python3 > 2 > COBOLLife is  \call(?argkwarg='hey' _arg, %*args, another5.A, **rsE]2='holukasz.langa.pl .me(maybel1 .rea3?1.0....__class__glist[str1dic\, int"se PtupleN_, ...int, float, j 5slice[0/:1/:2:-K11:2(X:c, d:e:f"(xaG@'strNone if sys.version_info[0] > (3,) else /Tbytes8'f'f-string withoutmatted values`just aQKing'Bf'{{NOT a;.}}+Ysome t {a} {few():.2f "or.,!rI'''f"{f'{nested} inner'} outer"''') 8 eq("f'space between opening braces: { {a for a in (1, 2, 3)}}'") I{(lambda x: x)!None if a else 0 '(yield from outside_of_generator)')0l a + b,await some.complicated[0].call(with_args=True or 1 is not 1K![x%x%ab;c)]+* (b0c0d0'f(\ayf "# <, 2#(((a)))', 'a3, b (a ') if __name__ == "__main__":unittest.() import $re subprocessy 1os R K0supS # Skip this !f the _tkinter module wasn't built. #= J.Y!_m/$('" R_2Tcl8TclError try_Dcapi)INT_MAX, PY_SSIZE_ except ICKF0+ =1 = sys.maxsize tcl_version = tuple(map(int,& .TCL_VERSION.split('.'))) +_patchlevel =  def get_tk"()`global]8 3UQ9Q tceFTcl( 2tclP'infom = re.fullm(r'(\d+)\.q([ab.]) 6', Cvmajor, minqreleasep, seriam.groups 8*Aint(1), X %{m = {'a': 'alphab1bet . final'}[9]sT8if '2x( 1 = ,L5, 0gQ0LbQlreturnE class TTTest(W.qCase): CgFlattenLen(self2# f(:.assertRaises(TypeH_P , 8+ cl \setUpxJp = BwantsBelf./F.tk.s() def testEval(self): `tcl = x.interp .e2'set a 1')0assertEqual(tcl-@'),'011def_N_null_in_results  "a\\0b"'), 'a\x00b') Exceptionz"Raises(TclError,,$q 2r= (8, 6, 0, 'final') or9="5, 8) <= Fu O42.07 !, y?&(TDValu)),E-O'42\ (UnicodeEno t.@ud80x#odouble& Ka' 42 'e6$.5858B42.5l42(ises(TypeError, tcl.getdouble)  self.assertRaises(TypeErr4, '42.5', '10'B#bC= /cl~au DValuTP%), \ (UnicodeEn1y3@ud80}def test_getboolean(!):`tcl = .interp.tk3Is(I'on'), Tru211/42a0), FalsZ 5 , b @bA|$?1.0: u'Ol/onY xEvalFile  with open(support.TESTFN, 'w') as fSW:0ddCt%up7unlink, G<f.write("""set a 1=b 2c [ expr $a + $b ]#6"""gQevalf %QEqual6 ('oa'),'10b020c0A3') _null_in_resultA} "a\0b"b B 'a\x00bf.assertEqua6l(tcl.eval('set b'), 'a\x00b') def testEvalFileException(self): %tcl = self.interp? filename = "doesnotexists"#6tryJ4os.remove(>)-e Z as e?Epass0assertRaises(TclError,e, PackageRequir!2,'pf" rgD DNEP@unit.skipUnless(sys.platform == 'win32', 's Windows':LoadWithUNC# Build a UNC path from the regular.[# Something like \\%COMPUTERNAME%\c$\python27 B.exeh@full` = os.@.absexecutable34if 6[1] != ':' r DSkipTest('Absolute should have driv#rt=kCunc_r'\\%s\%s$\%s' % (os.environ['5'],E0193:]5not>g()0CanFconnect toDPathwith support.EmentVarGuard()*nvvenv.unset("TCL_LIBRARY"\`stdoutPubprocess.check_output(U[P, '-c  im1 tk; print(3)']s&SIn(b'%2', +G_exprstringG o2caloVa', 3 Vb', 6 }(~, expected@esul>P* M qEqual(r;Z iIsInstance43str% [v2ypew a5 Q, '8.'+6BbC? + A . w, 'spam}'018.2l~, '14.2!p3.1 + $N'6.1!@p"$a.$b"d(5.}4*[llength "6 2"]*8L check('{wo rd one} < "word $a"', '0') check('4*2 < 7hypot($a, 4)#/5.CP5 / 41_!.0?.25!( [string length "abcd"] + 0.0 z1>P20.0/O, '4"0x03" > "2 |\xbd\u20ac"]3/r'5 '=abcS7'"axw .r/ "0b}W\x00bR)if tcl_version >= (8, 5): # bignum was added in Tcl 8.5JQN@2**6 Astr( 1)) ( def test_exprdouble(self):C`tcl = x.interp.call('setF', 3:tcl Vb', 6 }~, expected}result =.* M*assertEqual(;Z /IsInstance4Sfloat' .Raises(TypeError,5 `, '8.2G'+6BbC? + A /clw, 'spam}0'',18.2lm, 14.23.1 + $a-.1<Q"$a.$'5.`D4*[lz16 2=8.0J{LY0-Y Y5A;O', 1W ;U<S4z Q 3WQ 5kw$AOlongM) de f check(expr, expected): result = tcl.*Along3)(self.assertEqual(9X/IsInstance4Uint) 0[Raises(TypeError,3, '8.2', '+6'@"bA? + ? /clw, 'spamyV'', 018.2hM, 143.1 + $a', 68"$a.$b"', 5 4*[llength "6 2"]', 8&{word one} < " $aQ4*2 < 7hypot($a, 4)5 / 4', 1/.0( [string abcd"] + 0.0 oUa20.0/5VW"0x03" > "2> q\xbd\u20acG3/r'3IW"abc"J if_version >= (8: # bignum was added in Tcl 8.5wc2**64'def test_2boolean(M^`tcl = u.interpzkcall('setI b~4 6 4V<?NotZ4046ean6)y/, %AVFalsefor value ('! 'f#= noGoff'}G#8+, R '"%s"' %a) O{%s}) 1@true0yes/on 7Tru({%s}' % value, sTrue) check('8.2 + 6', 3.1 + $a ="$a.$b"#4*[llength "6 2"]){word one} < " $aWNFals4*2 < 7', hypot($a, 4)s_5 / 4 /.0 ( [string abcd"] + 0.0 xo20.0/5\"0x03" > "2 z\xbd\u20acd/r'6%self.assertRaises(TclError, tcl.exprboolean, '"abc"'c if%#_version >= (8, 5): # bignum was added in Tcl 8.5F2**6" @unittest.skipUnless(tclq, 'requiresd38.5@def N_ s(!):l`tcl = u.interp;, expected=Aresult =p.call('0'1r8,<.wantobjects(N&bEqual(cQ/3IsInstance8:intFelseAEn=(, str(int*))T B'stZ_'true?yes/onfW?/no?off_1 < 2r11 ><w=_zPfor i;@get_=ger/} "if ~iw qfq<<!/$, 2**1000)) passing_value4"V($ return self.interp.c all('set', '_', value) self.assertEqual(passV%(True), A if *wantobjects else '1')M@FalsNO0O'string'), -g\u20ac>DG\x00@D\xbdDH JLb85'),3& )5strONCmXSc0\x8Z7~ - WV"bd3) &.for i inZget_integers():t0i),Efstr(i)tif tcl_version < (8, 5): # bignum was addedTcl 8.52**1000), yfXp(0.0, 1-?1/3vsys.floafo.min, /ax:-'; +axk Vf), f.(D*f)KFf = OW'nan'#Nof& [Ainf'"('*-E F< I C K :), V# XXX NaN representatdcan be not parsable by l* (1, '2', (3.4,)) (1, '2', (3.4,)) if self.wantobjects else '1 2 3.4') )assertEqual(passValue(['a', ['b', 'c']]),7>(-(-/))a {b c}') Pdef test_user_command(!):!fresult = None;func(arg15nonlocal >7k = argIturn.interp.create'~!', ]ddCleanupHutk.deleK&, LBpcheck(v, expected=, *, eq= %if71 isBY Y1 = k I 62r =;Fall(,iIsInstance(Z, str/%eq !PK`Ffloat_eq(actual' InSAlmosT?<)=O delta=abs( * 1e-10@($True, '1@Fals0'stringO\xbd^u20ac be$, _#\xe2\x82\xacw ;(bd3 b'! O\x00  #4strq\xc0\x813 + ? Kfor i in@get_[gers(Ki?6(i)Cif tcl_version < (8, 5): # bignum was addedjyTcl 8.50]r2**1000c ifBp(0.0, 1O-1.0f, repr(fA01/3>Asys._info.min, /ax-'; /ax2eq=y&eqJ`('inf'2)-*('inf'), eq=float_eq) !# XXX NaN representation can be not parsable by B(@check((), ''1, (2,), (3, 4$5 6', () 1 2 {3 4} {5 6} {}B[1, [2,], [BB], 'B [] B def test_splitlist(self):0 = .interp.tk.-Ncall(#D assertRaises(TypeError, R#0, 'a', 'b:2m cases = [0('2;)), {}>'',/""a\n b\t\r c\n '], 'c'L/b'2'a \u20ac]] \xe2\x82\x2\xc0\x80b c dkP\x00bc dr'a {b c9 wr'a b\ b'((,  "a t2=2U2+b'a 3.4 %G 3. & f"[] "['W'Y  ('`', 1, ] (3.4 "2 if wantobjects else: '1 Z'].tk_patchleve=Iget_Fif tcl_vers|>= (8, 5x!if9or Y" = (8, 5~Lnif noty or get_tk_patchlevel() = (8, 5DS.Uocreate8 9'";|nif not or get_tk_patchlevel() <L# Before 8.5.5 s were converted to s through stringc4 _ = {'G L ^/,  `zV(jP,#[new_tcl_obj]4Typ_oTcl_Obj) class BigmemTclTest(unit.bCase):_setUpvs = Tcl(@support.cpython_only @fskipUnless(INT_MAX < PY_SSIZE_, "needs U"MAX") @suppVort.bigmemtest(size=INT_MAX + 1, memuse=5, dry_run=False) def test_huge_string_call(self, size): +value = ' ' *Fself.assertRaises(OverflowError, !pinterp.bA, 'sp', 'index', aQ, 0) YP@suppcpython_only@unit.skipUnless(< PY_SSIZE_ , "needs U"BMAX" jL2LbuiltinsPItk =!tkQ lO1' +r"tk.getintX\ ;odouble>%boolean?"Oeval9&/fi$orecordx"@addeOinfoA"csetvar;0, '?'a'E>A/, E$unGB=BJ.BexprZN?Olong=&)splitlis#>"createcomman_, max<LdeleG62# These Es require largerory for possible 3 messages e = '1' + ' ' * size %self.assertRaises(OverflowError, tk.evalfile, value)=unsetvar=,5'x'B def setUpModule():if support.verbosetcl = Tcl(print('patchlevel =', tcl.call('info', !B')) test_main}zrun_unit!(TclTest, Tkinter cBigmem) if __name__ == "_Y2__"JP() im contextlibllectionsdpickler sys from  V`Case, , skipUnless, Skip , expectedFailureKDcopyG `, deep  !dtyping#Any, NoReturn!TypeVar, AnyStr# , KT, VT # Not in __all__.0Union, Op%/al#0Tup LiMutableMap/@Call#Generic, ClassVaOcast=get_type_hint A"no!ycheck, _decoratotZt?NewAamed9IO, TextBinaryIO(Pattern, Mp4abc tweakref?4est=Rmod_g_s_cache cgP Base( 1): 6QIsSub2(P, clsass_or_tmsg=None^F@if nj$ss@:04message = '%r isB$a B of %r' % (LGdif msgD"o+= ' : %s[9msgIr ".fAExce(A)5?Not8)i4*0RclearsaPfor f ._-Jnups f(i EmployeEpassManager(#i $Founder(Employee): pass class ManagingFounder(Cer, 4AnyTests(Base 0Cas]^def test_any_instance_type_error(selfVPwith .assertRaises(TypeE0+/$isT(42, Any) x1subx9TP(EmplO~QTAny, V =rep4/aEqual(% , 'typing.Any'Ls.Any[int] # is not a generic 7.ucannot_ %'0 A(=+ Z$_S` _tiate,QAny()dv(L`works_S]_aliaZ# These expressions must simplyUfail.Match[Any]Pattern"IONoReturn 1nor+O PL(L1L) +%,cqRrtype(NoReturn)):+ Qpass def test_cannot_instantiate(self):'@Pwith .assertRaises(TypeError+/NoReturn()B%Ttype(G)() class sVarTests(Base kCase):basic_plain4T =IF('T'# T equals itE"Z(T, T:bis an GTce ofeE1IsIp!ceJ{ypeVar)3var0ce_ _es$is1(42-1subRmA(intfJlT, intqconstrainedgqXj#X'tXunion_uniqu N~YgY2NotFX, Y;"Uo[X], X&H) O, Y]3 Y/, \03], a^ 5?int7 (.__args__, (XG);parameterA=3Is(b].__originw  AA', str, bytes 2A1g,A]Lreprt 8%hT), '~S(K)K*V*V*aAnyStr HT_co%', covariant=True,'0_co_+>.Lntraae i4m-^'no_redefinitio self.a ssertNotEqual(TypeVar('T'), 3) oself.a8, int, strB!) Mdef test_cannot_subclass_vars(g!):)yPwith {aRaisesWError+/I! V  #'Opass0_itz;instantiate1LA')(pbound_eU-hAX', X6=42J Nstr, floatZEmployeeno_bivariant_ValueWcT', coVP=TrueHntraB) UnionTests(Base kCase):~]basicwAu = B[\]"u,1 d$isO(&NI1N1?Ostr]X1SuL_anyk?Anyfu, Any*u1  >%u21Any[*u3fobject G{G1, u!h1%2%3%AD  ", $J DM P0NIX2 }ordered  &float, int]   self.assertEqual(u1, u2) !def test_single_class_disappears(?!):,0t = Union[Employee]+jdIs(t, # l4basjLkeptdud, Managerm$Nos$n(, u.__args__)#n(t +,6u _int, floatvu#v,wM8 aLrepr S%), 'typing.''inWuSF[%s.|B' % __namep3p?u]pT = TypeVar('T0T, [ V Oint)EAListITO [ G'cannot_sub Wwith pRaises(WErrorD1 C(  Epass\$CtypeabD|o, str]fIinstantiateL,(/'E 5 kcuY; intxI}P[fun,2S]), 'v'_str_pattern)# Shouldn't crash; see http://bugs.python.org/issue25390*Abstr, PgA2_etreeus://github.com/|/Us/229# (Only relevant for P6 2.6trynfrom xml..cElementTree import lexcept I& SrD SkipTest("T noFund"g , - A<.k(*argsdreturn#<liQNor s this c` TupleQs(Bas bCase):Olbasics[Tbx(x,Z'tZA TP(*WTrue(/Y)@ 2&TP/OejiM(!]K ~ 1,6nt, ...])  self.assertNotEqual(Tuple[int], , !) 6? 9a...]) :def test_td_subclass(N!):#a1 My~(,"Epass/>uTrue(isYD)instance_type_errorHwithRaises(TypeE0 $isTs((0, 0)VJ3IsI 7 =rep%B), 'typing.' 6L[()]:>int, floatFNI R'& \L#42?M0 CallableTests(Bas kCase):DCLC(lambda x: x), [M# |eq_hash^3E_len({J_}), 1GMOstr]H+BG+]E/ rcannot_Y\tiate(BG)H=c =%ic\;c def test_callable_wrong_forms(self): Pwith .assertRaises(TypeError+2CS[[...], int]L./()I4?[()5[int, 1], 2/&'def test_instance_work0+f(ApassN3IsIMD(f, )+7Not.HNone12{`type_e O5 qP[[], ]dB?Anyc2{ ;j LreprUct0 =QFboolaEqual(Fct0), 'typing.?'9ct2bstr, floatk2k H tvt..., strvk?:') R_ellipsi,;Voo(a:jU/T]8 Aget_hints(foo, globalsj1loc %),C N{'a'}_in_generic;"# Shouldn't crash; see https://github.com/python/./issues/259e.List[M"] XK = Var('XK', bytes) XVV class SimpleMap"(Gp[XK, XV__getitem__, key: XK) -> XVZ6... ?__s7, value: XV <:getk, default6! = ... class MySimpleMapping([XK, XV]): def __init__(self):.store = {}1sgetitem4, key: str>vreturn EX[key]EsEw, valueL E" ="M1get,ault=NonL6tryexcept KeyError<0defkProtocolTests(Base 0Cas`xtest_supports_in assertIsSub(int, ty#.S>AInt)X.7(No:?str:;Ofloa+ ]FA$< cox# Note: 0 it doesn't have __1__._9\* C.n0B"0jv.C"C$$> TTbytes$$" B ,hc?b'' BB$<%ab?Abs7:\round4iss2R6 ;(t< reversible6lis>R= 9 p_instance_type_e; Bwith )Raises(Typek $isT#(0)g.SupportsAbCs) class C1(typing.SupportsInt):&- def __int__(self) -> int&*return 42@fK2(C1VFpass'f = C2(h .assertIsInstance(c, C1) WGenericTests(Base qCase): [test_basicsX = SimpleMap[str, Any]? Equal(X.__parameters__, ()Wwith 4Raises(TypeErrorXrm>!V, strCY+XK#Y7XK,Y*> OSM1 }6intQissubZ(SM1,\]SM1()4Ggq _e O@T = vVar('T'qSS7[T]*D&/[Ti&/[SE&6 C(M&, a): ...4isi4[], List[ZQ[OlistS13New +V+MyU6[T]^/S]d;_a?Linit5W/, 01, SH_!`Xh7[T]$'g%itK__(cls, **kwargs26super().:5)  cls.attr = 42  class Y(X):Epassself.assertEqual(YJU, 42)%Wwith *Raises(AttributeErrorfXHCE = 1j< = ;Z(YM W(X[int]*   $Z  %W%def test_repr(0 e%SimpleMapping),G ""<'a.0_ty5.C6'>"s)My2u# Ew_chain T = TypeVar('T'SAS') R C(Generic[T/X = C[Tuple[S, T]] +X,+,#No/gT, S]]Y = X[T, r&Y,&m *SP*hT, str`Z = Y[#Z,#b 'imK 'TFTrue(str(Z).endsT(OC'.C[2str3]')kc?newaUaU', covariant=OList), '4 7O[~T];+U]r?[+U;RS][T]: ~*  0_coxTTSOT _~TS, paT, TS]=Y>  1inty fT, T]][List[int]]), 'typing.List[ TTuple :#, 5]]'L!) def test_new_repr_bare(self):"|T = TypeVar('T')(.assertEqual(C(Generic[T]), ?~T]A_ProtocolJ Lclass C(>Dict[Any, Any]): ... # this line should just work%C.__mro__2Odict)LB`dBpassfb = B(ib.foo = 42R |@b.____, {'foo': 42}V@C(B[! Wc = Cc.bar = 'abcF cRbar':3qsubscripted_g1s_as_proxiesZ`+T]x?defCP.x, ')w "C[,]-schangedw E(v 2strs.!C["0].zz?newv @z, '$r U(&].1~?C()]/()_0D(C) D+.|ODEfrom derived zPai $x$ hCr SDS  D[oZ 5#z'!abc_registry_kep7C(collections.abc.Map(,  "C.roer(intIsInstance(1, C$3)._WclearC scaches_ # To keep refleak hunting mode (nMfalse_sub3 My#(MutableMapping[str, str]): pass self.assertNotIsInstance({}, MyMapping)0Subclass(dict23def test_abc_bases(r!):> MM(Mutabler,0R__getitem__O7, kR&return NoneBsB?, vE -V?del;Citerp%6(()x{?len?0# this should just work MM().update(n,, collections.abc.D4 {OLista -1M) multiple 1 /2(> *,  ^Equal(MM2._O__, uGeneric)3BorigGgT = TypeVar('T'@C(ty8R.DictT{1...! FC.__rF,naive_runtime_checkf(%(obj, tp0# CC` if a .ionary conforms to J typYif len(tp.__parameters__) > 0i`raise mplementedError#&1if Qnargs__FPKT, V& AEVMall( 4isik, KT) and ve4for k, v in obj.sL(>]True({'x': 1},d7ingGGint]KOFalsLo1: 'x'LWwith QR/s( 2t#T]eg$n  Bthe Kc class  if not hasattr(obj, '__orig_class__'): . raise NotImplementedError*return obj.Se == tp,i Node(Generic[T]): ...$self.assertTrue(naive_g/p_check(B[int](),O /))EOFalsF?strF8GListWwith RN/s(O {[1, 2, 3] Bdef 7list_base.+tpc0# CL@ if 1 conforms to a A subdall(isinstance(x, tp|s__[0].__arg Gqfor x i@%z0 C((5C  >'a', 'b'], ? itest_multi_subscrt(WgT = TypeVar('T'UUVV |T][U][V:$AD(C,['a Equal(C.__parameters__, (V,-1D1C6e 4 huo, (int f2.0, (2#,  !._$`!C,u:qv ., )Eipt_metaM3OtypeE[.!],% $ Union[T, .", G@Callable[..., 3, (Ellipsis)lhashesA-.B.!OW S .ual(A, A)  self.assertEqual(mod_generics_cache.A[str], !) L= OB.A, B.A#W@B.A[x%],^f; %) <#No$f5 7-n7p lA[List[Any]]: By?&?int A #z bTuple[Y2], B] - BH PUnion%, ' C+Z 3y%typing.FrozenSet_| 6Lif sys.version_info[:2] > (3, 2):*~True(repr(.endswith('z6]')sN PR_ C+ Edef test_extende_rules_eq(T = TypeVar('T'UUA x `T, T][Pint, U <Iterable[Ld][T], !terable[Tuple[T, T]]) with self.assertRaises(TypeError):+2ATuplEint][()]I% U]U...] LEqual(Union(wV, int2U][int, C ]str]]Mclass Base: ...Derived( )!-"][ #, G YdT ?][1V Callable[[T] [K'KT. -..., List[T]r?], PQ1U][vTR-"[]:def test_extended_generic_rules_repr('@T = ?vVar('T'(f>X2 ]).replace('typing.', ''), 'JR/LOptionalL! S@None/]] *Ni+')mdforward_refefoobar(x:xk'CC']]/CC [get_type_hints(l, globals(), loc H{'x'UCC]]}['A`barfoo+ATa;Is(8['x'], ATC Ca&T]2C 2 ,CT1sub= (3, 37Ub[v 3= B\!) Ptest_repr_eq_any$hobjs = (getattr, el) for el:_N_"0obj#I oNotEqual((obj), ''H/,Pobj, ,'4if !'__parameters__',) and lenm.#j) == 1Z[Any].__argsj(Any,)if isinstancepk, typeFb/Cbase0.__mro__- ?B@48H0 ,  lpickleglobal C # " wants to reference the}fby nam?T = TypeVar('T'uJB(Generic Bpass/2C(B+ V = C(c.foo = 42=c.bar = 'abc'Pprotobrange(.HIGHEST_PROTOCOL + 13z =".dumps(c, Mx'zloads(z xO, 42(Bbar,+`__dict{'foo': 42, 'bar':C}D`sample, Union, Tuple, h0, CEVar,Q5f, str].c[List]O!0...!1allW], bytes]] typing.DefaultDict, typing.FrozenSet[int]] for s in samples:!Pproto"range(pickle.HIGHEST_PROTOCOL + 1)=ACz = 2dumps(s, Q)h+x+~loads(z$self.assertEqualOx'Smore_v = [LisIterable`Type, $,C0[ 0MapW]MAbstractbPTupleTo, str]n 6s-def test_copy_and_deep (@T = @vVar('T' class Node(Generic[T]): ...cPhingsUnion[T, ", i@Call[..., T], ]7X\IAny, Any],[B= S*V &<,o:)TCF0Var;4T]]+'T', 'T']Z]#>.F[% It't0+ [  1t, /&t))\-oimmutability_by| # Special forms like Q, etc., g aliases to container5#L## !B0and;e variabcles areGsidered Qle by  5global TP, TPB@V #_:)TPkPl:TPBB', bound=int:TPV(V(Aytes)X[T?A]T1Is(NVX), XRQ5Is(K* *X)f# Check that local py)TLmLLLTLV = TypeVar('TLV', bytes, str) for X in [TL, TLB5V]:!( self.assertIs(copy(X), XG&Hdeep*Qdef test__generic_instances(i)|T = TypeVa'oclass C(GB7[T]6i__init__V, attr: T) -> Noneg1~.'! =. c = C(42,REqual!c)@/, + / TIsNotZ?, c%T )cE = 1 1ffX', . ci&_[int]+i,0 Y(ci), ci' +!ci2 ]jZ 4 /ci.__orig_Q__, CS)Bweakref_all7 things = [Any, Union[T,  , Callable[..., T], Tuple,UAny],COptional[List], typing.MapvA,re.Match[DAIter'whatever']]t  \3.ref(t)(), tVparameterized_slot8_Q__ = ('potato',OgtU*.?E = 0/Wwith Raises(AttributeErrorAy.tomatobI"H_intMfoo(x: C['C']): ...  get_type_hints(foo, globals1loc `)['x']9&C]M N+]%, mp__dict}/ D{'banana': 42}fd = D(d]e#]( d.banana = 'yes' d_int.banana =with self.assertRaises(AttributeError):MTd.foobarM&noiL" Pmdef test_e s(l?Typ B = SimpleMapping[XK, Any] nclass C(Generic[B]t!Bpass7lrepr_2 NTNJXEqual(C.__module__, __name__)1:),)^ 'aTests.h..C'iX = C[int]S |Xq(X).split('.')[-1], 'j"')dI"Y( E Y1E5Y*Leq_1( L#, +5[T].?[T]12NotXV([K5V6A# B/ OA, A OA, B"A%"1, B=multiple_inheritance* , R :  OKT, NQC(A[T`V=!, /B[K jnparametersr(U) _special@S = gVar('SW S]): ...UaC(List #1mroC, list, B), objectinit_sub_super_called" FinalException(  ; Y*__ _(cls, **kwargs) -> None:bfor base in cls.__bases__: 0if  is not Final and issubclass(!,)FYRraise&Exception;)ysuper().__init_i__(**kwargs4 Test(Generic[T]Epasslwith self.assertR!s( lSu "gA_[int]ldef test_nested(1): CG = !Visitor(G[Td37a = None4m1seteo, a: T.@a=g=7creturn:vyn) -> TqACV = [typing.ListZ]h0Int0((VJRappeni, x: int.-&x)j h a.`([]D1&42rEqual(a.o), [1, 42]2type_erasureZUT = TypeVar('T';)GNodey c_Z, label: T,gQpleft: '[C[T]'1Origh2 `" =@ # =: T.0eft-,O3al[]<2 = >?2^foo(xT0o&(xb!\de[T]c=Any0Is(P(a), c a)b)c) +, {)/b.)c)^Z+kimplicit_any9 Cj/7D(C] & D.__parameters__, ()D[int] with self.assertRaises(Exception): eD[Any]/wi>1T] =def test_new_F`_args("):#vclass A(Generic[T]Lpass/Bk_h_(cls, argFk# call objectobj = super().O)+`.arg =i `returng# mro: C, A, @, B,&kC(A, B  = C('foo'\pEqual(c#, ',2iainit__2kofrom_a& m)LIAI#k[T], AR #__ac niX VQZ *c*/no2\TypeErrorrA E7> -ub = 'b'fD|m E`A<(!/'c(,5arg b, bc') cChVarTests(Base DCaseN Ubasicp/[1L.Cint, strJ  ClassVar[int][str] def test_repr(self):.assertEqual(%K), 'typing.%')<Jcv =vW/cvQVEmployee]["5%s.A' % __name__)cannot_subcE %Wwith Raises(TypeErrorPTD C(type(8)%)Epasse1LjkOinit,( *H4[Optional<])(no_isinstance,I*1,&%is6intVC) dastTests(Base kCase):lbasicsQcast(jv42), 42,Qfloat)`."Is\0o), int` 1AnyY^?lis -PUnion#!, ]bg aAnyStr*/ ANone( e< # Bogus calls are not expected to fail.yZ"42a~r'hello'3ForwardRef/9s% Node(Generic[T]vi ___!__{, label: T 3 " =(nM#Reft =@righ e['|add_both| N'uleft: '-o[T]]',4z3: ',@' = 2`stuff:,Pblah=P(left  self.right = " def add_left(-, node: Optional['Node[T]']):;A2.@Pboth(:, None)f g^" =9d ^dEint]_hints = get_type%(t, globals(), loc )EssertEqual(V ['66'],-?T]]@A)UYstuffD=NotIn('blah', sbs"s4V ['d s1#5XZ test_forwardref_instanceQerrorZfr = typing.F:Ref('int'Wwith Raises(TypeEVQ$iszs(42, frsubclass_zO(int _e?ity;#6?fr,qr7#No QList[1], < \M_repV%KXC), " ,]"Tunionv$ foo(a: U)=['TFpass K?fooI,uy D{'a']?"?Namp "no]checkZ@whatevers') -> {}B _th = =mc]th, { o_class-* C <ceC.foo)2 cPiF/()H iHk !Pno_ba AmethQ, x: int): ...dP7D(Cd/Uc = C=# verify that K nL affects 9 C.q), {'x'9 #_ref_as_string 1foo: typing.CVar[int] = 7;Dl;4 E4'p'qF= r6 expected_result = {'foo'}8 for clazz in [C, D, E, F] self.as4sertEqual(get_type_hints(clazz), expected_result) def test_nesclassvar_fails_forwar4f_check(self):<@0& Efoo: 'typing.CRLVar[int]]' = 7NFNF' @!']@AAfor in [E, F]MPwith 0.as3Raises(TypeErrorP >rmeta_nox )@_decorator!Vmagic[(funcpreturn  I.__name__, '' G@ foo(a: 'whatevers') -> {}bFpassR9C<g k 8fooUfoo')[th = 6foo! Ofth, {}!cC/C.E cF ?C()H iH8default_globalsode = ("~1\n"AN" R , CP'D': y;X/D:X1barr, b: 'DXCVsuns = {}exec(code, ns'ns['C']Z =, {'a': 32, 'wD']}) OverloadTests(Base bCase): No+_Rfrom ' import 1HBeRuntim#3@FWblah(s*: }succeedqaq  &H ASYNCIO_TESTS = """ fasyncio T_a = Var('T_aAwaitableWrapper(.X[T_a]__init__`, valuO\." =_0__ao<io1Ite8[T_a]: syield &return self.value class AsyncIteratorWrapper(typing.[T_a]): Sdef __init__(U!, V#: ;R4ble6" =3QSaiterRD) ->N:VK @aio.coroutine,Danexb6T_aLqdata = ;W fromEq0if (6)Kelse&aise Stop5ion"CM1 +en2int'z!42x 9xetype, eval, tb)BNone """ tryexec(ASYNCIO_TESTS) except ImportError,' = False # multithreading is not enabled ; TrP# Def]$ions needed for features introduced in Python 3.6 atest i ann_module, 2 368ContextManagery: floatJ3B(AU@x: C]Var[Optional['B']] = g y:b cCSub(BKzK''D3B()uG(Generic[TX7lst5aList[Tz$[]AndForwardparent: ''meaning:|CoolEmployee(NamedTuplename: strABcool=WithDefaultHD = 0^XMeth:xqJadouble22 *xUOReprU A = 1dE__stXe0f'{,0.x} "y}b>3add~, otherHasForeignBaseqb(mod_gs_cache.some_xrepr: 'Xyg__a: '=6' Sg_with(am:7 D[int{?9 am as xxsdACM()).send(x=]WOcassert e.args[0] == 42 gth = get_t_hints GetTypeHintTests(J 4CasP_D_i_various_objects]# For invalid % should fail J (!AttributeQetc).bK1FRS"s(Cror):  gth(123)  with self.assertRaises(TypeError):+3@_'abc'B*aNone) Ydef test_get_type_hints_modules(3ann- = {1: 2, 'f': Tuple[int, int], 'x': , 'y': str}|``Equal(f6), sA o2), {}/3/@expectedFailure1 _forwardref<)# FIXME: This currently exposes a bug in typing. Cached R references># don't account+ the case wherere are multiple`Pes ofB samPname coming from difw#t !he9 program.2mgcB'default_a': Optional[mod_generics_cE.A],BBbB /B]T v5),  cl | .C), # gth will finduright globaln {1: ?.C]IsInstanceJ1.j_), dict .M'123': 123, 'o':D?.D)2{'jE, 'k +xYzh-2S"7str"5fooD?int BAndF pa:': 5, 'meaning ( )z HasForeignBaseCT some_xrepr': XRep!QotherR/.Ag! 'PJ:B .__new__ int, 'y': int})  self.assertEqual(gth(mod_generics_cache.B), 3{'my_inner_a1': @/.AA A2A&0out@AA}) def test_respect_no_type_check(!):*@class NoTpC604:Inn}__init__k, x: 'not a u'): ...iUTrue(s*._?__)5DInn.B ann_module2.NTC.meth), {}zrABase(GB7[T]P<{(x: intr ADer(^ 5')1'x'o 2gethints_for_builtins# Should fail for .A-in es and functions D l(?dir'?len'object.__str__2/()4tstr.joi)previous_behavior*kf(x, yCf.__annota__['x'] = 'int'nO@>-ygKNone|QgQ(;X_with * AHBfb = B(b*A = {O'A'}* b, locals()t lCG-Va;HCV, `__dict p{'var':gDing.|[H7CV]sB, globo yq!, CpOptional[B]], 'b&w OCSubzEz': p:iy': int, 'b': int,  'x': ClassVar[Optional[B]]})7self.assertEqual(gth(G), {'lstAaList[T=0 cWp CollecXsAbcTests(Base qCase): idef test_hashable(w!):IsInstance(42, typing.H97Not6/[]6jOiterQI9,# Due to ABC caching, the second time takes a separate code# path and could fail. So call thi=1fewN%s.:8 3+ kJust in case, alsoa issubB_() a S-Elistq 5 C AV[int]:\n":?qreturn  1Wrapper(42)\n"globals(), nsIfoo = ns['foo']jAg = L]3 5foor8g.send(None) # Run till comple ,#avoid warn9coroutin_ _CWwith Raises(TypeError]>4isiV W\W=86tryvexcept Stop 7OpassIO, 'Python 63.5 and multithreading required') def test_async_iterable(self): #base_it = range(10) # type: I5tor[int]V3.AV Wrapper(M+ self.assertIsInstance(it,aFing.G?ble8:(Nos/42s@skipUnless(ASYNCIO, 'Python p'?torp?torp8;8e\sized%[]S63 ~containenC:7 llection if hasattr(typing, 'Co.&')9utuple()@@>frozensetBSubclass(dic}L< AabstractM)A?6Set9 9 0mut:iJM>A apI j(%{}7M8!5 mS?]< PsequenK9S6 =$Sequence)  'self.assertNotIsInstance((), typing.MutableSequence) ;def test_byPring(N!):#]Z5b''[`ByteSt<)6 ytearray(b''ABOlist Subclass(*LListdLcollections.7YDE{1 My(j [int]): ...J>=), x counterC9 `/sen5setL6Set.mfrozen8%/Ff8 ?dic*=Dic0no_!_i0tiaa Wwith ERaises(TypeErrorSs(E'?[T]H3(_s"):MK(Fpass:aa = My8_#a,*) 3 \ , _ ' 0no_P,A.Eo[KT, V10M_str, 6 6EEict[Q 3 ;d;=d*);u0MapA _ , eASubclass(dic*t, MyDict) def test_defaultdict_instantiation(self):.2.assertIs(typeRing.DC^()), collections._)KT, VT]S9str, intU "subclass*c!ef;typ[}U;BpassGdd =H5IQce(ddvG S2MyD*UNotIsE@skipUnle0'ys.version_info >= (3, 3), 'ChainMap was added in 3.3'c)?map%i Tp A,!Mm CMfqe): ... 4e(CM[int, str #CM=H= ; !cm;F< cm/ $My+ >o;7_deque%D= NS Oque[?queBo DD?[T]DD=counter?%C? A+EFI HKC(typing.Counter[T]): ... self.assertIs(type(C[int]()), C) *def test_counter_subclass_instantiation(N"):4a$B MyC7`Cing.h!):b.Fpass@7d =>)*hIVce(d,-,7typ1`collecs ono_setWwith Raises(TypeErrorFSet(D&?[T]G2#6 L*Is?Set`frozene#F] J,1d(Xi 1/ no_tuple~:TR?*BogeneratorxKfoo(}yield 42GAg = ( xSce(g), Gy: y' J@[T, /Q, intY`Eeasync_) qns = {}4aexec("5 Duf():\n" $ " \n", globals(), ns)  g = ns['f']() 'self.assertIsSubclass(type(g), typing.AsyncGenerator) ?def test_no_a!$_g"_instantiation(e!):5wPwith yRaises(TypeError+/O1X[T, TU2int, intY3sj4ing!@ MMA~MutableMap Bpass< # It's abstractx@v[C(MMAy__getitem__;, k&Freturn NonemBsB?, vEN>?del;Citerp%6(()1{?len?0Equal(len(MMC()), 0aP call#v.update$L1IsIl ce*(/BY[KT, VT] /BB[str, str]20ec(NoPdict,cS,BY65MMA2~03B3C3 B" W =collections.abc.T= <?B, <class(MMC, c ollections.abc.Mapping) with self.assertRaises(TypeError):+2 issubclass(MMB[str, str], tyZb.\6IsS=gC, MMAV3 I(IIterable): ...O7NotR}list, IQGQGenerator[int, ]adef g(): yield 0zwG`)32cn <w Vtype(g), GYTtest_ing_async_ga(9A.]29jQasendO{, value$(Epass@9Sthrow:1typ?=None, tb KLuns = {}aexec(' d&', globals(), nsg = ns['g']J pK "L8 o xA _ instance = G(I$(-?  /Is> H QL6 -g AhookK&):9DBasea 3@*emethodD_He__(cls, othez2"if.__name__ == 'Foo's,return TruezOelse6 \False C( 3J Foo:BarQFoo, \)CRSubclass(Bar, C) def test_subclassing_register(self):*." A(typing.Container): ...Q'3B(A C.%A.p%C)+{.assertIsS_(C, A$+No'BDwBwDSwDw $t#M( collections.abc.MutableMapR M 3M, <j_as_base'M(, 1 @Iter3bS(SequenceS# >f 9I+ gI7fa, meta)=C{ABCMeta * BkBa Ba VOtherABCTests(Base DCase-ntextmanagQ1@coClib. *J5():>yield 42:Em = .- Instance(cmBextMa</42<v@skipUnless(ASYNCIO, 'Python 3.5 required'mjasync_ jNotACMApass'UACM()Ao{G_ TEqual5[int].__args__, (int,){Wwith Raises(TypeError4isiYxg&typing.AsyncContextManager[int, str] class TypeTests(Bas Case): def test_type_basic(self $HUser: pass9B5()$0Pro "Gnew_user(_r:[8`]) -> :6vreturn 4"()Sp?var^1U =Var('U', bound=?optionalSA = O[[[VAExce&]]foo(a: A8 3 if a is None ?els.aassert isinstance(KeyboardInterrupt), sE:)u0Newx sSId = H"('u', int)LName*',.4IsIB[Id(5)Z.\('Joe')bQEqual]s + 1, 6lerrorsc /Id)Wwith pRaises(E)kQissub OJ! DL? nX$QdTupl A E0EmpB2ameI('Emp', [('nameT, ('iY],S `Emp, t* jo}2EmpG, 42Pim = tP='Jim6d=1$@joe,9( R@joe.", ?**id%%imO?im'y0im.O$`Emp.__A__, R.fields, ('name', 'id')) self.assertEqual(Emp.__annotations__,.5acollec(.OrderedDict([('namppstr), (w, int)]~"Is{field_types, !) def test_gdtuple_pyversion(!):)sif sys._info[:2] < (3, 6*.Pwith BRaises(TypeError/3`NamedT (' ', one=int, other=3f class NotYet(gsahatever = 04l_usage0tim = CoolEmployee('Tim', 9000=IsInstance(tim,=1*@tim.!, * OcoolS!._JX__, ''i(!._sjl Au.xi , z~k zt  } I__defaultV[jelleXSWithD/ 'J!q_G aF>n epI.u', Cer_eD Sjoerd', 1g P.2Y3&#V I'PdU1s, \L3=0)@exec(""" nSAfter  x:A = 3yC """k|methodskEqual(XMeth(1).double(), 2) self.assertEqual(XMeth(42).x, ?[0]4str(XRepr8), '42 -> 1'4012 + u3), 0) Wwith Raises(AttributeError):0exec(""" classBad(NamedTuple1ax: int<def _fields(o"Oreturn 'no chance for this' """C2osource as well`test_nt_keyword_usag_LocalEmployee = T)("0", T=str, age=int ynick = 2('Nick', 25)`IsInst(?!, +&.", [, !._Y__, ' ).L@, ('', 'age')annotationsPdict(L SQ?Is(z_types,w9.__jQ|?Typw ' ', [('x',eP)], y_90x=1V3'a']picklglobal Emp # $ wants to refereBthe <!by# ; B'Empp', str)$id0jan4PEmp(' V', 37Wproto in range(.HIGHEST_PROTOCOL + 13z =p.dumps(a!, Pc*2.zloads(z$wL5 , 3) ZIOTests(Base 0Cas[.$iostuff(a: IO)*jAnyStrza.readline(EAa = E U['a']l a.__parameterZ(|#,)^Otext CTextse binaryio(self):  def stuff(a: BinaryIO) -> bytes: %return a.readline() !2a =J.__annotations__['a']'self.assertEqual(a.__parameters__, ()Wtest_io_submodule(B)from typing.io import IO, Textp, __allc__name__0Is(6S?IO)%_)-/1Cset(0), ['IO', 'l G?'])J3, ' io') class RETests(Base CCaseb # Much of this is really ing _TypeAlias. lbasics pat = re.compile('[a-z]+',IQIsSubq(pat.__ Pattern6 @type;?), 2 qInstanc-,msearch('12345abcde.' m_Match4 omat), 0 5mat* # these should just work![Union[str,]~! {, str]]a _e# We don't sup04isi%).Xo/421s  Orepr{%V):?DFH? 6ssertEqual(r epr(Match[str]), 'typing.C') self.assertEqual(r@^bytesB1') Edef test_re_submodule(W!):!iSfrom re import , Pattern, __all__ ename__@O"Is,PF5Is(\}/Cset(0), !['cC', '??'])B"__z-re.`cannot2\class1Wwith Raises(TypeError) as ex:cK3 A(#Fpass9ftr(ex.exception),> "type 're^' is not an ac@able basece") llTests(Base CCase0"""Ts forB."""r, line 1)")(6tryz5 eval("""'''this is a test""7 except SyntaxError as msgM.assertEqual(str(msg), Jelse=$raise support.TestFailed if __name__ == "__main__"A@unit.`() """>s for http/cookiejar.py.""" imf4 os $re K%im ourllib.request fromw.w o(time2isoz,"2S, iso 2netscape,parse_ns_headers, join_words, splitCF Jar, DefaultPolicy, LWP#vMozillaALoadb, lwp_0_stUEFAULT_HTTP_PORT, eS_pathPreach_HDN, do@_matZuser_T Cg_$, !host) class DateTime(SqCase): 1def_v base = 101922700087day = 24*36 ZK ), "2002-04-19 14:36:40ZiB H+dayF/20F",2*H1H"3H2H/Vaz = b 50text in (az, bz:1`Regex(/, r"^\d{4}-\d\d :3Z$"FF"badMmat: %s %s" %)NRC^VFri, 19-Apr-bO GMT_ Oc "Sat, 20l; m4ooun, 21o3o Moo2onetscape(500000)# for text in (az, bz):% # Format "%s, %02d-%s-%04d :Y GMT";self.assertRegex(]{,r"[a-zA-Z]{3}, \d{2}-b-\d{4}:.$"P"bad time2netscape f: %s %s" %!) def test_http2<("parse_date(areturny1.gmDN0R)[:6]q1b0gEqual(`"01 Jan 2001"), ( 1, 100, 3.0)Na# this will break around year 20700~ 3-Feb-20|20, 2, 3y?, 0| /48|!98|O1998| _s# supported  s. Test cases with 2 digit?#`probablyi!in&e 2044.,Us = [ 'Thu, 03 Feb 1994 00:', # proposed new HTTP:matFPrsdayKIold rfc850GobrokenL  (no weekday)A> C @, no secondsHT)tzO2O_24:00Od#tz) using hour 24yesterday'2 '0'"94m9imeFH "7KVKI'q# A few7 extra space at various places: '    7 '&#?_t = 760233600sassume 'POSIX count"ofds r esult = time2isoz(test_t)  expected = "1994-02-03 00:%Z"*self.assertEqual(r^$, C,+\"%s => '%s' (%s)" % ,, J5)) Lfor s in %s:] Phttp2A(s),2V_t, s6 .lower()>|M.uppF2def_garbage()[*''s"'GB  Mandag 16. September 1996)01-00-1980/13O0-01/32h42 25iqWO61:0#]00:62F8-Oct-3697739/01P9 Feb'42632 22:23:32 GMTIfWed, 01?8340 ] uIsNone(")3 "0%s) is not J&\n 4<eE) %s&, Y3isoo7elf!parse_date(text|areturn1.gmM/R)[:6],0 # ISO 8601 compact format7 0203T141529Z"U ( , 2, 3, 14, 15, 29 Awith behind UTCp7:15:29 -0700Bahead of"A19:4O+053*M__s#  'p supporX%s.hRKs = !b@ -00L RM';+;& ',U # zoneoptionalw3:<Ponly 5T00:00:00', # Use T as separator '19940203', # only date5-02-02 24:00:00@ # using hour-24 yesterdaH}!T0ZE ISO 8601 compact format !# A few tests with extra space at various places=0' O3 ',TH:00 ']_t = 7602336* # assume broken POSIX count"of secondfor s in:self.assertEqual(iso2time(s),1o_t, s)5.lower()=E=uppE2def_garbage()G['GB Thursday, 03-Feb-94 , f-"(error -- follows)\n\n%s" % f.get z  3Z#, #, """ When Ming: '%s' E:2Got ""~(", b)roundtrip(selfC): tests = [("foo", .),C=bar  $ foo &""foo=", '/"' bar bar=bazHn;5;5RR baz'bzr/P="\""4="\\"', 6r :r,,,bar',C ')-1:), 'text/html; charset=iso-8859-1' ."/ `; port="80,81"; discard l:?bar8 r'Basic realmtfoo\\\\bar\"".;/)]@for arg, expect in &input = split_header_words([arg]_ reVJjoin+F +self.assertEqual(res , """ When parsing: '%s' E0ed:2GotI1was9w""" % (!, q) class FakeResponse def __init__(", s=[], url=None^$ +: list of RFC822-style 'Key: value' stringsG im~e email!.ix.message_from_T`("\n".()FPurl =^Ainfo): return +C" &teract_2965(cookiejarr, *set_S_hdrs%O2_in= 8 7, "Set-C^;2"){netscapeGA~thdr_nam#"""Perform a le request /}` cycle{Bing :S.2reqClib.H".RPB(urlujar.addH(req% =4.ge"("".G]6R0hdrJ J5.append("%s: %s'S, hdrQb1exts(res, req)  return cookie_hdr class FileCJarTests(unittest.Case): def _lwp_valueless_US(self)-#ms with no 2 should be saved and loaded consistentlyqHfilename =|.support.TESTFN'uc = LWP%()#interact_netscape(c, "http://www.acme.com/", 'boo'<.assertEqual(c.8s["<P"]["/aboo"].f, NoneM2tryI c.(, ignore_discard=Tru?2.KQkfinall os.unlinkKhexcept OSError: passp42Nqbad_magicfps (eg. K doesn't exist) are allowed to propagatec5c3forBjar_>)inv, Mozilla , =Cc ="Athisrwork, aq"KO"#no9" z as excXD# anB sub'q(likelymNotFound;), but notR# Loa& cIsNot(exc._6__,: >lseMfail("expectediqinvalid\'3# I0conCs ofs1Abad v string# causes a. Eopen`, "w")ff.write("oops\n&G K &rVuRaises(", ,>o,<Q# XXX# Get rid comparisons whereP actu_0ingr / repr# .clear() etcIP addres7 50 (single number,N dond domain-matching functions (an2d is_HDN)? See draft RFC 2965 errata. # Strictness switches is_third_party()1unverifiability / &-& blocking-Netscape cookies work the same aswith regard to portAet-CA &negative max age(vIf turnThandling off, SG2should not clobber.-g#2 <be sent if *any*/A areYV1 (ie. V0 OR V2 etc.)Ns (V1 and V0)o expiry datent"be discardedMQuoting:accept unquoted -attribute values? check,Bdq Whichrequired onaway inLout?~lways re <Proper tesw of whe%s kA(wai,3formPath-match(.!V0%V11Q:Aance#;[Drule352out version ei@jectpeculiarit0 list from Ronald Tschalar The first two still need2!s,ArestPcoveruT## - $a only s around7~"es@recognizedsuch ## (yes, some folksQI");kany otherLn@trea0as ]:!.--pace: whi Qnames6s is ignoredADefault path:!no r`ameter3RgivenL)" d6s0theK 7iest-uri up to, butincludingPlast '/'. NotJ@thatVentirely differjw%e spec saysRCommaW delimiters:&0jusrses untilnext ';'K This means it w\rallow cdetc insid9 3bot-$Pequal!mmy`appear7)t").Balsod `if yould multiple header fields into one,Ha-separcg, it'll be a>@acheparse (at le!myJstarts hurtevery time I"nkat code)Y0- Epes: Youtget all soM"of`formatH empty expires attributes ("expires="). Be as flexibl +you ## can, and certainly don't expect the weekday to bere; if you@"'tKparse it, just ignor_pretend it's a session cookie.A- Domain-matching: Netscape usesy 2-dot rule for _all_ d8Ss, no 7 special TLD's listed inN!ir. And folks rely on that... def test_n_return_ok(self):%)#' optimization: .6 ) should filter out mostH4s! C,pJar bef[Qwe trQacces"m (becausaNmay require disk 5 --aparticular, with MSIEr)This is o,a rough checkperformance reasons, sownot tooNcritical@long$sufficiently liberal.9pol = DefaultvPolicy(!Curl, @, ok[E("http://foo.bar.com/", "blah ", False),8rhubarb.@-.<?Tru:'=?", q?com2]:;4 3f2`_3,+?foo*o.local0- ][mest = urllib..Request(url2n = pol- ,:est6pif ok: p.assert*(r&Ielse%:&missing_valuep = signP~: headerregarded by Mozilla#a =qb# name0by .9jar3 9@file; = test.support.TESTFN c = MozillaCookieJar(filename)'$interact_netscape(c, "http://www.acme.com/", 'eggs'=%"spam"; path=/foo/Kcb = c._ 8s["P"]["/%"]self.assertIsNone(?W.valu(TEqual'1, "VD '2][''=X 3lwp/C_strE), ( rJ|""; domain=h9; '=' _spec; discard; version=0')0old = repr(c c.save(ignore_expires=True, [9Itry:c.revertw kfinall{os.unlink(c.I"# 4s unchanged apart from lost info re. whether P was _Uified a,e.sub("Rr=%s" % mZFalseLe3  O/")ud% 1') def test_rfc2109_handling(),`# RFC #Aare /s 965 or N,# dependent on policy settingsDfor %asM,D965,2U in [7;bfault according to9 if not explicitly,G(", + 0Z1#^vW (`tU), # here means noTW storG($  ] hA= DejP *.=$5%1965-6965'x "<eexampl"ni=ni; Versiong=1") Itry:cookie = c._ s["www.example.com"]["/Ini"]Bexcept KeyError_&self.assertIsNone(version) # didn't expect a stored i?lse^ bEqual(:.d#, c# 2965js are unaffectedz.interact_5(c, "http://)=/",<@"foo=bar; V ,`if rfcm  ;fooGC\G11) def test_ns_parser(@)Qc = CSFJar(xBnetscapeF1acmlC 'spam=eggs; DoMain=.:; port; blArgh="feep"'#r 'ni=niS=80,8080L!`:80/",OQC):expires=M)H' 'l "Foo Bar 25 33:22:11 3022b'+/', 'fortytwoB=unladenswallow Hholyhandgrenade'j fsOaU.domain, "B5DTrue4_specified1 f, DEFAULT_HTTP_PORT9EFalsk9i# case is preserv#has_nonstandard_attr("/")@@argh@l  <n!, C8=jm3, "\10`cookies["www.acme.com"]["/nini"] self.assertIsNone(cookie.port)'IFals&_specified) 1# invalid expires should not cause i to be dropped@foo = c._&ns["www8foo?pam6 Cfoo.*Fspam( 'P']['/fortytwo't_valueTEqual'I, ''Ttherebe a distinction between a present but empty P# (above) and a that's entirely missing (belowholyhandgrenade$mdef test_ns_parseral_names('): such as 'Q' areal in first 1=tW pairKof Set-CKv: heade Bc = FJar(interact_netscape(c, "http://A5/",o=eggs'E%qversionE ;  ;sZT%n(I,s *'*U%ifh!isuture, keepx1...Nf7 = time2.v()+3600ad"bar";e=%s' % r4len(c), 1$?now -+Q# ... if9tpast or,'ucard itPfoo="n5Oh = s+$FIn('O', hKpNotIn("{## max-age takesCcedence over,nEzero0is request toPdelete both new@any old matchk intera6ct_netscape(c, "http://www.acme.com/", 'eggs="bar"; expires=%s' % ufuture)"ointerar?barq- self.assertEqual(len(c), 3%''$; max-age=0' % 6 s  Oh = 8\51) b# test1y at end of session for cookies with no-es attributeNrhubarb.netwhum="fizz"'2$c.clear__(" $In('spamN', h'@if f Rionaly is accepted Q = C=(0, "name", "value",-None, False, "python.org8 7Tru8/+ ]"1444312383.018307</{}&.&, {XXX RFC 2965u rules (some apply to V0 too<1def_default_path(%):#Yrpol = D5Policy(rfc=gecvJar(pol8 zP; Ver|?="1@In("?$c.[&/"]9Lblaha/\ "i[rb/",   'eggs="bar"; Version="1"') *-self.assertIn("/blah/rhubarb/", c._cookies["www.acme.com"]) E# NetscapeQc = C:FJar(qinteract_n3(c, "http://b~R'spam/7", Xv:3C6def test_default_path_with_query(%):/cjUuri =aexampl /?/"Gyvalue =j, uri, 82# D  does not include , so is "F"%".r:j #^ sent back to the same URIfoEqual()e3 ases = [2quoted safe("/foo%2f/#, F/),,, ## r%C%_B mA/unG%19oG H9%7d,"7D ,C# unt6#&"~+&"Dp o/( (@\176}9, " .To\031LX1%19 K("/\175fo4%7D -xicode, latin-1 rangDla\u00fcTQ%C3%BC"),# UTF-8 enTdk Obar\uabcd\EA%AF%8D_\ ]Tfor arg, result in casWes: self.assertEqual(escape_path(arg), result) 8def test_requ)F)Y# with parameters;vreq = urllib.C".RK(&* "http://www.example.com/rheuaponticum;"8foo=bar;sing=song?apples=pears&spam=eggs#ni");  Ureq),, " m ?out#T?#4 0mis final slashE  ]O "/"@ort(D1acm:1234/"&headers={"Host": "Lo4321"} "iDEFAULT_HTTP_PORT=hoss# this  is illegal (RFC2616, 14.2.3R!1.5(80# libwww-perl wants sponse, but that seems wrong ?# section 5.2, point 1., and RFC 2965$!1,jggraph #ufn<N'.17s(irrelevant<# port shouldn't be in-;:2345/resource.htmlb-me.com:5432"C}) self.assertEqual(request_host ), "www.acme.com") =Pdef t)pis_HDN(I!):[XSTrue(&"foo.barJ /1foo2.3bar4.5~4FFalsd192.168.1.1")0%.& _..foo[Z)cd~_reach}& 8, " =6, " 8`local"L. 8)4#2 d"% )(|0|9, " :domain_mat  ,Ve E 3 1x.ya, "x.Y ~< ; . xvQa.b.c$ x;H>sexample|Pblah._", ""y8/.rhubarb?>.L/Zuser_ *D EL%P9=!ABuser_domain_match("x.y.com", "Y C)) self.assertTrue(user_domain_m?=OFals>|+>.!?@7>/m"<'.=)x)<'192.168.1.1j"# not both HDNs, so must string-compare equal to xz5, "Gs# empty is a special case)h@def test_wrong(!):!!# Cookies whose effective request-host name does-[6 th"#  rejected. nXXX far from 6let@3c =FJar(finteract_2965(c, "http://www.nastd5/",j'foo=bar; =friendly.org; Version="1"'u*EN(len(c), 0)a|/ctb"country-code tld like .co.uk shoulde set if(yPolicy.PUtrue.<cp = Default8(8=)cjpj6=cp"netscape(cjrexample/", 'no=problemohF p'okey=d1; D)=.vVj), 2for pseudo_Rin ["=1.za Qtx.us + ]eg%s/" %tS'spam=eggs?( T_two_component_domain_ns(self):  # Netscape: .www.bar.com,  2no VL should all get accepted, as R.acmeb _ and Ofor 2-componentpts like >.c = CookieJar() W# twoH#V0Ke is OK(interact_n(c, "http://foo.net/", 'ns=bar'):V.assertEqual(len(c), 1$Ac._c3s["^P"]["/ns"].value, "bar"HB), "L# *will* be returned to any other)1(unvRFC 2965)..y  YE/"),D...unless requestedEwiseKpol = DefaultuPolicy(#g@stris =2!.D;S+2Nonrc.set_p^6pol*9 "" , even explicit`# because . matches  -&/"_Q 'spam1=eggs;H==;#if starts with a dot -- in NS rules,!?bar29 3 TT9 _@ "\ i /W0]["m2m16| | F# top-leveldtoo general*ini="ni"5 ##] protocoPesn't$ow non-special zs (suchQas co.uk)4theattribute  there are at least three ## # dots in it. 2Oh yes it does! Real implementations don't check this, and real Kcookies (of course) rely on that behaviour0interact_netscape(c, "http://foo.co.uk", 'nasty=trick; domain=.(') self.assertEqual(len(c), 2)$14) %def test_two_component_w_rfc2965(G!):1pol = DefaultC sPolicy(1V=TrueBc = 'Jar(pol)}Le# two-z3 V1e is OKt@ <@net/;foo=bar; Version="1"'21$3c._ ["net"]["/foo"].value, "bar"I%), $"$31; n1# w be returned to any otherU(because1was?ied!Cwww.y/"), ""PunlesUgiven explicitly, 0the@ mus@ # rewrittenstart with a: .net --> q, whichJ nod-match<#'spam=eggsp; path=:U #+R fromu/  *fW* getN6set%es8p\//"!W+ y0]["   "! q  r v '1/"$Da'Gtop-level domain is too general interact_2965(c, "http://foo.net/",,3'ni="ni"; domain="0"; Version="1"')= self.assertEqual(len(c), 2) %`# RFC  doesn't require blocking this1 _co.uk asty=trick.53def test_p_allow(%): c = CookieJar(policy=DefaultP(2s#edZs=["acme.com"]u *Fwww..)Vreq = urllib.lest.Request( ;&/"headers = ["Set-: CUSTOMER=WILE_E_COYOTE; path=/"] re=FakeResponse(TyQc.extcD`s(res,(qm0:<*1!Qcoyot,!>6# set a  with non-_7...;~>sc.make_Sc.set ('?[0]2$# ... and check is ge eturnedSc.addu_RF(reqQPFalseD.has-""'d opol = 0rfcb=True, 06poldSQ<G*qp = polsYmains(["acme.com"])  c.extract_cookies(res, req$ self.assertEqual(len(c), 1) Ifclear(7req = urllib.request.R("http://www.roadrunner.net/"C s = FakeResponse(headers, B-'-Sc.addg_(h@TrueD.has,!"C&") 223pol.set_blocked_domains([".acme3F# set a zc with  5...OI!<cc.make*cH1(7s[0o K2# ... and check is doesn't get returnedXOFalsY Udef test_secure(!):for ns in t!, T#whitespace+z" ", ""'+Bc = J>^if ns7pol = DefaultDPolicy(rfc2965=Z5int = intenetscape(v-""Oelse%< z; Version=1p>polq urDL v`int(c, , "foo1=bar%s%s" % (vs,  ?2?"; hGH(n$c. ["fP"]["/2"].},DR"non-!registeredw'2 ") def test_quote_cookie_value(self): Qc = C Jar(policy=DefaultP(rfc2965=True))@interact_%(c, "http://www.acme.com/", r'foo=\b"a"r; Version=1'KOh = O5.assertEqual(hk$`!; w\b\"a\"r') def test_missing_final_slash#2# M% ( from request URL's abs_path should be assumed present.wu_url ='"$ )`url, "(bax"Creq = urllib.".RF(url* mlen(c), 1$Tc.addsheader(req!ELS.has_,"v,")domain_mirror poU) b'po rfoo.bar hspam=eggsjbNotIn("DU", h,~0"aba  returned with"T<B'"; =H SIn('$L"M "'# "5not8s# note . initial dot in c2Ld[APathY D?B@l/=/ selBf.assertIn('$Path="/"', h, "path not returned") def test_port_mirror(self): pol = DefaultCookiePolicy(rfc2965=TrueQ1Bc = (Jar(pol)l urL"http://foo.bar.com/"$interact_\(c, url, "spam=eggs; Version=1"ZOh = :"4sel$ No'b"Port""absent por%R with0pre 7W!; Regex(h, r"\$I([^=]|$)",s " no value@N'o="80"'$,2ortF osinglem?,805K#dmultip%s;" ! "usB2no__comment :''L"'C="does anybody read these?"; = LURL=HCnet/_.html& # "C or QURL c-attributesp to server* _it~)csN# add some randoms 04s, RPblah.u.org/", 'foo~Ml"') < interact_netscape(cs, "http://www.acme.com/blah/", "spam=bar; secure") OO2965K7<H"foo`; Version=1kGopath=/k!sol.no",r'bang=wallop; v; domain=".B?; 'Dport="90,100, 80,8080"2 %max-age=100; Comment = "Just kidding! (\"|\\\\) "') s = [1, U0, 1]#Aname "7foo&680, "\.2@.org6z["# rpul]for i in range(4):Yi = 01c1*cs+/self.assertIsInstance(c, Cookie)J 1Equal(c.,@Os[i]9 , 3,7i , 36Ri + 1h def test_parse_ns_headers(0r# missing value (invalid cF?o> ` n[o:"])0[[(,3Kbar"@ ("As/"), ("Ha, None$F0")]$# rexpires'P =Foo Bar 12 33:22:11 20003 ("E"!/ (7 s Gd attributes&'W'x%', 'bar'I','\'G0')] /al(  parse_ns_headers(['foo=bar; version']), ,0[[(%', 'bar'), (',, None)]])3# shouldn't addWB if u is empty3self.assertEqual(""]), []) 6def test_bad_cookie(M"):'+"jar_from1"s(1s):[4Qc = CZFJar(req = urllib.request.R ("http://www.example.com/"D = FakeResponse/, Ac.extracts(r, reqgveturn cfuture = time2netscape(.s()+3600j# none of these bads cause an exception to be raisedZ5for;Ein [hb["Set-u: "], # actually, nothing wroith thisC2DYditto(`# missNdomain value#2: a=foo; path=/; V.B=1; B*"]7#'omax-agY2: bX)_=oopsKtK)\=spamK:; Expires=%s" %  ]O #;?;(ibe set1 len(c), L w invalid ehtreated as ses 2l9 = " cL =Foo Bar 12 33:22:11 2000"]J1]i 3`T = c.+["8P"]["/cl Is(z.) class LWPQTests(unit9.CCase # s taken & libwww-perl,aa few modificaPs andi.fse_]_$_1/#-/O# First we check that it works |the original & a{'# newsref/std/m_spec.htmlp Clients a document,-receives in# rg#T( CUSTOMER=WILE_E_COYOTE=Wednesday, 09-Nov-99 23:12:40 GMT # 2 When client requests a URL in path "/" on this server, it sends:K gCookie: CUSTOMER=WILE_E_COYOTE/ - Cdocument, and receivesthe response:D DSet-PART_NUMBER=ROCKET_LAUNCHER_0001;&=/E +g/;  M4$SHIPPING=FEDEX&foZ ?fooA*; }i The last $ is buggy, because both specifications say that theMEmost+! c must bet first. vJ should thusNI } year_plus_one = time.local ()[0] + 11headers = []3c = Jar(DefaultPolicy(rfc2965 = True))<#req = urllib.".R("http://1.5/",#\={"Host": "www.acme.com:80"})<t @|t{|..append(M") J ; "< expires=Wednesday, 09-Nov-%dI" % SFakeR($, &/"<c.extract_`s(res,z b3add^_G(req_self.assertEqualD.get."_"), "`M2N'$Version="1"') < headers.append("Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/") res = FakeResponse(b, "http://www.acme.com<c.extract_cs(res, req) _  = urllib.request.R(bfoo/bar"Sc.adde_(f0h =jD.get!"Gself.assertIn(". F", h =CUSTOMER=WILE_E_COYOTE3'SHIPPING=FEDEX;Ffoo'tD b!No  ?req 'True(h.startswith("33;") def test_netscape_example_2(y%):# Second E" transaction s 7nce/9"Assume all mappings from above have been cleared.<  Client receivesk66 j 1 Why s a URL in "/" on this server, it send   2cIDING_wD0023 Fammol >8   NOTE: There are two name/value pairs(d ow" due tPthe inheritance of the "/" mapping in addition to the "/ammo" mapping. c = CookieJar()headers = [].req = urllib.request.R("http://www.acme.com/"S.append("Set-{: PART_NUMBER=ROCKET_LAUNCHER_0001; path=O reFakeResponse(/, c.extract_cs(res, req)4Sc.add^_(_self.assertEqualD.get."5"),"9 "s VcIDING_D0023S!D _Regex!r?I\s*"| ?  def test_ietf_example_1(X%):b/#-/M Then wezQ witha~s from draft---state-man-mec-03.txtS 5. EXAMPLES rDefaultPolicy(rfc2965=True)#\B1 E&& 1 Most detail ofc and rd E has been omitted. AssumeP{user agent3no stored y.0 1. U<A<-> Server% 9p POST /{/login HTTP/1.*[form data]F &identifies Yp via a @32. 7 ->` j} 200 OK +2: Customer="WILE_E_COYOTE"; Version="1"; P1"o|H reflects 2's (ty+*q = inte<t(P@c, ' '' 'u.assertFalse(cookie) # 3. User Agent -> Server% A POST /acme/pickitem HTTP/1.1-C": $Version="1"; Customer="WILE_E_COYOTE"; $Path="_"N[form data] selects an for ``shopping basket.''> c 4. R"% w} 200 OK BSet-2: Part_NumbRocket_Launcher_000&3 Nu 0 /S contain .!c = interact_2965(c, 'http://www.A.com %',z ' >' 5');self.assertRegex( Fr'^\H?1"??I?; \/$'[5[*2shiW#L [ &-s=gA   method from .^ O 6LS="FedEx";  MBNew B ref "N"'] Q%')7 b?/?;t r'\s*\" x' z7*processy Cookie: $Version="1"; #Customer="WILE_E_COYOTE"; $Path="/acmeAPart_NumbDRocket_Launcher_0001KShipping="FedEx9 [form data] User chooses to process order./  8. Server -> CVAgent% hHTTP/1.1 200 OK  * Transaction is complete. *cookie = interact_2965(c, "http://www.A.com/%")Fself.assertRegex(WF, r'k?lc?;\s*\\R/"'K;In(,", Y)#p# The uaB makes a series of requests on the origin!ver, afterP@each7which it receivU3newa. AllPas haveGsameQ attribute and (default) domain. BecausA URLs all[R@ aqprefix,Vthat match:he z!, ]Orcontaink"d so farBdef test_ietf_exa`0_2('):Xb5.2 E & 2 c This C illustrat`effect gdetailQresponse headers been omittedHBssumyHShas no storeds sQc = CRRJar(DPolicy(rfcah=True)| Imagin} s}U, in to earlier,), R Set-?2: e g   ciding_0023"; f/ammo"4  G/specific"m9':('M  K'[`A subsn1 by5()B for}%of)# the form /acme)/ammo/... would include the following request header: #  Cookie: $Version="1"; 3 Part_Number="Riding_Rocket_0023"; $Path="/acmeHALauncher_0001J" @ Not!atNAME=VALUE pair forcQ withmore specific Sattribute, , comes bef<_6oneROlessR. Further nSsame n appears than once. 7= interact_2965(c, "http://www.F.com>%")Gself.assertRegex(X?, r#.* )# A subs%nt!byuser agent to(r) servea URL of#)Cformoparts/C %QHere,csecond!'s} s0 is a prefix4URL 2, sNB doeL0getwarded toTvT,ROIn("2_1Not9l7def test_rejection() T of Set-2 respons ased on domain, path, port.mpol = DefaultDPolicy(rfcW=Truerc = LWP+QJar(p/G=pol& max_age = "max-age=3600"Wsillegal (no embedFdotsJ%",'foo=bar;| ="QC"; v9&1'}OwFalse(c(# x>ping=pongEqual(len(c), 1 Dhost"o" contains a dot  'whiz=bang; domain="acme.com"; version=1') 7 self.assertEqual(len(c), 1) %s# legalTcookie = interact_2965(c, "http://www.a.,; 'wow=flutterC2can't partially match an IP-addressG125."xzzzz=piA*"ilpath (must be prefix of reques&thosol.noblah=rhubarb@ ; ="/foo"; 'l '  fO/barhing=bo.R3Sort ( -pnot in listFzOffftort="90,100? ?ort  p   r'[w=wallop  r', 80,808  r'max-age=100; Comment = "Jkidding! (\"|\\\\) "4* attribute without any value (currx*2Ffoo9=barI ,95qencoded# LWP has this test, but unesca w9@ chaers seemM# like a bad idea, so IX nks should fail: ##965(c, "http ://www.sol.no/foo/", ## r'foo8=bar; version=1; path="/%66oo"') A# but this is OK, because '<'not an allowed HTTP URLQFcharacter:cookie = inte_2965(c, "http< *3c self.assertEqual(len(c), 6) # save and restorepfilenamtest.support.TESTFNC6try c.T(@, ignore_discard=True2old = repr(cc = LWPCOJar(policy=polDoc.loadvkfinall os.unlinkK hexcept OSError: pass  uDold,@def R_url_encoding(:)I# Try someq's of the PATHs.0# (behaviour here has changed from libwww-per>c`rDefaultPm@(rfc acme.com%2f%25/" @"%3c0Anew%C3%A5//",6"foo = V#1"n Y <<%0anew\345/\346\370 'bar=bazx5');{ _rhr2pile(r'^\$=\"?1\"?'J&.I40In(2", )bRegex(!,%?_re/7/-SFalse# unicoddoesn't raise 5ionLt D\xfc&~mozillaS( / e" M%/Netscapep v formatyear_plus_ontime.local ()[0] + 1DFy=63 F> n0 1; max-age=100; V" interact_2965(c, "http://www.acme.com/", ('foo2=bar; port="80"; max-age=100; Discard; Version=1')Ninteract b "foo3igsecureP5") Qexpires = " =09-Nov-%d 23:12:40 GMT" % (year_plus_one,netscape?foo .a %sphAbhDomain=./; yNcy6|def save_and_restore(cj, ignore_d2%):2N:try0cj.J(:=p3new_c = MozillaCookieJar(filename= rDefaultDPolicy(rfcPo=True)_.loadofinall os.unlinkxexcept OSError: passdqreturn T/ =!, Dself.assertEqual(len(?), 6) # none /ed:@In("=]1', value='bar'", reprTeVFalse 42 of them1 on2Ttest_``_misc(# Some additional N! c s E%s.`header%[]-req = urllib.request.R(6bar 8foop#allows a host part that contains doto.append("Set- : Customer=WILE_E_COYOTE; d"FakeResponse(bQc.extZ@(reslqdR# and3the0 is*0 sa qwithoutng a leading#1 to?!. Should not quote even if strange chars are usAA# inJ5  oCookie: PART_NUMBER=3,4; domain=foo.bar.acme.com") res = FakeResponse(headers, "http://www;G/foo? c.extract_cookies(res, req) dq = urllib.request.R(e i3adde_(f self.assertIn("PART "D.get=!"C&")  C Customer=WILE_E_COYOTE",reqIdef test_intranet_ps_2965(e!):* # Test handling of local > hostnames without a dot.CBc = Jar(DefaultPolicy(rfc|W=TrueAinte&(cexample/",e"foo1=bar; PORT; Discard; Version=1;&k =r$|R'foo2{X1=".2"}'2", ) 3nT =Equal(len(c), 3},ns{8!/ls;netscape? ) E 5<2  d d(  2empty_path`Afor % %)# Broken web-server ORION/1.3.38 returns to the client r+V likeM BSet-: JSESSIONID=ABCDERANDOM123; Path== A ie.#@ setvnothing# In this case, a) must?to / (root II&[]O/re\0nts/%S.append("K ANDOM123; Pasth=") "res = FakeResponse(headers, "http://www.ants.com/< c.extract_cookies(res, req) aq = urllib.request.R(b3add^_(_self.assertEqualD.get.!"C5"), "JSESSIONID=ABCDERANDOM123i2"), '$Version="1"' # missing path in the1E URI/re7W:8080/c.;def test_sesW s(%):5 year_plus_one = time.local ()[0] + 1# Check X  are deleted properly byi"# W`Jar.clvBv methodj 'ilqmeisterpscripts'%[].append("Set-S: s1=s;Path=/T.? p1=perm; Domain=.%;"T "o;expires=Fri, 02-Feb-%d 23:24:20 GMT" %F  "p2 /s2u.`'U2: s3r1;Discard "/?  6c =(" # How many/oUanentdo we have?uounter = {"_after": 0"Y$ KobeforeL %}3forckey = "%s_;# %-e.valueF-c[key] = $c # How many cnow? for cookie in c: key = "%s_after" %,i.value,counter[key] = I+ 1 -# a permanentT got lost accidentally7self.assertEqual(b"I%],ybefore"])Htsession}hasn't been cleared3{E~0i`we did[Shave 1vstthe first placUv,NoH_, 0) def test_main(verbose=None).support.run_unit(DateTimeTests,kHeaderC: BFile,Ja12LWP 4) if __name__ == "_6__"True) = Python IEEE 754 floating point N >>> from sys imOS_info as FI%Dmath&*qPI = pi E = e You must nevempare twoZ`s withbecause you #`not goto get whatexpect. We treatN@as eI@ if difference betw  them is small than epsilon.PS = 1E-15T(x, y): ...pp """Alm helper }Es"""-return abs(x - y) < EPS NaNs and INFsS In 12.6&anewer 5($a number) infinity can be constructed strings 'inf'7q'nan'. RINF =(")N-;&AN0H)HE inf= 4AN nan The Gmodule's ``isnan``inf`` functionsused to detect< DANAN:disinf(INF),  nan(NAN) (True, 0= -1 W# - Ambiguous operalike ``0 * orCnf -`result#2NaNqp1* 0-%/A HowN0una QCinf s2infX*FJ1.5 06a/ 1000 Not a Nt#reto another, even it NB= NAN False;< 0%>= All operation s involving a NaN return except for nan**0 and 1**nan. >>> 1 + NAN nan**0 21 *11.010NAN$0 0S(1.0 + FI.epsilon)T Misc Functions =! The power of 1 raised to x is always 1.0, evenspecial values like 0, infinityQNaN. pow(1, 0)=INF-2NAN) 0defined as 0, ifpositive. Nega  are a domain error or zero divisiosult in a silent010, 020, Traceback (most recTcall last): ... ViEi: mathe?-1 QSZeroDX0.0 cannot beZ3a n7'o Trigonometrio|Asin(RNS@?cos<R<S/tal=R<S Neither pi nor tan exact, but you assume that'a(pi/2)b large c#pipvery smo:# PIB> 1E10 True--PI) < 1E-1556adAN), a0, a1BP(nan,@)4", ? (S _7aequal(Y!, 3', :", M (c , ) HyberbolK import builtinscontextlib$py $gc pickle from random import randra nge, shuffle import struct$ys uunittesweakref from collections.abc MMutableMapping+D m_`s, sup` py_S$ =.R_fresh_module('$w', blocked=['=A]) cNjL @contextlib. manager def replacedTname,ment): original(2ys. s[6](s( =N$2tryUYQyieldf`lL class OrderedDictTests: T_init(self{4Gelf.@'Pwith ;.assertRaises(TypeErrorR/C ([('a', 1), ('b', 2)], None)+ # too many argspairs = \fQc', 3pQd', 4 be', 5)tEqual(sorted(Qdict(l)).items()), E # *e inputa **9co# kwdsa Ilist " #b9w%],rc=3, e=5s ?s# mixedc # make sure no positionalE conflict possibleb d  _"8=420[('vE2)]);n M^otherNO ,O, 426 ():!._e2__){5# Mthat direct calls to 4 do not clear previousFtent8d =a5dI&?Pf', 6g=7, d=4dh#~ g', 7)])  def test_468(self): OrderedDict = .' items = [('a', 1), ('b', 2 Qc', 3 Qd', 4 Qe', 5 Qf', 6 ug', 7)]Wshuffle(_)Bargd %Hd = #**7HassertEqual(list(d.oQ()), !) z'oupdate*$BwithHyRaises(TypeError|#).zf], None)4# too many args(Opair"oja$od(m) sorted(o5 # ce input **:LOkwds! 20!A # ]!9], c=3, e=5*Smixed&# Issue 9137: Named ument called 'other' or 'V'>shouldn't be treated specially.*_]?=23"[(f, 23)];q6={}7.o 6#[(O, {}sred=5, blue=6, !7,/=8 %),d 0[('h4m8 re{X@', 8P# Make sure that direcRs to d do not clear previous content@R# addI9s4A areAPmovedXuthe end 6T;<5i<[('Z], g=7, d=4 self.asser tEqual(list(d.items()), [('a', 1), ('b', 2 Qc', 3 Qd', 4 Qe', 5 Qf', 6 g', 7)]) U'self.assertRaises(TypeError, OrderedDict().update, 42)?)()Cdef test_init_calls(%):XV = []lass Spam'N=keyCK.append('*'}!return ([ 3 \+] P._(k2, [K@from Id< = wHod =.PG'abcB0o [(c, None) for c in F]^p , value=F|[0y0?abc$IsInstance(XMutableMappingTrue(issubcQB+, @l_clear$Ppairs ('   shuffle(U V Den(od), len-N.A0,0del.q del od['a'bRNotInx&od BwithQ?1Key>*df.assertEqual(list(od.items()), pairs[:2] + 3:]) def test_set2q(self): OrderedDict = .'Wod = ([('d', 1), ('b', 2 Qc', 3 Qa', 4 e', 5)])M['c'] = 10# existing element2f222=new-assertEqua2Xz!10 f0Ztiteratorsv$` = [('Y mmm16)]shuffle(U  N), [t[0] for t in{:B.keyA%UvalueC1! Breversed(od)),TX  7e0$od&nTSp m 1),  L)detect_deletion_during_b?ionb$ Q.fromV'abc''inkey = next(it-del od[keyBwith`Raises(ExcepR# Note, the exact e* r;d is not guaranteedAThe only"Q thatSa) willELsuccB$Xcsortedz'TypeError |v], None; ,O;  : !<C t in pairs]3) ,self.assertEqual(sorted(od.values()), [t[1] for t in pairs]EBitemD54arevers5)),G[t[0>nA])) C def test_iterators_empty(!):$\OrderedDict = .'Wod = (WU = [].Gdlist(od), .=*B.keyF132k od#4o=!<"0pop#$x('c', 1), ('b', 2 Qa', 3 Qd', 4 Qe', 5 gf', 6)9qhuffle(U& ~ Rwhile _4od."),2&()mBwith Raises(KeyError<bQW w2len0__last.Qi, i)irange(30)];obj L>8 bj11FTrue8o=9.obj), 20'.gshk, v =d :f(k), v!f('xyz'D k %`, 1234(# make sure pop still works when __missing__ is definedrclass M#():  def __missing__(self, key): return 0Rm = M;U(a=1)F .assertEqual(m.pop('b', 5)+a', 6), V+6+default=^3Wwith Raises(KeyErrorAa') H`test_e1ityJ5OrderedDict =hDopairs = [('c'", 7 2) 3 Qd', 4 eU1('f4]Mshuffle(Ugod1 = ~!2! 'od1, od2)# same o implies 1 = c[2:] + &:2/od#Not # different-in # comparison to regular dTis noEsensitive:(# )$MclengthR/d W  l[:-1])copying$# Check tha#!ed7`s are ]able, deepQpicklH# and have a repr/eval round-trip*>65/od cG(dupmsg = "\n: %s\nod@" % 03TIsNot&_, msg+w?dupQ &1lisV.items()), %odh 0len9oen(od)0 Ctype1 2<0od.$(K69 !# C e directly pulls the modusRso weRto fake itFreplaced_4('collections', for proto in range(.HIGHEST_PROTOCOL + 1= subTest(O=043hTloadsudumps(od,)h check(eval(repr(od)))  update_test = OrderedDict($.0ECbcheck(I:V~ ;@def w_yaml_linkage(self):!;0 = .'# Verify that __reduce__ is setup in a wa"supports PyYAML's dump() feature.Z0In , lists are native but tuple&ot8 pairs = [('c', 1), ('b', 2 Qa', 3 Qd', 4 Qe', 5 uf', 6)]+od^g#.uod) --><# '!!python/object/apply:__main__Q\n- - [a, 1]\n b, 2]\n'QassertTrue(all(type(0)=='P for x6od.{()[1]))not_too_fat &do not save instance dictionary if eneededVB3IsI('1__, 1BNone-6f_()[2].od.x = 10@REqual?l['x'], 10A/ n, {'x': 10}pickle_recursiv% od[1] = odG)"# x directly pulls the module, so we hto fake it%with replaced_4q('colle=2s',@rotorange(-1,.HIGHEST_PROTOCOL + 1AETdup =4bloads(ps(od, pe8IsNot(dup, od7&*/.keys()), 48 Is0[1], dupg. @).Iod),"(z*"|Teval() /)"e(self):  OrderedDict = self. ## See issue #9826Wod = 3.fromkeys('abc'))['x'] = odqassertEqual(repr(od),#"a([('a', None), ('b c x', ...)])") Qdef test_h_recursive_values(!):*wv ("42.d@r = t # Cannot perform a stronger, as the contents ofJF are implementation-dependent. All we can say iTWat weCBwant result, an excepT}any sort.;G.IsInstance(r,5od[Witems8_Againhsetdefault$pairs = [('e1|2 3 Qd', 4 Qe', 5 qf', 6)]Zshuffle(U M / _o = list(od.<FU7od.>f10), 34# make sure adidn't chang \ &, _ 7 &1050'x'added to/enI @[-1].jf Cg', :c=9), 9Kb@ sti_orks when __missing__fdefinerclass M#(voK[, key(,return 0sp)5 0 into# # Given E4 a, b]@lete5re-!# verify thais now latVhan b !'a1\Qod['b2@del 'a' < ^,62)][G6 = s oKX1Umove_to_endct od = OrderedDict.fromkeys('abcde')  self.assertEqual(list(od), 12od.move_to_end('cN_dec')N 6, 00cab2Q<>b', last=False:bcaWwith 7Raises(KeyError): 'xJ-qndef test_2_issue25406(" =R  cm%?cab aX%!acX/aU ?bca !baosizeof$q# Wimpy8 : Just verify the reported d is larger than a regular dict0F(a=1bo_F(**dEGreater(sys.gety"of# Ad)) u _views& See http://bugs.python.org/DA4286qPs = '#6quick brown fox jumped over a lazy dog yesterday before dawn'.split()W 'Ls.F1od.p!),.5 hitems(6 Zride_updated&V[at subcl Qs can1c c ) out breaking __init__0Bg MyOD(]!Vi, *args, **kwds-1r Exceptionp  = [('a', 1), ('c', 3), ('b', 2)] self.assertEqual(list(MyOD(items).Q()), !) <def test_highly_nested(O!):"a!# Issue 25395: crashes during garbage collection9OrderedDict = V.'obj = Nonefor _ in range(10005O0([(C, obj)])K0delsupport.gc_( _subclass]deleted = [  |__del__;]b.appen&.i5^P8i v4yobj.i = iY;E!, reversed(8<)))0delQ_hash\ision*_6Key1Cinit , p 4*! =$["PvalueBtr(i)'sfsmbreturnt mB#eq@, otherG+tr`=F. o1except AttributeErrorK'\FFals*Crepr=K?blocking(D D# See th2`-handlin lookd(in Objects/o I.c).MINSIZE = 83 & $*-1(i << 2) + i +:F + 1COLLIDING =key = Key(!` id#+E:SvaoP(pod[key] = ..!4od[Wt'after'[eV T+kb'odL`[(key,|]ciD_24347jct class Key: def __hash__(self) +return randrange(10%) Jod = OrderedDict()qfor i i?; bPkey =5vod[key] = ii # These should not crash.pPwith .assertRaises(KeyError}list(od.values()H#OitemG(repr(od%od.copy(test_issue24348" =7x>/1M.od[Key()0/is`od.pop}<6675"""bdict resizes after a certain number of inSion operations,EPwheth)r e were dele- that freed up slots5theG table. During fast node lookup,n must correctlyIrespond to all, even if the current "A" is6sama`old onWe verifyhpby forc'a Non a sparse o!ahen perform aW[DPtriggnCs (e.g. ). One Xqaspect &isHwe will keep0ize  at eachcIcall. This ie-at we handled\ pr=&ly Es c0W'0123456789ABCDEF'*1*`if lenZ == 4K!r a0last=False '= c0 + c142keyq@# Di uyfrmethods"'A_setHC-  ^$._`__(od, 'spam', 1yNotIn('NULL',  YN_del OrderedDict = self.OrderedDict Wod = '()['spam'] = 1h2dict.__delitem__(od, ?RBwithassertRaises(KeyError):Orepr(od) def test_jp_clear(5V.NotIn('NULL', ?popqK0pop"t7setdefault?.a6, 1p#oupdateD]"[( ](reference_loF# Issue 25935J+zclass A3`A.od[A0ENonenr = weakref.ref(AUdel A)gc.collect IsXL(r()Efree_after_iteratingsupport.check_2 , B,)Ilambda d:S(d.keys())]C_value_G,^" +PurePython9lTests(`, unit.!bCase):module = py_ @ CPythonBuiltinDictTests(unittest.'Case): """Builtin dict preserves insertion order. 0Reuse some of R* O#0edDCselectively.42"""=module = bss<= for method in (("nQ_initxr_update 2abc Rclear delitem " +@1setMdetect_dele_during_itera <6pop<"re"moverride uhighly_nested1 _subclassq_hash_collis").split(setattr(CPython#s,K3, g)s "c)) del/E @7skipUnless(c, 'requires the C ver0he Qons m2')  (%, R2 = ?.%check_sizeof = support.@pVQ_onlyC"deF_exact(selfYxg=elf'@calc$dtruct.k#`alcobj#Cg FEbasij ize('nQ2P' + '3PnPn2P') + ~('2nP2n')BPentryw]!('9p5P')Mnode=wcHod =L(@V(od, + 8*p + 8 + 5*) # 8byte indices$*2//3 * 'e tableod.x = 1n52od.([(i, i) irange(3)]"T + 3*ABpO, 10t!16Fv16 + 10Hx.keys(), V('P')$2%\value&pc:iP2xn(`(od), 2 3(od)* +0`key_ch  j?X 2.fromkeys('abcdSe')  self.assertEqual(list(od), 'abcde')2Wwith 7Raises(RuntimeError):`gfor i, k in enumerated '+od.move_to_end(kwzLess(i, 5&#/od['f'] = Nonef 1+12) vdef check_m_handling_en_Qelf, ing, u, s):;for i in range(len(u)+1"&@d = Ncs.getincrementalX1er(-in 1"{e(u[:i]+$g8 !~&s class ReadTest(MixInCSHW @ial(r, input[ialresult# get a Streamm0er 5the and feed bytestring versionB# ofs1 to-preader 41 by. everythGavailable fromNo S thatb eappropriateLqentriesc.'q = Queue(b""3ra.q/gU = ""ZT+(c)'Azip(MeY 3Hq.write(bfs([c]) ` += r. Z& 0 uS#rre's no@leftubuffersi(, j'N!, T2# dfagain, this time us^'n _ $rE ) @+Sl+CP3b"" /d. whetherreset method works Ferly.&result, partialresult) # check that there's nothing left in buffers9self.assertEqual(d.decode(b"", True), ""k2U0, b([CiterTF ened = input.(] 6ing.eB,"".join(e7cs.[bytes([c]) for crQed], j!) `def test_readline!):!0get1er("sm0o.B"IO(=sreturn i (d80allsr, keepends=, size=None;Ver = reZY = []QwhileJ'/32 = `.( E if :b!Ybreak0@s.ap( Zk#"|K"sSs = "foo\nbar\rz\rspam\u2028eggs"usexpecte6|7v|baz\r|9|: nov>:8 2 XsHi ;@Fals<Bj010)m?*, @o.("\n", "# Test lo1ines (multiple calls to ()2e&()*vw:vwop1(i,1endIenumerate |$vw(i*200+200)*"\u3042" +N?vwo7  H5vw)7'vwHV[Gvwo)ZwQfirst might end with \r, so%#)Qer halook ahead whe" this is ae \r or a (G{ange(80# $ins1110*7*"a + "xxx\nier = getreader(Ks) for i in range(10):$3self.assertEqual(&*preader.line(keepends=True),8size*"a" + 8?end,vO"xxx\n"er = get (kOFalsv4 wuMdef test_mixed_mA2_an (s = ["Humpty Dsat on a wall, 3had a great fall.\r8 All the king's horses and a_men\r"Couldn't put together again."]data = ''.join(;4;sm = io.BytesIO(Oq.encodeP Fing)U<preturn (6cs.c4(c%) # Issue #8260: Test () followed by(vfdrf!),dOs[0]1:(),FG[1:]h7O3211nN1/1]0 10*>3[lea + 1:][:10_16636 Xp? *(#/(n9(C =40, chars=5), data[:5])  self.assertEqual(f.read(), data[5:]) )-E'') (# Issue #32110: Test Wn) followed by9pf = get+?er(ysize=40, chars=5/:51.-@0),   10*;o6:106]_12446 WlinesY|1, [ 0[0]B] + 1def test_bug1175396(B%):Us = [c'<%!--=j\r\n',LQBLOG index page: show recent articles,>today\'s*5 or of a specific</e.J2O--%>P<%@inputencoding="ISO-8859-1"3template=TEMPLATE.y0rimport= frog.util, 6objects3 Afrom\.storageerrors SEK-Slogging"Clog=.getLogger("Snakelets.Oer")=Puser=.SessionCtx.AmEngine6 ?A FromDate(date, count=None):Ssentryids=.listBlogEntriesQ?D.reverse() # descen{"if\=![:]V?tryQ return [.yy.load( iPe, Idr Id in  xexcept /,x log.error("Error loading articles: "+str(x))\r\n', ' self.abort("cannotJG">Rshowdate=None!Aarg=Request.getArg(v0if 0="today":Q/#- TODAY\'S ARTICLES?write("

Tn5\'s_

  = frog.util.iso/) zentries = readAFromDate(Y%eloactive eACTIVE redirect'Y&"("v/.y_loginLOGIN PAGEpL OF A SPECIFIC DATE8(1 = CParameter("c+ ten on %s%`medium\Ph+/seeRECENTB oRecent =storageEngine.listBlogEntryls|1if C%9?=[]&SHOWAMOUNT=10) Dfor ? in_.extend(U &, S-len(>?)) e8if 2&>=K& <_break % $]stream = io.BytesIO("".join(s).encode(p Uing))>nPer = & cs 2(g9(i, line)`enumerA%):eassertEqual(9, s[i]) *def test_@BqueuLq = Queue(b"")  writer = codecs.get(self.encoding)(q) 1{ read445# No lineendsl.("foo\r"iassertEqual(g.KP(keepP=False), CAXr__\nbara-^ (ba ?baz]-A,5") ?# LE4Tru  )b/\nR"? / %^#@ G,Ddef test_bug1098990_a!):!s1 = "x / y V\r\n"S2SPoffenA: ladfj asklklasdj fskla dfzask@fj l1 fjzzzzaa%whereisthis!!!r3rAnextm. = (s1+s2+s3) e  ,-tream = io.BytesIO(sHsH9y_), s102030"]KbB Kass$b ,stillokay:5+xx$4broken!!!!badbad$5$PagainH& o+s4+s5,rual(reader.readline(), s1)  self.assertEqual(reader.020304050A"") ill_formed_sequence_replace = "\ufffd", def test_lone_surrogates(2!):PDARaises(UnicodeEnPrror,\qd800".e!, 7 ?ing"[\uDC80];Ging, "backslash5"), "[\\udcP)*Onameoxmlcharref�c+oignore zB?|F"# .Utial  eeacters*N?800 'J-.0bomM_for before, after in [("\U00010fff", "A"), ("[ ]F 0("A*D&)]#s# =Re^)[len(bom):]FED]estring +*2" + x40 = # ++5  sI@7 'De !.dY u`7pl  "surrogatepass"), +test_sequence),self.assertEqual(,.decode(&encodingm q "_tring/ "ignore'before + aftery1oreplacziill_formed_Jbackslash&= ''.join('\\x%02x' % b for b in 1  : class UTF32Test(Read `, unit.aCase): = "utf-32" if sys.byteorder == 'little':1 = b"\x80\xdc\x00TOelse<4@A80" spamle = (b'\xff\xfe['"0b'sp am F4b.ffiF4)_@def _only_one_bom)Z_,_,reader,writ "cs.lookup1.T 9!# e some streams = io.BytesIO(6Bf = h'(s. ("c"d = s.getvalue_# check whether e is exactly one BOM &it4`True(d+jle or bv# try to H@ it \ d! =3(er w f.XA(), "?bad  4*(ffa$ = gedRaises(Uni.rError, %s = io.BytesIO(8*b"\xff") f = codecs.getreader(self.encoding)(s/assertRaises(Uni@Error, f.C!) `def test_partialX!):MUcheck" P"\x00\u0100\uffff\U00I00",.[@", # first byte of BOM -osecond.Othir-mfourth[1 =>order known'E +9dEv "Y(k=]` handlers Equal(('jd', 1)p.cs.utf_32_de (b'\x01', 'replace', True){qk,Wignorje D  , "strict" H-r_stateN _4ingdo  P"spam1", D +lezV,beissue89410# I #: insufficient result allocation when cing into# surrogate pairs on UCS-2 builds.+aed_le = `ff\xfen1' +1e* 1024Fh^'"' -32_decode(encoded_le)[0]) "enbe = b'\x00fe\xff' +100' * 1024F self.assertEqual('\U000100-,.{cs.utf_32_de( class UTF32LETest(Read , unittest.aCase):pFing = "utf-32-le"ill_formed_sequenc"\x80\xdc!" /@def b_partial(fe.check"8"P@ff\uf\uffff'" [<@ "|@90dELv "Y(kt]t)osimple"[Q203".z4 ping), b3\x02\x0R"noerrorsnRaises(Uni*D0E5 , K#leN ];ff", "strict", Trueissue89410# I #: insufficient result allocation when Eintov# surrogate pairs on UCS-2 builds.+]dPKSB(b/80 "\x00\{xff", o"\x00\Do\u0100v "YO\uff (k@\U006 8]!) def test_simple(self):.assertEqual("[203".encod4 sing), b01\x02\x03"noerrorsnRaises(Unic DeE5 , cs.utf_32_be_d "strict", Trueissue89410# I #: insufficient result allocation when ing intoP# surrogate pairs on UCS-2 builds.+]bd = b'`P0 ' * 1024- '4000-!S( )[0]) class UTF16Test(Read `, unitG.CCaseDA= "utf-16" if sys.byteorder == 'little'~ill_formed_sequence"\x80\xdcLOelse4 dc8"QspamlN'P\xfesZpam'AbAeE/001 '{only_one_bomz_,_,reader,writ*alookup1~!# |e some streams = io.BytesIO()Bf = h'(s. (""s.getvalue_p# check"Pther  e is exactly one BOM in it (d/jle or &be# try to H it back\ d8 3(er w f.%A(),  ?bad Ic$ = ged6elf B<'") f = codecs.getreader(self.encoding)(s) assertRaises(Uni@Error, f.C!) 1def test_partialX!):PMUcheck" "\x00\xff\u0100\uffff\U00I00",.[@", # first byte of BOM -msecond.1 =>order knownA  4 *> "nJ(k] handlersEqual(('jd', 1)lcs.utf_16_de (b'\x01', 'replace', True)Lqk,Wignorje D 2 b" "strict" -r_state _4ingd@  P"spam1", D +lezV,bebug691291%# Files are always opened in binary mode, even if noA was # specified. This means that9automatic conversionD'\n' is doneN!onZing and writing."s1 = 'Hello\r\nworld 'bs = s1{ H addCleanup(support.unlink, fTESTFNAwith/2", 'wb') as fp0fp.eGd% warnings(('', DeprecationW)WDer =zDU', = O 0%(), s1) class UTF16LETest(Read , unittest.Case): encoding = "utf-16-le"ill_formed_sequence = b"\x80\xdc" '@def Z_partial(self^be.check"8 "\x00\xff\u0100\uffff\U00I00",.[@ "T4 > "J(k])lerrors:Js = 0(b'rA', ':d')@(b'AZ#A$ B)CD3?BCD6&@\xd8\%A&T*A"W+^for raw, expected ins~assertRaises(UnicodeDeE , cs.utf_16_le_d tO 'strict', True)+~Equal(raw.\"('o lereplace') @lnonbmp@ b"Q203".e4 ;ingJwd8\x03\xde' k.,~r ) class B(b dc\u0100\uffffK",  "\x00\xff\u0100\uffff\U00+002]@!) def test_errors(self):iUs = [0(b'rA', 'p:d')!400A&A' 000BC DZYOABCD6 d8+)%O\xdc)600A*A dcy+dfor raw, expected innsbPu.assertRaises(UnicodeDeE , cs.utf_16_be_d zO 'strict', True)~Equal(raw.\('utf-16bereplace') FlnonbmpF b"p203".en4 ;ingP }\xde\x03' k.,~r ) class UTF8Test(Read `, unit2.CCaseJd@ = "Q!8"ill_formed_sequence = b"\xed\xb2\x80*_TQ" * 3Y0BOMI+''qpartialkZdcheck_"Gc7i8i 1F A4 o\u07ff> "7M\u08ml(C~.} 0@I g|r_stateu 7fD} 104ja_handlingrq RBu, u8 }r(self):  for data, error_handler, expected in ( +(b'[\x80\xff]', 'ignore _[]'),- breplac.b\ufffd:surrogateescapBdc80\udc| backslashA)):with self.subTest(6= ;=I FCg= x*wassertEqual{.decode(encodingHx def test_lone_sshsuper().,)Ko# not sure if this is making sense for/UTF-16 and %32"[\uDC80]". "2" _cBOM + 2]')Raises(UniE eEBz) as cm>\uD800\uDFFFexc = cm.exception%exc.object[ `start: xend], ':Dpass s"abc\ud800def\\pxed\xa0bh "\U00010fff=\xf0\x90\xbf" &\0 b20  /b_cWV/b"P 0 PTrue(cs.lookup_( D  t"v# b"abc\xed\Pxa0z".decode(self.encoding, "surrogatepass") @unittest.skipUnless(sys.platform == 'win32',  'cp65001 is a Windows-only c') class CP(Test(Read %, pCase): fC = "b!" @def _#59Qs = [-('abc', 'strict', b)('\xe9\u20a. b'\xc3\xa9\xe2\x82\xac'@U0010ffffn\xf4\x8f\xb;Yudc807NNonec(aignoreO breplac(?) backslash2"\\pOname3 p\xed\xb\0]for text, errors, expected ins='if"`s not R %)>tryd1d =yM$e(')5except UniE eE0 asofail('Unable to 0 %a  } with 'w{'(=%r: %s' % (@>rr)assertEqual(dp 6q4'%a", %r)=%a != %a/p NelseA~Raises(~,ogx^xgyx_ 8 ? _ ;;eI\xbd~x'\ufffdD(b'[ ]1[]1# invalid bytesNIM*ffI3[\x)-'[n R"'[0 Pescap38 dcx 1 1\ufffd\ufffdc]'), ] for raw, errors, expected in tests:,='if"s not None%)>trydecoded =x.('cp65001')v8except Uni@DFE0 asnself.fail('Unable to u %a from |} with 'y}')=%r: %s' % (@>rr)assertEqual(dplT '%a#"", %r)=%a != %a o ?els~Raises(~3raw/, d1defb_lone_surrogates(w).< En , "\ud800".e%, 0JN, b"\xed\xa0\x80"Q "[\uDC80](6, "backslashreplace" b'[\\udc80]'rOnamemVxmlcharrefs�(7_escapRxO*_ignore(9?c E pass_handlerK>2abc9?def X "M;Sb0n 7R| "\U00010fff\uD8y$4f0\x90\xbfD /\x:* "\U00010fff\uD800") Vself.assertTrue(codecs.lookup_error("surrogatepass")) class UTF7Test(ReadTest, unittest.TestCase): lencoding = "utf-7" @def 0p_ascii()26# Set D (directly Hed characterst_d = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'v\ 'abcdefghijklmnopqrstuvwxyz.0123456789\'(),-./:?'fEqual(set_d. iing), '/')M00.de]MaO (optional j` o = ' !"#$%&*;<=>@[]^_`{|}UoeM 0 oM5# + Y_'a+b'ob'a+-b "^White spaces!ws`o\t\n\rR/wsu -wh# Other ASCII*o'.join(sorted(bytes(range(0x80))xE)) -H 0setLA_d +3o + '+' + ws)0 E@b'+AQACAAMABAAFAAYABwAIAAsADAAOAA8AEAARABIAEwAU b'ABUAFgAXABgAGQAaABsAHAAdAB4AHwBcAH4Afw-').QpartiI'lf0dcheck_" \x00c\x80d\u0100e\U00 Y00f',0[+'a#++/+-be|c~ !d"  'a+-b\x00c\x80d', "bo\u0100(e)6@\U00y{3f]K!) def test_errors(self):tUs = [(b'\xffb', '\ufffdb')E(b'a$a% )/0+IKvRvA+IK-$O+IK,%xmB20acsxt+z?wgrW?wgrY,Z,[-B\KwgrBb4ge/,+IKw5Z \u5/01fg /8"8bo3.. for raw, expected insPwith .subTest(raw=raw('assertRaises(UnicodeDeE& , cs.utf_7_d K 'strict', True)W1PEqual.bp('utf-7Mreplace') lnonbmp _',p4A0'.en4 ing), b'+2AHcoA-'Jud801\udcaLlf.assertEqu&al(b'+2AHcoA-'.decode(self.encoding), '\U000104A0') &assertEquJI-w'\u20acvb'+IKzYAdyg- ( w RQ 3wgrNgB3KA+l9 t<s!4 def test_lone_surrogates!):$,$Us = [ (b'a+2AE-b', 'a\ud801b'),&D\xff)Offfd)M$LAs&JH&Q)J/220d_  1f"IK7:q/5n 7 ]@for raw, expected insQwith csubTest(raw=raw('4raw`'utf-7replace')|) class UTF16Exi@unit.qCase): \]errorSRaises(UniQDWE5 , cs.utf_16_ex_u@, b"", "strict", 0, True)bad_argOTypex )ReadBuffer(\arrayWqimport 4Qreadb_{!e(E.@("b""mspam")"6, 4x 4Bempt): self.assertEqual(codecs.readbuffer_en(""), (b"", 0)) def test_bad_args(self):!_Raises(TypeError, Wk)?+ , 42) class UTF8SigTest( `, unit.CCaseing = "utf-8-sig"TBOM =@BOM_N partialdcheck_"S!"\ufeff\x00\xff\u07800\uffff\U00010000",:[L " # First has been  and skippedb'", # Secondi emiAE" 8byte of @ed "k"Nz&G- XO  w(M\u08 \V.OI4] ug1601501# SF bug #!!:  that the works with a $nOstr(b"\xef\xbb\xbf",\]), "",omd}getincrementaldeG'r(')(BBspam "d.E2(s. ML), sstream_bcunistrCABC\u00A1\u2200XYZ*4cs.WP + b"=xC2\xA1\xE2\x88\x8Ep)er /for sizehint in [None] + list(range(1, 11)) + \  [64, 128, 256, 512, 1024]:3istream = reader(io.BytesIO(bytring))5o5Aio.S":IO($zwhile 1nif sizehint is not None)-sdata = .(> p.?elsH)) A!ifv]break7p.write(> \dgot = 'getvalue2 self.assertEqual(got, undef test_`_bare(;)4 = "ABC\u00A1\u2200XYZ"A = b+xC2\xA1\xE2\x88\x834er = codecs.geB;"utf-8-sig"7for0n [class EscapeDePTest(unit.CCase\empty ?PAcs.e_!_d`p(b""), 7, 0>ytearray()F,Rb in 3256bF([b]dif b != b'\\'  (b + b'0' C, 2)#RcheckAing_!erL", (b"[\\\n]", b"[]P r'[\"]', b'["]'@Sr"[\'?'@a /\\!a!?x07#b#8#t#9#B\x0a# check(br"[\v]", b"[\x0b]") acheck(#f#c#r#d#7#7#8$8%#41%!!G!D$10EAEC1010h/A0$5Fxh/x4h for i in range(97, 123):b = bytes([i]if b notCb'abfnrtvx'@)with self.assertWarns(Deprecation;ing{;("\\" + bL g( c.upper()kso$kAr"\87\\8U.9U9U6s"\\\xfaX !) $def test_errors(decode = cs.escape_A5Raises(ValueES", -w, br"\x68[\x\8bEqual(ax]\x", "ignore"), (b"[&6)CereplacDo?]?", F 0$ U _0]\x08EH class RingTest(unitF.CCaseC^r. `f = io.B6IO(&f2u En~dFile(f, "uni_internalHutf-f2.write("a{f2.closei-# Python used to crash on this at exit because of a refcountP# bugD_csmodule.cd #bTrue(f d) # From RFC 3492 punyG_Rcases = [l# A Arabic (Egyptiank("\u0644A752 !28 3 144"Y >,48\u0634\u0639\u0631\u0628 4A`1F",  b"egbpdaj6bu4bxfgehfvwxn")! # B Chinese (simplified):?("\u4ED6 EC 3A C0 480D\u8BF4 2D\u6587~ ihqwcrb4cv8a8dqg056pqjyeCtraditional5011\u7232i@9EBD !AAtvzc91f659drss3x8bo0yb D Czech: Proprost#Eesky(0050\u0072`6F\u01<0070073$174"> ", 1B!6E5DC7 76 E710D>"06 X6J&791Pro-uyb24dma41aE Hebrew005D 5Dd5D4\u0!5E!E975D8>D 5D 5E"5D>P2> &&EA 4dbcagdahymbxekheh6e0a7fei0F Hindi (Devanagari]0092 939]0094@d917\u0$b(94x 92 94 91 94VJ09>'398 h|3V2h8947>F0902i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd#(G) Japa kanji and hiragana5306A\u305C 7F 9365E5\u672C\u8A9E9@8A71 57 664D8PD@3044F304Bn8jok5ay5dzabd5bym9f0cm5685rrjetr6pdx (H) Korean (Hangul syllables C1oACC4\uC758\uBAA4E0\uC0AC\uB7 B4(C7 D5 AD6D\uC5B4\uB97CJb74\uD5$ B2>(BA>0C5B^ 9Cp098\uC88B>FAE4C&989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5j6b"psd879ccm6fea98c (I) Russi)Cyrillic!0043 43  44 43 43 44 43Ex 434e0 >8Vb0>!0044J z|4.4(3A>&38Ab1abfaaepdrnnbgefbaDotcwatmq2g4lJ) SpanisborquolG%"00C0#00$&64\u0065\u006E\u0073!69DP70" "!6C5 6 >48 1>2D1 72D4  |2F 6F>B6C",$b"PorqunopuedensimplementehablarenEspaol-fmd56a"), 9# (K) Vietnamese: Tisaohngthch\D6 iti43ngV`tA(qr54\u1EA68$CBqF_ 679788>11ECpF >9vB\>@0056jK31ECvTU khC`chniti t-kjcr8268qyxafd2f1b9g(L) 3B<b33\u5E42\u7D44\u91D1\u516B48\u751F 3B-ww4c5e180e575a65lsy2b (M) -with-SUPER-MONKEYS5B89\u5BA4\u59qF8E\u60727#/H0074I6&558 50a05H$(4D>44'4B2&53-pc58ag80a8qai00g7n9n N) Hello-Another-Way-72305D\u308C 5E 5834\u6240-fc4qua05auwb3674vfr0O) 2 30 300306C@683914E0&322-u9tlzr9756bt3uc0vP) MajiKoi5de0(130B!D4h:'d9juau41awczczplS) -> $1.00 <-d"0032232323 2sf1-")i] for i in punycode_testcases: if len(i)!=2: print(repr(i)) class PunycodeTest(unittest.RCase)@@def 0_en,S(self^for uni, puny in)_5RcasesH-# Need to convert both strings`lower ;u, since@some of the extended Buuse uppC{but ourE produces only x2. Cing just; toE2is also insufficient input charactersM(ar.u.assertEqual(0str.0e(""), "ascii").?(),>2, +!)  dec. Q.b)! =,  8s20UniInternal+v9@RskipUnless(SIZEOF_WCHAR_T == 4, 'specific32-bit w(2_t'rbug1251300v0# D@with#_i2 uswnot correctly handle ","# points" above 0x10ffff on UCS-4 buildseok = [A(b"\x00\x10\xff", "\U00N"15d01\x0110411!]Onot_7"!"800!%!06O[S,W*okGif sys.byteorderK"little"*O0 = 2s(reversed()i-Csupport.check_warna(+O\u?"v h,(' 3c has been '{ 'deprecated', D BionWd)c sRaises(eError, internal.decode, @"uni,_internal")6if sys.byteorder == "little":&cinvalid = b"\x00 11"*_backslashreplace = r;Oelses os";with support.check_warnings()self.assertRaises(UVD_Error C  #jEqual(h(g3, "/") '\ufffd'3M 7 p!) @unittest.skipUnless(SIZEOF_WCHAR_T4, 'specific to 32-bit wchar_t@def K_~ _e_attributes('::tryG= ,(' c has been ''deprecated', D BionW)M;300"T!~except j as ex1Xex.encodingg >, ex.objectM 4+Ostar* 8*6endR_fail(P@callJ Rs.register#("I"bTest",s.ignore+s4r =(3get  Rab = "ab"jeNs("%s\x22%s" % (ab[:4], ab[4:] d "ascii"),  "UnicodeInternalTest") 1self.assertEqual(("ab", 12), ignored) /def test_enQ_length(B!):"Uwith support.check_warnings(('u#_i Jc has been 'HL'deprecated', D BionWk)E# Issue 3739b2r =Ss.get,("7U ;9a")[1], 1h1 \xe9\u0142:2t7 l8s.escape(br'\x00'~H4) # From http://www.gnu.org/software/libidn/draft-josefsson-idn-test-vectors.html namm p_ Qs = [O# 3.1 Map to nothing.(b'foo\xc2\xad\xcd\x8f\xe1\xa0\x86 Cbbarb'\xe2\x8$b 4baz\xef\xb8 8@!l-qb\xbf', barbaz') 2 Case folding ASCII U+0043165FCAFE\HcafeW3WA8bitADF (german sharp s)R# The originalu c is bogus; it says \xc3\xdf(69(ss4 U+0130 (turkish capital I 3dot[V4\xb0i\xcc\x87b5bmultibyte1I237AVR5\x83&ba^0\xc4Xe\xb9f6fPU+212033CR1D7BBd# XXX: skip this as>fails in UCS-2 modeD$#(z4\xa1\xe3f0\x9d\x9bs# 'telc8\x95kg\xcfp(None, q7 Normalization of&006a030c20A04jxcX0 =7$ a861FB7 and n9b7 d@6\xc 9 Self-revertIVs/F0u,`\xc7\xf0#(b0/10 /39fGe\x99f1fBf kf # 3.12 Self-reverting case fold U+1E96 and normalization. (b'\xe1\xba\x96', )# 3.13 Selfn/F5ndnn4 ASCII space character U+0020 ( '@b5 Non-DO8bitIAI\xc2\xa0P6PmultibyteU8168UbU9a\x8YHNone7Y9200Y2U8 Zero Width SGeU+200b=4\xeFbF G933X #20vcontrols!10'7Ff10\x7fQ#\xO'21 aY'85Y$85Y '22RWG180EWoa0\x8e[3No-Break8FEFef\xbb\xb'248D17f0\x9d\x85\xb5 Plane 0 private usHF123f\x84\xa36S/15T 4Uf3\xb1\x88\xb4Y7Y6YY10F23Z@4\x8Z 8\code point U+8FFFfV[SI10FFfbT 30 SurroggU+DF42IPed\xb2E3Bplain textx U+FFFDNRN2 Ideographic descrip W82FF33 Display propertyPG0341c1hcc\x81?34 Left-to-right mark 28 35 Deprecated@'2A@$aa 6 Language tagg%U+E0001. (b'\xf3\xa0\x8P1', RNone) # 3.37 Language tagging character U+E0042.;d(b'\xfU_1\x82U8 Bidi: RandALCatT05BE and sgfoo\xd6\xbebare9e OFD50eef\xb5\x90i/40i ?B38iW9\xb6ib'foo \xd9\x8-41wwithout trail`U+0627 U+0031I\xd8\xa7-42dSZ>628Zc8%u3 Unassigned code pointk0k# Skip this test as we allow u@#'# ( ,44 Largerh(shrinking)# Original!case reads \xc3\xdf(b'X\xc2\xad9f\xc4\xb0\xe2\x84\xa1j\xcc\x8c-0'C ;gaa\xce60]CxssiC7tel\xc7- 7( 'n5oexpand903\x"e3/96(92,8!\xN8 bd 1 bc N80\x8-bs28d\x29!2:#a2 cNA88') ] class NameprepTest(unit.aCase):/1def.#_n.S(selffrom encos.idna import 3I,or pos, (orig, ~ped) in enumerate(7_skC0if <1 isp5pedvcontinue# The Unistrings are givenYUTF-85S= str "utf-8", "surrogatepass"s$if `Input ains prohibitcs_.assertRaises(eError,,> NelseH /, >tryVUEqualM))  except Eion as e:   raise support.TestFailed(" 3.%d: %s" % (pos+1, str(e))) class IDNACodec3(unittesMRCase)z@def _builtin_decode(self#.assertEqual(o b"python.org", "idna"), )C.D/."E@xn--_n-muaB\xf6MN H/enH,.4I aE/."F  GIh O P Plstream@r = `Pcs.ge"Cder(8(io.BytesIO(b"abc")r.read(3 #:") incremental*Ap"".join(Citerq (b([c]) for c in c*),U$,.%."pFH. 2 v+.0(b"Icxam", # &3r;ple-9ta.o=\xe4xampleDH!rgW |p", Truep+oreset( X9ta.o", ), "\xe4xample.")  self.assertEqual(decoder.(b"rg."), "o 9p", True<1") 9def test_incremental_enr(!):' b"".join(;scs.iterH"python.org", "idna")),?%$}.~%."[5A\xf6 @xn--Pn-mua,Cr = 7getE((L+.!("/b" /r7JeP), b"P^O-9tab J(be,j+_resetY  (("lerrors """Only supports "strict" 0 handler""8,>b/7/2forzs in ("ignoreareplac backslash"surrogateescape" Raises(Exception, ],N _ class CodecsModuleTest(unit.kCase):e . b'\xfc', 'latin-1' 5m_PTypeE,Ry4 abc'), 'Wk0Uni;DZt , ffcascii'0#2 keywordshobj=b'\xe4\xf6\xf c', encoding='latin-1'), '\xe4\xf6\xfc')) self.assertEqual(codecs.de (b'[\xff]', 'asciiyrrors='ignorev Q[]') mdef test_ e(y!):. /, b6Raises(TypeE , 2cs.y4 oLookup6, "foo", "__spam__"I rq('abc'), b !0UniE0, '&ffr# keywordsiJobj=Xz+/b'registerm!<6C, 42lQ!: 6B , "2get]">: k2get%> : Oread#2get= 9 ?wri3$2get= 9 _issue1813I0# I # : under Turkish locales, F of someq failedD<because 'I' is lowercased as "ı" (dotless i2oldi# =rB.set(.LC_CTYPE6ddCleanup(locale.setlo ", .LC_CTYPE, old3) Etry: !G(Fv'tr_TR'DdexceptoZErrorT# Unsupported( on this systemself.skipTest('test needs TurkishD c = codecs.lookup('ASCII#VassertEqual(c.name, 'ascii') @def rP_all(4)qapi = ((-0"enyb", "de register"CEInfo IncrementalEM:r",D"DeNStreamRead^3Wrin  L2getD2geti' 7get% >rCgetw ? _e* .bstricts-wreplaceVignor @xmlcharref9backslash C&" @open\dFilevP)9 (0BOM!dBOM_BE /LE'T_UTF8"YUTF16 ?_E'329*329/329($v "BOM64@!64< @docu*ed^Qv.CCounDapi, _&__3@for +in#getattr(|0cs,3  ddCleanup(.unlink, jTESTFNmode in ('w', 'r+wa 7a+'Qwith x1sub-II), \d+.. , 9  as fileDnwIsInstance(,x ?undefinedDRaises(UniVbI bcPK _, b'aL.6I?s in ('strict', 'ignore areplac backslashG): self.assertRaises(UnicodeError,,7Pcs.en `, 'abcrundefined', e:)s);g$"degbh  class StreamReaderTest(unittest.qCase): def setUp(!.rB0 = |Pcs.geYder('utf-8'0sm = io.BytesIO(b'\xed\x95\x9c\n\xea\xb8\x80')_q\linesAf = c"!er.o qEqual(fQ), ['\ud55c\n\uae00']) 7EPdFile(6 Qbasic;Ke7hA(f, mA16-lze(), b'\\\xd5w@00\x$aewwvM 8Dwlatin-1ef.writegc3\xbcfTSvalue xf0b all_u_bings = [r"ascii"X"big5 ThkscsucharmapFp037 H10062%12Wgcp1140**251234b(25~(2562588'42E4'50(72 ''77x8'85)85'88'86u'86(86[6'86(86u6u&69(874'93h'9449euc_jis_200HEx021>$kregb1803Ugb231{4gbk(hp_roman$hzEidna so2022_joi_Hl  ] class BasicU[Test(unit.Case, MixInCheckSHandling1def  _bKcs(selfs = "abc123" # all cs should be able.eqe theseB7for~nB1 %/cname =h.lookup(, )._0%ifbP.endsY1("_(AD += # M'elOQ == ":_1"MI" IJ.assertEqual.replace("_", "-"), J)) R @rt.cP_warnA(## ;- been deprecatedb7(b, size)1get%erM)(s); H, len(s), "Eing=%r" %Io(chars deb? O 0?in  !#  stream reader/writerjsq = Queue(b""6 q7nedresult = b""zc writer.write(c) chunk = q.read(%self.assertTrue(type(:) is bytes, Gencodedresult += C q = Queue(b""JPer = Mbcs.get(`ning)(q7 de0}M= ""yfor c in I:(Gq.write(^([c])s( w2+= njiEqual(@a, s, "ing=%r" % %if@ notbroken_uni _with_stateful# check incremental !r/er and iter0()/ %K>tryg%? wl except LookupError: # no IEr(MpassOelse Ngb(s$ L"+=2er.7@"", eu G' W$+=.8r@  4:|`.join(7cs. /2(s, I ,  empty string 8/+  ("idna", "mbcs"):  # check incremental decoder/en with errors argu' F Otry: N = Vgcs.getv(ing)("ignore")Sexcept LookupE: # no IEAOpassOelse dresult = b"".join1er.e(c) for c in sp ]SL.(bytes([c])OlHself.assertEqual(8O, s,{! "ting=%r" % !) D@support.cpython_onlydef test_basics_capi()`from _&0 imK_,rqs = "abc123"2all5s should be able toue theseBlMpall_uniI_su"ifKping not6ebroken9_stateful=A(fetched vian C APIc$era. q(yHL4+= -_\8"", TruewcB&O= ""  Wr/A (.0 C("idna", "mbcs"5ental decoder/encoder with errors argument Otry:,cO = Wpc_increL#al(ing, "ignore")Pexcept LookupE: # no IUEAOpassOelseedresult = b"".join(."(c) for c in s0cde/r P4"r.(bytes([c])PmHself.assertEqual(8O, s,{! "ting=%r" % !) Ddef test_seek(y)R# alls should be able toKqe theseMs = "%s\nq(100*"abc123", gdef456"pall_uni_si"ifing == "idna": # FIXME: See SF bug #1163178@vcontinuYin broken_stateful=R0reaRs.get`)(io.BcDIO(s)t.t'wrange(5# Test that call&p resets interna and buffer.H^(0, 0sdata = )(%f 0s, 9 Bbad_\_args" 4N< &Raises(TypeD#, ; ?!no(p, "puny"kO, 42'e'5N '' support.check_warnings(## -has been deprecated"   ing_map_type_initializedS5romV@s imu cp1140# This used to crash, we are only verifying there's no crash. table_type = (cp1140.encoding_")1self.assertEqual( B&, !) 2def test_decoder_state(E!):"# Check that get%v) and s`handle " properlyIu = "abc123"Dfor in all_uni_s&if20not6ebroken9Bwith:ful=A .c%_O (yb, u, une)pNRK<R class CharmapTest(unit.CCase _rI {0: sys.maxuniR + 1, 1: b, 2: c}%) self.assertU>DYa}Uo0xFFFEeEqual(u (replaceF)Go("ab\ufffd", 3)c_Nebackslasht9sI-| P_ignor2L#b  class WithStmtTest(unittest.aCase):@def 0_enT`dfile( f = io.BytesIOfvc3\xbc" Pwith BBcs.EKFKf, "latin-1utf-8") as efbuLAef.read()fo-True(f.closed`streamGerwriter!dinfo =lookup("GSxrReaderWx0f, H.f  info.streamwriter, 'strict') as srw: 7:self.assertEqual(srw.read(), "\xfc") class TypesTest(unittest.TestCase)W@def _decode_uni(g)#~r# Most %rs don't accept 4e input,5= [L`cs.utf_7w,!8! _16_le%b%/exJ /32"?32_?32_ latin_1 _ascii! }charmap#]if hasattr(s, "mbcs3"&s.append4.2)[4forS4 in swQpRaises(dError,3`, "xxx2~_escapeE-Uing ang is supported and gives the same# resultN&equivalent ASCII bytes _.@j.r(r"\u1234"), ( F, 6)ZQbR(4raw5h0U O3UD<d , iU00110000"Z%6r"\E, "replacefffd", 10& abackslashj Jx5c\x55\x30@1\x3MbdhKl5ep (r"\x5c\x55\x30@1\x3", 10)) class UnicodeEscapeTest(unittest.Case): def _empty(self.assertEqual(VBcs.u`!_ea0_en(""), (b"", AE!deEbFE 4rawmV0 = EMfor b in range(32, 127O%if b != b'\\'[0]1 q(chr(b) ytes([b]), 1;tK7256Kr c%(bp + b'0' + '0', 2  $Rcheck-Aing_!er", ,)-('\t', brn.n'rr\\ Gw+0noto'\t\n\r'K9, ('\\x%02x' % b).&() {^127, V0s'\u20ac z$U0001d12m!) R eP}-, b"[\\\n]", "[]"r'[\"]', '["]kr(br"[\'='>^( a o"[\x07"b"8"t"9"O\x0a"vDb"f"c"r"d"7"&78#"41$!f#41E!B#10CACB1010e/A0#xD/x4D K| %"\;", "\U0001d12S0")  for i in range(97, 123):!(b = bytes([i]<if b notCb'abfnrtuvx'A*with self.assertWarns(Deprecation;ing|;check(b"\\" + b, nchr(i).upper()/UNNu 7-32$Qr"\8"_8T.9T9T6r"\\\xfaW !) Tdef test_decode_errors(0 = $`cs.uni s_escape<P@c, d(b'x', 2), (b'u', 4 U 9dXRaises(UDE", ,:cZ"0"*i6t?[7u~]x@data"3 I bEqual((Y, "ignore""[]", len)$L `replacM > ("[\ufffd]zr br"\U0011000VF  0 W", 10E5 ("L class RawEBTest(unit.CCase\empty {cs.raw_ en!("_b"", -ICbJIqM*Q2bN7256O!bd( b)0|b]), 1)K^ #.assertEqual(decode(bytes([b]) + b'0'), (chr(b'0', 2)) def test_escape_enCaself):"&0 = cs.raw_uni 92Rcheck1Aing_0er(X", O)-for b in range(256|if b not$Vb'uU'b('\\' + 3, bu1u20ac', br'\ $U0001d12;(GeG#1G,G78#, K[uB(br"=4", $9( Gq_errors6G*@c, d@(b'u', 41b'U O.i+d{j.assertRaises(UDE", ,:Pb"\\"V"0"*i>2t?[u~.]"|data = b"3 I TEqualY, "ignore""[]", len(.))L `replacM K("[\ufffd]zr U00110000MF  0 W", 10E5 ("L class EETest(unit.oCase):';Ys = [yb(b'', :0))(b'foobar# 6)spam\0eggs-4\x094Aa\'b."a\\'b", 3&0b\\b(b'b\\ 'Ac\ndM2'c\ &Bd\re&"d\ &bf\x7fg($f\ *]Gq, outpum: with self.subTest(data=K): ) assertEqual(codecs.escape_enB), output)E=Raises(TypeError, 9 I, 'spam'C*bytearray(bN) class SurrogateEunittest.qCase): @def `_utf8(!`# Bad l,7".,b"foo\x80bar".de("utf-8", "sM5"),KO J2udcL  ).u# ta# bad- `%d \xed\xb0-`\udced b0680" |"# /- )3^ascii4b4$O4]u" 4Icharmap: \xa5 is unmapped in iso-8859-3O x)a5l:=%Q[ 2udc)Uz' Xnlatin1AIssue637"4 bf!f6%c"d/-12b"\xe4\xeb\xef\xf6\xfc"}0Bomc(q'\seek0 = "1234567890"Bs = ]?16"J_16-le b/329/32W ]32-be ddCleanup(support.unlink, fTESTFN{2forp0ing # Check if the BOM is written onlyw once !with codecs.open(support.TESTFN, 'w+', encoding= y) as f:LWf.write(data)nseek(08 self.assertEqual(f.read(), iN * 25/f.O* # Check that the BOM is ten after a rcI>[0].%No1@tell1_* +) ^(StreamW</r)mrt?er.{ $J?not) at a positiondifferen3!an8Ystart'I*f!i  /# | N  |i br%T + bytes_transform_Qs = [i"base64_-"",*uujquopri5hex6] d`aliaseb{N b3: [s1", \_64"]y'%uu quopri", "quoted_printable", "quoted], "hex_codec": ["arot_13Prot13q} try:;import zlib except IRError$ = None elsebytes_transform_encodings.append("8)m-aliases[$] = ["zip<-"]?bz2Opass?bz2 #bz2"] class TC|Test(unittest.qCase): @def _basics(self)Jbinput = W(range(256):#Dfor e2 in*V7Pwith n@.sub(E= 2# generic Xs interface#(o, size) =-A.get\%erm")(@assertEqual(MT, len34/(it deto;oon4i,  LreadZ6sin(b"\x80",:&er:2get@io.BoIO(sin'o9.(j{Sout, ))EOlineTX-buffer_api_usag`# We check all the 1 ac+memoryview :)# Aand 7ing$also thatiy roundtrip correctly1original&a"12345 s!Mtdata = &= "(2|encode(data, encoding) `view_eed = codecs.(!, =self.assertEqual1No, datar = memoryb(( de+F, original_]nNsdef test_text_to_binary_blackliststransforms(_!):@# Check ;4 -> cs give a good error for str inputHAbad_r = "bade type"%; in bytes_FingsPwith .subTest(E= 2fmt = (r"{!r} is not a ,~&; 4Zr"use \(\) to handle arbitrary&" msg = fmt.}a+RaisesRegex(LookupE, msg) as failure+v)+YtsIsNone(Z.exception.__cause__) @zhx3strkslumessaget!->{f(r"^'rot_13'* "just an example ""(""rb"w.A andTarray l# 6.)Q = b"pe firstCensure weyPmat restricws:Z#d_n w9ww:  encoded_data.de (Ring) $with self.assertRaisesRegex(LookupError, msg):?Ibytearrayg{)|>def test_binary_to_text_blackliststransforms(|# Check str ->c gives a good eR for ia input1ad_ in (b"immutable", $b")D<subTest(bR= 48 msg = (r"^'rot_13' is not a  5; "9ar"use sj \(\) to handle arbitrary&", as failure"("yqsIsNone(Z.exception.__cause__) P@unit: .skipUnless(zlib, "Requires  supportxqpcustom_#__is_wrappedd-@^0mal+eda!"^Aing .'Q_'X&ed(!Ea(b"hello", "SmIsInstanc ,;?typR) ?hex3hexI|?b~y# Unfortunately, the bz2 module throws OS+Qwhich%I-# machineurrently can't 2 :(s# Ensur$ aliases from http://bugs.python.org/issue7475 workoR@ e_name,g5in y_<{.items(expectedA" =1s.l4(\ ).b-}\x .esS^+=  info = codecs.lookup(alias) self.assertEqual(A.name, expected_!) @ def test_quopri_stateless(J!):%h# Should en with quotetabs=True,#d (b"space tab\teol \n", "{-W&c" F3d, H=20tab=09eol=20\n=r# But sstill support unescapedas and s"=l,u eol\n"' @s.de (F , uu_invalidMissing "begin" lintRaises(ValueError,@Ax%uutr # The( system tries to wrap exceptions in orderensure the elb # men(Popera0 beperformedy"-c involved. We # currently *only* want thihappen for relatively ' #S, wheK significQ"rmthey contain hheir # type a le str argu.;Use a localCregistry#`avoid arto leak objectsBn # 3e#`multipkearch funcEs _TEST_CODECS = {} Q_get_O(xreturn ?H.get) 5$s.(UQ) # RG s None, not usable as a `rator tryy# Issue #22166: Also neqo clear=`intern@@achecqCPythonobfrom _1 im@_for ! I*#pass class EChainingTest(unitb.fCase):D^setUpT{'s no wa $un_# a,s, so we just## iawe ren} one fairly harm@ aft!heCcase finishes by u @repr/F(s module normalizes2s, althoughhdoesn'# bemally docZWed...x@We a<Qmake uAwe uztruly unique idLbcustomJ2to iscwhen runMsO&%# times (e.g.P huntf _i"o8 + str(id(self))  self.codec_name = encodings.normalize_(unique_id).lower() I # We store the object to raise oninstance becauwf a badHinteraction betwee< caching (which means we can'tFrrecreat;entry) and regrtest refleak huntWH1unss!4multiple times). ThisE@need Censu!s call back in"<`hto finBout Qexcep$drather than binm[a2cloEo anhat may changnext run?3robj_to_0= R=rmeErrordef tearDown(3%):B_TEST_CODECS.pop u, None)0# Issue #22166: Also pop from es;avoid appeard of sN0s._Ke6try_forget_ A Key DFpass-sN,Pe, ded>c_info = 0s.CQInfo(7,=[&]@contextlib. qmanagerassertWrd@p, opera, exc_type, msg full_msg = r"{} with {!r}  failed \({}: {}\)".f!t(z p !._"__Fy6RvsRegex(0) aJughtyield ca\W3IsI0(%.Raion.__Ar D0NotQC.__trace#__C_obj*args, **kwds`# Help|o dynamiLRqd by a M dYzcheck_w:= b = ) ., !"Fing""str_input".3eltype, msg):  codecs.en ("str_input", self.c_name) 7BwithassertWrapped("decoding", exc_type, msg):<Db"bytes i.6/e(oFsg }def test_raise_bycheck_wRuntimeError, "") PBvaluQmsg = "This should be \"JAx (sy~grandchild_subclass_exact_siz%G8 My( __slots__ = (\ T,nk_weakref_supportOpass  cv5notz:, obj_to|obj(*args, **kwds& L Aset_W(*e_obj, t*RNisRegex !#h v) Ia y%init_override_is_m4CustomInit(<a!__^_ 1nh?new!?New\L_(cl6return super().__-_$ ?Newinstance_attribut uld NOT be wrapped" exc = RuntimeError(msg) .attr = 1self.check_not_wU(exc, "^{}$".formatL!) 9def test_non_str_arg_isBY!):/h |1), "1"emultiplefsg msg_re = r"^\('a', 'bVc'\)$, >2), \# http://bugs.python.org/issue19609+codec_lookup_failure1 msg = "^unknown encoding: [Fname# The initial } } should not be Qwith WassertRaisesRegex(L[;"str input".!e(I~_g(Osbu, o7tb"bytes de`Ib x`unflaggedPtext_c_handling"stdlib non-4* s are now marked so they'reu# pre-emptively ski0 by+ Mmodel related methodsBHowever, third partyAwon',we still makAsurew&case where an inappropriate output type is produced i.7ed 9%lyn0_to(*args, **kwds^#return "jDY!", 0MMeObP:strNj#se(+, h("No9 or#Bs onYds module function:p3d =ONoneiSEqual)d,6g(g77d, Nf`# Text$el7complainfmt = (r"^{!r}2er ed 'str' instead of '6';   r"useAs\(\) toW to arbitrary types$") msg = fmt.format(self.codec_name*Qwith assertRaisesRegex(TypeError, msg):_f"str_input".en[efmt = (r"^{!r} de/r returned 'bytes' instead of 'str'; "t r"use @2cs.Is\(\) toW arbitraryb!b"  @unittest.skipUnless(sys.plat == 'win32', 0 '  pages are specificWindows') class CodePageTest({CCase# CP_UTF8 is already ed by CP650015-!=  1def3_invalid__j zT(Valuv7!cs>_i, -1, 'a'HHbI #OS?123FF ExB0Uni8EM'cp9J&d932, '\xffh nDnnb'\x81\x00',ict', Tru  = [4 , /ffbcheck_>Q, cp,sfor raw, eMs, expected in- ['if"s not None%>>try4d =*D( eEsexcept N0 asHfail('Unabley %a from "cp%s" 'Rp'9=%r: %s' % (\)HbEqual(Fd[0][3'%aa(, %r)=%a != %as"# S 0 <=@d[1]0len self.assertGreaterEqual(decoded[1], 0) Rself.7NLess4len(raw);_else:M Raises(UniDmError,6%0cs.b_page_, cp, raw, e=s, True) Edef check_en:(3ftests)for textHexpected in .-6if "s not Non:try:>@d = ( cDcxcept FEF0 asz.fail('Unable to t0 %a "cp%s" with 'Ln'z=%r: %s' % (V "M]YUd[0],_B'%a..(, %r)=%a != %a6 t9 8)a_cp932~ i932, (('abc', 'strict', b)('\uff44\u9a3e0\x82\x84\xe9\x80'=#aor handlersI\xffWn H0('['](PignorLb'[]q)creplac*y+Qu20acV -?-1xff+backslash4\Ename3  b'[\\N{LATIN SMALL LETTER Y WITH DIAERESIS} xmlcharrefi\oÿ:O\udc~)surrogateescap_8apass',U.a (-b' 4 # invalid byteC)) '[.fdb'[\xff]', 'backslashreplace', '[\\xff]'), B(b'[, 'surrogateescap7?udc8pass', Noneh\x81\x00abcostrict.QignorCao\ufffd:@\|1)) Qdef test_cp1252(self):o.check_encode(&5, ("&,('bp'\xe9\u20aK1 b'=x80' y-,ff)# error handlersi\u0141M'(,b'q('?b'L)Adc98x /984%))/de90e9\ , 3!ff[)z\_utf7{cp = 65000/cp@+AOkgrA-{U0010ff b'+2//f/w4Yudc80_b'+3I` ,9//0X  3( 0$, , # invalid byteib'[+/]W/'[T h Pmultix%ff\u20ac b3 *??7xmlcharrefA€ÿ€a0abcdebackslashZc O[b\\xff\\D1udc80\udcffdsurrogateescapV M~0subF(= = K =expected):  'self.assertEqual(data.encode('ascii', error_handler), @ expected) ,def test_Y_surrogateescape_`(!):1WPwith Raises(UniEE48# the first character can be de=d, but not,esecondyE'\udc80\xff'''f lsb'abc'..n1), T+@for  $, Y in (b(b'[\x]', 'ignore ;[]' -breplac.b\ufffd: ;C, '[l_udcffBbackslash A SqsubTest=;= g= xR v   F r class Latin1@unitx.CCase  O@", )"!('0xe9'& / gx1('l&') g*gsyh B20ac k/b'l1Yb'[??:(4U000abcdei+  !\u\: ^Z0xml\9ref€�Y-, M.,U=g+{ 9(s(UnicodeEncodeError): # the first character can be decoded, but not,isecondE'\udc80\u20ac'.en7('latin1', 'surrogateescape') @def test_iW(selffor data, expected in (;`(b'abcd,),[\x80\xff]$+sWPwith .subTest(== =A<assertEqual@.)L) if __name__ == "__main__"@unit*.() # UserString is a wrapper aroundnative builtin s.[type.Anstances should behave similar toEobjects. import Q from w_"s collections&w classLp.Common MixinStrUni_0.ACasec"):'2' =# OverwriteiQthreemethods, because?#_'t cope marguments propa)du# (and we don'tqA1sub51es)*Yachecke, result, ", t, *args, **kw 6" =0fix(mT &&#1fix;/ )!itrBreal = getattr(q,)(B.`. tqaraisescolb?obj96CoRexc) as cmoXUR#Nostr(cm.excepH), '/Ccall-+?ect.6ectg9?ect A] suEos module, thiswoefully inad"te! # does add s Ja few functions which* have been determined to be more # portable than they had4rthought1P. im. asynchatN dcodecscontextlibtdecimalTerrno fraction?egetpasitertooldlocale?Dmmap o$Fpick$Ushuti~FsignUsocke&stsubproce%syasysconfig|threadin%imuunittesgDuuid9warnings from & V0sup~ try: resource except IRError(!} = NoneA_fcntl>;_winapi= ?1grpgroups = [g.gr_gid for g in grp.getgrall() if @user!n 9Amem]Qif hasattr(os, 'ABid')=l@= osNQgid()@"8if %2notH*.append(5)3]1pwd@all_cu.pw_uu0pwd!pw]k(, Attribute Yt_uDcapi`INT_MAX, PY_SSIZE_po0+ =1 = sys.maxsize ..script_helperassert_python_ok8*unix_shell, FakePath root_in_posix = False "&eu# 5("#() == 0) # Detect whether we're on a Linux0tem\`t usesa (now outdated # and unmainta0) l=D3L library. There's an issuwhen combiA C with a failed execv call: se<http://bugs.iQ.org/[X4970./ syRq_info').versionUSING_LINUXTHREADS2p.starts((" ") elseR@ # I #14110: SomeMspFreeBSDP0the@r isXawheel . HAVE_WHEEL_GROUPplatform'freebsd5W4 def requires_os_func(nametreturn $.skipUnless(24, 'K%s' % name) def create_file(name, content=b' '): with open-"xb", 0) as fp(,fp.write(D) # Tests wing TESTFN class File (unittest.CCasedef setUp(selfm if os.path.lexists(support.c,0os.unlink'tearDown =n }|_access0f = |,O_CREAT|os.O_RDWR)Uvclose(f.assertTrue(os.w \kW_OK))S]rangeOirst&# We must allocate two4secutive J descriptors, otherwise# it will mess up$ < (perhaps even the threIstandard ones).cbsecondPdup(fc6tryretries = 0Dcwhile N1!= HJ + 1?+1os.x lcI+= 1d4if N> 10^%`# XXX  skippedH'@!B("couldn' 6ds"C,SuR7kfinallW .!# , a fd that is^A, an5n'tOF + 2BRaises(OSError,c, b"a"@@cpython_only} re' V}1 9I olsys.getrefcount(4 FTypex , 6r]0newz]Equal(old, new,adVr, "w+b":objCfobjkb"spama fflush(-f,[ilenoos.lseek(fd, 0 >qos.read"4] type(s), bytes- s-0b# Skip est on 32-bit platforms:number of]fit in ae# Py_ssize_t @'0UnlINT_MAX < PY_SSIZE_,3   "needs INT_MAX < PY_SSIZE_0") & @support.bigmemtest(size=8+ 10, memuse=1, dry_run=FalseD@def 9_large_read(self, J!):im.addCleanup(|unlink, bTESTFN]8create_file4$@, b'{5') f# Issue #21932: Make sure that os.) does not raise anCOverflowError for rInZ5with open"rb") as fp edata =0fp.Cno()<1Thegptry to 2 mon 2 GiB nce because#rating system is freeOturn less bytesrequested.HssertEqual( Qwrite#) acceptv- and buffer-like objec!utustrings"fdLos.O_CREAT |tO_WRONLYfRas(Type,2, fd, "beansC1os.(b"bacon\n!ytearray(b"eggs* Lmemoryview(b"spam,close(fdA:objCfobj*.splitlines(),p[2",  #"]!_windows_conso)W*args retcode = subprocess.call() # ca new Vtflood t9ioutput[ionflags=m+E_NEW_CONSOLEvPshellp1hidf (SW_HIDE47C=TruDWelf.aO3, 0GP@unitp.skipUn (sys.platform == 'win32'`3 specific#W'r_|a11395:{ X0 re`as an e^A(12:eenoughr# space&P) on into stdout if m2is binary?(th`lengthgRc66,0001(or, dependowon heapfusage) "print('x' * 10%)"7ceys.executable, "-c", V? .executable,( "-u", "-c", code) def fdopen_helper(self, *args):$(fd = os.*(support.TESTFN,O_RDONLY)21]4(fdT!w.close(Stest_2CREAT|os.&WR#osj#fdl`.l3?'r' S, 100cYqreplaceX<J2 = Nu + ".2"&addCleanup|{unlink,> 8create_filef&f, b"1"\*"2#'2"N5os. /3PssertRaises(FileNotFoundErroreOstatQwith a , V as fpEqual(f.read(), }S_keywordsf$q(path=_A__, flags=, mode=0o777,ddir_fd=NoneW0sym \get_attribute(os, "%;try(h(src='target', dst= -_is_directory=False, except (NotImplemente!OS=cpass # No OS or unprivileged user # Test s on return values from*f* family. clhTStatA@K`s(unit.CCase\setUp+vWfname $ D( 4ABC@skipUnless(has'P'), '` needs#()`check_R", Ebresult#2(!{# Make sureect access works"Z[U.ST_SIZE], 3 a2.st_size,_xall the,0are%re1members =(|Afor !in !if"[:3] == 'ST_'8"! =*v.lower(e JP.ends("TIME"):   def trunc(x): return int(x) #]else:Fx+self.assertEqual(zgetattr(result, =)),?j 2[Astat, name)]~0In(e, members) m# Make sure that the st_?time and _ns fields roughly agreeK(they should always$ up to around tens-of-microseconds1for in 'st_aDst_m c '.split()floaty =)8+P * 10sf3nan>: + "_ns") //CApSAlmos|`, delta=2:try^[200]g fail("No exception raised" IndexError`Opassassignment ms.uode = 1,CAttributeOrdev.(R, Typ t Koparrot.  Us2at_Q constructor with a too-short tuple.p2 = os.Vf((10,)|!^Olong(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14b/Aest_2 s(3Lo.check*!.fT]_byteZ K1 = s .encode(sys.getfilesystemNing(0Uni4E:^skipTest("cannot QPe %a pm7" %QJJ _result_pickle(self): result = os.stat u.fname)%for proto in range(pickle.HIGHEST_PROTOCOL + 1^eCp = .bdumps(s,Re,.assertIn(b'_0J', p-"ifCF < 4G KWcos\nP.\nR"undkloads(z\UEqualA!) =@unittest.skipUnless(hasattr(os, vfs'), ')d needsbvfs()'@def "_@vfs_Eaibutesw2G%# Make sure direct access works(=.f_bfree, r3[3] ]all the @ are5re.gmembers = ('bsize', 'fr `blocksv Pavail ufiles',L 'f&00lagsnamemaxe2rvalue, enumerate(so5 "0getc'f_' +R)2i6ITrue(isi3nceK.f_fsid, int)oTest tha e 60 ofd tuple doesn't ch*r3lenlY), 10d0iassignment really fail9:try)9E = 1GC("No exceptiouRised" )Q AttrZErrorkBpass1PparroUA# Us constructor with a too-short2+f((10,),YOTypeTOlong+0,1,2,3,4,5,6,7,8,9,10,11,12,13,14 J"  _]& p = pi ckle.dumps(result, proto)  self.assertIn(b'statvfs_3J', p0"ifFY < 4:JU NZcos\nS.\nU@unpiBd = {.loads(}_UEqualA!) !@unittest.skipUnless(sys.platform == "win32", "W specific 9"s"1def_1686475()# Verify that an open file can be 1'ed$6try?0os.$(r"c:\page>4.sy$ except FileNotFoundErrorJ{Test(r'P does not exist'_!OSU_ as eZfail("CouldF 7Jhasattr(os, "pipe"), "requires os.-()O5261 'ing a closed fd7cause crash;fr, w =u)8E# shPpraise eFnfinall2&(rP2os.wQwith Re#s():ctxGB{Bctx.ion.errno,no.EBADF@`check__aibutes", hQiTTrue()\, 'stK/')?0isi3nce-.@_, intDC0 <=>30xF "J is  ia#_ (FILE_ATTRIBUTE_DIRECTORY&etl9f.fname%@ +d .&d.,G0h directory s 0dir = support.TESTFN + "dir"os.mkdir(2 ddCleanup(os.rmdir, +F {#e) self.check_file_attributes(result) s+assertEqual(!.<.stH & stat.FILE_ATTRIBUTE_DIRECTORY,G+ !) ,!@unittest.skipUnless(sys.platform == "win32", "W specific 9"s"1def_access_denied(!):l!# Default to FindFirstFile WIN32_FIND_DATA when M7 isBZ. See issue 28075.#&os.environ['TEMP'] should be located on a volume that@supports V ACLs^fname = os.path.join(q , .."addCleanup(i.unlink, /acreate(, b'ABC'RRny the righY[S]YNCHRONIZE'toqforce Cdto fail with ERROR_ACCESS_DENIEDDETACHED_PRO!E = 8Z`subpro;cal+# bpo-30584: Use security identifier *S-1-5-32-545 insteadfOA# oflized "Users"\not depen&le@['icacls.exe'~, '/deny', 'j:(S)']dionflags=? !#No4 size, 0) class UtimeTests(CCasew\setUpkBdirneTESTFN&|@c, "f1"UZcrmtree=os.mkdir.nav_subsecon,# Heurist!o 1 ifI+ssystem  s iQstamp%# l resolution:Pfloat and intFs are differen|"stg1ileoreturn ((0t_a != st[7]H3or *m*8* c*79])^_ _u  t_bD=Nonz0if R ' =-|( (J$if@ ~f# Time' aYr1 microJ (10^-6)A#  # The resolution of the C internal funcused by os.utime() # depends onDplatform: 1 sec, 1 usns. Writing a portableMtest with a 1 ns requires more work:A1seeissue #15745.$a_ns = 1002003000 # 1.Ionds7m7t40050067"4. 7Lelse?useisecondp5 * 10**9!8!"@set_(filename, (S$, <)@st =Estat5%) Q`if supB_sub self.assertAlmostEqual(st.st_|!, }* 1e-9, delta=1e-6_M M[;;r 6_ns3j3 @def =_r)'ns$v#DAns keyword parameter ,b[ns=ns_@lricmethons_to_sec(# Convert a numberBnano (int) to s (float)  # Round towards infinity0addG0.5 `Z`void r95ing!# n,?)%s_Fminuereturn (ns) + 0.5e-9{B_by_indexed(p# pass Qs as Tpoint Lx2:= n;$0 = ._1W- -uQnsat(apec), s4val(6bufuB# or10*_tMGX  ': = self.ns_to_sec(atime_ns) m = self.ns_t- -# test the 7s keyword parameter\@os.u((filename,7=!, f)_d_9@set_B!) YP@unit.skipUnless(f in os.supports_follow_symlinks,B "+ DQ for required "G ar this&"."1def;_nom(%):W09'ns$k# use M=False tosPnsat(EBspec@a# or ls#:val"] O=ns,z=.6d d  /fd%with open!'wb', 0) as fpr a  descriptorfnC2or (' & p.mno(), ns=:_dir_f "-F%2dir =6path.splitLRdirfd,Dos.O_RDONLY2?tryRpass  ,X= ofinallos.close(< directory%cpcallingp() on a`0i,>=q_current$, B# Ge!system clock@! = .(kh# Call tofrAtamp74he Mjset_time(self.fname) if not self.support_subsecond(3:3:delta = 1.0Jelse&# On Windows, the usual resolution of time.() is 15.6 ms.Xp# bpo-30649: Tolerate 50 ms for slowj buildbotD R!x86 Gentoo Refleaks 3.x once failed with dt=20.2{ So useJCalsother platfor9F0.05;st = os.statuhmsg = ("st_*=%r, current d"/3 % (st.st_m52', $ -I%))@assertAlmostEqualM5u =, msg=msgdef test_u_)J&"seQ(file q# Set toeHY1 inynew way1os.yqN_ 2_ol>=old explicit 'k, None@get_qq_system(g, pathtif sys. == 'win32'3rooA.splitdrive(os.0abs())[0] + '\\' imy ctypeskernel32 =.windll. .6buf)create_unicode_buffer("", 100<Tok = R.GetVolumeIna W(xI, 0,wC ? Bbuf, len(bufyZif okreturn buf.valu## 1 ifNrunknownU6Qlarge82v# Many Es are limitedyear 2038. At leastD^b# passGNTFSVA.dirQP != "C" skipTest("requires +BT = 50 # some dayE2128(F!, -?def test_utime_invalid_arguments(self): # seconds and nanoparameters are mutually exclusiveDPwith X .assertRaises(ValueErrorpwos.utime.fname, (5, 5), ns= ) from test import mapping_s class EnvironTests("`.BasicM9Protocol"""check that os.eK object conform toz# pB1"""Ptype2 = None def setUpn'__save = dict(w)<' if0sups_bytes_*QbRbSfor key, v2 in_reference().items(br[key] =BtearDown9v.clear(Supdat 'Qbm .b.r&b)\  return {"KEY1":"VALUE1", 22373"}^cempty_2}T# Bug 1110478?P@unit.skipUnless(unix_shellos.path.exi4!),D2 'requires a K'p_X2HELLO="World"`copen("%s -c 'echo $3W'" % P as p- .=.read().stripqaEqual(:%, (lg1os_\_iterr.\"line1\n2B3\"' UQit = K Inext(it), 2?2\n232 StopIteration, C, it# Verify J3"s Qhe OS/Rof th#`# corrO@str 0.=81keyF_ 4 self.asser tEqual(type(key), str) self.asser-4val-.def test_items(5!):Kfor key, value in !._reference().959'}os.environ.getV!) o# Issue 7310__repr__"""Check that the (f() of o looks like ({...})."""jWenv =7 euenv), 'Q {{}}})'.format(', '.join(Hep'{!r}: +_ {4envm#))6%get_exec_path*0defR_list.split(os. 6sep = ['/montyp/python /flying/circus']@V{'PATH':_R2sep$")}%csaved_Z \&ry4q= dict([5(P# Tes,at defaulting tofy works.8@Sequ;,B )M|D"env=NoneLofinall BYP# No ment variable4F'{}# Emptyo)_('',)hN*''qSuppliedt)6R{ijsupports_bytes #u cannot contain c and b Ekeysct# ignore Br@Warnw ?.Swith s.catch_(record=True;2mix5 = D'1',y: b'2'}xiexcept Z&# \be created nI -bb_>:pas+NelseeRaises(V^Error_,o!# 2/or m ) os{=yabc'}),Js [']H self.*assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}), [)])_self.babHb c@unittest.skipUnlesssupports_bytes_environC"os.&b required for this c"1defV b(!):Q&# M7 ->b$value = 'euro\u20ac'6tryNR.1 = .encode(syfilesystemOing(L'surrogateescape'*except UninEtZErrormsg = "U+20AC character is not able to %s" % (g *QTest(msgz2['u$']4s7,j]76b[bp9%) wb$ = b'\xffk7uD_str*0.de^  7*#['w$# On OS X < 10.6, unsetenv() doesn't return a (bpo-13415).E@.s_mac_ver(10, 6a _e 0if platform == "win32"S# an >ment variis limitedf32,767s0keyx' * 50000PRaises(VA,a.__delitem__, keyaLelse4"="allowed i[InameFkey=_/OS^key_type`missind' 6key}cNotIn(%dWwith 4S1Keyz) as cm-[]]PKbIs(cm.6ion.args[0], 55JTrue7 __ress_context__,7del)[missing] " self.assertIs(cm.exception.args[0], missing) 5JTrue7__suppress_context__) <def _test_environ_iteran(T, collec!):3r%Por = (%$new_key = "__ 2__"xEPnext(?ator) # startR over os.f.itemsA# add a new j'in- mappingH[]6try\forcemodifiedD\oEqual(?, "kfinall7del 9Wz_error_when_changing_os /\jw/msp$/()x!_valuey&>z class WalkTests(unit.CCaseI0"""As fowalk().""t# Wrapper to hide minor differences betwee?@ andf #=~s both fun s with the same code base6C, top, **kwx if 'follow_symlinks' in ) -[0,xS.pop(LUretur(QsetUp`join =Ppath.addCleanup( ort.rmtree, cTESTFNX9v# Build# (/` !1/#a file kidtwo directorysFo tmp1;SUB^ ]a[C\2^_/noJSUB2,EpOtmp3_ t readabl\s 5L$a !to?FN.pbroken_AZ A TEST2/  #e tmp4  a lone file  self.walk_path = join(support.TESTFN, " :1")7Jsub17 Mo, "SUB67M7 8?ub2i2;ub2dC_2_;tmp- "_?tmp" 13Jtmp3,5,;, "-cA'2', o, True9'j4', F)GvHPSUB21IZtmp5'GGg2_tree = (sT0, [Y 21u9"], '["7/3"N ]AJelse ]a'"]os.chmod0f:tryeos.listdir30except PermissionErrorCaddCleanup( , pstat.S_IRWXU` >/, =Pos.un(/rm del self.#sub2_tree[1][:1] def test_walk_topdown(self):!%# Walk top-.all = list3.E r_path))iHW .assertEqual(len(all), 4)U# We can't know which order SUB1 and 2 will appear in# Not flipped: TESTFN,512t22212, = all[0]Vp0] != "")f.sort(t3 - 2 *_][-1](' ]`K0], 2, [,02"]vtmp1"])O51 +YAsub1G1R2R2RS G!,  Qprune , W=None&if@ is 5;" =v0# Pl the searchC%[]- for root, dirs, files in](b@all.Mnd((C,@# Docdescend into!'@if '' #n e that this also mutates81 wepnded to6!G).remove(w>2  >11  D Q_likeUFakePath-v<l bottom_up.[ 6-up ,d=False{ 4,?#2,# : 212 3[  2 (53], (s elf.walk_path, ["SUB1", 02"]tmp1"])) s5 assertEqual(all[flipped],'.(9Tsub11oa[O + 1_^%1122 - 2 * 2_tree) def test_Tqsymlink!):!if not support.can_*&*dkipTest("need +?"z/# Walk, following-%s.}Qit = ]@fs=True for root, dirs, files in L6_it!if-# =q '+X`&[]|' +/4"2UbreakJelseRfail("Didn'tFCS with~ qbad_dirX top-downerrors = []M !on:=s.append-s= next(\*zR(, |dir1 = '"'80os. e.join(z1d1new = , + '.new'5os.rename(?!, 6new#:try}M!r g, d, fe K(` $TNotInk+Anew,s.@dir2 { ifg@2 !=1!%?In(_-2)kfinall? sv) @unit .skipUnless(hasattr(os, 'f]P'), " s()") class F(# s( ,!""<s3os.;F."""f?a,Q, **kwargsD] 0_fds8_?topEIfyield {EP0, *Mfreturn *_compare_toL_!, t'F=() results. """ walk_kwargs = u.copy())f8 =  +zbase = :\Bpath `.join(2, 'dir1'2&3'>r s(<)O# Should workn&~4v x`# Try sAa '.nEthem]!.a)Raises(OSError,Es fcurdir\-/5'U Hob54',M" 6es.makedirs(path) def test_mode(self):with support.temp_umask(0o002(,ebase =.eTESTFNJ"parent = os.path.join(8, 'dir1')0,th.D020os.makedirs(`z, 0o555U.assertTrue(Rexist8)2Qisdiri 1 ifname != 'nt'REqual(stat.S_IMODE].)M)O<775 A_ok_ ing_directorye .g = 0o777@old_YMd&22J QRaises(OSError, , /, <-!, _ok=False61w0 =4 $8 # Issue #25583: A drive root could r  Permission' on WindowsQ(0absC]('/'):R#_s_isgidI;pS_ISGIDs;Ah!:try&!fn(uvzAos.l  6 xGos.chmod(Cx #| ^Elexcept (@unit.SkipTest('Cannot seta for dir.0if  % &F$!= L $Noe # The os shTapplyx from the YFyus, buta# this.` need `depend> that behavior. Be explicit.H# # http://bugs.python.org/iY14992^2# S fail when the bit is already set. os.makedirs(path, mode, exist_ok=True)3# remove the biQSchmodNstat.S_IMODE(os.lP).st_m) & ~S_ISGIDjMay work even whenv is not alr demanded3 | yfinally:os.umask(old_ !) def test_? ing_regular_file(self)Sbase = support.TESTFNQ` = os. j.join(+, 'dir1'>f11penjH, 'w.write('abcfclose(E.assertRaises(OSError,7 , 6#vGFalsi|F 2os. larDown:ks"2'53', 4,56|A# If=s failed,bottom-most directory ('../dirE1mayhave been creatKso we look forZZouterXb# thatsJQwhilec;Q) and , ! gxdirname&) @unit'.skipUnless(hasattr(os, 'chown'), "Test needs ") class C#@File"%s(SbCase):@/amethod`setUpCHG(clsLKkdir x1st__uid_gid_arguments_must_be_index7 b00uidIu stdg"givalue in (-1.0, -1j, decimal.D(-1), fractions.F w(-2, 2) VFType?,!, V, gidRO(3uidTO`IsNone W!, ?>" -1I)len(groups) > 1, "0moreqan one '")L ,W1D_2 = groups[S:2] uid = os.stat(support.TESTFN).st_uid-os.chown(, uid, gid_1)-gZ gZself.assertEqual(gR2>12) +@unittest.skipUnless(root_in_posix and len(all_users) > 1,?n "Pp needs K privilegeLmore than one R"@def ;_`_with_@(F%):quU_2 = [ !_1[ SR 2C 1not4@non- accountout_permissionO{ Raises(PWError E1@classmetho+parDownCG(clsos.rmdirA) K RemoveDirsTests(CCaseMi\setUpuos.makedirse:"te =ormtree@ Ast_rL_allGBdirapath.joi'%'l mkLdirbK" , AbAbArOJFalse(os.0exi}.//a)/m_opartiaccreate_filBjoin(dira, 'file.txt')) os.removedirs(dirbself.assertFalse(os.path.exist./?Tru.ay].support.TESTFN)) def test__nothing(M!):#tdira = Zjoin(Q0, '%'os.mkdira K:AbAEpcreate_|@Z0, ' Pwith ~Raises(OSErrore. p class DevNullTeC@unit.CCase|devnull"@openT$, 'wb', 0) as f&f.write(b'hellofclose(a?rb'^Equal(f.read(), b'') pURandom/s(!ur.|_length tl6@(0)) 0 1010a/1023450l_valueRdata1(?(16IsInstance(5v, bytes,2K2Not301, 2Cget__subprocesss, countcode = '\n'.2(0'im" os, sys',{ b%s)' %g -sys.stdout.buffer.E)Z-yflush()XRut = =_python_ok('-c'&de_yUut[1]-)D.-rreturn  -rk-s>00( #% @pskipUnlhasattr(B'get'), 'needh3Getjests(unittest.TestCase): @classmethoddef setUpCC(cls*.2try7 os.getrandom(1)Bexcept OSError as exc; if.errno == z.ENOSYS*Q!# Python compiled on a more recent Linux version=# than the curr1mkernel0raise unittest.Skip;&(") syscall fails with " }Nelsec zvh_^_type(selfzdata = v6l/.assertIsInstance(6, bytes+Equal(len*o), 16)0\empty0h1_, b''e_QTrue(hasattr(os, 'GRND_RANDOM')Z{# Don't ^ 9,8) to not consume-ArareMresource /dev/,_nonblock40# T:AmusttC. Check alsotflag exists NONBLOCKBQingIO # System u1 isinitialized yetOpass Ovalu1;|O2! 2Not501, `2) #p() doesuse a file descriptor when itimplemented the # getentropy() function,= or6R OS_U_DONT_USE_FD = (Y'Ponfigc!_c _var('HAVE_GETENTROPY')@15!or-8u7$_SYSCALL?E) @&skipIf(,B"os.cg1") 1 URo FD%s(}tUnless(1, "requiress moduleD_-ur#'hailingU^@ablejHopenG.# We spawnew process62mak obF0(ifvrlimit(# failed to restore the file descriptor limit after this,&swhole  # test suite would crash;2 actually happened onFOS X TigerKbuildbot).code = """if 1:import errno/osresource Qsoft_b, hard 4 = /Q.getr!(RLIMIT_NOFILE)P$s7 H, (1s)H:tryos.urandom(160except OSError as e@@asse9.;2 ==D0.EM2, e ?elsJqraise AP1ionu$("~Anot "*d"5"""]_python_ok('-c', )1deff__fd_closed(self)# Issue #21207: 1Q() shreopen its fd to /dev/'5 if"# bq/sy8@.supw 47Awith 8.SuppressCt ReL(O1os.range(3, 258 sys.stdout.buffer.write(k4rc, out,I? = S odetect]@# chsomething b, and 6 ita.addCleanup(.unlink, fTESTFNpcreate_S4$, b"x" * _0forO9in a6(fdL b(:pasv7q# Foundfd (XXX hopefully]Ubreak  &"({%!r}, 'rb')fnew_fd = f.d>no( 6935: posix allows new_fd and fd to be equal but .# some libc implementations have dup2 return an error in thisN]case.if new_fd != fd:!0os.m(*], fd)(sys.stdout.buffer.write(os.urandom(4)72 """.format(TESTFN=support.erc, out, = assert_python_ok('-Sc', code5Rself.+E(len(out), 8&2Not)out[0:4]uV[4:8]022.22) @contextlib. manager def _execvpe_mockup(defpath=None)1"""PStubsV 4  be funcwhen used as p qqRecordsE calls. The vZalways raise anPexcepynthey would n%lly never+# A list of tupleaining ( name, first arg,s#< 2 orbe thatbeen mad2Q= [] (qS*args5.append(('m#',,,#RuntimeE!("1oOed")yeze{ "OSverrno.ENOTDIR, e2tryhBoriga = os.& ee ! "S! =pk ^`3if Q is not '$s.$=.aQyieldhfinall ?K class ExecTests(unittest.4Cas@ skipIf(USING_LINUXTHREADS,"avoid triggerFa linuxthreads bug: see issue #4970"pe_with_bad_program(R#s(u,7pe, 'no such app-'[+!],*0argD aises(ValueError, os.execv, 'notepad', ())  self.assertRaises(ValueE?/[]?*O('',,Q'']) def test_pe_with_bad_arglist(!):-)pe1[], NoneG/{}E-P''], GP@unit .skipUnless(hasattr(os, '1'),2 "No internal55 function toi"."y_x_73r,-W_type}program_path =hsep + 'absolu5th'iF is bytesRP = b'futableC$Ffullr .join(os.fsencode(H3), Dwnative_O 'arguments = [b'Kname', 'arg152']6Oelse gf}  if != "nt"_"d} VJ>6nv = {'spam': 'beans'}D# ) D an r T._mockup() as call|KcRuntim=U4os.[$, %,  ^Equal(len(O), 1, (a[0], (A(v'r(s3,))I1A rel0#_"ge>() returns def^%=r"OSm \l, env=envI uSequence}   +', "h: # os.get_exec_path() reads the 'PATH' variable Qwith 4vpe_mockup() as calls:)01envZ = env.copy()"if test_type is byteEI"[b] = programa TJelse CB self.assertRaises(OSError,iW4os.,, arguments,= fEqual(len(FO), 1,Sequence40>[0] ('ve', native_full:, (DA))) #deinternalP_str()_!._ /F(str ifqname != "nt"EII  _invalid_envargs = [sys.. ut, '-c', 'pass']# null character in penviron .:newenv =. #["FRUIT\0VEGETABLE""cabbage"Rg QValueo ves2s, x<*vpLgorange=Ze[Qc=ORANG_lemonI` @unitx.skipUnless(platform == "win32", "W specificus") class WeTests([CCasen\setUpj:tryos.stat(support.TESTFNexcept FileNotFound FPexistFFals=|?exc:6Tru9Ufail("file %s must not p; &1ed &%sG+% g, exc) L" % ;0_re Y 2%,rename, support.TESTFN, suppor+".bak") def test_remove(self): .assertRaises(OSError, os.4 a Z_chdirY3X /mkXddCleanup(ounlinkSwith open3?"x") as f1 otOutims3 Xn, Nonex?modx>mod^0) class TestInvalidFD(unit>.CCase;singles = ["fp", "dup fdg qatasync estat",{dP "f2vfs$-tcgetpgrQttyname"]<#}.append("close")We omit  because it doesn't r an exception on some platformsKBget_o(6]helpeif hasattr(os, : ]check(get+#rreturn hfor f in slocals()["_"+f] = w, f, *argsx6tryYf2make_bad_fd():(Q AReIsmEqual(e.errno, f.EBADF?elsAfail("%r didya bad file descriptor"3% f]@skipUnless( 'i`y'), 'l` needs-2()'$!_f 4os.* nt), Fals_rangeEfd =m X# Make sure none of ths we are about to7areFcurrently  (issue 6542).(i7(10cR(fd+i   2pas  Ubreakif i < 2Ow^@SkipT(7Ip"UnablePacqui* of invalid file descriptors") %self.assertEqual(os.closerange(fd, fd + i-1), None) =@unittest.skipUnless(hasattr(os, 'dup2'), '& needs os.2()'@def _!):_`.check"O, 20ofchmodw$/, ?own?own pown, -1pathconf &, "PC_NAME_MAXmf0aftruncate &2$_lseekx#?, 0?rea "?, 10v+v(buf = bytearray(10TV, [buf]tcsetpgrpt<(?wrix<#o, b" "4 <T'abc'!inheritableY Gget_-s'_, Trueblocking'),x '3`() andI9,Zlf.check(os. set_blocking, True) class LinkTests(unittest. Case): def setUp(self.file1 = support.TESTFN9 $2 = os.path.join(1 + "2") 9rtearDownu@for tA in %, 2%ify0exi@ %)os.unlink(!__f,1npcreate_>C1]2tryO 1os.R.L except PermissionError as eGP.skip$('V): %s' % e)Twith open`, "r")S6f1,22l`assertE(@sameX1(f1no(), f2 ) &stP oB1a_bytesP%V`ys.getsystemencoding()),; HO2, sH unicode_name(!fse("\xf1"&UP# eraise S("Unable to [ Xthis platform.$R1 +=  1 &@0If([ == "win32", "Posix specific 3s")`UidGid qUnless(hasattr(os, 'setuid'), 'd` needsV2()' gMz() != 00.aRAs(OS,m2, 0m 1~verflow7S1<<32g?gid and not HAVE_WHEEL_GROUP ?gid !7 eVlowError, os).seteuid, 1<<32) @unittest.skipUnless(hasattr(os, '7gid'), ') needs osQqgid()')L@def "_3q(self):l if6@getu5 != 0 and not HAVE_WHEEL_GROUP6:I.assertRaises(OSError,Ro2, 02verflow8rI W?, 0!<@(0T {C"\_neg1\1# Nto accept -1. We run this in a subprocess +Evoid# altering the>dner's 6state (issue8045).@\.check_call([ sys.executable, '-c',&'import os,sys;p6(-1,-1);Hit(0)']/re5&g#@#\%] 0If(platform == "win32", "Posix specifics") class Pep383Tests(CCase\setUpa`if sup.TESTFN_UNENCODABLE_dir =3.el[NONASCIIX0Use: s elf.dir = support.TESTFN s"b#os.fsencode(Udir) +bytesfn = []def add_filename(fn):e:tryGp9fn)6except UniE^ErrorLireturn>p.append _UNICODE+if8_UNENCODABLEX 5\ NONASCIIY2 VCnot  JskipTest("couldn't create any non-ascii "AuFset(|os.mkdir= for fn in4a_emptyh(os.path.joinmV, fn)Ck deL !#if @)raise Value("duplicE7+ [:.ad rshutil.rmtreWrtearDowK9tst_list=expectedH1>BfountHassertEqual(;$, ds# test L without arguments}current_directory = os.getcwd Pos.chfos.sep{ 3os.[()), Gkfinallw m=ope; ;f>-1dir,j, 'rb'f.close(P@unit.8Unless(hasattr(os, 'statvfs'),= P"need02()"y{# issue #9645c@# sh AfailDeWZ@fullC k> 2 (=B ]X 6) skipUnless(s ys.platform == "win32", "W specific tests") class PKillTP(unit!.Case): def _kill(self, sig0# Start sys.executable as a subprocess and communicate from thebH. to parent thae interpreter is ready. When itJcbecome!, send *sig* via os. ewGheckL}return code}PequalDY.2import ctypes ":win$umsvcrt ;# Since we can't acRthe contents of1n' stdout untilNhas exited, use PeekNamedPipesee what's insideVL@withhwaiting. Thissdone so@ telL@is sJ!ed-running at a point where it could handj6nal =.windll.kernel32.' @.res4 = _.BOOL.0arg.Us = (0HANDLE, # YA..POINTER(pc_char)O?bufNPDWORD?Buffer size@ O3bytsO8_availP.B) # 6lef)smsg = "j"g"' =.Popen([u, "-c",7C "Fsys;f/g.write('{}');oflush(7input()".Bat(msg)]=B_.PIPE8?err8",in7).addCleanup(.o.close+?err+$in*count, max = 0, 100@whilQunt <#n`poll()7BNoneu# CreateN trbto store the result of stdout from the pipe buf = ctypes.create_string_buffer(len(msg))8# ObtainVtext currently in proc.} 7 Bytes read/avail/left are s NULL and unused@rslt = PeekNamedPipe(msvcrt.get_osfhandle(.fileno()),M Dbuf,sizeof(buf), None self.assertNotEqual(i, 0, " failed"Aif buf.value:_\Fmsg,1.decode(YbreakPtime.sleep(0.1count += 13;els("Did not receive communicationw0subeess") Zros.killpid, siggSCs.wait()+Kdef test_M_sigterm(>)I# SIGTERM doesn't mean anything specialTt make sure it worksiOW.j(signal.X >int on Windows can tu an int which gets set asgPexit 7100_with_eve!, g, name0tagA = "Hos_%s" % uuid.&1(m = mmap.(-1, 1, C&u[0] = 0# Run a scriphas consol;antrol enabled.C6 = M.Popen([sys.execut2os.path.join( 0dir0(__"/__ S"win__uer.py")][ionflags= CREATE_NEW_PROCESS_GROUPKQ# Letinterpreter startup before we sendBnals. See #3137@P, maxF, 101whi<#r.poll() isSAif m:= 1|@# Forcefully `ess if @were 3 to6 it  6INT-S@ didifinish initializjb#10endBnal(" could also be done here# Allow time for the signal to be passed and the processsexit. time.sleep(0.5)aif not8.poll():;# Forcefully killgif we weren't ablezK0os.A(S.pid,v.SIGINT-self.fail("sub31did stop on {}".format(name)) @unittest.skipBBes ainheriting Ctrl+Cbperty"@def D_CTRL_C_EVENT(#from ctypes import win& # Make a NULL value by crea a pointer with no argumen;=.POINTER(j.c_int)(rSetConsoleHandler ?windll.kernel32./A.arg4 = ,H Q_.BOOL @.res% =7w@CallBthis\GCFALSE causesc,%to1# hB? , rather than ignore it. Tg1pro\C is z'edK6by &esg(3, 0? ._`_/r_event(.8, ""D _BREAKi=mq Unless(sys.plat == "win32", "W specifics") class ListdirTests(CCase0"""" l-AWindows."""#\setUped_paths = []for i in range(2t@dir_ = 'SUB%d' % i>#Y` = os. .join(supY.TESTFN, K >EfilebOFILEc%Zd ) eos.makedirs(K "}a open(C!, 'w') as f\.write("I'm %sproud of?QBlame_os.\n" % [ |.extend([,< ]=9Ysort(marDownhutil.rmtree ?3st_xB_no_J TAwhenpath is not an "extended" path.""" # unicodeself.assertEqual(3 sorted(os.listdir(support.TESTFN)),4Vcreated_5s) %u# bytes!pos.fsen [0Q) for A in ]def test__](9%):"""Test when theastarts with '\\\\?\\'HSee: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#max& =` + os.@.abs ]M8Q..EE = bJ )B`"` @unit^.skipUnless(sys.platform == "win32", "W specificTs") @E!_uF_symlink class :S%s(zCCase@file9 '7_target =/ __$"__g4dirM LKdirname(I>"Rmissing_ 'c\setUpaexists%.k34?notk d0h1# aarDown/ifw.os.removeG.&!Oax-NmR0$Ll  *_directory*3os.D ",3 @True5.56-is5True(os.path.islink(self.dir C)) check_stat'!, 5_target) <def test_file_U;!):]eos.sym.)H] assertTrue(os.path.existsfL 7 isc7 7 7i6 9_create_missing_dirC!'C( a "directory" c to a non-Bent ''bname =m%4if `lJ s( 8fremove!F{ = r'c:\\does not Y.29r3c740#+"s(B0_is+0 = ~i(,#,:T\5_toP# For compatibility with Unix,ya will NE the5#  us and call RD0 if< sDBwas qd ==M.12os..6?P@unit@".skip("currently fails; consider for improvement"; is/onHqhaving s return truefs %F !=/rm!WPallow#u` )#Z SjPEqualkm),5Not<l.=Qbytes =rfsencod'`_@eC3Q12084r=blevel1+abspath(support.TESTFN) level2 = os.path.join(A1, " +2"0302030self.addCleanup(supprmtree, a51) os.mkdirz 23LWfile10abs(.&")Ypcreate_( rrig_dir^vgetcwd(;Etry:kUos.chBlinkIS7inkQ0`os.sym60rel<7ssertIn("@ ",@list4os.)Gsp# Check. stat calls from the same !as\ |PEqualI3tatax_below{ {1 1 Q)_above3Yfinallyo7@unittest.skipUnless .lexists(r'C:\Users\All '}0andGFProgramData'), P'Test4ectories not found}@def p_29248(#)#) C+SymbolicLink, which Es# reparse data buffer withpprint nSgstored=first, so*offset is always 0. ?P "PgName" DOS T (e.g. "C:\") l>3an wof 0, followed by"Substitute]@)NTfA\??\ju. The " " AG, on=gother hand, seems to have beenl`d manu>inverted order."btarget@read !.aPETrue 0(U!,  'j_overflowtOlder versions would@= when detecting #0 whether a link source was a directory. This test ensures we # no longer crash, but does not ob wise validate the behaviorHsegment = 'X' * 27path = os. .join(*[1u] * 10)-_cases = [ # overflow with absolute src)('\\' + o#, i)),$MdRrelativRE,TKPwhen >ingb[:180]H N]0for@!, !in:%:try`os.symB(srcEc" except FileNotFoundErrorLIpassrNelse'jos.remove( /OS$ a# Also bytes, sinc@at iPseparAcode.>pos.fsen>J ), X` @unitx.skipUnless(sys.platform == "win32", "W specifics") class JunctionTests(^RCase)>j&3 '`_targeX@dirname(0absY(__file__)) Bdef setUp(selfuN`assert8@.exi%.v48{tearDown~/ifz #-rmdir delegates tohqdows' R\DWbwhich $s points safelyq st_create_Q-_winapi.C'&S%lfty6Truy7Zisdir+jQs arerecognized ases,FFals"isze @ un%_Hnction(self.junction_target, self.3)  assertTrue(os.path.exists(6%) 8os.unlink#!:YOFalsZ @support.skip_unless_symf class NonLocalS Teunittest.bCase):def setUp%):Er""" Create this structureB%Ebase- \___ some_dirPos.makedirs('=//'@tearDownshutil.rmtree@ 7 stzpectory_P_nonl KCThe K  should resolve relative to the [U, not"current dir.w5QThen,D S7 ->dir and ensur"at]+p$isod as arIn issue13772, it was discovered thaQ dete" failed ifq .M specifie9 1Eq, whicha defect infimplementa.=dsrc = Cjoin1, '[-'3os.( dir', src$Uaisdir("" kFSEncodingW/s(f]st_nohPEqual^0fseXe(b'abc\xff'), >qdecode(=Pu0141?identity## #fsSx)) == x`for fnP('uni\|0, 'n\xe9', 'ascii'k#6try|rbytesfn{&fn&except UuneErrorQwcontinu" 0), w aDevicel hnbad_fdf`Returne when an fd doesn't actually qQIsNon@d_Aing(123456)W@AU@risatty(0)k(sys.platform.startswith('win') o0(ha?!r(ce, 'nl_langinfo'S #CODESET'))),&J' require1ttyeither Windows or g(P)t (self): encoding = os.device_@(0) %self.assertIsNotNone()'True(codecs.lookup0 ) class PidTests(unittest.aCase):}@skipUnless(hasattr(os, 'getppid'), "B` needs"@def _(fp = subprocess.Popen([sys.executable, '-c',4'import os; print(os.vO))']A xstdout=2IPEr , _ = p.communicate($ # We are the parent of our `Equal(g$),Kaid()) 4L|waitpidLargs = > 'pass']J# Add an implicit for PyUniF_FSConverter().<2pid`spawnvjP_NOWAIT, FakePath(`[0]), &Pstatu4os._pid, 53, (*S:pcreate_9, *, with_env=False, use_bytes@exitR = 17Kfilenamepu.TESTFN1>addCleanup(su'unlink, BUeif notRsys; 5it(%s)' % tJelseL(nv = dic7venviront"# C4unique keyY#K0key tr(uuid.4!)Aenv[ @key]3 Sa# readQ@variP from  to check that it exists2(3dr; magicPK[%r]O K!% IZ.key,n*c , "w") as fprfp.writ R&if \DQos.fsEAe(a)Aa inHe{60k):~Fv(;N@k, vaO.items()}ARretur@requires_os_func('k"l'lWr=FRos.P_B`[0], * 8SI ires_os_func ('spawnle') def test_q(self): pargs = .create_(with_env=TrueK/exitcode = os.Tos.P_WAIT, =`[0], * ,Y6envCkassertEqual(T-c!) @requires_os_funcpp/p(96/pe/pe@vvuv74vv@vIXvX3vX?pWAvWI VonowaitV7pidQ+NObresult7vpid(pid, 0$ w5#7pid)@tatu!!1]u if hasattr(os, 'WIFEXITED')m,!(sa)r 2@os.W]dSTATUS5<FelseMRx B_ << 8 kf_bytes # Test bytes handling in parse_arglist and1env(#28114) args = self.creat>s(with_env=True, use_n?exitcode = os.spawnve(os.P_WAIT, `2[0] ,h6envBzassertEqual(S-b!) @requires_os_func('v"l'Sdef test_0_no(f!):BD"1.Raises(ValueError,l IP_NOG4O, '' eeMeO, {}L"''PvvLv/()K/[]K6O('',8?''] vvMvM"()MP/[]P;S;3[''B_pinvalid!, /"[sys.executable, '-c', 'pass']M# null characterthe environment variEQ name:bnewenv@.f.copy(#["FRUIT\0VEGETABLE"] = "cabbage"R6trycRk{vexcept  ZxJelsec 3127B?le value   newenv = os.environ.copy() #["FRUIT"] = "orange\0VEGETABLE=cabbage"6Etry: Gexitcode = spawn(os.P_WAIT, args[0] ", rexcept ValueErrorZEpasskJelseself.assertEqual(u, 127) ;0# e  character in the ment variable name;Gr=ORANGEN_lemon:v;@fileLupport.TESTFN"ddCleanup(s'unlink, B1with open(, "w") as fpfp.write('im~ sys, os\n'0'if.sgetenv(5) !=:BLqraise A1ion' = [sys.executv]|uL g0e@requires_os_func(' #vedef test__invalid_ja)!._.&3os.=u pv/pew):pe) # The introduction of this TestCase caused at least two different e s on # *nix buildbots. Tearily skipYato let, move along. @unit1.50("S;due to platform/d ceV *NIX+")QUnless(hasattr(os, 'getlogin'), "{c needs@") class L)%s(- X(USuser_N5os.'X1#NoElen(:0), priority') and 6set,c".KA%ProgramPx /1"""!B forstpriority() and os.setpriority().""" def test_set_get_%bself):&*`base =KgKos.PRIO_PROCESS, Qid())b< 5 !, i6+ 1?Etry:LP1new%D"ifj`>= 19 &V< r2raise unit2.SkipTest("unable to reliablyT t) "O"at current nice level of %s" %FNelse.assertEqual(ckfinallg xm xcept OSError as err if.errno != no.EACCES. class SendfileServer(asyncore.dispatcher, threading.T FTHandl;Ahat.DT_chat){E__init__(wz, conn)< E.6 )N.in_buffer = [] closed = False push(b"220 vy\r\n")h_  qdata = recv(4096.append(9 kghreturn b''.join# I* 6OTrue eYlwaddress f # +reate_socket(.AF_INET, SOCK_STREAMj?Tbind(7listen(52Rhost,Dportj0get name()[:2Tr_instancN6Non%`_activ w_lock =SLock(# --- public API@property|runningpB4\start2dB notYi#KY_flagfEvent(b &nM@.wai@!op): assert self.running _active = Falseqjoin() def wait(7!):I# for handler connection to be closed, then stop u serverIwhile not getattrj.U_instance, "O"",time.sleep(0.001)a.~# --- internals1run}[=-;Tru,__flag.set(s <and asyncore.socket_mapQ2_lock.acquire\(IPloop(Aout=, count=2ZhreleasZViD_all2m_accep, addr =v(Er.HC(Hy/_-ecuR/cread ==writablereturn 0*PBerroraise @unittest.skipUnless(hasos, 'sendfile'), "* needs os.()") class TestS2(\bCase): DATA = b"12345abcde" * 16024 # 160 KiB SUPPORT_HEADERS_TRAILERS =zsys.platform.startswith("linux") \JMJsolarisL3Runos"[!re!s_headers_trailers = ? ,'W W[support'@amethodG0`setUpCG(cls:pcls.keyG0.thing_setupfpcreate_?(u.TESTFN, H tearDownP~cleanup(*[2keyb,kunlink Y4 = S (PHOST, 0)y<X`clientMT[&.I.WRhost, ho(b # hronize by1ingP"220 y" responp\recv(1024Pockno -)nolf.file = op en(support.TESTFN, 'rb') self.fileno = 1() *def tearDown(%!):E/{.close(\mclient"ifmserver.runningVZ!Lstop[v = None@send_wrapper, sock, , offset, nbytes, headers=[], trail """A higher level ^ representing how an application is+sed to use 5().$5""" zwhile 1:try+O SUPPORT_HEADERS_TRAILERS26return os.&,DJ-Oelse0 Yexcept OSError as errf if@.err= no.ECONNRESET2# disconnected]raise)elqAin ({.EAGAIN,GBUSYpt# we have8Qretry:] datap5 couxN0st_p_whole_7H# normal:|Ptotal;Ut = 0r }u = 4096)F0< lGDATAoy .2no,o  HL~nt == 0 UbreakL +?)nt;assertTrue(#<= ,bEqual(w&, d .&,Pg5Qshutdocket.SHUT_RDWR/W.waithandler_instance.get_(7,$) 40 L5$teat_certain_cQstartaUc at a :a ~ `+ =U // 2<#mu(-hSs = 4096  while total_sent < must 0d: " = self.sendfile_wrapper(bockno,# offset, nbytes)S2if V:= 0muYbreak0L +)nttassertTrue(w%<=L)client.shutdown(socket.SHUT_RDWR/kclose(server.waitPdata L"handler_instance.get_(7expected;DATA[len) // 2:]fEqual() , ;T)4()3/%, ] def test__overflow)# specify an ,0 > RQ sizeL"=e+ 4096'6try\8E= os.Ko e,S$except OSError as ed# Solaris can raise EINVAL if=length, ignore.if e.errno != .I q,g>;els 6, 0"fKb'')asinvalidi`BwithMR#s()*cm^,,-1( 2cm.<2ion, keywords2# K arguments should be supported Aout==0, count=?,;Z**{'in':7}7 lf.SUPPORT_HEADERS_TRAILERSM!headers=(), trail sflags=0Pc# --- -% /+s>@requires_(_Q  ZA = 03c m0@ |F=[b"x" * 512] offset = 4096  nbytes = 4096  while 1:sent = self.sendfile_wrapper(bockno,#9no,CGoffset, )D2if := 0ZYbreak0atotal_3+)ntk  expected_data = b"x" * 512 +EDATA/assertEqual(wi, len(P)9client.close(server.wait>"handler_instance.get70Phash(M1),  @requires_headers_trailersdef test)pTESTFN2>rupport.a + "2"D3pabcdef" ddCleanup(sLunlink, T2@pcreate_W( , e)Zwith open''rb') as f%os#.s f.Zrno(), 0kI=[b"1234"]p   $wJ(;z,LB, b"D  P@unit!.skipUnless(hasattr(os, 'SF_NODISKIO')- 'F needs os.7(Qflags?try!0,m=except OSErrorT:errif err.errno not in (p.EBUSY,no.EAGAINraise s_extended_isibutes(<!ifgP"setx*"$Xeturn Fal_ D9u, "xb", 0Cp CTY7(fpMpb"user.""Z8 ^ i rgfinall HW2F0TrufGw="n-broken   W") # Kernels < 2.6.39 don't res  3. @<.es_linux_ver&sion(2, 6, 39) class ExtendedAttributeTests(unittest.Case): def _check_xattrs_str(self, s, get5, s cremove4lis"**kwargs):Z^fn = support.TESTFNd.addCleanup('unlink, fn),create_file(Rwith J ssertRaises(OSError) as cm(fn, s("user.E"), b] Equal(cm.exception.errno, .ENODATA)ZlBinitX5 = +`IsInstance(9,8T?b""'et[`  Iset(1), DS8 xbwX, b""D\ hello", os.XATTR_REPLACEQes  8bye_CREAT_EXISTD2++b"~ E>)fo? 2oAlf.aH QA L&U7a"*1024 V , @manyWortedY{}".format(i) for i in range(100)ufor thing in mgany: setxattr(fn, thing, b"x", **kwargs)0 self.assertEqual(set(lisB@)), Qinit_W1) |qmany)) Kdef _check$ s(Y0, *nx .3_str(str6csupport.unlink(cTESTFN(]os.fsencodee,test_simple) S(os.gT, os. aremove^, 5os._lpatha, follow_sym|s=False"fd'(#with open$"rb") as fps)`returnbZfp.fileno()ae_ owb", 0( ;Y W[ ( %, Z) @unit.skipUnless(has os, 'get_terminal_size'), "requires3 "") class Term3eTests(kCCase/N_does_not_cras@"""C,M if 2() s a meaningful value.oThere's no easy able way to actually P the 0 of , so let's1Uif itAsomeK` sensihinstead.K5""" ,tr_ize =e(except OSErroreif sys.platform == "win32" or e.errno in ( .EINVAL, SNOTTYE# Under K a genericcan be thrown5theEhandle cannot1retrieved-C("faileddquery "!lraise self.assertGreaterEqual(size.columns, 0) 1 Bline/0def test_stty_match(@!):R"""Check if & returns the same results 3'actually` s stdin, so get_terminal_ is invoked onFdin explicitly. Isucceeded,nR(hould work too._5""" 6try= subprocess.c_output(['@', ')']).decode().split except (FileNotFoundError,^rCalledPlP4Qssion!.skipTest("Ucation failed"expected = (intOe[1]), 0])) # reversFrder 5m = os.q(sys.____.fileno())!OSZ as eys.platform == "win32" or e.errno in ( .EINVAL, [NOTTY59# Under K a generic can be thrown=the# handle cannot1retrieved-  to quer0W sizeFrais~I", ) class`s(unit.CCase\setUpDsStr(str-8pasabytes_ames = []0uni0$ upport.TESTFN_UNENCODABLE/dJNone"s>?els?3.append(~/ N34/DE enO>?Ros.fs(E ;d-Ddarray(78memoryview9}l!+   "@_ose Afunc&,chdir,),)mod, 0o777),  (self.filenames, os.lstat,), ( )Aopen2O_RDONLY4_rmdir]hunlinkR] if sys.platform == "win32":$funcs.extend((jbytes_+r7, b"dst"; _place<unicodeyx <z=!@list %))7Oelse` Zh gT / 4if hasattr(os, "chown")1appCV6o, 0, 0\l']7^truncate`9 chflags^8] l&^9_ ochroot]7,  #>tryif isinstance(J, (str, bytes)_32')Qwith  assertWarnsRegex(Deprecationing, 'should be'Yexcept OSError as err/tIs(err.", =@str(x +hUd DejslEpass@Jfail("No lion thrown by {}".$at class CPUCountTests(unittest.CCasef@def `_cpu_c04`cpus =#1if !is not Non=4IsI4V, intJl-Greater(*0(-6@skip1("CIdetermine the number ofSs") *FDInheri/D/get_set_i: class PathTConverterTests(unittest.8Case): # tuples of (function name, allows fd arguments, additional 3 toMB, cleanup )"Qs = [ ('stat', True, (), None),"l#OFals$access', %os.F_OK,Qhchflag.0(l)Gopen|Ngetattr(os, 'close'!] @def _path_t_converter(self+str_file = support.TESTFNK&bif os.$b= 'nt'bytes_fsn3 = W~MOelse?0 .encode('ascii'wl{FakePath(T4@fd =^(. ), O_WRONLY|os.O_CREATEER.addC({unlink,G81os.R, fd)6intM# q8for_fd, extra_args[q_fn in X Bwith!0sub(=T:try?Xfn = A#except AttributeErrorRcontinueDAHin (!,!, U)C \+02if vs{) p,`=eMresult = fn(+6, *+$ifp_s not ?B_fn(y assertRaisesRegex(12Typ, 'should be3ing'6fn(O p"if?_fdPGN/Mfaila] YJVr"=vr,  'os.PathLike'): "8fn(fd, *extra_args) @unittest.skipUnless(hasattr(os, 'get_blocking'),`'needs os./`() andsE()') class BXeTests(CCase@def S(self@fd =fopen(__file__,O_RDONLY); .addCleanup(os.close, fd&ssertEqual' fd), True) [9os.o_FalseX5Y | ~pExportsn}los_all{y@In(''z_./__*Kwalk*Scandircheck_no_resource_warning = sup.$W_setUpBpathV P.real (]kTESTFN`bytes_(;fsencodeb. 1Yrmtree, Z 3Pos.mk%acreateo, name="W.txt"1W)Gelf.if isinstance(?!, f) elseux](W`.join( 8, b'python')treturn $wentriess = dict(( y.!, f2for"0 in:sk;anasortednies.keys())s86iesKq_stat_eob , 102, h_field(if 7Gtat1.pif not +.startswith("st_6/continue !ifHsA`dev", K3ino _nlinkZ.+0get(' 7!2,7gn7  } 96y =, is_dir, is_file, is_symlink): self.assertIsInstance(entry, os.DirE )2REqual-p.name, +Apath] a.join(CDinode(),sos.stat\dfollows=False).st_ino) M_? = I_s_dir S.S_ISDIR[p_mode)d?fil e?REGe%4 0os.a0.is_j)UlV/, %zim=! {' {"'_ev +!os == 'nt' and not>qdef test_attributese` = has$`(os, ''{0 = support.can?(k0dir  V"dir"ZPos.mk$:Lpcreate_ ("G.txtJ0if :try0os.*(Eb"(smH except PermissionError as euskipTest('): %s' % e\3if m G(.B"rtarget_;ectory=Truy4z+7+ps = ['dir', '&%']$9.append(; names.extend(('symlink_dir', file.txt')) entries = self.get_(names) +Cy = ['_]@QcheckB y((1y, ', True, Fals[ `,_le0if :#_S- 5 &3 t ? 8 |Ddef f y(R , j) Dpathabytes_if isinstance!, b) else*list(os.scandir('.assertEqual(lenwies), 18T0 F,.areturnKybacreate~DS<%='+`/B"=wVyP.base0(V)test_currentRector0oldCP = osFcwd(6try Pos.cht# call ) without parameter: it must  the contentI"ofB dir 'XQdict(*yby) for0 inqyasortedRies.keys()),9 @[os.]pofinall\ZAreprrr N?), "" fs_protocol72os.\n0y),lQ.joinhV, B_<1_fsencode('sTmname=bytes_filesname) fspath = os. (bytes_entry(self.assertIsInstance(2!, 3-TEqual(v}0os.a.join(qencode(x!),eQ_file!) Odef test_removed_dir6!): d@ eYs, 'dir'O/Pos.mkG.1 = :2get#(>9Vos.rm=# On POSIX, is ) result depends if scan>) filled d_type or notN if == 'nt'QTrue(.x(GFals)h/()*xsymlink- Raises(FileNotFoundError, 7nod# don't fail2Vstat( sfollow_!s=.OelseKtGreaterNV(), 0?mT =*/,  5ceQos.un36W"T&H t dbroken  if= support.ca* breturnskipTest('cannot  symbolic 8RA0M ("V.txt" 3os.(;, g3, ">WX4iesget_entries(['file.txt', 'symlinkC]) entry = Jies[('Pos.un@(filename) self.assertGreater(Oy.inode(), 0q-TFalse+s_dir())()) # broken returns Z ssfollow_C!s=#?7Truq Raises(FileNotFoundError,fy.stat,# don't fail)(def test_bytes(%):E!.c_x"F"Bpath@ = os.fsenc?ies = list(os.scan(FEqual(lenries), 1 b"0]O-.D, b''2,s[ 0os..Q.join`', n)M Q_like2for cls in array, memoryviewz =75Wwith Warns(Deprecation7ing7u3i7j  W1 6G:6dIs(typP!),s33P@unit .skipUnless 0dirMupports_fdR'fd s* DrequiredAthis}.q/fd In7,qjqWexpected_C[&]&$ifD.can-(g(EmQ'.append('+"fdj9opeTos.O_RDONLY)  Rtry:  with os.scandir(fd) as it'-entries = list(it)J1nam[( y.Q for 1 in Iies]6 self.assertEqual(sorted(?s), expected_< $,  a.path, [$ 9Pos.fs8(C?ntr?5.is_symlink(AP == '' if@stat|upports_dir_fd4t =8", 5>=fdj8 s,3so, follows=FalseG(, kfinall"os.close def test_empty_)T Raises(FileNotFoundErrorw[, '')]consume_iterator_twice(Z icreate_file("V.txt"$CJz |K51len) ie1 U# check than ing the  doesn't r4 exceptionvJ2U2), 021badM_typh80objL[1.234, {}, []] OTypeg'F-unicode-escape'), 314), $(chr(0x200), ValueError), ] class TestFailingBool:<def __bool__(self)Wraise RuntimOKBIter3KOiterK00fil0char(arg}return ord! > `"d") 6Omap_374+1)pBuiltin(unittest.CCaseu# Helper to check picklability-_ e6, it, seq, protoTFitorg = itD2d =]e.dumps(=8$&it%loads(d).assertEqual(type(j3), )0list(it)%) Y#P the ator after dropping one from 2try 1nex|uexcept StopNZation31@? C[1:]nq_import___('sys'r?ostring_name=W\, level=0"R1s(I&, p, 'spam?2Typ =1, 2, 3, 4|  >'s!",  v# embedded null %Uacter;ModuleNotFound \\x00' o# floa ..8 3.  $,+O# st wabs, 'aJ # w _\zFalse),(?othR b *f, None0AbsClass(object):' def __abs__(self):*return -5).assertEqual(abs(AbsClass()), -5) /`test_allaGll([2, 4, 6]), True)G/CNone2OFals3 Raises(RuntimeError, all, rTestFailingBool()P{HDoIter()@9Typ010)# Non-iterable K GRK_ argsFA, []U# Too manyL # Empty ?torM70, ^a# Short-circuitLS = [50, 60]Fx > 42 for x in S}L4P% /nyBny([9 4,Ne6U "Cny, ~ %KD%=%4!ny %;%% %M1% % ?, 3) ?ny()o10, 20P$ )Oscii+&''), '\'\''Y,0+0(?'()*[?'[]* {}}'{}*aa.append(aaLh[[...]{Q{} a[0]c = a self.assertEqual(ascii(a), '{0: {...}}')1# Advanced checks for unicode strings.Qdef _(_uni(s):~s), repr(s)yG?"'"''"0O'"\'/\0wr\n\t .# Unprintable non-ASCII character}G\x85F _u1fffjU00012!# Lone surrogatesOud80,udTIssue #9804:\ should be joined eveng# wide  (UCS-2 builds).*!'\d121'), "'\# All togetherV =40\"\n\r\t abcd|"éHJb\uD800D121xxx."C 5s),#r"""'\'\x00lB\xe9^nna'""") Ptest_neg(x = -sys.maxsize-13*True(isinstw(x, int5,G-x, W,+1@call Jv(?lenqeFalse((?"a"( O0,lambda x, y: x + y6 __gtins__1def f(): pasW#f);class C1RCmethLY'C1vc = C1( c.k;* c@# __u__ is looked up on the Q, notk%c.?e= None 6 @:?: 0JFdel N=' C2(object c222/c2@ # AzL3(C2 c33() self."assertTrue(callable(c3)) def test_chr(self):.?`Equal($32), ' ')' 65'A' 97'a' @0xff)O\xff,Raises(ValueError, chr, 1<<24 sys.maxunicode), str('\\U0010ffff'.en4("ascii"G-escape')}7Typ*z0x0000FFFF), ""81<881818E888F80p881p8" /-1/517 (Overflow;v)H]2**324/mp4s not hasattr(builtins, "cmp"lompileSc'print(1)\n', 'Gexecbom = b'\xef\xbb\xbf'H&?+ bO1source='pass', filename='?', mode=':dont_inherit=0;dtmp', Z0I7valI|s V1 memoryview(b"text"@", " H 8#, #, i#420badAuU single', 7ZJ 'f! !*UC j/y[(Zc"\xe5"^xec') 2 self.assertRaises(ValueError, compile, chr(0), 'f', 'exec') Dstr('a = 1'Jebad') J # test the optimize argument&codestr = '''def f():D"""doc"""debug_enabled = FalseRif __#_F86Tru7:try.E ]except Aa1ionX 8return (^, f.__doc__, ,yOelseMN5'''V Nv s = [(-1 nR!%),_^B(0, T'doc' 0"1,c#, 1323ENone 2]0forvval, *expected in iboth direct-ation anduvia ASTl1objK.append((2pstr, "<(P>", " ",/=optval)%Qtree = ast.parseJ &_ w>tORBZ Dn){}J, nsrv = ns['f'](Equal(rv, tuple()wM_delattr(<Osys.spam,Pys, ' 4TypR: }iy#X(wrong number of p`ir, 42t?\) - local scop0_vab1gEIn('%!',P_fmodule ACexit<?sys?_with_invalid__dict__Tclass Foo(types.Mt;E = 8f oo("foo"UQ=, fLBIn("strip"<G(strk0Not,y__mro__.6objkkobject__init__:  self.x = 7 _y = 8Uz = 9f = Foo()@assertIn("y", dir(f)) $#obj_no__dict__BQclassVobject):9__slots__ = []__repr__n__with# (an ugly trick to cause getattr(f, "__E ")!Ofail#JW-"def __init__( 3$.bar = "wow"9!No<TX?bara `using Xr?dirreturn ["kan", "ga7roo-% RTrue(S == [BOI__tuple0("bc&a"aQres =HsInstance(res, list)R9v]not_sequencA Raises(TypeErrorp=, ftraceback:try]rMa IndexM&jexcept-jEqual(lenAsys.exc_info()[2])), 4test that d has aPesorted([].E(^$[]e_b|_divmod '12, 7), (1, 5)'0-1_-2, 221-c2-3e4@1, -maxsize-61T+1, 0.for num, denom, exp_result in [ (3.25, 1.0, 0, 0.25)),F ((-C -4J?0.7DC-D-E  (-3.25, -1.0, (3-0.25))]:  result = divmod(num, denom)(self.assertAlmostEqual(?[0], exp_=1=E1]) {wRaises(TypeError,.def test_eval(8)%'1+1'), 2)k 1+1\n, globals = {'a': 1, 'b': 2}4loc"00, 'c': 300&uCa', d_) , 11", {)8bi8?200rc:3:&/bom = b'\xef\xbb\xbf'jD4O+ b'%f"\xe5"2), g+O, ()/ cSyntax\, bom[:2]  vclass X%__getitem__'W, key,(rpR Valupk%", "foo", {}, X=~general# Tests that ) mappings can be used for the argument=M"_Q interface versus possible calls fromA()."K ifd@ == ) GKreturn 121Key AkeysUlist('xyz' M&M(n4g =nWP0, m_>2Nam>'m;dPdir(){-', ;t?g514i3~A~CNon- PEpassA, 'a', g, m)3 # Verify that dict subclasses work as well30 D(-%):Q def __getitem__(self, key(, ifz == 'a'Greturn 12e.q 3Akeysilist('xyz')"ud = D()P. rtEqual(eval('a', g, d), 12.Raises(NameError, :D, 'b;d Tdir()-', qxglobals?g5;loc4d;' stores (used byf compsi2('[2() for i in (2,3)] 0collections.UserDict()SpreadSheeto"Sample applicaI showing nested, calculated lookups."_cells = {}{>__s,OmuladRt[key] =-\oQ _%,  , <s; `s['a1'5'5's2Ka1*6372*79elfUE3'], 210ur() catches a non- # SF bug #1004669%C brA Key(&_$NA1 # EPto beA but's no longer an eIdFm;TypmD5, C-test_exec-g#`'z = 1if '__builtins__'gXJl g[']g, {'z': 1} +X&2} l#with check_warnings(9t.filter("ignore", " statement",aVmodule="" exec('global a; a = 1; b = 2', g, l) if '__builtins__' in g: 'jdel g[']"BlBlBself.assertEqual(( , ({'a': 1}, {'b': 2})) zdef test_exec_globals(J){code = compile("print('Hello World!')", "I"S# no  function{iRaisesRegex(NameError, "name 's' is not defined",IM , X: {}} must be a mapping typeo C(Typ% C123}:9d_class__A) A: passw u xuOfouns2!frozendict_e`(Excep' =(B 2__setitem__, key, value/Wr "readonly"-sif isinstance(_*,Zs.ModuleG z\' = J0.__&__FelseNE dr['super9a']=2; (e( I8 \p@spacC'({, 0x=1NvuredirectedFsavestdout = sys.  = None # Whatever that canVlush(:try^# Used to HaSystem!(' return witheV set'[7('a.  ~!9kfinall VOfilter(self): $ self.assertEqual(list(filter(lambda c: 'a' <= c'z', 'Hello World')), 8' _c None, [1, 'h=', [], [3], '', P9, 0]f )%?9])jx: x > 0u@-3, ]5, 2`9 USquares(10)4X16, 25, 36, 49, 64, 81 O%2, f5[ Wdef identity(item):return 14m/5)_Raises(TypeError, B-class BadSeq(objectP__get0__(({, index*"if*<4%42rR Valu!q% =,)badfunc(OpasssCCrN, range(5nG# test bltinmodule.c::ftuple(U(1, 22 Q>=3, Gb, 3, 4M Mp#42Na_q_pickle4pfor proto in9).HIGHEST_PROTOCOL + 19(Cf1 =_char, "abcde"X323check_iter"f1rR(f2),!) |getattrQUTrue('ys, 'stdout') is sys.>K,:?, 16#g, "foo9sk Attribut*, @chr(maxunicode##  surrogates are not encodable to the defauling (utf8"1, "\uDAD1\uD51E"?has'  chasattr, sys, 1)# self.assertRaises(TypeError, hasattr).Equal(False)(sys, chr .maxunicode))) D# Check thatb propagates all exceptions outside ofBAttribut.class A:def __get0__(z, what))-r SystemExitJ6 )%, A(), "b"4Bk BValu%B:|test_hashFNone$!1)bOh(1)+'.0-Go'spam'B &rb6K(0,1,2,3cf(): passVh, []]/&{}/# Bug 1536021: Allowh to return long object)X)Uo2**100Ptype(J(X())), int~ Z(&+|@Z(42} ,exV{hex(16), '0x10> Bex(-+-,@ex, ,id:id(.Fid(1V).0Y?id(Cid([Bid({@ : 1, 'eggs': 2, 'ham': 3}j&# Test input() later, alphabetized as if it were raw_. Liter;1+@, 423lists = [("1", "2"), [ ], "12"]@for l in 8 @i = &(l_tR`next(iR1O+ 2+StopIteration, f3, iVsinstanceiC ";D(C%E: pass uc = C()Wd = DWe = Eself.assertTrue(isinstance(c, C)J*d* Gnot Xe.Oc, D \'foo', E2Raises(TypeError,Q, E, ?; !) odef test_issubclass(5!):& C 7G D(C6%EG .D C* XCl7Ve; v 1'(xWreturn pow(x, 0.5n, x)), [[16, 4], [81] [4.0, 2.0%9 O3.0], y: x+y, [1,3,2`N,1,4!106vaA{plus(*vBaccu = 0+Sfor i in v: !9+ i({_ 3, 7,X b0, [?, 2m+4, 3+9, 7+2A #sO1, 0~!+1_7+2+0(int, Squares(1030,  , P25, 39, 64, 81~BMax(a, bCif a is None;$bOif b3a3Hm6Max&3) 2#k?map*', hF, 42;class BadSeqO__iter__Vr-R Valu-'Qyield@ , +, ,6())}badfunckRuntim']5}z|_pickle!Pproto).HIGHEST_PROTOCOL + 1Am1 =map_char, "Is thie real life?"n,m29 "Is this the real life?") self.check_iter_pickle(m1, list(m2), proto) 9def test_max(>!):T.assertEqual($'123123'), '3'~-1, 2, 3)W (+#, )5[,5]5k 5 .0-/.0 .0Z )-Raises(TypeError, max*O, 42. GValuYF, ()/class BadSeq__getitem__ w, index*r k%,~6for stmt in (i"qkey=int)", # no args6default=None)",! '^# require container -Lm&, *1n# singleP not OableF2IYstonep# wrongOword<7P, abc ^# two many?Y815@ #7qfunc isMcall Q:tryQPexec(, globals2uexcept HD:pasNelse'Afailpf A(1,)z=neg), 1)+ # one elemHGIHG Hs8), 1), 31o# zeroP$, 2rq39 d3`data = [random.range(200)AiU100)]ykeys = dict(( , ?Fe(50)) for elem in data) f = keys.__getitem__self.assertEqual(max(@,4E=f),+Osorted(reversed7)8a[-1]) =def test_min(q!):J in('123123'), '1'-1, 2, 3), 1* (+#, )5[,5]5 5".0-/.01)#.0a [Raises(TypeError, min*O, 42. GValuYF, ()/class BadSeq w, index*r ko%,~6for stmt(i"key=int)", # no args6default=None)")W '^# require container -m d*1n# single not iterableF2IYstonep# wrong!Oword<7P, abc ^# two many?Y815@ #7qfunc isMcall Q:tryQPexec(, globals2uexcept HD:pasNelse'Afailp~cin((1,F1neg@q# one e a H2I 2)IHG Hs]3), ,!, 31o# zeroP1 $% N'3 =21 = [random.randrange(200) for i in range(100)] keys = dict((elem,'dom.rand250)) for IUdata)C@f = G.__getitem__self.assertEqual(min(@,4E=f),+isorted.Q[0]) 2def test_next(g!):@it = iter(&2)+ Aoit), 0&1&Raises(StopIteration, \O, it35DV(it, 42)`class w(object 7 __,__6 preturn )R<}< t 4Kgen( uyield 1' <' ?), 6 Y-oc $, '0o144'p,---.yTypeError, oct, ()`write_Lfilel# NB the first 4 lines are also used to input, belowfp = open(TESTFN, 'wddCleanup(unlink, -vwith fp<1fp.w('1+1\nW The quick brown fox jumps overlazy dogD.`Dear John$PXXX'* 3YYY !<;.+rrJRpfp.read_(4), b6 5y`^ xQ5 ?, ':@(3006"107 # embedded null bytes and characters self.assertRaises(ValueError, open, 'a\x00b')6b78@unittest.skipIf(sys.flags.utf8_mode, "utf-8 is enabled"{@def B_open_default_encoding(!):mold_environ = dict(os.Q'6try4# try to get a user preferred n different than the curNflocale9to check8tc ()fsD 6 K}`and no{e; ; for key in ('LC_ALL', 'LANGC_CTYPE'?$if:> 1&Fdel $i[key] p.write_Vfile(CB_# =E.getj(FalseIBfp =\TESTFN, 'wl~with fpEqual(fp.l, kfinallUk.clearwupdate()F non_inherit# \4obj __&__jileobjY69getnN@obj.]no()),rdXWord(' '), 32'A'/65' a'/97' @\x80*?128+ ff+3255<b/b'/b'/b',1chrmaxunicode)), K5TypJord, 42C r0x10FFFFl fFa"\U0006d"), 0x 81.881818E88F8F8 "\U00100000"), 0x00103)  self.assertEqual(ord("\U*(1"818FFFFE88F81F) def test_pow(!): $o0,0), &1&1L 1,L12M12,1?024 42,2*/*1/3/4M -!-2/-2 -2,2), -2,3), -8SSAlmos"0.Z.~.0.1\!1./1.2]&2.&2.#.8,8>/ b-//-20F/Nfor x in 2, 2.0Tyl10, 10#z#0%0'+ if isinstance(x, float) or \O)1y1z1 ^ 9Raises(TypeError, pow, x, y, zR?Oelse] Vo, 24.0%p-1, 0.5j e1 1/ 0.5 + 0.8660254037844386jz IValu Q_-2, 36 1,\5 v_input`write_Vfile(fp = open(TESTFN, 'r')# savestdin = sys. 6out # Eats the echo0Etry: bS_ = fpO= BitBucket()%elf.assertEqual(input(), "1+1"-'The quick brown fox jumps overlazy dog.'V 'testing\n'), 'Dear John') # SF 1535165: don't segfault on closed x;#"must be a regular file for triggeringxz=#= ?out$1in.|Raises(ValueError,  tf = io.StIO("NULL\09Typ@, 42 f['whitespace'p q: r ?EOFS7del  KkRuntim{'promptX/inW3ofinall p8 %fp # ~_int(): see2.py ests of built-in function 6.2def;repr(self) }%'G\'\'S+00' ()(/()) [])/[]) {})'{})aa = []>a.append(aaKh[[...]yP&{}Pu[0] = aM{0: {...}1Oound& 0.`D uetype(r/)t +1ZZU1!, ,0_ 0C< e21-!, Ylf.assertEqual(round(-10.0), # self.assertEqu.06F>"e2l / o0.1), Y1*O1.0)T 1U,1= --|b-6 o0.9), 9* 93-*)508.0DtypeO6), float) 8&0)7r 616# Check even / odd ing behaviour.5.5), 6V6(-Q-R-S*r on ints!sW_8), 8-'-( ?intV.!-8o ),3e0:# test new kwargTnumber=-ndigits=-Raises(TypeError,#rgenericdelegation for realclass TestR:Cadef __0__(")!%return 23U/NoWFpass-W.w()), 232, 1, 2, 3 5t'()qt = TestNoRoundC()  t.__round__ = lambda *args: )self.assertRaises(TypeError, B6, tX/Q, 0) b+# Some versions of glibc for alpha have a bug that affects?float -> integering (floceil, rint)]? values in the range [2**52, 3). See:0+ http://sources.redhat.com/bugzilla/show_bug.cgi?id=5350@ We skip this test on Linux/if it would fail.9l"_"= (platform.system().startswith('Oa') and=={machine>e"')`5=l(5e15+1) != jP@unit.8If(Land P,7"DQ will!;  ure is probably due to a "FSbuggyt function"1def`large()# Issue #1869:tAral As shremain unchQzNLaEqual(@AA-1),?"-1o0.,+\+\#+2^/+2`303Lbug_27936JbVerifyndigits=None meanssame as passPin noUument,x_[1234H?.56decimal.D#(',/').1fra43s.F (056, 100)]+0x, )#(xb3 Ctype,<8), ,))z|setattrxys, 'spam',  @sys.'&c,n4, 1gK>#str(): seeunicode.pyPbytes1"s.j>sum$1[]) %Qlist(7(2,8))), 27Y]iter(9:Squares(10i/85j(Squares(10))), 285) self.assertEqual(sum([[1], [2 3]]), [1, 2, 3]) ?Raises(TypeError, sumi*O, 42.['a', 'b?c'];(O, ''?b{b'c'], b=values = [bytearray(.8), Ob')]C", V C/') ;_{2:3}`3A*2, 0class BadSeq:def __getitem__(, index)*.rm VomK7g%,~'()Pempty um(([x] for x in range(10D1GF 4, [,test_type>%b''), ?123#No)4 $()# We don't want nvars(), so these are static methods@i@get_CG_f0(preturn (a@ 2@BuiltinTest.cyUa = 1Ub = 2~rCZw(objectLDictpTu{'a':2}k __dict__ = property(fget=getK]|zAset()d 1dir28sys5I aO, {}12;! 1?: 2?r3/<V.1zip/[(jc(4, 5, 6t/-4), (2, 53$E ^Plist(z@a, btRh[hC(2, 7\ self.assertEqual(list(zip(a, b)), t) class I: def __getitem__(self, i)&*if i < 0 or i > 2: raise IndexErrorZ4return i + 4cO.ass;I()/)&[]*?*[]-Ras(Type, zip, None]>GOpassRfa, G()T2iRuntima, TestFailingIterCv# Make sure$ doesn't try to allocate a billion elements for theKpresult F when one of its argu8csay how long it is.LA MemoryS0 isk@ mos_kely failFmode9hSequenceWithoutALength}J== 5AOelse;jY(), range(2**30 ?enumerate(+'5)R%) 1IjBadSeq9avariouLomatter 3, ''), '3'1# RLqs some  es!us ks. There'p# an old-style version, and a new9p[_new( A(object@e__initAx'+Ux = x~F$Hw R return str(self.x) + format_spec class DerivedFromA(A):#.Ypass 9Simple(object): (1'`2jdef __init__?, x'`I = xFHR_retur;&-2(k)A,} P2do_test(O# XassertEqual(9(A(3), '@' 3 }<0A(4>=B, '4 G (5L1abc5 J#C2(10Lidef'),GU a'10abc** es_new())$bempty_Wk(value # Z that## (x, '') ==)x)'#a, ""),Z)_< 8# builtin types,0mat/""/f17**13"/.0 3.1415e104& -'&-N( N4GNoneS# TypeError because _d"_ ps the wrong}dQ BadF)[ResulvQ .uE 1.0i]uRaises( ,!()D is not unicode orz": s .T really belelsewhere, but # 0re' good place to put them   x = object().__format__('') # self.assertTrue(x.startswith('T)ed?z ys.append( 0Che0#heLw1gotcorrespondsaeuser's s!enezs) != 2 # Something went wrong, tryasavEderrU# Beware of Linux&G@EIO "tslave i9 C5_output = bytearray  Ptry:  chunk = os.read(fd, 3000).except OSError: # Assume EIO.h]breakqif not y8child_output.extend(E os.close(fd@8 =  .decode("ascii", "ignore"B self.fail("got %d lines in pipe but expected 2,c was:\n%s"+ % (len(R)<) J# Wait until thezprocess completes1os.waitpid(pid, 0) breturndef check_input_tty( , prompt, terminal!, stdio_encoding=None)@sys.)Pn.isaTA) or5out>/~.skipTest("F@ andyout must be ttysPild(wU0# CAe handlers are accoun5for.9 ifx #in = io.TextIOWrapper(.detach(),`A i xFs='surrogateescape'~j$ 3 s='replacprint("tty =", iRr, file=D SF(,("/))41 = Arun_( V + b"\r\nwe did exercise@GNU dU pathnsassertIrq[0], {'  True', vFalse'}"ifd[0] !='5 handard IO3should have been aA_result = evalP[1]) iB) ->) roundtrip = S Jelse^^4in.)Pwhat O?MREqual`,x def test_input_tty(self): 0# Test input() functionality when wired to a tty (the code pathH%is different and invokes GNU readline if available).?q.check_"prompt", b"quux") 1def test+_non_asciiCV stdin/stdout encoding is usedq, %é\xe9", "utf-8@_uniO_errors+ handlerHR2no_N~_filenoIssue #24402: IfCoriginal term 0but#Cout.S)~# fails, do not F 9 descriptor@3child(wpipeqprint("$@.isa():", sys.,c=F_E,`= io.StringIO() # DoesqsupportG6no(D( captured(y.getvalue())As = Brun_g6\r"zexpected = ( .z True",$" ''"eassertSequenceEqual($, ) classSorted(unit .0Casl_basicdata = list(range(100)pcopy = '1[:]Qrandom.shuffle(&4>2, s,-8Not0)sE.reverse/,, key=lambda x: -x./=1}d_argument=9327: The first 3QpositW-only&[]Bwith=Raises(TypeE Y@iter=Ku# OtherPs areAwordhG"[]ONoneError):  sorted([], None)  def test_inputtypes(self):#s = 'abracad'/ = [list, tuple, str]#for T in ,UYelf.assertEqual(Cs), ST(s))3'.join(set # unique letters onlyystr, set, frozen dict.fromkeysBobaddecoratorq@dataThe quick Brown fox Jumped over lazy Dog'.split()^Raises(TypeErro  , k, lambda x,y: 0) class ShutdownTest(unit/.kCase):H|cleanup"# Issue #19255: builtins are still available at svcode = """if 1IeimportT422sysCI|__del__print("before"w # Check thaYexist2olen(()Rvgafter"8Wc = C# Make this module survive until4r and sy)ed@.herQsys.mRs[__name__3|"- # Create a reference loop so@needs to go# through a GC phase."5"""9 20599: Force ASCII encodingPet a c implemented'C,Notherwise0Pmay brloaded Y4 C.) is called,P3so 6") fails becaugacannotj0sedeNqstdout.(@ing.@ exa, on Windows8qthe OEMP pageR thes JePython rc, out, err = O!_p%_ok("-c",q PYTHONIOENCODING="ascii][62, "].Bde()Plines^HZrP_new_ 1A =] ('A', (), {}) self.assertEqual(A.__name__, 'A') /se*3.QmodulZd_ Pbases(object,)1!Is.-,*fx = A(Is(type(x), A"x.__clas5A) 5 B:+def ham(f)return 'ham%d' % (AAC = 'C', (B, int), {'spam': lambda5!: $%sF}CC * ._M4Is(- (51In(0', /odict__Q0Not-?ham,)OC(42>H?x, KCB9Is(K&h.D!),)/42 x.(, - to_bytes(2, 'little'), b'\x2a\x00'Ptest__nokwargsAwithRaises(TypeErrorL0('af}, x=5.N*?={}%) :A = type('C', (), {}XWwith URaises(ValueError):J$A.c = 'A\x00B'"I/ x-_udcdcz9?Typ?b'Adef test_(+\A'': 'B.C'B A mA=* k[0eT /('?b'Bn ?D.E8Y8 2, '}1 e!E2M4_dict= []aises(TypeErwror): type('A', (), s.MappingProxyT E{}))6with self.assertRaises()/Era None,), {}N1OboolN7int, strdef test_bad_slots(B 'h"'_V__': b'x'2 ^]5Y3X/42ZEox\x00y^_Value x', 'x': 02 a('__dict__i )nGtweakrefqt*Qzclass B_Epass".'B 02bP}) Pload_ s( 1er,$s, patternfrom doc+ import DocTestSuitePs.add((builtinszbreturnk if __name__ == "__main__"~@unit[.() """This is aC module for_pydoc""" __authorZ "Benjamin Peterson" __credits"`Nobodyrversionp1.2.3.42xyzX, Y and Z" /A"""HellopgoodbyeXu__init__(] """Wow, I have no function!;'nB(objectFNO_MEANING: = "eggs"8C8lsay_no2"noE*get_answer.R""" RO() Nt.!Wis_it_trueW elf.get_answer(s) """ return self.get_answer() def doc_func():2:PThis tion solves all of the world's problems>ahungerI@lack-aPython"wad},nopass """Basic testDq frozen module (source is in d/#A.c).b\# The 9 code contains a marshalled2j` # andrefore depends on8 format as well@bytej# #!@. IA3oses have been changen$n needs to be # updated. # %_importlib also90s tm1but because th8sre much mpcomplicc, it migh: unclear why y are failing. # InvalidI@datacould cae interpreter to # crash when __hello__ D sys @unitQ from@.sup -captured_stdout)2  util class TestFr(`.CCase*>x_(azname = ''1if  in.B 8del[1]B[with ()v2outED.assertEqual(out!value(), 'H!\n') if __A__ =rmain__'u,() # Mailcap fil"_mp; basedLRFC 1524 # ReferrIo by1C.py pcomment2 apion/frame; show %s; print="cat %s | lp"5 postscript; ps-to-terminal?\<> ?aose=idraw %sBx-dvi; xdviqmovie; `player Q3maknR de`ion="MD#"; x11-bitmap="/usr/lib/Z/!s/YJ.xbm,*; echo "+is \"%t\" j}is 50 \% Greekrme" \;  ; copiousoutput audio/b \edit=)\ 1An "P frag0"kB* ; ocal/bin/3-%t image/rgb; disx#9gifx-xwindowdump xAinua\@charuldn't \ #  a differen0n ap. messexternal-body; showexternal %s %{access-type} %{namsite} \ %{directory#2mod#erver}; needsterminal; composeRsd = extC %s;Sdescription="A reference to data stored in anC@loca4" text/rich ; shownonascii iso-8859-8 -e %1 -pPtest=s "`echo%{charset} | tr '[A-Z]' '[a-z]'`" =Zpiousoutput video/*; animate %s`mpeg; _play %s# # _codecmaps_jp.py # C mapping's for Japanese encodings # from% import multibyte\@_sup @unitz class TestCP932Map(;.$bBase_M,Y.aCase):' = 'cp932'mapfileurlhttp://www.python.net/uni/B.TXT?0sup6A = [O(b'\x80', '\u0080')a>f8f"fd:Mf8f1:%fe2f3]irange(0xa1, 0xe0.append(( s([i]), chr(i+0xfec0))) EUCJPCOMPAT-/ beuc_jp2fEUC-JP@OSJIS8shift_jisSHIFTJIS'Bpass_enc!1_b\^5/de5\24xa54A(b'~[u203e>\x8h'qISX0213q\0isxv7'F 6D/_Jpythontest.n:et/unicode/SHIFT_JISX0213.TXT' if __name__ == "__main__": unittest.() """This is a test""" import __future__ from "nested_scopes def f(x)k3g(y}return x + yg result = f(2)(4)Tqueue Tsched threading%im*u0sup TIMEOUT = 10 class Timer__init__(self._cond = .Condition()+time = 0Astop2) nRwith Hs\D> L# increase the  but not beyestablished limit=Qsleep7, tassert t > Ct +=cSwhile:< t& J- J(%W.wait(cadvanc# for user ie)3wnotify_all()estCase(#.T"):a_enteral = []o fun = lambda x: l.append(x{@uler .(Q.,g.:;Mx in [0.5, 0.432*1]zc].x, 1, fun, (x,)]=.ruvEqual(l,1qv?5])5?abs8w090000=@50A|E#|currentMAq =  .QFq.pu_|,5 rr=f1f1f3)3)T(target=n6runht.star.n1) self.assertEqual(q.get(timeout=TIMEOUT), 1) 4sel4True(q.empty()#for x in [4, 5, 2]:?F z = scheduler.enter(x - 1,fun, (x,Qr.advance(2j 4!3h 1 4p\5p)7000?upport.join_thread(t, HO#6M r.q(), 5) Ndef test_priority(9)pal = [],{ fun = lambda x: l.append(x.f.sleep;1, 2, 3, abs(0.01, F", V.run( Jl, [ ?cZl=kQnow =5bdevent16/6"+ 51.*A2A 2H0.02A3A 3A3A4A 4A4A5A 5A5A..!&!pB 3,/4]s_concurrent~q = queue.QUq.putr = Timer,; Tr]'X>U1; G DAcheduler.enterabs(now + 5, 1, fun, (5,)) event3 = scheduler.ent;3;3;t = threading.T (target=N6runnt.start(imer.advance(1self.assertEqual(q.get(timeout=TIMEOUT), 4True(q.empty(cr!l(2x!5! ~< 3"pG4p)7000?upport.join_8@(t, #6M r.q(), 4) Ndef test_6!):el = [] fun = lambda x: l.append(x$8.Wg.sleep;9for x in [0.05, 0.0432&1]z xx goFalse(7runD_`queue(7f=}/e5C2+L/e14 1424 2444 44 50.0!#  property is ssed to return an order list of# upcoming `spUs, [e1, e2, e3, e4, e5]pargs_kw G:seqvfun(*a, **br4seqc(a, b)k$< hc(, argument=(1, 2 scheduler.enterabs(now, 1, fun, argument=('a', 'b')) scheduler= 1, 2), kwargs={"foo": 3}LGrun( elf.assertCountEqual(seq, [((), {}),{8 Z'foo'1]) edef test_run_non_blocking(self):%el = [] fun = lambda x: l.append(x\1 = h.n`(time. , f.sleep; for x in [10, 9, 8, 7, 6]P&(x?(x,f=Falsev@l, [* if __name__ == "__main__"@unitF.@() -BEGIN DH PARAMETERS- MIGHAoGBAIbzw1s9CT8SV5yv6L7esdAdZYZjPi3qWFs61CYTFFQnf2s/d09NYaJt rrvJhIzWavqnue71qXCf83/J3nz3FEwUU/L0mGyheVbsSHiI64wUo3u50wK5Igo0 RNs/LD0irs7m0icZ//hijafTU+JOBiuA8zMI+oZfU7BGuc9XrUprAgEC ?END# Generated with: openssl dhparam -out dh1024.pem """This is a""" from __futuruimport * 3f(x3g(yreturn x + yg print(f(2)(4)) T__multiprocessing =0sup " B.PGOdraise `.SkipTest("Bs not helpful pPGO") ..installps_in_mo_dict(globalsF'spawn')''collections.abc$io $os Eerrntpathlibdpickleesocket%ta ftempfi*uOmock<D8TESTFN, FakePath trygrp, pwd except IwRError(Pgrp =" = None class _BaseFlavourobject):h_check_parse!tse, expectedf9=fX.; se'5sep?alt"%@ctuaf([x.replace('/', sep)Oarg]0aHb2if tG1> = y/|>self.assertEqual(actual, expected) def test_parsets_common(self):'+check = !._06(4sep&flavour.sep# Unanchored partsT@([],o P('', L[]))2>'a'525/65b9 5X, 'b'# Expansion/K? N $M'a/b: /cd:4, '";# Collapsing and strippexcess slashe 'ao)b/wvD c/D# Eliminatstandalone do#'.j.2 55 M:oaThe firstrD is  ./aZasep, [ e/@Fzp# IgnorV before an  /bc  @/A @c, class PosixFTest(_Base`, unit. CCaseS = pathlib._pN_% 3of @leadmZcept for thXQuble-t# special case.L/> '/[ G'Ea///ED # Paths which look like NTs aren't treated-ly/c: $#c:\\a'],  P('', ['c:\\a'])) check([',=#1)) < def test_splitroot(self):@@f = .flavour.*#assertEqual(f(''), u'''.a/a0+/b2d=/b/5/j // /a4 67 `# The  is collapsed when there are redundant slashes# except2exactly two leading<w, whichC is a special case in POSIX.&/K~ 5/Lj r# Paths look like NT paren't treated/ly *c:z .\\:: ;a\\ "\\) class NTFTest(_Base`, unit. CCase! =lib._windows_ Gparse_partsIM_)/Z# First Eanchored!;(/']P ('c:{2', %}</=<#\\>/\\h> ><?c:a| zTB?, 'E/ AQ# UNCYW{C('\\5, ''LhL'c5L I, 'c# Second, so that) f?igna0Z:b ('Z:', '', ['Z:', 'bsc'])) check(['a4Z:/#, (;P\\', H J# UNC paths^P//b/cg3d']_('\\\\b\\[[)'d# Collapsing and strippexcess slashe Z:1/c// -, /a`? ExtendedPa//?/c:jA?\\cBQ)\\MNaK:0NO, 'aS V, '/bY%# { (format is "\\?\UNC\server\share")1UNCD!?\_B\/AIw` oPSecon rt has a root but not drive  ?Z:/I3 bN|!Z:ldef test_splitq(self):@f = .flavour.*#assertEqual(f(''), ('.a//a'0 ;\\b3f'\\hj1\\aZ7n &c::C : v<x# Redundantr in theRare c/ed <!8/  c:v0\\ae >z# ValidP"zf, '\\', ''))# self.assertEqual(f('\\\\a\\b\\'), `', '\\?'))BOc\\dFJ# These are non-UNC paths (according to nt.py and test_KHowever, command.com says suchXjinvalid, so it's# difficultvknow what the right semantics9TVFLjP 96 # # Tests forppure clQs # _BasePurePath1(object): Q# key canonical'r, valuelist of tuples argument:# supposed5produce e\Nmequivalences = {'a/b': [0('a0b(a/  / @Q/b/',Ga//b / /p# empty:0pon get removed+ ('  i, ''),<]'/b/c/dGJoq///b//c/%b" |p0, 'I/}mdef setUp(-%):+@p = @.clsflavour = p._ <"%seC J.sep$?alt'Yconstructor_J,onPgPrtIsInstance(p, P3@, 'bH)c'ar - 1Fak!("0" !P(C)), e1,1 /b30P('+g65"c')_check_str_subw, *args# Issue #21127: it should be possible4 a U Q+# from a str y# i, itnas convert;F!a Fb.U StrS'tr1pas P = selsf.cls p = P(*(StrSubclass(x) for x in args))/self.assertEqual(p,? &>@partA p. %s:CyGIs(type(&), str) ,def test_str_s_common(A)Ty._check/;(''%.&a&o/b.txt,%/a- OjoinAP = G'a/bxp p.Lwpath('cC C?/c'Bp), )oO, 'dt(/dv MP  I'm % ?div # Basically the same as zo / 'c'2a/bg//diB'F( 'cBpFc?08/ / '>s'[, expected,FQcls(*=F @str(qN.replace('/', Lsep)6-p# CanonPized s roundtripPthstr`('a', ! /c ' qTtr, ( G# Special caseTQemptyBW'.', ('',NQOtherIsMOP) are`equivalences(Gas_posix9;P2$).1(),9n*# r as_posix() are in test_equivalences() defas_bytes_common(self):$(sep = os.fsencode!U.sep)$@P = 7E.clsassertEqual(f(P('a/b')), b'a' + bo+ b'b'?uriuBwithzRaises(ValueError').as_uri(HE`Oreprfor pathstra('a',  /c/5, '/a/b/c'pCcls(R clsname = p.__class__.__!__'@r = (R# The@) isthe form CQName("forward-slashes"True(r.startsv(+ '('), r< 2end:/')0AinneD[len]) + 1 : -1]Qeval(C@), p(zposix() roundtrip ?Aq = O!r,lib.__dict__NFIs(q4;q, W#qc/equ YV$, - 70#NoJV`'.@1\R/Z))"7_), {}\,l), int\_match$ VAa').VO, ''8.9p# Simpls`lative7OternHtP('b.py1/a/3gQFalse2/b/d'/a.py').match('b.py')) self.assertFalse(P$/c').mat4 # Wilcard relative patternW5TruVT*1"a/3/4 g3/G3(pyU g# Multi-partXAab/cM# Absolut [1  3 5  6 ,a a],+/a7//:- def test_ordering_common(!):$3# O! is tuple-alike"JLess(a, b@DS#@ "Greater(b, a/AP = G5cls:a = P('a'(b'/bc'bcd( ico 2d?b, 27c, 2 ///a  baaKBwith<Raises(TypeError:P() < {} js`` returns aCmpN5sep*c B`Q = p. BEqual(parts, ('a', 'b'))  # The object gets reused!self.assertIs(parts, p. G When the path is absolute,aanchor separat+%rtip = P('/a/b'Yh$ =r.TEqualg(sep, 2def test_fs_common(E!):"@P = E.cls &_check_str(p._[p_(), ('0,h 22os.)(p0xequivalencesfor k, tuples in2w.items(canon = k.replace('/',>6sep{-Yposix-e/-2if ]1!= 9[=1+ [( tI#t $i]{s.append((', _p0( \P_cls(*}", {, "failed with args {}".format(t MAhash  8"),0Qp.as_H !) xoparent# Relative5 '/c @ent,p--4B2 9h6=1# AOK>m ?'/a$/'/9 @ 9s:C4par{6ent '0lenO), 3M Qar[0]DvCar[1+5 Bar[2).)ertEqual(list(par), [P('a/b'), s.')]) with self.assertRaises(IndexError):,3upar[-1]@!3?OType~e0] = p# Anchored0p =v/a/b/c'0par;.parents0Equal(lenC3> & !0]\k/'), 1,*2*) 8lis/.13] 'def test_drive_common( 2P =K/cl].K7, 'Q2P('.(')* OrootJ&ser.0').^,/V?sep]%. a$G`.,( 0 ?nam.0').G.*T=,b8./^ fa/b.pyp 45aosuffixI,"-,./ self.assertEqual(P('/a/b/.').suffix, '') Lself1ha/b.py14 e&f5 xa/.hgrcj /32.f i(F7 ;htar.gz8 ?9!a/Some name. Ending with a dot/Kdef test_[es_common(W!):$i@P = E.cls 6oes, [] ./\?a/b01]3'f( '9;9m 5im5'o) ?rc'; O swptar', 'D [E-yM?tem1?temh*+/..$ W,bW /~01q 6tar.gz').stem, 'b.tar') ,self.assertEqual(P('a/Some name. Ending with a dot.').stem,DK'@  ;def test_\_n_common(!):%U@P = E.cls Eb').O('d.xml'),  ?/a/E?/a/Foa/b.py2H QDot e$.O Raises(ValueError5$, @ A!/- B?, 'q>//c@+/c/@-?d')osuffix8QU('.gzb DE G G# Strippi1]1&('1/') >? # Path doesn't have a "file" component {", @AA# Invalid !;0, '3B+%suffix, '.')  -self.assertRaises(ValueError, P('a/b').with_suffix, '/.gz') @D"?c/dC-O.c/.E/D1ad/.')  def test_relative_to_common()!):'8@P = E.cls5p =w& 4Typ'p.k 4_, b'aiEqual(bV(P())q7/''6!'p?b')nao5/6 %5I4# With several arg`ba', 'b S!Un!ed pathQ /'c=Oa/b/A,?*(/af/gbDP('/9X7q~6!m~Bo+B.)l'9(ValueError,- p.relative_to, P('a')) def test_pickling_common(self):$(@P = E.cls0p =Ne/a/b')for proto in range(0, `e.HIGHEST_PROTOCOL + 1gkdumped =3Bs(p,Uh,p[`loads(.*ed&assertIs(pp.__class__, 5pEqual(p$ hash(pp), )0 2str/  PurePosixPathTest(_Base`, unit.!CCaseJ0cls?qathlib.4K OrootC2P('.DG, '/./0# POSIX special case Htwo leading slashe~e/eq5Not^CA1a'),1///r-]%0/ oas_uriC/').C), 'file:// 6_a/b.c;@ /%#A%25%23c'_non_ascifrom urlparse import quote_G_byt.6tryos.fsencode('\xe9except UniE%ZErrorCG@skip0("\F cannot be ]d to the bsystemOing"V /bT - + (E4_matchzFalse(P('A.py').E^'a.PY~is_absoluteh%().Ey/a'/ /b@a1Tru.]a.assertTrue( P('//a').is_absolute()) self.assertTrue(0./b23def test_is_reserved(D!): V@P = E.clshIs(False, P('hK 2/3 foo/bar: dev/con/PRN/NULBOjoin0p =C:p p.Epath('b'Equal(ppB0//a)FL?//cN'c'LDMLK!
"('6.eK cL@Uc:/')+, 'file:///;_a/b.c@E/%#F |%25%23c][EO\xe9 o%C3%A9K eN  Lq;f j>4 o<%#c@ p t:@match_common# Absolute pattern3BTrue2/b.py').jA('/*$5/c:6#m AFals+d:$c:8 # wrong drive;jG3 False(P('b.py').match('c:/*.py')) self.assertFalse(P'b&.75"l/k/c: 5 # UNC patterns1Tru//some/share/a?Zo/otherM 2 # Case-insensitivityB B5Ob.PYa4c:/a/B.Py')c@C:/A; 0//SS CE=EK def test_ordering_common(!):$ E(OFedEqual(a, bCGVSGLess(j 'rGreater*Fb, aAP = Q&clAp = FA/b',qWC:a/BFp, q8`&?p < > "e/@HAREQt\partsd adAQ = p. ^  , NP', 'ab6 9b \\_d//a/b/c/dqg\\\\a\\bmcrdbOroot+B?, ' c?')..,/\\\^2[0 '\\') < self.assertEqual(P('//a/b/c/d').root, '\\') def test_anchor(self): 2P =T1cls0eRc:').D0, '/ ?a/b2/06.4\\\\a\\bp: ;E >NOname+BQ, '')YC?').,.b[0fa/b.py 6 //My.py/Share.phpt :>osuffix+D.013"7#a/.hgrc').n ?c:/5!4.j1.hg*9 htar.gz: .;#pa/Some . Ending with a dot.gM5  < @Q /es1oes, []0 self.assertEqual(P('c:a/b').suffixes, []) ?sel2/3ja/b.pyh'm) ;za/.hgrcvq7!m.n's+ ?rc'=[jtar.gz'.tar', 'F1- G//My.py/Share.php >BSome name. Ending with a dot.N?/a/O9def test_stem(C!):U@P = E.cls tem, '' ,-/..[/b[23J 8Y8b$:7O '@  ;i_n(J'd.xml'), & I?/a/Jqa/Dot eSR/S Raises(ValueError&5').$, CBoC*Fname, 'd.xmlC') (self.assertRaises(ValueError, P('c:a/b').with_name, 'd:B/eC//D.//My/SharJdef test_psuffix(%!): 7@P = E.clsIlEqual(<Lf'.gz')[G/H Ida/b.pyK"K  # Path doesn't have a "file\" componentY ", b@.A-/A.i # Invalid ! =0, 'D-/&/\\D/c'/D-/\\G2/c:G3//d]0/\\F0/.c1".crelative_to0p =C:Foo/Bar$(p.^"')>/ ?'<{4foO~zo('c:foO'), P('Bar')) self.assertEqual(p.relative_to('c:foO/'), <P>QbaR')By;|:A# Uned pathsRaises(ValueError, T:/''@9_P('d:~>/=)?Foo?)/@,/C:B/Foo/Bar/Baz)"C:I E0p =f&'?&@3'c:b=;str), '\\Foo\\DA N(X'^he=}4foO~/=<"=/"<#A?'C:m/J6 1P('>)+ d:'Dive_to, P('/Foo')) %self.assertRaises(ValueError, p.relative_to, P('//C/C# UNC pathsW2p =.Server/Share9_/Bar'iEqual(r(q!sECsHare'))2FooJK:'//IH3//'% &%IH.I H GA# Un+ed /)?c:/O96//zK)/zRJdef test_is_absolute(A!): 5@P = 6.clder NT, only with both a drive and a root are e^ZFalse(P().;,?'a'/?/b/2///a/c:/c:/c:0Tru?'c:(01*  j by definitionxc/[ 2e//cg >c/d6join(self): P = self.cls p = P('C:/a/b')p.joinpath('x/yHassertEqual(pp,H/-M!mN J# Joining with a different drive => the first  is ignored, evenvA# if-esecond.relative.*p !D:!( /D: )L//host/shareV3` lWOsamei appended to if#g$cg clC)!) def test_div(!):C# Basically"5as 9g.a1 / h5';/y'9Q6k+/xl 6 ST ) !D:7Ik9   O7$is_reservedjIs(False8').KD2/3 foo/bar:2Tru>con4 self.assertIs(True, P('NUL').is_reserved()) Oself4O.txt8Ocom15!_9.bar9BFalsbar.com9:?lpt?lpt(># Only the last component matters c:/NUL/con/bazj UNC paths are never g//my/share/nulo>auxo class PurePathTest(_Base, unittest.!aCase):Qcls =Dlib.4 @def 4_concrete_l(?@p = .cls('a'type(p),\9 zpWindows if os.name == 'nt' else@osix.) different_flavours_unequalPS q$ )ANotEsOp, qorderedMBwithRaises(TypeErrorE < q==>)>=*{` # # Qs for es # # Make sure any symbolic links in:Abaseresolved BASE =RP.real (TESTFN) join = lambda *x:+(?, *x) rel_-T/ only_nt =tskipIf(C!C {' requires a -"atible system')rp,uu = x_POSIXv! @x As(  : W#ntTVeWindowsPathTest): cls = pathlib.WindowsPath def test_owner(self9=@P = A.cls/BwithassertRaises(NotImplementedErrorJ9P('c:/').l)_groupTl) class _Base:d(objecA0"""s for the FS-accessing functionalities of$K [bes."""# (BASE)KE# | -- brokenLink -> non-existing&EdirA `-- linkC5u../dirB 9--  |-- file%EDECUEIdirDH] BE # No permissioncAM^BpMsetUVcleanup( os.chmod(join('dirE'), 0o777support.rmtreeelf.addCfnBos.mkdir8?A')6B C , D' ECopen#$'wb') as f{f.write(b"this isV A\n" V@', '^B^ B^ C^C^ C^$fDf DfD4if pcan_sym # Relative "y3os.(~BA', oN  /6F;[0dirXkB5  00os.. ..i5),L L0# Tone goes upwards, creavq a loop1 'bMif os.name == 'nt'/# Workaroundqhttp://bugs.python.org/issue13772S def dirlink(self, src, dest): os.symlink(# , target_is_directory=True)<FelseFrdef dirCl!) SEassertSame(path_a, b./@(os.$.samefile(str(U_a), Ab)),n "%r and %r don't point to the Z [?" %Cs FileNotFoundfunc, *args, **kw Wwith xRaises(JError) as cm](\V Equal(cm.exception.errno, w.ENOENT_test_cwp2q =0cls0get))= zOp, qqHIs(type(p), (0p.is_absolute() p. GpN&hoS '.expanduser('~'3{ 4! 6qp'U A_,4 = join(BASE, '!'jB1 SdirB'9B9(FwZp" CC /r0/pp.vFalse(pYY 1Ja# Testnon-existentU caseEnon_'ooprc(>&, ?, r<((rn?, p<&, r.samefilec, r) 0self.assertRaises(FileNotFoundError, r.samefile, non_existent) Hdef test_empty_path(X!):ja# The  points to '.''@p = :.cls(''Equal(p.stat(), os M'.')xpanduser_commonPq OP('~ e\PP(os..C)oP('fooZpA/@/..B,P .absolute().anchor) / '~\N), pOistsFBASE qIs(True, p.'s(( (podirA')34rFalse, h5r?bahqif support.can_symlink(TX.8B8B C =V3P('/xyzzyOopen6 Iwith ).I('r') as f P Instance(f, io.TextIOBase 4W`f.read"this is V A\n";bBuffered`.stripb1, bx_ing=0N?Raw7 *~_write_byte/().Db'abcdefg, ?9), A # check that trying to write str does nouncate the file self.assertRaises(TypeError, (p / '0AA').X_bytes, 'somestr')KjEqual(?Bread>(), b'abcdefg') Bdef test_(lPtext(!):$@p = .cls(BASE pC3'äm, encoding='latin-1Rutf-8', e?s='ignore'), '_# cheeB~f!D&, e |iterdirPQPtit = p.GDQpathsFFt(itexpected = ['dirA', BCE]if support.can_symlink(c+d"e fbrokenLink'[m"B, { , q) for q in }Q@skip_unlessD+ z@# __#__ on a =a directoryS 2, '!=G [TfUD'] }Q_9 /no !!thS_iI,4Bwithl!OSjv) as cmvn=# ENOENT or EINVAL under Windows, TDIR otherwis# (see issue #12802 In(cm.exception.errno, (@.ENO`, :1ENT#2no.)glob_common_:(&,& k1set2)o :!("R"IsInstance(it, collecas.abc.Iterator<-[Y]) _ch eck(p.glob("fileB"), []) 8_ch$Pdir*/)*)Q"dirB@B", C'C"Cif not support.can_symlink():ip m!*Ae'dirA', 'x'A'ZOelseB 0, '~ K'"B/  A", O9D',&*"B/B5'"BDSdef test_r_common(self:%:&, expected$07.assertEqual(set(2 ), { P(BASE, q) for q inI& }AP = J1cls[3p =A)qit = p.]&A"CIsInstance(it, collections.abc.Iterator<-[Ao z 1 |8+Q E w^0"KA3B( @NijC@AdirDD}bfCL?dir` D* @skip_unless!\_loop# Don't get fooled by 2 2s (Issue #26012 Qgiven$t(F'*')K7 = {'brokenLink|/(B'y^C( C/{ C~E 'fileA',  'linkA', ! B}/"self.assertEqual(given, {p / x for x in expect}) :def test_glob_dotdot(K!): # ".." is not specialK4s'@P = :6.clp = P(BASE))%`set(p.N(jS)), {6,|?) }?dirA/../file*"J/A"U../xyzzyP6)) ?_check_resolve=C, p,ied, strict=TrueWeq = p.7$qR# this can be used to both relative and absolute rRution _5+= B   @support.skip_unless_symlve_common2H v, 'foo'*BwithyTRaises(OSError) as cm w cm.excep5.errno, v.ENOENTb# Non-PMstr(False)) os.path.joinT p, 'in', 'spam6 < x .. 0<F0absD(LR )# These are allXH AdirBLileB{ \vV(p, pz PIAHxWileA' W_C <h &pDpC- oo5 V 'in',  'spam'), False) 4 p = P(BASE, 'dirA', 'linkC ..0foo inH@if os.name == 'nt':d# In Windows, if \Y points to dirB{\K\..'Cqresolve0 without 3ingYifirst.@self._check_/e_relative(p, I fOelse_Posix //B$ w beforeto parent oft$$  # Now create absolute symsSd = support._longpath(tempfile.mkd (suffix='-dirD')addCleanup(Lrmtree, d+3os.@(os.h.join(d), VXf;*BI I;Y;\XI Y &B' F BABn-strictoJM,K  KOd, 'wQ@skip_unless_!def test@dot()# See https://bitbucket.org/pitrou/<lib/issue/9U-fails-on-complex-tA.clsu0dir ('xo0R%ink(os.path.join('0', '0'), c1')) self.dirlink(os.path.(F, '1828q = p / '2'LassertEqual(q.resolve(strict=True), pPr = qH 3'4N Raises(FileNotFoundError, rb(, cb# Non-FAFals!) Bdef test_with(L!):R@p = .cls(BASE it3.iterdir(2next(it2,t& ppt5ass # I/O operation on closed ']SValueVxF, itx01 op.open_p1absolute2__enter___chmod*VfileAAmodestat().st_# Clear writable bit1new.0 = 5 & ~0o222!"p.)*p.., 5_# Set/| B# XXX also need ala for l m s@;`'# Change by flippingF $st" ^FU@.addCnup(4z5 -l#Noo2 @support.skip_unless_sympl J 0/ '<Ibst, p.i) 3_noq"P@unit*U)(pwd, "the pwdaule is!edAthis"_owner";uid61uid:try1namfwd.getpwuid(uid).pws_name except KeyError: self.skipTest(."user %d doesn't have an entry in the system database" % uid)NeassertEqual(, p.owner()) +@unittestUnless(grp, "fgrp module is needed for this 8"s1defp_group(~)@p = .cls(BASE) / 'fileA'gid = p.stat().st_gid6tryP/ = grp.getgrgid(gid).gr8!_EounlinkF"#p.=*~FileNotFound(k(S3_rmdir7dirAq`p.iterF-q"p.pC(e\ PPKsize80# Rking to another path#Aq = [BdM0p.rE?e(qqV , 1#  str of a relative0r =b_join(6AA'wqr"osr oeplaceTla non-exist JWn() bdirB',BR/e(Ytouch_common!;newFalse(p.exists(C)) p.touch( self.assertTrue(p.exists(6st = p.stat:old_mtime = st.stl :_ns#5_ns&# Rewind the Osufficiently far inpast to work aroundGfilesystem-specific timestamp granularity.5@os.u#(str(p), (z - 10, `# The thould be refreshed by calling we againkGreaterEqual(w7_ns?_ns>;8# Now with _ok=False = P / 'new %B'4Ymode=0o700,kQRaises(OSError, k`def test__nochange(u!):#BPdcls(BASEp Ax8Qp.open('rb') as feix f.read().strip(), b"this isAA") _mkdir!gnewdir q7$0is_l1M ?*cm@/p.Rcm.exception.errno, .EEXISTO_parentsW0# Ca chain of directorie(C,>UdirB' /C'F}#^VNOENTp=d W $ :#0 `Q` arg}(tat.S_IMODE(=&ode) # default 0=DEzt0o555, True)  self.assertTrue(p.exists()) $his_dir$if os.name != 'nt':@G# the directory's permissions follow#mode argumentCEqual(stat.S_IMODE(p.`().st_D), 0o7555 & Loparent default process settingsG aG`def teQkdir_z@_ok([)@2p =cls(BASE, 'dirB't_ctime_first = q]1Bwith?Raises(FileECError) as cm0p.m(cm.exception.errno, v.EEXIST;M>=~ >9, sb!) P__C b~rl / 'newdirC's OE*0Y/, yLroot # Issue #25803: A drive , could r% P on Window#'/').resolve()  5M |@only_nt# XXX: not sure heotP thisQPOSIX: T_unknown_ ,for d in 'ZYXWVUTSRQPONMLKJIHGFEDCBA d + ':\\!if$p.g >#QbreakJelse$skipTest("canfind a drive that doesn't exist") with self.assertRaises(OSError):)0(p / 'child' path').mkdir(parents=True) 8def test_"_l_>`_file(wb2p =cls(BASE, 'dirB', '0&B';p1(p.6s()$# An exception is rd when the last component'a7aisting# regular ,ardless ofRBther^0_okFtrue or not.G oPFileEswj as cm}phEqual(cm..errno, v.EEXIST(<,  8 F3no_kFA> 20?_ok$C`concur,P_crea u0fortern_num in range(32CPC%d' %Fe9iYFalse&"my.(, mode=0o7770#5t~*thw!# Emulate ano@procthat would edirectoryJjust before we try to=it ourselves. We do itGin all possible71bins, assuming OthisK@funcncalled at most 5 times (dirCPC/dir1/2,H$", 41 &2)$if_.pop(&%os"th) # from -"lyaed.add3 os.mkdir(path, mode) # our real call  pattern = [boolB_num & (1 << n)) for n in range(5)]G concurrently_created = set())p12 = p / 'dir1' )2'&Itry:with mock.patch("lib._normal_accessor.m a", my_ )MQ2p12+0(pas=True, exist_ok=Falseexcept FileE'nsError` self.assertIn(str(p12), ) b?lseP /NoS1(p.Bs()) @support.skip_unless_symlinkdef test@_to(VZPlf.cls(BASEtarget = PVfileA2# SiPing a"h 1z>AdirA6AH.DbEqual(1ctat(),r!.s57Not8l*9 3strcJ 9!I0is_) to a directoryB_w7[.'#stb2tercF;* e([) 01Anon-zOing'8i<?bah94if 4can( \AW 5,4B4i/ 'brokenLink9 ^ self.a ssertTrue((P / 'fileA').is_ S()) aself.a1DFals2?dir1non-existingj A'?bah: if support.can_symlink():* 56B6/ 'brokenLink:@only_posixdef test_is_mount(@P = .cls(BASER'/') # TODO: Work out windowslt~2:; R &D EYZ*|T4< =vuZ  88< afifo_f/5W/fo1j:P@unit .skipUnless(hasattr(os, "mk1"), "os.() required"G0 _t[ P, 'my/'F:tryvWstr(PI except PermissionError as eCfTest('R): %s' % e-PP &osocket(&;is_socket_false(self): @P = .cls(BASE)assertFa; (P / 'fileA').is_socket()4?dir3non-existingn 2>'3]_check_complex_symlinks , 0_target # Test solving a non-loopchain of L (issue #19887KV(BASE0dir(os.path.join('C0', 6), ?1')D1D)1'D2D2D2D3DQ02@# Re]e absolute  qE(P /".r1(G?, Pstr(p), j?1')jT2jV3j@|relativ@old_ = os.getcwdos.chdir 6try54cls$,(#+z%,zM5zQEz;kfinall!I@support.skip_unless _t06Z{(%{symlinks('.') @support.skip_unless_symlink!def test_complexs_relative_dotq(self):6[}._check=$(os.path.join('dirA', '..')) class PathTest(_Base`, unit.CCaseu`cls = W@lib.0qncrete_` Ap = cls('a')assertIs(type(p),vpWindows} if os.name == 'nt' else@osix*#uned_flavour\yRaises(NotImentedError,>T*  glob_empty_pattern BwithRegex(Value'Unacceptablqd'(plist(p."('yp@only_p m$CiQ_loop, *args, strict=Truf- r(Runtim `print(W.resolve(zropen_modeGold_mask =u &(0ddCleanup$$, 9, FBASE(p / 'new_file').L('wbEpass"stRstat(pCb`Equal(0.S_IMODE(st.st), 0o666:1os.f(0o022fother_w& In,44Qtouchc (e z. 4Belf.ng(edRX=0o759tat(join('masked_new_file')) #self.assertEqual(stat.S_IMODE(st.st_mode), 0o750) ; @support.skip_unless_symlink!def test_resolve_loop(n!):!# Loops with relative Gs'3os. ('aX/inside', join d_checkbBASE, F' bY[Y[Y[PZ/../ZdZdZd# Non-strict6l. r'foo', >f=False absolut U)UUh)V'aVaVa WWjWjWj&OW', xLglobpAP = &cl^`p = P(Qgiven-At(p.Kw"FILEa";cexpect&) if not fs_is_case_insensiha else e ", f (+se`*")), )dC , "dirC"1p.rT/d" P@unitU (hasattr(pwd, 'getpwall'), 'pwd module does@expoA#()dexpandusera im@ule({YE pwdPpwdenApwd.`uid(os `name =Bpent.pw_M"+ho"Pdir.rHp('/') or '/'4# find arbitrary differO (if existsk3for0 in (Pother.pw_name  otherhome = pwdent.pw_dir.rstrip('/') .1if 5name != user 2andO:48UbreakJelse$UT/A!\ !  "p1 = P('~/Documents#p26' +?+ '.3.w/4/O../~`51/6/7P~fake with support.EnvironVarGuard() as envenv.pop('HOME', None)k self.assertEqual(p1.expand`(), P( _) / 'I2I53I 4J*p45252 6262Raises(RuntimeError, p7A Benv[] = '/tmp'%7h5 @only_nt class WindowsPathTest(_Base, unittest.RCase)0clswathlib.E@def 7`_glob(8@P = E.cls8pFBASE %aset(p.T"FILEa")), { P(9, "fileA") }r5Q, "dirC"]dB`/dirD/D:pUSERPROb%env.pop('HOMEPATH', None) env.pop('HOMEDRIVE'['USERNAME'] = 'alice' N# test tha e path returns unchanged3p1 = P('~/My Documents'#p2%u* 3*?bob( 4(/x 5&/d:' 6' self.assertRaises(RuntimeError, p1.expanduser;2;'3;Equal(p4,o(), p425252 62*6)Vdef check():<*T=(),\6 P('C:/Users/ ;u4Key;?envteZOuYuM s & 6e first lookup key in the env varskYAC:\\c!\\d'-  "z0at I PATH is available instea{;3Q&`> &l l  'm&~cPROFIL if __name__ == "__main__"@unit*.() import contextlib4sys o >R fromrA0supI3time resource = support.imD_module('resource') # This test is checking a few specific problem spots with the J [. class RbTest(unit`.Case): defy_args(self): .assertRaises(TypeError, x.getrlimit)9%@, 42Asz%9v)fsize_ismax6try&*(cur, max) =(-RLIMIT_FSIZEexcept Attributc bEpass`Jelse(# Z should be_INFINITY, which willa really big]# number on a platformularge file On these,+s,Qwe need toqP that4U get/ functionsperly convertPto a C long6and`?sion doesn't r P@an e.ZEqualY : <&, =enforcedCPsee whappens whe$small. SomeBP# ver's of Python were terminated by an uncaught SIGXFSZ, bu1pArun.c has been fix@ignoZion. If so, twrite()kreturn EFBIGSReded.ed# At least on=A*ed5vattemptOto change iR ValuR instead JB1024C_set = Tru%5'pt #HNFalsIf = open(TESTFN, "wb""f.pb"X" * > try:  f.write(b"Y") $ f.flush("# On some systems (e.g., Ubuntu on hppa) the Mdoesn't always cause;exception, but_close N eventually. Trying several times in# an attempt to ensurfile is reb synced andM  raised.0for i in range(5):+.sleep(.1+  OSErroruif not limit_set*t/ifD0# CX will[byte we wrotej# RestoreuQ firsavoid gett#a spurious ePresource.setr ( RLIMIT_FSIZE, (cur, max)0finGC/f.3P*support.unlink(TESTFN) 2 def test_fsize_toobig(selfS# Be Y5at _Pcheckllarge valuesftoo_big = 10**50*ryW5 = g Attribute&6pasJelsetHL(Overflow0, V, wv -Smax, &N\usageKZ.assertR_Rs(Typ,?9@, 42APF UUSAGE_SELF=childrenACHILDRENE# May not be av ailable on all systems. Etry:  usageboth = resource.getr(RUSAGE_BOTH)A except (ValueError, Attribut)nEpass>_threadoTHREAD-# Issue 6083: Reference counting bug)def test_s&A_ref'W(self llimitskLIMIT_CPU ]\Jelseclass BadSequ  |__len__return 2@sgetitemDW, key( if in (0, 1&.slen(tuple(range(10&))).raise Index ,32())Dpagesize0 (3.assertIsInstance()_, int-GreaterEqual/0P@unit.skipUnless(sys.platform == 'linux', '* requires Lw,1_co,tsfor attr['MSGQUEUE\1NIC`RTPRIOQRTTIMSIGPENDING']with contextlib.suppr 5R0getgB, 'Ri1' +)m&pfreebsd?tan @SWAPQSBSIZONPTS|RRs(TypC,=SPif oseuid() != 0GY`Permis_,_13C&ASrrocessLookupu -r limit = resource.getrlimit(resRLIMIT_AS) self.assertEqual-p>?0, A!, \I.H,i!# Issue 20191: Reference counting bug* @unittest.skipUnless(hasattr3, ''), 'no Esupport.requires_linux_version(2, 6, 36@def r_EA_ref(f!):Sclass BadSeqC|__len__5return 2N8sgetitem<W, keyv(AWs[key] - 1 # new rS a*& =\J,?()) Ps) wmain(verbose=None4un_#(R Test) if __name__ == "__N2__"`) """Units for collections.defaultdict.""" imB4 os Dcopy dpickleftempfih fromg Vn sfoobar(Bst vDTDict(d.0Cas5W\basicWd1 = ~(` S$d1_factory, h3"w = list"[12].append(42o , {12: [42]})(d1C&24CL, 24G)3]4K, 13: [], 14=RTrue( is not (3]&4]+d2?, foo=1, bar=4 2A`)d2, {"foo": 1, "bar": 23[1Z [N?], 7, [1In(m?, dF!.keys()(I !I /42F C ~NotIn(1Ff.assertNotIn(12, d2.keys())  d2.default_factory = None"self.assertEqual(3,2UEtry:@ied2[15]except KeyError as err3 werr.args, (15,Oelse<bfail("z didn't raisex"nR$as(Type#, !dict, 1) def test_missing(C)Hd1 =:(m  d, d1._Sf__, 428/d1Alisth  O(42), []Orepr#  sgd1), "_(z_, {})oTeval(A)4$[11] = 41<}i11: 41+d26intt " 222  #, {12: 42ef foo(): return 43h+d3?foo}True(d3t is]3Vd3[13 n3 %s3: 43})" % ( _print g 0fooF: 2}# NOTE: We ca:use tempfile.[Named]TemporaryFile since thisk# code must exerc~qthe tp_! C", which only getBinvoked for *real* %s.fVtfn = mko f = open(tfn, "w+mF 1A(d1,&=f,"2"f.seek(0< 5f.readline(),d1) + "\n|@2@kfinallUwf.closeK+os.removeP Ocopyi!1.7' `type(d> 0assertEqual( d2.default_factory, None) self.assertEqual(d2, {}!,d1Cu = listCd3 = d1.copy(9 Ztype(d3), Odict0,d3z,y3 F[42]4444, {42: []m74[1 Cd64, 1># Issue 6637: Copy fails for empty{ |8d(d['a'] = 42.e.e:a, 42) ;def test_shallow_0!):! d1]foobar, {1: 1*@2 = B/d1 X5 (, V,U,MOdeepJ)[1vNU( #PVTrue(d1[1] is not d2[1] |'"keyerror_withouh( 6tryV[(1,)except KeyElz as err5p err.args[0], PrOelse>,("expectedo"recursive_repr 2045: stack overflow whena bound method class sub(2 __init__DCw!= u1U2Ureturn [Gib^aRegex(19d),nr"sub\(<0 .*.+ "3 of@\(\., \{\}\)>, \{\}\)")  2# NOTE: printing a subclass of a builtin type does not call its Fq # tp_E+ slot. So this part is essentially the same test as above.Mtfn = tempfile.mk &() 5ry: f = open(tfn, "w+"- t1@(d, e*=f20fin g6wf.close+os.remove!) 1def_>able_arg(self)h.assertRaises(TypeError, defaultdict, {}X}picklinT8d =;F(intAd[1]or proto in range(Ue.HIGHEST_PROTOCOL + 1=Cs = .Pdumps\Mm'o'zloads(s PEqualGo) if __name__ == "__main__"=@unitP.() import " CEmpt>__repr__return '<0$>'?2Cmpo=Cinit=G,argrg = argqCmp %s>' % D>$eqpg others6%#AnythingOHTrue/ne TFalseuComparisonTest(.CCaseset1 = [2, 2.0, +0j, Cmp(2.0)@set2'[1], (3,), None, (&candidateZ + :)%_csPfor aMP;&b&*Vif ((Qv) and (@") z:s blF Ja, bA'OelseA8NotD/id! # EnsureX M qes id()F1rgs]LDiDn#10@L.in (len(L)//2E^La YI1 b, a) eid(b),5'a=%r, b=%r( 3ne_s_to_not_eqw1a =1bc2&@Is(a0b,  $f.assertIs(a != b, False) self.assertIs(a%c, True) % def test_ne_high_priority(;!):%M"""object._, _() should allow reflected to be tried"""Jcalls = []lass Leftqu# Inherits };'__eq__(*argsu.append('j.2'-(return NotImplementedqcKRighD%r/ner35 ()CG(9+fSequenceEqual(v9, [q1, 'AI/']?low not invoke)OBaseSj%Derived(J): # Subing forces 4er ?7r%tt5I40, 'P other_delegationDNo default ( between oper:s exceptM op?(#(', lambda a, b: a == b),-]lt__'-<,e,YgY>YgY>Yhfor name, func i1sQwith subTest(1<QunexpOufail('U2or method /ed* CX-6 = $[9, _  if other != name: setattr(C,2, unexpected)6!ifO == '__eq__'[self.assertIs(func(C(), object()), Falsec?elsTRaises(TypeError, c*, d def test_issue_1393(K)x = lambda: None8.(Equal(x, Anything() (%6, x(5y =eye y) if __#__Emain@unit .q() from import sup.!`bigmemDs, _4G 9Z:$io0 BytesIO, DEFAULT_BUFFER_SIZE<$os dpickleDglob epathlidrandomeshutilubprocesWthreading dunlinkC_compressionsys # Skip4sethe bz2 module doesn't exist. =U.+!_m+c('bz2'( BZ2File, CTBZ2De or has_cmdline_bunzip2 = Uext_d2S(dataX?al A/if1 is]4@ = bool(.which(''/`Xreturn s.check_output([P], input= <JLbz2.  class BaseTest(.CCase-""B forrcases."^TEXT_LINES = [9b'root:x:0:0: /bin/bash\n',.bin:x:1:1: / "Pdaemo%C2:2: //s)adm:x:3:4: P/var/ Olp:x:4:7:lp:$spool/lpd:*sync:x:5:0: u/ .`hutdow626/ $ ;0hal2A7:0: 3 /mail:x:8:12:  0news:x:9:13: 0 00uuc$a10:14: 1 1operatorE1:0: .@gamer12:100:R/usr/ /Aophe[b3:30:g0lib/gopher-datas:\n',  b'ftp:x:14:50:FTP User:/var//bin/bash6nobody:x:65534N\/homegppostfixkt00:101:ldspool/ miemeyer:x:500:e$/nRAgresx1:102:PostgreSQL Servlib/pgsql:L myxE`103:MyDsD&D1wwwb3:104:h0Yfalse]TEXT = b''.join(q_LINES) ADATA BZh91AY&SY.\xc8N\x18\x00\x01>_\x8 0\x10@\x02\xff\xf`1\x07n,R?\xe7e:\x99\xaa0\xc/3F\x86\x8c#&\x89 3\x06\xa6\xd093M\x0fQ\xa7\xa904hh\x12$\x11\xa4i4\xf14S\xd2\x88\xe5J9gd6\x0b\n\xe9\x9bdaf08.KD@v\xfw27xw5@1\x9I1|/";\xa2"9fMb1#A\xb6\xf6oc5y\\\xebOr@85\xE bc-5p5\xd7"%P>V,\x2a6z8da!fH11"\xd6E)I\xa3^\xca\xf3rf003UQ26\xen\xed\x8b\xc1Ad\xc4 a^9P\xacD#7m0\x1pe\xb8\xbd\x1 ab80ankRe}Bd83]cP8\x82#P9"6l$K"j@8GP0l1..[ks"ls/Pf4\xcP3\xbeE>@\x9d u 9d6G`3n\xfaM01%yv\xb4\x00z\x1b\x14!c/9%!en7.G\xfc[1&01B@ A!8`'iEMPTY_prE8P\x9N 56BAD3this is not a valid bzip2 file' g2# Some tests need more than one block of uncompressed data. Since&Pis at least 100,000 bytes, we gather suF dynamically and fC it.R1Not!t passumest/ion works correctly, sosccannotLsimply usRe bigger for alls. test_size = 0 BIG_TEXT = bytearray(128*1024)#for fname in glob.(os.path.join 0dir*(__file__), '*.py')):Mtwith open(W, 'rb') as fh&*Qtest_ += fh.readinto(memoryview(%)[.":]C5if 4 > hQbreakN@DATAz2.compressf$, level=1) 8def setUp(self.  = support.TESTFN=|LDown@4if j isH!Rjos.unlink& class BZ2FileTest(Bas D"D the% 3&."createTempEd, streams=1, suffix=b""T b, "wb" qf.write_.*eZ)wqBadArgsFassertRaises(TypeError,, 123.456o7MValu8os.devnull, "z"@+/rxA-/btB+ 0* L+10ORead tX:LJbz2fX/`, float()jl=eEqual(1A(), H5Bad.  K0KY@BAD_0#OSaMultiSc5:?O * 5_onkey!# $u/() on a m*- archive where a)L# boundary coincides ~aend of@raw  buffer.B4= _\ion.BUFFER_SIZE/_compression.BUFFER_SIZE = len(self.DATA) Etry: $ createTempFile(streams=58+with BZ2$\filename) as bz2f\5`assertRaises(TypeError,3.read, float()r A`Equal(h5A(), _wTEXT * kfinall_compression..buffer_size  def testReadTrailingJunkT) ?auffix=JBAD_FHB )aMultiS6os=5, sb 0Em)0), b""oChunk1Mtext = b''SYwhile True0str22z2fn&10X if not str@ Ybreakr +=7  @)>!* Rf/10M  10-!k[:100]?PeePpdatappM2Notu8;), ./o.p.starts(<he*), self.TEXT) def testReadInto(self): .createTempFile()with BZ2+filename) as bz2fKOun = 128Ab = bytearray(n^UassertEqual(T`.readiOb), 2!, FTEXT[:n]a1len.#_) - n - Mh,a-n:]) ALineGRaises(TypeError,line, None @for 6 inj_LINES C1(),KMultiStreams*6s=5FO * 5<s Rs(K s#?s4  IteratorWlist(iter'))khdClosedDeadlockv# Issue #3309: /ion on a cD3 should release the T. $ =N.D&.y() self.assertRaises(ValueError, next, bz2f) # This call will deadlock if the above failed to release!-.P?sel| .rbaines) 7def testWrite(A!):with BZ2Fil.filename, "w") as26E 4Typwm5V.TEXT"BopenA'rb'fEqual(ext_decompress(f Q()), o Chunks10x.Qn = 0ewhile TrueVstr =[n*10:(n+1)*10]G/if not strK ]break6x&trr2en += 17fNonDefaultC\Levelexpected =.$, l@&=5:R[Le2"rbQ $, L }I A< lrNL.f_LINES- # Issue #1535500: Calling >) on a closed# should r| an exception!qv, ["a"]?MMethodsOnReadOnly.s(b"abc"M/r@/ #OS-f, b"a"[oh9I0, [?]aAppendf.) bz2f.write(self.TEXT) with BZ2Fil filename, "a") as bz2f:29IassertRaises(TypeError,/qg5GBopenA'rb'Equal(ext_decompress(f.read()), a * 2) def testSeekForwardz)7createTemp#:KO5 Fseeka4F.J(150O,o[150:]AcrossStreamss+&=2 \l%O) + >@Back(+50v-150, 1g0500@b^to = !00cwhile 0:> 0W"-M;(:to);Z/1Z& +ahfoFromEnfM *8 CJb@000, _[-1002OPostYL1500vtell(),KTEXT))  self.assertEqual(bz2f.read(), b"") *def testSeekPostEndMultiStream(G!):*..createTempFile(s*Es=5)'with BZ2 filename) as TX.seek(150000Kv @tell1len.TEXT) * > QTwice] <71$~)7B4reStart>V?-157-&`6$2<(SK * 28/no $opa, 'rb'"Nrawf"% =U!9:try2 :qo<G. PofinallTjfclose(2iRaises(ValueError,g ?w abF7elfeeqBytesIOgf.DATA){ BTrue]i:"iE(V$ &K c), "w" try:  self.assertFalse(bz2f.seekable()) ) finally:.fclose(*TRaises(ValueError, 3a%) Osrc = BytesIO(DGDATAW%rc = lambda: F^GZ2File(srcA+trendef testReadu)h "3Truri$E #:# o), "w".aFa@Writ?wjF :(s0`Fa|OpenDelOcreateTempfor i in range(10000%ofilenameF'Rdel o`Nonexistent#OSBQ, "/non/B"linesNoNew d# Issue #1191043: '*s() fails on a  containing no nS.data = b'BZh91AY&SY\xd9b\x89]\x00@3\x842c !\x9ah3M\x13<]\xc9\x14\xe1BCe\x8a%t'{with open.b") as f f.' e(G] JD G*;_aEqual(2, [b'Test'])  with BZ2File(self.filename) as bz2f: )xlines = list( Q.read5()),LassertEqual(9, [b'Test']) -def testContextProtocol)|f = None4a, "wb" f.write(b"xxx"]X, "rb)v.close(;6try xEpassexcept ValueErrorD ,:lse\fail("__enter__ on a d  didn't raise an t7ion V<1/0ZeroDivision*?1/0 yG Th4GiB input" Q"x" *::tryx ed2zl edy kfinalleNone # Release@5ory&Gbz2.t  62lene..strip(b"x")), 0r aPicklefor proto in range(p).HIGHEST_PROTOCOLa9 Raises(TypeError/3]kdumps(,) classD  orP(Base \_Constructor,dC, 42f[ Y0bz26BZ2$ z >UBtextd }.iJ`;0 a 7 / <&UnusedDatau;_U"this is  Q C+6N= T) self.assertEqual(bz2d.unused_data, ) def testEOFError(self): D = BZ2Decompressor()!ptext = (%.d#GV.DATA*ZtRaises(u,?, b"anything"B&"p@bigmem (size=_4G + 100, memuse=3.3g!4G , ;|# "Test) with >4GiB input"8PblockS = 10 * 1024 % = random.get Vbits(@* 8).to_byte, 'little'6try1 * F // ^6+ 1@3 ed94z2.(M ,> Q6SdE_*ed\OZTrue(G*= ofinallENoness= =  i ?<aPickle60for proto inAge(p).HIGHEST_PROTOCOL9HAAType /3]mdumps(,"orChunksMax bz V}max_length0 ou."[]~+# Feed some$,len_ = lenQ.BIG_SU - 64'out.append(bz;16 [:P%],8}= )XjQFalsexaneeds_*out[-1]), ^Retrieve moreI<providingo 8b''nw@hile!:=OLess!`remain'unNw@not :eofgth=max_lenggth))  self.assertLessEqual(len(out[-1]), max_length) <out = b"".joi.XTPQout, BIG_TEXT-bzd.unused_data,eydef test_decompressor_inputbuf_1(d%):# Test reusing ) buffer after movexisting:contents to beginn bzd = BZ2D(&[]1# Creatend fill it|?.DATA[:100],9 =0), b''X.# Retrieve some results, free$capacity atI# ofout.append(yb'', 2)Add more  that fits into`f#A{[100:105], 15$t^75:]x&''Y<8h  2$ 2by 1theiend right away9_empty$2.- FLwith newtMg200:280]2, not enougharequir&izy@80:38 1?300I3`extend&it(almost fuX: aHevenbo it, ?resf.DATA[200:300], 5))  # Decompress rest of data"out.append(bzd.d/(self.DATA[300:]))4 assertEqual(b''.join(out), CTEXTdef test_failure[%):Pbzd = BZ2?or(pRaises(Exception, }@BAD_V * 30I6# Previously, a second call could crash due to internal inconsistency#J@support.refcount_+8refleaks_in___init__EgettotalG4 = Zget_attribute(sys, '/'& refs_before = Ifor i in range(100YSAlmosfj7 - , 0, delta=10) class C]Test(Base l. _5t = bz2.Q#.Gext_UG"~EmptyStringfbLtext'b' 2QEMPTY pebx% rw?b""q$k!TomZ 8 In< le7elfMLValueError2~o[:-10]|BadData\m/OSj NhMultiStreaml UO * 5C.]TrailingJunk+{)O* 5 .assertEqual(text, self.TEXT * 5) class OpenTest(Base ): "  the open function." 1def(W, *args, **kw DHreturn bz2.I(*Otest_binary_modes\K@for  in ("wb", "xb""q"if%!==aunlink].filename)"Bwith0*,^n) as f\rf.write]mYTO"rb"Tile_data = ext_decompress(f.read()fassertEqual(F  7  ml%ab[ * 2)implici !# , |s (no "b" or "t"string). 10/ ".&-?k, " =i.de("ascii")_native_eol =  .replace("\n", os.linesep9 >t?t@ tAd with open(s elf.filename, "rb") as f: &_data = ext_decompress(f.read()).de("ascii")EspassertEqual(V0, tVnative_eol=Qwith >Qopen( <t+ srgagf.write(Tnwa * 2) def test_x_model)@for  in ("x", "xb't"'>aunlinkAe!gApassi"Raises(FileExistsError 9>81objphqBytesIO&`.DATA)!6FTEXTXhzNi" =[ bad_paramsX~# Test invalid %eter combiwAons.xIQValueD,&* 8, 7wbt)ka5xaMrencoding="utf-8Krs="ignoreqPnewline="\n"b`non-default +V2)_ ! =.replace(P, os.?sepft", encoding="utf-16-le") as f: f.write(text) with open(self.filename, "rbGile_data = ext_decompress(f.read()).ede("utrlassertEqual(xV , _native_eol:t", encoding={ G !) def test_W_error_handler3)fq# Test Snon-default > >.c1wb"foo\xffbar".%Pascii@s="ignorH\ZMHQnewlineB explicit , (universalmode disabled)RD1 = ETEXT&wTO="\nuZrZrZY:`s(), [sU]) YSmain(support.run_unit(pBZ2File,C-orD 5" =FOpen&eap_children() if ____ == '__2__'kP() im collectionsD.abcg dpickledrandomestringyVGweakref from+  class Dict.kCase):m invalid_keyword_arguments.ZCustom(dictEpassCfor Z in {1 : 2}, ? BRaises(TypeE* /u3(**kO {}.updateTconstructocalling built-in typesDout \ must return emptyd V), {}%QIsNot%Kliteral_ Sheck + +  different sized dicts  # (to exercise the BUILD_MAP oparg). )for n in (0, 1, 6, 256, 400):&*.items = [(''.join(random.sample(string.ascii_letters, 8)), i)JN}i}range(n)](`qhuffle( Jformatted_ = ('{!r}: {:d}'. p(k, v) n q/ Ldictliteral = '{' + ', Jj))}'self.assertEqual(eval(W0), !) >def test_bool(DxSIs(not {}, True$({1: 2} 1Is(f{}), FalsG'Jq Lkeysad = {}(aset(d.:)>@'a':0'b'LDk = ;apk), {'a/b'!n(!k}KIn('b', ]d< Raises(TypeError,_, Non9AreprJV(a=1)B"P_Q|['a'])"V_value$<?1:2C{76(/[1#;gC{(1, 2);5[/1) contain;0Not;rs"@'a' 7in &\ Y<0c',z"$__-,__?lene3Vd), 0b self.assertEqual(len(d), 2) def test_getitem(self):  = {'a': 1, 'b': 2},r.assert^d['a'], 1)$ b$2$d['c'] = 37JE = 4ncJ3J$4$del d['b'][,4, 'c': 3}1fRaises(TypeError, d._M'__5class BadEq(objectgVa__eq__{, other%)rtV Exc(AChashC<eturn 247"d[)/42$?KeyM, 23Exception): passOHashfail = False_ef __ 1if E>T Oelse6N&420x =;d[xO x.f = TruRe;ExcT3, x_Qclear6d1:1, 2:2, 3:3.3z?, {Pl, Noneoupdate'v{1:100}$d.?2:2 ; -NiA%oAttribut)) 6qSimpleUserDicto__init kILkeysrL.*!AH7, i& K&[i~d &()|*R 6Failingf)5%  p=f):  class BogonIter:  def __init__(self)(5o.i = 1K ?terKpreturn RL?nex!ifH/.i 0r#?'a''raise Exc"=t)()#msgetitem%_, keyuK5keyC..assertRs(Exc, d.update, FailingUserDict()) = " 2OkeysC =<EQzord('a'.NRXgA <= /z'rtn = chrC/.i.?i +Q( 5rtn@StopNatio,G) +badseq(objecti (<L @GExc(3Jp%{}qh5ValueError, <[(1, 2, 3)]ttest_from\Equal(dict..'abc'), {'a':None, 'b c }ed = {},^~IsNot(d[d>//L p(4,5),04:0, 5:0: []5-a+g([WyieldR 0g()S1^Y47TyppOAlikeu): pass#Xd0ict.k'), {'a':None})  (self.assertEqual(dictlike().fromkeys('a'), {'a':None}) > ?IsInstanceD B\@Bclass myy%):def __new__(cls" return collections.UserDict(Cud =g&b'# L'ud6O, 'b@8kRaises(TypeError, %) +Exc(Excep|): pass$0badE1Qpinit__(S j,kTExc, lW, [1]8BadSeq(objectsOiter<?nex48)2cssetitem, key, valuerr2 r# test fast path forVionary inputsG(zip(range(6), )"7b(d, 0) Lo[0]*6)F3Fda{i : iCi inE10)}'res = d.copy#res.update(a=)3, bc 3 {"a", "b0c"}Q#esG_{1: 1, 2: 2, 3: 3.dIsNot(?, d&Bd[4] = 4j#No=&W#{}?, {63 ,  g\_fuzzP_size.r[10, 10+0]2ict9=fdom.rand80+. //+8BwithsubTest(dict_size=dict K): md = {}for i in range(B Qd[i] = i Id2 = d.copy()self.assertIsNot(d2, d( Equal(d, d2(d2['key''value't ?NotO (len(d2), b) + 1)def test__maintains_tracking(Lzclass ABpassOUkey = A(bd({}, {'a': 1 Pkey: ''}e3}Cgc.i{ed(d), #2) noncompact# Dicts don't % themselves on del/pop operations.&# Copy will use a slow merging strategy that produces>at0ed  when roughly 33% of  is a non-usedBkeys-space (to optimize memory footprint)qIn this we want to hit/7ingodbranch7 and make sure it works OKuPk: k $k$V1000) <9500uel d[k]A =7-geHPIs(d.2'c'), None(+@, 3)z, 'b': 2pJa1 a',KSRaises(TypeError, W,L setdefaul#.!z 40 dX$F, []bS 'R.append(3\R<0[0]P S4S'W7), 4Exc(Excep,:): 5class BadHash(object): fail = Falsedef __hash__(self9D0if .E Wraise Exc()^Oelse6eturn 42 5x = BadHashK`d[x] =)Qxf = TrupassertR s(Exc, d.setdefault, x, [])sVtest_!|_atomic # Issue #13521: 1() callsG and __eq__ only once.`class ?ed(o__initcount = 0b!$?eq_"fCB#DM+= 1gru_K, other^db !idK) == id(QTed1 =\Sy = { K: 5}4245(<2:nSEqual& 1..u6, 1020&1.- k5ed2qCitem_at_resizeLa@# 5 sX  , 0: 0, 1: 1, 2: 2, 3: 3Q# 6th` forces a o[A_%[]}0pop? t# dict.for copymode in -1, +1p# -1: bZ same structure as a#,+,Pis a.Y p@log2oprange(12ize = 2**1 jNab = {}  for i in range(size):  a[repr(i)] = i#if copymode < 0HVbL H>H`b = a.p-()ka, va = ta.popitemT self.assertEqual(va, int(ka)2Pkb, vtb`b`b``False(@ and^!= tb <a$5b) oed = {}PRaises(KeyError, d?def test_pop(9w# Tests pop with specified keys k, v = 'abc', 'def'+ [kvvs, 'ghi'3f(k), v< &len(d), 0K~k/ zyd :1;HType class Exc(Exception): pass $BadHash(objectRqfail = !__hash__! 1if Enr:Oelse6eturn 42Dx = K0d[xT%42 x.u = True8Z3Exc3, xWmutating_itera[ # changing dict @ dur5 &0d[11 abRuntim 8dBCd[i+ab_looku "a / (issue #14417eNastyKeyI!e_#f= Nonec__inite /luvalue = K # collision! rz1\%eq[otherC4if .  mydict, key = NastyKey.mutate_/ )@?one03delk][key]$ return self.value == other 2@key1j8(1)22Pd = {;E: 1}1!(dZde2] = 2=assertEqual6cb2: 2})def test_repr(2%):A.P4d), '{}'/[1 91=tdLd 1: {...}1 class Exc(Exception): pass<$@BadRgobject#)_&,__( Qraisek^E41: ^)R;s , 3, dDy\_deepbVfor i in range(sys.getrecursionlimit() + 100}F1: dNRJ_Error,eqKf{}, {}9!1, {UOCmp(#eq, oc__hashC<91nd@{Bad)d&1}0Bwithy}, oYB= d2;9keys_contained{helper_*lambda x: x.+()7Pitems84G, fn# Test rich comparisons against views, wh*should behave th# same as sets.@empt[0fn(Ssmaller = fn({1:1, 2:X9Mlarg W, 3:3%cF&3l4l&ETTrue(2< h O +=+KC > `V+=+FFals>= larger)  self.assertFalse(smaller > larger) *- ,!S <= 7- -[P$ <3[-=- 38Z-# Inequality strictness 0RTrue(M42 >y +<+ WV +<+ $ =2WG$ !,%) W%# There is an optimization on the zero-element case.= APempty ! *=KT AWithsame size,wise compare happen' i,>def test_errors_in_view_containlp_check(d!):5vclass CNa__eq__/w, other6% raRuntimeE{ d1 = {1: C()}p/d2wNRX(s(Y ~d1.items() $d2iS*?!= S=S&d3c;, 2 ]_ < d3j1E( >i}Adictset_operGs_on_keyskp112}.$ky^, 3:3$:54:4E(k1 - k2, set()h)3, {1,2}) 2R_1, {3' 3'4' 1 & k2, {1,2})  self.assertEqual(k1 & k3, set()) ( )| k2, {1,2,3}+ ^+'3RA4}) ~def test_dictview_set_operations_on_items(!):5k1 = {1:1, 2:2}.%(k2 _, 3:3%3%64:4ap =-=-f{(1,1), (2,2)D 2 - k1, {(3,3+ 3+?4,4+ 2 [/, #1 .+2 d@[mixedF =# Just a few for .keys(>PTrue(i}% =y-}$$:14Z [Q| {2}$/ 2b5A2} |b5X# And #&y!,1=(H,@1c. ~missingMake sure t doesn't have a __9__ methodWs0False(hasattr(H7, ";"] 7/{}5# Test several cases# (D) subclass defines returning a valueO# (ED aiJ RuntimeErrorGFG:set instance variable (no effect'G# (GF eat allD8def: [, key(,'5 42YPd = D 2= * vd[1], 2"_3], 4"NotIn(2, d &Equal(d[2], c42) class E(dict): def __missing__(self, key(,raise RuntimeError()Pue = E()Pwith Q.assertR@(s(Aj) as cUe[42]E@Equal(c.exception.args, (42,)FCinit# An instance variable& should have no effect,] = lambda`e: None4_f = F<1Keyy8f83G8Epass_g = G+g)test_tuple_keyep# SF #1576657ed = {}h od[(1,)20badu 0Dicary lookupss`fail iqeq__() Vs an tCustomE6( t <0Bad:Keyo__hashIpreturn %1.__'__yM{, other)Tif is(&,b[ 6' "Y? 3Vx1 =  /x2d[x1] = 1sfor stmt in ['d[x2 52',"Q'z = &" x2Ld d.get(x2)"setdefaul)?, 4- ?popO update({x2: 2})']} Pexec(>, locals(Kqresize1yB #   ing bug, found by Jack Janse 2.2 CVS development.# This version got 1ure0ebuhild, inf}eGp inNrelease build. Unfortunately, provoktwkind of stuff requires #: a mix of inserts and deletes hitting exactly the right hash codes in #*aorder,WI can't thinkta randomized approachN that would be *likely* top a fail case in reasonable time. Led = {}Qfor i2ange(5):d[i] = i0 0el 40, 9): # i==8 wasKuproblem6 {def test_resize2(self# Another dict &bug (SF #1456209).Se# This caused Segmentation faults or Illegal@trucsRclass X(objecta __%,__ return 59#eq7!, ^)%if d.clear()`yUFalse !J+= (@[X()1;234# now trigger a6Tru0d[96E6qempty_p60ed_$_in_freelist# Bug #3537: if an BT but Fjpwith a u larger# than 7!inrD, it@n aswzFilurc.$ Raises(ZeroDivisionError 'a': 1 // 0, 'b': None, 'c d e ($'f6 'g h Sx}container_iteratort680: tp_traverse>not imple0ed MR#Rview sCEpassF@Ps = (dq.items,Yd.value FkeysVvK> {obj = Cref = weakref.refQw8fobj: 1j!obj.v = v(+ B!x0ter`*.v 0del+%, @`gc.collect0Is(#),]V"Cycl@Fed")@_notAcked (, <# Nestedn take several Y@ions uuntrack self.assertFalse(gc.is_tracked(t), t) def @self:J?TruI)gc.collect()BWC@support.cpython_onlyBtest_literals(\)# Test GC-optimization of dict 7Sx, y, z, w = 1.5, "a", (1, None), [];.mC._noVed({}x:(), y:x, z:1, "1:|o"b": 2,@2, ( , !, , ()): int@1obj}# Dicts with mutable elements are always \, even if thoseV#54not2 right now..8S}({1: []_([],)" /{} @set(Atdynamics1ally-createdsxqclass MyO$6pas1=, o@!(),X1d =d`d[1] =0 y02.z.3.yx.copy()4RwR?NJd M+Q UB# dd isn', but it mayte and therefore dHwhich contains7dust belbddfB6 Imd.fromkeys([]Rd.update( =, o&B0(x==&=zd tracked(d)  d = dict(x=x, y=y, z=z, w=w) # self._tracked(d>z.updateQ L?notP=  [(), (z, 1)]p @w@ O @  @support.cpython_onlysdef tesn_subtypes(!):#t# Dict  are always +class My1(;GKEpass-g:51)) !make_shared_key_Q7, nYuCjJ:es = []for i in range(Q2fa = C(+p.x, a.yz = 1, 2, 3S$j.append(a._#__"areturnYssplittable_setdefault  1"""( ) must be combined when ? breaks insertion order"""ba, b =2`a['a']"@Psize_Upsys.getFof(aAa['b525'b.f'b', 20B_ Rb"bSu asGreater(I!, +Equal(list(a), ['x', 'yza,b'[h=b=0A?del"del d[k]&Porig_3 aga['y'] # %isBwithc:Raises(KeyError \G %, +8z!] R# Two have differentw.:6= 4'z']) @(support.cpython_only def test_splittable_pop(self):#'1"""! " must be combined when d.:Uk)"""9pa, b = O .make_shared_key_dict(2) -orig_size2`ys.getGof(a&ag'y') # %isTBwithassertRaises(KeyError\=Greater(s%, )z8 Equal(list(a), ['x', 'z']. b.y3b`# Two Gs have different inion order.4a['y'] = 42 , 7'@_pendingcpop a key in a 3tedshould not crash&Ba['a21Ub#a' Oitem>Me1 = @ ( y;, ('z', 3)oq`del a[`Py) setattr_after$"()eonvert!Binto5."# Issue 28147 imF _2Fcapi_vclass C2NEpass<ca = C( a.1! UTrue(f.A_hasA(a._@7__)S# o3) c[it touH6'OFals$hBut C {g again) ttable(a.__dict__)) # Same for popitem()Xa = C.2 self.assertTrue(_testcapi.dihassplittable(a.__~ ._OFals`#3SD@def _iterator_pickling(!):&Rroto in range(+e.HIGHEST_PROTOCOL + 19=0dat{1:"a", 2:"b", 3:"c"}b)Pit = (3Cd = sdumps(it, p (D)zloads(d!Equal(sorted(it), XY6try12drop = nextb except StopI>ionBcontinue;6@del []d)NmRp # views aren'tE, only theirvsXitorg.T:s()S?org## note that type of "und @# is> necessari s!asDoriginal. It i# merely an object supporting?{col, yielding2theyI+s [ one.4 s(!), E }4IsInstancecollections.abc.e/or@2g,H(%# ?[0] dvalues0%#q._() is its iterato7r  it = iter(data.values())% d = pickle.dumps(it, proto(M)zloads(d!self.assertEqual(sorted(list(it)),  9)) ndrop = nex] =624 = @ + [z]p?def test_instance_dict_getattr_subclass(o%):F FooR__init__3W, msg8%O`.msg =!W0f =Uf('123'nK(strOEpassAXff#, A(f, Gg'msg')92f._'_[9]:Bobject_set_item_singleY0non?A_keyK  e1] = 1f.a = 'a'p, {1:1,/W:'a'}check_reentranaertion, mutater# This will trigger,ion of the \ when replaced# by another . Note t^relies o:fcounting:U}G won't achieve its purpose= fully-GCed Python implementa%s.JMkS__del':D{k: T() for k in 'abcdefghijklmnopqr'}:'do0d[k k>4# R0 inB`shouldFcrash (see issue #22653m @['b'5`ID^ q.update?v.clear(8zwhile dv0popx$merge_and_X>o__hashreturn 00:#eq87, ol!W)  return False  l = [(i,0) for i in range(1, 1337)],other = dict(l)[X()] = 0d = {X(): 0, 1: 1}self.assertRaises(RuntimeError, d.update, t)def test_free_after_iterating(T&):cupport.check2 , B,s=lambda d:G(d.keys())Q7_valueS;HitemR4]equal_opXor_modifying,ndi#A fixBseg fault re edSissue 27945 part 3.v`class )|__del__s_b.clear(%?#eq>J!%EaE77Tru6!aChashc} ="13ob6X()1(,2a =#_b" omt<5.4a;int/__15_ef __if len(d) > 1L "-} # this is required to exist so that d can be constructed!JX(1): 1, X(2): 2:try2.fr # shouldn't crash\xexcept G:implementation defined7Bpass?2setV>6b>;8 .fromkeys(d) # shouldn't crash except RuntimeError:0implementation defined7>Qpass "def test_dictitems_contains_use_after_free(self):6Dvclass XOa__eq__/w, other6%d.clear()Preturn NotI"edd = {0: set()}>(0, X()) in d."()6Oinit'Chashpair[:] = []"130-X(), 1235 ([ ]oob_indexingr_iternexvG(int___del~i: X(i) for iqrange(8)}__and_mutate(?`resultD Q2if ([0] == 2#'0d[2pNone #  --> X(2). was callW.assertRaises(X+, B) \CAPITest(unitg.bCase): #  _PyDict_GetItem_KnownHash@support.cpython_onlyyLZ1_ge _k; `from _,pcapi imQ R<9S'x': 1, 'y': 2, 'z': 3a!oEqual(V(d, 'x', @'x')GyGyG2G#zGzG3Wq# not a#l aSystemc,,OP, [],A&1)# key doesm_existl?Keyi *{}iMQExc(Eaion): #ZBadEqFerE ExcwX?P7zk1, k2 =  \q_k1: 1"a?(k1?Excd0k2)mlh@mapps GeneralM )s()`.Basic$Protocol):  type2test = dict class Dict(): pass1Sub%MappingTests(m _Lps.Basic$ProtocolNvj if __name__ == "__main__"@unit[.`() """_) cases for traceback module""" from collections import ibdtuple#$ioStringIO *linecache4sys rNP0suprg.!%TESTFN, Error, captured_output, unlink, cpython_onlyN.script_helper\tassert_:ktextwrap =0 w_code =( ('', ['co_fileD0',  "]);Lfram<=f[8f_globals 0loc F+tb!tb@4tb_M@'tb_ noBtb_next']) TC&(.:# For now, a very minimal set of  s. I want to be sure that #pmatting3aSyntaxs works based on changQ2.1. Bdef get_excep_format(self, func, exc2try %!()OK5 as value0freturn;.snR(exc,?\,lsM`aise Vf("call did not rVion")s- _e_with_carecompile("+fact(x):\n\tx!\n", "?Oexecd!_2`f?1 +Pbad_indentaSPspam( print(1)\n 2)non_asciiu!'P8 = "\u1e54\xfd\u016325\xf2\xf1" +'> BZ`err = ..9, u;Equal(len(err), 4&@True![1].strip()"7 In("^", err[2]) # third Q has  81].find("!")J0^")T in the right place  err = self.get_exception_format( syntax_error_with_caret_2, SCEB)5]assertIn("^",[2]) # third line has r:Equal(err[2].count('\n'), 1) # and no addi`al newXN 1].find("+")@^"))Zin the right place TY*non_asciiadef test_no&):}Wxc = t!(" ", ("x.py", 23, None, "bad &")traceback.#Wonly(eV, exc@0lenO), 3&1].strip()`dbad_indenta  QI 4print(2)"5 @  _)eD A"BpB&se8 # Test thatAs derived from BaseER are 2tede = KeyboardInterrupt(4olst =  e.__class__, e> mst, ['rR\n'])I _A_2l_str__5 X(Y_;61/0traceback.form at_exception_only(X, X())  self.assertEqual(len(err), 1&"tr_value = '' % X.__name__a!ifmodule__ in ('__main__', 'builtins'):51strL! =A [Oelse4'.'.join([,L] err[0], "%s: %s\n" % ( , 1)) def test_encoded_file(b# Test that tracebacks are correctly `sed for M source Ts4# -8 line number (Issue2384,qrespectG[3ing.F3975.import tempt, sys, subprocess, os# The spawned& has its stdout redied to a PIPE, and%FNmay be different from the curinterpreter, on WindowsMat least.' =.Popen([sys.execuu, "-c",:"4Bsys;(M.?)"]O7=r.-hstderr;fSTDOUT]*3 = .communicate(/Soutpu=(E'ascii').splitfs()[0]0do_R(firs%, message, charset,'no1mq# Raise3IaEQcatch' -6try9WQwith TESTFN, "w",=R) as TDH.write("""{0}if 1-1,;"rRuntimeError('{1}'*""".formatn.){ B37j0.de(:ing sofinall#runlink(r1ed ^'lashreplace' handler8_=">eI  'backslashreplace') ## and we just decoded them with  output_encoding.Amessage_ascii = &3ed_.S(D)) Eerr_line = "raise RuntimeError('{0}')".format([s I0msgHB_: {0}@ self.assertIn(("`%s" % no), stdout[1],;W"Invalid-p number}!r} instead of {1 DHcJ:no)STrue(0p2].ends( )Ptrace"f/!rE2], sQ3] ==4?msge *3Gmsg)do_test("", "fooF", 3for charset in ("$"iso-8859-1;Putf-8 iGBK"):%ifC3== B #@text @+elBd@\u4E02\u5100"I/se8h\xe9 ho4("# 5}\nYr,6, 4Z]!shebang\nh25h_ \t\fd?# Issue #18960:* spec should have no effect8x=0PGBK\nP1, 'eC', 5@support.requires_type_collectingg@def u_print__at_exit(X22599: Ensure that it is possible to us%e Wq module{#&display an exception at Pythoi0 = wrap.deden  imE sysko tpclass P E0AtEgobjectN@__init__, >try]x = 1 / 0 H.exc_info = sys.exc_info() # self.e*[1] (traceback) contains frames:Hexplicitly clear the reference toj1 incurrentPr7wbreak aL_cycle; = None %def __del__()).print_exception(*60)bi# Keepmodule nF"paAcall destructorR# whe/m?is unloaded*pobj = PEgAtExit6"""rc, stdouterr = assert_python_ok('-c', code:expected = [b'T, (most recent last):', b' File "", line 8,%__init__?ZeroDivisionError: d by zero']{Equal(stderr.splitwTs(), -\test_N:output = S'IOvJ%, p("proje1"),r, file=qA.*.getvalue"a%: a\n") class FormatTests(unit .bCase):&Gsome% raise Keys('blah'd$@co1nlyPecheck_<!_f,_nup_func=k`from _capi import Igv:try.^ ;qtype_, g, tb = sys*z)ifq is not W-5# CRSinner,4Pthis +((tb.tb_next- fmu\n' + \FG v''.joinL.z_tb(tb)_?X2(tb_FH! =(_ 0# C|_tb and  Rs.with captured_R"("A") as tbI _ tbC=<  with captur ed_output("stderr") as exc;: traceback.print_exc()&excfmt = +_forma,ile = StringIOMDoPfile=f6ile{Jelseraise Error("unable to create test! s5") # Make sure that Python and the<rmodule 0sam55ingOself.assertEqual(q_fmt, p^ # Now verifyX_tb func ]b.getvalue(), tb;j ?exck-Y,Cm 7ileI is properly indented.!tb_lines =ia.splitw Dlen(@F), 56`banner_5[0]slocation, source,6-2:.vRTrue([.startswith('T{&') 8v :o File7  :! H=1def<_()n.check+L__cleared_frames`0# C]ting also works P1 a RQ()ed Tnup_tb(tb Rtb.tb.(r0,T bstack_3V_&Js. Note we havuse _gete(1) toq# compa!emout this` appeax1 in` W6Pcaptu *"sth/%X(sys.t,L , B!=sIY uc", 6/st|"".join(h)y_k7elf$Gprn(/with captured_output("stderr") as 7: Uprn()lineno = prn.__code__.co_first-self.assertEqual(`.getvalue().spli7s()[-4:], [@' File "%s", a %d, in test_print_stack' % (__file__+lno+3),P =()'i?prn\1\traceback. n1]) # issue 26823 - Shrink recursive Ks0def _check_$_$_display(v, render_exc)# Always show full diffs when thisVR failt# Note that rearranging0 ngs may require adjusting=the relatqnumbershe expected?.maxDiff = None=0# C@ hitt j>on limit='f( A#f( with captured_&_fQ8:tryZexcept RponErrors>exc>{KNelse/%D("no@on occurred"0no_Mfaresult-(J$'TP (moscent call last):\n'3f{}{1+5} _'V# XXX: The followq changes depend on AtherMcb# are ru.Qrough(qinterac preter or V)-m # It also variplatform (V sizeFortunately, we don'bout exactness here, so' us9gexr' \[PrevioushPrepea(\d+) more times\]' '+ : maximum`depth HededA$=  &actual =/_fX1# Check the output text matches expectations # 2nd last line contains the repeti1e count6self.assertEqual(actual[:-2],i!ed)5TRegex5 46-2]3#an have add"alappendedi2In(ed[-1], U-1]) 1s# Checkrcursion is roughly aDlrec_limit = sys.getreB(6In(int(re.search(r"\d+"2]).group()), range(lU-60, )a known (ed) number of9ve invocadef g(U=10):%1"if dreturn:&-1aise ValueError{with captured_("stderr")s *_gt:tryggmgexceptxP>exc:rB\r_excC>lse/fail("no v e` was r'd"[ no_g = g.__code__.co_firstiaresult-(f' File "{__file__}",{E_g+2}, in g\n'>'C  &d' [Previous"ated 6 more times]#3d u c'20tb_: = 'Traceback (mostent call)():Q7 _c_Dve_tp_display_T8g()z$+ a).splisuN _gSb(22 differ?yve secth&: h h()   except ValueError as exc: render_exc()Nelse/self.fail("no v`! eawas raised") Jlineno_h = h.__code__.co_first-aresult-('Traceback (most recent call last):\n'3f' File "{__file__}", r { +7}, in _check_recursive_tp_display_'Vreturn h(count-1d' [Previousrepeated 6 more times]&d3d gPexpec5= (#+ qg).splis0actual = stderr_h.get(2HassertEqual(C$, Ddef testppython(L).(`.printu"@cZQ_onlyV .internal`from _capi importqeption_gUkexc_type)!c_c tb0ys."Ginfo9o('?90_format_stack%Gfmt( D1 = D.`uU[-2:], [U?$%s7!%d- mD % (ono+2),v?fmth.@?\n'y1y]unhashableuclass UOEEion( !8a__eq__{x, other% return True ex1 = UnhashableException('ex1'))2)2)Etry:6fraise ex2 from ex1en C TXOS,_type, exc_val tb = sys.finfo()1with captured_output("stderr") as *_fion_print(\7valZwI_f.getvalue().stripplitlines( self.assertEqual(11, len(tb)&context_messaged, tb[5]9OIn('):'9391910]) causeA = ()"\nThe abovG was the direct <" "2!offollowing:\n\n") n0Dur4Phandl N ,mvanotherd occurredmboundaries = re.compile'(%s|%s)' % (re.escape(  ),7 !))<lass BasReportingTests:def get_(B"_or_call)if isinstance.%, >9ifreturn"d% / u}eTyzero_div1/0 # In !3dcheck_9W, msg> =/.s (1[-3].startsW(' File' 3', K2}n1nZeroDivisionError')N1B0test_simple eMarker q_Ue = _9r?(e)g EO), 4!0 Traceback: Z& / P<cause(self):  def inner_raise(): :tryself.zero_div()1except ZeroDivisionError as eKuB Key%efrom eQ?out # Marker> blocks = boundaries.split(get_report(d)&assertEqual(len(UO), 3)%[1], cause_message3echeck_I6+0]'OIn('3', ;A2]) 9test_contex M 6 W<   kn_suppres{  E5ion6NonB"_YUe = _@line"e) (=%O), 4eQTrue(# [0].startswith('Traceback'":1:o File752', v3v UKk?and&# When both a@ and  are set, only the&should b# displayedD,F.q muted.  TP{ CtUxyzzy'jAName "e]self.get_report(outer_raise)) self.assertEqual(len(blocks), 3)%[1], cause_message3check_zero_div[;[0]'tIn('inn() # Marker', qA2]) def test_recursive(!):$( U:try\.except ZeroDivisionError as eh3Uz = eB KeyCKfrom*o#fH+z A(4 4 = boundaries.split.get_repzc# The first7v is theLd 9HS0Not?1/0+csecondf(apartg$y)Q# re-$x'c^syntax_e_offset_at_eol*v# See #10186.EmIe! S[Q('', 0, 5, 'hello'amsg = "e)flines((msg[-2], "&^"/exec("x = 5 | 4 |15',^'M_nonC# A ( that looks like "None" should not be treated specially?err^E@ion(N_( : )\n', err`_ '7a= W class PyExcR]ingTests(BaseFReportingTests, unittest.TestCase): #2 This checks reporting through the 'traceback' module, with both L format_exception() and prin.v def get_wt(self, X@e = .&\!e)?"s = ''.join(.type(e), e, e.__+6__)Zcaptured_output("stderr") as sioKpI.s assertEqual(siovalue(), sreturn s class CExcRts(BaseE /, built-in !byinterpreter@cpython_only`from _pcapi im _SKk  k(fnyRLimitqTA''' #( l2 argument8rIt's enx o  extact_tb, r Qstack^ F '''Zlast_raises1\k q('Last ?d')D2D e939 /2(949 3959 49P~s_frame/ sys._get%C .CBelf.5Tr  CN QN XN fN mN {0_ex8!t_ k8&5(bL(**kwargs p.0|m%, =8[8p(actualpected, ignor=(>8"[:.]AA @8+1:Ce+1:])  self.assertEqual(len(actual), expected)) 4' with support.swap_attr(sys, 'tracebacklimit', 1000):=Enolim = ex.9t()qGreater5O), 5.UQ=2), :Z[-2:];zExcept(<6100>100:], -5-1F-/:2-R:100])el sys. ' UI = 2Y:X43;3; -<+:3&"O = 0 uO/-1P-def test_@_tb(p:try} .last_raises5e :ion:exc_type, value, tb =BGinfoO(**kwargs ureturn .0Etb, 7arO, 5+\ }o%s -1"_8 6 XVQ1  P <(:O-PMlf.assertEqu(al(extract(), []) def test_format_exception(self):%)6try  .last_raises5()-F$ EM :exc_type, value, tb = sys.GinfoO# [1:-1] to3lude "Traceback (...)" header and#/ r q#**kwargspreturn =q.,` %, RtTwith support.swap_attr(sys, 'jlimit', 1000nolim = }_assertEqual(len(3o), 5+1. UQ=2), <O[:2]:$10;7-r?-2:s-t$>1del ;' i;:ys.NO = 2R3?[:3M;--30 m /-1P class Misc Cases(unitP.TestP#a # Check non-printing func 7s ir module7D\l_clear:couter(s8gmiddle* 30inn@u;* ): = 421/08 Y T"_,8?# Initial }ion: there's one localP1he u frame.C_ = tb.tb_next&: O1.f_Ss), 10# CsY.Is(tbELvariable dict should now be empty0kkho_stacksextract():  return traceback.ex t_stack() ( result = !flineno.__code__.co_first"Lself.assertEqual(][-2:], [(|(__file__, F+2, 'test_B', 'G_()'),N C1, 'IC Q ]) class TestFrame(unit.qCase): @def _basics( !):cache.clear hQ.lazy ("f", globals()7f =rSummary31, "dummy"4 f=m:`, '""" cases foru module"""' d|tuple(fkA&f,.   &r# Since .__eq__ doesn't support rp, the e5ity# operator fallIs to;_.5S& f&IsNone(f.locals)]_t, lookupgo=FalseA, f..(T>x  f. =explicit !Pine="c !* SBwalkD wdeeper(27Plist(0<JO1 = .D2 = y len(s2) - V1), 1 /@s2[1`,s1,tb6try51/0except E:ion*_, _, tb = sys.exc_infosXtb(tb: ,Ts = traceback.StackSummary.extract( eback.walk_stack(None))  self.assertIsInstance(s, =S8\!) :def test_k\p_limit(S!):(e?s =M!, T/=5Equal(len(s), 5 ookup_linescache.clear (sbupdate '/foo.py', globals(Yc#Wcode(,'method'_f+frame(c, &Hiter([(f, 6)]), lV=TrueNePs[0].5, "import sys"s up_deferred_~J~GFalsK , {}n'.-yL bfrom_lis45[('1, 'fred', '6')] [' File "N"p 1, in U \n(WY\n'],>s.format[{r_edited \6A(g[0] = 2 s22racG.|sH-2H2Ial_smoke?# For detaileds see the a, which consum%Esame # .<hE0loc.st_frame(c, globals(), {'something': 1}) s = traceback.StackSummary.ext(iter([(f, 6)]), capture_locals=TruePelf.assertEqual(s[0].+ a'1'}) def test_noXq(self):linecache.updat ('/foo.py', cVHcode,' 6od'+f+wframe(cP ?*r*LNoneoformat B_inner(k, v>BUa = 1PYb = 2oreturn 3I)B`walk_sG(/, limit=17 = G3, 4 U [' File "%s"[ne %d, inR9\n'5/ '*Obk_k = 3v = 4\n' % (__file__,0.____.co_first'Hno +?R], s.A()) class TestTException(unit. kCase):\smoke6tryu51/0ue^ e *exc_info4ys.(P!ex.*; :bpectedEw 4tb(iF[2])m P, excoause__.oontext0 TFalse_suppress_c:(exC"0]1?typ &tr+1@sZmb_from_'J# Check all the paters are ac5ed.XGfoo(Do 0B_ as e!.q>mit=1, lookup_lines=False, capture_locals=True)%self.exc = traceback.T Exception.from_e(Dte, limit=1, lookup_ expected_stack = r"cassertEqual(None, exc.__cause__. oontext0 p_suppress_c: exc_info[0]17typ @str('8S1]), 1)) 6def test(A!):6try 51/02kfinall:# ysz(.2P (*,^N5 = !(""+Xraise)uh oh")  6- 3 ~  K &SJSummary.ex^tvwalk_tb262])m d'(_,) , Ie.Z3i5 0} 4None, exc.__cause__) self.assertEqual(exc_context, exc._7 TFalse1suppress:expected_stackC  rinfo[0]1Otype41str8S1]), 1)) def test_unhashable(!):1uclass U Exception( .2Ua__eq__L{, other%)return True_ex1 =pV'ex1'?ex2)2)6tryc`raise @from ex1e C TXOS,_p = sys.(c = traceback.T $(*76formatted = list.&()'OIn(':7R\n', >oted[2]B1B,6]Qlimit?8Yrecurse(n:Jif n.&-1Nelse/51/0  L&10K| Sx!, &=5CP SbSummary.ex9%t(=Ppwalk_tb!v*Dnjlookup_linescache.clear 5 = k("uh oh" Gcode('/foo.py', 'methodf$+frame(c, NoneQ$tb'|tb(f, 6!e, e, tb, =Dr W {}}!ne ../Rupdat%globals!c.@[0].R, "import" ocR8.eHglobals(), {'s omething': 1, 'other': 'strC}) tb = test_tb(f, 6, None!0exc"raceback.T Exception(MT , e, tb, capture_locals=Tru_self.assertEqualMexc.stack[0].@W, {'s7'1'"A"}) 2def#no(t!):linecache.updat ('/foo.py', globals()5 = ("uh oh"3UHcodeK'6od'+f^+wframe(co 1<" )Hft|_headerm# do not print a 1 1 if exc_!ish# see issue #24695 ("haven") Plist( format()), ["I!: I \n"]) class MiscTest(unitk.kCase): warnings _DUMMY_SYMLINK = os.path.join(H@.get )),Z ` TESTFN + '-dummy-symlinkP/er \setUp# create empty  fpJpen(X, 'w+ wp.closeteardown_Vs = [ support.TESTFN ] self._warnings_manager = support.check!/(): .__enter__+_t.filter('ignore', '.* potential security risk .*',v RuntimeW!) 1def tearDown(!):>1fordown_file in $.2s26yunlink(+xit__(None,  stNoArgFunctions# test posix f& which take no arguments and have# side-effects;we need to cleanup (e.g., fork, wait, abortNO_ARG_FUNCTIONS = [ "ctermid", "getcw bouname" "s/getloadavg4Ugetegz%eu ogroupsJp>Cpgrpp^OsyncO ]Awn = k_ = getattr( , BA^"if7ais noth [+J(assertRaises(TypeError,b3, 1P@unit.skipUnless(has'getresuid')'Gsk.82()'6st_user_ids =E 4.Equal(len(:B), 3n0val! TLrGreaterSoval, 0'g'$?gid'' (+5 (;)"*EsQ$8**current_Y Is.^*P)o# -1 means don't change that value.j-1, -1, -1)) ' @unittest.skipUnless(hasattr(posix, 'setresuid'), 'Gq needs :.8A()')9@def '__exception(self):(d# Don't do this8 if someone is silly enough to run us as root.Kcurrent_user_ids =g(xif 0 not in 9*8newS(.[0]+1, -a;.assertRaises(OSError,!8, *h!) g$?gid_groupd3=bIsNonel2,*Q)?# -1 means d$change that valuek)^uZ:5 = /3gidUAinit9s "6os.62()"s# It takes a string and an integer; checkAit rq a Type9 # for other argument lists]H_[7 , =&s3, "fooE~ >, 3, object(L# If a non-privileged P invo it, it should fail with pVEPERM]if os.getu Z != 0:try@namev wd; pw=p_ `)).pw_'{8A KeyYT# the UID mayhave a pwd entryX raise unittest.SkipTest("need a pwd entry") Itry: posix.initgroups(name, 13<except OSError as eL self.assertEqual(e.errno, k.EPERMX/lsIfail("Expected{pto be rVd by 1") @skipUnless(hasattr(, 'statvfs'),4  '` V!s 8.62()'@def %_)BTrue~Fos.curdir)fl7 fp = open(support.TESTFN. RBafp.fileno())FJ9(8kfinallfp.close(StruncateT8UVS, 'w+W \A# we to have some datap fp.write(^bVZlush(fP}6, 0,7kP'), "Ot#()u cOwithc ')&fp ($ &1get os, 'execve', None) in os.oJs_fd. ()% the fd parameter%{{Lforkr0os.kFwaitpidILf o"s.r0ys.'putable,O_RDONLY #0pid1if := 0hdir(os.path.split(sF)[0]}7 ve(fp, [6, '-c', 'pass']zenvironMe assertEqual(os.waitpid(pid, 0), 3) finally:os.close(fp) @unittest.skipUnless(hasattr(posix, 'ppid'), "+q needs .2()"|P os, 'forkK0os.F@def j_^Vself)epid = 51if 6= 0-hdir(os.path.split(sys.executable)[0]3"+ve-:, [>, '-c', 'pass'],venvironUJelseZres =Kv`P_PID,,vWEXITEDN.assertEqual res.si_pid)register_at_Pwith $Raises(TypeError, msg="Positional args not allowed"N=os.ulambda: None|Aqmust be callvbefore=2rW afkin_child="threepMparent=b"Fiv*!bes,uv}ds~"pInvalid\O was[# Ensure a combinaC of ?Cnd iKpis an e.w*%, O3Ht .&''A# We actual rg s in their own process so a"toh # pollute) this one. There is no way to unregister for cleanup. code = """if 1:import os r, w = os.pipe()pfin_r,  % &4os._at_fork(before=lambda:_write(w, b'A')hBafter_in_parentKCK_childJEJ IB'),w DK F 2pid 1if := 0>B# Atqpoint, -Gers have already been executedJos.close(wa# Waitptell us OexitQx(Nr, 1W@os._;*(0Nelse>try with open(r, "rb") as fM1data = f. assert len(3) == 6, 4# Check  callbacks6jZ@[:2]i_b'BA'mlasortedA[2:]list(b'CDEF')| `.index9A') < V6EIofinall= *!'5"""_python_ok('-c', )@unittest.skipUnless(hasattr(posix, 'lockfB"*q needs .2()"@def #_Vself)f50supM.TESTFN,O_WRONLY |RCREATY Q3os. dy os.lseek(fd, 0ewSEEK_SEX\,F_LOCK, 4-# sectionZ =fy=F_UN /fdx, 'pread'), "test needs posix.pread()") def #_aself): fd = os.open(support.TESTFN,O_RDWR | RCREATW=6tryJos.write(fd, b'w'/"Qlseek"0cwSEEK_SEX).assertEqual(b'es',fZ2, 1)d# the first ) shouldn't disturb$le offset}%te}_|ynfinall@clos!) bP@unit.skipUnless(hasattr(1, 'Ov'),v v(7Y1tt2t3t5t6t6t8buf = [bytearray(i) for i in [5, 3, 2]]w v6buf, 3), 10 ;@[b't'!3t5t'], list(bufDRWF_HIPRIv_flagsp4^ ?os.{rPb'xx'h Pb'txxeA'4eDo().*T3"xxn[b'test1', b'tt2', b't3'], 2)  self.assertEqual(n, 10) % os.lseek(fd, 0, os.SEEK_SETN b'xxtest1tt2t3', posix.readMF100)Cfinally:}close(fdP@unitV.skipUnless(hasattr(a, 'os.RWF_SYNC'), "0` needs"}@def !_pwritev_flags()@fd ==open(support.TESTFNO_RDWR |$gO_CREA.trmCb"xxtnN@ [b'1 s T Y_fallocate'),`'.-#()"!5$oWRONLY& except OSError as inst(# issue10812, ZFS doesn't appear to 4I0so } Solaris-based since they are likelyV@haveq.{G33655: Also ignore EINVAL on *BSDX{is alsoGpoften uZthereg!if .errno == .d and sys.platform.startswith(g('sunos', 'freebsd 3net  Dgnuk$)"Geraise SkipTest(may failfilesystemsDJelse^Y |31106 -!()/ not setFPor in "nos[;_  ~ X1-42Y b!bOBADF0Odvisdvise()")  def test_posix_fadvise(self):  fd = os.open(support.TESTFN,O_RDONLY)26try?F`.fQfd, 0.POSIX_FADV_WILLNEEDRkfinallVos.close(fd) }P@unit.skipUnless(hasattr(g1, '1'),:":q needs % ")"7l_errno= 1-42 #0,x  except OSError as instq!if.A != j.EBADF*_raiseBos.utime in s_53fd *6 6_with_fd0`now = m.(r64Wf, None}&.assertR1as(Type? , (AGH*?nowG1Jnow) P(int('$, 2 3 Z0OValu1GP, ns=/, V4"0)T CZ0V\ & -g * 1e9)E H@)ollow_symlinks,  :nof;"o [W=Fals _/, gGg)f$Error, posix..utime, support.TESTFN, (None, now), follow_symlinks=False) RposixI(HBint(F Q,?now0@unittest.skipUnless(hasattr(, 'writev'), "+q needs .2()"$@def $_aself):kBfd = os.open@os.O_RDWR |$rO_CREATX=6tryJnMkpfd, (b'~1', b'tt263')F9.assertEqual(n, 10) %os.lseek(Y 0,wSEEK_SE) Nstt2t3',)AreadK;10)j'# Issue #20113: empty list of buffers should not crash Size =&*[]except OSErrordH*# =t raises1(22, "Invalid argument@# on OpenIndiana%IpassNelse qvsize, 0kfinall/os.close(fdF"oszR pRbuf = [bytearray(i) for i in [5, 3, 2]] G6Bbuf)Z 7['"],sCbuf]RAR@ <?idup'),8 Sbdup()'P9RpJ:]try:  fd = posix.dup(fp.fileno()) self.assertIsInstance(fd, int+pos.closfinally:U#fp*!) @unittest.skipUnless(hasattr(, 'confstr'),4 'Ec needs62()'@def %_)Raises(ValueError,T, "CS_garbage"_CEqual(len.u9PATH")) > 0, True Odup2 3 fp1 = open(support.TESTFN?fp2# +trnU2(fp1pU, fp2c:1;lC}Fos, 'O_CLOEXEC'), "45os.@requires_linux_version(2, 6, 23_oscloexec(]y?os._!, qRDONLY| ]N.addCleanup(uL, fd&PFalse'get_inheritabl,/oEXLOCKv$O_7 oexlockB (&WR4q@OREAT#OS$, mz@NONB0}(;if P"O_SH;"  ] fb<$0R (3,$: $Oossh! r!fd]_ `T) os.close(fd2) o51) if hasattr(posix, "O_EXLOCK"):'E fd = os.open(support.TESTFN,)-os.O_WRONLY| SH] VCREAT5 self.assertRaises(OSError,|/, }Q7FO_RD@NONB -,@unittest.skipUnless(:'fstat')'Cq needs p.42()'@def #_  fp<:tryBOBTrueufp.fileno())CG6(5 6Regex(Type .h 'should be string, bytes PathLike or integer, not'dS{, floatpkfinall+#fp8l3B* 4os.fsencodeBRWarnsDeprecation2S5 oarray( AFNoneSsMlistx mkfifo'), "don't have 2()"rhlunlink?v xTE- .S_IRUSR |BWUSRSexcept PermissionD_ as eskipTest('po six.mkfifo(): %s' % e) self.assertTrue(stat.S_ISFIFO(po? (support.TESTFN).st_mode)) L @unittest.skipUnless(hasattrG, 'mknod') and ]`, 'S_Ir1'),O "don't have K3()/8"@def _%):Q# Test usingA to create a (the only use specifiedFby POSIX).lunlink-'20 = ep|VRUSR EWUSR:6try  , g2, 0-except OSError as eN# Some old systems mallow unprivileged rs85usef#UB, orCcwdevice nodes?>In(e.errno, (.EPERM, UINVALgACCES)+ls\*# Keyword arguments are also /.  Tpath=I=U.=0<dir_fd=Non/$ P'), 'r needs 2()'LmakedevOR,6(.Hst = 1dev1devOsInstance(dev, int@(GbrEqual*0_QUmajor%JIr)t,:)~!, Raises(Typey,P2q, floatE>2 T(ValurOverflow)(-1`(in` m)`,`)~!, a `minor, float(dev)) self.assertRaises(TypeError, posix.minor2 T(Valu4OverflowC)De, -1) {# FIXME: reenable these tests on FreeBSD with kernel fixEif sys.platform.starts2('freebsd') and dev >= 0x1_0000:H skipTest("bpo-31044:CURRENT, () truncates "NRq"64-bitPto 32"}cEqual(}akedev(maju ),G Gr, floatN)I#P#I(;!=Pdef _4_all_chown_common(T",  func, first_param, stat_)A"""C= code for@1, fHKl uFs.""`check_\(uid, gid`{ is not None&F& =(3*C?A.st_?uid3guid = os.getuid(Mgg# a successfulOU call[O!, @*] G"-1)F k ifZ == 0 # Try an amusingly large//Kto make sure we handle{#3nsigned vQs. (L lets you use any>1uidk"like, even ifgpy aren'ffined.| L This problem keeps coming up http://bugs.python.org/issue1747858`4 O45911L15302Hopefully_@ in Z Qes it Zgood!m  Qart oKonly runs when as root.@O*scary people-QtheirKs9 :Abig_z = 2**3chown_func(first_param, big_value 7) check_stat(-own_func(figo-1, -1Y@uid, gid[!elif platform.system() in ('HP-UX', 'SunOS'): !# " and Solaris can allow a non-root user to chown()  M(issue #5113 raise unittest.SkipTest(" ping because ofvstandardr"l "behavior"Lelsebcannotf!, s OSErrorzself.assertR#s(&,E,), -F0, 0!g$hPif 0 in os.getgroups(*%( K # % illegal typesPfor tstr, float:ATypeot(uid)zp# t(@? skipUnless(hasattr(posix, 'Q'), "DPneeds#()1defd_#4 an if the file does3Qexist os.unlink(support.TESTFNg;.*, @h%) k# re-create> p_empty_ _0B_allr_commonXs9getx', None)fu^ &N{ = openUV, 'w':tryBfd =zD.6no(1F. n, fd,  getattr(posix, 'fstat', None)) Afinally:test_file.close() P@unit.skipUnless(hashlchown'), "+ needs os.2()"}@def !_Vself) os.unlink(support.TESTFN=# create a sym+3os.(_DUMMY_SYMLINK, N!._Aall_r_commonC B,uy lD^Pchdir]'].2()'"_^2os.curdir9..assertRaises(OSError, : &zlistdir(N|]+In`;]_defaultes# When H is called without argument# it's the same as?(. $)_bytes1 a 5i objec returned strings are of type9os.fsencode)Ob'.' \_likefor cls inarray, memoryview` ,Warns(Deprecation7ingZ7snames =S(cls(%c InX&Bs#a s((*!),smcFs_fdh |$fd U=_fdS4opeugetcwd($O_RDONLY'ddCleanupNY<, f(ueEqual(kcsorted=( (fMu# Check thatfd offset was re (issue #13739<T @unittest#.skipUnless(hasattr(posix, 'access'), 'test needs .()') def $_aself):.assertTruebD support.TESTFN, os.R_OK)) @P@unit\ _umask@old_J# =&0 IsInstance(8V, int-+D#strerror'),  7 .0Opipereader, writer+`os.close(/@tPos, '`2"q1os.2()"b@requires_linux_version(2, 6, 27.E zRaises(TypeE 5, 'DEADBEEFp;C0, 06# try calling with flags = 0, likew(5$ ='2(/wyEm Yos.O_CLOEXEC| NONBLOCK^ddCleanup(n?, r%w%PFalseKget_inheritable(r)0w0blocking]-Zfrom an empty  : this should fail, not M~J}&OS{^f, r, 1xa big enough to fill-up theeeither{# or perform a partial]6tryT1os.(w, b'x' * PIPE_MAX_SIZEsexcept NCpasstFcpython_only DT_c_limits(6# Issue 15989% im_ _capi self2.assertRaises(OverflowError, os.pipe2, _testcapi.INT_MAX + 1) OselfJUKLP@unitk.skipUnless(hasattr(posix, 'utime'), '*q needs .2()'@def #_!):h`now = L.(4Lsupport.TESTFN, None*S CType>G,, H(IOP2?nowO9Fnow)(@int(/$, :;!) p_chflags_regular_file(t$, func, target , **kwargs@st =Wstat(-VETrueust, 'st_#')&!# ZFS returns EOPNOTSUPP when attempting to set B UF_IMMUTABLE.Kts = st.k0 | .106tryA,vsDexcept OSz as errV if.errno != 6no. .rGcrmsg = ' D noted by underly49fs'GTest(msg Onew_WoEqual( ", \AO  fd|:pen3'w+%b e,FPERMkfinall.sbL 3os.J WlK . %, follow_symlinks=False" @unittest.'skipUnless(hasattr(posix, 'lchflags'), 'test needs os.()') def #__symlink(self):%)%pfn_st =Istat(support.TESTFN) -<.assertTrueEc, 'st_95os. ], _DUMMY_SYMLINKlteardown_files.append(3Tdummyl 4*Y_nofollow(path, ,qreturn .8/", Cws=False for fn in #, P |b# ZFS s EOPNOTSUPP when attempting to set UF_IMMUTABLE.< = 7.0 | <.C B6tryJS+fnI ;except OSError as errM if.errno != 6no.2Yraiseormsg = 'e S not ed by underlyM=fs'KTest(msgjEnew_)nA8 ? EeEqual( , f Q M T>,JT T ofinallS_environ( ifname == "nt"{item_type = strTOelse*Ubytes,@k, va.^+s( P(k), / 01v1P@unit. os, "putenv"), "require2()"zVPwith URqs(Value,M3os.I'FRUIT\0VEGE', 'cabbage1a'bbbc:b', 'orange\0VEGETABLE=cabbage') with self.assertRaises(ValueError):,3os.putenv(b'FRUIT', b'orange\0VEGj@i=ORANGE', 'lemon9\b]!@unittest.skipUnless(hasattr(posix, 'getcwd'), '+q needs .#()@def $__long_pathnames(q0dir$ =d-< -directory-0123456789abcdef0'curdir = osAbase @.abs(support.TESTFN) + 'A%' A=try)emkdir([u_os.ch jexceptP# Just returning noth instead of the SkipTest Fion, because!# /R results in  that case. Is /dev/null') as idg370s =.read().strip(y$3ret%rclose():tryTEidg_Xset(int(g) for g in(s.split()iexcept ValueErrorX :0if is not None or  Meraise SkipTest(" working H''"(# Issues 16698: OS X ABIs prior to 10.6 have limits on  sys.platform == 'darwin'import sysconfigd;_&_var('MACOSX_DEPLOYMENT_TARGET')#i'10.0'Pif tuplenn#dt'.')[0:2]) < (10, 6b 2) is broken? rb and 'a()' shouldurn the same#op, ignor0ordduplicates,Z;effective gid.E#10822/#26944 - Itimplementation defined whether? 4s() includeswrsymdiffzT.symmetric_}erence(`f)PTrue("Y4or E== {F}}#|s%' *at funcBllowos.accessK`os.sups_dir_fd $y@XI >. getcwd()O_RDONLY6  GI{(.TESTFN,bR_OK, '=fkfinall4N\fwG_chmodF in>DC1os. stat.S_IRUSRs5{ 4 | GWUSRvT/ S self.asse rtEqual(s[0] & stat.S_IRWXU,UUSR |sWUSR) finally:posix.close(f) '@unittest.skipUnless(os.chown in os.supports_dir_fd, "1r needs  $2>2()"@def 2_Ff(self)A.unlink(bTESTFNHcreate_empty_file23Bf = Ropen( getcwd(),O_RDONLYj/tr? m,&QgetuiRros.getg  &=fY.i=+Qwith a., 'w') as outq.write(Ysline\n"%5%s1  t/s2, ,6elf.asse_1, s2["KNone9^%RaisesRegex(TypeError, 'should be integer or ou, not',;88,#[]float(f) (Overflow'%f10**20l.@utime\>o5`now = .(T- ,V;8 2j{ ?nowU(j)^) F self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), dir_fd=f) ](None, now)]@?"x"\(0int4), H#  e (& - * 1e9)",y)/s=)) Lb# try h and follow_symlinks together6Rif os0 in +s_@:8>tryx o=FalseMexcept ValuWt# whoops! using bothD noted on this platform.zFpassdkfinallsclose(f @unittest.skipUnless(os. d0, "0d needs2=2()"@def 1__D(,)3f =Ropen(getcwd()O_RDONLYW 9i @ + ''c', srcu=f, dstiPermission3V as eJgTest('): %s' % eW+ls@ # should have same inodesfSEqual1KstatN)[1]/8Nl und dSmkdirQQs>FKjOdir'B 9%) !$r 5ion$ posix.close(f) support.rmtree(TESTFN + 'dir') 4@unittest.skipUnless((os.mknod in os.Bs_dir_fd) and hasattr(stat, 'S_IFIFO'),X "i requires both ?.=Xd t@ for2()"@def L_u(self):# Test using )at() to create a (the only use specifiedHby POSIX).{.unlinkdjmode =|VRUSR EWUSRa`f = poRopen( getcwd(),O_RDONLYq6try9 , R, 0, t=Hexcept OSError as eX# Some old systems don't allow unprivilegedX rsy5use#Ydevice nodes>.assertIn(e.errno, (.EPERM, UINVALfACCES)6;els\ATrueS3 TP).st_W]ofinall0os.", SSneeds:=87 Pwith G `, 'w')1koutfilXq.write(cline\na#b7 2a <read(b, 9).decode(encoding="utf-8AYEqualV, resy"\=b 0os.A&AEI9 ym| # ''  J 9Wf Aposix.close(f). @unittest.skipUnless(os.rename in os.supports_dir_fd, "2r needs  $2?A()")f@def 3_Hq(self):"C.unlink(bTESTFNI'create_empty_file2 + 'ren':f = posix.open( getcwd(),O_RDONLY76try9u,.S, srcu=f, dstjoexceptm.QUraiseeOelseaKstat) # should not H 5ionRofinall#close(f)l 0sym;m@ni o;l C #',8*=f.assertEqual@read8 _O)iV'q &?;O7delO9&+A`[@ M -0R[s(OSErrorB ?omkfifoe&?eeP H\5 x ,1%stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)  except PermissionError as e:)4self.skipTest('posix.mkfifo(): %s' % ea4assertTrue(bSFIFO(C (support.TESTFN).st_mode)OzfinallyBclose(f) requires_sched_h = unittestUnless(hasattr2, '.yield'),J"don't have Fculing " affinity4set8  P@h@def H[-()# This has no eQconditions (at least on Linux).\D_]@get_priority_max@ "_=#() aRound-robin usu"interest0>8iesBl = SCHED_RR.%lo3 bin(pol~]/hi/ *ax/.IsInstance(lo, intV'/hi'GreaterEqual()&loO# OSX evidently just returns 15 without check6the argument8 if sys.platform != "darwin"Raises(OS,vZV, -23J&#axJ1setuler'), "caUchang,er"rand_set@_\parampossible,Qs = [z for name,&3 in3__dict__.items('+ !ifHp.starts"("1")]1Nmine&(0h0In(9 1,trX_arento os.getppid(QDIif e.errno j.EPERMr;els parent, possible_schedulers) self.assertRaises(OSError, posix.5A_get >O, -1A!Zparam=, =k/(0eIsInstance('priority, int) # POSIX states that calling A_setIV() ornPa process with a3uRpolicy otherln SCHED_FIFO^'RROis implementation-defined: NetBSD and Free can return EINVAL.K if not sys.platform.starts(('freebsd', 'net 5)):?:trys(0, mine, ?5 9&5 /sexcept {^ as eif e.errno != n.EPERM+r IEBI,NOTypez%, {FNoneKNJ&43B (j1Jmlarge = 214748364700h,7FOverflowGY Ir_c/=-=@unittest.skipUnless(hasattr(L2, " rr_interval"), "no funcB"@def P_5(8 ^  G# This likely mean is only valid for(#e3theo$RRer in effect+?NSOKaTest("@work)#esxwqmr, float/# Reasonable constraints, I thinkZGreaterEqual(interval, 0.) self.assertLess(interv&A1.) ' @requires_sched_affinitydef test4get([!):&mmask = posix.J.0IsInstance(@_, set)GreaterEqual(len/O), 1.Raises(OSError,7, -@for cpu in Hwcpu, in , . ,$1 << 32 s15if bJ > 1 q# Empty$s are forbidden DV.pop(!0,N)n: V; , 0, []~C_ValueL F?-10I OverflowLo1<<128O  $-1!qrtld_co},ts# check presence of major RTLD_* :VOLAZY?NOWoGLOBALSLOCAL@unit.skipUnl hasattr(os, 'SEEK_HOLE'),M "D needs an OS that reports file holes"11fs_+Even if the@system doesn'[U#2bOS sup~!itEd# will be defined andahave aeistent# behaviourQ# os.hDATA = current*6tio*\` = end* .with open(.TESTFN, 'r+b') as fpfp.write(b"hellozfp.flushHsize = fp.tell2fno+noJtry Qi`range(`"  i,Olseek(fno, `)L@HxO O self.assertRaises(OSError, os.lseek, fno, sizeSEEK_DATA) self.asseNJHOLENsexcept - :k # Some OSs claim to support T/ @but it is not true.&For instancehttp://lists.freebsd.org/pipermail/-amd64/2012-January/014332.html|r unittest.SkipTest("!Qd!") <@def *p_path_e 2()1""",M functions that call @), providing two filenames in their EAi@for 321("r?", "replace Wlink" = getattr(os,Jj, None2%if!Pcontinue22dstnoodly2",O{.TESTFN8>tryc('doesnotexist;j', dst6H?as r)gOIn("e -> '{}'".format(t, str(e)}XUbreak ?elsfail("No valid5 Waos." +with_null_characterKfn =1fn_BNUL = fn + '\0' addCleanup("0.unr  6(fnAfd =sY  oQValueQ@Wos.open(gO_WRONLY |O_CREAT) # skfinall d os.close(fdFalse(os..s-<Pmkdire=j!s, 'wb')LKstat@ 3Obyteos.fsencodeLQ4bor):   fd = os.open(fn_with_NUL,O_WRONLY |CREAT) # raises Euinally:if fd is not None#os.close(fd)<self.assertFalse(os.path.exists(fn)-R(ValueErrorwmkdir, =j!s, 'wb')LKstat class PosixGroupsTester(unittest.qCase): def setUp(&)R@if pG.getuid() != 0 n \@Skip` ("enough privileges"!ifhasattr(iq, 'getg'i 6eed= h sys.platform == 'darwin'0(2){broken on OSXj>r.saved_, =&()stearDownv s6.K p\elif Y?inio@name wd pwn P).pw_'E$X("-, 3[0] @=skipUnless( ,qu"c needs{)(_q# find missing k~g = maxn@ or E + 1JFgSIn(g,)_B/')^8(]\2forQ s in [[0], list(range(16))]Qs eListEqual()Smain('trpsupport.run_(X>er,efJeap_children Aif _D!__ __#__() """Unit  s E contextlib.py, and other  managers.""" im asyncio 4systempfilehreading from contextlib import * # Tests __all__ from test$0sup, 3weakref class> AbstractContextManager(unitJ.bCase): defc_enter(self):XDefaultE"a48V__exit__T{, *args'+super()./)!m9 = ).assertIs(/Pc__(), )V Cis_a5MissingExit(BpassjWwith Raises(TypeErrorp/n structural_sub?ing7FromScratchh_ %areturno=exc_type, pvalue, _eback\FNone-(tTrue(is(/, 8% :5 'c"No h? = iIFalsj_Q?xit  c,%l_plainUstate = [] @8{woohoo(E.append(1Fyield 42G 169993VfZ as xtaEqual(KV, [1]Ec3elf>)[x, 42$xeDc, 999]t 5_finallyo^:try1 .RZeroDivisionError):' with woohoo() as x: + self.assertEqual(state, [1])-_x, 42(D.append(x raise ZeroDivisionError(*r, 999]) def test_contextmanager_no_rej(N)@*F JWwhee(,Uyield&bctx = (.__enter__%# Calling __exit__ should not result in an exceptionUFalse(ctxfHQ(Type7%, ("foo"), None)! Qtrap_0_af_throw-ZY-:tryf* lg? l/Ra%s(3rdRuntim3EKA LJT  DTU = []H  EU1+u5 42t*|eq/ ue.args[09GR  )8  F(999a eR fBv_stopiter op_exc = StopItera v('spam'6 z (WarnsRegex(DeprecAing, ""O=xw#3{K$ E. tIs(ex, GK;els6ifail(' was suppressed'|_pep479code = """\ from __future__ import gen!or/&4lib&manager @contextmanager def woohoo(): yield """locals = {}exec(code, )#W# =!"['5'] #stop_exc = StopIteration('spam'L2tryKwithdraise _pexcept Eion as exZself.assertIs(ex,GOelse6ifail(' was suppressed')wtest_context_do_not_unchain_non_i- ep# s(@Kkissue296927 ^ >c -~RuntimeError('~ :C  from exc *A sZeroDivisionxY Qtype(ex), v2Equal(ex.args[0],  ?IsInstanct.__cause__, B@.,  UB) jC$ZIsNonA.|_createsmattribO2G**kwjvdecorate(func $for k,v in kw.items+0setmJJ,k,v$"preturn k@hfoo='barf@baz(} """Whee!?baz rW`baz = . .qbaz.__nam-G'baz-Sfoo, -@ort.requires_docstrings! a'_ 80doc}iUstring_given_cm_docstring(self): `baz = ._create_contextmanager_attribs()(None):4assertEqual(baz._j__, "Whee!") 0def test_keywords# Ensure no $ arguments are inhibitedQ@mawoohoofp, func,Ows, kwdsHoyield ,WWwith X2=11[2=22^2=33a=44) as targetmn 7%0, (PKF<44);nokeeprefzclass AgBpass|u+Ga, bU6a = weakref.xabb Is;O(a()# b#A(), b=A() xparam_error|* Raises(TypeEy K@O3, 5D-:_instance! # Issue 19330: ex " Cs have good qoB = c3'6objt 4objA(, an @statn%[]j HC I.append(1fx = C( 9F, []$ nxJy FFx, yAself.assertEqua!l(state, [1]) def test_closing_error(self):"&7U = []vclass C$(NIeAI.append(1)Nfx = C(.assertEqua]$Wwith )Raises(ZeroDivisionE7ing(x) as y&XFx, y|#U1 / 0 5o 3 NullcontextTestCase(unit.P&_n5 [V Epassc]RcJc_in 0Is( c, c) _FileCWithOpentfn = tempfile.mk +trf = None^o_tfn, "w"f*False(f..edf.write("Booh\n""I?TruH@ r.d /f.read(), 5 zkfinallsupport.unlink(tfn)vOLockvboilerPlatb, lock#edj &(Fed()w Q " 9"\ ( }&  n hh6Aing.%F`1.  iRE;. j&k_is_ownnConditio r*v!) *areturn..Semaphorhreading.Semaphore() def locked():i.acquire(False$(>x.releasYqreturn > `Jelser/ETrue.self.boilerPlate(s,!) (testWithBoundedSemA? = threading.1  class mycontext(CDecorator"""Example dion-compatible @ manager for uaing"""started =exc = NonUcatch!6__enter__(.X ^#c__exitIc, *excb,.1excJ.# 8LTest2P(unit.aL@support.re8s_docstrings!:_instance! # Issue 19330: ensurCs have good o!cmd& =  ._!__)8obj (6assertEqual(obj?(, a _5R,or xEwithxas result82Is(",5+H(}_ *+`exc, (,6)) 0__exception= RaisesRegex(NameError, 'foo'; 9rI C(BxsPIsNot6Y*#F[0],ac0 = m`@NR  (nemassertTrue(context.started) Vtest(self.assertEqual(c9exc, (None, A)) K@def K _decorator_with_exception(Z!):-{XS = my "()L@0a(D)W Is +ETrue) -raise NameError('foo' }R0usRegex(6", 7[(sto%Isvexc[0],ing_methodpclass T*object): o, a, b, c= 0E = a_b = bVc = cq# theses are for argument passing when used as a d" =K.F1, 2=+Oa, 1$ bHcy_ p'a', 'b/c' _a, 'a&bQL @c, 'rLa=1, b=P8*_typo_enterCD R0__uJ,__Lf6Cexit5k, *exc\*;<j(Attribut F4 de!hxV'Rfthing' [', 1g, 999] # Issue #11647: Ensure the  ed function is 'reusable'k  _ else6 ZTestBaseExitStacks! =k @support.requires_docstrings_instance! u'19330: e&  Cs have good o!cmd! =. ._!__/>obj&(4objE(, mno_resourcesLwith ZScallbackOexpected'((), {}),/1,2), dict(example=1)T%a&`result ?(*args, **kwds 0""" metadata propagae9""" f (VTA as "nFfor F in reversed( 6!if5P and ~ T"f. *,  9#elaX" Lelif kwds:  f = stack.callback(_exit, **kwds) 2]else:&LDself.assertIs(f, t (for wrapper in(_s Z@b[1].__ ?d__o=NotEqual(6rCEname@2.__ IjIsNoneG8docFEresult, expected) def test_push(6)exc_raised = ZeroDivisionError@D_XP_exc(7@typemc7_tbW4j 2s`suppressb*1{detailsYreturn True/ok}s (#class ExitCM(objectq_init__p, check +!& =-t'VSenterWLfail("Should not be AJed!"Tx (.Qwith *Y_nR() asR*okK=O.q[-1][1]4_DDcm =h/cm%0.__ E`_#k%/, G;excl u u i $i1;1/0qcontext.?Tes. E/?!.Jnd(1A , *exc_detaikls): result.append(3) "U = []cm = TestCM() with self.exit_stack() as u@!.callback # Registered first => cleaned up lastlPdef _k(4:assertIsNotNone(K (.enter_context(cm$L(K_s[-1][1].__yL__, Ee2b1.^bEqual(*, [1, 2, 3, 4]test_close(;9 )%1 B< 6pop_all83 2new" =. P F Z. |N_raiR%s(ZeroDivisionErrorW7[1" .push(lambda *exc: False+/21/0#uh|uppressE;Tru exception_chaining_referenc# Sanity check to make sure that ExitS M matches# actual nested tatement(aclass :ExcH__init__>[, excz]Pexc =!DE@areturn=<,o_detai4IB.exc RWithC<outer, inneY$1 =  #@" =H# def __enter__(self): preturn  def __exit<, *exc_detailsJ>try_nQraisebi.innerh!oexcept=eouter >class SuppressExcAV2ypedd.saved)7 = 7FTrue J`with RGExc(IndexError +WithContext(Key4, AttributeDH]((,OValu[ 3U1 / 0 0 as;  .assertIsInstance(exc.__cD__, )_q= I , O0# Ieptions were s)ed/ ~=Nonz Oelsefail("ExpectedC, but noQ was &d"X# Check the 1sh_exc =v 5[1]1 G', *5, ZeroDivisionEBtestZion_chainingJ# Ensure + matchesreference behavioutY# 1a ) PJSnonlocal {Kl"pstack() Z{`.callb+ ,264  :Xpush(y[V self.assertIsInstance(exc.__context__ , AttributeError) # Inner exceptions were suppressed/Eself~?Nonz v^else:Ufail("Expected Index, but no was raised"X# Check the io_exc = saved_details[1]% c;l, ValuM5  , ZeroDivision!) ~def test_exiT_non_@ing(m)E# http://bugs.python.org/issue19092_c<8H l3~6D*exc9 ?eturn TrueA6tryRPwith .stack() as -1`.callb+lambda: ) -,V6$ E:excvT<J>3KeyEQXpush(D-)]6z-\8Z v_correctyQ20317d?@umanagergets_theho_right ZJyielkfinall+ fexc1 =)(1223344j# The  already fixes!, so prior to9#-p, ExitS` would try*fix it *again* and get into anEinfinite-referential loop) z 4Tenter(ntext_right(exc4))  stack.enter_context(gets_the_right(exc3B.2Braise exc1except E`ion as!:!self.assertIs,$4 %%.__131 =2=$ I1IYNone(8excM !) Mdef test_exision_withTsting-(I)# Addresses a lack oO coverage dis ed after checking in a# fix for issue 20317 that still ained debuggBUcode.CG_nested(inner_exc, ou7excw6tryE >aofinall5h5& =(Iexc2Jj  Iexc55U  .  ()i .callback(*oH4s49 295c2 >:Z1 = = Ik H j  @body0ept@supp_ x/(*exc_detailsreturn True)5Xpush(k@51/0wIndexErrori:excgvfail("Expected nof, got E"Elion_chaining_suppress(self): Pwith .exit_stack() as )0 .push(lambda *exc: True)S* ?1/0)q{}[1]) U def test_excessive_nesting# The original implementation would die RecursionError hereo!for i in range(10000cP>Pcallbe Belf.Z1Is(.+s[-1][1]Odont_rerr_Runtimhttps://bugs.python.org/issue27122[jUniqueExcep@( u/  5e@&umanager{second(F:tryuyield 1?)5pt  %)8 .b("new Dion") from9 _firstU6exc|1 shbe caught by d 's!# handler which chapised a !g6.<=1 0ezerr_ctx@.es. }(+/.$U ("please no infinite loop."lSxc = .U-Y3IsI\(exc,4$._{$__@C@Nones? 7oause__5h%,{ k" ~TestExitSEBase`, unit.CCase.5 = ExitStack  class TestRedirectStream: r!_sq = NoneKorig @support.requires_docstrings!def test_instance!q(self):"z# Issue 19330: ensure context manager Cs have good oM!cmd0 = k. ._#%__?obj+())NassertEqual(objN(, {)U5no_|in_initfdout = getattr(sys,  Z?Is(X #, f g toling_iof = io.S6IO("msg = "Consider an API like help(), which prints ly to st"-BwithL2F(msg, file=6 !lws = f.getvalue().QpHdls, msgenter_result_is_targeu- H as `Belf.&8Is((<, f cmreusableNwrite_to_.0g !"Hello", end=" ".cb oWorld!Z  M\  ?\n"oentranN !QB4ys, self.orig_stream), orisdout) s = f.getvalue(,elf.assertEqual(s, "Hello World!\n") class TestRedirectStc(, unittest.qCase): r<7 = O&LQ = "si"?err9?err:errSuppress( @support.requires_docstringsf@def *_instance!q(self):"# Issue 19330: ensure context manager Cs have good oM!cmd0 = ._%__u7obj3 4obj>(, _)no_result_from_enterEwith (VError) as 2D2xIsNone(,exceptionq9pow(2, 5), 32qoexact_tBType s^len(5Z_hierarchy oLookup`'['[50]_other JRaises(ZeroDivisionp ;1/0no_args,z}multiple) /, rz )E2cm_is_reentrantCWignor;%$(E6B 5 2pas1 /d$ # Check nested usage] p`outer_einued = Tru:((? ) if __name__ == "__main__",E() """Basic s for os.popen(Particularly2 useful for platforms that fake popen. """ import unittest from  0sup")os, sys # TestVcommand-lines get down as we expect.1o do thiecute: # python -c "yys;print(sys.argv)" {rest_of_sr}[Uresults in PObeing spawned and R0theYA lisWe can then eval()  Y1 of,IPsee wSPeach c was. =] exable if ' '"': t= '"' ++ # quote embedded!ce0cmd class P(.qCase): mdef _do_As(self, Q,2ed)cmd = '%sQ1%s'n7=2% (h)&with os.P(cmd);p~Kdata = p.read(=Rgot =#)[1:] # strip off5[0]n.assertEqual(got+'4CRaises(TypeError,/y"foo bar",[@", "_'_Q"spameggs" "silly walk"'x 3,4.Qa \\"@d\\""3'a -+' /p_children()return_code("exit 0").close(), None ifname == 'nt' [(42\&42ZOelseL+\ << 8contextmanager  "echo hello"f fd&"6<\n"iterating{<e(f), [{]|keywords{ Dcmd= , mode="w", buffering=-1=Ppass  __  __ "__main__"6 ()AestsPextenunpacking, starred ressions. doctests = """ Unpack tuple >>> t = (1, 2, 3)a, *b, c = t == 1 and b 1[2] c 3'ETruejFlistil = [4, 5, 6]-iF = lN4Yf1 ^|implied*a, = 7, 8, 9U[~ Mstring... fun!Z'one'N7'o''n', 'e'\long sequency0a, b , *d, e, f, g = range(10(*))%B(0, D[3, [,B Ohort ;i2genericcclass Seq:Gk def __getitem__(self, i)&*if i >= 0i < 3: return iT.raise IndexError! =(b}`in for statemen6>in [(1,2,3), (4,5,6,7)]Tprint1... 1 d[14 [ % 7a:in d[z]J5R 7, 34w4Multiple targets=m%d[e`Assignl! u9ing@b, *Ai3[F, 4]82 = p!*c29B0], v) Set display elPs\sorted({1, R0, 4}ih],11, ,I`Traceb(most recent call lastO$ YAType : 'int' object is not iterab'?Dickwds = {'z':'w': 12}D 'x`, 'y':u **; }.3s()('w', 127 'x  By', gz', 0)`2**{c}d.3}h]3]]' 3T44R{**{}h&{}%a = {} >>> {**a}[0] = 1 >>> a 1{} Q{**1}Traceback (most recent call last):'1...TypeError: 'int' object is not a mappingk/[]l.?lism%len(eval("{" + ", ".join("**{{{}: {}}}".format(i, i)0....for i in range(1000))_2}")?0:1, **{0:2}, 0:34{0: 4} List comprehension elem}iunpackF a, b, c = [0, 1, 2], 3, 4#[*$]'&]lD@a, (>), {5}, {6: None}, (i r7, 10))XkBitem' Bin lNcSyntaxPiterable @ canVpbe used 1![*])g?'a'[+wGenerator expres in funct@argus@(*x x(!5)#3) f 7^ nvalid shdict(*r[{1:2}]a R  Iprint(*[1], *[1 2 3 Make sure that they don' Arrup passed-in &s.`def f(x, yyvoriginal_N = {'x': !If(**%U, y=2Q( $KA Now}some failuresPe raieCs are right9keyword _from colles.abc import MutableMapping >>> class CrazyDict(Muta'!):)0...0 def __init__(self %t.d = {}<D?terDfor x in MB.__i0pUif x == 'c'L['z'] = 10%tyield xsgetitem?, kTretur4[k]GO3lenKH1lenn4.d)BJs?, vTkvGO?del3del [Ychr(ord('a') + x): x range(5)E7eT2**dTraceback (most recent call last RuntimeError: dictionary chid size during ma! <}d#3f(**kwargs): print(^#TOverridden parametersf(x=5, **{'x': 3}, y=2Q ...4Typyf() got multiple valueskeyword argum8'x'z5+q /2}n1O**{1: 54<s must be sts Unpacknon-sequenceXa, *b = 7Vcannot uq nHble int object too short, c, d, OSeq(" ValueError.: not enough values to unpack (expected at least 4, got 3) U%@ing sequence too short and target appears last >>> a, b, c, d, *e = Seq() aTracebmost recent callE!):FQ ... V_Error3awhere the test forlong raises a differkind of eclass Bozo(Exception0...Q pass*=RadSeq/def __getitem__(self, iUZif i >= 0Zi < 3K%return i!elD/==:A/set:QIndex; Trigger code whilez6an 8# ( r, wrong)Ea, *Bf($#._E_ex. Now some general starred expressions (ofail).@*d, range(10) # docu:+ELLIPSISAFRSynta_: twoin assignmen[Go*c] = |/*aPmust be 8` list BFuple/*aDcan't use 1oOx = iSsize constraint.9s = ", ".join("a%d" % i ip<<8)) +, *rA <<8 + 1)"ompile(s, '', 'exec'/OxError: too fmany expressions in star-unpacking assignment >>> s = ", ".join("a%d" % i for i in range(1<<8 + 1)) + ", *rest =52)"Xcompile(s, 'test', 'exec') # doc:+ELLIPSIS7Traceback (most recent call last):'A ... SyntaxError: too  (there is an additional limit, on the number of]Pafter 0 '* ', but it's 1<<24 and yit takesuch memory.) """ __+s__ = {'Ds' :*qs} defQ_main(verbose=FalseAfrom# import sup. r1_ex$0S.run_('#, y) if __nameA= "_2__"9 pTrue) -BEGIN CERTIFICATE- MIIDWTCCAkGgAwIBAgIJAPm6B21bar2bMA0GCSqGSIb3DQEBCwUAMF8xCzAJBgNV BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u IFNvZnR3YXJlIEZvdW5kYXRpb24xEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xODAx MTkxOTA5MDZaFw0yDMTcx I/ YCCASIwDQYJKoZIhvcNAQEBBQADggEP ADCCAQoCggEBAKvvsX2gEti4shve3iYMc+jE4Se7WHs1Bol2f21H8qNboDOFdeb1 RKHjmq3exHpajywOUEgne9nKHJY/3f2phR4Y5klqG6liLgiSpVyRlcBGbeT2qEAj 9oLiLFUXLGfGDds2mTwivQDLJBWi51j7ff5k2Pr58fN5ugYMn24T9FNyn0moT+qj SFoBNm58l9jrdkJSlgWfqPlbiMa+mqDn/SFtrwLF2Trbfzu42Sd9UdIzMaSSrzbN sGm53pNhCh8KndWUQ8GPP2IsLPoUU4qAtmZuTxCx2S1cXrN9EkmT69tlOH84YfSn 96Ih9bWRc7M5y5bfVdEVM+fKQl3hBRf05qMCAwEAAaMYMBYwFAYDVR0RBA0wC4IJ bG9jYWxob3N0TA4IBAQAtQ8f37cCEk7/rAcbYR53ce3iK Vpihb0U2ni1QjG9Tg9UIExkIGkwTiCm7kwQL+GEStBu9AG/QVrOjeTriRiddhWkk ze8kRaI3AC/63t6Vh9Q1x6PESgeE4OtAO9JpJCf4GILglA789Y/b/GF8zJZQxR13 qpB4ZwWw7gCBhdEW59u6CFeBmfDa58hM8lWvuVoRrTi7bjUeC6PAn5HVMzZSykhu 4HaUfBp6bKFjuym2+h/VvM1n8C3chjVSmutsLb6ELdD8IK0vPV/yf5+LN256zSsS dyUZYd8XwQaioEMKdbhLvnehyzHiWfQIUR3BdhONxoIJhHv/EAo8eCkHHYIF >ENDS# regjr0SAX 2.0 # $Id$ stxml.sax make_parser, ContentHandl\SAXExcep , SAXReaderNotAvailable, SAXParseException import unittest from mock try: make_pGQr() eK SAXReaderNotAvailable0# don't try to g this module if we cannot create a aqUraise.SkipTest("no XML+4s ax"")pxml.saxTutils XMLGenerator, escape, un quoteattr, \XMLFilterBase, prepare_input_sourceaexpatr*R .thandler*feature_namespaces/:xml[IS, AttributesImpl NSL$ion By+O, StringIO-dcodecs$gc tos.path shuVN0supt.yfindfile, run_, TESTFN _zdILE = / ("f.xml", subdir="xmlidata"):O_OUT>O.outB0.en("utf-8")4!l %:0Uni=ECRError7@ is 3}o^0utf Ss_nonascii_7s = True if?sq1 _.FN_UNICODE ENCODING(a, Type)ne# Either the system 0ingwNone, o%DY"be7_ed inR.9AFalse require$.skipUnless(_,%#'RaQ non-#s ') ns_uri = "http://www.python.org/xml-ns/sax /" class XmlJ(CCasedef verify_empty_s(self, )o.assertRQs(Key,.getValue, "=-<oByQNamC%;B+~ ByI!__getitem__? `Equal(&s7Length(), 0J 5 /s(), []) self.assertEqual(attrs.getQNames(), [])  02len4O), 0(pNotIn("Y0", s(BlistQ.keys() Qcs"), Noned 3Q, 25)Oitem@valuMfdef verify_empty_ns(d):+}Raises(KeyError,Vh, (ns_uri, v) F !By`, "ns:"F@E. ByL+P__get/__I`Length />^0n #x m < : _w, "1i/"f 5(6.-O"valM Q3/, 7 D?e A98 ~q) 8+? I>^fEqual(attrs["attr"], "val") self.assertEqual((s.getQNameBy(>3),  def xml_str(doc, encoding=None):b%if@ is ~return doc,'\n%s' % (t,F)Zbytest, decl_2F=... 6... =  1!).te'xmlcharrefreplace'Pmake_LOfileSwith open(TESTFN, 'w'ing, errors=V as f2f.write(! ) class ParseTest(unittest.4CasGdata = '!' tearDown( support.unlink)8pcheck_p;7, f>@fromp.sax imJ ,x`result = StringIO(*(f, XMLGenerator(2, 'utf-8')0 +%0(),,JI"stQ_text s = ('us-ascii', 'iso-8859-1,W $16(F16le b/5forf5 in sc+Sy")@E s1 /r/)kaf :,y gA( MNp# UTF-8i@defa, US-ASCIIcompatible 7^H 16+autodetectedMVTJB!IO .f,`.UN)  with open(TESTFN, 'rb') as f: self.check_parse(f)$ BytesIO(xml_b (#data, encoding, None))LPmake_8Ofile7  Z7# accept UTF-8M5BOM0 'utf-8-sig', ', 9    6]declared iso-8859-11uC# fail on non-incompatible !Oout $}<assertRaises(SAXEx[Jion)-U%ij7b0'} 41f) def test_InputSourcs{ 2butexplicitly specifiy'i8 = "@.setlStream#E'(' O a=eclose_sfbuiltin_! = Qobj =0Amock5g(*args"nonlocal fileobj  fileobj = builtin_open(*args) #sreturn 1  with mock.patch('xml.sax`utils.R', side_effect=0j%):Ihmake_xml_g(self.data, 'iso-8859-1', None0 assertRaises(SAXExceptionko1check_parse(TESTFN[%VPTrue(obj.closed) Gdef IaString7, szSfrom " import {2 result = 6IO(0(s, XMLGenerator(8, 'utf-8')6SEqual+.getvalue(),A_stryIBtest0Q_text4encodings = ('us-ascii',]  166F16le 6be'Dfor s5 in s`r M B=T  #\bytes$# UTF-8 is defaw, US-ASCIIcompatible 74H 16+autodetectedUVW8T jH dlYpC@# ack?5BOMeT8-sig(b KUdeclared#El# fail on non-\7 intOout \P.-2 class MakePrTest(unit.CCasegG.r2Creatingrs several times^a row should succeed. # xA this because there have beenuures of )6kin# beforeW;Gp = 9from xml.sax import make_parser 8p =%()from xml.sax B_ # =7 # # saxutils testsd7= class SfTest(unitn.aCase):q escape1def__basic(self46.assertEqual(-("Donald Duck & Co"), Aamp; o?allm"),V Y"<3o>")_extraHei på deg", {"å" : "å"} =+B"unf/  D_-(   g_/!("v=?amp&Afoo;L& : "splatL" " (quoteatt*0 +''vsingle_gUd *'Includes "double" /s'a /'\8-\'Y""'' \8-\"Y_ self.asse%rtEqual(quoteattr("Includes 'single' and \"double\" ,os"), /"\G&=;K OQ\"") Q0# = make_parserdef test_q(self): # Creating a < should succeed - itfall backAto the expatread~^8p =r(['xml.gs.no_such']) class PrepareInputSourceTest(unit.bCase):\setUp.file = support.TESTFNwith open<-, "w") as tmp,tmp.write("This was from a l.rtearDow^yfunlink|;`byte_sYm%Creturn BytesIO(bPis a 6 6 ScharacterX StringIOX;]checkContent,&2, cassertIsNotNone()%v!.r&()W1)p.close(PL7_A# Ifst 'n  -%a Ivuse it.Hrc =;^trc.setCS*)=0pre_Pare_i,_F(src)Ej0ne(4@.get:tY0 0    / &that does not have #3 bu/+} , #]RVsa0 = %   [system_id[has neither no!O? IDce(src) " self.assertIsNone(prep.getCharacterStream()) 15checkContent5DByte0,04 b"This was read from a file.") :def test_string(v!):M# If the source is a +, use it aystem ID and open it.H0 = are_input_Ts. 1pbinary_6 0~-like objectGEbyte5#j?eamGPmake_EQUf: OtextO.M c]R.JW   V[@ # = XMLGenerator class XmlgenTestxl_basicresult =!ioK(Ygen =o(3 #.startDocum1Ele"doc", {}$9end" \SEqualvalue(),xml("?c:1d"?gene.Ss("huhei" endDocument(C) self.assertEqual(result.getvalue(), $xml("huhei_scapexaF<&h]-B<Oamp;i oattr_ef{"a": '"', eN*;"'"*veF/\"H2o\n\r\tK'? ^ a='\"'>"*o"$ +} encoding s = ('iso-8859-15', 'utf-8 i-sig',{+$16,F16be /le7 $32+&327V32le'Dfor 1 in dings:   result = self.ioclass() gen = XMLGenerator(7, encoding= ,) ;.startDocument[ 1Ele"doc", {"a": '\u20ac'}.characters("&"%9endX" assertEqual.getvalue(),0,4xml(''89def test_xmlgen_unZPable(^%):us'ascii'}2gen V1 ! .0 €">  _ignor:i kU ($Whitespace(" (%~EQr" "> `#")do_empty8RshortV"_egcs=True SoVing_bytesn s = ('iso-8859-15', 'utf-8 ^-sig' U+$16,F16be /le7 $32+&327V32le'5for5 in s&r.!e(Fing) J .encode(encodinWg)) gen.endElement("doc""ADocu#)) Aself.assertEqual(result.getvalue(),0|4xml(' ', encoding= )def test_xmlgen_ns(V%):m0 = .ioclass(gen = XMLGeneratorbWstart PrefixMapping("ns1", ns_urin.JjBNS(($", u , ;:F, {};# add an unaified name]None, "uP2), W5$ 3/ 5" $b\ L6 '<3>' %?o_empty6r, shortV"_eos=TrueO/>P?''LR68mNS((None, 'a'), 'a', {(None, 'b'):'c'}) gen.endElementNS(+a> +@Docu,5() Fself.assertEqual(result.getvalue(), $xml('')Edef test_1463026_2(0%):cR" =Hioclass( = XMLGeneratorbWstartPrefixMappingIqux'l.H7'#pvg 0 ^>end #(7xmlns="qux">'$a:g1 xmlns:a="Kexample.com/ns"5p 'Hello') }er = make_+().setFeature(f_{vs, True4result = self.ioclassTYgen =(3CwContentHandler(gen&-(assertEqualg.getvalue(), =:xml #C <Adef p5027_2(%):P# The- prefix (as in?p below)Kreserved and bouyI`definiUC to direct manipula of "\gen.startDv FPMapping('a', ' ?':Y0EleONS((5r, 'g1')F, {}Ft@_att?{@ 7'): 'en'}2@2', Pcharacters(' ?endk `@> @  "*.u   'Hello' , '#a1>')) &def test_no_close_file(self):"Cresult = .ioclass() Ffunc(out7;gen = XMLGenerator%;$.startDocument[ 1Ele"doc", {}assertFalse(!.dxmlgen_fragf><3h# Don't call gen0foo"a": "1.0".characters("" 9endL  1barlbl2lL,L 7end\.TEqualgetvalue(),,90xml('\n%s' % (TcY_!un"able = NoneVBytes>/( 0 !).e@'xmlrefreplace'gWriterH(liswD0 = u.appendT1 = j@seekiJTrue5Otell1## 3Q0 at  and not 0 afterg;wrb''.joiOVmStream\WJxh waraw = 'IO r = codecs.get('ascii')(raw, 2<je = raw5e.## (encoding, doc)).encode('ascii', 'xmlcharrefreplace') class StreamReaderWriterXmlgenTest(XmlgenTest, unittest.TestCase): fname = support.TESTFN + '-codecs' (adef ioub(self)?wx0 = qcs.open$.]q, 'w', Ding= <errors=, bufferL%0)Fcleanup(av.close(2gunlink'S.addC]e!zgetvalue{# Windows will not let use re) without first 5ing= G(%name, 'rb') as fJreturn f.readA4 = ;*1xml9iso-8859-1'F('\n%s' %(Nt4start = b| $' oXMLFilterBaseY(Xp!_f0a_basic' 0sulwBytesIOgen = XMLGenerator(re.xZ&D!.setContentHandler(gen)M'DocumentF1Ele"doc", {}.acters("cv"%ignorableWhitespace(" (9endr I7end'ssertEqual;.B(), + b"0 = ,x /S@]C?=Y'(fZ ue(), xml_test_out) def test_expat_text_file(self):$(parser = create_%()!result = BytesIOxmlgen = XMLGenerator(1c.setContentHandler(@k*with open(TEST_XMLFILE, 'rt', encoding='iso-8859-1') as fp'(f.assertEqual.getvalue(), xml_8K@requires_nonasciiJQnames' labinary$2 wf> = support.FN_UNICODEVshutil.copyf'E?ddCleanup(\unlink, /]!t.(?b')/b_Qos.fse{KtFC(Pd?intb8 f?'rbgh. no@., closefd=False2/f2/0# =C DTDdaclass Test":__init__  a_notations = []N!entities !"_=ADeclc , z, publicId, systemId\@s.append((?Oz!uno dEy, ndataE^Cdtdh \kQ 8 = self.TestDTDHandler() parser.seth',) ' feed('F NOTATION+ PUBLIC "-//CompuServe//$raphics Interchange Format 89a//EN"p]p")%<rreturn ?def test__:rO = create_p>I.0(result = htContentXMLGenerator(A)8!whatever^*&S;d'.getvalue(), start +E"b"5>p.bverifyL(_Zfw~ o='val'.close()  self.verify_attrs_w(gather.0) -def test_expat_ns*s_empty(I!):(,parser = create_5(1)"b0 = :a.AttrGt6er(%7.setContentHandlerq.feed(""Hgclose(6|a2Kz xmlns:ns='%s' ns:='val'/>" % ns_uri&8Bs = {.assertEqual(0.getLength(), /PNames."[(0, "L6")]?VTrue(nQ@ == [] orl Vs 4"$?"])p2lento|Axml_3out;_sysid !("$@requires_nonascii4sC 6 Lfv*.FN_UNICODEZhutil.copy , fname) self.addCleanup(support.unlink, fname) parser = create_%()!result = BytesIOxmlgen = XMLGenerator(1 c.setContentHandler(@k|.(InputSource(SsssertEqualu .getvalue(), xml_test_out;Adef expat_inpsa_byte_stream(\%):!tXrc = @with open(TEST_XMLFILE, 'rb') as fOSfP$1M,/.a7character t', encoding='iso-8859-1 CX0# = IncrementalP1XI X. NN n!n .feed(""G/oclose(start + bt<\Jo_resetPWtext"74;LM 9(1x ,Locator support def test_expat_locator_noinfo(self):)-result = BytesIO()xmlgen = XMLGenerG(1&parser = create_G.setContentHandler(`)*feed(""h./gclose(S.assertEqual(dgetSystemId(), Nonek5oPublic5LineNumberl1OwithD(TEST_XMLFILE$Dy >9= @requires_nonascii_filenames!n 7 fC = support.FN_UNICODE[hutil.copyx !, E `ddCleanup(\eunlink/]sj!r.(7O6O # =7 # # error re1inge7= class EgRfTest(unit.CCase inpsource")) #ill-formedhp0"a I "fQ![6try^?.!Gfailexcept SAXE ion as e[:\+e.W complete,entHandler(ContentHandler()) # do nothing self.assertRaises(SAXParseException, p!r., StringIO(""))NaEqual(3r.getColumnNumb?, 56FLine411) kdef test_sax_c$_eP_str(!):,# pass variou lues from a locator to the 7 toImake sure that2_s__() doesn't fall apart when None isGed instead of an integer line and c4! n5>  use "normal" va$he ("message",,^:[r.DummyL9g(1, 1)#fNy [N1\&ObothN clg__init__S,0no,'nob(_Cno =+e"1col!ngetPublicIdq breturn "pubid";oSystem; ?sys;hx. } *D ?# =7 # # xmlreader"se72= 2AXmlRgTest(XmlbBase): AttributesImplattrs_emptyBr.verify!_-(OL({})( _wU s' U"" : "val"c ns!/ NS _({}, 0 Lz' =XM(ns_uri, "attr") : "val"},  {(ns_uri, "attr"=1ns: 5}) Bself.assertEqual("s.getLength(), 1)/PNames.[{]?Q@"9 2len0C3p4645776416779583070097648 I25"48p1688656a81011634p249507432669034802B7123 10019165;@0871?I`650630382127517p165052812824652360157063132413278057045r2221429M2 69 @61151 I94703 I2991908938 I75090Fp6325751163201446@8464p347261729039594@3973r6 I19045 I77464957p164598524295876 p738244515633049739931741@p021316231879332}126780757q1190784 p9516921p358010027299782$3736811646 I300965641jQ93043p0402w6P4888074866844 I44287637_q8536872P78592`513785P1180528031469h 9872192919408702618p4808380 p7384529q68798610049Yo@4929346831129q3796211F88988633 I16432106}2983998124927308p5860487604073029 I41210828q149647629723571_q6631169SP64262 03Ha871862d0803/397476660730 3842528855p929093604462b899088 95v2p6754793`305178 I151487661p2540365R242045064Wq0343773!3329905953517512 S85834V 07a0#a70727801282_ 33"42 `856724p8831706 2005666473 I340310122$04641h370257611 0055q`944353_`75771020124842B30586497@09708 5325pP37864947790 I2582724774 I4291336243 I25681898 61923072690 I1121589611 I837696302 I3284631720 I3865021324 I3576453165S59531629 I145923176<506550036 I3754420159 I2622000757 I124228596 I1084328605 I1692830753 I547273558 I674282621 I655259103 I3188629610 I490502174 I2081001293 I3191330704 I4109943593 I185994850163806460 I508833168p5637103=p7092537120689565709284281Gp913926520396387a981982p5360941F368855295 I5199397 597480732 I4058175522 I2157@196231: 89952353788 45548108 I2370669647 I220357639299H732303374`53136253764195p7386917G3232854186Y I282976027@8785m2024257927623619700p639493464063586746=4a857679333079808>q45740053135610046 I606400718@6026`981133mT29772R92732hq9038200p5990887612335971q3405222`3447593684202717p1501134kp8256785p6899695Gq3934753o30349606p2085732%4004113739929048 2587153719p2917907}p5654249p77913061048582932135916O360779343`125493047811901 I7 5Q48544q4210090P23314&4 I70057213 I7764749P52888P03612q6495526F0311424d4141564426139 I868843623376030m191813144RP84343 `255190673340118 I42140815204549080472263 621232996800P94646p4305831Bp294026505395,a922761P41886K0 I3@5445v3915957954498179p1917808C 2320297>8p5713050E0423a8u36119164!R04516298234978!41 P53380i083918191517[q4123474 p3867703391458943783104979oOQ054626p1060132p5454834p3006005]p5166411836930210iP85291z04000`674079m14795579 36211888l 09=357844111227055556P689833H@54980583&!2q4097682#2106728013f[0676#138172643p7986701 13@4961 52 5'5P57875 160430P10126 I1950513752 I1121355862 I3586816903 I438529984 I2473182121 I12299972#05445940 I1695535315 I427014336 I3916768430 2298359 I1884642868Q`447308]741058080 I567479957 I35276211.3191971011 I3267069104 I4108668146 I15207955876581006 I47379447562126550 I92910 I88953329466556608 I8745186-3520162092 I301376504920231414 I54724643998093769 I373719373872944207 I793651876 I260638431u5991012 I1394836332011644 I85438042:18666767 I256830200995512132 I229491093ip73500283645507383692341S`436569E394438898q0649496G40637r7032444090798829 IP425789 22&HP01550174247824 I624 tp2 Ntp3 b.import ast Ttypes tdecimalunittest a_global = ' fvariable' # You could argue that I'm too strict in looking for specific error # values with assertRaisesRegex, but Pout ia's wayc0eas  # make a syntax ]{@the pngs. EsPally W all of theGtriple quotes, raw:, backslashetc. I think it's a@worthwhile tradeoff. When I switched to8s method, I found manyEexamples where I wasn'tHwg thought . class TestCase(.): defh@AllRk(self, exception_2, rL_3ngsDH trf #f"d`@.sub(str=strJ(,a(DH@evalg%) __format__!upC0# MEVsure ,1 ised up on* !1notinstance.oX yX~,=return 'I'cx = X(# Add a bB_]lde 'y' T5not!# &'x%ysn'y.f= 1s.MType(lambda 4: '{G', y$.Equal(f'{y}',*umat(y)),$* 9(x)YZ#@call!hin3Rstillj%iB # returns what we expect (socan make sure we're bypassing u# it).self.assertEqual(x.__format__(''), 'class')4y4instance') 8# This is how gactually calledxtype(x)s?x, =y=y=def test_ast(%!):G # Inspired by http://bugs.python.org/issue249758H& XIMiP__inip i . = FalseU D!,__  D:TruC#return 4\fx = X(expr = """ a = 10 f'{a * x()}'Gt = ast.parse(8Fc = compile(t}z, 'exec+Mx was not #(x& uA[run the codea{)(c2 |ZI w<_line_numbersP/1t),fModule~ .len(t.body), 2)# check `` BpC3[0]xfAssignO61.#/no}of'...'}1}OExpr{ C[1].valueJoinedSt? 2>D_s), 1x:9F}AtedVwA%1]A3| .4":?s[0r0bbinop location+= { 04F_BinOp 1D.lef?Nam f3.opiOMulthDrighiOCall6d binop.left.lineno, 3) self.assertEqual(binop.right.li0col_offset^_left.3417) def test_ast__numbers_multiple_formattedvalues(!):>expr = """ f'no / 0' f'eggs {a * x()} spam {b + y()}';Jt = ast.parse(\ntype(t),2oModule.len(t.body), 2)# check `%'` R3[0]FExpr\4 .#:JoinedSt? n^?...1 /1]~[>D_s), 42 :v6 (; CFV$2M'3C 4!Es[0] r>1>*2>*3> the first  location O1 = 1G_BinOpw 2D.lef?Nam 6#opkOMultj:7OCall7fP+0sa8 4 self.assertEqual(binop1.right.col_offset, 12) # check the second 8 location*2 = t.body[1].value3s[31IselfBtype2), ast.BinOp2 S.left7OName6#op4?Add316OCall7.lineno, 3+?eft0125 617) def test_ast__numbers_nested(!):,expr = """ a = 10 f'{a * f"-{x()}-"}'-1t =<`parse(?vs7_Modul9 Blen(?), %``C3[0]EoAssign R%0]}of'...'}1}OExpr{ JoinedSt? 2 O), 1xJ9FormattedViN A1A u4's[>U#NM0MLK".JOMult R{N65NY_ ^ g3g7YE;] callK self.assertEqual(len(binop.right.values), 3) self.assert5Otype6[0]), ast.Str? 1?FormattedVJ 2J [0].lineno :1:&2:call = j AOCallG*)col_offset, 11) def test_ast_B_numbers_duplicate_expression(S!)::eD"""D' '[!2NOTE: this is currently broken, always sets location of the firstk^.5""" 0 = a = 10 f'{a * x()} ' ,1t =`parse(MxHtoModule.t.body), 2)# check ``eCfAssignO6t}of'...'}?Exp*"1]/oJoined 2[>D5  x:9N  * [23; 4C;} K4!As 8  D/s[ 35> e.values[4].lineno, 3) # check the first binop location)= t.body[1].value3s[00self.assertEqual(type(F), ast.BinOp1S.left6OName5#op3OMult3DrighiOCall6.R *?eft/0col_offset 347FosecondG$2G{ # FIXME: this is wrong+/3)K%wLOthir%4,&def test_ast_._numbers_multifstring(!):7|T|E1 demonstrates invalid behavior due to JoinedStr's # imme0diate child nodes containing the wrong lineno. The enclosed  # expressions have valid7 information and column offsets.FSee bpo-16806,30465 for detail3w = """ a = 10 f''' {aW* x()} non-important@ent 2B t = ast.parse(c)F self.assertEqual(type(t),2oModule.len(t.body), 2)# check ``p C3[0]xfAssignO1.}of'...'}1}OExpr{ !1].valueJoinedSt? 2[>D_s), 3x:9|  CFAtedV $[2M q# NOTE:`follow"in\ behavior is described inB[-number should be\r*first*"(3), not la&(8i:# -M4_be -1LY,4!oEs[0]r>1>*2>Bcol_F, -1z!9&?0].C-1C/2CgG"pcorrectG zwithin lbinop =  ^ F_BinOp 1D.lefe?Namc f3.opiGMulthelf.assertEqual(type(binop.right), ast.Call) self.assertEq61lineno, 4*Oeft./06_col_offset, 3.l3417) def test_docstring(.!):@"'f(f'''Not a 85'''4CqIsNone(f._c&__YgYX% \Z}jgj&gliteral_evalWwith LRaisesRegex(ValueError, 'malformed node or 6'! ql"f'x'"vast_compile_time_concatx = ['']expr = """x[0] = 'foo' f'{3}'""")1t =`parse(7Cc = ~(t, '', 'exec'#&(c$K,~,3'\ _eIsW1All~r(Syntaxy 'cannot mix bytes ann ?s',F [r"""f'' b'A-  - b'q-]]f("aa$  $ unterminated_B 'f-:(: OG t?{"xFsQf'{"xY Of'{(Z([ mismatched_parenEM "O(}'"  double_brace b {{?{c a&a' 1{{bMbN(+a{)f.assertEqual(f'}}', '}') self.assertEqua%a&a' 1}}bMbN(/a}) "{{x{x a)a* 3{{bSbT Sc?{}c U/a{V WaXW,/{b- Q{{{10?{10 $}}+}+X6Y a"}a P10}{{?10{\  +X}Y@a{{'4b, '10}u'# Inside of strings, don't interpret doubled brackets.?~ {""/) /AllRaise(TypeError, 'unhashable type',: `["f'{ n }'", # dico a set< # ]def test_compile_time_concat(%):Ix = 'def'! ~'abc' f'## {x}ghiabc## def=`{x}' '- , :Qi{x:42abcC 'zf ,  {xk70/}0}19{x}35f/{x1 d/x} " '8, (1 / '. 2W2- &'11O1def2i 3f'-;Odef-4assertEqual('' f'', '') self.assertEqual(% (Tv?f''s%p !AllRaise(SyntaxError, "f-string: expecting '}'",D< `["f'{3b+ # can't concat to get a valid dS A ]) !def test_comments(!):# These aret', since they're in %s.;d = {'#': 'hash'}d pf'{"#"}B#C f'{d["#"]+VW ression partRnot include '#"1#@ # eq becauscbecomes "(1#)" 0(#)Z*')( <When wrappedpps, thisQ # '()#)'. Make sursat does4Fpile A many_expCreate a{` with 7|srit. Not # awe havK1pachere as a literal, weactuallyH go1to 1wic;ast nodes: one for eachVFJplus%>build_fstr(n, extra=''V return "f'" + ('{x} ' * n) +4b + "'" 2ux = 'X'width = 1## Test around 256iorange(250, 260Weval(i)), (x+' ')*i{1ena?2 largs 7ingi255)*256oA(255wGs = 253, '{x:{?}}  sb7254\ylots of0andpstants, 0cat&eds11}' 'x' 'y'" * 1024@'1xy/]format_specifier: width = 10 precision = 4value = decimal.D('12.34567'), self.assertEqual(f'result: {H:{width}.{mU}}', 'Z5W /!rYD(:0Y/:13O1}{0ZCR 1}{ \ i%{10:#{1}0x_ 0xa 7{"#"}1{0}{"x"5?U-10:-A|-|=Q{"-"} ~A3 != {4:5} and !AllRaise(SyntaxError, "f-string: expecting '}'",D! ["""f'{"s"!r{":10M_""", 7  # This looks like a nested format spec.E &])finvalid s 9# I0g insido4:{/5}H  0ressAtoo deeplyQCan't9xoifiers~ "CM:{0} '`conver character' @# No!an8J or # the : or ! it3 35{"r0 W def test__effect_order(y%):zvclass XS?__init__1 HV.i = ;=,t(CE+= 1return st#.i x = X()  self.assertEqual(f'{x} {x}', '1 2') , def test_missing_expression(E!):'+TAllRaise(SyntaxError, 'f-string: empty L not allowed',SW ["f'{}'"&  &O }'"L &O {} N/!rv)o10:{ }U2 {  # The Python parser ignores also the foh?ingL whitespace characters in additional to a $.O "f'''{\t\f\r\n}''t3 q# Catch 1`beforeE invalid conver?{!xO{ !x?!x:SO!x:a*}U+W1 9!{O # We find@ cloo bracej F /s:(&xM]b# Different e- message is rJd for other  identifier3xa0_"\xa0  oparens_inqsr!3,D(3,)A# Adse because when anis evaluated,B5ens`# areed around it. But we shouldn't go from\kD>Pone. Sadded{pHjust@supposed|(including newlines). self.assertAllRaise(SyntaxError, 'invalid sO', ["f'{,}'"'  ' # this is (,), which@an ep E ]) !s "f-string: expecting '_3)+(4+@'EOLle scann literalo/\n def test_backslashes_in_v`_part(G/):VEqual(f'\t', )&r &?\t'' N( Rf'{2}x2*0{3}O2\t3 +*f'\u0394W  ./ ^0225  e3g2( U0, 2\c 'f')l8<+3, ' * 69@S1 7H N{GREEK CAPITAL LETTER DELTAHIJ, K_ /2\K H 3I  IK 0x20w  3r'\'\ 4 x20', '\\x20'3) self.assertEqual(f'{2}\x20', '2 '+2{3}.3/ W, + 2-VU )3*U S* ~Hwith/Warns(Deprecationing): # invalid escape sequence value = eval(r"f'\{6*7}'"N4, '\\42 \N-r{-AMPERSAND = 'spam'0# Get the right unicode character (&), or pick up local variabl# depending onRnumber of backslashes.{%N{j&! 11\\NOfr'\7!?'\\8def test_misformed_M_M`_name(!):5Dq# These= are needed because<s!gparsedA differently inside f-stringq AllRaise(SyntaxError, r"\( eC\) ' ' c can't de bytes in posiG .*: malG \\NPI%", [L/N''  '{( GREEK CAPITAL LETTER DELTAB q # Here/Dnon-d versions  # which should give*Bsamer Or"'\5M{ <1]) 57no__in_expres\_part 'eJ Jnot include af' ]{\'a\'}$of'{\t3*(rS-+}'",  r"""rf'{"\N{LEFT CURLY BRACKET}"}'""", ;r"f'{\n}') 1]) Jdef test_no_escapes_for_braces(self):*d5""" Only literal curly 5 begin an expression.7C# \x7b is '{'#u.assertEqual(f'(1+1}}', '{ %')S0.- u007b1+1/1+1\N{RIGHV-}'tewlines_in_, v!{0 0 rf'''{3+ 4}''7llambda_x = 5^ "{(9 y:x*y)("8")!r0"'8/'" @!:1C? FD8D## doesn't work without parens, because the colon@a makesparser think it's a format_spec5AllRaise(SyntaxError, 'unexpected EOF while_sing' [?x:x \yield # Not terribly useful, butB sur >e turns #  unction into a generator'zGfn(y_Rf'y:{WRy*2}'g = fn(4[next(g), 8kRM_senx1D f'xi: x * i)&10Cthe_#= .g(4), 4I ,!g.@'str"d), 'x: 0W__triple_quoted_6r"{'''x'''}"ox f,ceric's1""# Test concatena- ;4,Qx" ""_"s""" "y" 'xr?"sy ;'{"@<; wvrtEqual(f'{"""x""" """eric"s y"}', 'xSy') self.assertEqual(f'{"D_""y""HrIdef test_multiple_vars(!):"ex = 98y = 'abc'0 Ax}{y 98,/) . %X{/X0z]X^X_+/@{y}X]/X'Y`OX98YaYbY x}1 981" ZdZ|closure wouter(x.kinner(return f'x:{x}<v'987')(): 27.7argument2Yf(x, widthq={x*y:{%?}}'f('foo', 10p=foofoo ,F'bar.6(10F@-20]localvalue = 123dA'v:{*]v:123`pmissingMiabl7Wwith [Raises(NameErrorUftH_jformat_specvclass OvA#__6_3 , > {,aif not E&'*ZQO():xSx*(*(:) "{3(y63!s)QFaglobalGAERg:{a_."g: A var+ ? !rAL"g:'B"!a_Y hg0} l=5}',6: '1 l:7_global!r}',/ "g:'global variable'")0 self.assertEqual(f'g:{a_30} l local!r}',8 o2"g:4gA l:':yBzIn("module 'unittest' from", f'{A}') @@def %_shadowed(U!):$ = 'really a '$3k', 'g:=@4  A"  ; l:s #s Ag Yt4Lcall)Wfoo(x=return 'x=' + str(x{F@10)}8Mx=10nested_fstringsUy = 5bq"{0}"*3c 00b/y/=555invalid__prefixe\AllRaise(SyntaxError, expected EOF while parsing; ["fu''"`?"uf%FJ/fUJUo/uFJ?ufr&rq/fuL/frrwrx/URFbK/fB%FJFJbbBJBJ ]) def test_leading_trail spaces(self):  .assertEqual(f'{ 3}', '3')' (/3 O&3 (x expr={ {x: y for x, y in [(1, 2), ]}}',C'B_1: 2} )k l)dQnot_eu# There's a specialthis because t(bp# case the f-string parser to lookR!= as not en48 anGession. Normally it would, whileM_!s or !r. G gA3!=4OTrue {,:-/!s.":.RTru')`conver?3.14:10.10  W.14!s:4>:r:&a: 1"a"a P"a"!r*_"'a'"S ,a,# Not a .\A"a!r LI , but show that ! is allowed>a$1matv 6:!<!UAllRaise(SyntaxError, ': invalid character ["f'{3!g}'")A)3)G)!):) s*q # no | beforeJG  ];"`expect'e ox!s{y}, sV  "f'{3!ss:}'", +s,1]) M def test_assignment(self):h.assertAllRaise(SyntaxError, 'invalid s' ["f'' = 3 0}+x+x+ ?delNodel f'(/''+ mismatched_braces"f-string: single '}' is not allowed /{{~?{}})%x&xr"f'\u007bS  # Can't have { or } in a format spec.C a3:}>10p c,-"AexpectingO3:{{!':'/!s(Q/:3S/x{&&/3:{O{{}})# But these are just n5"l s8Equal(f'{"{"}', '{')`(}(}( b3:{"}"ZD, '}38 !2:{,2'aif_conditionas# There's special logic in compile.c to test if the # conditional for an%(and while) are&stants. ExercisEthat code. \1deft_fstring(x, expected):'flag = 0if f'{x}',010Oelse+2+self.assertEqual(concat_empty /''?non' q`e'', 2) f ', 1) ? !D LH1H%L*^_format_specifier(2Px = ''" :,()?:}'*/!s,r,""|4strdifferencesd = {'a': 'F%',  0: 'integer}*a]Ad[0]L3 Rd["a"10 a._@'{d[..e(d=d),h9 9sinvalid_expression~*AllRaise(SyntaxError,{E! s [r"f'{a[4)}'"& +?(4]+]Ze # see issue 26287mDTypeunsupported(lambda: 0):x ?(0,-]AllRaise(ValueError, 'Unknown format code', [r"f'{1000:j}'"-  -1]) zdef test_loop(self):for i in range("1.assertEqual(f'i:{i}', 'i:' + str(i)nLdictnd = {'"': 'dquot"'": 's@'foo:/statm: we don't pass.$ #{P' PIDavoid a race`dition1cas- unlikely -6recycling. # IfYW crashes, ing from"@ ent>ill fail with ESRCH. import os %sy time try#page_size = os.sysconf('SC_PAGESIZE') except (Valu?AttributX\ _]+a-X4096 while TrueAsys.r.seek(06 = i(data = int((.split()[5]!6out.write(" ...@I0: { :.1f}G\n".u(+=6 * / (1024 ** 3))Sflush.sleep(1)dbase64 Temailurllib.parsetrequesthttp.server th<4inghashlib Cest 0sup$sljIsl = None herpath.dir|(__file__) - lf-signed cert file for 'localhost' CERT_l$ = os.path.join(here, 'keycert.pem') # Self-signed  file for 'fakeZCname^a 2b # Loopback http server infrastructure class+QHttpS)(5.5R.HTTP): """Uw/ a few modifications that make it usefulBltesting purposes.A""" def __init__(self,u _address, RequestHandlerC.Tk. |8r t the timeout of our listensocket really low so~#kwe can stopMr easilyXnF.PC.setsR(0.1)tRget_rYwR method, overridden.nE, client;8 = saccept(8# It's a *`connec[Q, so !ng)houldn't affect anything, but s@deadlocks less likely to occurMIG10.0return (* )Thread(tBing."""Stoppable $9run85  "_hIg^ >)7__|z= False"3y =W@Evenm .protocol_version = Z/1.0"]?d =("127.0.0.1", 0),:t Dport8_SL,Se web7@if icurrently runpBTruet" Tclose}`Digest+ca perform8d1) a]F _num = 0  self._nonces = [] @user+{}realm_name = "Test R"(0qop!aauth" def set_qop(eq, qop):|. = 57 9assert isinstance("{, dict)`1 =  dd d B_generateVHAquest_num += 1 = hashlib.md5(strFE._re7).encode("ascii")).hexdigest(Vs.append(#qreturn 0cre_A!, 7strfirst_space_index ='.find(" "pB&[CB+1:]@part;.split(",")%7 = @for @1 insj[`, valu)]=*0 = 1g.stripg "ifG[0] == '"' and$-1 9}V[1:-1 Oelse6 [2] =l'Kd_valid`, password, method, uri1nal6 i0.up`(} f%$["i" *( &1uri#5uri pHA1_str%2.Q)s:%( {f)s" % xE W6HA2xWs2sFsQ["HA1&HA 2 2response1HA1J uc)s:" \5F"%(c.w?HA2hv  :$[""3_'challengehhandle d.send_`(407, "Proxy Authentication RequiredLheader("Content-Type", "text/htmlAuest_handler.send_header( 'Proxy-Authenticate', 'Digest realm="%s", '82qop Rnoncei ' % \7q(self._Xr_name, 4qop generate_KE()))C$# XXX: Not sure if we're supposed to add this next 7 orEFnot.request_handler,'Connectionfclose' ;f/s(&wfile.write(b" ion Required."Gturn False Bdef _`#, !):/"""Performs da{on the given HTTPNDs`r. ReQs Tru Kwas successful,otherwise. If no users have been set,np is effEvelydisabled anmethod will always r 6"""aif lenP!._f) == 0KH ;WPorizaA" not inP.sZg___challenge(JelseN:cdict =q0cred  []};5if k ["P "] 9password([N RM Z@ita.get("&")r'Dt.remove(q6"])!validateb\ `# MSIEs short_pathCits =ion, but Python's# urllib.MePfull PC, soPgoing seT J ei60 ofm works herE1forY[xqr ]=P#ife3c,21 command@ pathO): auth_validated = True +zif not *Nreturn self._ _4 challenge(request_handler)g3 class BasicAuthH2(http.server.BaseHTTPRV#3""" for performing bTentication."""1# S] side valuesUSER = 'testUser'dPASSWDBPassPREALMBTestA_0"%s:%s" % (", ENCODED_AUTH =e64.b64encode2K.'ascii')).de$def __init__(, *args, **kw 7"d.L ulog_messagex#atv# Suppress console log =nFpass_qdo_HEAD[L.send_response(200]E header("Content-type", "text/html"6U59s();401WX`("WWW-  realm=\"%s\"=mP 0" % ,I"ascii")v "Our apologies, but our  is down due to "{ -b"a sudden zombie invasion.") # Test cases class BasicAuths(unittest.CCase`USER =nbstUserdPASSWDBPassINCORRECT_"Incorrect#PREALM:i"\setUp4jsuper(,").1gb# With entication=@def _fp_with_b  o(5 breturnjiz 6w2s = LoopbackHttpSThread(TaddCleanu:S.stop *~_url = 'j://127.0.0.1:%s'*_.portg.startU5Py.wai!>r 4elf'Xv = None-tearDownO04|successW&ahW.zupah.add_AwordR.j =M{install_opener(Tbuild'ah:tryassertTrueJ0urlcRdexceptrQerrorE lafail("7  ed for the url:+ %s", self.server_url) def test_basic_auth_httperror(4!):)- ah = urllib.request.HTTPB<AuthHandler()3.add_passwordRm.REALMCUSER INCORRECT_PASSWDW install_opener(Tbuild6ah)G.assertRaises;E ,0urll V class ProxyTests(unith.CCaseWpURL = "s://localhost" :1er"V 2123TaSRealmDQsetUp|wjsuper(").1)# Ignore p0 by settings in the environment.grestore_!D(old .3os.%X.cleaK iupdateKtddCleanup((, gGopy(['NO_PROXY'] = ''`$1no_$%0dig^XA = D27_users({$:}!|Er7c# With enticationcreate_fake"_h(*args, **kw return Fakez,, P 4| = LoopbackHttpSThread(Ja0Rstop__ *g.start6{.zXy.wai!(}127.0.0.1:%d" %aEportO` H{K2" :m V .er sqi.Mm'r = None4Jvwith_ba!_rt IURL,  l*k+"bad"d.set_qop("autSh") self.assertRaises(urllib.error.HTTPE ,29Dpopener.,QURL) Qdef test_proxy_with_no_password_rQ_http(l!):<@.digCauth_handler.set_qop("@qop_o_works5add$6.REALM, ?URL 8 93SERDkPASSWD(iresult =bwhile 2g.read(%(oclose(HX2int\_or_throws_urlLoG-int6try7*yexcept 1URL V# It's okay if we don't support P, butcertainly# should;receive any kind of ion here other thanF$a .ENone#ifh  c. GetRequestH(responses):class Fake` ..server.Bas#G)P_vers+@= "TzUTTP/"res = []headers_}dB= 80lado_GET DbodykPsend_`(BBg* Sdone /wfile.write(. F.0 = [:-:]?POScontent_lengthsbers["C!-L"0wpost_data7rJint(\)dA.append(l]Q U.headers_received = self.headers requests.append(Ypath),response_code, O, body = s.pop(0) =TTsend_(( P /Rfor (b, value) int:[_5 < % {'port':) }!ifZ "Content-type", "text/plain"T.s(#areturn  ; def log_message, *args)Rpass iFakeHTTPRHandler class TestUrlopen(unittest.CCase]0"""s urllib.B".u8 using the network.`These R s are not exhaustive. Assum<!at) Ofiles does a  good job overall of some|basic interface features. ThereLeexercioptional 'data' and 'proxies' argumentP!No]transparent redirecL have been wr\!n.2""""QsetUpoIPuper(v,")..@# Ignore  localhosUsvXqrestore_environ(old .3os.%k.cleariupdateKFaddCleanup ', Hfcopy()6['NO_PROXY'] = '*'a%0no_ y%&j, , =None, **kwPal = []@0f =6B(urlMH8:try2# Eye various methodPlPl.extf.readlines(200''A#_(1024F Bkfinallwf.closeob"".join(l{stop_serverg.'R0 = 5HtartS,c&if1 isJ sd, [], b"we don't care") hGj = Get[:s LoopbackHttpS Th(W8<() self.server.start() Sself.ready.wai!xport = (Ahandler.0 = sreturn # Adef r_https_|(` , responses=None, **kwargs):<if not hasattr(urllib.request, 'HTTPSH'8<e.skipTest('ssl sup AVired'from test.sslAs im0Imake@ is = [(200, [], b"we care a bit")]TBr = GetR(NT= = hPs_class=o yY#:_redirection{expected_ = b"We gwere..."fE = [N(302, [("Locai@", "\://localhost:%()s/somewhere_else")],NJ "") r]N4q>Ddata,urlopen(Ts/" %J}assertEqual(T/,  2H`s, ["/I 0"])chunkedhello worldB_J = (Tb'a\r\n'!b* 1! d! 0! ("Transfer-Encodingo   7 a| `V?404RBad b  R[(40498:try6k oweebleqsexcept |error.URLE Z as fq f.a|wf.close @fail("404 should raise w"T0assertEqual(data, expected_response) !self.assertEqual(handler.requests, ["/weeble"]) 9def test_200(B!):T l = b"pycon 2008..."-m0 = F.start_server([(200, []]DdataAurlopen("http://localhost:%s/bizarre" % xV.portJ [~ 2Y >y?_with_parametersO, ab"get=feeling"W/,  < i*pcontext,sl.create_default_(cafile=CERT_D{A s#, j=\ mwe care a bit" $Ocert ^@ sup.check_warnings(('', DeprecationW)}op# Good k R+ Ok /|-O# Ba-" Raises(urllib.error.URLE v) as cm\b#  @fake7nam|, but mismatching 3 if|@ f(self): 2 handler = self.start_https_server(certfile=CERT_localhost) # Self-signed / should fail verification with system*ue storeR&upport.check_warnings(('', DepreSW5)):?CassertRaises(urllib.error.URLE z) as cmAEurlopen("5://:%s/bizarre" %K.,L cadefault=True) .udef tes0ni(if ssl is None+.skipTest("(module required"`if notM.HAS_SNIM RSNI sN in OpenSSLYsni_name =@cb_ssl_sock, a0, initial_context@1nonw aZT#Srsl.SSLCd (ssl.PROTOCOL_TLS_SERVER(:C.set_callback(0N{=Z,_ *screate_?.?(caD   xMVdEqual(1, ""sending_headers:!({creq = est.Requ  9 ={"Range": "bytes=20-39"}i j;reqEpass I.~_received[*], d_basicZ#N_url_ _ ^for attr'("read", "close @info{geturl"& @(hasL(,[), "object rG~efrom "b " lacks the %sNAibutj?try.(Ping '' }kfinallWG#(03b.request.urlopen( "http://localhost:%s" % handler.port)2Pwith EU_url:Pinfo_obj =!.(>self.assertIsInstance(%9, email.message.M,fj "object returned by 'T' is not an "E i? of"UEqual.get_content_subtype(), "plain") def test_g l()L# Make sure same URL asU edD.Y0 = W.start_server = urllib.request.ur$68urlM_url, OiterationRexpected_response = b"pycon 2008... A [(200, [], T&)]!Odata[5for line in X) >+ {'_1s = [b"We\n", b"got 4her verylong " * 8192 + b"\n"] )}q".join(i8|eindex,@enumg e([I] "Fetchedpnumber %s doesn't match}6:\n "E length was %s, got . (,>)&)) ?F + 10 s)) threads_key = None setUpModule(b# Store th7ing_setup a Daand en9pthat it.@clea!up#0GqearDownwglobal R up."()tQ (ifVsMBup(*` ) if __name__ == "__main__"L@unitN.q() from_.b import verbDose, import_module, reap_children # Skip these tests if termios is not available iM#('(3') d errno 4pty $os &sy UelectUignalEocke@io #Tdline#@unit TEST_STRING_1 = b"I wish to buy a flicense.\n"323For my pet.a, Eric, if verbose: def debug(msg)Qprint? el-@ass Note that os.read() z1ndebnistic so we needey careful #0makKy suite E. A normal call5vmay # give us less n expected. # # Beware, on0Linux system,=I put 'foo\n' into aRnal fd, I get # back)r+ at other end. The behavior dependsx th # setting00new& translatiay be OS-specific-$o 0>?est2@ and9"inAent,@func]0s _t! #.`pize_out 0can usC > #S(dataJ# Some opera]s do conversion . We could possibly fix#t by doingappropriaz.tcsetattr()s. IP n'gure outQe right comboTru64. So, juste"iz L0docKproblem O/SesPallowqcertainc!inps for splatforms, beavoid BJdifferences (like extra whitespace,, ilugarbage,cetc.) 1ThiBaboub40we pdo withg@feedEAfromone more knowledga.lqOSF/1 (V) apparently turns \nYq\r\r\n.\0if E.$2(b''X reA)vreplace(`, b'\n+PnN*n'Lw 33(fd"""Read M@. M@lock@ever`3no &{A.""" er = io.FileIO(p mode='rb', closefd=False)5<~1() PMargij"bof pty*. Cannot`extens;'do or fail'T0ingaecause>@code<@too # XXX(nnorwitz): ,leak fds whenrG anyor. class PtyTest(unittest.TestCase): def setUp(self2# isatty() and close() can hang on some platforms. Set an alarm E# before running the  to make sure we don't^1Aver.FAold_X = signal.(.SIGALRM, .handle_sig)CaddCleanup9@,VHrB7, 0)Q(10) lqwd, frambfail("g hung"HAa_basicH2tryIdebug("Callmaster_open()"+fd, slave_name = pty.82aCGot %yfd '%d'Fy'%s'" %:>5 (61)e%r)" % (,<#fd< 4n#i2except OSError~# " An optional featcould not be imported " ... ?%eraise @Skip("Pseudo-terminals (seemingly)ZBfuncw.<r^assertTrue(os.fCdfd), '1 isMca tty'G# Solaris require add$fdPanyth+fturned# My guessjthat sinc:5 fd#D# inx00(),M@needbAread9BEOF.!Enxqn-block`n case:1re'0to R2= os.get_* Oos.s4v, False; ?1s1 |tj, 1024?.Belf.Equal(b'1* Z as eKif e.errno != ~.EAGAIN,0fl`# Rest.@orig&f flagstM9>@Writ#to'fdos.write, TEST_STRING_#s_qFlineuEdg`I wishpbuy a flicense.\n', normalize_output(s1)chunked output")  os.write(slave_fd, TEST_STRING_2[:5]) +? .'5:. s2 = _readline(master_fdP6self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2)) Fclosh2os.9def test_fork(%):debug("calling pty.'&)"[Upid, W' =&Hif pid =VCHILDe# stdout should be connected to a tty.P3`if notisatty(1!Child's fd 1 is9S'?!1os._exit(3)$w# Afterp, the c_ alya session leader# (on those systems that have concept.n"Iny$, os.setsid(3:tryq/ Z exu OSError8# Good, we Kwere So<:] was raised.IpassHAttributeHDpty, but?Q4No $ available?)We don't want this eUpropagate, escapbNmall to#) and caus50ver0culiar behavior inO@regr_.py ! qNote: cadd traceback print{JhereQAn unexp z1Nelse_Q succeeded! (bad!e2e4yu1Wai2forP (%d)finish." %K{# In verbAmodeEo0sum!e g P from #x or will blockvChang Nparent's waitpDXE. TZ1s aaAlatform-dependent amount of datazl0ten it[. OnJLinux 2.6, i4000 bytes%sw\[on OSN@X evrhe small writes in the child above will block it. Also # on Linux,=bread()8raise an OSError (input/output e)Nwhen it tries to QQ past_aend of buffer bu+'sO al@+y exited, so catch and discard those exceptions. It's notOworth checking for EIO.&while True:5>trydata = os.(master_fd, 80#.WR]break if o7sys.stdout.write(str(E .replace(b'\r\n', b'\n'),z encoding='ascii')) 9o##line,@s = 4q.split( iaif FaldBs != ['In`, callos.setsid()')##d'Good:Q was d.', '']=! TestFailed("Unexpected 9Bfromq: %r" % ;0(pibtatus)Brwaitpid W re:s/Y >> 8debug("CC(%d)Qc with 60%d .dCres,)1if r:= 1Aself.failrdJu `ion in9"j&ell2l pty.fork() } ed5makP sessqleader.j3j Hspawned by {1didhave a tty as }qO!= 4q `punknowncs"C###0Rea y now thatC has -##"s1 J1024"##Q N;pasK#els+U j .8ion+os.closeH#ed. class SmallPtys(unittest.RCase)"""These s don't =ren or hang."""Bdef setUp(NJ]orig_stdin_fileno = pty.STDIN_FILENO  self.orig_stdout_fileno = pt3?OUT4pty_select1 ^fds = [] # A list of h descriptors to close.>2ile@ j_rfds_length& cresult&Mdef tearDown( !):20 = ",#in+ 21 3_ 4 -X*2for4"inAs:try(.Z%()Nexcept OSError9Epass1%d }d{#osy/fd{ |]_pipeBipe_[1os."dfds.extend(-"treturn  msocketpairs'.^' CmockZ , , wfds, xfds# This will raise Index when no more expected calls existpassertEqualz. i.pop(0), len()X;~;f[], []test__copy_to_each-"""Test the normal data case on both master_fd and stdin."""read_from2d, ndw  :f%d, writeMcu Ka5 s. Pno() s#a# Feed\. Smaller than PIPEBUF. Theseznot blockQ1os.(p[1], b''_-3.4?"')5E@ two,& lal"ne9cauMMv'( 0appe2 ++[` _f_s[0]]E.E2 @with"f.Rs(IndexError)7: pty._copy(masters[0]) ## Test thae right data went to thuplaces.=rfds = select.([read_from_stdout_fd, }c1]], [U0)[0]Nself.assertEqualJ)B0os.( p20), b''K(, Bcstdin'Zdef test_z_eof_on_all()3"""e empty  EOF case on both_fd and lE."""6 Fmockf._pipe(!STDOUT_FILENO = :f!inwrite_todc .INb8asocketpairK = [s.fileno() for s in 4][1].clos#os S# Expect twoq calls,%last one will cause IndexErrorq,YG'*T__lengths.append(2 +eresult+[`?F[0]]Ec# We eywere removed /plist asy#encountere`before.P secoEW 0@with:vRaises(wm}  arDownModule(:reap_children() if __name__ == "__main__"@unit.() # Sample script"by#qgdb.py foo(a, b, c~5bar$r=baz$sz(*argsFid(42) `1, 2, 3) """PyUniting against strptimeb import   dlocaler $osBsys :nS0sup[@dateT [_  P_ class getlang_N$s(.CCaseo_/st_basic~.IB(), .[(LC_TIME))LOTimes4u@.All values areL lower-cased when stored in LocaleTime, so make sure to compare values after running ``Z`` on them. 52""" def setUp(self):W"""Create time tuple bon current.M3F.2_2=#l%()b+LT_ins = _strp".&()_against_+, testing, directive,_position,u error_msgHelper method thatks^x!5thet 1 of!. Uses # a message i0trf_output is( i,!).\@isonGN[6[<%]])assertIn(0"%s: not founi6" % 4lfEqual(,, {r1 ur within3` incorG; %s != %s" %K(,H )_weekdayw6# Mrfull and abbreviat#= names are 5 in`# both9nd .Nee.$.f, '%A', 6[ ""TT failed"aa!R#^month 1/s;d'#hpq_B', 1H !a_Db&O  ^am_pmPAM/PM representa done properlyQGDime.bq("%p", Y ! t, self.LT_ins.am_pm, "AM/PM representation not in tuple");if self.time_[3] < 12: posi<5= 01Ielse1IassertEqual(DLT_i[Sq], strfvooutput? he wrongCwith1") def test_sAzone!):G# Make sure $ is correct(='.l("%Z",M).lower(qC}->TTrue(&Ie[0] orC +C/1]wzB!%sBPfoundO_%s" %}  )AdateCheck that LC_),P, and M are# the magic @used so as tohave issues I %c when day of"# O@onthJa single digit has a leading space. This1(anPvG cepstill parses it!lyKe problem isKu@thesives forCness by compar.J.@ = (1999, 3, 17, 22, 44, 55, 2, 76, 0]_R <2c",_:Tu ) 8, "F3 in2 3x6 !$X2*ALT = _str(.LocaleTimei"LT'o'', ''VlQLT.LC}N's LC diB0canhandle " y`"emptyMingsNlang is set to what _getlang() returns @# Assuming locale has not changed between now and when self.LT_ins was created V assertEqual(1., _strptime.) class TimeRETests(unittest.aCase):0"""Ss for1Q.""" def setUp{2"""Construct generic>q objectE+W_re =!()n*E_1 .L]4&()_pattern # .%mE=rw4_re.(r"%a %A %d"ZTrue(KQ.find..a_weekday[2]) != -1,A"didDL abbreviated EC in w@ str'%s'" %T0,f4OfulljO['d''d' directiveR&h_escapingDx# Make sure any`practers0the4matthat might be taken aregex syntax is y1ed.b2 $?\d+In(r"\\d\+",.Nr"%s doeCxhave re properly 5~compileeaCheck =$"d *`is cor"\found7=A").matchh B/6]a7 .group('A') =fUbS "re3 '%A' faile Ga %b4 = :n%s" % /4]" a_month[4])B \ "M` with >m'%s' string" 8% -(compiled.pattern, "%s %s" % (self.locale_time.a_weekday[4],JV Jmonth[4])))J'assertTrue(found.group('a') == $E andN ObO"re object couldn't find the abbreviated / S_ in ""'%s' using !; a 'a' =,b[%s'" >string, &ree^ >,(b'for directiveM!,'A','b','B','c','d','G','H','I','j','m','M','p'| "'S','u','U','V','w','W','x','X','y','Y','Z','%'):d ;C_re.f("%" +L#3 = -d.match(DP.strf B C @, "MJ fa1 ono regex  a B1)) Ndef test_blank!o# Make sure when tuple or somethhas no value  is gener6.r# Fixes bug #661354 = _strp!.LVTime(-.&zone = (frozenset(), :fEqual(jd7RE(\)]("%Z"), ' f"with = ('',''), [P'%Z') != ''"@ing_P_escapes a format that requires :of characters worksw! _rARr"\w+ %m"F H/(-'10-U20r"E3f'r.10!_data_w_lV_meta)RCheck2if B B contains IUy are,#Sed properlyDiscovered by1039270 '~~-(frozenset(("utc", "gmt",  "Tokyo (standard time)"))Gfrozenset(EdaylightEV_re = _strp.TimeRE(locale_)0self.assertTrue(_re.compile("%Z").match~ "t! data that contains regex metacharacters is not" `" properly escaped") .def test_whitespace_substitution(!):,V# When pattern?, make sure ittaken into accountOso as to allow sub`end up next(each other andJ"steal" Vfrom 1..`0 = .('%j %H'False(re3, "180")3"2 3 class SzTests(unit.CCase0"""Ws for6"""\setUp"""Create1ingp tuple.?! =)0.gm1(CValueErrorq5# M&raised wU. fails or!maA&bayR<&s(Q,,King="%d format="%A"nBbad_p in ("%!% #e"96try8^ ("2005", c{9vexcept \$Einue8E?0ionn>err>Y}s("'%s' 1%s,y9" %bf(, err.____.__name__':Oelse1did 9" %6# AmbiguouP inlete cases usISO year/weekday directivesO01. .)P (%V)specified, but theN  with %YK inud of %G( cD. ("1999 50GY %V2# 2P (%G)D Kare hror):  _strptime. ("1999 51", "%G %V") -% # 3. ISO year (%G) and weekday are specified, but- (%V) is notOfor w in ('A', 'awEu'):'~with self.assertRaises(ValueError04{}".format(w)4&is alone (e.g. :C`('20157%G'L[ 5. Julian/ordinal 1(%jk "%Genot %Y^Z42256q %j") cdef test7_exception_context(~# check that this doesn't chain A s needlessly (see #17572Z as el8_!('&D'`UIs(e..__suppress__, True>`# addi #alQIndex branch (issuF9545@fN6p][B] ==w,7" of '%s' failed;-> %s != %s" %O' (  +))P# Teseis handled properly0('yfYv16, 0 # Must also make sure %y vs~0cor wbounds set by Open Group & for century, bounds in ((1900, ('69', '99')), (20 0068'))): IQHG s!)strp_output = _Utime. _(?y, '%y')eDexpected_resulHb + int=7self.assertTrue(|{[0] == Y,z~"'y' test failed; pado'%s' "Cand returned 5B" % *, 1)) P1defvp_month(1# T1or directives>0('Bb'm'N.a.helper(6<, 1?day?day]l'd', 2WOhourXUVH', 3Cstrf0 = o. ("%I %p", i_tuple>Re#, VE3 ?[3]"ing of '%6%p'] -> %s != %s" % ' -3]>[3]_inutemll'M', 4osecondYY\S', 5Yfraction[Rmicro`import date.P5d =.p(2012, "2034, 56, 78987!Ptup, ?, _(@(d), mat="%Y-%m-%d %H:%M:%S.%f"RXrtEqual(^'d. Oweekl_AZawud6_juliaV\j', 7YloffsetAone_d= 60 * 60Dhalf36= 35R(*_, k5), _{p"+0130"Jz Z%, %+ ) self.assertEqual(offset_fraction, 0) R(*_, !5), - = _strptime. ("-0100", "%z"N/se{, -one_hour,z5?303(q + half minute)c .01u=&-19%O+01::ze9>:8/*`?:300n?.00? ?1000Z~n10) def test_bad_(>!):Pwith Raises(ValueError,0 b `5^F1234567", "%z")  with self.assertRaises(ValueError): _strptime. ("-01:30123456", "%z"):f as errm-30eEqual("Inconsistent use of : in Dstr(err.exception)) def test_Pzone(at# Test  directives.A6# When gm&P() isdw%Z, entire resultFstrf-XemptyOCheck for e~names deals^bad locale info wGthisoccurs; first foundFreeBSD 4.4|_output = )Q("UTCZ:aM.tm_isdst, 02!n ?GMTn0q_tuple =S.:(f. "%Z") #UTC does not have aQAy]pQQer LGTime!if0.tz%S[0] !Q1] ordaylightWTrue(R[8] =SFE[8], "i" cailed; '%s' -> %s_%s" %H  *, ,)Oelse/-1 |.has duplicate vXs and " ".7 bujFset to -1"1bade ExAitly possibility<;#D:0^!1]>B0tz_eE!$`.upper3%n UV@skip('need non-UTC/GMT'!4upport.swap_attr(2, 'C', (#, U)), \J/ sFO', 17tzset', lambda: Nonen/ = - = 1 tz_value = _strptime. _(tz_name, "%Z")[8] self.assertEqual/SY, -1,+6"%s lead to a dQzone 6 of %s inst"of -1 when "L?.daylight setV%s and passing in %s" %B(B"tz,Y#, 1)) Fdef test_date( !):# Test %c directivefor positionwrange(6>BQ.helper('c',3(.Ax70,3@ xCX/3, X~percentMake sure % signs are handled properlystrf_output ="%m %% %Y", m.x_tuple)ApAJ TU'XYHWPTrue(1l[0] ==5and B1B/1]G"3M3of nQ failed"caseinsen.vecShould ~ s 5-65ly.3B M0.upx)?B")Y  does notALL-CAPSm"olower()Bl {`Julians&~jL (1-366)acceptedBall_1__daysPfor i range(1, 367B # 2004, si it is a  B, we8@366 B/eq@'%d \P' % i j %Y')[7], iCalculatiocLp) fillsmissing info correctlyW\setUpH_tuple = 0.gm(gc P~ F^qN%ed^`format = "%Y %m %d %H %M %S %w %Zresult = )f (b,)  ETArue(result.t m_yday == self.time_tuple.t?, "Calculation of 1 failed; %s != %s" %D (resultn1)) Edef test_gregorian_c(!):*# Test that G1 date can bed from Julian dayEformat_string = "%Y %H %M %S %w %j %Z"/0 = 2pQ. _(P.strf (_,) E).assertTruem?ear5andFe?monFEOmday   A"%s- Year,    NyR?monK9 4day_of_week60the 0he ;D is ted as neede0 1Am %d7S1w H.N8" %1xHif support.is_android"Issue #26929: b) on A/ incorrectly s %V or %G+ # 1@last QfirstATmpletC@n a .;_ymd_excluded = ((1905, 1, 1), 6, 12, 3B2008/29&R(1917(631)_ s'%G %V','Felse* %KLP@unit.skipIf(sys.plat.startswith('aix''bpo-29972: broken2IX'a_lculation(seclf): &# Should be able to infer date if given year, week of (%U or %W)Npand day%1the1 def test_helper(ymd_tuple,greason1foro_|_format in ('%Y %W', U [G %V'AE@if ( ESself.Us_excluded and?@<}>mreturnU3dayVA('%wuaA[_string =-q+ ' ' +i LQwith subTest(,37 9=6=Mo0dt_h! =Atime%(*y0strp_input?IP.strfG(E2outFp?. _('l?  ms"%r: %s != %s" % *?[7]._()[7]assertEqualU:3], V, msgJ`(1901, 1, 3), "i? 0", 8,common case11^n Sunday44f4/Mo4 513Jan 1 oi65j57jSfirstaZ` startj?on OA2, 3_Dec 38p 2008, 12, 29.AlastK2Ksecond-to-U"0"| 0197A0, 2Yrandomly chosen41<chosen date"3) #test_helper((1978, 10, 23), "year starting and end on Monday while "PW"date not on SuD#orN"17, 12, 17?ithaat the beginnrP!ofCB 31`Dec 31\B m 0200a!, _UFirst f : 14oSecond<6,Law6w;2xOto lEAdef week_0(self):check(value, format, *expected-1@.assertEqual(_strptime. _ Q)[:-1], V~ '2015 0 0', '%Y %U %w', 2014/T28, 0f6, 362:EWEt5, 1, 4@0, 6, 4A11 1zG %V %u9C03E0EE E?1 23R0!/360EE! E?1 3125EE E>1 4CO3, 1A A$A?1 52?4, AA , 2, 0, 0, 0, 4, 2) check('2015 1 6', '%G %V %u', , 1, 3, 0O5, 3A0AY %U %wA*WA"?1 740, 6, 4) a09 0 0B08, 12, 28D/36  E!09J a09 1 19o0, 364EE E?1 23Y0!?365EE! E?1 3126EE E>1 4CO3, 1A A$A?1 52,AA A~4~A A~ class CacheTests(unittest.aCase):0""" that caching works properly."""@def Ep_time_rcreation(selfTv# Make sureWqe is re/ed when current locale does not match whatOed object was LEith.*P_strp. ("10", "%d"j# -A2005/Y/TimeRE_cache.locale_time.lang = "Ni" original"_re = _strp1_TimeRE_cache3 *>("10", "%d")-self.assertIsNot(q,pDEqual(len(Rregexa), 1) ~def test_pleanup(!):"# Make sure !d 0es are discarded when" becomes "full".L6tryY]8delYe['%d']:except KeyErrorFEpass*bogus_key = 0owhile ) <CACHE_MAX_SIZEoY[yv] = NonU += 1L+!new_localeqA new L" instance should be creata1+RE objectD# is. ?_idK.)S,t*,8d?_id `!re>3ionBThe .}Aed upon changing the jdinfo =2get((.LC_TIMEJ )s:, ('en_US', 'UTF8')MCk.skipTest('q needs T.Q'W 0'10'%d># Get id of currentG.Rfirst4 0# Ce and force a 0ionq IR Pde_DED@559+^'s idosecond=jDTheyz0not~ee C *, I # Possible test locale is not supported whifnitial&7. # If this@the case jusJPress  exception and fall-throughO!to0resetting eorigin ^y.Error:Xself.skipTest('needs de_DE.UTF8C%')># Make sure we don't trample onB1onc,Pleave!Mvf*lyNB.set (.LC_TIME,q_info) \@.run_with_tz('STD-1DST1def_TimeRE_recrea_timezone($)b# The 0` instashould be Ced upon chang4he Toldtzname =.tm = _strp<. (2[0], '%Z< .assertEqual(tm.tm_isdst, 0e1e1e# Get id of current cache objectQfirst _r.8$0# CeWETdorce ako6chesos.environ['TZ'] = 'EST+05EDT,M3.2.0,M11.1.0'yFset(M9newV's id>osecondSThey 5c@be eU#lfiIsNot(*, u@old ] longer acve -Raises(Value8X(e@p if ____ == '__main__'AunitgP() imp collecTs.abc.Q from  1T *xmlrpc.cli2as tlib @Hb('XXX: buildbot.python.org/all/9/3gone') class P'B61ersWbCase):\_l>erslist of builders from the XMLRPC buildbot interface at # python.org.server = xmlrpclib.SProxy("http://[.DR/all/65/")QEtry: {;bers = m.getAllBFers(<except OSError as eL self.skipTest("network e/: %s" % eP/addCleanup(lambda:('close')()) # Perform a minimal sanity check ontresult, just to be sureHrequest means what we think ilf.assertIsInstance(A, collections.abc.S^-ncBTrue([x for x inif "3.x"5x],) def test_main()support.Eiresz pun_unitA!(Pn) if __name__ == "_h2__"i9() # Used by0doc.py. class TwoNames<'''f() and gpre two mssame method''' f(,>>> print(r@().f6f8return 'fig = f # define an alia`f # # &a suiteOptik. Suppli *Johannes Gijsbers # (taradino@softhome.net) -- translated/original `! #aw tos PyUnit-baversion.$Id$ # imD sys o $reDcopy ! 3io DStringIOZ ooptparse+/pmake_op",Ron, \TitledHelpFormatter$PRUGroup7SUPPRESS_USAGE2 Conflictp0Bad`#on SValue s_match_abbrev# D_numIC!edc!(EQ3ion__init__,M_message=None%xit_status# Ghm.i" =y+o)'s(S__stroPB or wO"go"2ingc( }Bexit Ua0, msg\( raise InterceptedError(exit_status=!, message=msg) def e5`self, :raise Interc`1_M class BaseTest(unittest.RCase)WqassertParseOK(y@argspected_optpositional_)LA"""AOp the op&s are what we exT when parsing arguments. LOtherwise, fail with a nicely formatted :vKeywordVU -- A list of%1 toejO%r.IT/ 3:GwzReturnsV:nd @s@ fur: 6ing6"""^(,D0 = ."er(=)optdict = varsPlF^PEqual#2 YR5 E%C)s. Should be %(3Args wers.""" % locals() V  P( +%(I(  r9 8NionsRes_func,j/kw ex?ionF) {!at37 `A is PdAcallDp, and tRrightzLincluded<D6tA rg ~S Ks'?/`<`1{3k0._< s~Gp@>GP(or p'rnE if a compiled regex object[mk1xis Nonep6= (3if T 1 kwargs = {} Etry: func(*args, **kw )"except expected_ion as errL actual_message = str(errPrif isinstance([6, re.Pattern)_=self.assertTru?.search(%),E T"""\  " pr: /%s/ \': '''%s''' """ % .I", D+)"Oelse [Equal w3 ! `returno"fail("""%)s not raised called %()r with 0 %(r)r and #2 %( #)rlocals ()) oa# -- Aions used in more than one class -FBdef `ParseF, cmdline_,goutput;5"""8` the pO r 3!s :@. CrCmust ensu t .Nis an Inter9ingOption%r.E QX(0sedErrorYMBPerr.e/ HsOfFalse(x\\ure")O(#_& status=0( Z=NoneD;aprintsM on stdout.Rsave_2ys. d  s9 = StringIO($_ArH 1kfinall!&= {.getvalueyQ$.INoutput, str),  $"expected output to be an ordinary string, not %r" @ % type(@9)) !$ifY4!= l_,:*Wself.fail(: \n'''\n" +A- +BF"6xbut gotE}0 + ")")C assertEqual(err.exit_status,?wmessage@Verror?JelseVFalseb parse3()"sBdef PTypeE_(Dg, funczf*args)vA"""Ae that G is raised when executingZ6.""q.R2"s(}jv, None,X CHelp4Ghelppactual_$ =#aformat(m8if .?K ureException(=-'@c text -;3_:\n"'<P+ '";/-\n') # -- Test make_oq) aka O / -JAIt's0nec ryt]correct `s here. All the $@s in $ #_`() sec; deal with those, because;y're needed #re. classChecks(Base BsetU73r =PI (u=SUPPRESS_USAGEuXRq=[], kw ,{}  , 19,Y _a_emptyL( "at least one1P mustLsupplied too_short x"invalidE'b':two characters long"n_["b"]H_t*J '--Y0"of   -x, (x any non-dash)--"]) def test_opt_string_long_invalid(self): .assertOptionError( '"< I! o' \ '---': "1must start with --, followed by non-dash",8["---"]) 2defOattr*D-b: keyword arguments: barob"], {'foo': None, 'bar }cI=aV!: &'' Otype=^[w$]gV: 'tuple'| & 0no_FR_for_C)"not supply a aR for a 'count'/)0, 'COint'choices_list+/--bad: X< ofw" '1, "\T/@1"Bbad_@aname =`p('').__!__F`w_be a  rs ('%s'qied)" % 'b"{"$",Os':"bad s-%no,+|u '% Oonst8 'cQ'%befo 'stor>'|)Z=: 1no_nargs9Qr action 'count'", ["-b"], {'action': 'co), 'nargs': 2}) 6def test_callback_no able(self):*c.assertOp]eError( $!"oT -b: UA not Uo: 'foo'f'`T\dummyOpass_no_tup7_V, if supplied, "0must be a z:-#AP U + kw4Ldictlo- _W5{4r6&nodBfor_55_! (;) for non-$ ._storet" ?Mo_@ZXq single_dash"invalid long string '-debug':- start with --, followed byQ#"]@?d:  B", " elf.assertOptionError( "invalid long op' string '-debug': "4must start with --, followed by non-dash",8"["QS", "- ]) class TestOParser(Base!):Fdef setUp(self!.p49 = C): %R.add_B("-vqverbose nk-noisyK ac/="store_tru@ddest="PqoRquiet osilent{1fal |9Vtest_B_no_)MassertType2b=  s"not an instance: Non(/) _argumentsHl l!", 4get?popt1 = .-l i3IsI(B,3,QEqual'a._shor@s, [^X?n"]98-?D(, x ',  + _e _Oopt2, Oopt33 )n",4, G1ATrue0 isr234q0has?ion Vf .6)6%removed{) 6=d]ME(/n"*#CTF 7 >(self.parser.has_option("-n")) self.assertFalse(jparser7`-noisy<=?Tru<q7r bs6 p-silent<sdef test_remove_short!):%fb, (+Ad() " oOlongn-verbose"ru nonexistentaRaises!., ('foo',), None,+ValueError, "no such ? E" +@support.impl_detail('Relies on sys.getrefcount', cpython=dQfleak# If an OP is carrying around a reference to a large# object, various cycleHn prevent it from beYwGC'd inCa timely fashion. destroy() breaks the[to ensure stuffIcan be cleaned up.`big_the= [42]F, =X(4S) =8( @.adda", "--aaargghM.g5 = *s.#dEqual(,Bdel SR$ class TestQ`s(Basey\setUpBpass#Rbasicz> vDCs = a Rvars(0_), {}+ Olues%2Not`N, {"foo": "bar"Y 4"jdict =H,Ouz": 42}rdefaults=B -' ! \)$ (H[]) yTypeAliax`str_aliases_string(seclf): self.parser.add_option("-s", type="str")1assertEqual(B8getB ).B , Caing") Gdef test_q_objectG?str5  x ?intu!%x" 0int # CustomeA foring process of default values. _time_units = { 's' : 1, 'm b60, 'h * d p*24 } _check_durab, opt,k6try-"if[-1].isdigit()Dreturn int(/FelseL0 ,[:-1]) * [Fr]=except (VError, Index qraise O-(E}' %s: invalid : %r' % () class D9_(}sTYPES ={.D+ ('Z"',_CHECKER = copy.O: 2[PK] = RTestDC`s(Base_setUpP)(A2v", "--verbose",_=True@q@Qquiet>Cst='N'@n"q/37=m=1-\="foo0aCGuL=Non:expected  : e,f'n': 37# @m': s% As': & tKu%&cbasic__s 9_HBs(),; UmixednO_pos 5set-(n=42, m=-1006o.update({/'i2}39ixed_defaults_pre(self): .parser.set_defaults(x="barf", y="blah")5add_option("-x", Bo="frob5Jy") [expected.update({'x': Q@, 'y }assertEqualg_values(), l fremove;@( yKNones)?def test_process_class = DuraO d", type="d:;300CeC ?"6mW \n="42){d': 300, 'e 6 on': 42?9u OFals8 0, '; TestProgName(BaseH1"""* that %prog expands to the right thing in usage, version,Band help strings.` U=", U,o>_Z{8#2.,-()>qVsu. w&) zW gn}Ih# Make sure|{@ram - taken from sys.argv[0] byb&@ave_!& =,!:]y 6try?Q= os.path.join("foo", J8z.pB?2 = `P"(";E..."=(1.DA = "@: barb ...\n/?. ,(-5 7"k5DHelpiQ] + "\n" +4 "A's:  " --version show program's number and exit\n" AUh, --helpUQthis xmessageN)Ofinally:`sys.argv[:] = save_ %def test_custom_name(self)Iparser = OptionP(.="thingy",Qr0="%7O 0.13u1arg arg".remove_oO("-h#*expected_uP = "U~": {$q.assert,(*, L1V63F1EHelp. a + "\n") class TestExpandDefaults(Base\setUp7est70p_prefix9A""\ :\" [Bs] ?sY-2D6 "">|Pfile_zread from FILE [d3: % ]>IB_L$Aelf.9+ \fc6=p foo.txt]? OnoneCZ~_ F.addcpf", "-- ]#="2|=(!, T)//_1CD.set ('5', .J2w s(&;%nob$x.  help=self.file_$) (assertHelp(parser, expected9q_none) ?def test_default!_1C!):#fER.add_option("-f", "--%",/3d_=None-W2CU%se s(N%;Efloaf 2"-pKprob"blow up with &ability PROB [3: % +]"HV=0.43, " =_prefix + \A -pA, --R E]\n"Vu kalt_expandg$"foo.txt:="read from FILE*DEFAULT*formatter._tag = ":8U =_  B/noA 5f f=  & # -- Test _args() -q classKStandard(Base\BsetUs = [makea", type="string")r 5b5boo>int", dest='boo'G!-fA ac%="append")]s0r = InterceptingOptionParser(usage=SUPPRESS_USAGE, option_list= 1s) Edef test_required_value(self):#kq.assertFail(["-a"], "-a V Fs 1 argument"jinvalid_integerkb", "5x"] "C-b: k k m: '5x'no_such_?a-boo130no A 3: - Slong_S?=x51.x5_empty OK([], {'a': None, 'boo f \}, []shortopt_n_oappend}{0, "--foo=blah! >$["M?"]}n C_0bar  =  ) #["xP_o_joine/bc?bc"   _split/34/34Hg`?"-beR34, '+1m_negative- )/-5* =13"],   {'a': None, 'boo': 13, 'f ?}, 9A[]) def test_long_option_argument_split(self):/?.assertParseOK(["--boo", "111"]| /116Sshortpfoo=bar_-axyzU'xyz'~s ["N]habbrevqdefaults(Us, args) = Ap;!r.q s(`M .Cget__values()Equal(vars(/As), )ambiguous; Tr.add&"--foz", ac;="store" @type-ring", dest="foo"hAFailjfe 5 " p: --f ( o, {oz?)") @8and aHF!,  V? lappend)b0123T /ba=/2;1, "JBone_posi aljr 5  consumes_separator --6c  mAqn"--foo", "bar"O],  {'a': "--", 'boo': None, 'f ["bar"]}E A[]) e"def test_short_option_joined_and_separator(self):6.assertParseOK(["-ab",`"--foo = n+),hyphen_becomes_posioal_arg7="-"no_append_versus!b3q!"5 =/z"5o, "bazPconsulike_strin/b3!"-$ AcombKsingle_invalidhpMEr.ad&"-t", ac="store_true")@Fail "no such a0: -[ class TestBool(Base 9\setUpEs = [makeO"-v" T"--verbose,`odest="cdefault='')[ q"--quiet* ?fal *)]YA = O"r(s_list =sSbool_ 3 _': '' S s, args) = ?"-q&{'0 7 l  DTrue.verbose is False) def test_bool_true(self):"(options, args) = !.assertParseOK(["-v"],59{'verbose': 1}=5[])nT._@ is flicker_on_and_off^qvq", "-  class TestChoice(Base_setUppr = InterceptingOr(usage=SUPPRESS_USAGEPER.add_P("-c", ac="store", type="c"Fdest. 7`s=["onM@"twoW|three"]bvalid_5 \?xyz "{'\': 'one' !["R /in@Fail?@four?abc 2 "S -c: sO0: 'I5' """(choose fromp, 'two'<')"% g.=d--default+f=1fiv%0sixn4optx4getK"-d"%PEqual.$, - #, () Oount`vp = make @ion(c2",  =\c.^ +4"--W?intsR_-quie&^_consu!, ,=0Qempty $.8], qNone}, Fh=_onF U Y1V@"-vv 3}, []) def test_count_three_apart(self): .assertParseOK(["-v", ], {'verbose': 3}, []) D joverride_amznvp-d;=2"s2sOquierqx0x?ing&tAv"],P 1interspersed_args-<3- O["3"-?no_pr.disable5))/0} no_such_option @FailqP "no C C_: -3"l!_no_valuem=sO ""-1 does not take a |with_defaul5set'|?, 0 7g; *?"-vh2Z class TestMultipleA@Base_setUp@ = I.ceptingOr(usage=SUPPRESS_USAGEzED.add1"-p=-point" H ac="store", n =3, type="float", dest="T 3_T@posiP/al1foo1 02.51-4. ?xyz': (1.0, 2.5, ?)7 }c@long] -point", "-1p", "2.5 -0xyz"],  {'point': (-1.0, 2.5, -0.0)}9 !["]!) ^def test_nargs_invalid_float_value(self):..assertParseFail(["-p!1. 2x ?3.5 "option -p: "dh " Aing- : '2x'"requireds`-7 |s 3 argumentsclass TestMultipleArgsAppend(Basew_setUppr = InterceptingOWr(usage=SUPPRESS_USAGE)mER.add_(P", ac="store", 2/=3m atype="", dest=""fW--fooa&25intQz>zer_const"}q!, 3=(0, 0)u OKs43@blah0 "1O666"LNone, 'foo': [(4, -3), (1, 666)][ ] _Of4,3 ] "-fx2xPso_simplz=t4 \o[(3, 4PJ M*-"O, "-k ", ", # Versionv  .`="%prog 0.1ave_argv = sys. 5[:]\6try:V%0] = os.path.join(os.curdir, "foo", "bar") self.assertOutput(["--version"]4g 0.1\n:finally:Kys.argv[:] = save_ %def test_no_^(|)D.parser = InterceptingOptionP(usage=SUPPRESS_USAGEE0KFail "no such ou&: ) # -- Test conflic default values and Vs() -q classKCJDI`s(Baseg7"""& p: the last one should win."""}_setUps gq_list=[F(Rmake_("-v", ac ="store_true", dest="verbos%[=1)])L_IF.add}q}3faln ~ y/=0JOK([], {'': 0}, [__nonegONone1\Group_!O+d _gt_create_instancP%8 =  w, "SpamTm(N5&P("--sO] `help=";  xp:D': 1_4i z`TypeError$r,{x"not anz  : M!", pinvalid(aumentsd9rB argr bwrong_T n1v8&r(}RRaise7_group, (group,), None, #ValueError, "invalid OptionGroup (wrong parser)") Mdef test_g%_manipulate(self):%u 0 = .Ea.add_oc?"("k/2" N adescriJ="Some more \:s").set_title("Bacon!Q("--b$, type="int0assertTru;getL1),  ) # -- Test extending andhK_args() -q classKEJAddTypes(Baseb\setUp = InterceptingP(usage=SUPPRESS_USAGE _=y"Myf+S("-a"string", dest="aDf", "--file" F larDown6if os.path.isdir(support.TESTFNu_os.rm&)elQRlunlink'b ]# (eacheck_l4,0, v eif notexists(*SraiseHc`("%s: pQ doesQI3" %uFv is=v"Ga regularubreturnLsTYPES =.@+ ("&",_CHECKER = copy.: 6[T]>wv<_okcreate_emptykqFOK([$ 6>oafoo"] {'<': >'a': 'foo'}A )[]!st!no4 Gelf.OFail./ A!  t+ _os.mk1 ["--file", s upport.TESTFN, "-afoo"],  "%s: not a regular file" %8 so) class TestExtendAddActions(Base!):Udef setUp(self!op0@ = [A.MyOP("-a"-apple", aZ1="ek" \type="string", dest="O!)]&wparser = ~P(b_list= 1s) 9" (7uACTIONSR.5+ ()LdSTORE_$.;^TYPED;  ;wRtake_]j1, opt, value2s, /#ifD == lL" =T.split("," *)s.ensure_(b, []).(O =Nelsey.k XBest_H_addc9~aassertuBOK([G,bar_=blah !{'P': [" 3, "E=} #[]q_normal(#-a-O=x,y&xY?y"]A# -- callbacks and._args() -CJ!mmKO("-xONone -$="W*=process_opt)m f`1"--TN8l  j ="_name"2-UhC]1ionm_` ifW-x": " self.assertEqual(option._short_opts, ["-x"]) 19Dlong84True(parser_ ish4Pvalue2ONone+Dvarse.9s), {'filename': F9}) _2u.x = 42"elif opt == "--L%": TfT"t\;1lue, "foo"\3, 'x': 42e{setattr,Zadest, Oelsekfail("UnknownA %r in process@." %def test_callback()_P1OK(,=&)], kV9 /[]\_helpa# This@ wasmpted by SF bug #960515 -- the point is# not to inspect&l text, jusmake sure that?bformat) doesn't crash.'[A = OgYr(usage=SUPPRESS_USAGE4p.removewion("-h#6add !t"P", ac$="" %r=lambda&, type="string@ 7= exW!ed"R = ("Us:\n"!* " -t TEST, --= w foo\nH#), x) class TestCExtraArgs(Base%MsetUq&Ps = [vpv_w|_tuple <_args=(3, int)F{!="s", default=[])]rb_list= sN ", b_, len~%33!54int) if opt == "-p": self.assertEqual(value, "1,2,3")-(elGo-pointL4,5,6") Me = tuple(map(type, .split(","))getattr(parser_.+ s,ion.dest).appendodef test_callback_extra_args() PgrOK(["-p C, "-2, "%],T !{'&as': [(EA), (:?)]}; []) class TestCpMeddleA@Base\setUpoptions = [make_(str(x), ac$="" *=.process_n, ='things'4 for x in range(-1, -6, -1)]HV~Qr = O"r(b_list= s$# "q that m(sk`rgs, le*.E#, i`#m is -3, -5, etc.W!ne` = intF[1:]rX.;qif len(A) < K^ fail("Expected %d arguments _#%sa." % (GK$ =J.ensure_XV , <g1[0:k]g{4&Jdel A% 1", "foo -32barzOqux" K"H@1, 3C _separator~2-'foo', '--'2?any10"-a--apple"/=2$`many, e="string")K$2"-b bo +3J4N-5many(self, option, opt, value, parser_):  if! == "-a"self.assertEqual(F("foo", "bar"))L(elNo-appleS@dingTOdongUbP1, 2, 3/boL-666, 42, 0)) def test_many_args(.Y=Pv@OK([c(, >C, "-)9, ",i0"-b.123 --U0666?42"H ?0"]" #{"P None9 }9 []) class TestCallbackCheckAbbrev(Base7U_setUpLA = OU&r(~q%a.add_o'("--foo-@, ac3="c 4 *=_c!_a v~Tadnz__expansionvZ)~ "], {}, @VarAfs = [makeva", type="int", n%=2, dest="a")> Estore_true"EbEc $--5"/variableEc")] = Interceptingusage=SUPPRESS_USAGE.b_list= s8 'BTrue1 iswr# =n.awhile  nRarg =&[0Mif ((arg[:2]-" and len) > 2) orf63[:16 51FZ@1] !'")FBYbreak\Jelse( p.appendz&>delsetattr(0.Fs.0): self.assertParseOK(["-a3", "-5-callback0foobar"], {'a': (3, -5), 'b': None, 'c': ["J}K A[]) k!def test_consume_separator_stop_at_option(self):5c 37 --0xxx -b_hellolp OTrue  ] " &@posial_arg_and_variables&\// '5c':9$3&bF invalid@Faila"], "no such <: -5") # -- Test conflict handling and p0!r.P?) - class CFPBase(\\setUps = [make0"-v--verbose", ac="count"i dest="?help="increment eity")]Hr = InterceptingOxCr(usage=SUPPRESS_USAGE 4b_list= sshow_vers,, value,eb.(s.FD = 1( J"""Use the defaul$`resoluP for k 1.2: error."""Pyc_%c, funcr erv9qRaises(O!48, (!$b"), {'$V' : " ?C'4A@'lD"@j 9$on}E< c"A -v/E:!string(s): -v") self,.assertEqual(err.msg, "conflicting option string(s): -v") MselfF4_id, "-v/--version") 9def test_ip_error(M!):#_\OTrue-.parser.add_ub l_grouphA = OG#^1, "/ 1Rvno_suchohandle uRaises(!'seOO, ('foo',), None,>`ValueEy, "invalid earesoluv) J class TestC)R-4ve(CBaseMsetUv,."!(",ve4P("-v"@, ac="callback"_ *=Sshow_, help=" *A  v1 = ^0get1ionwpverbose3 (":2($isT.0not22a`._long*Vs, ["M]l:q6a._shorHA/v":z# zv 6vR_ WOutput(["-h"], """\ suZj incremenity -h, --i&Athis message and exit1v1v! 1? ""&P OK?v"] #{';"': '_': 1}A /[]c*olve_long_opts(self): .assertParseOK(["--verbose", usion"],7>#{'5': 1, 'show_ver;}> []) class TestConflictOverride(Basedef setUppr = InterceptingOptionr(usage=SUPPRESS_USAGE)Ec.set_c_handler("resolve"4Qadd_ooB("-nEdry-run" P ac="store_trudest="dry_Dhelp="don't do anything-  const", _=42, #ry run modd7tesol hopt = 0get*eion("-  Equal(opt._shor8@s, []2 @longi1i@`Outputh"], """\ s`-h, --Dg a this 0mes and exit -n17 duo """) x =argxrlQ=_': 42+# -- Other oing. - _expected_(_basic =^U3: bar.py [9s] wqa APPLEuRthrows at baskerPb NUMvboo=NUM ut "boo!" times (in ordo frighten away all thepevil spirits that cause trouble`mayhem--foo=FOOBw  ing foo list for later0ingB sFw ="""t2P_firs~>-v1, -~@, -hy~age and exit$ """ _expected_help_title_formatter = """\ Usage = bar.py [options] O "== -a APPLE Rthrows at basket --boo=NUM, -b NUM shout "boo!"times (in order to frighten away all the n &evil spirits that cause trouble and mayhem) --foo=FOO>p store  inc foo list for la$fooing --BE, -h?show this @ mesHtOexitshort_lines~:wO: r i%, |t^  v8 / #m@ -hBvery+, /" &*. 2 6 1the + 3748< @  JNclass TestHelp(Base )$ def setUp(self Q.parsRmake_Q(80) iA*, columnsPA = [8d<("-a", type="string", dest='a',7;metavar="3!",\!="K `*")I Qb", "5int?booJNUM"f="! \\"O # P", ac="append. f1  " R ]U# We need set COLUMNSPconstructor, but 4 # we must restore its original value -- otherwise, this test # screwsngs up for4*s when it's part of the PythonHWu suite.with support.EnvironmentVarGuard() as env:3env['COLUMNS'] = str(columns)*return InterceptingOptionParser(o b_list= 1s) Bdef assertHelpEquals(self, expected_output)save_argv0ys. 1[:]Q6try-# Make optp believe bar.py is being executed;>sc0os.path.join("foo", "I".O~(["-h"]f4l:AQ_help:)3elf__Z4g_basicN_old_usageXKSr.set% "U,: %prog []!long_opts_first formatter.short1E = 0k r&etitle_q }("}"] = "80"~@ = Td`F('v  Swrap_  # Ensure that *p^0res3s $s variabl# Need to reconstructb, sincf';e only time*ulook atyOMSRmake_6(60:+6nGline#:RedAvery_iKounicod / ==SUPPRESS_USAGE @.addion("-a", ac!=" _true", i="ol\u00E9!B""\ 6s`-h, --9` showsI@ mesj and exit -ag6 ""3  v_Bq_descri): self.parser = InterceptingOptionP (usage=SUPPRESS_USAGE, adescriW="ol\u00E9!")Hexpect = """\ "" s: -h, --help show this 0mes and exit """\sassertHelpEquals(r!) 'def test_N__groups(D)<H.set2(Q'@ "Tis the program `` for %". V has IQ"an o= as wellcsingle3s."7,"= CG , "Dangerous1*s"@"Cau: use of s is at your own risk. It(believed that somO`m biteR.add_("-g", ac="store_true", !="JP(g;U\: bar.py [Os] 6$. ?  pa APPLERthrow`basket-Pb NUM1qboo=NUM4ut "boo!" times (in order to frighten away all y evil spiritPat caqtrouble`mayhem--foo=FOO@   ing foo listPlater0ingC = ! S#-g E 'p.epilogPlease report bugs/dev/null.Lg o + "\nL \na class TestMatchAbbrev(Base(Tm$"_a%!)(_.K"--f6{/oz": None37o7"/ie7"5/})nLm_error7^ wordmap = {"--foz": None, "--foo": None#ie3} self.assertRaises(" _match_abbrev, (s, wordmap),Y / BadOptionError, "ambiguous o: --f (--fie, "ooz?)") class TestParseNumber(Base!):odef setUp( .p9r = InterceptingT1r()F 1R.add_("-n", type=int/l/_Qtest__num_fail>p, ("", Q, {},eRValueu re.compile(r"invalid literal forO().*: '?'?")0xOoopsHCs?'?fKdef d/okbfEqual(5("002&x15/166%XAj1kj8i5b11j353:0) [snumerics^^BOK([?@"42"xz"0x20"]{ "n": 42, "l": 3o }, [] nP0b010_"-l01m5l8i F?008 2 "GT -n: uinteger v: '008'"pl/23sls_b0123v_0x12xy3Jx@MiscCase(unit.l_all__yblacklist = {'check_builtin', 'AzNO_DEFAULT'rupport.Fp,%, q= Smain(sQDrun_(__name__) if p == '__>2__'q() from0 im \t gdbm =.import_module("dbm.gnu") #skip if not supported im unittestos from .. ,TESTFN, _NONASCII, unlink filename =% class TestGdbm(p. Case): def setUp(self.g = None ,tearDown/iGqlf.g is7cNR.close()R()lst_key_methodstQ@ = gvEopenFV, 'c'd*assertEqualJ.g.keys(), [],g['a'] = 'b'Fg['12345678910$ 019237410982340912840198242>qb'bytes9fb'data#Pset = 6,5t[b'a', f )I1In(7#[$\[]X1key1.firstkeywhile keyBpIn(key,$F_set[Sp.remove) 1nex~6key&# get() andW`defaulwork as in the dict interface*.UF)b Is;2Oxxx'_-`Afoo'i Qwith Raises(KeyErrorK)0g['U]D? 4set+b3D[96v _e_condition# Try to  a non-existent Qbase.T ~"f,r$, G, 'raccess a dkkb gCArlambda:Ptry p,an invalid<Eflag(cDrx') d1est` parameter() by trying all\ .Vmodes"P_(s standardGs (presumably "crwn")Ve! =- set('fsu')# for mode in sorted(s): # put "c""Ufirst9@ self.g = gdbm.open(filename,4)/.close() # Test additional flags (presumably "fsu").4"= all - set('crwn'r:=Es#! +t6: def test_reorganize(()yP''csize0 = os.path.get^U['x'] = 'x' * 10000:1M LassertTrue(:@0 < 1tAdel ,gxj0# '+*' is supposed to be the same even after deleting an entry^oEqual( ,<'g.2 &11 >nA2 >= 0context_managerOwithNf as db/@db["~ Y Y""ti?r')i5qlist(db.keys()), [bwKpRaises(a.error|,cmfICstr(cm.exception),,x "GDBM object has already been #d"_bytes1!b'K key \xbdRvalue4" b'( ,`7/db5=db[94],  nmunicod! cRdb['ULqU0001f40w~JwOu1.en/)]Y@elf.assertTrue('Unicode key \U0001f40d' in db) self.assertEqual(db[@0.enWI()],DO AXvalueC'}2@unittest.skipUnless(TESTFN_NONASCII 'requires OS support of non-< 0Rings'@def p_nonascii_filename(!):D; = #2.addCleanup(unlink, ;sMwith gdbm.open(!, 'c') as dbz1db[b'key'] = b''y3True(os.path.exists_)rclist(db.keys()), e8.%],) if ____ == '__main__'3C() from 1 imBmock3._httpservers*NoLogRequestHandler6 iTestCasewsgiref.utilK`setup_iing_defaults0Ghead~H $CBase , 5CGITSimpl H .validate"os[_1,QWSGISC , ;A CmakeTt.clienteHTTPConnection'$ioStringIO, Bytes ufferedRP1jsocket>$platform[qpython_Qmenta l$os $re esignaly#threadingQ class Mock(J r"""Non-  A""" /__init__,"_address, Cu_ .H Gv_bind()(~ahost,  = .-`,0 = < O penvironK 2): """Non-socket HTTP handler""" def setup(self):.connection = zrequest'brfile,!w .@ 2nlfinishoppass !hello_app(environ,start_response ("200 OK", [k('Content-Type','text/plain'),'0DatMon, 05 Jun 2006 18:49:54 GMT')1]return [b"H, world!"]Iader ' / ' ';'.join(? ['9_X_TEST_HEADER'], QUERY_STRING']X!PATH_INFO']D.encode('iso-8859-1')<run_amock(app=, data=b"GET //1.0\n\n"Merver = make_s("", 80, app, MockS Hinp = BufferedRe(BytesIO(})(0out(@lder{`sys.st   = StringIO()8tryx.&_o((inp, out), ("127.0.0.1",8888hfinallKA = oqout.getvalue(), errcompare_generic_iter(^it,match{"""Utility to 73 a 9 2.1/2.2+ Bator with an2ble If running under Python <, this tests the;L us1[()/next( as well as __getitem__. '' must be a fun!Sqa fresh_ to0ed (since1may ptwice).sH2it(>`00forQm in `if not it[n]==: raise AsserQErrorHAn+=1 b@except Index:lDFelseo("Too manyhs fromnO",itP, StopIteraONameS# OnlzUS mode?8VizYer(it) is it\ SS!==U G@ 53 else:  n8b"GET /p%61th/?query=I  @b"X-P-HeadP 5-2. 80\n% *hc_app, 2= 2outlines()[-1],"'b", 6 2;7v;/path/  Rdata=M(b"x" * 65537'b"'\n{ 0bR414 RDP-URI \Long"validated41or()# the middleware doesn't support len(), so cM@! i'Uthere D u\Falsesl_Qion_eNf0bad(,start_respon_: "("]T", (' 6',''Lreturn ["]U3or(V.endswith(W|Qb"A sor occurred. Please1actadministrator.%| p;err2"": 0!) ;def test_status_validation_errors(self):-k1create_bad_app(;$(!environ, start_response26 !Z#, [("Content-Type", "text/plain; charset=utf-8")])T return [b"Hello, world!"]*&!>!Ys = [.('200', 'Asser3E21: SKat least 4acters'),MOX OKP dessageXgin w/3-digit codeT0Shave a space afterV]0fortus, exc_m!inPs2BPwith J.subTest=<2out, err = run_amock(yjaTrue(out.ends(xkb"A serveruor occurred. P e contact the administrator.VK) Equal(err.splitlines()[-2]L wsgi_inputK(e,sY0e[";.;"].read(s("200 OK"m,Cw[b"data`n3or(84| 4" HbyteiWUif inK.wait(timeout=float(1))y?]breaknonlocal received"z = len(b)0clo Jbackground =tQing.T~(target=run_cl_S9v.start(server.handle_L ;Ijoin:lf.assertEqual( , support.SOCK_MAX_SIZE - H class UtilityTests(bCase): def checkShift(self,sn_in,pi0art0out7outenv = {'SCRIPT_NAME':>'PATH_INFO':J}^util.setup_testing_defaults(env :_path_info3_,part9Genv[] k2]freturn envKDM key, value, alt=Non~0# C -wLUemptyjE sinstance(StringIO4IsI4 ekey], 7l`_Bytes^5\s )W1exic\key:altW I[#3altZYCrossW,**kw&kw{~ "kwV bAppURI?uriuefaults(kw)  !self.assertEqual(util.application_uri(kw),uri) 7def checkReqURI(D,query=1,**kw):,0Ssetup_testing_defaultsZ(Hsrequestd"FWtext,size,match):make_it('=,=1.qreturn FileWrapper(StringIOC)?6compare_generic_iter(uSit = /()  False(it.filelike.closedrfor item in itxFpassobX"itl?TrujSimpleShiftsdI ('','/', '  -x*/'00/',YcNone, h/ a6x/ycae//yg 8Q', '/8'Normalized @/a/b2/..!..a " 75 pn  !/y ;/< <;x'0//.bQ/y/./F g:d1a/bG,9xrsbu4', d D}key, value[ ('SERVER_NAME','127.0.0.1'),)@PORT8/80#ROTOCOL','HTTP/1.,__HOSTv REQUEST_METHOD','GETyTCRIPT PATH_INFO6wsgi.version', (1,0)%run_once', 0"multithread% tprocess& ( 'wsgi.input', BytesIO()), ('errors', String)url_scheme','http'Q)]:\self.checkDefault(key,value) *def testCross% s(8)KG'('HTTP_HOST',"foo.bar",SERVER_NAME=)mL,"0s",eoS="on"E/1D0?yesF&?fooEK0PORb/80?*5443@MaGuessSWassertEqual(util.g1a({}),  8 C0S':)"E.&onD F&1 loAppURIf!(Q://127.0.0.1/^.spam", SCRIPT/JG?%E4I_\xe4mt.example.com:2071/"M/="0[ ="D}! xe za$q$s , 8 f:8000/Tsetdefaultr<y[/],[] def testRequireList()Rps(TypeE,N!, UlExtrasPf\str(h),'\r\n'Yqh.add_h <r',baz="spam ,&; 5} foo: bar8cheese=None x '^  R\y'j J ) class .Handler(BaseCGIj"""Simple h'B sub=S@ing <92"""# records the OS environment at import time, but Avars# might have been changed later by other2s, which trips upC`Tests.E1()."3os_ = dict(os.t.items(tH__init__FS,**kw1`setup_eCing_Fs(kw]1m.OD}, BytesIO() bString9kw,8multithread=!, qprocess0 %( A, w/ passthrudef handle_error(self): Hraise # for testing, we want to see what's happening class HandlerTests(TestCase): `def checkEnvironAttrsA, ha9Tenv =".e3Hattr in ['version','multithread process','run_once','file_wr%r'M]X0if q*==/E andXwsgi_N is NoneKOcontinueo.assertEqual(getu(!,'b '+a),env[.1]) Oi#OSkfFempty = {}; setup__defaults(e#)X rom os import 0k,vw.items(eif k not)@ + Fk],v$nElIPIn(k,HEh = Testf(X="Y""h.Re(s h" (h!a["X"], ?CGItBaseCGI,&{}n eyurl_scheme', Uinputzerrors'In(key, S]=HTTPS="on"); vyta],'https' tj='AbstractMethodB0 = @name 5_flush','get_stdi@ err','add_cgi_vars%HRJs(NotImplementedE%, ,)@h._write, ""!ContentLength  # Demo one reason iterati s better than d()... ;dUrivial_app1(e,s#s('200 OK',[]return [e[.encode('iso-8859-1')]< z2z(fme'].encode('iso-8859-1')) return [] def trivial_app3(e,s):=s('200 OK',[]Qp'\u0442 35!412'.encode("utf-8"){4{# Simulate a response to a HEAD request ('Content-Length', '12345')h = TestHandler(gh.run(71self.assertEqual(h.stdout.getvalue(),("Status: gY\r\n"""?: 4$ehttp")6"))2LQ3).b''bs0: 8 %xd1\x82\xd0\xb5\1/2'#4]b4r\ndyestBasicErrorOutput(A&):)Pnon_e$(RN qraise A1ion ("This should be caught by h "7< )= 0 a*8err"3!%s =Type: text/plain+.O: %d%b % (h.sE,lenebody))Q  $+ F3mJIn("1", W|alue())  def testErrorAfterOutput(self): MSG = b"Some o# has been sent"+SeO_app(e,sGNs("200 OK",[])(MSG)< raise Assertion("This should be caught by handler") FAh = 7H(aeh.run(!.au Equal(h.stdout.getvalue(),b("Status: F\r\n"".encode("iso-8859-1")+~JIn("1", 7errnHeaderFormats&Enon_'';return []dstdpat = (*"HTTP/%s r"Date: \w{3}, [ 0123]\d \d{4} \d\d:A GMTK k%s" r"Content-Length: 0+" r~3mOhort ` _0for ssw in "FooBar/1.0", NonehnAsw =,and "Server: %s%Vor ""^7bqversionf_Z"1.1"`-Qproto+b0.9", <AH>iDTesthSERVER_PROTOCOL=by7h.origin_s = Falsegd.http_#= -R_softwareM,  sD, '-:?Tru,1if "==LX ZQO,b"";els=X\0 !re.match((#%(f_,sw)) M  F*N  0)  def testBytesData(self):!app(e, ss("200 OK", [1("Content-Type", "text/plain; charset=utf-8"),?)])return [b"data"]hh = TestHandler(8h.run(app.assertEqual(b"Status: Y\r\n"zb/: ; Length: 4% h.stdout.getvalue()CloseOnErrorside_effects = {'c-_called': False}MSG = b"Some output has been sent%Ces_('v[])(MSG class CrashyIterable(objectq.n__iter__ while Trueyield b'blah'qraise A5#io^"This shouBe caught by h"Mv []9rue ?v ! ' ,frPPartialWritepwritten`ytearray(?ArdDY?, b'pdI[:7]3e@ten.extend(/$_6len$ M\flush>Fpass`enviro{"SERVER_PROTOCOL": "HTTP/1.0"dSimpleiIO(), &0sys'Serr, lsmsg = "snot do  &esWwith WarnsRegex(Deprecationing, msgPhelloU >Date: Mon, 05 JunX6 18:49:54 GMT7/13&H, world!"Yten) if __name__ == "__main__" un0st.() """ Fodder for module finalizAs in !_m".9 import shutil impo)rt test.final_b x = 'a' class C: def __del__(self)# Inspect module globals and builtinsE.print("x =", x). .-shutil.rmtreeQgetattr(, '__name__', None)x9lenA?len7 c = C() _underscored@impoOcimeit @unit4sys io from textwrap 3tdedent ast.sup[!captured_stdout)err # t 'sault number of iterations. DEFAULT_NUMBER = 10C krepetiDREPEAT = 5>XXX: somexs are commented out that wouldprove th%verage b$ake a # long to run becaus3yc=;defloops, which isKarge. Thcbe enabled ifNre was a waywqoverridtX' #ZlP duriresting,3hisPrequi Ahang)he signa #8Afuncc*y @argu[.FakeTimerBASE_TIME = 42.0Rinit_, seconds_per_increUG=1.0 .count = Jsetup_calls]sVp._fake_ @r = k #pareturn-.+* aHpassypst_reinHl_emptyassertEqual(?4it.6("", 0), "",545osingle 1!, pass") def test_reindent_multi_empty(self): .assertEqual(timeit.<("\n\n", 0), )=4=t \n1") F?defMY"print()\npass\nbreak(N_, 4),(  r_invalid_stmtRaises(ValueError, @it.Timer, @_=None?oSyntax@'return'D*_yieldC0 from ()K+|C+continueF+ import *' Oetup*A*A-E+D.L+D.G `fake_s(C = ":H"\n!._% !r.+1()"<0inc:;?scallabl( D'CAi!, , number, globals ]q = Fake5(9t =P(4=m=s!r=[U ikwargs = {}f-#if@ is number = DEFAULT_NUMBER Uelse:kwargs['number'] = &delta_time = t. Rit(**:)(self.assertEqual(Afake=r.setup_calls, 19ccount,8-# Takes too long to run in debug build.,def testit_default_iters)C#@ gstmt, !) a `Nzero]\/=0f?fewe73ePable_+ 3 3rbsjDstmt_and_|l"2)*functionAEimei ?,Er=FakeTimer()$N,zu, DEFAUk_?Tl"=0 globals_Q" _ri 7 = j$t)=';.inc()', nRaises(NameError,<5VG?tmtS" #s=/()zRlocal5 6  +sarepeat , Rtup, U=None qdYr t = timeit.Timer(stmt=, setup=0, t=self.fake_3) kwargs = {}if repeat is None:6= DEFAULT_REPEAT$;els2e"[':C'] =a4if numbersseNUMBER?s:s 4Qdelta"t.2(**#<assertEqual(M .sps_calls,>Tcount8# *A7r[float(A)]) # Takes too long to run in debug build.,def test_ _default)#$Y|i Z@zerofs@\[/=0e Oiterf+Rf1few__and_n/W3=3,/=5oPable_xG 3' , D21tmt?tmt2*function! =i d [FR=FakeL)~$N{,3 *  _n"=0 [Z  *,  timer=FakeT @()) self.assertEqual(delta_2 s, DEFAULT_REPEAT * [0.0]) ?Bdef :_exc_string(Q&,  apected&aname):@(wlines =4a.split(Greater(len(CO), 2.FTrue' [0].startswith('Traceback' >)-1?,extest_printAio.S8'IO@t = 2it.V"1/0"6tryCG"t./Dlexcept'O.getvalue(), 'ZeroDivisionError'TMAIN_*OUTPUT = "1 loop, best of 5: 1 sec per6\n"Irun_main%,( onds_per_increment=1.0, ches=None,(r ["if@ is ' 6 = ?seco7%ifh0arg&[]:lse$&[:-q.append.fake_stmt#1it.<) modifies sys.path, so save and restore it.orig_sys_/% =:* captured_stdout() as s=q, _wrapU r=#&r.i[:] = return sHs R_bad_W>u1witT['--bad-9''] )s, dedent("""\Oxoption K not recognized/use -h/--help for comm  0C""")|Fdef ?5.5 05.5_milli,_0.005 !50^szm}?cro0W00025['-n100R ?"10_2.5 ufixed_iters(self)3: 0s = self.run_main(seconds_per_increment=2.0, switches=['-n35'])HDassertEqual(s, "35 loops, best of 5: 2 sec perQ\n") Fdef testp_setup()#T , '-s', 'print("CustomSx/").\n" * DEFAULT_REPEAT +)multiplesSIa = -3a'}fixed_rep"&,60/r9 1_9: 60negative=- 1P@unit!.skipIf(sys.flags.optimize >= 2, "need __doc__") ?heljh8# Note: It's not clear that the trailing space was intended as part of A #5 text, but since ibthere, check for it.A.stimeit.o + ' 'verbose v @dede5""\P -> 1sw@raw "s:#,>`5F O""")/y_0.000_03v@4R3e-05D;2 sf6&&1N&10O)3v (6( 50 loops -> 0.0015 secs 100 loops)3(2(6(5(x yx (x (x )x raw times: 300 msec,  M4100, best of 5Z usec per 9R"""))Ldef test_main_with__unit(self):;_U = A.run7(seconds_per_increment=%3,>switches=['-u', 'sec'])([assertEqual(wK"d yE6\n"aPv ;S&3;S&Je+03 0# Tinvalid e input captured_stderr() as error_stringiooQ!*I ?par .getvalue()7c"Unrecognize. PleasemQect n)y@, or.L+ exceptionN#s0?1/05C_exc( 'ZeroDivisionE'_fixed_repsP0-n1Lautorange,Y1/1024, callback=Noner = FakeTimer(1t =3it.Ftmt=self.fake_stmt, setup=self.fake_, timer=3) return t.autorange(callback) &def test_"[!):Gnum_loopsd_taken = 'XussertEqual(B?500)`, 500/1024_second(o=s_per_increment=1. 1QKid_with_ 0Ga, b print("{} {:.3f}".format(,e captured_stdout() as sQ= k/.a7expected = ('1 0.001\n'W !'2 2 5 5  10!/10!2!2!5!/49B!10"/98"2"/195" 48Ds.getvalue(), I) if __name__ == '__main__'@unit. () from contextlib importmanager @dateDfaulthandl$$osesignalubproces "ysy0sup.! cript_helper, is_androiditempfilehreadingddxtwrap`dedent try2_capi except I*RError)" = None TIMEOUT = 0.5 MS_WINDOWS0os.`nt') `_trace(lineno1, p2, headpmin_couEsregex ="I+= ' File ""S %s in func\n' %h1>@2@uif 1 < *s'^' + ( '\n') * (2 - 1) + "TOelseH%b + '$'Pskip_seg4_on-(5# Issue #32138: Raising SIGSEGV on Ac may not cause a crash.].z6If(,' R 'raising SIGSEGV on Android is unreliable')(test) @contextmanager def temporary_filename(): a0 = %0.mk 0() !2try* `yield %D gfinall$support.unlink(-) class FaultHandlerTests(unit.RCase)rget_output(self, code,@=Nond 81""" Run the specifiedE in Python (in a new child process) and read?OP from standard error oraA (if 1Uset).LRReturWlines as a list. ,QStriprreference countp 4forUdebugKcbuild,place "Current th0x00007f8d8fbd9700" by'K/FXXX"~ = dedent(0).sapass_fds = [][:@not 15.append(fdTwith SuppressCrashRe, = script_helper.spawn_p'T('-c'}= |PU stdout, stderr =q.communicate3@exit@1Gwait*D=i_o(~5 0.dee('ascii', 'backslashre,'<iR .assertEqual(]7, '>*Eopen*p, "rb")*fpV1I` = fp. ( els os.lseek(fd, os.SEEK_SET, 0=d, closefd=FalsearBQsplitD(), acheck_ 3_number, fatal%E, *,+b, all_^s=True, other_regex$G , know_cJI'C@ tha0e f" h Ks enzdGPtrace; ^ _IRaise an error if the output doesn't matchexpected format. 5""" if all_threads:+if know_current% $(header = 'C* O 0x[0-9a-f]+'ZOelseH T@<VStackkregex = r^{fatal_error} {O } \(most recent call first\)File "", line {no} in jqdedent(.(5U=_number, = %=0)).5p()Iif other_  += '|' +(?, exitcode = self.get_(, filename= v, fd=fd/\\n'.join(#[passertR!!, (NotEqual(B, 0)def check_>(d", { &g, **kw@Fr Python yw: %s' %DBp.+0 {`| windows_exception1WU  [D @unittest.skipIf(sys.plat.startswith('aix')") page of memory is a mapped -only on AIX"<_ Q_nullGif not MS_WINDOWS25w( import faulthandler$w.enable&&>"""73# Issue #12700: Read NULL raises SIGILL=Mac OS X Lion'(?:SegmentaR'|Bus/!Illegal instrucR&)'0",  'access violation')  @skip_segfault_on_androiddef test_sigsegv(self):>.check_fatal_error("""#'qimport cyhandler .enable()" $I""",53'Segment_c_threadtrin new 'know_currentc=False*$sigabrtt tAbortedP@unit. If(sys.platform == 'win323"SIGFPE cannot be caught on Windows"F?fpeEw? PFloating point excep\ U_bcapi is None, 'need ' Unless(hasattr(signal, 'SIGBUS')F. ?bus+yF  ;s`.raise3nal" RT 6Q'Bus u6?ILLM?ill?ILL 'Illegal instruction') def test_fatal_error(self): $i.check&5"""#'import faulthandler .Jyb'xyz').I""",23#_without_gildo, True'P@unit .skipIf(sys.platform.starts('openbsd')$"Issue #12868: sigaltstack() doesn't work on @"OpenBSD if Python is compiled pthread" not hasattr(A, '__overflowY'needd.;#()J [ Qrenable(=' 3'(?:SegmentaQ|Bus *)'0other_regex='u to raise a ! |@vA_seg_on_android^gil_released\uigsegv( YV*\_file# te'1ary#name() as 1w {+ $output = 1$({tc}, 'wb7(.(D 0 ,#_s(@""".4at(U=repr)4p'&c  \ == "win32x"subprocess@1suppass_fdsLtWindowsRi-_fOA$.TJFlR'wb+'JpDfd = fp.filegno()  self.check_fatal_error("""'2import faulthandler$=sys8.enable(%sg (_sigsegv(""" % fd,j4'Segmentation'&qfd=fd) Q@skip_seg_on_androiddef test__single_thread(U!):)d` yA3alluzs=FalseP 3L:""" 3;C1dis '6|code = &!}#8not_expected = 'FK Python R',stderr, exit.get_output(1W\n'.join(#assertTrue(rnot in 4 "%r is presen/ %r_ J,D)yNotEqual(3, 0L.#is1 $Rorig_r = sys. 76tryR`# regr may replace; by io.StringIO object, butVI '() requires thatXhas a fileOr# metho%]_"__l%%wa " =:~4  &w6 6q r; +D'b(8ckfinallQ7if %   d Oelse@ Nqd_by_de -S# By , the module should be F0+; print(faulthandler.is_enabled())" args = (sys.execut$`, "-E"c", code)2# don't use assert_python_ok() becait always ws faulthaN output = subprocess.check_(}Rself.vbEqual(&.rstrip(), b"False") ddef test_sys_xoptions(G!):!r# Test ? -X = "import$; print(r filter(None, @ if flags.ignore_environment else "",K X-{env = os.fi.copy( .pop("PYTHONFAULTHANDLER", ,D`, env=envM >TruL~env_varGPemptyiE varz9;sVdict(^env['x'] = ''F'|DEVMODE" So# non-?)1@ 4Wdump_traceback, *, filename=A, fd %&""6Explicitly call U`) funckQ and yR its .a0RaiFpn error3the&P doesi`match expected formatHn"D = { 5!r}$d*d};e'B(00%if\rwith open(w, "wb") as fp5=.(fp, all_threads=False) elif fd is not None:%4faulthandler.dump_traceback(fd,48all_thr s Y def funcA()IB() 2*A(<5"""$pcode = .format(filename= .8fd=Ah; lineno = 9h4'125 a&4&xpected = ['Stack (most recent call first):'' File "", pa %s inAB' %/no<$17<Ao 193'] `, exit = self.get_output(%, 6 fd,assertEqual(OH*r3, 0[test_sel.check)H _(>Mwith temporary#U() as Ba>P@unit.skipIf(sys.platB == "win32"w!"subprocess doesn't support pass_fds on Windows"uN?_fd$.T b('wb+' pPd=fp.MCno()truncatemaxlen = 500_S = 'x' * ((B+ 50$U('F'...8 = @i(t  {}P6 [}1unc.=S-eM4u %s 6;elf.get_output(code) self.assertEqual(trace, expected*@exitMQ, 0) Qdef check_dump_Kback_threads(n, filename):65""" @Calllicitly LD(allP=True) andw the output.ORaise an error if& doesn't matchg formaH8 = import faulthandler Rfrom Cing /Ty, Event0!BtimeaEi(CDif {b}bwith open(*, "wb") as fp7?.](fp,  BOelse`\ X Yclass Waiter(Q# avoid block Cmain r/s0xceptionLdaemon =  ef __init__(.+ &9P.runn=+(#+Vstop ( TA?run HsO.seto @.wai% lDer = P.star: } &0er.Kjoin8.(NU=repr)s51 = >Bget_v% = '\n'.^%if2 8lineno = 8O]%%10&regex = rv^ 0x[0-9a-f]+ \(most recent ckfirst\(?: File ".*`.py",  S]+ in [_a-z]+{){{1,3}}D> 23:9run6.r _bootstrap_innE @Curr=" {:0no} 5 28/$ c """ regex = dedent(.format(lineno=)).strip()<self.assertRG(output, F(Equal(exitcode, 0) Odef test_dump_traceback_threads(k!):+o.check1ONone\\_fileawith temporary#name() as 18P@unit.skipIf(not hasattr(faulthandler, 'later'),h'need B.@2()'}Mgpeat=False, cancelloops=1 %*,@=A, fd C how many times the %` is wrKAn in"out x 2.5 seconds'or"3"3 ifPTrue: 1, 2 or 33s dependingxPon reD and@options.Raise an errork/ doesn't matchrexpect .mout_str = str(date.cdelta(=TIMEOUT)~) = it;~ b6sys0)3= { }8<2= { eB = { u j +!r$d*d} Sfunc(!, v1fororange(*. =)=Q  !b Nbd.sleep+O * 5,k %if- = open( j, "wb" elGdbuMsys.stderr.So4Oelse=Z H 70ilelk.closet(  timeout=TIMEOUT, rrepeat= rcancel= aloops= filename= Fd=fd)trace, exitcode = self.get_output($, W : = '\n'.join(L%) \rif not :count = 2if  15I*= 22header = r'Tir \(%s\)!\nThread 0x[0-9a-f]+ \(most recenll first\):\n' %I_strhregex = expected_back(17, 26, a, min_=5apassertRS8!, `+Jelse9TEqual9&''6 $3, 0def test_dumpp_later(A)xo.check/T_[6_=Truefhf6f  dwith temporary_#U() as:TXDP@unit.skipIf(sys.platform == "win32"n!"subprocess doesn't support pass_fds on Windows"Y2 ?_fd$.TFile('wb+'pPd=fp.SCno() \twice #=2a qhasattr(faulthandler, "register")Xneed 6.4m=False, all_ts@ $unK)d chain wfd=None5"""LR3 a  displaying the 8a user signal. Raise&PQ and 0 wrnK.E"If@ is ,8!at=previousuis calledMan error ifBQmatch ]5at." um9ignal.SIGUSR1# code = """import faulthandler /ososignal9ys all_threads = {}(S um# unregister" &Pchain! pfilenam { +!r$d=:fd}def func()):Mos.kill(os.getpid(), .LoO, frameV(`.calleITrue| "ZFalser4if  = open( "y, "wb")i elGd is not NoneMsys.stderr.S,o(Ls=Z z1if o`2al.M s.J3=,z= ,!={}6if  ) K (A and >v?ile output =G t/el8 >print("Error:23al 1!",~=T lCexit1e/0/2#k.closeS( {0 = .format(S _ %2um= ?= #=   Fd=fdttrace, p = self _(W : = '\n'.join(L!!if 7if 1 regex = r'Current  0x[0-9a-f]+ \(most rec!q first\):\n'yNf_StackQ;expected_back(14, 32, #_passertR6, regex) else:  self.assertEqual(trace, '')(if unregister?#NoBexitcode, 0Dz 8}def test_}()f.check#*) <>.\=TrueM\_filePwith temporary#name() as 1*= P@unit.skipIf(sys.platform == "win32",^ !"subprocess doesn't support pass_fds on Windows" ?_fd$.TF#R'wb+'pPd=fp.GCno()|threadsMCall_/ _chainR)L@contextmanager~stderr_non00 =  =;try/2ys.$u = None+/{Raises(RuntimeError*cmV<YyieldNIstr(cm.exception), "1 is3Tofinall  _ # Issue #21497: provide a helpful e7 ifO# instead of just an attributeD0: "w has no%".-waulthandler.enable(cI%Qdump_GbackQ if'(fz:, '3{_later'b.`V(1e-3"`"8T(signal.SIGUSR1^ VUnless(MS_WINDOWS, 'specific to _ro_ for exc, U in (B? ('EXCEPTION_ACCESS_VIOLAa', 'acPviola~&') @ INT_DIVIDE_BY_ZERO', 'int divide by zero'), ('EXCEPTION_STACK_OVERFLOW', 'stack overflow<)):Gself.check_windows_exception(f""".import faulthandler$.enable()& h_raise}a~._{exc}C:"""3aname) @unittest.skipUnless(MS_WINDOWS=pecific to W'{@def ;h_ignorH[for exc_code in ({0xE06D7363, # MSC.v ("Emsc"r/3b4343523COM Call[ RuntimeD7CCRDO/=  ( * -> pdedent( /output, exit0 = R.get_5"assertEqual(*J, []^ )gqm9nonfatal#g# Thess are not strictly errors. Letting# display the tracebP@whenyX;d is likely9`resultnoise. However,A=may still terminate# process if re_'no9} installed vthem (which8typically<is, e.g.3debug messages).(P0exc 0 k0x3456789040=100070"7F`* &  0x/:x u  D# Onp older a 7 SP1w actual0$5hasK# bit 29 cleared}..4In(o$ A(exc"` & ~0x),test.skipUnl.ess(MS_WINDOWS, 'specific to Windows') def test_disable_w_exc_handler(self):04code = dedent("""import faultA 0.enu(> " # *_EXCEPTION_ACCESS_VIOLA`_raisepeption(Z6""" output, exit'0 = R.get_ >assertEqual(&F, []V %_a, 0xC05) if __name__ == "__main__"@unit.3() a from 0sup5 AV# used by regrD6T.run_b( .'.suite()0eap_children()uPload_4Cs(*_hxVtreturn  j"c4. (verbose, refcount(, ,strip_python_stderr, conly, start_threadsL temp_dirquires_type_collecting).script_helperok, make_, >4sys Dtime $gc tweakrefing tryCs5Dcapiwith_tp_del except I:RError:(C(clsgclass C(object;p__new__7, *args, **kw /3 Q TypeB('red .A:C ### SR ##8 # Bug 1055820 has severals of longstanding bugs involvs and # cyclic gc.ZPAn in: ceHCfa-loop, so becomesBtrash when # unreach#. L ainit__f7, iUi = i`} `GC_Detectorc# Create aI. Then gcCn't happened againG1 as{P# I.g%is false.  <0= F;:?>4it_(ignoredD& HDTrueG # Create a( piece of cyclic trash that triggers it_happened when # gc collect'.self.wr = weakref.ref(C1055820(666),X ) @with_tp_del class Un]able(object):e"""Create a reference e I multiple _Q__ methods. @2An P? inCll never have zeroh!s,Dand so must be garbageed. If one or moresst1theExee P, theb refuses to guess an order@leav"hu;aed."""kdef __init__(, partner=NoneZ$if@ is v=.<+ ==%)y3OelseE 71 pass ### Tests #8 ~!GC_(unittest.4Cas)Q_listPal = []!l.A6d(l3gc.(Udel l7C.assertEqual(4B, 1)=diced = {}Sd[1] = dS#\tuple@# sis are immut we closeBloop a \ Uvt = (l,=fttWt2t * AuA.a = A#/No0newstyle Y C}instanc*= ;6aMaM#M@requires_type_1ingo|?new iQ 0) class B(list): Epass(oC(B, A( ua = C()8 a.agc.collect%Fdel #self.assertNotEqual(76, 0`;EB, Ca>AAAM#zXdef test_method(7R# Tricky: .__init__ is a bound 9, it references the instance.jAY 5~|* =[;%<@cpython_only8legacy_finalizerP# A()0#unkpable if1is part of a cycle, make sure!shows upt # in gc.garbag[@with_tp_del.p*#__ `B " o Z0id_#Fid(aWb = B b.b1zfor objA d(obj) == Fobj.HUbreakJelse>fail("didn't find% (K&)";aremove nA_new@q,ecj_ @test_function(sself): # Tricky: f -> d f, code should call d.clear() after the exec toLQbreakecycle.ed = {}:("def f(): pass\n", d)#gc.collect(Udel d#self.assertEqual(4Q, 2) +@refcount_testz p_frame(I+( * = sys._get|9f!e1}|saveall# Verify that gic garbage lik0stsw up in gc.! if # SAVEALL option is enabled.= # First make sure we don't  away other stufcat just happens&e waiting for 6ion0N!# is fails, someone else created immortal trashC, []~eL = []9!L.6d(L0id_&i*qdebug =p1et_Egc.s |,cDEBUG_dL\R 0len"F), 1m3objJG.pop Lid(obj), u/de __del__ methods can trigge,e0thi4?thresholds5et_2gc. ~/qvclass A 2dirWa = AwaK`gc.disa$* s\A_new{## e97ectpJ$ef mV# The follow@two Ps are Bgilew+y precisely id number of alloca`!s,)p# whichnhighly implement'-dependent# For exa&, disposed tuplenot freed, but reus8# To minimize v:ariations, though, we first store the get_count() results # and check(@m atQ end.!A@ref9Q_test@def _Uaself):Vgc.collect()a, b, c = gc.;!ex = []0d, e, f0u.assertEqual((`), (0, 0)Y)Y)# This is less fragilA2an iing that a et2s 0(hLess(a, 5# Betweenatwo calls to,least one object waf# created (_list)G'r(d, a) X b_generS( 5ill "trickle" inR N + 1 afterAeach &(N; _0%0# xnow in gen 1c|S1S 2SS2S 3Sg, h, i# We don'ta, d, g sinc eir exact values depends onf#ernal implement details ofinterpreter` u1u1 utrashcanclass Ouch^Qn = 0CK|__del__EG.: +L !ifn.n % 17 == 0z% #&"@a hao preven overflow when deallocating# very deeply nestuples etc. It workspart by abuseJqtype po fields,Pcan y horriblHproblemsqgc trieqtravers structuresc0# I!isf! f(as it doe2.0, 2.1P2.2),Gwillmost likely die via segfault.Note: In 2.3possibility for compil/ wigt cyclic gc`removet"nd+in turn !ws_ mechanismamuch sr means (e.g., it never abuses the type pointer or 4# refcount fields anymore). Since it's much less likely to cause aLproblem now,w$various constants in this expensive (we force a lotOof full collections) test are cut back fromn2.2 version.Ggc.enable()uN = 150Bfor in range(2):,it = []6i2N26t, Ouch()?uR"6uRov = {}61: v, 2:Ecgc.dis@[1def_trashcan_threads(self# Issue #13992: 0 mechanism should be DQ-safef>NESTING = 6N_THREADS = 2 ,sleeper_gen(K """A generator that relea!GIL when closed or dealloc'ed."""jO:tryyA 'ofinall+Qtime.@(0.0&1)class C(list# Appending a $ is atomic, which avoidause of\&ck^inits?del@f __3!__0, a} XR[:] ="  C.G1s.aV(None!S__delkd0# TG&called by sub_*()b C.$# `g` will+f*garbage-Aed. # helps assert's behaviour sH`switchtQmiddl.itAg = c Pjnext(g{2Now$`finished,#}proceede#Flso R".make_nestedPCreatGsufficiently /@tainbject so&thriRvokedY at-itx = C([][ 0?k[C([x]3Zdel x3run """Exercise make_nested() in a loop.""" while not exit:' H  old_switchinterval = sys.get%()5 s F1e-5$:tryU = []G~threadsPfor irange(N_THREADS)VD2 = HQing.TR(target=run_4s.append(t"with startA#s(1, lambda:k?/1)ime.sleep(1.0akfinall"WGgc.collectelf.assertEqual(len(C.inits), bdels))def test_boom(selfclass Boomy5__getattr__7`, someWibuteFo@del a.%  raAAttr@RError1a =ba[E = b_baM:garbagelen =(3gc.t'a,_# a<->b area trash cycRw. Cion will invoke#.O (to see whether a and b have __del__ method7andNIdeletes thternal " " js as a side effect.OThat causGto get reclaimed via refcounts falling toP0, thus mutat#he5]graph of merely askingM!exists. This used to (before 2.3b1) chPythonHNow =@isn'Flled(aM6, 4, *}U#, _?len2WH25=Vx = 0#NE+= 1N"ifZx > 1GC A 2  aMuch likeS), except tKb1doedbreak the 8 # cycle until the second time gc checks for __del__. As of 2.3b1, G#?re isn't aI , so this simply cleans up4b trash . K# We expect a, b, a.__dict__ and b(4 objects) to getGreclaimed6wayeself.assertEqual(gc.collect(), 4)H *0len.garbage), Qlen) 7def test_boom_new(E!):Boom2ractly like )$, except useNnew-style cl"s.l BBNew(/$__getattr__ me[ibute26 l .%raise Attr@VError6a =mbacE = bgbaU); = %1dell Qrc/2_ CinitAVx = 0'#NE+= 1*N"if Vx > 1fC1(2 3get_referents7alist = [1, 3, 5] go:gc.@1Mgot.sort( Cot, 8_atuple = (}-k~'a = {1:E: 7}J'ed?, 7T o 2], {3: 4}, (0, )v [9@] + (range(5))self.assertE8qual(gc.get_referents(1, 'a', 4j), []) def test_is_tracked(self): # Atomic built-in types are not 7 , user-defined objects andiJmutable containerG."SNOTE:bwith special optimizations (e.g. tuple) havesIheir own files insteadtself.assertFalse;eNone))Y. 1+/.0- + 5.0j4?Tru]Ob"a".-bytearray(e}?int-03())hclass UserC bBpass+@Int(. r# Base 5#is|; no extra fields*ZSlotsa0__sg__ = ( kfixed size larger thanQFloat (f )#Avari[#Inw_] */gc +{2T$ f@.2 /[]?setK :%:8dbug1055820b Corresponds to temp2b.py X bug report.ouch = []iomcallback(ignored50[:]8wr() for wrhFWRs]] Cs#C"(i*i)range(2)] " WRs = [weakref.ref(c, callback) for c in Cs] 1c = None gc.collect()self.assertEqual(len(ouch), 0'# Make the two instances trash, and ] again. The bug was thatt#H materialized a strong reference to ans, but gcNqclearedV's dict anyway..CK%2) # elsqdn't runoxS:xA# IfA resurrected one o se guys,, Jwould be damaged, with7empty __ &__ !x,3)4def test_bug21435(1)# This is a poor. - its only virtue! it happeno# segfault on Tim's Windows box beforlQpatch[Gqapplied{0at'Qnastyprelyingcspecific pieof cycliT ar7in exactlyright order1fin_garbage()'sinput listP# ButLre's no reliable way to$hahfrom Python code,bso over time chpare goo"is!woPeally0GmuchO of9 thanymore. Still, if bl!upg_some_Fproblem ;-I n,vclass A[Bpass#B#__init__7, x8f.x = xP?3del>;MattrO=do_work(9Wa = Aelb = B(A()^#a.^bban*N W4is  (bad C pointer) whenCfailY1@cpP_V_at_shutdownbimport subproces = """if 16_|Acapi@.y_tp_del#Xk< #Gname&* 0 =  d%OOrepr4(return "" %% ]V__(self):  hpass x = X('first').xy1ksecond2Jdel 0gc.set_debug(%sa5"""Ydef run_command(code):p = subprocess.Popen([sys.executable, "-Wd"@c", F)],FJxstdout=M?IPE(1*# With DEBUG_UNCOLLECTABLE, the garbage list gets printed] ?gc.[+Z&UTrue(kG(b"[4 , c>]" inO) or:-;_ :  SAVEALL, no additional mess`should # (because gc.also contains normally reclaim@u cyclic# references, and its elements{runtime anyway).G-@requires_type_k1ingxtest_gc_main_module_at_Q('# Create a8e through2_P"_ R=Qcheckxb3# iL edFWrpreter K = """if 1"zclass Cj|__del__#('*l callel = [C()]>l.append(lrc, out, (lrok('-c'D{ Aout.@requires_typ0e_collecting def test_gc_ordinary_module_at_shutdown(self):37# Same as above, but with a non-__main__ K.9$temp_dir()B`script:'d; = """if 1"~class C|__del__sprint('. called')0l = [C()].append(l69"""0Ocode import sys7sys.path.insert(0, %rrB gc Ev""" % (w,BRmake_%" 'P#', 6rc, out, err = as_python_ok('-c', 8Y..Equal(out.strip(), b_get_statsf = gc.${ wAlen(4F), 3(for st in  kEIsInstance(st, dictE9elfset(st),"#{"Ted", @ions#unoable"}rrGreatera4st[Hed"], 08: <# Check that ion counts are incremented correctly; if@isen 'd(VddCleanup(gc.* `gc.disB(?oldF3gc.(E?new3enew[0][>oldF + 1K1K G 2G G 2 lfreeze3gc.*+_kRgc.un KEqual(gc.get_fr#eeze_count(), 0) class GCCallbackTests(unittest. Case): def setUp(self# Save gc state and disable it.=(70.end = gc.is%()&3gc.=;Rdebug9Aget_$Egc.s0Qcs.appendO.cb1&2&othergarbage = [] tearDowna #fRestor&3Adel WUvisit6gc.aremoveU & l<i$lf#gcl# destroy any uncollects:for obj inF qif isinstance(obj, UbXobj.partner = None`3gc.j9[:]preclea" all fluff from the system. Invoke this functionZ# manually rab than through# ) Ewmaximum@ksafetypVf  ,3[:]n@[:],/ <^L`*O1cb1, phase, info9\%(1,Qdict(1&))?cb2S2S"if == "stop"shasattrm"7up"=0# C0 ' + ucee% eI T |7 hif notu *ucWe}n_CODvS# Algorithmi>y verifycontents o# becaus is longtortuous.d,CIW`numberUPs to each VbnAv[0]v8 n1(i%i%n~1&2&2& self.assertEqual(n1, [1]*2) self.assert$Q2, [2$%# Count that we go e right number of start and stop callbacks.Jn = [v[1] for v in fvisit]'1(i%i%n if i == "e",2, 'op+k R""Oheckinfo dict6all :EV= v[2True("generation"582collected1#un3Gable5def test_$_().preclean(3gc.=(#1[)a], 2) @cpython_onlyoarbage`# Eachthese cause four objects to be gXQ: Twoz0# Un0ectmsYtheir instance[_01VC1055820(666!f !6op"continue  2ed"CU\*["C], 88 # We should now have the|LsP3gc. rFlen((J), 4CeI $N3IsI:(e, Now, let Tqo handl9s0up=G a{=[:]}:0zm :4} WsF&on \ $0) class GCTogglingTests(unitS.CCaseD\setUpQgc.en) def tearDown(self): gc.disable() def test_bug1055820c6.# Corresponds to temp2c.py in the bug report. This is prettyf# elaborate.|cc0 = Cz7(0)/ Move c0 into generation 2.%gc.collectT1T1Tc1.keep_c0_alive = c0M del c0.loop # now only c1 5s62i2i2wr = weakref.ref(c2)V callback!Houch = []f)(ignored50[:]8vc2wr()]QU# TheA gets associated with a wr on an objectg.c0%0,`KccHNoneWhat we've set up: cJ1, and c2 are all trash.#P%in#teQthing1it ?t|c1 pointN0it.(inc00in U-'swere's aOdglobal2@c2 (q), but u has noN]olso a X00 ()Xdoes havew) references@via '()!c0NXVz, which]/wrI^|G0 ab7Fdots6). | Io| 0 below &j^->c1 2nI8<1| "@<--v" S So tnightmare: whe(kPed, weNc-T-free10c1 n't even@B. C0@!seIal^70 i" a6. gc clears c1G!c1?side effqof dropp#refcount o c0BP0, sogaway (despiteOit's in an older generation) 8# and c0's wr callback triggers. That in turn materializes a referencePto c2 via c2wr(), but gets cleared anyway by gc. ?We want to let gc happen "naturally",preserve the distincLwbetween%s.junk = []Ui = 0detector = GC_D(;while not +B.gc_5ed:Ijji += 1f i > 10000-1self.fail("gc didn't Rafter93 it&s"A assertEqual(len(ouch), 0+ .e d([]) # this will eventuw6 gcg1K2els]0wasuinvokedPfor xj A# IfDresurrected c2, instance would be damaged,d # with an empty __dict__& x, None)def test_bug1055820d(4)# Correspondstemp2d.pybug reportiis is very much like#pcZ!us__del__ method ead of a weakrefKHto sneakV0ion;cyclic trash ;class D(C M. %T0[:]W8]iwd0 = D(# Move all abGinto& 2gc.collect(XTc1 = &(1c1.keep_d0_alive = d l d0.loop # now only c1 5Qs d0 6(c2i2i 2wa.ref(c2)V!H R0# Wwe've set up: d0, c1,C2 ar6.#w'in +! 2eQthing"it?t|c1 pointNi(c1i" 00in G-^Were'sNa globalZ@c2 (7nUu has noOP# Therd otherU)#|6!d0]aC}rs E^|G2 2 6dot+#. . . . . .` . .|.# #| Generation 0 below dots6^->c1  2 has a wr but no callbackV1| "@<--v"  So this is the nightmare: when ggets collected, we seeNdthat c-free weakref, and c1 doesn't even have aJ.B. Cp:ing@ see d0 at all. gc clear"c1v2PN!c1oside effect of dropp#refcount onrto 0, so goes away (despite it's in an olderEZ) d0's __del__ triggers. TTin turn materializea reference tovia c2wr(),L2c2 `ed anywby gc. pWe wantG0letNhappen "naturally",ppreserve distinc(LYbetweE%s.detector = GC_D%()!junk = []Ui = 0while not KB.gc_5ed:(ji += 1f i > 10000-1self.fail("gc did\b after93 it&s"A assertEqual(len(ouch), 0+.ed([]) #Awill tuw6 gcg1KEelseX!watuinvokedPfor x E# If?aresurrA c2,3Pinstaywould be damag eith angp# emptySVict__ x, None) def test_main()enabled =#isE`gc.dis!(3 missing = (set(l1) ^q(l2)) - K$if7Mprint("l1=%r\nl2==%r" % (, file=sys.stderreQ.fail("%rtH|.pop())9sHasattr:Pobj, =h:43A) or<(. ?+if: returnZ33): 0B???"^True(?,bf3'ex6%r, %r)'/) 98key8?key70key!0obj0/ .!oin objbQ***",?A1In(,=obj+EqualsOrIdOa, ba]bab .#inj and b (Rcheck0Nam9=?=()?R.readHB_ex(  ) corresponds  to the actual module object,. Any identifiers in ignore are d. If noD is provided,rppropriateLmis loaded with __import__.''' 2or = set( 1) |"['7'])0fUNone:K1# IgK it.(''to work around an API !@ines!)K=!(Name, globals(), {}, [xdict = pyclbr.readC7_exMdef ismethod(oclass,z, name)c,0.__)__iTinstance(obj, Mb1def_nested(J!):gCmb =# Set argus descriptor creation and _0_tr6allm, p, f, t, i = @', '', {}, None~source = dedent("""\&f0w1(a,b,c2(a=1, b=2, c=3): passW(return fR)d)%class c1@C "T )."G?F1({"Method0''Pd/ CR25R!"C within :8R3(): B 1+1q6"""8actual = mb./e0("*F0# Ck&e }s, linked together,expected dicA"f0w@FuncsA'f0'1"f1(%$_f.f0, 'f1', 2,2,1,V2', 3,cXP(UcU5)CC6+FTCFW8,C,)C)1C*C1/F3C2, 'F3', 140= {y:vC0':C0}0Ncompare(nt1, children1, 2;B"""Requality of fpairs.lZCEachU,g )p defineree. The)Fs arFassumed sA. Cuing theionaries as suchAdoeswork due toparison by i tZdoubl agWe separatD`ng str>number attributeDfrom| 1of *""j.assertE(j1.keys()29QO obi:ovalues:obIs(ob.5=\)2.\ self.assertIs(ob.parent, G2)  for key in children1.keys():)4o1, o2 =+e[key],2 8t1 = type(o1), o1.name 2fil Cmodu nlinenoFzF2F2F#2.F%2.F/2.FEqual(t1, t%if is mb.Class- Vo1.methods3 |9# Skip superc`0es now as nott of example0com($1.x%) ;3None, actual, expected/def test_others(Bcm =sacheckMi# These were once about the 10 longest sm('random', ignore=('R)) # from _& import "9CoreGeneratorX8cgiUPlog',Rset with = ?hpickleBppartialF* # TODO(briancurtin): openfpMdeprecatedwof 3.7.=Update this6it has been removed0cm('aifclP', '__params'/# 0sre2s@dumpQ`groups !poR5constants*; propertyFpdb'9ydoPinputg1out D)) #N9iesf2est9s inside package[Pemail;ser.`_pyclbissue_14798 #)! IPErrorraised whenFfirsPa dot& i#aRZ's(p", R.read  _ex, 'asyncore.foo') if __t__ == "__main__"Aunit() """ TascriptpUnicodelementation. WrAn by Marc-Andre Lemburg (mal@l .com). (c) Copyright CNRI, All Rps Reser NO WARRANTY.  t_string$csitertool>dstruct/%sy) warnings &0sup", _Rs # handling (bad der return) bsearch_funcH(encodingq#7!1(, errors="strict"):# return 42 # not a tuple def encode1(input, errors="strict"):)LI2I(42, 42)@ unin deN1iing=="test.m-1"(", r1, None)/elR2R2R2LR-sew cs.register(search_function) ,uplicate_sng(text1"""Try to gefresh clone of the specified =new object with a reference count=21. a his is a best-effort: latin1 single letters andvQempty? ('') are12ton-0can"be!d.5.2().() class StrSub C(str Dpass"U@Test"@ing_/s.Common,x!MixinStrBUserString4 *@unit|.bCase):gPtype2b = strcheckequalnofix(self, result,, methodname, *args =%Rattr(5-Breal]# =V(Q"elf.assertE(4P-PTrue(1)["))2# ioriginal,ed make sure that0# tdoesn't happens&%es.6if _'[P usub>Y__repr__$(! 'K`%r)' %.<3" =]"1' 1Uv5_literals: '\xff', '\u00ff'+3uff-0U00/1Raises(SyntaxE&`, evalh@'\\UHofffe\'q@f@%%08x\'' % 0x110c000) # raw strings should not have unicode escapes6self.assertNotEqual(r"\u0020", " ") -def test_ascii(8!):!ifksys.platform.startswith('java'04 # Test basic sanity of repr(*m'abc'), " "4%\\6 \\ :o9'8c5c6l54n4n3r3r3t3t3b3?x085P"'\""8""'\\'"'""q9(p ''l?'''P" ""5 `latin1E = (-x00\\x01234567p8\\t\\n b^c\\r"TePf\\x1]1]1]1]1]1]1]1] 18-9aT1t 1c"dc 1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHIYJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7fP@\\x8888888888 8a78/8dY8V9c9c9c9c9c9c9c9c9c9c9c/9bY9v9V9c9cacacacacacacacacac/a9Yavaacacacacbcbcbcbcbcbcbc/b7Ybvbbcbcbcbcbcbccccccccccc/c5Ycvcccccccccccccccccdcdcdc/d3Ydvddcdcdcdcdcdcdcdcdcdcec/e1Yeveecececececececececececefvffcfcf4\\xf5\\xf6\\xf`7\\xf89abcKd" "eIf'")testrepr = ascii(''.join(map(chr, range(256)))<self.assertEqual(M, latin1Y 3b# Testk! works on wide unicode escapes without overflow. | "\U00010000" * 39 + "\uffffi4096),I + (I)) Jclass WrongRepr:g`def __0__()$(return b'byte-0'L;xRaises(TypeError,,#()~  if not sys.platform.starts{('java'basic sanity of ()$'abc'), " 3%\\5 \\ 9m8 pa4c5j43n3n2r2r2t2t2b2?x084P"'\""2""'\\'"'""8'n ''j?'''x" ""4 I = (wx00\\x012345608\\t\\n_0c\\r0`0f\\x1]1]1]1]1]1]1]1]11/1aT1t1 1dYc 1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHIYJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7fP@\\x8888888888888888V9c9c9c9c9c9c9c9c9c9c9c/9b9v9V9c9ca0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9Pxaa\xab\xaWad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7" *"\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5K'c6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3K'd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1K'e2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xefK'f0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfdKe\xff'")testrepr = (''.join(map(chr, range(256)));self.assertEqual(L, latin1Q 3a# Testj! works on wide unicode escapes without overflow. {k ("\U00010000" * 39 + "\uffffi4096),H  H)) Iclass WrongRepr:f`def __0__()$(return b'byte-0'L;uRaises(TypeErroFepr,#()}_iterators# Make surobjects have an _?__ method@it =h1111\u2222\u3333".2(5next(it),C- j-GQStopIPion, L, itB\count>pstring_cs.Common._23 # check mixed argument types%(e_nofix(3, 'aaa', 'Z +a' 606b6 -3,k/ 'l / 'l0l616/-1 _, -10; 2u0>= ={ # >"Okind (1U\u0102' +1 * "?U:?304C%'\U00100304' + '\u0102' * 10, 'count',3) self.checkequal(.a88U00100304't AB^+ 'a_/a_AkCE2 a:&a\v b= GHdef test_find(R!):dpstring_ s.CommonTest.10#K implementation details of the memchr fast path>}'1000, 'S-1, 'D?201D?120D.2D -6L2 L)20L!#  mixed argu:o typesPnofix 'abcdefghiabc@?9, @ ?, 1C def', 4) assertRaises(TypeError, 'hello'. w3F, 427UOkindL(V[8(aN@>D;  9GCRK9 = cBeckequal(100, '\u0102' * 100 + 'a_', 'findca_') self.checkequal(100BU00100304F> c-1, 'a;:x dO}\HWdef test_rr(b!):tpstring_!s.CommonTest.21#M! implementation details of the memrchr fast path?!UA , '"V &aF?201F0?120F02F  #6 *M ?204M)20M!#  mixed arguBo types" nofix(9, 'abcdefghiabc"B?12,B ?' '?!Okind( a'$aZ<?C|7+ '>`e(h(:1x C_L H_ AqE _)   ?l(-1, '\u01022' * 100, 'rfind', '\U00100304\u0102') def test_index(self):pstring_!s.CommonTest.21elf.checkequalnofix(abcdefghiabco', '')> O3, '>?defA   9 A;, 1DassertRaises(ValueErrorJ.l, 'hibC'B%'"Dghi', 8 D-#c mixed kinds(X + 'a4,'a+rA E61, '53('a)'C1xiLjOBf_/a_$G3 L'aE aHyq Rer3M,12}r $@9M )C  CP, 0,   .B self.assertRaises(ValueError, 'defghiabc'.rindex, ', 0, -1) self.asI2abcLIAghi'I8H4# test mixed kindscheckequal(0, 'a' + '\u0102' * 10' @U00100304D!~I ) ~()D+HdM k_ ;_a'Br6, 'F_* ! EI%"!) e1def~_maketrans_Plate(*!):(< # these work with plain 1 6nofix('bbbc2bab'=%',im @{ord): None}l ?iiil5!, |Bb'): ?i')x4c?'x' A'w1xyy!xzz yyhis needs ( rt 'b': '`tbl = (`.type2.B{'a'/, @: '2ababc', 'translate', tbl) # test alternative way of calling maketrans(6tbl = self.type2D.)'abc', 'xyz&d':4checkequalnofix() zy+abdcdcbddddxqvariouss switchfrom ASCII to latin1 or the opposite;Hsame length, remove a letter,9replace withonger string.IpassertEu("[a]".I(str#UX')),C["[X]"<c{'a': 'X'}eNONonef 0XX30O\xe96% _'axb'9@, 'b?123u Ox123 st%5") 3Bnon-g(don't takeffast-path-<{> [' "[K {'!apak46,]O[123 aps<\u20ac)W d invalid Unicode characters#_ = 0x10ffff+1"for before in "B\U00/%":/z@mappG={H(: v}<text = "[%s]" %{ _'Raises(ValueError, A2#, e+Q4TypPself.type2test.maketrans) self.assertRaises(ValueError, xtype2te@, 'abc', 'defg'O ?TypN2JI/2.I?', P 1{'xy': 2}.R{(1,)Jx'hello'.Olate0'abc:axyz') @def p_split(5!):epstring_!s.CommonTM2L2#N mixed kindsMfor left, right in ('baa\u01010U00010301\ '0'jKU *= 9a[ |Rdelimvo2o2eS.checkequal([z+)],0 /1, 'i1', 6n3m] u$?v} n( *A4* 2}2r37]v"@ o8 left + delim * 2 + right, 'rsplit',2) def test_partition(self):"pstring_%s.MixinStrUnicodeUserS PTest.$ IH#h mixed kindsr .checkequal(('ABCDEFGH', '9), \u4200')Qfor left, in ('ba,0101\u0100U00010301\ '0'KU *= 9a[|vceo2 e2eS zB9'),8  7-*:z.Fxd}%C52$  Z r&- J5x| g+,W,$B E 2$ [ ?joi.Drclass MyWrapperm__init__, sval):  ! = def __str__(self): return .sval # mixed arguments-checkequalnofix('a b c d', ' join', ['abcOd'])K !bcH/G(G)G pw x y zF string_tests.Sequence('wxyz'T91raises(TypeError12', MyWrapper('foo')O'3', bytes(K#1, 2, 3,@P@uniti .skipIf(sys.maxsize > 2**32,*u'needs too much memory on a 64-bit platform'@def __&_overflowXnX= int**0.5) + 1)eq = ('A' * 6#,) #lf.assertROv '.b, seq)N}replaceCommonTest. 4P,# method call forwarded from str imple ation because of unicode one@two!three!Jone!"R@', 11 5=. , "r", 42A#Fkindfor left, right in ('bta\u01010\U00010301 E0'):KY *= 9[ |Rdelimvo'e2ei<;;;3;?S(+R* 2 'aace', , F|Oepl !q:f.checkequal(left + right,  2 'replace', delim * 2, )Nself.checkequal?epl"u> @support.cpython_onlydef test_pace_id(!):Bpattern = 'abc'CtextF def@.assertIs('.^(L#, 0), !) Vbytes_comparisonUwith _warnings(.simplefilter('ignorBkW= EQ == b , False5!5?Tru4iytearray(s)t@ oi5# Cs,!'w(7Od' >(1' <'#d'Fif 0# Move theses to a Unicode collation modul$1...A# Testing UTF-16 ;point order "s= >No surrogates, no fixup requiredn a\u0061v\u20ac'C6Nonbg below_valuew v d800\udc02o} abp } zlecmp(s, s2i 0s <)!Lp/(sH2%\u1C "sF9F+aF2bF2/d0+F-F)'\udb00\udd0K1' test_lecmp(s, s2)"s2 = '\ud800\ude0F+9F2aF2bF2?fff^*F-F-F 1Sfixup('\ue000'V %uff61') K# Surrogates on both sides, no ] required6self.assertTrue~bc02' <4d\udc56pAdef islower(G&):Vyuper().$..checkequalnofix(False,p1FFc', '] 9/c2167'.,+()f-?217,# non-BMP, uppercase$vU00010401z 12P~/29~ 0/4E0|  OF40DNIF46F1_IxI $if not sys.platform.startswith('java'}m}Xu|+|7u} - O|1z0{ 0}{ N| N] 1} 1} N}1_}Utitle} super().test_istitle() self.checkequalnofix(True, '\u1FFc', '8'8bGreek >ocases ...K# non-BMP, upper0b + low )`assert('\U00010401 C29'.+():$27:/4E: # apparently there are no Kdd (Lt) chars in Unicode 6`for ch[ 29zFF40DuF46F']:LFalse(ch, '{!a} is not'.format(ch)) LCdef `space(U)hVsuperA$ ZA@2000!is8Ao\u200a88_u20149~ s 01p)27 s %+(). _alnum $6FD7F6@7106104AKjOF107 ?pha$8KWalpha N#Q 01H0E`; 0c=.isN 1)6F@_ascii $ {m"0ac",- UIffff1 }decimal0, '#is:Ffix(False, 'a', 'isdecimal') self.checkequalnofix(True, '05@Fals6\\u246; # CIRCLED DIGIT ONE O;xbc # VULGAR FRACTIONO QUARTERW O\u06ARABIC-INDICOZEROT0123456789> ? Araises(TypeError, 'a)e, 42) =for ch in ['\U00010401)27E4E',K=KFF40D=FF46FF1065yF107']:LaassertE(ch.(), '{!a} is not .'.format(ch)FD7F67106O04A0/def test_isdigit()super().$. a\ SF, '\K76+8mTYF D!a D7*U VR mP}numericR#is:0655:8:U"? _VRe"abc".'\U00010401', '\U00010427'9n4E', =FF40D/yF46F']:0self.assertFalse(ch.isnumeric(), '{!a} is not .'.format(ch))Pfor ch in [F1065FD7F6O1066 F04A0/OF107?Tru  def test_isidentifier()*&iI"a".0 ,Z,_,/b0-c-/µZ 𝔘𝔫𝔦𝔠𝔬𝔡𝔢GT." .)-[-/©.WprintableVy.T +abcdefg\\2/\n4# some defined Unicode character 9o\u0374Y$unVN O8Osingle surrogat V1d80 c`9.is5 5lE0020'5jCsBrsq('a\uD800b\uDFFF80FFF?800k 6a7'a' s.islower( )W*?upp*XtitleTAB0FFF$0800$@FFFA7A  ) for meth_name in ('islower', 'isupp title'): < = getattr(str,P)+Rfor sc`\uD800bc\uDFFF <800 vself.assertFalse((s), '%a.%s() is h' % (s%) ; Palpharisalnum Rdigit uspace',F 'isdecimal2numeric4 identifivprintabzf"'ab!, 0FFF(0800(1FFFgM;afZ-def test_(T[pstring_!s.CommonTest.2K Equal('\U00010427'.d64F'} =1Gvz v$4F9j&4Fj9X427x l0 B 6fi 'q Xu01302\u0069\u0307j# Special case 4GREEK CAPITAL LETTER SIGMA U+03A3F[u03a3x73c3r5 45;A A<* Ba/c2 CaD/3aED"a3 C#c2 3B C<c[ Y8fffe@ :217&urMfold@uhello'.1{ assertEqual('hELlo'.casefold(), 'hello') self.assertEqual('ß3/ss0 ;fi1/fi1 k\u03a34/c38 A$ 45 ?a b9F o\u00b5~Qbc') def test_upper(#!):5pstring_!s.CommonTest.21 c\U0001044F'.d/27 '&4F Gv '/&27 j1j9Xx l;  x/FI. f\u0130b# 'E f5 z1/SS K1fd2!39 08n/00A Y8fffeE i\u21779@u216CcapitalizeH 7U 07R. L W/4Fy:104WoN0 27/),9 @(4F@ h.d0 'H6Qexp = 0 0su|v?exp finnishB 'FI=  'A\u0345\u03c2') def test_title(self):super().")elf.assertEqual('\U0001044F'.P5), ?27'=Gv `9j < N'27N1FZV$4F%27(XXx ?4F ;/4FR  fiNNISHw 'Finnish8 A\u03a3 \u1fa1xy@"c2?9xyIAAQ3a') 1~swapcas`tring_s.CommonTest 5Q7 5 O27'.@/4F   J Qm P* 1$G '273I 9fi^O 'FI1 k\u01304`\u0069W0u# Special  for GREEK CAPITAL LETTER SIGMA U+03A3N{?3c3 0345/a3>9D Ea[F2f.assertEqual('A\u0345a3a'.swapcase(), 'a 99sc3A') self.assertEquaHG2F a3q/45F c2/99F #E Fca?99 F?8 +ß4/SS0 k\u1fd24y 08 Q00') def test_center(!):pstring_"s.CommonTest. 32 3x'.]2, '\U0010FFFF'),6l ('x)( *^3^]h4h-}P@unitT0.skipUnless(sys.maxsize == 2**31 - 1, "requires 32-bit system")(@support.cpython_onlyase_operati!|verflow# Issue #22643C2//12 + 16try?. = "ü" * 9)except MemoryError8Iq('no enough m2 (%.0f MiB pd)' % (e /620)d`uRaises(O, s.upperCkfinall\del sL~ontainsPing Unicode c*u method`In('a'??bdb#?bda#aGb#7NotmlHEg1,None(%O,'a') --) %R('x',1,'y}+,2bcd_cxxxxb'd$# FbpL! self.assertIn('', 'abc') self.assertNo$/\0& G#/\0K%_abc\0p%alI @asdf' !/sdr(?') Raises(TypeError, "abc".__contains__# test mixed kindsTfor fill in ('Au010a\U00010300'):33J*= 9or delimNc\N2 N2NR I,*.7In(+" +3 d6O * 2e/i1defi_issue18183(<'S0000 10'.lower('casefold*?uppQpitalizeSOtitl'@swap Qcenter(3,  -_ljust,r,lformataEqual(''.*G), '*a+a, b-b. *{{/{/ *}}/}/ *{{{ *}}/}/ a_a`# examples from the PEPeimport datetime9 "My name is {0}"'Fred'), !"gM [X]SPdict(=]%), w'v} :-{{}xnmB#}"5d =L.U(2007, 8, 18 The year_. d ;n# classes we'll use for testing class C: def __init__(self, x=100)'+._x = xCVformaEOspecDpreturn  EDrQ3!tr6.x)"# with __str__, but no __ E?zVs'E(' + _+ ')'?rep4 or F? F that forwards to string,P some +'sG?"U is "9(ifz == 'd'ZHGq+vobject. LI(datetime.  @strf[($_J(intx6-inJ * 2 M  ~MM | = NoneNeN _3assertEqual(''.-u(), '')`*9abc-0 5{0}0'-", e?{0:6#J{ 0 8'), 'abc')  self.assertEqual('X{0}'.format('abc'), 'X  5. 7N{0}X7oabcX')7nY8oY9 &{151,  X9sr  s &1};u 0-15?-15 (0}7-15 ?-15# A  {{- }-}- +{{/{0 x1x2 7{0}40123O{1239: { :}}{/}0 x1x2f# weird field names "{0[foo-bar]}"#{'':'baz'} J JJ A ':3O3') '{foo._xfoo=C(20)/20 8{1}D(10), D>1@ W0._x.}3C(DBx6[0][, 'def']A1A Jo'{0[1][F 1[D(J')]K# stringv'{0:.3s'& 9/ab pU \0<u 3&2:c') #self.assertEqual('{0:2.2s}'.format('abc'), 'ab') 939 : 8x<0saresultv z ?x<5@,6@,7@ x8A B/ < @-> > A^A/^9 B1DX10000a' + ' ' * 9999 DC=> AU000) # issue 12546: use \x00 as a fill character4A6<1foo{0fooO O\x01I 1!I/0^I EA foo33  /<6J"J,0^J J e'b.1.144.14| DD D3D J@ =s'12P+2.0j `(3+2j)0\x00\x00')  !self.assertEqual('{0:\x01<12}'.format(3+2.0j), ' j)!3') X Y/0^YD\x00eY U2 Le ') "# specifiers user defined type26abc$0C()!:abcj!r, !s and !a coercionsZ &!sXp'Hello'\ ; :<)/15>L _!s:15<Ir""n /!r >{#F(r!F() !`\u03783"'\ ") # nonprintablm O4O[4'") # L1F('#4'a/, \=p+ O\a5*5# A # test fallback to object.__%__- {}d/{} 1 []1/[]11213 &:dgrG('data G( E@ ?string is GGRaises(TypeError, 5^105, EBC#>X&, "{0:date: %Y-%m-%d}".format(I(year=2007, #month=8@&day=27))Ap"date: -08-27") # test deriving from a builtin type and overrid#"__%__Fself.assertEqual("{0}".((J(10)), "20{6P# strR( specifiers# Yd'{0:}'Z`'a'), computed X"{0:.{1}'hello world', 5i/')GsH2precision}P$={width}.{=a,U=10, .k p H'10'r!'5tvarious erroDRaises(ValueE&D, '{N22aeaf/{a3UIndex00 414/bc2m3KeymU '{x;o4"}{|3uabc{0:{9/{0lO"{0.h!5?, 0[m!5O, []n O"{0]n!&.[7U..foos<[9ueError, "{0[0:foo}".format, 0) self.assertRaises(KeyError, "{c]85 SValue7"{{ {{{0}:r =8 _bar=370!x98X ?!rs:#!7 UIndex:4!ih%big = "23098475029384702983476098230754973209482573"Gp("{" + bc+ "}") @[A]Bu, [0]) # issue 6089<]h"{0[0]Wo[None]@E(10)U$, C%# can't have a replacement on the field name portion=4Typ'{0[{1}]}'V, 'abcdefg', 4exceed maximum recursion depthp 1x:{1:{2}:tP', 's'=L:{3:{4:{5:{6} 0, 1, 2, 3, 4, 5, 6, 7rstring Tp spec e8sW_ -d?, 't, "", "-"=r# Alternatetis not sup>%ed0 '#7920'sNon-ASCIIEqual("{0:s}{1:P("ABC*a\u04101E2"),K A'ABC' 3}+.3zCvd0d"),  T'') "self.assertEqual("{[{}]}".format({"{}": 5}), "5"):a : "a"=a= v"; };[v[;!;!; Raises(ValueError, "{a{}bpO, 42d;:%0x{:0{:d}X4p(0x0,16;0x0"_# Blocking fallbackjm = M('data'&!rypm), 'M(5)6)6Typc%!sB?, mm75_n = NnN (6 ndef test_P_map(%): #''.{;:/'a1 ?'ab3b!O'a{{5{5 /}}5}5 /{{{ /}}5}5 akal@# usJmappingsrclass MW(dictP__mis@!__[, key(,`return`j{helloT) ^ a} {worldG3a='EP /InternalCinitW = {'a': }NsgetitemQJ ]U[key]Q}:'{a  (\C def __init__(self, x=100): y._x = xdef __formaEOspecDpreturn DXassertEqual('{foo._x}'.V map({'foo': C(20)}), '20') G# test various errorseRaises(TypeE%8, 'i)4a56EValuk{7O, {}p : :au'av'{"};a## issue #12579: can't supply positional params to FE l{'a' : 2 B?'a'L{a} @@{"a"@, "b '1}class BadMappingugetitem?key?1/0+4Key:{!u ;/[]" ZeroDivision~#() huge_precJ+string = ".{}f"(sys.maxsize + 1_with T cWresult =c(2.34, _} _widthonumber{{}:.6f}}NtRauto_4> ua{}b{}c@0, 16a0b1c') Oua{:{}}b;p'x', '^@, 'aYx/ b G:{}xHa20, '#Pa0x14?# can't mix and match numberingUauto-; Raises(ValueError, '{}{1~ , ~<?1}{<&O:{1}=&0. , 1Unamed5(9f(4, f='test d E{}{f ?4@! {:{f}}{g1, 3, g='g'2O 1g3I f-{K2A(2, 1NI$4g@def _7Pting(!&):0tz_&s.MixinStrUnicodeUserS PTest.$ JI # %> u! sFEs...0 "%s, %s" % ("abc", pabc, ab? @, %i, %f, %5.2fOg8, 3X!.0o, 3.0 l/-2m/-2n@A-1, o*.5r53Yo, 3.57s7 Ss?100v$xif not sys.plat.startswith('java' okQr, %r\b0"b'E(bci Jqual("%r" % ("\u1234",), "' W'")  self.assertEqual("%a" % =>:(x)s, %(y)sD{'x':"abc", 'y':"def"}, 'abc, def'NO\xfcQT U'%c' % 0x$, 2P214833AU000  Raises(OverflowError, "%c".__mod__, (0x110000,){&'\rOType|7"aa"FValu:.1\u1032f_1.0/3E ~i<~# formatting jobs delegated from the strimplementation:D'...%(foo)s...S{'foo`...abc G ,':123}, H'- RQ%q(1,2,3,T!),1...2...3% ^h5q 7WY0%*s50(5,1'o' abcy6-7_abc 7 .o2q? ab:3:Di %*wh10, 5,A?10 ;i%sF3I 7?103L0'a'class WrapperyFdef __str__()#ereturnl%h(v%) 6# issue 3382NAN = float('nan')  INF = float('inf') self.assertEqual('%f' % NAN, 'nan, F,?NAN, X_INF, X,eINF') # PEP 3930.1s"a\xe9\u20ac", 'a /.26E issue 19995class PseudoInt:fdef __init__(, value)'+.q = int( $ONGvreturn N3dexCFV *16Cpi =v(3.1415!letter_m'vInt(109"W *xeo42, '2[ X*P15, 'So)o9, '11 c) 10+m* _, '6d0 0D0 0?1551 1RaisesRegex(TypeError, '%x format: an#eger is required, not', operator.mod>0', %),uXu*X', 2.11uou*o', 1.79u_Me/piy  Ac', >ORtest_ting_with_enumN!# Q18780>hpimport 0(y, W.EnumP?API =3[15926B(YO.Int<IDES = 1)Str(struABC = 'abc'rP# Tes Unicodestrings... self.assertEqual("%s, %s" % (Str.ABC, O), '$-%')-?sele , %d, %i, %u, %f, %5.2f" %; o Int.IDES, b Float.PI, F, 153.141593, 5') y# formatting jobs delegated from the strimplementation:D Z '...%(foo)s...' % {'foo':}0<'<*fig (hi*@h 158d*bJub, 'def':x8frb,q?123l Hdef test__huge_precision())_= "%.{}f".(sys.maxsize + 1Pwith LRaises(ValueErrord(result =Xqb% 2.34xissue28598'subclass_rhsD# A 0 of an __rmod__ method should be able to hooka# into% operator# SedStr(stwl, othe'turn 'Success,L={!r}) was called'P#'lhs %% %r` _'rhs'0 "U"v@support.cpython_only _c_limitf_=pcapi imb INT_MAX]G' /W6xQwidth % sys.maxsize +S 1) with self.assertRaises(ValueError):,3result = format_string % 2.34 +pdef tes@artsbC_end T s(rZfor meth in ('foo'.st=", D8`3Typj as cm9qf(['f']exc = str(cm.exception$2In('str', exc& Ttuple(+@support.run_ _locale('LC_ALL', 'de_DE bfr_FR'bd\floatV# should not e a comma, but always"C  Equal('1.0%.1f' % 1.0)constructorunicode(obj)& s (this maps to PyObject_U*) at C levelkCtr('l remains 9'),,(&wBtextPasciiA\xe9Qu20ac U0010FFFF'subclass = StrS(V }>?), 2Glen(26 iirxt == '.1.en:D), b AEiutf-8'EF >\s are convertedW1dSjCompat0__init__;, xwUx = xe>3str=:breturnx:!0('_ __patible o}Arecognized')4;A#(is!to}&):o,2ingo@ +JDo), HT G1objF123, 123.45  Abj),')_, encoding, error) tests (this maps to # PyUnicode_FromEn dObject() at C level) 5if not sys.platform.startswith('java'):0lself.assertRaises(#TypeError,/st'decoding u2 isupported'Jo'utf-8ystrict'|ZEqual`str(b'Cngs are Ted to4', ~ +Jct')B,nmemoryview(b'character buffer Mj  :M kGT C 42,71def] _constructor_keyword_args(U """Pass various , argument combinationW the ]E."""q# The oBpan be pkdd as af.:I='foo'), 3b,0, e<Cing=Fe*55out@` triggM"Eo" mode ^==1 #")H ,", Udefault\Check:+f'' or b'') /') 3`utf8_cq= '¢'.$e(\ q'¢sq/ctrD_='ascii'decs_utf7AutfT5= [+('A\u2262\u0391.', b'A+ImIDkQ.&# RFC2152 exampleL ('Hi Mom -\u263a-!', b'Hi Mom -+Jjo--!'), # RFC2152 example ('\u65E5\u672C\u8A9EN+ZeVnLIqe-I? L Item 3 is \u00a31.Lp+AKM-1.SL +;+ #+-?J?'),83r'\>AFw#'+-7r'\<?AXA# $/Bc&4++-?+--\U000abcde`2m/c3g)# surrogate pairs!'/C/ %] $for (x, y) in utfTests: hself.assertEqual(x.encode('utf-7&y)T@# Un&ed@s arssed throughe a'\uD801'hb'+2AE-')=x>x? C|3|?C01|>| ;.de`=/x'>| >| =|"PHab9z( k"# Issue #2242: crash on some Windows/MSVC versionn |b'+\xc1Q, 'ignore7)''}rDirect ^d characteset_d = "ABCDEFGHIJKLMNOPQRSTUVWXYZ8fghijklmnopqrstuvwxyz0123456789'(),-./:?"H# Optional d o = '!"#$%&*;<=>@[]^_`{|}'LVcQN cMvascii')z 0RB oZdef test_cs_utf8()c I'8b2\u20ac'.encode('u tf-8'), b'\xe2\x82\xac') self.assertEqual('\U00010002'.encode('uHf0\x90\x82L_23456La3\x91\x96L \ud800H, 'surrogatepass@d\xa0U cUbU CM*10)G~ `B1 D '\u6b63\u78ba\u306b\u8a00 46q68\u7ff!33,f'E@3055 8c69 44 7e 5b9?02\u4e00E@90e8' 6f c9aE c49K 675-4cE@3001! 42"30Q9]8?8*/67E`5b9f\u969 Q0cWenn ist dasE Nunstuck git und)),EPe6\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8L yH'8648LWbf\xb@bdXf0Hd5#8c d&84.beH0\x9tD2\x92\xe4\xb^9\x83HLa(C\x89h 8HSa\x9e47 9L51\x1H$  dH9p 1aH`\xe5\xae\xX@9\x9| @ %) # UTF-8 specific decoding tests( @str(}&, Lj KxKK  Gyu20ac' Other possible u cases:# * strict'/for all of the3 br8_ERRORQ in PyUni| _DqReUTF81def}a_utf8_ e_valid_sequences(self):  sequences = [ # single byte(b'\x00', p), (b'a"a' @\x7f)),?1# 2TsUSc2\x8Y%80LRdf\xbPmu07ff'R3Ree0\xa0VFu080XWed\x9\d\ eeB8uE0FB/ff4QF0\x9`bU00010d%Zf4\x8tU0eFFFF')0] for seq, res in :#self.assertEqual(seq.decode('utf-8ares) 9def test_utf8_*_invalid_Y(X)k# continuationa of 2, 3, or 8=_ `([x]) xQrange(0x80, 0xC0)s# start}pof a 2-Dequivalent to  points < 0x7F7 2B_YC2 4`> 0x10 4 F56'F8 (m$+ 9#+>)0+ [s F7(10)?e- Raises(UniD aError,<$,  r(sbp wc2E *(sb+cb)} ~1J[:3]/3337 A6  1+80'+cb3 w \;A0)1zEvror,  (b'\xE0'+cb+ BF').decode, 'utf-8') <# surrogatesfor cb in [bytes([x]) xrange(0xA0, 0xC0)]:;Xself.assertRaises(UniDiError,26 D/80 <vA< '8'9'GFO80\x+XzOBF\x/29/VH'F4V/[z/def test_issue8271()i0# I #: during the  of an invalid UTF-8  sequencea# only?Rstart(1andcontinuation(s) are now considered#u, instead ofJ`numbers specified b~.OSee http://www.uO.org/versions/d5.2.0/ch03.pdf (page 95table 3-8, Row 2more informQaboutalgorithm usedFFFD = '\ufffd'`Us = [  gx"P80', ^@), #b  S15!*2729kckWEc0\x!W#1@cD cg# with-;@a 2-?y2 34\xc7G # 2z<23n!*3z374A+'A'5 m # with start byte of a 3- sequence (b'\xe1', FFFD), # only the starH37!*2922s373737;4;4;-801 continuation)4A+'A'qinvalidA%\xE+fJb followed by _b(\x%2 N *80I1 KJ'e1N *2.K1andQTotherO 4161> T7 Rg# with  4  f  Ef1\x7 37 7;  ;?55+5?1K=A2KAc!cb  3+'ADI2?W8!3 cvIcMO5+Q ZB ~S!A'TPJM $4b2/cm (rfc2279)y5D), # only the start byte p(b'\xf5', FFFD*2), # 22s3*803only 1 continuationqF80\xB3uB2BF4F3AE\x41A+'A'B 1 valid cb and 1 in G DK+O/),4 416 *2 <d# with of a 5- sequence (rfc2279)8vt$ D8\xf7$8j3l>one@[D4 + L v5! 5sBj  6cDc\xf7R cn*k *CKO66 J# YeW x% Dp# other Ex42\x43', '\ufffdk#\x=%ff'=CU? lc2\x81|9S61\xF|E PC2\x6MP0\x63\xBF\x64'w '\x61\u ?A E]ifor n, (seq, res) in enumerate|%):3q self.assertRaises(UnicodeDe`Error,!.dp, 'utf-s'strict'QPEqualz<(;preplaceBCo+b'b')I +%M >seqFPignor <  Cres."('A')) 9Bdef LCorrectUTF8D8@ing(, seq, res, ecrr): 5""" (Check that an invalid UTF-8 sequence raises a UnicodeDeError whenN'strict' is used, returns res+ 'replace$2andudoesn'tO= anythingAVignor@./with self.assertR(v) as cm%Qseq.d('utf-8')fexc = cm.exception qIn(err, str(exc)A%nEqual(n,')Ds>(b'aaaa' + + b'bbbb') T M#+ L0=.('\ufffd', '&9S  2def test_ _start_byte(HBTestCan '< < <1' e/"isNdthe first%is not in !ASCII range or\"a d of a 2-, 3-, orO 4-s U. TheA!d Ba singleKbU+FFFD%s=E.g. <80>a continua- can appear only after a5Q$= x2for]in b'\x80\xA0\x9F\xBF\xC0\xC1\xF5\xFF'+CorrectUTF8DAing(@ ([5]),|,} )<uunexpected_end_of_datay@@ end@}%ngOendsIZ R.out haviPNough3s. complete3\ C, F3lbDx , but it's followed by2 s&thEOlast0misQNote:Y mu:Re all~ , if one of them is  invalid another error will be raised. *5""" sequences = [&'C2', 'DF',PE0 A0QE0 BF 21 81CC BD2D 9BEE0D 'EFF BAF0 9rF3 !BNFF6 N!N3!30 'F8!N4!14 8,FN!7] FFFD = '\ufffd'for seq in:#self.assertCorrectUTF8Decoding(bytes.fromhex(seq),f DM 'unexpected end of data') def test__cb_for_2P_seq()Test that an 'C continuation H'E#is@ when the 4@a 2-@sE4 is. The startfLgeplaced by a single U+0and{` secon" teWuhandledFseparatelyBs='r['@E.g.t , C2^ r@, but 418bnot a $because it'sKASCII letter 'APx2 = E * 2X`('C2 0H5+'\x00'), 7mJ7f')$C<$x27F7/O('DFn?DF n, E18thepof a 3-sKs?,<is a validq, but 4Y6not)bLbecause it'sASCII letter 'A'Note: wheG E0 or ED,Eranges forUfirsty KJlimited to A0..BF80..9F respectivelyPython 2 us9consider ally>| N#BF4was ED. ThisPfixedIt35"""C= '\ufffd'Qx2 = !5* 2Us = [('E0 00',5+'\x00'), '7F%7f80Nx2),O97JC2F&EA>A0 Bw?A0 z /BF/BFz?BF z*BFz1k 1t< e1bJ8V(V'w8V /1 VzV= CVCVCCV C'C' V CVzV= zVDVDV , E1a3aKs?,<Bis a!q, but 4Y6not)bLbecause it'sASCII letter 'A'UNote:is E0 or ED,E ranges nfVy J limited to A0..BF`80..9FipectivYHowever,D, Python 2#esidersf "in s"BFYp. ThisPfixedR3""" FFFD = '\ufffd' FFFDx2 = E * 2sequences = [7('F0 00',5+'\x00'), '7F%7f80Nx2),O87JC2F&E9>90 Bw?90 z /BF/BFz?BF z/BFz O90 8 8/80a ?90  C /BF  *8   BF* C  11[1 12w:B e= 8_=zBz z88n}*H C8nH &*  %   H 3n 3z3z3nJz: n\x7f'),  ('F3 80 C0', FFFDx2), 'FF 3"DBF 08t+'\x00'=DBF 7=_7f'),Bz?BF z 80}*?80 * /BF   *  BF/BFC 4444 9 44 B2 4 4'w/80z?4 8'z /80]a XC*  b/808H  ] for seq, res in uuences:#_"self.assertCorrectUTF8Decoding(bytes.fromhex(seq)Q `H'invalid continuation Z1') def test_codecs_idna()# Test whether trailing dot is preservedQ@ Equal("www.python.org.".enq ("p]"), b#nerrorsE handling (encosding)  self.assertRaises(UnicodeError, 'Andr\202 x'.en, 'ascii'F3,'strictOoEqual((,'ignore'), b"? x"KgreplacL?M'& 'Nov e&s=I$ $Ding=mu%) R!# 4 handling (decoohstr, bn E/, nOstr(,J mJ fuFFFD x  Q,l6 '\Iunknown character namescb"\\N{foo}xx".Be("u0-escape", "`"), "xtruncated ? sequence,, 4Typwb"helloIStest.1RG{L8, "E2E?o FF wrong argument rB42, &lone surrogate in3_Py_TransformDecimalAndSpaceToASCII()3 DValuint, "\ud800 5f5Ofloal 7ncomplexself.assertR2aises(ValueError, complex, "\udf00") def test_codecs(self): # Encoding.".assertEqual('hello'.e*e('ascii'), b)<_utf-7<(8<dS16-le|P\000elo 'C16-bT?h XTslatin-1# Default ping is 8e\u2603\xe2\x98\x83'b$Roundtrip safety for BMP (just the first 1024 chars4,c in range(#)u = chr(c59@n ('A7', 8 &16 ,F =, 'raw_uniF_escape'@ /$ 'Ainternal'with warnings.catch_(04## Z-Z has been deprecated[0.siAfilter("ignore", D?BionW| 7Tstr(u5&), ' uK/# =?256< ;256*;E,AW?128 ;128WFnon-\a few .\p'\U0001 Q20002 Q30003 Q40004 i50005's  'raw_unicode_escape', % '/ internal'):D self.assertEqual(str(u.en{(Ving), E u) G# UTF-8 must be roundtrip safe for all Mw points; (except surrogates, which ar<bidden).4u = ''.join(map(chr, list(range(0, 0xd800)) +6 )6Axe00;@1100=%))= in ('utf-8',MI(def test_'pcs_charSfu# 0-127s = bytes?128 8'cp037', 'cp1026 ;273gD'cp4(2500'$72 2775>850B4852'86K48612B$63B6L11251iso8859_1]D4RD' B A'6r&9&`koi8_r t u Az1047|latin_1?mac_cyrillic1+Q  12#25{$121125Qcp125 %!258Ccp85)8(#86[0869vcp874',^Pgreek# iceland','Troman~turkish}1100~| ### These have undefined mappings;#2Fsfail th-BJ875' 4s, )) su128-2555_, 256:N~H 'iso8859_9', 'koi8_r u latin_1', 'mac_cyrillic'+I2', +### These have undefined mappings:/p'cp1250U 1 2 3 4 5#I6!7 8+#42K#853#852$866']cp874CJ K Odt^kz104JPgreek$ iceland',uTromanturkishsfail the round-tripo!005[ )=self.assertEqual(str(s, encoding). !e(B, s)def test_concatenation(Sf b("abc" "def"),  2nW "ghi;</printing*class BitBucket>Qwrite6g, textfBpassVout =R!()@('abfile=out'def', &U\m !oend=' *1def*u!IAucs4x = '\U0010'2{Ty = xW "raw-unicode-escape").de(H 'Cx, yh/bryf   ~L:tryH1' Eexcept UDError as e` e.start, 0_)gend, 1(?els_fail("Should have raised UnicodeDeError") def test_conversion(self):## Make sure __str__() works properly-class ObjectToStrHLoD greturn "foo"XaStrSub ]G(str)b<ojnew__(cls, content=""gstr.__5#2*7)D/G(.assertEqual(B()),\p4 k_"bar">| = str(1:)o &Is(type(s), f9( =&_ Zu}\_repr\? s1&0,__2PV'\\n'P2P5 1(s1G|y9elf{,2,tprintable|'\U00010000''%c'" % (0xe,)) # Zq0N 4N\_ ")9f # nonQRa# This:& only affects 32-bit platforms because expandtabs can5CtakeOan int as the max value, not a 64WC long. IfQis changedN0to \975, tshould apply to all.FP@unit.skipIf(sys.maxsize > (1 << 32) oruct.calc('P') != 4,KG'4`pplies 7'W*>_overflows_gracefully%R3s(O6, 't\tt\t'.Y', @support.cpython_ptimizatEs = 'abc'> GIs(sS(), sh1Mem #if.calcsize('P') == 8: # 64 bits pointersascii_struct_size = 48#Pcompa %%72%Lelseu/32u%24Pu536 &for char in ('a', '\xe9Qu20ac U0010ffff')0cod@ord(F)X~1if z< 0x100:!3/P1 # ;of(Py_UCS1N1 b v ~+el 22 ` 4u4u-# Note: sys.maxT! is half of the actual max allocation because of#3signednessE@Py_sY_t. Stringmaxlen-1 shouldUprincipleT$be{ able, given enough memory.3\X = (('- A) //V I = lambda:' *9lenjself.assertRaises(MbError, \2e def test_format_subclass(D^g S(str?B_m,__5return '' overridden'$s = S('xxx'Equal("%s" % s,M9 B{}".?(s)? L_add Badd_;, o21"3"t S("4") + S("5"), "3" i!'"1gs += "4s=getnewargKtext = 'abc)0 = 6.__=6__("`IsNot(6A[0],8(7(1lenTR), 1) reb `length^range(1, 100, 7# generate a fresh-ing (refcount=f te xt = 'a' * length + 'b'  with support.check_warnings(('unicode_internal c has been 'LW 'deprecated', D BionWo=)):M# fill wstr ]field+abc = text.en-')6self.assertEqual(abc.de@,a)B# resize !:  must be cleared and then recomputen += 'c`oabcdef+&No", R?defPtest_@are(l# Issue #17615eN = 10UasciiN2zPlatinO\x804J\xff1bmp5Ku01072bmp5"A#E0stroE = (U!, )2,!,  Pbmp, 2N21for1 2 in itertools.combinations(7, 2e<A1 isRe% l-=12, F4!44not8 !"ifTRTrue(0 w1#p: dupli B to skip  "str1 ==/2"OqoptimizYQ_eq()Xsreally Jcharacter per  *vcopy1 =_-$00 #`IsNot(A01, 2_0(3 ` RFalse`? !=b<152 >0S )# <K('1bmp% self.as sertTrue(ascii < astral) pself.as(DFals)1>= 22*_latin)?bmp'r?ciiS' ( %A B(AjA >=  * 'A?bmp? Q&%?bmp$:J8 L5?>=  &1"4)7{)' e!QSE ) `12) K def test_free_after_iter1 g(:!):)support.check2 , BW, str<reversed@ class CAPITest(unit.bCase): #  PyUnicode_FromFormat(Bom_f im_module('ctypes'H Rfrom  ,% ()!pythonapi, py_object, sizeof,*c_int, c_long s2,_t2u3u(  4 c_void_name = "&"_ = getattr(Q9@.res?& = (o(w, *args5c = tuplexq(arg) if isinstance\ else arg<0for0 insreturn e68ormat(expected, format, *args): text = PyUnicode_FromF1(8 7 self.assertEqual(expected, R%) .u# asciiBnon-argument+bcheck_v!('%b\x7f=ue\xe9',.7 b/h%U', '5 j,: ensure that5V()# raises an error#R#Regex(ValueE* ?r'^bV\(\) ^eASCII-endV% 'v'string, got a 6 byte: 0xe9$I{8, bF0=%sX'Rtest "%c" k\uabcdrb'%c', c_int(0x+)` JU0010ffffN-P]with (Overflow #(g110000h# Issue #18183 U0A000\D )r9m## %m'5 %6sl/%s8?[%]9O[%%]:O%abc;!%% b'& runcated GO 8 Pb'%.3-^?defabc[\ufff .5L[\u20ac]'.w('utf8'w 2"'\1_ABC'"A*NH*.5J?DEF&"'pRRAJ*.3L>9.3SO.O,.3V', '\u20acABCDEF', None)  check_format('abc[\ufffd',#*cb'%.5VG#, 220ac]'.encode('utf8')) C# following tests comes from #7330+! width modifier and precisionuwith %S= "repr= abc"$B%5S''L/abI /.2J M 5N#C"R="' /8R%'&3K  (5.N& A=&)A&7K&N& s=&nPs', b;o/KpO% U=%&UHm2J#N" V="&FN?123N/R2V?123T at("repr=12"?,  b'repr=%.2V', None, b'123')1check_format("0o 12"T 5UV# test integer _s (%i, %d, %u_'010'{%03i', c_int(10)EF /.4G-+D)lGPlong(+H&IM.ztssize_t 5'd)&G.&llIM.zL'M u&u/23&E lF1G'HL,zIH'cu output@min_ = -(2 ** (8 * LEof(c W) - 135max< L5- 1e Hstr(*) E 8``8`u"? = $)&6ax_- ,(PyUnicode_FromFcAb'%pvoid_p(-padding (width and/or precision P.rjus_, '0'd2010sV0R/10R" .X check_f ormat('123'.rjust(80, '0')100),  b'%100.80i', c_int(123)) /~check_fe1eZA010uWuXW S"?.10 h i4xih"0xj/T#kZ l fm# test %A r"%A:'abc\xe9\uabcd\U0010ffff'"H%A:%A', <ZV'repr=abc'o"#%Vp', b'xyz'dTstring decode from parameter of %s us"eutf-8.# b'\xe4\xbae6\xb0\x91' is 00 enXd byte sequence ofH'\u4eba\u6c11' v )@Nonereplace error handler _ufffd5:xff not supported: copy the raw e .!se`s are U here>Q# to < crashes and should obe considered as specificationsNI/%s %1 b/')A1 %=/+i/0)D.1b'%'!# PPyUni_AsWideChar(f@.cpython_only<1def_aswidec4aself):vx_ypcapi im# ul81m* _module('ctypes')  from ctypes import c_wchar, sizeof  = unicode_aswide2('abcdef', 2)6self.assertEqual(W" i_'ab')O', 3|" |c}!4}5/\0!/10h#\07R nonbmp = chr(0x10ffffN#if(u) == 2:buflen = 3nE = 2else: #S4% R<R1-D", Gb&pVF + 'N# Test PyUAsWideCharString(X@@sup.cpython_onlydef tests:)uf_+DcapiiB>\?y_module(''(_\bItNk7#; `&NOUCS4Pucs4( 4for s in [Z', '\xa1\xa2 u4f60\u597da\U0001f600',Dr'a\ud800b\udfffc', '\ud834\udd1e']: l = len(s)!self.assertEqual(unicode_asucs4(s, l, 1), s+'\0'>!0>_uffffB '+1\F)0F Raises(SystemError,  , -RFK2, 0Z0 = p.join([s, s]"=} C:~# Test PyU5FindChar(@support.cpython_only:def test_findc2)`from _#pcapi imH6 M for str in "\xa1", "\u8000"80 d8Adc02U0001f100\ 6f1"WPi, chYenumerate(str)L8, ord(ch), 0,2tr)i7LT*-&i)&"= "!>_=+lbf0iN# negative^'-b  O^0 t@Copytoactersz@copyz8 < `ings = [M'abcde', '\xa2\xa3\xa4\xa5',- \u4f60\u597d\u4e16\u754c*01. '\U0001f600\U0001f601 2 3 C4' %] for idx, from_ in enumerate(strings):.@# wide -> narrow: exceed maxchar limitation8j tobXj[:idx]]aself.assertRaises(H#SystemError,!unicode_copyacters, to, 0 5?)# same kind7Pstart{range(52_Equal(e vO, 5)6[+: +5].ljust(5, '\0'D6 5-5  1to_ Oj ): r3  #'/ 8# Tests omitted since this creates invalid +.4s =5[0]X`5RIndex Xa, s, 60HM//-1N90M63M56V7 N_0, -11a0, b''1"0);@support.cpython_onlydef test_en/decimal( _)pcapi imN"<;WC /_('123Hb"Xq\u0663.14h _3.14' "\N{EM SPACE}CN"\ 0 tUE  unicode_endecimal, "123\u20ac", "strict") <self.assertRaisesRegex( (ValueError,3"^'g ' tc can't character"7replace") s@support.cpython_onlydef test_transform_(!):&`from _,pcapi imQ ?>toascii as ZSb>mEqual(+z('123')!Sq\u0663.14c _3.14'"\N{EM SPACE}?N" :  '/pep393_utf8_caching_bug5# Issue #25709: Problem with N ng concatenation and utf-8 Wegetargs_s_hash-or k in 0x24, 0xaV1f40dLes = ''APfor iEwrange(5 # Due to CPX specific optimizuthe 's'Fan bI# resized in-.$s += chr(k# Parsing^uP"s#" !atc calls indirect=S# PyU AsUTF8AndSize() which creates `]UTF-8#d!ch5_ objectT_ C(s),.+() * (i + 1)Check thatasecond r return@same=ult  class StringModuleTest(unitR.CCasedter_parser`)(*@rr list(_o.)S)+;bter = ^$"prefix {2!s}xxx{0:^+10.3f}{obj.attr!s} {z[0]!s:10}&a9, [l#('iP', '2sP('xxx0{', None] ('#r', '', 's')7, (' ', 'z[0] 106s')&5]) 2formatter = parse("prefix {} suffix").self.assertEqual(?5, [&#('G~GNone'e0', + ?str$?strz*w ?{0}J f[5 Raises(TypeError, _string._ Cr, 1*def test_#field_name_split(c%):3$items = list( \CC4[1]FS:[1]&qreturn  "obj"), [ G, []M4I.arg8(True, 'arg')EZ[key]F@FalsG?keyGK 1]2R8 [(/' (1F 2 R if _t_ == "__main__"x@unit. () # -*- coding: latin18 # IMPORTANT: this file has the utf-8 BOM signature '\xef\xbb\xbf' # at,start of it. Make s0V&is preserved if any changes # are made! Also note thY cookie above conflicts with #b0ncea"--is intended. # Arbitrary encoded>text (stolen from0doca 2.py). x = 'ЉЊЈЁЂ' #y(1"""gAnd again in a commen*:(00pasATestrunpy module import &os T.path%syr>@temp%UUlib, .machineryDutil6py_compiwarnings 1A.supX! (forget, make_legacy_pyc, unload, verbono_tracingcreate_empty_file, temp_dir) from test.support.script_helper im ( make_pkg, * 7zipC) ERrunpyr ]_run_code, cmodule , path # Note: This  can't safely Mas_main as it #K s* s in the current process, which would mess with+CQeal _W$__c(usualP.regr]q) # Seem_cmd_line_!a for a that executes  E@t up1*and expected results example_source = """\ # Check basic >oBion ; = ['Top level assignment'] def f():/.append('Lower5reference') f() del f}j$sy@sys argv0 = sys. 1[0]name_in_sys_as = ___2 0(c3 K1and globals() is_$s[].__dict__d0nesoperation =') """UQlicit1spa{"": None,lfile__ncachedopackag1>doc.6spe4 } m Psys":I"": _": ["O", "s$"]A0un_A0kM #t": Fals3$ 0": K(impq TEx=1,!=""loader__=/),I.updatek) class CodeEHionMixin# Issue #15230 ] not handlingV correctly) highlighaP#'Eblem way argu/s were beRqpassed nJ*CAPIsNdown to lI.yp easier0ensure fullJsvoccurs at those up@laye1ll,Bjust(e utilityL. QFigurZuT"e q detailGpadvance)@harddo, so we skipKcKE$ofWba_state;CHECKED_SPEC_ATTRIBUTES" pa `origin cached",  "has_location", "submodule_searchPs"] H*def assertNamespaceMatches(self, result_ns, expected_ns):>B"""Check two nE0s mG.f( Ignores any unspecified interpreter createdJe # Avoid side effects& =u.copy()%( = )# Impls are permitto add extra, so filthem outnfor k in list(Cif k.startswith("__") and k.end{8<@ note)-f.pop(kN["nested"]X ) b# Spec equality includes the loaderJqwe take&O0 ofV#-chat separately5T  0"__w0M +4&ifR7zis None6].y Is3;els9u# If and8 is set, we just `we got9V righ# type, rather than7@ing Efull; . 5E(F)),l; ; ==5@attrCHECKED_SPEC_ATTRIBUTESEk = P." + H actual = (k, get%,7) ;=?Kp@# Foe1!still don't use direct dict comparison on9#k2, aBdifftoo hard to debug i0ythNVbreak (se,( 'ns?N*ns U$6[k]~l + cl$Kv_code_execuI_"@What an interface runs the example codrrectly First argument is a callable acceptingNinitial globals andJ#us)m to create8actual namespace5iSecondpected result25""" sentinel = object()"ex@f_ns = W.copy0@run_ -As["_E__"][saved_argv0 = sys. ,[0"3mod modules.get(i$, # Check without pgs\V(NoneSself.assertNMatches(r[G_ns,!s<7Is(', 0  H6modFP# And7n${"N%":Y}1&s[*]D+# =\tbXIsNotW0  class ExecutionLayerTestCase(unittest.e, Code.qMixin):Z"""Unit 0Ps for@py._8and:_E1defA5(|b /.update({iL"__loader__": Y, } s(_"Pvreturn _source, {},@o .c$_e(z ;tsT :1mod( = "k f "Some other n+ *5LNow you're just be#Zsilly3package = '' # T= atop level N spec = importlib.machinery.MuPSpec(*@porigin=CD!D <+ "__name__": mod_name, f"__fil"f#eloaderG IfpackagL (EspecL "run_argv0$_in_sys_modules": Tru+ %}) def create_ns(init_globals):%Freturn _fcode(example_sourc8g ..nself.check__execution( , expected_ns) # TODO: Use ?addCleanup to get rid of a lot try-finally blocks class RunMTestCase(unittest.t, CodeESMixin"""Unit 0s for runpy.A""" _import_error(,X;;try#unc(GzGexcept I[EZ =Apass[Jelse.fail("El  6" +r_invalis# Builtin?5ulewV"sys"# Non-existentFG .imp.ericP1os.path.half1Wa.bee*# Relative s not allowedw.howardQ ..n,0.2# P^ without __main__.pymultiprocessing")DtlibraryE.assertEqual(e#("1["_`d__"], g_add_pkg_diz,pace=FalsezPos.mk2,&if7 Q6Non?H4 = hPjoin(dir, "__Qy Qempty+2KrL@make#, b depth|Rbase=0_*"*(, parentxs@sA: # +Enforce a couple of internal sanity checks on test cases  if (namespace or parent_s) and not depth:;B'raise RuntimeError("Can't mark top level module as a "CG "~ package")41pkg = "__runpy__W _fE =z_base+os.extsep+"py-<dir = sub_ os.path.real (tempfile.mkd &() if verbose > 1: print(" P tree in:",c=#sykinsert(0, $aUpdated EbQ9[0]B!_flags = [2] * :u[-1] =  ,6forj; insVcSjoin(&q6@self._add#6dirA=GvCNextC0Cre5mod  6ile = open(FG, "w@write(sourceGv.close(\Y7@ = ( a+".")*% +63spec = importlib.util.`_from__locatioY,Dv7dreturn,# r |def _delp(~,)PentryPlist(ms(1if +.startswith( 261delT[C]SRemovN<7ies?^/[0W5TyRroot, dirs, sos.walk(topFdown=FalseB5>o>tryAos.r(kU0except OS/ex^mex) # Persist  cleaning upk:  fullname = os.path.join(root, ;) Mtry:$os.rmdir(V<except OSError as exM%if verbose > 1: print(ex) # Persist with cleaning up :toph " Removed package tree"<Z  def _fix_ns_for_legacy_pyc(self, ns, alter_sys)Achar_to_add = "c"Ons["__file__"] += , &acached(*= 9*Tspec  /@new_ = importlib.util.R_fromlocation(.p,E cl&ifPO~<run_argv0: Ccheck_moduleWdeptho=False*uSspace- parent_spkg_dir, mod_f)  A = (O ._make_pkg(example_source, 5<f= 6 )pforget(bexpected_ns = $o.copy(/.update({!"_fA__":KJ D"m EA%}. N^ sq.rparti}".")[0]8T5 "}; "(-0_ins": Tru"&/fcreate_ns(init_globalpreturn i<(, 7O FA"Run ;&:"r+code_execu',  >N`invali_[sh"__,%__) os.remove(mod_fname) if not sys.dont_write_bytecode:,7make_legacy_pycW+aunload"x # In case er caches pathskimportlib.invalidate_2(n!if verbose > 1: print("Running from compiled:",  xself._fix_ns_forexpected_ns, alter_sysD`check_H_execution(cre@MBzfinallyzO_del_pkg(pkg_dir4rModule |ed successfully") Rdef _package(mw, depthq=False,5p0*, QSspace. parent_s) 3 spec = ({!._example_source"__main__" r 3  )[% =~q.rpartiu".")[0]fforget@84 = ZW.copy"/0.upF%({L!"_E__": u"__file" Ed%Qutil._F)jH3 %" "}r&ifs%"run_argv0j$(0_in!_mzs": Tru5"!/?(init_globalsPpreturn i3(, 7+trh dbq>X "__,!__l /os from compiled:", pkg_name)  importlib.invalidate_caches(.#self._fix_ns_for_legacy_pyc(expected_ns, alter_sysD check_code_execution(cre~@MBfinally:del_pkg(6dir4if verbose > 1: print("Package }ed successfully") c def _add_relative_modules(u , base_dir, source, depth)"ifV <= 1raise ValueError("Rf f test needsEF> 1" = "__runpy1__"dI% =for i in range(AcparentANC$ = os.path.join(# Add siblingY#_fX"* .pJempty_file('QE  JHlnephewAuncl( ^1, "&c.~Adir("2" p C`cousin -2, "& #I3 EV 02, ")  &O5JF/1_1cQ, runW=None.contents = r"""\ from __future__ N absolute_'...(#6 ""+e,  spec = (e@make(  c@ is Qame =rOelse3 a3/tr0 N&q.rpartiy'.')[0]3f@RunnC[1mod:w d1#un]&O) # Read from source self.assertEqual(d1["__name__"], expected)<cpackag??pkg: In("sibling", d1c)onephew((del d1 # Ensure __loader__ entry doesn't keep file open importlib.invalidate_caches("__,___(moos.remove fN Bif not sys.dont_write_bytecode:make_legacy_pycW+ un"x # In case the 2er m pathso!if verbose > 1: print("Running from compiled:", )U.d2 = run_modul>, = ) # Read: 2@ >2-,2'zfinallyi_del_pkg(6dirM executed successfully") def test_n)for depth in range(4!@TestFOCut._checkd&1_incspace_d(H?1, X , =True, parentsy!_init_exceptions# These were previously wrappeddAan IError; see Issue 142853result = !._ "", 1, "__main__"j;6, _0, _M\8% =C.replace(".Z7, "^addCleanup.#, } init = os.path.join(pkg_dir, "__runpy_!_"init__.py") exceptions = (ImportError, Attribute4Typ BValu )JEfor N6 in %s:%vfname =0.__)__&with self.subTest(%)KOPsourcQ"raise {0}('{0}%__.')".formaJ nIrPopen(5, "wt", encoding="ascii") as mod_fileIr.write()#?try@run_module(K kF?errRHassertNotIn("fin spec", Nerr)?elsXfail("Nothing d; expected {}x` @ + " "Mdef test_sub!_ied_warning(w !_,1R, _ =@P_make f("", 13 x_k/__y#~.MWarnsRegex(RuntimeAing,pr"foundRsys\.'s"/ kfinall>A_delUspackage_ed_noV3bgmain__addCleanup.%, % =.replace(".__`7, "dS# No  should occur if we only C the parent m+A3In(T, sys,%ts.catchd+s('simplefilter("e:", Uc0" Q# Buta ] w run_package_in_ namespace_package(self): for depth in range(1, 4")if verbose > 1: print("Testing \I2:", )eCxu._checky, parent_s=True) @def test_run#CWq/_imodule_alter_sysL(L^ explicit_relative_importG2, 5i d dBs at"<s OmainRi 7P, "__\<__" A = 1* = "And now `somethcompletely diffeo"@pkg_dir, mod_f  spec = (3w0 }._make_pkg(exaht_sourcepforget(g\expected_ns = G$o.copy(/.update({!"_*T__": ,"Afile" #acached%lib.util.S_fromF)j9m.rpartition(".")[0]8w}5 "}! create_ns(init_globals):  return run_module(mod_name, init_globals,#$) ?Etry: !self.check_code_execution(create_ns, expected_nsKofinallO_del_pkg(pkg_dir) sdef testutil_walk_packages()# This is a dodgy hack to use theLrunpy infrastructure%iv# issue #15343. I8 declares tpjindeedw;import pkgdmax_depth = 4Abasea = "__5__"$_suffixes = ["uncle", .cousin"]54+.nephew", + ".siblingJeFset("u!Bfor in range(1, .".join([2] *L5A.addaK ,C in /)aVZ  5@" + Qgf*se)c (I"7Pdir, tf  spec = (e0 `._make8("""a'addCleanup.R,wSV  |2Z++1~`_add_relativeFsNTg*AinfoZ.[!]wassertIsInstanc0uleRQ!.MFInfo~B. _f,r,C lib.machinery.FileFB ~ ifo.ispkgKXremov.) [OelseL/s.K  Equal(len(Ws), 0/G  F class RunPathTestCase(unitH.t, CodeElSMixin1"""Unit tests for runp y.run_path""" def _make_test_script(self, E_dir basename,=Asource=None, omit_suffix=False):;2if ,@ is /V= example_?qreturn ( ) _check  expected_?fil*  :argv0, moE> u_spec=True, aloaderlr# First$pwithout lcreate_ns(init_globalsOAS}M), 8\)&s 2space.copy()/%if#1pecuNCKelseW4o/#ifX 9-n = importlib.util.`_from__location(/ K 8` 7cached =.u.)Sif no_% %NA!! =HN1}x78!s.update({x!"_C__":% i""_b ' a2"__P &qpackage'-"" C ")_in_sys_modules":  + }.code_execu,Vs:# SecondKes sure works in all cases = "prove.issue15230.is.fixed"/Y?, A andg 1expected_ns["__spec__"] = mod# expected_ns["__name+1run+lpackag..rpartition(".")[0]Aself.check_code_execu*create_ns, !) ;Rdef _7import_error(O, scriptq, msg):5msg = re.escape(>.assertRaisesRegex(IbEaO , Ipathktest_basic_with temp_dir() as6dir!odB = 'M' #a_make_(m,)GS.5,D, "<)>",G Npo=False6 _no_suffix@ s omit_=Truecompiled| 9dc = py_. 0doros.remove1 mb|*(e + - ./directory4__main__d\", U,M P_I1mod= !) Cdef test&ectory_error()with temp)f() as _'b = 'not_main'm:x0 = j!._6 S msg = "can't find '_n__' module in %r" % dimport=,sg/zipfile'4 '-1zip3, fKlk'Tzip',46 z O) t%,   ", hloader=False_compiledT = py.Wdoraise=Tru\ I&  .5, m@no_tracingEZ_recursion_?elf_,yPdummyxQ source = ("import runpy\n" " .run_path(%r)\n") % dummy_dir:script_name = self._make_test_(<Q, mod., source)O3zipfSME L'ebzip', = Smsg = "recursion depth exceeded assertRaisesRegex(R=Error, msg,J$ , !) Adef encoding(W!):vwith tempT() as6dir'+@file[` = os.Z.joinJ.py'hTopen(Gt, 'w', ='latin1'f{.write(""" #:3 sVnon-ASCII: h\xe9" """result =0 ($.{bEqual(9['s'], "j) if ___ == "__main__"@unit.() '''Tests for WindowsConsoleIO# &$io $os %sy SiQ from I0supwsys.platform != 'win32'ro IP.Skip (" only relevant on ;2") rncz_input ConIO = io._m class%s(CCase1 = n@'//?r1outn/wbv<LpathPtemp_0 = @.mkd (ddCleanup(support.rmtree, temp_path)3 conout_path = os. .join(temp, 'CONOUT$'):with open(D , 'wb', buffering=0) as f:ryif sys.getwindowsversion()[:2] > (6, 1)59self.assertIsInstance(f, ConIO)eOelseB /NoEF def test_write_empty_data((''<Equal(f.`(b''), 0`}StdinRoundTrip|g, texts$IN$', 'r'Dold_({ W:try*#: = +/u_input(D/.].raw,"( + '\r\n').encode('utf-16-lesurrogatepasscactual = ofinall ]sp3# ASCIIR w'abc123o# Non-@ϼўТλФЙFCombining charactersA͏B ﬖ̳AA̝S?BMPF`\U0010 Effff dCFpartial_reads NTest that !@lessn 1 full works when# contains multibyte UTF-8 sequence"ource = 'bpexpected:8\1for_count in range(1, 16 ltbq A71, sy$e = b''while not 'P.ends0(b'{:bO.(E'[R += b{x K.$, 1, 'l{})'.formatx VrQ pairPt candPbe de%Cd tom5out#F!an extra. source = '\U00101FFF 001\r\n'.encode('utf-16-le') expectedB8>for read_count in range(1, 16):fm with open('CONIN$', 'rb', buffering=0) as stdin=Arite_input(#, source) i,actual = b''while not 'P.endsk(b'\n'O2b =.(M'[^ += bself.assertEqual(.$, 1, 'l{})'.formatxdef test_ctrl_z(]x&axC4\x1AS: C.w;a, 71),Jall(  h[0:1], a/1:], b) if __name__ == "__main__"@unit.0() __getattr__(:0if  != 'del$'Hraise AttributeErrordel globals()['`!']!:rimport lib.util 4 os py_compile(sh*Estaty7Wtempf5 a from{@ sup class PyCqdTests(:.bCase):AL\setUpdirectory = @.mkd ,_path = os. Q.join[.LA, '_'pyD4pycATF+ 'cwTcache1u.(_F 4Mwd_driveQsplit(os.getcwd())[0Q# In thesePs we ute relatR s. When using Windows,<`Mcurrent work'6 D@ and1! '' might beMPon diRThereforeneed to  ch Athe , w)OSorary' u lives.+?G L"ifzos.chdir(W UQ, 'w' N.('x = 123ef tearDown(self): shutil.rmtree(.directory)&1if cwd_driveAHos.chdir@%!) Adef test_absolute_path,py_compile."b.sourc3,1pycBassertTrue(os.cr.existsH67OFals8Bcach) do_not_overwrite_symlinkr# In the face of a cfile argument being a B, bail out.Ce# Issue #17222=tryF + '.actual'Jexcept (NotImpleedError, OS } skipTest('need to be able fcreatep for a ';elsW  is] ?Bwith$;Raises(FileE 9}!P@unit.eIf(notos.devnull) or is,S 'requires;,A andG itbm non-regular\ 3non0_( {"x NYsjwk ?  P ~hasattr(os, 'geteuid') and os.geteuid() == 0,  'non-root user required')/ @unittest.skipIf(os.nameRO'nt'U cannot control directory permissions on Windowsn@def mp_except%_propagate(self):# Make sure that 5p raised nks to issues with writingIbytecode.http://bugs.python.org/IU17244,mode = os.stat.Gos.chmod! , 6.S_IREAD/6try@.assertRs(IOError-py_compile.{source_path, Q1pyc~kfinall@.st_!) bad_coding~>P.joine 0dirm(__file__), '6C2.py9 upport.captured_stderr(w,GIsNone(-jA, doSv=False)(Iqexists( r imlib.util.cache_from_(r,))H#_date_epochO9 ti 123456789 EnvironmentVarGuar$jas envtenv["SOURCE_DATE_EPOCH"] = str(sK'x)LTrueOw7 pAopenO.\, 'rb') as fpflags = _bootstrap_external._classify_pyc$fp.read(F_', {}aEqual(uc, 0b11 Asys.'.optimize > 0, '`` does Bwork#-O>double_dot_no_clobber@/#  U22966w&#  foo.bar.py -> _ _/ce0-34BQweird %h0, 'F`i n6 = e + 'c'head, tailfsplit(Spenultim 5AbaseS2{0os.=penultimate_tail, tail), os.path.join(%'__pycache__'9foo.bar.{}.pyc'.format(sys.implementation.Eetag)))gwith open(weird_, 'w') as file:,p.write('x = 123\n'Ppy_compile.Y'self.assertTrue(rexists(4MFals51pyc1)) def test_optimiz"(K)# Specifying .ed bytecode should lead to a reflect4Qthat.u$^In('opt-2', *asource,~-=2rinvalidLmodean  _=PGPycIMode.CHECKED_HASH[S, 'rbap flags = importlib._bootstrap_external._classify3fp.read(), 'V', {}|aEqual(uf, 0b11& /FM7/UNO) if __name__ == "__main__"@unit.2()  !  PowTest(.fCase):0powKP, typV!if != floatfor i in range(-1000, ')A@pow(o(i), 0), H15 "1)'(i7;l;0;r1mo3), i*i*i]@pow2? T v_0, 31r02, ~Xj@if iP30 : #! ="*2>$Pother_(int,)0Ulist(5G) + 1, 10)):  ii = type(i) for j in range(1, 11):+/jj = -otherVjV+pow(ii, jj) Po>wint, floatu)i!/00Dzero0:exp_i/10.)1if ,:= 0continueself.assertRaises(ZeroDivisionError, pow, ,g`il, ihe20, 20_Qjl, je5, 5Qkl, kV10, 12Gq = UEqual:!if ? ==reil = 1-RjAlmostX'elZ+injX-  5+&B &*k^S*.oif k !#[ W= 0 and k != 0R*self.assertEqual(|&pow(i,j) % k,*?,k)'N_nt(i)/ def test_bug643260(^class TestRpow>__rpow__8w, other?return Noney 5 **]() # Won't fail when ` invoked. SF bug #!. Qa7052310# -1.0 raised to an integer should never blow up. It did if th# platform ]P) was1gy,`Python:w(around it.Peq = m1a =# The next twos can still1ffloor(# functi0oes treat all large inputs ass`Dmath0Galso{at is happening:0eq()a, 1.23e167) 0"-#PbP/10QHfloat(b)), b & 1Wor 1.|Y 71008fiveto = W5n## For smL3n, 2wPbe od Eventually we run out of*Imantissa bits, though\_\eaferaFeven]HexpectedB% 2.c  |@34), G )-*4eq(? # else0didDpush0to ness if __name__ == "__main__"@unit.@() -BEGIN CERTIFICATE - MIIClTCCAf6gAwIBAgIJAKGU95wKR8pTMA0GCSqGSIb3DQEBBQUAMHAxCzAJBgNV BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u IFNvZnR3YXJlIEZvdW5kYXRpb24xIzAhBgNVBAMMGnNlbGYtc2lnbmVkLnB5dGhv bnRlc3QubmV0MB4XDTE0MTEwMjE4MDkyOVoXDTI0MTAzMDE4MDkyOVowcDELMAkG A1UEBhMCWFkxFzAVBr cMDkNhc3RsZSBBbnRocmF4MSMwIQKDBpQeXRo b24gUi29mdHdhcmUgRm91bmRhdGlvbjEjMCEGA1UEAwwac2VsZi1zaWduZWQucHl0 aG9udGVzdC5uZXQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANDXQXW9tjyZ Xt0Iv2tLL1+jinr4wGg36ioLDLFkMf+2Y1GL0v0BnKYG4N1OKlAU15LXGeGer8vm Sv/yIvmdrELvhAbbo3w4a9TMYQA4XkIVLdvu3mvNOAet+8PMJxn26dbDhG809ALv EHY57lQsBS3G59RZyBPVqAqmImWNJnVzAgMBAAGjNzA1MCUGA1UdEQQeMByCGnNl bGYtc2lnbmVkLnB5dGhvbnRlc3QubmV0MAwGA1UdEwQFMAMBAf8wDQY$a AQEFB%EAIuzAhgMouJpNdf3URCHIineyoSt6WK/9+eyUcjlKOrDoXNZaD72h TXMeKYoWvJyVcSLKL8ckPtDobgP2OTt0UkyAaj0n+ZHaqq1lH2yVfGUA1ILJv515 C8BqbvVZuqm3i7ygmw3bqE/lYMgOrYtXXnqOrz6nvsE6Yc9V9rFflOM= -----END CERTIFICATE- import re Ttypes unittestweakref from  A0supI class ClearTest(D.Case): """s for frame.c:1().% def inner(self, x=5, **kwargsRVE1/0 15out1,2try9[.f/Mexcept ZeroDivisionError as eHuexc = e;return exc_traceback_s'tbWB all-us in a F5)5while tb is not NonRtb.tbNRtb = %Fnext_Rlocal Epass`+5C()Swr = if.ref(cY'c=Udel cH.gc_collecte# A reference to cheld through theeSelf.assertIsNot(Jf, wr()[ws(exc.__7A7Thewas released by  Ngenerato]endly = Fals>'g('#1non 4f hYyield'}kfinalljf = Truwgen = gF(genV(J #6ingq closes0bgen.gi n=Lexecuting ): # Attempting to clear an execuframe is forbidden. Etry: 51/0except ZeroDivisionError as e7f = e.__traceback__.tb_{Pwith self.assertRaises(Runtime[)W./()D* f_KLdef test_a_._generator(/# j< tendly = Falsey'g(pnonlocal 4, /)6fT) W yyield fDkfinall-of = Truwgen = g0next(gen8(N 0# C#he+closes the F1dc2@support.cpython_onlydrefcycles doesn't leave any 6q behindY4{disable_gczclass C@EpassMWc = Cnwr = weakref.ref(cX ex6outer(c="Ydel ch.IsNot(None, wr()])0Zs(exc;d a" FLsTest(unit.CCase1"""41.f_)s attribute/0Bmake 2hNQx = 5B6=\inner/z = x + 23 Yt = 9*sreturn ` !.tbHY = []while tb2.append(tb ]~"MaJ itest_locals(selfC): f, outer, inner = self.make_frames()-*_locals =9#.f&AassertIsInstance(<a.pop('q'), types.FunctionTypesMYEqualH, {'x': 5, 'y': 6}9^" = _7_z': 7}) def test_cleare(Zt# Test q after 2() (issue #21897.R .7, {< -T-q before andto exercise caching#*$ Qf class Repr;P(unitg.CCase^1"""s for repr(!).# #E(Qx = 5@Yy = 6= =/z = x + 23=1/0Yt = 9breturn(v>Poffse/ .__code__.co_firstlinenoK6try@except ZeroDivisionError as e;tb = e.__traceback__i\)[]while tbO2.append(tb.tbu'~"Enexta;els .fail("should have raised"Lf_this, f_M 2 = ePfile_A = re.escape(1(__&_)kRRegex)n%),U Ar"^$ R 0% (@#, DO+ 23=U!7 r."^$" 0% (<!_repr, offset + 5)) if __name__ == "__main__":Qunittest.() import gc dpprint4sys : class TestGetPro( .RCase)rdef setUp(selfsys.setp@aNone) 3tearDown6st_empty8elf.assertIsl(g>}st_setgetHfn(*args:Bpass_1fn) , ,eHookWatcherO__init__a.pjs = []qSeventcallbackK!, =!, +W, argAif (X9 "or8oreturn!exception"c1dd_lra!=V"""Add anto the log."""if@ is BpZ0 = A_get#(1"?try3 no52s.index(  ValueErroW.J"leB' t.appendh#Zs#$%noERident)2gets. bpRemove Vs to )fdisallowedk1.__func__), )wy [item for 1in e1 if[2] not in ]PSimulator(C  , ^cu% =# Pstackq.gwr3# C registered with )/settrace(gF@disp[O],=;_ !$L ('+'H9& ik-m Mpop(e"io .testcase.faWil( '"the profiler should never receive exception events") C def trace_pass(self, frame):!g/ispatch = {s'call':H ,y!&ereturn# c_W 1 t#} class TestCaseBase(unittest.6bcheck_N8able, expected0E* = capture;5}`.new_wcUer())H#if5 !=^a?sfail("E4:\n%s\nR d"bC% (pprint.pformat(,, R5)))EPDHook:( YG FWest_simple9X7f(pO5f_ident = &(fk.f, [(1, #, =)`4'6]?1/0caught_Xtry: D/:  onested #K# This isn't what I r# (0, 'Pion',tect_ident),   # I expected this again: 1(1, 'return', f_ident),6 1]) "def test_exception_in _clause(self)37f(p11/0Q "g"6tryE'I8)> .2U passK1 = 5(f)g#g.check_events(g, [bscall', =`S(2, '44/(3j 4j j jppropagave9'finally: p.add("falling through"#> ?I&raise_twicns f= 6 !re H $ E(] ]) def test_distant_exception(self):&*'f(91/0!g!9f()!h!g!i!h!;j(pi"f_ident = &(fgghhiijj<.check_events(j, [(1, 'call', =%),P&(24434444*454y4return', 666 r6t6 generatorfor i in range(2Nuyield ifgCI DEpassAbg # Br the it, twice to ?ve value\ 6j"# once more; s end-of-0ion with# actually raising an > [X yF yUstop_!~lf.check_events(g, [(1, 'call', g_ident),  # 1 the iterator twice to gene valuesK &(2f4return', 64j# once mor1hit+oraise:w]) class ProfileSimulTestCase( RBase)def new_watcher(selfj R' 3Btest_simple]B7f(pT6pas)1 = 1(f)Y(.check_evef=OhVbasic_exception51/0ocaughtXtry: A2/: odistan  D+g(!&f(!h!g!i!h!jmi"jghhiijjj=43444*454y4 ( 5, 'return', f_ident),  ((46g636h626i616j6]) def (function):if hasattr, "f_code"$74 = >."CBelseM)_K!__+ M.co_firstlineno,Cnameprotect(f, ptry: f(p)Pexcept: pass /# =capture_events(callable, p=Nonegif p is p = HookWatcher(P# DisD the garbage collector. This prr __del__s from showing up in# traces.old_gc = gc.isenhdyBgc.dz6sys.setprofile(p.Bback# @ vfinally2if ^2gc.Tp.gets)[1:-1] mport pprint .()Pif __W__ == "__main__"unittest.() """Bigmem 3s -1for32-bit boundary in containers. These4try to exercivery low<p limitsmake sureFKthemselves don't suffer`bitrotoi7 m ,y a highml@regr,P-M op.! $" i\0supd.!b3, _1G, _2C4G CKoperator`sys # ests all use onerhQ decoBBindicate h`Tuch #tH5and @need0be  bIhe #ntwo argum+: a 'memuse' or4laring # (approximate) bytes per size-3 wi(at peak usage), a # 'min9m a minimum *useful* size. A test that # allocates a bytestring to N various operations near the end will have a # minsize of at least 2Gb (or it wouldn't reach D32-bit limit, soY" #|w/ be very useful) and a memusla1 (oneP per -unit, # if itQonly /3ig at a time.) # # When run withk2ory set, both decorators skipsYP need0ore>than availablebbaningful. The precisionbigmemeways passj!as`, eventhere is much m{1. #kbQscaleYp upwardfE.0B=houserules: - Try notHr too many large objects. It's okay.!re # refcountesemantics, doYRforge 's = create_b2()'M@does4 reez old 's' (6exists) sl well aftewIvalue has beensd. Use 'del s' befR callJ - Do *not* compare0 usassertEqual, @In oPmilar" Ka lengthy3errormessagebe utterlpBless!du"itrke sure whe{ a resultbright contentsP bec'p methods,$me,w slices33for;0ind/, offsets Csuchpin addi9 s. Anyth~<` probe#e boundaryHAepea#an (say, a sub!nga small list)~+a'R, mak2subw!isua power ofK2. That wint-wrappPlems x=easily detectedbDespitI,ssXactually be % cer number!A, inanormalQ(5Kb currently!@ThisI.mselves frequent3ing+BConsllleqbased oWped-in ''0 bepdc. AlsoQ-per-- sh  remain sane (n a few tvPand);ByourBuses more, adjuPst 'size' upward, instead. # BEWARE: it seems that one failing test can yield other subsequent as to #3 as well. I do not know whet: it is due to memory fragmentation # issues, or o(pecifics of the platform malloc() routine. ascii_char_ = 1 ucs224(4 class BaseStrTest: def _test_capitalize(self, d!):&*@_ = .from_latin1oSUBSTR"a(' abcgUghi')2s = _('-') *k2 + F#0cap&'s.Aelf.assertEqual(/b[-len(HE):],L $ [\ .lstrip(#),)Ip@bigmemK(:=_2G + 10, Ruse=1`r&_centermP6.Y2izes/)#s)(@lpadF = r (-0 - gu)) // 2:!iffs) % 27|U+ $s[)$:-}]g48.2#Oount_ .cm_('.')1s +G.Z /s.DT4 x3-i-Z j-0!endswithJ uTrue(s. ,'s)X2 ..#?+ sA2n BIFalse_('a')fx 6 c Oexpandtabs n$ tabsize = 8 self.assertTrue(s.expandtabs() == s)-Udel sslen, remainder = divmod(size, B6ize>ss = _('yp\t') * ER9 = DEqual(len(s), t& -w3p.strip('))), 0) @bigmemtest=_2G, memuse=2W@def !`_find(C!):C_zfrom_latin1cSUBSTR@abc QBghi'_@sublen = 0;').join([ ,^-V]8>!s.} ,U1(,X", +l,EP_('i'N>  ? + o+:,mOj/-1!x--Z> %~ nA($),W*q&#oRaises(ValueError, s.7A  isalnum,h123456aY}) s += _('.C') self.assertFalse(s.isalnum()) '@bigmemtest(size=_2G, memuse=2K@def !_=@pha(X , /!):Fp@_ = .from_latin1SUBSTR = _('zQa') *W2 + 2AZ4Tru)1s +b.\:`_digit,h1234569z\:!_lower Rcharsq'.join(~chr(c) for c in range(255) if not ".isupper()`repeat^ // len(rU) + 2j#3 * 5+gjgAd :`g_spaced Qwhite=i \f\n\r\t\v4ize.<38i8j:8!Otitl8!q4"')[_('A'),,]PP9a;R!le,IYra :d a) * size  x = s.join([_('a'), _('bP')]) ) self.assertEqual(x.count(:o')), 5-b-True(x.startswith^OA'))`35end1Ag!) @bigmemtest(size=_2G + 10, memuse=1[@def &@_lju,Pelf, 2!):I_5 from_latin1SUBSTR =CP abc RBghi'`@Bs = '.f7ize[gs 8! +_ clen(s) `drip(),!st<2<Power(i}<_('A') *us!.lXmI* *&/+*r*l]Ydel s  # Type-specific optimizationkif isinstance(s, (str, bytes)2pedJ"$N2Ois s&Prepla :Bment%aO_(' = M UR#s."(3LO - 4EY rs[-10:] 9/') _rfind &ublen = 0.;#') - "s.Qublen + size + SUBSTR.rfind(_(' '))) self.assertEqual(s*7), sublen + size9cB, 0,2,+I ?, 0 ->:?#.count(_('.')), 0l -!-.O * 27z713) L@bigmemtest(size=_2G + 5, memuse=`@def %_upper(self, 1!):H@_ = .from_latin1`_('a')9ize"s.Xu= s+A01%201_zfill = _('-568324723598234'd2+.j7izeTrue(s.endswith7S0') +_[1:])9 Ustart;O-0')/ M<tlQ0 - )ga# ThisB is meaningful even N < 2G, as long"th*@# doCd stringG> 2G (but it\s more if both are $:123(oconcat  l L7 + 9  m41eZtg*H slice_and_getitem%  01234567898n =P s = SUBSTR * (size // sublen) Astep= len(s)%?100!,5- ( %Sfor i in range(0,Z$- 6, %):jself.assertEqual(s[i], SUBSTR[0].C:i +96%:28K[::2sif i > 0a - 1:iI-3],= G::-3# Make sure we do some slicing and index near the end of }# string, too.6- 1'-14-,`0a`0d:], _('')\,`?-1: ^.d; -.bD[:])Z,V) - 56::5:-3O10) SRaises(I Error, operator.getitem, s CO + 1GC<<31@bigmemtest\=_2G, memuse=2p@def !_contains(k , p@_ = .from_latin1:N =0123456789'a6BedgeG-') $s!').join([4U , 1delSTrue(Fin s%EFals&0* 2 *O0_('O l_('a')K! +a_9%0_mpare "s1{*2F7= s*s2L@s1 +' self.assertFalse(s1 == s2) edel s2s2 = _('.') * size_elf.aM$@bigmemtest(9=_2G + 10, memuse=1w@def &_hash(self,j!):H# Not sure if we can do any meaningfulFs here... Even0Istart relying on the exact algorithm used,result will b# different dependN1 of@C 'long int'Gthis is dodgy (t's no *guarantee* thatRtwo things shouldKghave aS3, e rthey, i0cur>implementation, almos0way.@_ = .from_latin1Js4N\x007Ph1 = &(sOv@?;1|}NotEqual(h1,Y) class StrT@uniti.Case, Base1): ~return s0basic_encode_c6 ize, enc, c='.', expected W=NoneX)if"vA:try-cF<9blen(s.j(enc))wofinalliQsetUp# HACK: adjust0oryj+ests inherited q# accoroto character2.'_kued = {}for name Jdir(eaif not-.8pswith(''_'1vcontinu(meth = getattr(type,Z^- 00 = K.!except AttributeError'T = ascii_W_ **us ^[M]tearDown  S{.items(bBsY=ucs43capitaliz  +Bize)+Otitlz&umuse=ucs4_char_size * 3) def test_swapcase(self, &!):#'+._)Qize) #6# Many codecs convert to the legacy representation first, explaining h# why we add 'ucs4_ch'Q'memuse' below.p@bigmem(=_2G + 2, .f=asciiNK + 1 enqreturn bbasic_.q, 'utf-8'4G // 6 _raw_unio_escap6tryd^'.Bexcept MemoryErrorbpass # ac'able on 32-bito5 + 70Outf7#PQ_4 + 54_utf32<132'Qectedc14 *)3 + Do2G - 1_@t', c='A# str % (...) uses a Py_UCS4 intermediate1j* 2 +  oformatss = '-' sf0%s'"s,Qelf.assertTrue(s == sf!kdel sfIo..%s..M Equal(len(sf), )9]{f.startswith('..-').3end,8-..,,U//= 2@edge.'.join(['P, '%sFdge]hS~s % '...'d)v  /s.count('.'),*unt('-'), si+ze * 2) @bigmemtest(size=_2G + 10, memuse=ascii_char_!<;@def 8_repr_small(self, (!):`)s = '-' * ;6(s)elf.assertEqual(len(s)S +Rk +s[0], "'"OOs[-1%.count('-'zRUdel s!# ) will create a string four times as large this 'binaryJ5', but we don't want to alloc^much more than twiceFize in total. (WJa extra 2est&()! =P // 5bO\x000?* 4^.\\J0-2(5^ 2y} 2f!# x() calls encode('', 'backslashreplacewhich itT# s mporary Py_UNICODEesentation9Aaddi Rto th[# original (=tCS2) onThere's also some overWwhen resiz~ thPcii()3ultpthat is@takec e.*5+ 1Gucs2+;9Hucs4;;* 60uniS# Use an assignednot printable Db point0# I;range of low surrogates \uDC00-\uDFFFB@ = "5BA"  6tryPfor f(,$Xr = f r), 2 +  f(s)) - 2)+d@HTrue(r.endswith(r"\udcba'"), r[-10:]A r =s None finally:rr = s =*!@bigmemtest(size=_2G // 5 + 1, memuse=ucs4_char_$ * 2 + ascii110)U@def R _unicode_repr_wide(self, F)Z = "\U0001DCBA"H *6+trfor f in (n,eM2f(s.assertEqual(len(r), f()) - 2) H True(r.endswith(rdcba'"), r[-12:]E!# The origtranslate is overridden here, so as to get thB# correctu estimate: str.P() uses an intermedigqPy_UCS4 # esentation. xoZp 3j b_elf.from_latin1SUBSTR = _('aZz.z.Aaz.'b!]E = {3ord(_('.')):;O-'),!a!!!Z!$!}Lsublen = `repeat&U/6+ 2B2 = 9 *2 saP sz"* r32s[:$#], p> ->:?#d.count#,  s-9!')2 7z73) class BytesTk@unit".Case, BaseStr"):%=return s.eni!("B-1")BgE + 2k1|1_deZ* Ww Wd% \#s.\a'utf-88capitalizc!._+?izen!Otitli&d$swapcasg est_swapcase(size) class BytearrayTest(unittest.Case, BaseStr): def from_latin1(self, s):"return b](s.encode("4R-1"))Mp@bigmemv=_2G + 2, memuse=1 + ascii_char_e@def 71_de[@s = .p'.') * K%assertEqual(len(s.\'utf-8')),6!2)\capitalize1 Qelf._+%*nOtitli&d$swapcasg)jhash = None-split_largePTuple!# %s have a small, fixed-d head an  of pointers to# data. Since we'rening 64-bit addressing, we can assume that th#]Qare 8!s,)%us3 ts take up/1per.@# Aside-effectFClongO,sqppen to[0hav5 mohan 2<<31 reference any given object. H^G0use1dif8pt types2s as contents in *Cests6`_ompart1 = ('',/t2PTrue(D3= tAl t2 KB + 1 QOFalsR1K # 'hPcatenag into.BngleGslength,H)7conGa; separately, sP2the!erw still gets run eV ifKre isn'tpory forD@(but|L!lev_per know8 2#isGskipped,verbose mode.bbasic_tB/() TtD@Qt + t9O * 2Y // 2B24) def test_concat_small(self, size): preturn d.basic4Qtest(- -u@bigmem=_2G + 2, memuse=24))@def &I_large}A// 5 + 10^8 * 5_tainspt = (1,3, 4, 5) *$%assertEqual(len(t)Jq +True(5 in t lFalse({/ 0PzOhash1-0,h8"t1Nadel t1&t2>3.AU"= V?2))` index_and_sliccNNone'pt[-1], U& 5%b? - Q Raises(I Error, operator.getitem, t :(+ t[-5:], .O20:2^o25:-20b*4 l 6:8I - 2<8384) ++; h# LikeEq, split1wo.znorepeat!''t@E_t * 29* O// 2;  X }} 1G"12fD_}/_2;eat(size) @bigmemtest(size=_1G - 1, memuse=9) def % _from_2G_generator(self, =!):,0`.skipTZ"; needs much morebory than advertised, see issue5438"T6trya = tuple(range)0except MemoryError?pass # ac'able on 32-bitJelse6count = 0$for item in t1assertEqual(,!, L*Y += 1d E({ +/25 oalmost"{, expectedb# Like}concat, splitk1wo.&`basic_kO_repa(0,) *=As = 6tQ# TheR of al 0's is exactlree times the(blengthbHelf.blen(s)F * 3y s[:5], '(0, 0') 0-5:*))* .?C('0')D2G // 3 + 2H8 + 3 * ascii_char_Qo_small'qreturn ?ize $0lar+ cl5AList@unit.bCase):Es, lists have a , fixed-5d head an array ofJ# pointers to data, so 8 bytes per. Also l*tPwe ma:#heKold referenco various objectk ir,+FRmits.q)2G("16comparel1 = ['']/l2;VPTrue(BB= l2vxadel l2 l2 = [''] * (size + 1)  self.assertFalse(l1 == l2#edel l22l2 = [2] * OJ$4# Test concatenating into a single list of more than 2G in length, [# andFa: separately, sothe smaller tstill gets run even if there isn't memory forIDlargD(but we L0let(_qer know2#isGskipped,verbose mode.def basic__H(v,!):H$l/[] Equal(len(l)@ ?Ul + lf&9a * 2) ,p@bigmeml=_2G // 2 + 2,>fuse=24+_qreturn ?ize }}, sinplace\sys.stdoutOl +=,True(l[0] is l[-1]'C - 1. + 4)  A_& L_ A@// 5x0R8 * 56_tains* 1,H}3, 4, 5-q5vl [{/0P37+ 1K Ohash0 Raises(TypeError, N?, l/ index_and_sliceONone  s' , T& /5]%tEqual(l[size - 1], None) 'self.assertRaises(IndexError, operator.getitem, l, sizAEqual(l[:5], [h_] * 5m,?-5:-O20:2\o25:-20`? - 3 j 6:7H - 2;42 273]++65])  l[HzE = 5_en(l)%-32, 5h .count(5), 1 s?, 6D7:] = [1, 2, 3, 4, 5]'*6= 26a\ M7[-7&#*, v /:7U :7O ;Edel :1'1'14 u>-2:p2p2p0n1m.:2n1nK# Like test_concat, split in two.def basic_)prepeat(:'l8%+VvFalse(l2/''4 T ??l **p@bigmem(=_2G // 2 +memuse=2~+_o_smallbreturn7/}_large} (size) def basic_test_inplace_repeat(self, size): l = ['']!*=%8.assertEqual(len(l)K'True(l[0] is l[-1])'edel l * *uel *= 2' F * 2a+H - 1Zp@bigmem-(% =_2G // 2 + 2, memuse=16]^+ Xo_small^qreturn _large4OreprZ,0]As = 5lAsQ# The of a list 00's-exactly three times the'qlength.LW sF * 3w +s[:5], '[0, 0') 0-5:*)]* .count('0')I// 3g8 + 3 * ascii_char_|Pr 7 hs #overallocates ~1/8thQtotal# (on first expansion) so#.Rsingl5.append call puts at 9 byj1perZZ 9^object()l("Zq/+1)$-32t@Fals$-2)<52* 5f ` 1,O}3, 4, 5 8 `I1G+s"1"), 0oextend #l.:  R/+ ze=_2G // 2 '+ 2, memuse=16) def test_extend_small(self, size):'+preturn w.basic_9(- -p@bigmem_=_2G }_large}AI// 5[8 * 5_index~pl = [1,@3, 4, 5] * V *= 5elf.assertEqual(l.cR1), 0}:(5U - 5) 198? Raises(ValueError, 2, 1C -B "6)a# Thisos suffers from overallocation, just like-_append.Z]%109 in -.07Pize -2"A"ZA+= 1 Cen(lz9 '[-3:], [1.0, "A", 1.0]4Z +BK_, "B"_1, "CD&:3C  X[2 - H74;?pop<p"a", "bcd-e"P 0Xitem = l.H-1aH, "e2"A=a :27?- 2LHc -L7d`'+ 8_remov20] * size  self.assertEqual(len(l), size) % l.remove(10)$V -= 1O # Because of the earlierh), this append doesn't triggerq`# a re."l.5+(5+![-2:], [10, 5]c# w"w310]@bigmemtest( =_2G // 5 + 2, memuse=8 * @def ._reverse(:C` = [1,C@3, 4! *#.BLN+1[-5X5q3}1`2 :5 1'Osort(?4.count(1:  10 Y1] *  B[-10j, bmain() support.run_unit7(StrTest, Bytes QarrayQTupleP List ) if __name__ == '__t2__'u0if sys.argv) > 1Sset_memlimit(,[.V(pm  class ExceptionTCase(".Qtry_e7_else_finally,,3hit' = False?lseO66trybVraise('nyaa!'u 5|f = Tru, *-ZI($P%SJ$ls 3_no?ion_Epassg True  self.assertFalse(hit_except) %2Tru$finally% aelse) Hdef test_trya_D(`!):'r1 = 66tryEIqraise Eion('yarr!' 5 ~`y/1 = 01]\J:3_noLoGAApassT3W47fJOahoyJa%H  M& ?lse!?foou  J, + ){1Hb%*'I%k!(A 7 , onested1eSinner! C:D  try:   raise Exception('inner e5') ,# : Ahit_:_:y = True(finally= # > :s0oself.assert(,*\+ %{def test_nested_else(b)v = Fals#OY7<!5lse+tr &Epass3oD:  u ?out , -Z"S#GuH%  ) if __name__ == '__main__'@unit.() """This is a""" from __futurIsimport scopes; `site E3f(x33g(yreturn x + yeg result = f(2)(4)c up # Skip t!pf _tkinPdoes not exist. s6._module('0#')@.QPruntks J(]Drun_U(*DP.get_Cas(gui=, packages=['_ttk'])- pickle _toolsLK.= $errAbstractPYTTests^ class Optimized,(@"):Qdumpsd, arg, proto=None`B##.om(.IC?;eDloadebuf, **kwdsa.0* #  relies on precoutput of I__to_2x = Mwriting by chunks into a file object. test_framed_write_sizes_with_delayr = None def t< optimize_long_binget(self):)-ata = [str(i) for i in range(257)],.append(data[-1]);Vproto? pickle.HIGHEST_PROTOCOL + 1*Bd = a.dumpsf!, Vi0"un(2cloads( ..assertEqual(? , .&Is+%, :R[-2])q|2dtools.Q7.2 2225SNotIn.LONG_BINGET,d;)PU;Cbinput_and_memoizeq = (b'\x80\x04\x95\x15\x0'sb']\x94(\x8cIspamq\x01@3ham!h\x02e.'#B00:  5 4g"2"95 FRAME")21#P11: ]EMPTY_LIST C4 MEMOIZE@3: (=JMARK4z 8c` SHORTUNICODE 'Q20: q. BINPUT 2W;hamV7!94KQ28: hw"GEw2T30: e&pAPPENDS(j at 13P31: ."ESTOPKH *X 2, [l0, 'D< {(1]z y>u 3  2&)2[ 2[q :  2) class MiscTestCase(unit.g]l_all__H blacklist = {'bytes_types',/'UP_TO_NEWLINE', 'TAKEN_FROM_ARGUMENT1>-4EEN_FROM_ARGUMENT4U', 'TAKEN_FROM_ARGU. 8U', 'ArgumentDescriptorDread_uint192Eint4 )4L81stringnl_noescapeN @/[_pairN1DVbytes $tunicode -w  ,decimalnl_short -ElongBWfloat8K A2, VQ P! #    B N &Q & 's O2 StackObjecNPpyinty pyM integer_or_boo&py !pyu=!st"py] PKBnone,Ctupl 3lis dio 'pyse afrozen$c 'anyof 'marks2Oslic Op-@Infoos ?2op}support.check__all__(self, pickletools, black= ) def test_main():XTrun_unit!(OptimizedPWoTests)/@Misc$NCase'1docUif __name__ == "_2__"3P() im dshelveglob from 4collections.abc$MutableMapping+.D_dbm)dbm_iteratorOCL1(sIreturn s.de("latin-1") class 0key|(uD" that supports bytes keys" def __init__(self):x.d = {}-sgetitem0,N5rreturn <[L1(key)]@s@w, valueG @" ="H?del?del 3lenu1len 6.d)p@iter84tfor k i.$ I yield k.encode("latin-1"_ __]P__ = Bx t1ist.7#()SAcopy:ckeydicB class TestCase(unittest."):fn = "shelftemp.dbNrtearDowC{)f)Pglob.w.fn+"*")2support.unlink(fa_close@9"d1A@s = @ve.S(d1, protocol=2, writeback=False)['key1'] = [1,2,3,4]elf.assertEqual(s/,.M /`G), 1$.6Raises(V#Error, len, s.6tryvexcept F 1Fpass,:lsepfail('C|dZf should not find a'ascii_file_f$op~'fn0C = (/M 23lfinallR'bobinary* b.2*2X|in_memoryO *[VJs_d2 = ve.Shelf(d2, protocol=1) s['key1'] = (1,2,3,4elf.assertEqual(/,./.close() ` Blen(d1), %2%#Nod1.items(), d2 def test_mutable_entry(self):d1 = byteskeydict( = shelve.Shelf(d1,F2, writeback=False:W[W]tW.M.append(5 ;K/d22?Tru7,5]1 pkeyencodingnQ = {}/key = 'Pöp'# the default O is utf-8+ P)[key/[1nqIn(key.1e('K'< # but a different one can be given|,='latin-1'78, dwith all consequences  fascii'QRaises(UnicodeEeError, s.__setc!__R\, [1]`a_also_s_immediatelt# Issue 5754d6keyd6Ls 4p&d[q] # Willa a Key&@ if Ving store not updated$']2p }Hp!2) creates new object inV $V as sb5 = " k263s6 self.assert Raises(ValueError, len, s) Etry: s['key1']vexcept F 1Fpass,:lse!self.fail('Closed shelf should not find a key') K def test_default_protocol(O)bAwithQ@ve.SX({}) as s$assertEqual(s.T, 3) fromt import mapping_s class TesthyveBase($`.Basic"M;Pafn = "temp.db"counter = 0__init__, *args, **kwMv_db = [.bPtype2) =areferencereturn {"I@":"v@1", B2":2 3":(1,2,3)}Ucempty_ Y0if ._in_memx(byteskeydict()=<Ke1+=1ndAopenr.fn+str 7ndb.append(x5xp`rtearDowf^for db in *db@db.ci(\w )!if~RjfiPglob.gfn+"*"0sup;.unlink(f)7AsciiFile@() KN_4={'2':0 = FalseoBinaryY1Y 2Y2Y  2Mem &>TruW  WW W st_main(h`modulemdbm_iterator"]run_unit(.R\,! /"D eBd!c!ECase) if __name__ == "_A2__" () # Copyright (c) 2001-2006 Twisted Matrix Laboratories. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associadocumentatrfiles (the # "So40"),ideal in the  without restricF, includi!ClimifA`rightsWAuse,, modify, mepublish, # di_pbute, s0cen8and/or sellDAies ,`to # p[t1son|Jwhomis furnishedQdo sotQject Hfollowing condi!s:The aboveyr noticepshall bx> edl1coprstantial poru FdTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO sM`IES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORSCOPYRIGHT HOLDERS BE # LIABLEoNY CLAIM, DAMAGqR OTHER'1WHEIN AN ACTION #CONTRACT, TORTu=WISE, ARISING FROM, Y OF#IN CONNEHw!OR0USE0S DEALINGSX-. """ Tests for epoll wrapper ims errno $os eselectEockeDtimeunittest if hasattr(A1, "{"): raise 5P.Skip ("D works only on Linux 2.6") tryBX.V() except OSError as e(Qif e.2 ==r.ENOSYS  kernel doesn't sup,FF()") class eEPoll(qCase): 0def setUpfself.serverSiA = s .(q,.bind(('127.0.0.1', 0)1 lYnTQconne]s = []tearDowni0skt?Stkt.close()V_/aed_paiA%oclient!.setblocking(False D3y E@.getname()[1]fgNassertEqual(e.args[0], errno.EINPROGRESS) Uelse:raise AssertionError("Connect should have *'d X"Yserver, addr = self.Socket.accept() ~$ciions.extend((client, @)ezreturn Qdef test_create(])6try "epect.epoll(16i ex1 OSO as 6Wstr(e!.aZTrue(ep.fileno() > 0, | 60not)fclosed'1ep.( :#6#Rqs(ValueTif hasattrSect, "EPOLL_CLOEXEC"fY6selT 1) 7oflags==*0gfn", S12356b?bade]4Typ\l, 1, 2, 3h<_'foo':"ONone9"(C[]s",{}xcontext_managef}@withx~116)pkG-r6, 03AFalszW#7z m0addy,3f._Jxed_pairi2q.registc%DIN |q6OUTX;&epKK"mfinallH2p#ing by obj2w/ t works, too.1-/B ep = select.epoll(2) Etry: 2# TypeError: argument must be an int, or have a fileno() method. Eself.assertRaises(] , ep.register, object(),HEPOLLIN | 6OUT.rONonen-d# Valu.  descriptor canno7 negative?eger (-1 \ -/-1/#OS[Errno 9] Bad E _10000/ing twice also rIexceptionWP(serv^3D!^ ~lkfinallep.close() [def test_fromfd()@ cli= f._connected_pairL1ep % ;ep2.w0ep.M2o',f 'epHH*pvents =_F1, 4jer!90.9#`Equal(len(87), <)2* z  V as eI e.args[0], e.EBADF, e/lsFafail("A on d fd didn't| O"control_and_waite'16> xw YEXRk4Gnow = time.monotonic(Fthen?notonic()  self.assertFalse(then - now > 0.1, 1) 5 events.sort()xpected = [(client.fileno(), select.EPOLLOUT),8V(server8]8epbEqual($, 2  = ep.poll(timeout=22max<&=4_6#Usend(b"Hello!"Apworld!!! = .monotonicj71, ? 1'01dJOIN |2I=p.unregisterep.modify9q8X def test_errors(8%): vRaises(ValueE-(eF, -2v84().O, -1k #IN ~_closed",  =Pqf._conn W_pairf s"epA(6(16%epw1x0e[#fdk0+Popen_D0 = !(_y__, "rbSddCleanup(-+.XF\|cufffd\_8b10"m F"\x}J VPPignor u)"PThis  or everybody to add@bugsG t aren't # fixed yet. Please3a5! cnd appropriate bug description# When youP one of th-Bs, pZ0move]!to"`correcP_ moduleV " ZK"NoXpoutstanAs atsamomentc/_compression$ioBytesIO, UnCedOp, DEFAULT_BUFFER_SIZE$os upathlibTickledrandom2sys?y$$.#2_4G, TESTFN,_, bigmemtest, run_unittest, unlink ) lzma = import_module("") from   LZMACompressor,;Dec4ErrFile class :4TestCase(unit.): #  eWr cases.@def 2_simple_bad_args(self):=A.assertRaises(Type_, [])9#format=3.45B$check=""?$et="asdfD%filters=3# Can't specify FORMAT_AUTO when Oing.;OValuu<l.`"a and a custom  chain at the same time^with <@ (z3=7,ps=[{"id":,.FILTER_5B2}])Gr F, ();memlimit=b"qw (6RAWG"zzzh3&no4a memory  (?RAW+  A0x10VU onlyKE"s=vS_RAW_1hT  H&XZwX_ALONEz'Qlzc =H( d, lzc.|3 , b"foo"7barvQflush87lah9qempty =$ +YGquuxY =om3lzdYDecompressor(3) self.assertRaises(TypeError, lzd.decompress5", b"foo"Fbar"E ]f(empty?EOFZqquux") def test_bad_filter_spec(S!):$SLZMAC Hs=[b"wobsite"] DValuFL{"xyzzy": 3}N1id": 98765O^with  (!{"`lzma.FILTER_+12, ?: 0vT_DELTAv^:X86tIm'Por_afuVm# Test+ on known-good input data._,-, check, unused_AG=b"" c`False(6eof[out =#(J#EEqual(out, INPUT%j+?Tru qL j1uto7 Ylzd, ma.CHECK_CRC64hQkHECK_NONE)  def test_decompressor_xz(self): $lzd = LZMAD)(lzma.FORMAT_XZ)/>-._Y(lzd, COMPRESSED_XZ, DCHECK_CRC64) G_alone _ALONE7 NH_raw_1 RAW, filters=FILTERS_RAW_17292#2393#3494#4ochunksout = []6Nfor i in range(0, len(W), 107VassertFalseOF.eofj&out.append  a[i:i+10])>b"".join(out|PEqual, INPUT%lzd.checkh[?Tru!|Wunused_data, b""7 o_empty7b'':,E CertEqual(lzd4.unused_data, b"") def test_decompressor_chunks_maxsize(self):04lzd = LZMAD5%()!max_length = 100out = []|L # Feed first half the input6len_ = len(COMPRESSED_XZ) // 2'out.append(lzd. 6 [:P%],8= ).assertFalsexaneeds_*`Equal(out[-1]), ^Retrieve more P withFprovidingo 8b''nw_hile $ [:=OLess!`remain$un`!edw@not Eeof:,Ci=-.join(outout, INPUT%check, lzma.CHECK_CRC646 \buf_1# Test reus) buffer after movexisting# contents to begin N SCreatnFll i ?100 ~=0), b''%# some results, free)capacity atB# of0 )2)2Addthat fits into`f#| b100:105], 15(tb?5:]i6b''whecompressor_inputbuf_2(self): # Test reusing ) buffer by appenddata at the=end right away lzd = LZMADecompressor()!out = [] # Createand empty it+.assertEqual(lzd.di(COMPRESSED_XZ[:200],=max_length=0), b''. s')DFillHwith new D?outM 200:280], 2)cA some more_, not enough to require resiz}@80:3@ }[At off300:])c b''.join(out), INPUTdef test_1or_3after ext&it)almost full)+ 5vdd even3it,%0 tpunused_g extra = b"fooblibar"_l),  +Era, lzma.CHECK_CRC64= 2bad@pRaises(PErrorL SRAW_1@TFORMAT_XZw_ALONEw3%RAW, filters=FILTERS_6.bug_28275 # Tes t coverage for Issue 28275  lzd = LZMADecompressor()!self.assertRaises(-Error, lzd.d8, COMPRESSED_RAW_1G6# Previously, a second call could crash due to internal inconsistency5H# Test thatC -> erves the input data. Ldef test_roundtrip_xz(;!):!n3lzckkicPt = lzc.(INPUT) +Wflush2_or(lzd, pma.CHECK_CRC64)_alonelzma.FORMAT_ALONEvjN?rawRAW, filters=FILTERS4@\y.o_empty$]E@+'qmemory  ?RAW),A0x10 W onlyLSb&_1}H &XZ{D Y_ALONEKI_ T7ALZMAY COMPRESSED_)f 1es(LZMAError)7: lzma.decompress((COMPRESSED_XZ, format=;aFORMATmemlimit=1024)Iwith self.assertRaises(LZMAError)+_ALONE p# Test Dor on known-good input data. 7def test_1_*_*(d:1 = (2(N(>#aEqual(@, INPUT)W ZBgB,:jm7OZRAW_1~RAW, filters=FILTERS_(W22W33W4z in7OleteX ', XZ[:128]6K7N6N,BJ !A2;E3;I, COMPRESSED_RAW_4[:128], format=lzma.FORMAT:, filters=FILTERSA_4) Jdef test_decompress_bad_input(self):)vPwith .assertRaises(LZMAError+/X(COMPRESSED_BOGUS)Y@+1YAALONE, d/XZpA/XZmpX?RAWs  ]1]# Test that ^G()-> ) terves the xk data.roundtripc.1 = ogVINPUT)d%='aEqual(8#, N7t,L5X 4eK/4 ZO# Unlike DGor, ) *does* handle concatenated streams?b_multi' .WXZ +   J * 2brobusting of non-yp followR?(s)trailing_junk0 * _0:* 3 * 3) class TempFileg"""Context manager - creates a file, and deleit on __exit__.""" def __ina(self,=name, data=b""):,0#._"% =- !9! =@gqenter__hTwith open^, "wb") as frf.write/l)fw, *argslaunlinki) class FileTestCase(unittest.&):g7Ka@LZMAL(BytesIO(COMPRESSED_XZ)EpassEE)=x=)a=J__PathLike_1 - = pathlib.4(TESTFN)XNQ TempU6*, W %44{b assertEqual(f.read(), INPUT.\?, "%3N%G * 2  b`2 o=1BBR 2modJ  +r"(,{ =b>)w=*{*a{)a{;?_x_ddCleanup(", _@for @ in ("x", "x=  RopRaises(ExistsErrorJw, mode):  `pass def test_init_bad_mode(self):"&Pwith  .assertRaises(ValueError,0LZMAFile(BytesIO(COMPRESSED_XZ), (3, "x"))cG/""]I/xt_K+_J/rx_Jw_Kr|Kr|KwKwKOrw"):_check;?Typ:), "w", ]g=b"asd# CHECK_UNKNOWN and anything above! ID_MAX should be invalid.  Ylzma.j/6+ 3m# Cannot specify aK O="r"'FNONE[9 p_CRC32q\/64qYjSHA256r self.assertRaises(ValueError): ,LZMAFile(BytesIO(COMPRESSED_XZ), check=lzma.CHECK_UNKNOWN) Hdef test_init_bad_preset(selflPwith s.assert?Typ), "w", ^a=4.39)] ]/10[F/23[Overflow!/-1_K7_%V"foo"^# Cannot specify a mode="r". 'i3pfilter_Ecs=[b"wobsite"]$ Sg{"xyzzy": 3}iLid": 98765jApFILTER_,12, ?: 0s_DELTA}:X86m  S_and_z( RormatFORMAT_RAW, 36, =S4,_1_close3z as srcg@f = ck6src"f.e #2 should 2 the underlyinge object.  self.assertFalse(src.closed) #`# Try ing an already-ed LZMAFile.6fL(Lu @$# Test with a real file on disk, opened directly by?@Temp (TESTFN, COMPRESSED_XZ):t5f =H1 fp = f._fp8u# Here,R% *should*Te the underlyaZbjectR<rTrue(fpR<def test_(|- )BytesIO(Z9:trygM z, f.gA <kfinallt'NON o), "w"+33/noFRaises(UnsupportedOperation, f.~aValueErrorW@ dEqual( ()3_fp&()9=IsInstanceB:int7/L 3 seekable F?h  ?!) ])\Gdsrc = r = lambda: False  f = LZMAFile(src) u try: self.assertFalse(f.seekable()8kfinall<f.close('NRaises(ValueError, [!) def test_readsA) BytesIO(COMPRESSED_XZ 0Truh7 f.?4f), "w"r \@[@writ(EAi@ 42[@[ FwithiV as fZdEqual(v, INPUT. 'b" ALONE))*eXZ), format=lzma.FORMATy* @%wqRAW_1),0 iRAW, filters=FILTERS_F{222) as f:  self.assertEqual(f.read(), INPUT) (.6b"",with LZMAFile(BytesIO(COMPRESSED_RAW_3),]cformat=lzma.FORMAT1, filters=FILTERS_3) as f:KM424O1def test_0_0(9)L?XZ)O0), )_ALONEdL_XZ), t/XZQ{Z16chunks = []hwhile True<result = Z&10( rif not +C#YbreakuBLessBlen(K?), ot.append+ \XTb"".join(<7 GmultistreamQ O * 597 + sy2y? * *3"~ ,_buffer_size_aligned # Test the case where a  boundary coincides 01endA# ofE@raw  |."Xsaved = _compression.BUFFER_SIZE5 !ER_SIZE = len(COMPRESSED_XZ) Etry: with LZMAFile(BytesIO> * 5)) as f=Aself.assertEqual(f.read(), INPUT * 5kfinall_compression.BUFFER_SIZE = saved_buffer_size def test_k_trailing_junk()'+ /_BOGUSZ )multistream/O* 5 4N`from_f JATemp+xTESTFN,:'XZ. |2H%DZ?b""_ _bLname: , /2 = .encode("ascii"except Uni E&VErrorskipTest("b`orary   needs to be ASCIIf 5$ j in =let o[:128] Raises(EOF", .truncatedr# Drop  footer: CRC (4 P), index p# flags (21 and magic number.6* =ye[:-12](/>%&`, )Alen(*)3Bl6, 135# IF@ 12-v headerHfor i in range(12 @?[:ii bad_argso?f = )) f.clocse() self.assertRaises(ValueError, f.read.with LZMAFile(BytesIO(), "w") as f:Za^1COMPRESSED_XZ)f:Typ, float()) def test__bad_data()_BOGUS7 W1blocks = []fwhile Trueresult =1'rif not *B#Ybreakt.append(@X"|Equal(b"".join(), INPUT6 1?b""?1_0f5 ~O0), 16,*10Smultistream O * 5v2t  PLargsu>f =>O~_f.clo1X+_  |1, NoneLpeekS s f:  result = f.peek() self.assertGreater(len(5O), 0/True(INPUT.startswith96Equal(f.read(), A.D LZMAFile(BytesIO(COMPRESSED_XZ)) as f:1idef test__bad_args() o), "w"?Raises(ValueError,*) iterator|}IrQliness]BList0Plist(a(f)), l5_ALONE8nAXZ), format=lzma.FORMATATqRAW_2),uq#RAW, filters=FILTERS_F+yy1for1 ins 3+GK _yssdecompress_limitedE"""D% ed data buffering should be @1"""cqbomb = h(b'\0' * int(2e6), Fet=6ALessAMD), _Iion.BUFFER_SIZEw. =Dg:KA1), ) max_decomp = 1 + DEFAULT_BUFFER_SIZE self.assertLessEqual(>._buffer.raw.tell(), ma],DK"Excessive amount of data was Qressed") :def test_write(!):Pwith BytesIO() D&st#LZMAFile(dst, "w",f*."f.heINPUT)hexpected = lzma.;(,0,st.getvalue!Mc&, format=FORMAT_XZ>h %n_ALONESk{:RAWrfilters=FILTERS_RAW_2.S  h%8 F?_10IO or start in range(0, len/G, 10 [E:F+10]13G<4lappend8part1 = q[:1024]>2Z:1536!3!F536:b"".join(y x) xc(m01, 2&3)-^& p1hl rarI2I53ItEqual(dst.g(etvalue(), expected) def test_write_to_file(self):"&6try with LZMAF.TESTFN, "w") as f-1!f.au(INPUT)Y = lzma.compress,xUopen(t/rbu.assertEqual(f.readkfinallcunlinkm3 _a_bytesC?namG /2 = .encode("ascii"/except Uni E&ZErrorqskipTest("Temporary   needs to be ASCIIf oappend0part1 = u[:1024]2Z:1536!3!F536:.b"".join(7x) for x in (m01, 2&3)P a1YQ$a$L2L83LD{bad_argsx6f =BB\ IOiPf.close(Raises(V*#, gw, b"foo oCOMPRESSED_XZ), "rt?bartgLgLTypeFNone8W"text:?789Mlinei`I7;2 =  Dv8dst with LZMAFile(dst, "w") as f: f.writelines()$expected = lzma.compress(INPUT,self.assertEqual}.getvalue(), M!) ddef test_seek_forward(F)with LZMAFBytesIO(COMPRESSED_XZ) f.VO(555 `f.reado[555:] _across_streams O * 2 3len`o + 123?123 relative_to_current O:100z1236, 1 9 O1336/enG=-555, 26Oback;w \x+21t?211  J +33 ?737737:] + _*W@?150W ?150_past_? ?900L@tellT:?b""Ostar8$?-88 F }bad_arg:?f =9f.close(assertRaises (ValueError, f.seek, 0) with LZMAFile(BytesIO(), "w") as f:,3self.assertRaisesa#COMPRESSED_XZ)i(6, 3# io.BufferedReader rB Typ  instead of  (?,5)VZ9, ().EONone7 b"derp") def test_tell(x)qpos = 0a\while True`wEqual(f.j), pos0result = f.read(18%rif not ,t#Ybreakr+= len(= 3WINPUTD)0for in range(0,XW, 144Bf.write(V[pos:pos+144]"D K_bad_argsT>f =8 SOf.close(H8 ) class OpenTestCase(unit.+):binary_modelzma.open _, "rb 1), iQK:bio#0bioxyGjile_data = Rdecompress(bio.getv I ga{N * 2/xt$un(Bed =.=de("ascii"j-x_raw =  .replace("\n", os.linesepB A ted) with BytesIO() as bio: #lzma.open(bio, "wt".f,7f.write(uncompressed)Rfile_data = Y$de+_.getvalue()).de("ascii"Hself.assertEqual(Y(, ~J_raw:aa * 2) [def test_Pname()TempFile(TESTFN#$b_INPUTc IrIf.read()`b/, aa.N(2_pathlike@X2 = ,db.PathJN h6j &l0K'&nEt?, "pjbad_params# Test invalid %eter combinations.N~Raises(V[ErrorGN+?rbtQ=", encoding="utf-8bA-s="ignorea@newline="\n"ormat_and?terest non-default format and filter chain. options = {"-": lzma.FORMAT_RAW, "=s": FILTERS5_1}HBwith8open(BytesIO(COMPRESSED1), "rb", **zu) as f:Iself.assertEqual(f.read(), INPUT).wmK:bioM#bio, "wf.write(uile_data =decompress(bio.getvalueCT0def test_encoding(:)# Test non-defa+$unBed =H.de("ascii"W-x_raw =  .replace("\n", os.linesepBv!Dt", ="utf-16-le" (F"W)xHz ],"5 jseek(0) r2  R_error_handler`e > >s1(b"foo\xffbar") ,s="ignor-' #0new explicit , (universalmode disabled)$Otext I-wG=<E pris2[+]) x_F L ddCleanup(unlink, TESTFN@for @ in ("x", "xG"xt"MC(BN#,Y E.ApassO ?Raises(FileExistsEJ9x pass class MiscellaneousTestCase(unittest.): def  _is_check_supported(self):'+# CHECK_NONE andCRC32 should always be G,A%regardless of the options liblzma was compiled with.?.assertTrue(0./))B)"))-The .xz format spec cannot store H IDs above this valueOFalsID_MAX + 1`@be av%id+tUNKNOWN|: _encode_filter_propertiesA Raises(TypeErrorlj] b"va dict"eVf {"id": 0x100}fM FILTER_LZMA2, "junk": 12}~?OLZMA'CVDELTA "dist": 9001}41est parameters used by zipfile modul$JAs =  {71"pb": 2 lp_c": 3_size": 8 << 20&}aEqual(, b"]\x008"Ho/deoH]NsX86, {"bWbytesFL  b"too long' # ot s mCself["],TAlf.assertEqu al(filterspec["pb"], 2) self.assertEqu. lp.0.c.3.dict_size58 << 20) def test__properties_roundtrip(!):01 = lzma._decode@(040FILTER_LZMA1, b"]\x008"@reen]dmm:26tM ^01, 2) # Test data: INPUT = b""" LAERTESm O, fear me not.$I stay too long: but here my father comes.JEnter POLONIUaA double blessing is adgrace,vOccasion smiles upon a second leave. LORDh"Ye, Laertes! aboard,for shame!qThe wind sits in the shoulder of your sail0AndA are$'d for. T;@withRp=these few precepyy memorySee thou character. Givyghts no tonguENor any un<ortioned2 hcBQou familiar, byZmeans vulgar0ThoariendsW hast, anfeir adopwe tried;`Grapplpem to thy soul )Phoopstdsteel;`But doQ dull5Bpalm5eutainment3Of each new-hatch'd, unfledgedrade. Beware6pntrancea quarrelenBear't thae opposed may bYEthee:every mal4y eqUvoiceBTakeman's censureSreser@judglPCostl(y habit ay purse can buy!utbexpress'd fancy; rich,Ugaudy0For apparel oft proclaimlebyYFe!of@bArankA0sta:0AreGa most select(generous chiefV1Neia borrower n@ lenbdAloanloses both itgmf W_husbandryTvbove all:`thine ownfWbe tr/it must follow,qe night:&daT*anst not then be false to any man. Farewell: my blessing season this iee! LAERTES <Most humbly do I takeHaleave, ord. LORD POLONIU@ The time invites you; go; r servants tenE  , Ophelia; and remember What I have said toe. OPHELIA"'Tmy memory lock'd,K0And;rself shall keep the key of it . """ COMPRESSED_BOGUS = b"u s not a valid lzma stream7aXZ = (b"\xfd7zXZ\x004\xe6\xd6\xb4F\x02!\x01\x16 t/\xe5\xa3"PeH@7\x8c3\xdf]/5\x14\x07bX\x19\xcd\xddn\x98\x15\xe4tD\x9dPo\x1d\xc#5\n\x03\xcc2h\xc7\\\x86\xff\xf8\xe2\xfc\xe7\xd9\xf4b8(MP\xa8wN2\"u.n\x1e\xc3\xf2\x8e\x8d\x8f17/\xa6=\xf0\xa2f/M\x89O be\xde\xa7\x1cz\x18-]\xdPf\x13O"rZ"8c8do\xfa\x12N@9b#zQ0}P1\x82bMa1t\xca6 BF$}RQ\xa4BePl\xe8\x7N@9d,b?b d4 @\x81vRN\xc8L 15 5xt$2OM5@k15\xd0O\x9lco\xae\xf7zcdS\xb6t<2`F9cI#O089u266Y ce]ypa\x96-Pfde:\x04\t\x1bnP0db701fpJ\xba\xf4HV\xa9\xd`2%G\xf2f=?&1bNPe1(\x082= @I\xa(1 acR\xb7br\xb1i"95"@bd\x&faP002sPX8 2jL46d4c-H\x93oJlg iQkP8GRb\xc1 bcQ0\x1x8 pca?@\xfP7\xeax\xf1H12P\x0fOPa\xc9%buw\xe30aai6Wcd#cb5\x99 8]@d\x0}+ cWpdUG\xbf5 yFP1v\xb#0beh`8W\x089e5:\x1a?rD80\xaf8ob\5@5\x8x3m&ac00 7iJ 6Sck,Kvy\x88\x91\x9b6T\xdae\r*0]:kVlPVbh c3i9r\xeb}r\xd b*$z8cpdjcN`5-\xcbKIc5R5\xc0`86Z\xf&PbL\xefPcf\x98i^zce!\x92ce9^\xa59w \x9bP\xa3PHK\x08d" b"\xf9\xe2Z}\xa7\xbf\xed\xeb%$\x0c\x82\xb8/\xb0\x01\xa9&,\xf7qh{Q\x96)\xf2"Pq\xc3\x80\xb4\x1A a\xe6o\xf4![\xd4\x8aw\x10Rtr&b3`d9\xd5Q `^\x81\x11??\\\xa4\x99\x85RIe\x83\xc9\x1eXVa\xf1M"acea\xd7\xd0\xab\x18C\xf2S1\xb7N8\xcbS\xe4>Nha95H\xeP\t\r%9`\xc7$.1\xf3R\x17\x1db\xbb\xd8U\xa5^\xccSN"16^ 875/\x93\xdBr0v\xc0rcc\xa2Gkz\xcad`0e\xfdN8mp2Ix\xb3y3-0\xe3z^\xd608f_&\x9dP\x9fi d890\x84\xdDf\xcdky\x8e7f\xa3\xb2+|\x04\xef&\\cEfaS"e92e3Y01dYXh cfw29VPc \x8b|l3ej\xbe\x1z4z\x9c`\xda\x92A\x06\xe5\x8.qt\x9e=\xfa\x1c'_p%v\x1bo~!ZOxf4\t\xddM\x16- fcI4<\" CM#`g~b\xfuf3Xyde|\xa0'd6x\xae!J\xa6F\x88\x15uP@\x002c7yd8u\xac_ 0\x8 1@P\xecq5`3#\xadIM935\xb5)_\r(3]\x0fo]5Mmy\x07\x9b\xe[5!`\xcfK+N e4Ha431a @b0\x97t a1d9Vd\xc8P ae"+is0b9k`>f\x19Pa8\xf! f$e&{pN c6N@0\xcb66?h$@bZ%'#\nfHV"\xbaO@6r7X=mNX[B19FU9 86c\x90a+* P_$\x0x@xcd_ kxde\xaf46qK#92 3`C} ff f6x`\x0bw\x d8V)9[20bZ&80eb# 1d{104w*r%bw1PB:\x96P^VPaH\x003\n201X&9{a0u#%0*\x:018vPec!\tqL`Vj?uLUKIT#0f60twP`99P\xbA4g\x02( 4YZ" ) COMPRESSED_ALONE = ( N 0$P05\x107bXc[Pdn\x95 9d?s5d@cc2h\\\x86\xff\xf@8" b"\xe2\xfc\xe7\xd9\xfe6\xb8(\xa8wd\xc2\"u.n\x1e\xc3\xf2\x8e\x8d\x8f\x02"M417/\xa6=\xf0\xa2\xdf/M\x89\xbe\xde\xa7\x1cz\x18-]\xd5\xef\x13\x8frZ15\x80\x8c\xf8\x8do\xfa\x12\x9b#z/:kfaF\x01\x82\xa3M\6a1tOca6 BF$\xe5Q\xa4\x98\xel\xe8\x7f9d,bn\x0b d4 F\x81N`e4N\xcP6\x15 5x| 2O5@cP1\x005\xd0O\x9dco\xae\xf7zOc4\xcdS\xb6t<\x16h@9cI#>u266Y ce ]Naa\x96-Pnde:\x04\t\x1bv\xdb7\n\x8 fpJ\xba\xf4HVV\xa9Md0\x02%G\xf9 =?RPe1(\x82=\xd6I\xa(v0cR\xb7Mae\r\xb1i\x03\x95"bd 002sPP\x9dX0 2jLM 848pajr\xd1=^ dd03!EPvV\xd*f3\xd7\xb4N 0c`P~\xecE\xe37\xf'\xbb\xddc%\x0fI\x0#`0;\xafEPabZ\x99(\xe9o 0o>`\xe1\x"a8pa1\xb2}JNB834Tv- c10bcDQ`MA@\xd0d\x 93F\x1aNb 94F002S`8\xc9\xc5hBTJE}c8g\x17#ZVN,9o8k2e>0 90 8/ y_(z20br! b0|?Np83@\x84o}:@z\x96yf5BeyX\x|1G1 :\foPxD\\&j 5YJ v{gBe7)A004o 07S3\xe0=7|Pf?v\xXedVtTf\xb>7e:"'k w@c5\\cVp15|w\xbclb7\x08dE8}bU`b\xb9 DC` ,\xb3J@0\xdad1\xffv\x0 f}9 b%* df08.\xa16"1907fh"1cg0f \x11Bc6Bl019U"4s$p10H\xea pB8'008cZ0\xe'4A2#;z? 7{UP5!\xcybf\xc1Ad@0$\xj@02qgJf\xc7/|O0afr@^\x9E@8\xb'9 7n:@6{>80c7:,'.?M`1d\x0e-9@e\x0 f:A!'[O@"wD$$wq< ,1QN0d0,1 2w!$JN mgA9cA\M9d&\xca8i\x9c;KNQ" b"\x1frh\jx8beL;\xb0m\xee\x07Q\x9b\xc6\xd8\x03\xb5\xdeN\xd4\xfe\x98\xd0\xdc" b"\x1a[\x04\xde\x1a\xf6\x91j\xf8EOli\x8eB^\x1d\x82j@\xb2]R]\xb7\xd7N e9\xa6\xc3.\xfb\xf0-\xb4}b"88c1iN\x0e\x84wbQ\xdf~M24\x884\x96kM\xbc)T\xf3\x89\x97\x0f\x143\xe7)\xa0\xb3B\x00\xa8\xafP`82^\xc%a7..\xd p\t\x9dHG5\xe9#\xe6NV\x94-$Kk\xe3\x7f\r tP12\xcf'\xefR\x84-LH\xac\xe5\x1f0~?SO\xep 1Es\x1c]\xf2Mc4<\x11\x02\x10Z0a*?\xe4r\xffL6nG\xead^\xd68\xb6uEIO99\nV\xeP3\x95\x83\xf6i! &1F\xb1DP\xf4 SO3D!w\x99_GT+\x90P.\xab\xbb]\x91>\xc9#h;} 5JKC`^-[\x93a\\@asD\x19N#a14\xb8p\xar\xe0\xcar.l []d@af+0;gOP01aKY=Ip,\n\xe8|rV\x80_#f2\xa9\x06\x8c>w" W,N 8c0f96,cc2\x05=kTv0Uti@_\xc`a\x8dlhzO0fbfP0 Gx" ) FILTERS_RAW_1 = [{"id": lzma._LZMA2, "preset": 3}] COMPRESSED<$( 5 07o2fd]04"bXpcd\xddn`2cyq ddLaj 3'0\xdf P1\xa4IbdVL8\x15P_=Xc\xa5\xcd\nWk@$=R; k82b1{7 c5dNC\x87i"efb17S3Pxcc\xd2\xed 0e5bMbe4*\xaa\x0@5\x0@0\x8xp81.\x179b0ZrAG0Fs\"rNrdaG\x81B90cuy@a9.A]lH\x98\x10;\xc5\x03#\xb5\x9d4\x0%7ba%v\xa49\x97A\xe0\"Op8c\xc22qPi\xc1A \xab3\xdf\xbe\xfdDm7\x1bi15o:J\x92Mdb\x816\x1|b2O\x9990e\x8d\xf3\tQ\xed\x85S/\x16M\xb2S\x04M0f\xc3J\xc6\xc7\xe4\xcbf4\xe7d\x1 4=^B\xfb\xd3E\x1e\xcdN91\xa5\xd0G\x8f.\xf6\xf9\x0bb&\xdr2j\xa2\x9EP4\\\x41dCPv\xd2\x8a?^H\xec\xae\xeb>\xfe\xb8G\xd4IqY\xh0d4KH`1\xf4DWPmpeaO\xbfl^P4U\x1Q{\xaa6x81M;f\xa3k{\x95\xb+9"f8La3\x08O*\xf01B-h(RxPP@E\x93W:PV\xb7@Y\x9b]\x83\xc4d20gXdcf\x0fP{20]n*< a3)5*u*T20A$A7WO"ef0a#iwC0\x8t2d9%<e a=RB\xc0$c6P@D\x87@8\xd1\xbbq.a0\xf5Cqp\xeeL90\xec \x84\"\xe9MLt01@~\x909\xf0\x012eixd 0c5) 6)P@03@lzB\x7f0a5yIbFD:96\xb4\xb3?\xb9\xce\x07O R1\x00 c3"%_L$&Pe2\rhp#\xd67Q,62hnO.Ra3_?q`e2\xacO0d0_|u"caI095S.GW\x1Ofu dt 9L\xf2|\xdaWs PL\x18r_@$\x8aFkPvB 8hhb'c0a5Gr\xcc\x1fP`1\xdcyrI\x8bcw10rIp\x02:pp_\xc8vyablt3O4@e\xa@3\xa4`abH*m}@a}>lZ4jMP3d\xa>3 1Pc5fOgU@\xfcP^&\t@006JMO@5\x8aRU 1r z7ho\xc9^\x9c\xb_+,c4l U7r\\!\xea94k\xb9Ud-768azed@PG\xa;`2\x05w#^b+ e0M@033S,3f6@5N0\xaQR0\x9a0c3s6xRDM0f4`9s91\rTZ-X\e2\xee|\x1a\xbf@\xfb\x08" b"\x91\xe1\xfc\x9a\x18\xa3\x8b\xd6^\x89\xf5[\xef\x87\xd1\x06\x1c7#E\xa2Ot\tQ5/@S\xc05\xd2VhAK\x03VC\r\x9b\x936M\xf1xO\xaaO\xed\xb9<\x0c\xdaeP*\xd0\x07Hk6\x9fG+\xa1)\xcd\x9cl\b e7 K}5\xab\xa0\x19uP\xf6*F\xb32\x0Z" ) FILTERS_RAW_2 = [{"id": lzma._DELTA, "dist": 2},HL7_LZMA2+p "preseKfPRESET_DEFAULT ||EXTREME}] COM5SED(e@7\x85]5\x14\x06-\xd4\xa8d?1\xbe\xafH\xee\x04xcb.\xb5g\x8f\<CZ\ f\x025z\xa4\xdd\xd8\t[}W\xf8G1dmH~0a\xfcg\xba\xe5\x01Q\x0b\x83R\xb6A\x885B$e\n\x1cv~\xde:oO06:J\xa7\x11Cc\xea\xf25*o 83\\l\xbdE@\x1fa8\x10\xb0caU{\xd7\xb8w\xdc 1b8.0\xc@38\\JB\x13zf98\xfac7[\x17_9\x86%o aaa\x8dfs#\x1e=Q<\x92P\t\xfk6qP@=\x9f@1dftb=\x95Q\xc908\xp7\xc3\x7fP>  1#ArAm\xdbJ~ra3B\x82Z0cc(H`PWK\xad\x.P94kajI >0HwpfS\x84%!iMP\x99X!0B\x90;E\xfde\xf`da\xcaFT!bgn!j\ 83/]P"MP\x0frAPa5j~PuGH\xbfN*Z .\x81\tpE\x8@"%bdP"a98 4\xf9\x0eNP9\xae~Pc1\xa9P_~O 01k00\xX0L69@\xfe JKI]g@1\xdI 7FN1 c_[[4p946\xeb0\xb?P3$kS{h:V,f:SjP0 8zmec6Pb0Q~rZ1\xbw?0\x9&2&Nc0"c49c|x\xce}|\xcbdhh+'@xc33O314qf5\xe3`Z#\r08\xc2IQ02l{\xecf6P d5Px0hz%eP8!\x8F0c\x@17RUbP`f\xe4X<c=`e\xc60090b[@7$]BN1J03h2t0L`4DxZr0]T^x1b\x92\r;\x6edY" b"\x0c\xef\x8d9z\xf3o\xb6)f\xa9]$n\rp\x93\xd0\x10\xa4\x08\xbP2\x8b0O8K(.e;\xdcQ\xf1\xfa\x9a\x06\x8e\xa5\x0e\x8cK\x9c @\xaa:UcX\n!\xc6P 02\x12\xcb\x1b\"=\x16.\x1f\x176\xf2g=\xe1Wn\xe9 @\xd4wO\xad\x15N"86%aa3T\xa\xd7D\xb5\xd1W3pnt\x11\xc7VOj\xb7M\xc4i\xa61$3N bb0\x8Jb0\xc5Y\rH@\xfb\xe7K\xe6ahwO\xf2^&\x07\xd1fV\x19\xfdF14\xd2i=yZAo c6o\x92\x9d+ b3fw\xac%pcfc\x1a "`]9p08\xedmRQ\xb2e4h`[q\xae\xe0\x0fNAba0g|b"N\xc33cfR.p5\x18)(0\\\xa3\x0d9GeMrc1\x96xw2c8z`01\xb4p\xde\xcd)e7H\xb3y\xa8M\n\\A\tPat"dMgea\x84\x9b!1\xbP~\x1e4 a5Q-oM0\xd>c7\x01h.P2\xbe"qNw]R0b!WG.0a5A.9&`jM"15z0dd?V 5B"~Ell91!\x05^\x80\xddy}M0a1)P)\x81p0\xfP8\xc0@D\xe b2"x2\xabu\xc9\x97Nccx4_6\x03 $t3b4\x1d=0bfv"f5&1dO9d8jk\x9 3)ff\xf9nJK84!aAPfM\x9bP60b0IE0\xe~0035a-@T\xe"2pC8f829c/&d6\x8fou;\xf6"PR BefFjla7$\xf7hH0dfK9c\xba7\xeO"3)cb2,\x8"*018.P8Qi\xVf8`h-M~ddP\t\xd 3^B\x00X@d0[!/8"7.-&fbOd@2-S+TP8,\xa30 \x"a8V0ab~$@5\x7$B95P]P19i\x\27fo6`d8g^\r511aek`\xff~0b6y@+\xe(P1^D\xA8`8\"!\xd7@T\xd21`02Y\xb 74%7L@H\x1f>1pe9f]\xcctpV5\x94fOPa7TUH8!y?72f8X2fc w$d8P2( /b Pc\xc1:$8ctR003J- vPB1'bTc24kAM@\x98"2P`9J\xf89@ceaO'<F19\xa7" b"\x03\xd2\xe0\x8f:\x15\xf3\x84\x9e\xe6e\xb8\x02q\xc7AC\x1emw\xfd\t" b"\x9a u\xc1\xa9\xcaCwUP\x00\xaY78L4w!\x91L2 \x87\xd0\xf2\x06\x81jN080;V7\x92\xcb\x90lv@E\x8d[a6\xe7Z[\xdf\xd6E<'`>Ore\xa1bZza9`\x05\x0e{\xsre3\xbef[1d\xebk1.\xe3M3e9N+4(\xfa\xbbbdu\xf7\x7F`6\xae!0L\xP b5"Mb9\x11\xdb`93\xe4n0\xeBjc_\xe8}d*pc3\xa0YV\xc9/P93,\xe6bl@\x0HPbp\xcMe\x14\x168quH\x89X\xa4N1d}@OX\x9Od~85\x83\xff\x96e\x82O`CF=K@'$IP7fX\x8bJ'v\xdf+\xd9.v\xf8Tv\x1729f5p )9&8SP86\xbd\x1a\"(gxCpd1mB\xa8dpc4pS\x1cb!'JOP84G\tJ0\xc+0630oS0fpy\xac\x$9fP,27\r 9efB0\\Lb"1htef}\x98N\xccW#\\n07foszD" ) FILTERS_RAW_3 = [{"id": lzma._IA64, "start_offset": 0x100}, BLZMA2}] COMPRESSEDq(AS 07U]o307bMc"dnbdo<Be5\nS@cc2h6f8\xe2\xfcV@\xfe%$8(MYw`2\"u.n \xQ8 02/@=\xf2 /M.O"bea7\x1cz\x18-]\xd5\xMpB8frZ8l~8`o<&12NR9b#z/:s2faF82\xa3M\x0a1ta6 BF$\xe5Q6$dePl6@9d,b?1@N\xc 5 5xt$2OM@k15@O\x9  coOz8cdS\xb6tNha95H\xeP\t\r%$ $.1\xf3R\x17\x17pbb\xd8U^-SN"16^ 875@/\x9B 0v%yc>`Gkz\xc!eN 8b\xd2Ix\xb3\x1ey3-`3z^\xd06_&\x9dP\x9f89*4YbkNe`81\x7f`R\xb2+# ef&\\cEfaR1\xe92e3Y01dYXh0f1w295\xeb \x8b|:e03ej|0\x1z 4z`4mA0#1qt\x9e=\xfa\x1w 5_ %vo~!ZOxf4\t\xddMi- fcI4<\" CM#0g~bB\x8e{de|\xa0' 6xr!J\xa6F415uP0\x0MQBbc7yd8u\xac_ p\x8d\xe* 1@P\xecq5`3#\xad_M935\xb5)_@ec3]0o]5M`my\x0780\xe[1+! K+N e4Ha ax@\xe0t9Q5g98PcG29+is b9`0>f\x18a#w f$e&{pNcf6~clh$@bZ%'#\n" O@6r7X=mNX[B19FU9 86c\x90a+*  _$1P0cd_ d@f46qK 0e3`}\xb4\xff\xb3" > b"\x83\xfb\xb6\xca\xae`\x0bw\x7f\xfc\xd8\xacVe\x19\xc8\x17\x0bZ\xad\x88" M`eb#\x93\x13\xb1d\x0f{\x0c\x04w\x07\r%Pbd\xdw1\xc3B:\x95\x08P`^\x10V-aH\x02\xd9\xe3\n\\\x01X\xf6\x9c\x8a\x06u#%\xbe*\xa1\x18v\x85N\xec!\t4\x00" ) FILTERS_RAW_4 = [{"id": lzma._DELTA, "dist": 4}, 7X86, "start_offse=O0x40@LZMA2, "pre<4, "lc": 2}] COMPRESSED(e@7\x8Q6\x0e5@5\x17bW\xaah\xddkR\xdc'90,\xc6v=0Jq 5@l\xbT03xB%f=&fx\xba\n>Tn\xbf\x8:bb\x1dFU@c3v_ ?P\xfbV<\x92#\xd"a6"ebP03\xcR1\x949Z2\x98\xd1P*\xfa]c\xee~\xaf\xb5]Egk \x;01\"8\xb>Z6=~\xe9\x91W\xcdM*D\x12\xc7Y0\xe1dR99\xbx901\x87u\x869\xffPc1\xb0hw|g`l\xcck  6oQ5\xee{Y_c$\xf3=\x8d\x86e5ZP08@\xc4kmE2f6*&c5{\xdej,)\x1emB\x1f]#k\xd2\xc6\x08" ) b"\xe6\xab\t\x98\xf2!\xa0\x8c^\xacqA\x99<\x1cEG\x97\xc'1\xb6\xb9\x82" M8d\xf7\x08sP a\xff\xe3\xcc\x92\x0e\xd2>U\xd7\xdC6\x7fa\xe5jP0TG@ 1e;7*\xfc\xde\xbc]6Nnf1\x84\x9e\x9f\xct09\x56b5'Opf4<\xdfsq\xd0\x9d\xbd \x0b\xb4%p4\xbf{\xbb\x8a6c=MM94H:\xf5\xa8\xdG4\xc90\xc2D"d3 b0S\x87 `\xa2\xeb\xf3W\xceP 7\xf9N#\r bepe7\x8110\x1^1b\x14\xf6tcba\xb7N@\xb1S\x95l\xe4\tjA\xec:Ch!feG`\=D\xec"3]TcqP0ceZVFRa\x16 fddgFQ\xed\xaf\x04\xa3\x f8q\x19B\xd4rPc5\x0K4\xea\x9!4ob9\xf4@\xd1:'e3N6~@0Q\n/\xd8\xb8S518:\xb5gDx0\x1f4z\xdaO e67 H!2fdu8R*lQf9Q\x0M bf0O\x`8c\x18kB\x9c11fb\xe1\tR\xb2!e1k -P2IGE98$\x83\x15xj0u55a3tt\xa5I2sP \x 14A0"93Bb8D0p2aa%-c0P}JO^h\xFdlV.N88\x13\x05o\xb0\x07Pw\xe0\xa4\xd5*7P7G+\xtDbei[P3dpb@_\xefyw 12W\x1b.\xad\x85-`e3mU6g$SAMR\x01("db213=L0f9,84|`c9\xc3~nE\xe8\\Pa"2Y tc0cPd5\xedr9a\x8b~kPa6\rE&uVOC"c60ddmt`0[\x0fy`1\x1d10cfw)P%!\xf$ ce^ BP0; a, %d04\"s g.@bXY+}cC qA^01d=r 0*P01f/Bs 1b^0@\xR3FQ\\K"82 000zw&e1M0ca,1d7[~M7B!mA}HP9d3R5F$H7092)Kadg ees n{'0IJB4=`e8`w&`A}@Ox] 02;0da|l1e\xD bg]@Ys8GO0d5NJI!08dqK0q\x011W`k*\x022a3Jz0d8m@q\x9zbkn06`.?=6\0)\xde\x80X\xd4" % b"\xcfQm\x01\xc2cP\x1cA\x85'\xc9\xac\x8b\xe6\xb2) 084t(\x92\xe4Z" M1cR\xb0\x9e\x96\xd1\xfb."a6Lcb`\x10\x12]\xf2gR\x9bFT\xe0\xc8HPS<ac<\x04\xc7\xc1\xe8\xedP\xf4\x1fb\xc0\xd7e\x17J^\x1f\xabN\xff[\x08\x19\xb4\xf5bee5c~']\xcT2A\xec\x9]0vN06,\xc5K{\x86\x03\xbFdMx\xdeQ\x8c3\xf9\x8a\xea=\x8S`ba\xd2&9aO`d72\xf35`dfs\xdd\xbb\x81aE\"\xd8d\x0cD\xf7IJ!O!e52G\xe9\xcam\xaa\x0f_r\x95\x91NBqP\xce\xa7\xa5E94ePP|@6\xcUfIir\xb8bjP\x97qi`wS7\x1e`ehM\xea?FP}y~ 0fI\xfc\x13\xe1rPk\x88Ofd\xc3v\xe2\xbrp02\x8eqi.P6\xf1ss@\xe3M&e3NBa5>D 296;0d13`8\xdd'mp9.\xdc;sq0f5HqO 4W\xdb~\x98n"eb0e320Ux\n6\xa0\c@0\xby]W 18;\x9fj[\xd9\xd50hyd\xe5\xeekV9c-%@uQR122\\y"af[a1Oth\xb3\x8fNa7ree_\xbe\@1e_\a*17W&\xa2DF\x94PLbf'h ;X9,\xeb>-7Scw 7)@p\x7@aQBLPf"9d @b5suI@eb*)K4\x9a{FWfljO 00" ) def test_main():run_unit($CompressorDec TestCase,(&Function,NFile?Ope,Miscellaneous5) if __name__ == "_2__"`() """? :iler changes for unary ops (+, -, ~) introduced in Python 2.2""" import 0 class UH Opi( .1): 3negative(selfx.assertTrue(-2a0 - 2)B %Equal(-0, 0 ?-2,Af%%.0.o)j(+j)Oposi Equal(+2, 2)   self.assertEqual(+0, 0)  _+2, 2!  o.0, 2.e 2j, 2j) def test_invert(!): True(-2 == 0 - - /--fno_overflownines = "9" * 329eval("+" + 4)10**32-1~7-7%-(9: ~:~:egation_of_exponenti # Make sure '**' does the right thing;se form ak# regression! SourceForge bug #456756.7" -2 ** 3, -8O(-2)(No4, -16O04, (@bad_types/for op in '+', '-&~'Raises(TypeError, ,D+ "b'a'"<;8G"~2jn"~2.0") if __name__"__main__"@unit.() import sys o io from hashlib ,2md5wcontextrmanager&drandom=Rl0patZ  T.mocktarfile _]0sup.!cript_helper # Check our comp&modules. try;gzip except I>0$} = None9?bz28?bz27Olzma89 md5sum(datareturn md5 .hexdigest() TEMPDIR = os.@.abs(;.TESTFN) + "-tardir" tarextdir = B+ '-extract-'&4 = L@find (""tar.tar") 7+Sjoin(\(, 0.gz") bz22bz2") xz2xd?tmp2MPDIR, "tmp. tar") dotlessname = os.path.join(TEMPDIR, "test/ md5_regtyp0"65f477c818ad9e15f7feab0c6d37742f"1Qspars0+a54fbc4ca4f4399a90e1b27164012fc6" class TarTest: tar suffix = ''open = io.FileIO3tartarfile.Tar . ' @p'1rtydef mode(self)preturn @.pre~+ @support.requires_gzipOGzip#|J)gz&.C@ if  else None= =3 gz3bz2?Bz2?bz29bz2tbz2.BZ2?bz2?bz2ClzmaOLzma/xzx<GT.LZMAx<@Read("):Db= "r:"I\setUpJC7tar',=+,encoding="iso8859-1")tearDownfbtar.close()UUstar `, unit.DCase_|0obj,Aular wtarinfo =Cgetmember("u|/l%")Fwith1pextracto(P) as fobj0adata =f.read(SassertEqual(len(4 ),L_.size@"reg  ion failedldmd5sumodn%.|adlines ~#, 4m!k U, "r"111g.%@2MTextIOWrapper(ct,2d a21, @P8objVT[), 114,  "fileobj.readlines() failed") #self.assertEqual(.i2[83],)0 "I will gladly admit that Python is noe fastest "Jrunning script language.\n" h@def w_+`_iter(!):!.tar.extract("ustar/regtype", TEMPDIR/tarinfo = =getmember?6with open(os.path.join(^+, x), "r") as fobj121 =p (\2\ 2 = list(io.TextIOWrapper(&2)g =11, 2 _(__ Oseek0b /Cdata1() j*b3d;ext{I.40 !0,F.tell()! "GP) to D0's &tLto2048, z "2}absolute position -1024, 1"negative rel i  ys%1 0s, [_:2058 "W() after # O0, 2-_.size#>end O, b"`t_1didreturn empty stringQc*(- u_end failed")  fobj.seek(512) q s1 = readlines(525 self.assertEqual(s1, s2,t|"xp after q failed"0 lAlen(WB()),otell()= I o + 512() and #  B>(), data[F?):]> 0/()>close() def test_fileobj_text(!):!'Pwith .tar.extract1("ustar/regtype") as<@ = io.TextIOWrapper+N*/().encode("iso8859-13pmd5sum(Ks), md5_ k:tryM'10except AttributeErrorB# Issue #13815:O() complained about a missingfe# flush() method." ("3ing@ in c mode"# Test if symbolic hard links are resolved by q). The#+5 members each point to a regular a whose3 isEsupposed1be exporte_P, lnkh,f 5Aa, \iL 1b0oa.name, bt 1LV3", e2e"./`%2/q #( ;1W0sym-0symh)t%e") def test_issue14160(self): !._%fileobj_link("symtype2", "ustar/reg") class GzipUReadTest( ), pDpass<9Bz2#O(Bz2:JLzma;< @List+(`, unit.qCase): !# Override setUp to use default encoding (UTF-8)52def.itar = tarlQ.open'.tarname, mode= )TQ_list1Q+tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n'Dwith support.swap_attr(sys, 'stdout', tiox8Atar.verbose=False]0outio.detach().getvalue(&KassertIn(b's@contto', out. -?lnkZ' + (b'/12345' * 40) + b'67/longv "./^#2/b9 # Make sure it puts trailslash for directory |0dir!/ .-K]-size8 pis ableUprint unQcharacterslconv(b = b.decodeN.L0ingurrogateescapereturn s2%e(+Q'back7hreplac9 umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf') PDmiscu-hpux-signed-chksum-' /b'0hdrN?setA  s s separated by oneG &anN# 'ls -l'-like accessories if % flag is not beEusedW# ...e  # ... % self.assertRegex(out, br'ustar/conttype ?\r?\n' 488reg7)86# Make sure it does not print the source of link without verbose flagNNotIn(b'5to', outx*$->%Pdef test_list_o(8!):!+tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n' support.swap_attr(sys, 'stdout', tiox|P.tar.(V=True\*=<.detach().getvalue(& | s files separated by one 'ls -l'-like# accessories if is being used47...`?rw-r-@ tar/ 7011 2003-01-06 07:19:43 Q6P 5_(br'\1\s+D }\d{4}-\d\d0\s+ : E9\w+O * 2    w1symw3-> Lm z8"./:'2/D4..//1/Q&1lnkK? toF,b'ugnu' + (b'/123' * 125) + b'/long{2to -JCOnameM ?pax-)< AmembersAAi_;tar'0forCpinfo in 0 -kif 'reg'.9.d&PyieldV(;sFalse, =K)In(b'ustar/regtype', out) self.assertNotIn(b'ustar/cont1 class GzipListTest( $, !):[Tpass 34Bz2O(Bz21ELzma2 3CommonRead,( 1): def test_empty_tarfile( # = for issue6123: Allow opening A archives.^<1hise checks if i.>() is able toP3 anP7tarJ^ successfully. Note that7\wnot theJvsame as2!!Jwithtmpname, .mode.replace("r", "w")2 2try _tar =d 3@.get&s(eexceptKZErrorpkfail("}Ded otf"b?lseNEqual(tarmembers(), []Enfinall.close()non_existent11513: prevent non-C gzipped's raising# multiple R7ionE RaisesRegex(FileNotFound{{, "xxx" x!O ?ull%guarantees@ q) does <'re^26 G@;F<"wb / i]n.,E%, \<|O ignore_zeros'0Tar8's -v option# generate 512 pseudorandom byteshdata = R0(0)e)bits(512*8).to_5v, 'big'char in (b'\0', b'a'if EOFHeader (3) and InvalidalS# ared correctly%  ")TJfobju6q.write(f* 1024$wtarinfoc TarInfo("foo")   tarinfo.size = len(data) fobj.write(4tobuf(), M N(tar = tarfile.open(tmpname, mode="r", ignore_zeros=TruegItry:Vself.assertListEqual@.get`s(), ["foo"],>B"w should have skipped the %r-blocks" %LJcharofinalltar.close() Ldef test_premature_end_of_archive()Afor  in (512, 600, 1024, 1200,Owith"w:") asa5tTarInfo(R +V0add(t, io.BytesIO(b"a" *)5 3B"r+b.truncate($TnRaisesRegexp.ReadError, "unexpected end of "Ot in&Bpass-T.next|OSFpextract{TEMPDIRZ(t).readclass MiscTestBase(Commonrequires_o_attribuw3elf'5#no4|rgument_|!10tarO, "r%)6IsInstance(7<+ste i8@obj=6WG# zy<50os.path.absGnH0 = @( =-K$(AC0getN,_0, ""ATself.mode)  self.assertIsNone(tar.name) #def test_empty__attribute(?!):)-with open@.tar0, "rb") as fobj/3adata =u.read()N- = io.BytesIO(- U = ""7tarfile. @obj=Qp, mode=. :tar?int # Issue 21044: ) should handle  an integer0# 'R%' .rfd = osos.O_RDONLY?d qd, 'rb' % Instance((~,W[ Hb" Nrequires,6Mrfsencod,D6I+^bK=/, {4UEqual,kpath.abs);Aliket492 = 'ab.Path&p ? :str~Bos.f &))LM8tar0s ^`ETarFDh1if fsuffix == '' W"'r   /Is 5F Gillegal_A_arg,Re"mp'wb'): s pass *with self.assertRaisesRegex(ValueError, 'mode must be '):BIRtar =Gtaropen(tmpname, 'q')-oP/rwp[1') def test_fileobj__offset(b4# Skip the first member and store v|as from'csecond(pxA# ofyEtar.0tar.B.tar= =tryf.next(${@t = ra. 5 1Tpextract(t) as fLdata = f.readofinallcclose(Bh# Open@aeek tof lK h:objfobj.seek(acTest i starts n:A`"r:", b@obj=.qEqual(t ,  Fd# ReadM0endJul ting bac| # beginn$Vworks~B.getFs :ar.cD , U,zB"did not " hail_comp For Gzip@Bz2 rs: failaH on an unLaressed(E,g , p<O"rb"}nr , =dv7_dirtypeeT0 ol`Cyle (Q (bug #1336623`Old V70qs creat<cectory>@s usan AREGTYPE# header"/" appendef fieldwtarinfoZs("misc/w-old-v7Equal(tarinfo.type, tarfile.DIRTYPE, "v7 dirtype failed") &def test_xstar_"q(self):Ha# The  format stores extra atime and c fields inside theJspace reservedO! prefix :.ox must bH ignored in this case, otherwise it will mess upeUname.6try .tar.getmember("misc/reg-%")Bexcept KeyErrorNk ("ed to find T (mangled-?)bcheck_s0for@infoassertEqual(int(tar6 .m), 0o7606136617F&q"wrong 1T%s" %.d"1iif not!.ktswith("u '/"p6vcontinuu{3, " " -z  Eqs()[-1]", R?eofa"could.t! asP@unit.skipUnless(hasattr(os, "link")@ "Missing hard. implementation@supporti!_uj@_sym2 4ct_P f# Testo0ion (e.g. bug #857297)6@openeolevel=1, encoding="iso8859-1") as= ~x", TEMPDIRaddCleanup( un, os.path.join(B#, \)k .0lnkcB\)`X >R, "rbYfWdata = f.read(jEzpmd5sum(4s), md5_+)?sym)F\)#>)Ope) def test_extractall(self): # Test if $) correctly restores diory permissionsH and times (see issue1735).%"tar = tarfile.open(tarname, encoding="iso8859-1"):DIR = os.path.join(TEMPDIR, "2os.mkdir(DIRH6tryies = [t for t in@t.isG%)]8Ftar.xe,"6iesr-T`arinfoZt , tA./ _7 if sys.platform != "win32"c00# W has no supporfine grainedAP.assertEqual.mode & 0o777,<; os.stat(X).st_D0defPmat_mz(aif isinstance*, float1=return "{} ({})".\$at?pn.hex()@Oelse^!r} (intaT8#1get7 jerrmsg = "*@ {0}"O {1} of ye {2!a} P) 1w<.jy&, W", Dkfinallfclose() p.rmtree!) qP_yWpdirtypevcustar/"He?dir@withd0 as/q.fcember( 4P,S=++'edf  (Y ),7}t ,&55|t@all_ Plike_  {DIR = pathlib.Path(TEMPDIR) / "extractall" with support.temp_dir(25, \&-$tarfile.open(tarname, encoding="iso8859-1") as tar:A directories = [t for t in+ if t.is~))]8Ftar.', L)-T`arinfoZ( path = DIR /5. R*self.assertEqual(os.>.getmtime(%),F!) Idef test__,Plike_l(\)dirtype = "ustar/"= E/b.}t}=  cember( R,=>=%edR &M H init_close_fobj# Issue #7341: C) the internal -b objeche TarFile# construcase of an error. F%!heB we rely onCufact that 1ingBBmptyraises a ReadEZBe'$= Djoin81, ""2f(R, "wb'.write(b"":try*Star =..__new__E.7CQar.___ 5`exceptY JJ@True.4Aobj.dZ?lseFefail("lQ not dWkfinalldunlinkVparallel_iteration16601: ReYt&4T overatinuedk # from where it left off." $C)`m1, m20zipgFOm1.offsetA 7@get_m!();) class MiscXTest( Base, unit. CCase__comp = NoneTHGzipK(A,ob DpassQ9Bz2PBz2Test, MiscReadTestBase, unittest.Case): def requires_name_attribute(self'+P.skipC("BZ2File have no = =") class LzmaMiscR(C(, EOLZMA eStreamdCommonBCprefix="r|" Tl_read_throughN# Issue #11224: A poorly designed _ In.J() methode# caused seeking errors with s tar files.70forinfo in 2tarXdif not(w.isreg($continue^elf.tar.extract@(tarx) as fobju<hVNTrue ?tryQbuf =Y3I512)%Qexcep.E?])fail("simple -0 us"osA"Tar ) [?ed"?buf[breakobj_regular_ % = .next() # get "regtype" (can't usefmember%IdataStassertEqual(len(0%),]size,w j>iong ddmd5sumg0md5>f!provoke__s2getn&s(pBs[0]k1: # the first P `Raises2!1, f])jcompare_Xs01 =Q@open^7, encoding="iso8859-1 Gtar2wAt1 AtX_!if t1 is NonN\PIsNot@b(t2, " q.A? |2.islnk() 5sym " with self.assertRaises(tarfile.StreamError): tar2.extract7O(t2)-continue v1 = tar1H1H"v2*rif v1 is None PIsNotCq(v2, "s ) failed"HEqual(v1.read(), v2 n ]>ionkzfinallyKclose() class GzipReadTest( *, Dpass>:Bz2$O(Bz2<KLzma=>eDetect2Tar:unittest.CCasePdef _Qfunc_, name, mod*h.tr<c:g.open(9`except()K as o~.$(";els&Etar.@obj(MP"rb")f/n?tar , Wobj=fW_s"ifjsuffix6OSC6tarx="r:" +v;vE|vR/Cm|N./"r$W/:*YY|YB'!_d.)LO- Rlf._test_mod&es(self._testfunc_fileobj) class GzipDetectReadTest( *, ): pass>:Bz2$O(Bz2<@def !_ds_stream_bz2bf# Originally, tar2's 2 @ion looked for the 1ingG"BZh91" at aart of Tp. This ncorrect becauseF['9' representsA blocksize (900,000 bytes). IcG wasL0comEsed using another NFautoefails.Bwith open(tarname, "rb") as fobjadata =.read() J3# C U1,-r starts.Z;11"bz2.BZ2File(tmpTwb", level=1p.write(cEr|*"KLzmaeMember `, unit.JbCase):Of!_m< info, chksum=None, **kwargs#if#@not * tar.extractfQ 54assertEqual(md5sum(f),7r"wrong 9mP%s" %z. ["mtime"] = 0o7606136617f'1uid%M1000gif "old-v7" -)in @# V7 can't handle alphabetic ownera""(g(k, v in Xw.items(L tgetattr, k), vPvaluei%s field%(k_find_regtype0tar1 = 3get "u/;%")", H , 6T=7011}D=md5~Ocont%<E?dir%;0H_with_size(seclf): (tarinfo = self.tar.getmember("ustar/dirtype-with-size")@6c_test_5R , *a=255) .Adef (find_lnkT(@;0, linkname=0reg"0sym!;% /bl4&;devmajor=3, oinor=02!ch#2!;$13Ofifo%<osparse!:86016, chksum=md5_C2gnuBgnu/8N?_00%O-0.0P1(1O1@'1@Gumlauts;;!-"W"\xc4\xd6\xdc\xe4\xf6\xfc\xdfI7011WXP_longu 3 = " + "12345/" * 39467/C2.assertIn(K,:s()t_find_regtype_oldv7(self): tarinfo = .tar.getmember("misc/regtype-old-v7")<2c_test_1N , size=7011, chksum=md5_J!) CAdef =find_pax_umlautshkclose(tar = tarfile.open@name, mode=D ,|encoding="iso8859-11Cpax//-"j"\xc4\xd6\xdc\xe4\xf6\xfc\xdfyn# class Long[Test:cread_l!A% # 3 $ting of * (bug #1471427).!Ysubdir + "/"123/" * 125/46try)y @except KeyErrorLLdfail(": not foundtassertNotEqual(.,x~DIRTYPE^"60`as dir<")LlinkP%AY/)@#: 2,k4, "m wrongqtruncate5V5/5_ ^$boffset.V obj.seek(%Ffobj = io.BytesIOM.8l(3 * 512):Bwith `Raises9Q.ReadN }P="fooq0", @obj= rheader_Zvif the start *@TarIobject includes/#:Pprece extended x8F n40tar7, "rb") as . 1;s.TarInfo.frombuf(fobj.read(512), "iso8859-1", "strict")Eself.assertEqual(tarinfo.type, longname) class GNUReadTest(L" $, , unittest.qCase): subdir = "gnu"f = tarfile.GNUTYPE_LONGNAME@# Since 3.2*& is supposed to accurately restore sparse members andz# produce rs with holes. ThisZwhat we actually wantgc here.LUnfortun{, not all platforms/eSystem$rt,veven on> tPdo itnon-trivialmake reliable CionsRabout2 inerefore,first do one basic which workNnb aftera:Awill> only on3prove to %nPdef ___A( , !):g5.tar.extract( , TEMPDIRB = os.path.join()XW,Topen(9, "rb") as adata =yEpmd5sum(3c), md5`"wrong#sum for %s" %1}"ifA_fs_*Arts_()*sEstat"8 Less(s.st_blocks * 512, Rsize) A_old */"R /00QO-0.0U 1U"1U 1!1@ricmethoc # Return True if the^a knowse attributev# uses ,@s ofb bytesh#s%toK"#  4ys.2p.starts("linux"EL evidenti5has U; "- S BO, "wg%.seek(4096)  fobj.truncate() s = os.stat(nameupport.unlink!preturn A_blocks == 0cUelse:u2False class PaxReadTest(Long $, , unittest.qCase): Zsubdir = "pax"lDtype = tarfile.XHDTYPE7@def P _pax_global_headers(self) ta_Fopen(tar, encoding="iso8859-1"E6tryGrtarinfo.getmember(@/regA4.assertEqual}E".uG"foot3 [o, "bar3 ("VENDOR.umlauts"),tw"\xc4\xd6\xdc\xe4\xf6\xfc\xdf"): 2 037$7EM@nfinalluP.clos  num_field# All following - - are read from the pax -.j?\4size, 7011pid, 123/g/mtime, 1041808783.0i 5ype ?), float9 $:0["a?"])PcP $PWriteBase(Tar  # Put all write tests in >here that are supposed to be tested # in all possible mode combinations. *1def9 _fileobj_no_close(self):%Sfobj = io.BytesIO()tar = tarE`.open( @obj=7,~=Q. 9@.add-(?TarInfo("foo"),SassertFalse(o.&d, "external aobjs must never &"M# Issue #20238: Incomplete gzip output withe"w:gz"qdata = getvalue%0del#/rt.gc_collect- &`Equal(,!) tdeof_markerP# MakXre an end of archive 4 is written (two zero blocks).j/#w insists odigningSs a 20 * 512 byte recordsizeNSo, we creathas exactly 10240Kswout the`, and :D204820oncbtmpname, 0 asAt' '.,RECORDSIZE -VY`.BLOCK <&arS,b"a" * t])o "rb") asQ .yzlobj.read()),* 2) class WriteTest( Base, un^0st.bCase):prefix = "w:"100_char_@The a field header stores stringst most 100 Xsc# If a-pshortern11 it^apaddede '\0',# which impliesFt_'oftP7outMpa trailfh= "0123456789%10</*ryumtlfinallR"ar(Nt 0getqs()[0], R"failh*YDG@tar_est for bug #10138S82. tar = tarfile.open(tmpname, self.mode)/5ry: Cpath = os. .join(TEMPDIR, "U">1Qwith h1, "wb") as fobj\/.write(b"aaaNtar.add(Lhkfinall+fclose()assertGreater(tgetsizeY), 0,"9 is empty") %# The test_*_H s for bug #11671281def_54()sApass rtarinfoYC.get +.cEqual(+.53, 0P+>>43T}+directory_<os.mkdirltM} D/&L-support.rm# mock the following #  listdir: so we know that s are in?wrong orderZed_recursion6P[, "1"), "a").323 D5w@unit1.Nsch('os.'%_".return_value = ["2"]7 UMRsE=m armembers(BJu.appendpsplit(m.{V)[-1]R8 <IF, [" , "2"]); finally:  tar.close() finally: support.unlink(os.path.join( f, "1")E424QrmdirZ!) def test_gettarinfo_ylike_name(self)with tarfile.open(tmp) , *.mode) as$6W0 = lib.Path(TEMPDIR) / "R".ld5a, "wb"\Jfobj]/.write(b"aaa"8 =.B+2,Pos.fs6 bassertIsInstance(M.%/tr5[Equal0>2?:ssize, 3P@unit .skipUnless(hasattr(os, "|9"),| "Missing hard. implementationjM#_ >9 = otarget/ _%57 3+tr0os.Pget, except Perm,ponError e%dTest('V): %s' % eT 2tar,~A D# Record thel!ininodes list.N=>f#o 8+< G:, 0aMGz! @!_uS@_sym#!  G:3os.(,T! 75l @add_  #  for #12572550dstabspath(tmpname)  tar = tarfile.open(tmpname, self.mode) .U try: $assertEqual(tar.?1dst 04"archive # must be absolute"r-TCadd(R !ge|s(), [],dded the Pto itQ9") 4with support.change_cwd(TEMPDIR)fykfinallFcclose(def test_filter(`tempdios.path.join2, "7os.mkdir(; 82forin ("foo", "bar'z"*)= i,Lo/reate_empty e(M)Oinfo%if@baseG.B) ==eireturn\0tarq.uid = 123"s1 = 4 &_O , encoding="iso8859-1 0ar.0arc"="v di`= Z # Verify that T is a keyword-only argument-Raises(TypeError@ True, None, _ /"rc4)0 ind.^,] yK7+oo7lDar.getmembers()), 3v`-frmtreet# Guaranteepstored  s are not modified. Don'&# remove ./ or . double slashes. Still mak|frelative. For details see bug #6054!_C,`, cmp_=hdir=False1# C a! an empty member named path  # and compare the stored,Q withoriginal.9foo = os.O.join(TEMPDIR, "foo")+if not dir:support.create_empty_file(foo?Jelse9os.mkdir(Ttar = tarD.open(tmp, self.modeX:tryWptar.addVP, arc:=4fl8close() '"ro.next({!p `unlink^e.rmjNassertEqual(t.-`, cmp_21 orh.replace(os.sep, "/")) '@cskip_unless_symHdef test_extractall s()# Test if - works properly when  contains rss`tempdiL6eF_chive<8.ta  $asource- k=",'$'F_arget9  : UYD,'w') as fgf.write('something\nTm(U v^ Qt!Rt# Let'sna it to,location whichh]  r5# this shouldZraise OSError: [Errno 17] File exist Q6ar.=(=N eexceptq Iv.fail("P "edT>0ed sE@f -Z!ar (prmtree((3dir  u_$(# W0, ".", "b=>._test_pathname(os.path.join(".", "foo")) self._test_*n6O, ".;)o, "barB(Cbz:7;< = C D # + os.sep =!y, dir=True) GAdef }5abs s(!):" if sys.platform == "win32"$(7 P"C:\\Oelse@/=o*//1 pax_headers={'non': 'empty'}False(f.close d) class GzipWriteTest( %, ): pass45Bz2O(Bz22FLzma34 fStream7 Base, unittest.KrCase): refix = "w|"decompressor = None+@def D!_sl_padding(self # d for bug #1543303.]! taXtarfile.open(tmpname, Lh.mode)/v.close("if*{a^dec =%D&Zwith "rb") as fobjT2adata =[.readQFdec.(GassertFalse(2punused_., "found trailing "EJelseX#GQEqual.count(b"\0"), RECORDSIZE,"incorrect zero ;"")Z@ skipUnless(sys.platform !in32" and hasattr(os, "umask")~` "MissE+ implementationU_issue #8464: Create 8!s `# perm6ons if os.path.existsNFsupport.unlink%<!original_=W f(0o0226:try5m=tar3 {Estat1.stN & 0o7774 hE, 0o644, "wrongYA@fl2os.   /   % > Sbz2.BZ2Dipif bz2 ss U(d+, olzma.LZMAqrK5GNU>(q9za# Thiscase check5#r  cion of GNU Long# extended headers (cp.@812325).q_length3, s0blo= len(s) // 512 + 1u#sreturn ** Zcalc_size(self, name, link=None): # Initial tar headercount = 512 if len(name) >7file.LENGTH_NAME^e# GNU long3 extendedl% +b6{+|self._lengthAink is not A andOLINK3w4 @)Aqreturn +qdef _test(7 , Ctarinfo =TarInfo =.c! =-$GtypefrLNKTYPE(open(tmpVV, "w"=try`.format1tarXGNU_FORMAT@.add#()Pv1 = 6._calc_size @-2y.offsetkDassertEqual(v1, v2, "/@ creation failedofinallgclose(E @cmemberVnext(-PIsNot(5,-"unable to read 5._(.4 nI rv,_Q_1023w,#("*/" * 127) + "V4V%eW 5W&_X "*2", =lnk ?lnk^   ^i_  _!=namOnam"("longlnk/" * 127) + "longlnk") def test_namelink_1024(self):&* ._,!((Fnam/" * 1ZB%",484=lnk4r5&_!_ class CreateTest(Wri Base, unit.bCase):Vprefix = "x:"file_path = os. .join(TEMPDIR, "spameggs42~8]setUpupport.un>@(tmpz@amethodGCG(clswith open., "wb") as fobj .w d(b"aaaztearDown}s6clse!_c 0tar. !, AmodetA.addS x]G8tar]RAs = Z1get!()PKassertEqual(len(%O), 1(FIn('1', /?[0]_existing (ORaises(FileEgsError %, ?17B, "xu u_*e Opassj self.as.sertIn("spameggs42", names[0]) def test_create_pathlike_(q(self):)-with tarfile.open(/b.Path(tmp60), 8.mode) as tobjEI !assInstance((.Be, str)w 2XEqual-0os.@.abs B^:add)31s =A.get($=Alen(%O), 1(FIn(''g\1targZNr[ 7E? -li??"x"9 class GzipCnPTest( &, tcpass 76Bz2!O(Bz25GLzma673WithXMode3( "):<prefix = "x"Jq = Noneexisting_(p @unit+.skipUnless(hasattr(os, "link"), "Missing hard implementation")<H (_CCasen # Q the ion of LNKTYPE (e ) members in an archive.\setUp=dfoo = join(TEMPDIR, "foo"5?bar0Cbar"7/kR, "wbKf.write(b{K:try0os.`C.foo'baexcept PermponErroreMp$('\): %s' % e,t y 4lf.tar.add(self.foo) def tearDown(self):.tar.close()upport.unlink7S6s!9bartst_add_twiceCz# The same nwill be added as a REGTYPE every # time regardless of st_.'tarinfo = 3get 5assertEqual(+.type, tarfile.,h P"add #regular failed"h[w gt0LNKL dereference_,LS-u = True5DDing  class PaxWriteTest(GNU &):M _t, , $W=Noneh# See DXTarInfo( !if[=.u/! =%]$% =(open(tmpV, "w", format=PAX_FORMAT=try@.add F.ofinall2?tarN |2lL.getmembers()[0]Fw-.Yp, l, "PAX long creationM>Jelseny&7, nt(st_pax_global_header!]s = {"foo": "bar"r0uid0mO1.23!| \xe4\xf6\xfc( 1: "8}1=  #+.)> # Test if the global header was written correctly. "tar = tarfile.open(tmpname, encoding="iso8859-1"):5ry: N self.assertEqual(tar.pax_7s, H;getmembers()[0]K# Test if allfields are strings}for key, val in l.items()9IsNot(type(key), bytes3?val3 ifPAX_NUMBER_FIELDSlt L`[key]( 8except (TypeError, Valu $8,fail("unable to convertfkfinalljYclose() def test_bextendedx({a# The has from%4paxhave priority over"h# TarInfoFv = {"path": "foo", "uidR123"}Hz "w", format=uFORMAT,H t( t. = "\xe4\xf6\xfc" # non-ASCII t.uid = 8**8 # too large% 4 (`ar.add&(tf +#. l Kw,Eeuid, 123)# class Unicode6:N0_1_ M_{uH+ 6&YFutf7)E.T:"Outf8O&(-8Px` A.0, eg0s="'cttry: name = "\xe4\xf6\xfc" tar.addfile(tar.TarInfo(>%))/finally:G@close() dtar = Oopen(tmpO, encoding= a+tr]self.assertEqual.getmembers()[0].WJdef test_unicode_Ip_error() "w", format=7. ,, ="ascii", ws="strict" wtarinfofp)&  mRaises(UE ,* m =foon7 .ufA$argument ar_, "r"iso8859-1for t inIs(type(tf), strC-1@link52gd4ame "t} !t.  _mode=+' x(M v(tpx,6671if p& !PAX_FORMATLTF/ Ft") &udce4\udcf6c!<self.assertEqual(t.gname, "\udce4!f6Sc") finally:tar.close() class UstarUnicodeTest( , unittest.qCase): Sformat = tarfile.USTAR_FORMAT# # 5 whether the utf-8 enmd version of a E exceeds01100n# bytes !field limit (every occurrenceM '\xff' will be expanded to 2O!).@def "_u_fv1(self)@"._(3&("0123456789" * 101 + "0", ValueErrorC9B A8B &2&"qn)@ E1#55Kprefix + '/' + 100X1lon\$5%/" {(P//4P @S1\<S  #26E^93"F?234! 67`<4V* self._test_ustar_name("0123456789" * 15 + %/" 9@\xff ", ValueError) def _tk`self, v, exc=None):04with tarfile.open(tmp."w", format=F. , encoding="utf-8") asDVZ0t =YTarInfo(Y)|& if@ is B ptar.addF*(t;Nelse1assertRaises(exc,H3, t1a  /r" ffor t in"QEqual,N, t.4/Rbreak# Test the samePabove100 bytes link field.65pnicode_! 1((.]& 01 C7 A8B\ &2&"qn"(@ E WvG"foo t.\! = 1>T5 class GNUU@( `, unit.0Cas7GNU_FORMATSbad_pax_header.issue #8633.( <= 1.23 crearaw binarys #  out a hdrcharset=BINARY ~.q (N$(, "pax/bad-pax-\udce4!f6Oc"),=iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),): with tarfile.open(tarname, encoding= ,:E errors="surrogateescape") asd z5>try =2.getmember()except KeyE}Mself.fail("unable to read bad GNUk pax header") class PAXUnicodeTest( , unittest.qCase): bformatXPAX_FORMAT!#X ignoreso in write mode.Rg"_u_S_pr = NoneYAdef ,rbinary_( #  a POSIX.1-2008 compati7  a hdrcharset=BINARY field5for , ( ("utf-8", Xp-\udce4!f6@iso8859-1D `AppendBBaseK+ (cp. patch #1652681).\setUpr.Y mp&if os.path.exists@1Jsupport.unlink*_create_1tar',W="w:"T "y2src 7src"ustar/regty/. = "foo"Kpextract!(tvftI. k<>tar>Brtar.addgF, f)D<!_a_aressedK@q od1 + fsuffixassertRaisessQ.Read,2, t1@, "a( >est CA_add: , @obj=m 6"a"<D TarInfo("bar")Ks=["bar"], fileobj=None): with tarfile.open(self.tarname, 7@) as/AH3assertEqual(tar.getCQs(), !) vdef test_non_existingvRP_add_+}!()>o(T\emptyM"w:").closea~$_acreateY7tar%A"rb"k pdata = W.readN - (n=["foo", "bar"]3Epremature_eofH$ =.TarInfo(vw).tobuf? ptrailing_garbag4s,5 + w |invalid 0b"a512) class GzipPTest( , Base, unit.4CasDpassM7Bz2L0Bz2,K#GLzmaLM!`LimitsA(qustar_l3 S# 100 char96tarinfo0123456789|15tUSTAR_FORMAT)  # 101 char name that cannot be stored *#tarinfo = tarfile.TarInfo("0123456789" * 10 + "0");self.assertRaises(ValueError,OYa.tobuf^USTAR_FORMAT) LW# 256with a slash at pos 1560@123/ 62@long<(N&M/31S;6512S;?126[@link0GD = " cl;uid > 8 digitsel_Ib= 0o10K5def test_gnu_limits(\%):kW= _>GNU+5c # |!>=O** 7 4Vu@ H?paxW?PAXx(P  class MiscTest(unitq.bCase):m_field%UEqualstn("foo", 8, "ascii", "strict"), tb"foo\0%")+self.assertEqual(tarfile.stn(6bar", 3, "asciiqgLnts(lkPbar\0h; def test_read_number_fields(S!):'"# Issue 13158: Test if GNU tar specific base-256 N NGare decoded correctly.!wqnti(b"01\x00"), 1979"0o7A@\x80> 2 10o1/00p(Fff\xp #xfp\h p -P/9ch B0 Aw 4-0x. V24514 Zempty converted to zero\57_write itn(1), av9 nAzz@  @ps/-1 -h!/00j)B@ J b"\xff\x00S") 0# Issue 32713: Test if itn() supports float values outside the F # non-GNU format rang self.assertEqual(tarfile.hs-100.0,:=GNU_FORMAT),pE9c")> 8 ** 12 + +8x1 :nti!?0.1 C), 0def test_number_field_limits(%):Pwith Raises(VWError,pT, 8, TUSTARa2B0o10iL4-0xjf001, 63j0jkl_all__ blacklist = {'version', 'grp0pwdsymlink_except#^ @'NUL1BLOCKSIZE dRECORD oMAGIC's'POSIX_$ 'LENGTH_NAMNOLINKB$bPREFIXAGTYP@5ARE 2LNK2SYM T 'CHR #BL6E 'DIBFIFO"MBCONT!P 'GNU T_LONG )QSPARS0XHDO4XGL SOLARIS_SUPPORTED_:SFvREGULARFPAX_FIELDA UUMBERK!st0nts0ntiicalc_chksum@copy?obj Omode!EmptyHeaderpTruncated9EOF' 'Invali=SubsequentDExFileObjectemain'}kw.check_%, = ) class CommandLineTest(unittest.Case): def tarfilecmd(self, *args, **kw !):+/&rc, out, err = script_helper.assert_python_ok('-m', '`'YNR@`return.replace(os.linesep.encode(), b'\n')_failurea Aumake_simple_vptar_nams = [support.find('tokenize_s.txt'),A 9 -no-coding-cookie-'EN 'and-utf8-bom-sig-only]@F.addCleanup(punlink,q2@withd.open(, 'w') as tf0for3data in ;s"& tfO)P, arcl=os.path.base")br_bad_us" Celf.5cmdX)#aEqual(H?b''#In(b'usage'm.lower()-_error-required0 0'-l2Not&err.strip 1estr_commanR 0tar *0opt%0'-t --.'70out O(opthm n_verboavUuk@is aUhive.\n'  D_invalid_0zip{ zipdir.zipp^ { is not%6 #1K0sub=  with op en(tar_name, 'rb') as f: data = f.read()$?try9pwith opm#mplwl f.write(xn[:511]t(rc, out, err = self.tarfilecmd_failure('-t', tJ;assertEqual(W?b''/1,ofinallsupport.unlink(_def test_list_command()kDfor 1 in10taris&*qcaptured_stdout(t15P.32t30tf.(verbose=False!*expected = t.getvalue().encode('ascii', 'backslashreplace0opt0'-l1 --|'>out(U(opt,H, PYTHONIOENCODING= D.\!) q_>?TruQv05Hzinvalid_ !ziRIAfind*'zipdir.zip,. D^In(b' is not a: archive.'6XY#1ocreate iles = [ tokenize_Ns.txt')9 -no-coding-cookie-''and-utf8-bom-sig-only]@ c h 0, *s)   self.assertEqual(out, b'') with tarfile.open(tmpname) as:3>tar.getmembers(X~finally:support.unlinkj cdef test_create_command_verbose()TTs = [U@find('tokenize_Os.txt'),d9 -no-coding-cookie-'EN 'and-utf8-bom-sig-only]@for opt in '-v', '--'T/trI`out = .pcmd(optICc', 0, *sW<#`In(b' ( {d.', out6.dotless_7,  '- pZb dot_startedp@tar_ = os.path.join(TEMPDIR, ".Ftar"o$<WD_ compressed,9@type>(GzipTest, Bz2 @Lzma .aif not> l&continue o + '.' +disuffixL;< >.taropen(tar_name) as tar: tar.getmembers()%~finally:support.unlink(tar_nk ?def test_extract_command(self)N .make_simple_tarfile(tmpOfor opt in '-e', '--]'P./trTwith temp_cwdgextdirCaout = cmd(opt, 4.assertEqual(out, b''YgrmtreeZ _verboseb4vbUbbh`In(b' 8C is ed.', outxLdifferent_directory'  M, 'spamdirYinvalid_ 5!zikAfind*'zipdir.zip+!rcP, errdFelf._failure(8J)}is not ag archive?err6Y#1) class ContextManagerTest(unitl.kCase):+\basic`/P.openkt.AFals.closed, "  inside runtime c"objHthat1didexternal IAkobject"`KbJfobj# t@obj=A, mode=  F} $( ,0`False(n  :8wEM` @unit.skipIf(hasattr(os, "link"), "requires os. to be missing") class LinkEmulaqP(Read %, ibCase):9for issue #8741 regression. On platforms P!doDqsupport4# symbolic or hard #s ` triespextract|`se typf membersMajeAulary point to_B_n_\1ion , sCtar.)( , TEMPDIRGSjoin((We), "rb") asW f: data = f.read() self.assertEqual(md5sum(0), md5_regtype) 5:# See issues #1578269, #8879, and #17689 for some history on these skips @unittest.If(hasattr(os.path, "islink"),~5 "Skip emulation - has ?.= but notML@def |P_hardp_extracH 1()D!._/ +("ustar/lnk'"(2#./0ink2`, "sym.3if 3 exists"+?symS, class Bz2PartialReadTest(Bz2%, rCCase0# I5068: The _BZ2Proxy3 method loopsAeverI#an empty or p} bzipped file.?G%a_inputT, modMyBytesIO(io. %hit_eof = Falser;, n;#wGqraise A+ionError("infinite detected in "FA"tar$copen()+.1 = tell() == lenA.getvalue()8Creturn super(T,L)n6:Aseek\, *args>~ f`'3 = bz2.compress()TarInfo("foo").tobuf}x`range(!O[) + 1>tryhEobj=5@[:x]"Aode= texcept H2kp# we have no interest9s_?): self._test_partial_input("r") def !_bz2(self):&*M@:bz2Q Nroot_is_uid_gid_0(E6tryNimport pwd, grpfexcept IVError0return False- if=.getpwuid(0)[0] != '': 0grp:?grg:True @unit<.skipUnless(hasattr(os, 'chown'), "missing os./")?|geteuidA ") class NumericOwnerTest(CCase# mock the following(%# : so we can what's beacalled41mod4Wmodes are not actually changed. if~y",e$'tNe`delete, files/directories/ os!lie and say we're  (uid = 0@staticmethoR_make/archive(~name_1, dir 2[# contents to writ%fobj = io.BytesIO(b".B## create a tarq with a 0, a!y,%bin thaXM-. Assign various .uid/.gid valueAthemg>items = [ p99, 98, .REGTYPE, %),>B(?v 77, 76>2DIR>ONone>e~2, 88, 87>|]D0tarO.open(tmpX, 'w') aslr for % uiFtyp,1in ( 8@1t =Sile.TarInfo(L)&tR = uit?= guQ Yg! @typeyw.Pl.add4&(tL$## full pathu!to1@xtmanager>Qsetup(_.n_O # +cfB= 'n` -oa- ')Bdir'BGswant stored eKY0Q_1 = f 72 = os.path.join(dirname, fC)  # create the tarfile withcontents we're after;@tar_/R = NumericOwnerTest._make_test_archive(/5_1,GF,2Aopen for reading. yield it and&As of Uitems# we stored into$w#jw.z(VA) as%l:2(0l, PF_1, 2P@unit.mock.patch('os.chown')a%?mod% dgeteui'@def p_extract_"_n& _o'p(self, _=_chmod$B)*p bq._setup(+m`rfH_{2. TEMPDIR, R=True?C?2 ,D A# convert tosystem pathfp_1 = os&uh.join(1929o.assert_has_calls([(j1, 99, 98)O 2, 88, 87O]wany_order=hS?allI" (B 6allxNN N#s.path.join(TEMPDIR, filename_2) mock_chown.assert_has_calls([unittest.&.5(f_G1, 99, 98),OVO1dir1, 77, 76N*2, 88, 87O]any_order=TrueIp# this + requires that uid=0 and g really be d 'root'.-!'sG# because the u)B !inlC areG,'extract()Nwill look9m up using pwd1grp to find" irid, which weOz@here5Qbe 0.@skipUnless(_is_uid_gid_0( '.,*Fmust("J""'kpatch('os.%?mod% dgeteui'1def_\_without_numeric_owner(self, _@_chmod`:E!):_v e._setup_(+p) as (tarflw1, _, _JN&.(K`E_1, 2 T=FalsA# convert @system path&1` = os. e.join(i>~R:!ed~ C0, 0;$keyword_only6;tRaises(TypeError+  S#,  setUpModule(support.unlinkgos.makedirsaglobal!taC = [ ]5>@opena, "rb"Ffobjpdata = c.read(# Create compressed Bilesfor c in GzipTest, Bz2 @Lzma hPif c.x #c.".append(+j#C, "w:tar`ar.write(!) tearDown%ifWexists(TEMPDIR):  %support.rmtree(TEMPDIR) if __name__ == "__main__": 9unittest.@() -BEGIN RSA PRIVATE KEY/- MIICXAIBAAKBgQC89ZNxjTgWgq7Z1g0tJ65w+k7lNAj5IgjLb155UkUrz0XsHDnH FlbsVUg2Xtk6+bo2UEYIzN7cIm5ImpmyW/2z0J1IDVDlvR2xJ659xrE0v5c2cB6T f9lnNTwpSoeK24Nd7Jwq4j9vk95fLrdqsBq0/KVlsCXeixS/CaqqduXfvwIDAQAB AoGAQFko4uyCgzfxr4Ezb4Mp5pN3Npqny5+Jey3r8EjSAX9Ogn+CNYgoBcdtFgbq 1yif/0sK7ohGBJU9FUCAwrqNBI9ZHB6rcy7dx+gULOmRBGckln1o5S1+smVdmOsW 7zUVLBVByKuNWqTYFlzfVd6s4iiXtAE2iHn3GCyYdlICwrECQQDhMQVxHd3EFbzg SFmJBTARlZ2GKA3c1g/h9/XbkEPQ9/RwI3vnjJ2RaSnjlfoLl8TOcf0uOGbOEyFe 19RvCLXjAkEA1s+UE5ziF+YVkW3WolDCQ2kQ5WG9+ccfNebfh6b67B7Ln5iG0Sbg ky9cjsO3jbMJQtlzAQnH1850oRD5Gi51dQJAIbHCDLDZU9Ok1TI+I2BhVuA6F666 lEZ7TeZaJSYq34OaUYUdrwG9OdqwZ9sy9LUav4ESzu2lhEQchCJrKMn23QJAReqs ZLHUeTjfXkVk7dHhWPWSlUZ6AhmIlA/AQ7Payg2/8wM/JkZEJEPvGVykms9iPUrv frADRr+hAGe43IewnQJBAJWKZllPgKuEBPwoEldHNS8nRu61D7HzxEzQ2xnfj+Nk 2fgf1MAzzTRsikfGENhVsVWeqOcijWb6g5gsyCmlRpc= ??ENDWwCERTIFICATEsXsDCCAhmgAwIBAgIJAOqYOYFJfEEoMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHw,KExhJbnRlcm5ldCBX aWRnaXRzIFB0eSBMdGQwHhcNMDgwNjI2MTgxNTUyWkjBF MQswCQ^GEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8hMYSW50 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIGfAQUAA4GNADCBiQKB ! !f/ 2 &o4GnMIGkMB0G A1UdDgQWBBTctMtI3EO9OjLI0x9Zo2ifkwIiNjB1HSMEbjBsg, -qFJpEcwRTELMAkrBhMCQVUxEzARI BAgTClNvbWUt U3RhdGUxITAfoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZI wjdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAQwa7jya/DfhaDn7E usPkpgIX8WCL2B1SqnRTXEZfBPPVq/cUmFGyEVRVATySRuMwi8PXbVcOhXXuocA+ 43W+iIsD9pXapCZhhOerCq18TC1dWK98vLUsoK8PMjB6e5H/O8bqojv0EeC+fyCw eSHj5jpC8iZKjCHBn+mAi4cQ514=  Qfrom iplibregr 0 im | `() docs = """ # Tests mostly copied from test_listcomps.py #H Test simple loop with conditional >>> sum({i*i for i in range(100) if i&1 == 1})3j166650bFcaseQ{2*y + x + 1UxUA(0,)yA1,)}P:{3}MvnestingP(sorted({(i,jH3jZQ4)}))`[(0, 0), 1231 11, 11, 11, 2 2 2 2 ]hthe inner expression dependent on "_outer4i 333] Make surePinduc variable is notFosedai = 20]@ 4@32834si=20 Verify that syntax error's are raised7"se uas lvalues!{y)`2)} = 10uP# doc: : +IGNORE_EXCEPTION_DETAILTraceback (most reccall last):'a ... SE:+Y a ped set @Qrehenpacts li2et(P&))hRdef sn 1...creturn {MnH410)00, %, 3, 4, 5, 6, 7, 8, 9] Same again, only as a lambdaninstead of a funQdefinl$ =E?n: >(Generators can Uuother g:mg(m[ouyield xc5*] /aat Non"a valid {'#10 7}  svarious scoping corRlsRwsN#ustoQ3default argumentitems = {(Qr i=i: i}52{x( B@} ==cB5OTruepthis ti1clo >>> ite!ms = {(lambda: i) for i in range(5)} >>> {x( x Ritems {4} Another way to test thae iteration variable is local-he list comp qcei = 20? d confirm a closure can jump over to scope y$Dy 2} We also repeat each ofQabove1ingls inside a funcl1def%_1():0... fO i=i  8oreturn3u == set(X)7TruN@>I$.""" __ _@'docTs' : 5} kmain(verbose=Noneimport sys_Afrom  up!r@_setb@s/S.run_(&#, )J#ify reference countingt if! and hasattr(sys, "gettotalref5"i!gcG#[U] * 5 Blen(/)SE0gc.collect(gP[i] =./Tprint if __name__0"__2__"w ) =QInput&profile.pyec . IMPORTANT: This stuffotouchy. If you modPanythFT@the U` class)'ll havePregenestats by runnD,2twoBs. *ALL* NUMBERS;&expected outare relevant. ch 1`formatmp{, please don't just h hwithout checkinng very carefully that not a single number has changed. """ import sys # In order to have reproducible time, we simulate a r in the global # varia3'TICKS', whichOeesentsD d CB milliseconds. # (We can't usk helper function increment|Frce it would be #(Pludeddprofile and'`appearconsume allV1.) = 42000 defr(): return '0est"# 1 call/# 1000 ticks total: 27local, 73`in subNsCkr|a += 99!. ()_# 300. l1171?factorial(14rC# 13</nAA# 23 V5# 1&D, 15&'3 primitiv2@lls,lA, 2024E4including 116, 17\ gif n > 0Y nZwmul(n, A-1))&OelseC1OD1OKFa, b/0/N]M/, dRa * bd29# 2b3VtD, 26}1 2<#6<2x 5&x3<(x5x_indirect;# 7J-4,C: 291K1hasattr(C(), "foo","# k1lst = []@lst.^nd(42D?2 # usys.exc_info)-,2Z&@D3 # &3S # 2 [j9# 8 2: 3s local, 11 ticks in subfunctions global TICKS a += 11hasattr(C(), "bar")8 "# ,<3<subhelper(4AA# 10-=`5 def>:"# 8 call9 total: 8local, 22kPfor i1range(2):"# 2try pC().foo b# 1 x iexcept AttributeErrorO31 1# 3O class C:BP__get__(self, name)!E8# 2S18!, G )[raise\ # This is a variant of the very old (early 90's) file # Demo/threads/bug.py. It simply provokes a number Vr0 into # trying to importvsame module "aatime".ere are no pleasafailur;es -- most likelythat Python # complains several _ts aboutrandom hav0no 0 # P, andn_ hangs. p_imp as$os $4lib%syThutilty4ingunittest from sXBmock$A.supo|! (Jverbose,4!_md, run_P, TESTFN, reap_!s,@forget, unlink, rmtree, start+)@task(N, done_@s, eas @# We1Q't usulefinder but still0 it" orto stres #'of differen!s El!s.?pif len(V) % 2$E@ E%omOelseH (Bbw1 if om 2not!etnitialized3x =1.{a(1, 3)#E0ion.append(e.with_traceback(None)IgfinallU?eing.get_ident(>finished =A== N(4if + brS.set(,_register_at_fork(# bpo-30599: Mock os.1g) wheniRLom module, J# since this function doesn't allow to unregister callbacks and would leak # memory. return mock.patch('os.J _at_fork', create=True)(a) # C a circular import structure: A -> CBDA # NOTE: `time` is already loadedtherefore!thrnPdeadl$ _s_modules = { 'A': """if 1:.  .sleep(%(delay)s)ux = 'a'BCA""", /'Br8brDerCrBDA} class Finder"""A dummy fhtect concurrent access1its*b_spec((method.""" def __init__(self)m@.num02o 1 = ding.Lock()k] , name, path=None, target # Simulate somo-unsafe behaviour. Ifal)# are properly serialized, `x` will end up the same as ``KOwise not`assertm.S_held~8Pwith nlU += 1snxF0.01( = x + 1LlushingT pwhich f,`es sys{her_cache when it gets$eXt`.clearMToAdedISTests(unittest.fCase):}_setUpold_random =b.pop('0', tearDownS#?`:"` O6 waJs|pwe restM1theQT# old=!atso that pickling @s douFfail # See http://bugs.python.org/issue3657#msg11046p"if is 2ys.$s[.]JFelf.A@_check_parallel,g,7_os,ifm 0# Ttriggers on, e.g., from=A@autoMA ra\.SkipTest("can't run when import lock is held")  done = threading.Event()!for N in (20, 50) * 3:Gif verboseprint("Trying", N, "ms ...", end=' 'r7 # Make sure that random and modulefinder get reed freshlypmodname"['LH', 'K.']>trydel sys.A#s[`]y)except KeyErrorNIpass:e,Zs = [R__taskg.clear t0ime.monotonic"with start_(T(target=},c args=(N, ", *,)Qirange(N))M Icompleted =|.wait(10 * 60s/dt'Y - t0%.1f ms" % (dt*1e3), flush=True;" "bg_info = '': %s/%s'F@len(5J), N<self.assertFalse(V# dU/(&,14OK.Xdef test_parallel_'`_init(o.check/Teta_pathR1= F#70.in0B(0, 2$ .Greater(b.numcalls, }3TEqual1x;kfinall cremoveMJEl_hooksKA# HeeM instanceLonly used to  concurrent ;#$i5(). p# In or@our B O!beeed at each, we needd~A theF_4r_cache, which:do by registering aI`dedicaRmJg entryFing_ ( TC.{_spec('*raise ImportError   sys.path_hooks.insert(0, #) + ,Pmeta_.append(flushing_finder.Etry:;C0# F, the cache a first time+ U.\_spec(''bUnumtests = self.check_parallel_module_init(9. asGreater(fer.numcalls, 03TEqual1;x, ;8kfinall  IoremoveI2v3!) ?@def _import_hangers()# In case this2 is run again, make sur"e helper Li # gets loaded from scratchF.* 2delM0s['P.threL %']Iexcept KeyErrorEpass*X,. oFalse( .ezsqcircularsThe goal ofw to exercise implementations,5ort# lock which usHBper-, rather than a global>thex, rea possible deady7ithorts, for exaB# - $ 1+ A (grabbingt?#A)7s BrI2IBIBIAI@SuchC ushould be ato detect s.Csitu7andLaresolv2m one way o0e o, without freezingNOTE: our constructs a slightly less trivialort cycle,`in ordo better str:havoidance mechanismdelay = 0.5Zos.mkdir(TESTFNA ddCleanup(shutil.rmtree, /sm #aR3TrPname,9tents in s.items(A2con:=EA% {' 1': }3r open(oGS.join! ,  + ".py"), "wb") as fFf.write(.encode('utf-8')n. rbforgetq'<lib.invalidate_cachesC() results = []def import_ab():5) AG.append(getattr(A, 'x', None)u`/ba`B`B`t1 = threading.T (target=6_ab/t20'ba0w1.startH.t2j1.join% self.assertEqual(set(M), {'a', 'b'}) @mock_register_at_forkUtest_side_effect_(g!, <'oscode = """if 1GemP vy random8tifJtV G! =h5"""ssys.path.inc(0, os.curdiri.addCleanup(6oremove4pfilenam>TESTFN + ".py|with open(,, "wb") as flf.write(0.en('utf-8'7 unlink, ` fo", (rmtree, '__pycache__'/lib.invalidate_'s_v<__(p@del ^modules[ ] @reap_m!s _ maA-old_switchinterval2try' +y:getC s B1e-5except AttributeErrortNpassrun_unit(1edI\RTests[gfinall?if ais notxB) if ____ == "__d2__"R2()  , @.supY from.script_helperA _python_ok,tfailurempsys, iotUtructubprocesstextwrapuwarning operator ^c$gcsysconfigUlocal ing # count the number of  runs, used to createBque # strAn in8_`() numD = 0 class SysM23(.bCase):6QsetUpself.orig_stdout = sys.stdout self.orig_stderr&?err&displayhook+ 1def tearDown(`!):r>| & 7ys.} Q| test.support.reap_children()0st_Winal_H imI builtinsgout = io.StringIO()  dhHys._t"__; assertRaises(TypeError, dheif hasattr(W, "_"P5del.hvdh(NoneP.y Equal(out.getvalue(), ""-True(not4Vdh(42pO42\nt@._, Zf/el[fRuntim^Hxst_lost !aD code = compile("42", " osingle`eval, Y ocustom Wf badK(obj1rv Vv + =L)./, `except _ #ue[e6try a mz as excC@eh(*exc_info() `Y7err.endswith("c": lFVB kcaptured_output("j ") 1, '1', 1#" : print_ion(): Eion expected for " \  ", str found" in 6# FIXME:qing thei a , or replaced1 in# Python/prun.c::PyErr_PEx() is tricky.,it# call with two arguments self.assertRaises(TypeError, sys.exit, 42%) 8# call withoutY  ]SystemExit) as cm:2q%()D IsNone(cm.exception.coderc, out, err = _python_ok('-c', 'import;?()'v`Equal(Y0 u/b'C Qerr, #F integerK>/42cLe tuple one entry will be unpacked!,_(42,)4estring5"4"4z1twoz&ie[-o17, 23^(6test tha e  machinery handles s properlHqUtfailurerO?(47/47ydef check__message(, expected, **env_vars)TJ|Z1$ 'True(err.startsm()),:"%s doesn't 22%s" % (asciiN3), !'))&# J0std  buffer is flushed before thjy#uwritten#g"o Kr1A._Se("un7,")Q":")'b2$\Pbackslashreplace$or # handler to stderr check_exit_message(#r'import sys;.,("surrogates:\uDCFF")',:b$\udcff") $# test thae unicode ` is end to the7ingJinstead of)udefault*u (utf8)1%_h\xe9 , PYTHONIOENCODING='latin-1'1defC_geting(self): .assertRaises(TypeError,CF, 42# can't P moreln!type, as user might have changed itIsInstance(sys.s(), str1ingsettrace()rdone inDsys_1.py{ =oprofil?!ABq1set intervalowith warnings.catch_(.simplefilter("ignore", ?aorig =<g *Pfor nNP0, 10@20, @1: #0 lap`o restQstartAtate0 *(nv,0Equ[ pC), n_witchXIsetsB<G, "aAHValu ~o, -1.0 C0B (i# sanityQTrue(NR< 0.5A6tryyM.00001, 0.05, 3.Tf/. / iAlmost5 @6`kfinally orecursionlimit/o:getB p1oldX .ksk<V zt, -42)  sys.setrecursionlimit(10000) !self.assertEqual(6g6<), 9^1oldg!) bdef test_`overy(!):,if hasattr, 'gettrace') and(8<K.skipTest('fatal error if run with a Q function'C$ =j (8ff!6try] for depth in (10, 25, 50, 75^0 0? Pj)except RE  '# Issue #25274: The   is too low at theB# current@.continueBDQ5392:Yp stack Mffter hittingo i#NtwicKzRaises(1>, f[5kfinall"@P.support.cpython_only"_u _} |^"SeEa must be blockedc3already higher than< "lower-water mark". Otherwise, it may nopossible anymore to>Arese%ed flag to 0.f`from _<pcapi ima7 ge93ms!2_at*(i,l Q+/ =kP 7">=U ~) as cm>o egex(str(cm.rUion),]@"can%C[0-9]+ "M* B:C3the{"Nelse@O sys.setrecursionlimit(1000) Afor  in (10, 25, 50, 75, 100, 1Y200)::E# formula extracted from _Py_RecursionL}LowerWaterMark()L#if^> 200lpsdepth =)M- 50GOelse=* 3 // 4ATset_r_A_at_{(,zfinallywusys.setKJA(old wdef tesr_fatalerror(self{A# A  0 ocf if a second s is hit whenuovering#a first one. code = textwrap.dedent("""#import sys^'f(-+tr.fuexcept PE m;? &%d76"""Awith@.sup.SuppressCrashRe KiG1l sub = subprocess.Popen([executable, '-c', Y% i],xstderr=N6IPE$2erru.communicate()[1]Wn.assertTrue(sub.return,k@=In(_0b"Fr Python: Cannot`stack _flow"3doe* ), and verifiesgH"Jreturned make sense$entered_g =sing.Event()E_leave$ %_info = [] eVV's id&Wf123(mSg456((m.append(aget_id68.se@.waitTD(target=b`t.star=Pp V# At this point, t has finished its >, although it'e # ssible to guess whether+ still ohat line orqymoved oyo~ 1".assertEqual(len|G), 105_idF%7[0] / =for tid in dIsInstance(tid, int),rGreater)0p OL3In(66, dr "_do0# Vyacaptur2in-7 _3_t= d.popRTrue(/  n , called*p# from + isa litte tricky, since various b'ofDvpy are also!'s{D sta+(_i0.extract_J/Ni, (filename,Pno, func`sourceh)enumerate(R %if:P == "*"UbreakJelse$pfail("didn'tMdx"() &"@0, "(()0Q# Andnext record must be &4. filename, lineno, func`source = stack[i+1] self.assertEqual(;"g456")+6In(Y, ["leave_g.wait()", "entered_g.se5]) J # Reap the spawned thread.#Q=st.join(Kdef test_attributes(%):1IsInstance(sys.api_version, int 40rgves.nZbyteorder, ("little_big")fbuiltin_module_s, tuple?copyright, str2exec_prefix4_base_9!4outablel"lePfloat_info), 112.@.rad22d%inb/2Tru8* .bits_per_digit % 5 == 0m>csizeof<?>= ?typ| )A? 4:hex3hsYDhash9ALess8+.pus, 2**VwidthG*# 9 should be a prime; we do a quick`# prob(QalityT (doesn't excludeqpossibi&'ofFa Carmichael numbezfor x in range(1, 100A]@pow(6ys.?-1, -),H1"F{} is a non-F".format(UE# i6O.inf6/naMKimagm@algo9ysconfig.get_ _var("Py_HASH_ALGORITHM1+ifNPrithm P{"fnv0sipF24"}*  (N.hash_bits, {32,w 64}) 'self.assertIn(sys.hash_info.seed_bits, {32, 64, 128}) Cif algo == 1:ha[Equald:rithm, "sip}:24"'elc2c*=fnv]/seS  {"Q `,el[# PY_HASH_EXTERNAL0 ,k6, 0"GreaterUocutoff9KLess18kIsInstance8maxsize, int0ounicod35max.0x10FFFFfplatform, str1_refix/obase_p4{versiondPvi = kn xvi[:], tupleAlen(vi), 5%_vi[0]Ovi[1*2* [3], ("alpha", "betcandidatefinal")4p vi.majorO.min-?croZ.releaselevel8.serial~Y*** *?cro* )vi1 #vi+True(vi > (1,0,0/sfloat_repr_style}1('short', 'legacy'zaif not.startswith('win')ptabiflags#def test_thread<(CVcthread_info  self.assertEqual(len(info), 3) $7 'I .name, ('nt', 'pthread solaris', None)E @lockEsemaphoreAmutex+conODdef test_43581(!):*# Can't use sys.stdout, as this is a StringIO object whenB1theb runs under regrv.(y 5o"__q__.encoding,7err!) Llinternglobal num2U += 1Raises(TypeErrorc = "never ed before" + str(h3,PTrue(<0(s)_s,2 = s.swapcase()  Q2R.p# Subcl@s ofQing c%be`, becaGthey?provide too much opportunity fo @sane.ngs to happenp# We dofwant them in dict and ify aren'tactually4:, wXpo creat e garanceD1tha_ by allow)vsucceed@g S(str;W__hash__ return 123z, S("abc")sys_flagsvZ)gattrs = ("debug",""inspect", "`activeqoptimiz dont_write_bytecodeNno_user_sit8%no ignore_environmentoverbosMjs_warningAquie6randomizationi\?tedQdev_mb "utf8 ,0s;) n0has&v , ) i_type = boolU == "A els <xH@(getA ~m J0FreprAs0), s !&InX.l, {0, 1, 2}@rt_r_on_new__op# Users<&n4prevented from(new inst( e#, sys.version_info, and sys.getwindowsversion. attr_type = P(sys_)#with self.assertRaises(TypeError):+U=R(C/.__new__(U!) mdef test_flags_no_instantiation( _r1_on^C.Le:Zl4Ss x # Skip if not being run on W?.support"Pibute=, ""M B#()@~cpython_onlyBcleam_cacheMys._%e%ioencoding@env = dict(os.environ?# Test character: cent sign, Ued as 0x4A (ASCII J) in CP424,Irepresentable&2.'env["PYTHONIOENCODING"] = "cp424"Qp = subprocess.Popen([Qexecub , "-c", 'print(chr(0xa2))']w kstdoutc0IPEVv=env ( p.communicate()[0].stripexpected = ("\xa2" + os.linesep).P(bmEqual(out, O>ascii:replaceF Ob'?' [=Emstderr .enz, err = I.'^In(b'UnicodeE2!:'g3@rb"'#'"'~8  stdout=subprocess.PIPE, stderr @ env=env)& out, err = p.communicate(#self.assertEqual(4?b''#In(b'UnicodeEnarror:'g3rb"'\xa2'"'env["PYTHONIOENCODING"] = ":surrogateescape"5Hp = 1#open([sys.executable, "-c", 'print(chr(0xdcbd))'],K ? _Z[0].stripeq\xbd') @unittest.skipUnless(upport.FS_NONASCII'requires OS s; of non-< eCingszOgetfilesystem6 () == locale.getpreferred!oFalse)%FS to match\@def 4_ioa_nonascii(!):?env = dict(os.environ_ n^"y]~a%a)' %. '=Qos.fshe|)R 70If(3Pbase_`ix !=  'Test is not venv-compatible #i  should be absolute4 s.path.absK+),\ # Issue #7774: Ensure that4an empty ng if argv[0]# has been seta existent program name and Python_ un7 toNpretrievie realAw@For lrmal installation, itNwork without 'cwd'largument. L runs in the build directory, se8.Ep0_dio0dir. |eT["nonU"+ "@ 'imt"; D.&"Ebackslashreplace"k executable=sys.e, stdout=subprocess.PIPE, cwd=python_dir) 0 = p.communicate()[0]$`# =a.strip().decode("ASCII"Xvp.wait(self.assertIn(S, ["b''", repr(2.en_ascii", "backslashreplace"))]) def check_fs8@ing(wT, fs_, expected=None):<+@sNot(:cs.lookup#%ifhb fXEqual?test_getfilesystem?ys.70if qplatform == 'darwin'4 = 'utf-8'7Oelse-D*a c_locale_error_handlerp, isolatFalse,  # Force the POSIX Yenv = os.environ.copyenv["LC_ALL"] = "C"<["PYTHONCOERCECLOCALE)0)<F\n'.join((Dp'import*',dump(name):>std = getattL!, -,print("%s: %s" % XB.gerrocreturnf surrogateescape0out^q3;get=7 7?out' +: &\n!4?out5stderr: backslashreplace\n') ##  the default error handler, out = self.c_locale_get_._.(encoding=':ignore')B<assertEqual(out,'stdin: H?\n'+ ?out,err: back Qforce iso8859-1/ostrict,&:# have no any effect%0urrogateescapu s5m def test_implementation(!):#a# This* applies to all 90s e6ly.y levels = {'alpha': 0xA, 'bet B, 'candidateC, 'final&F}N.YTrue(hasattr(sys., 'name')=version@&?hexC-cache_tagV .-0!s[:2], (.major, Winor)>+ =6 << 24 |=E16 |Hi0cro,B8 | *[qrelease]$4O version.serial << 0) !self.assertEqual(sys.implementation.hexversion, %) E# PEP 421 requires that .name be lower case.5z@,22.o#() @test.support.cpython_onlyZ@def "_debugmallocstats(!):%tp# Test u,RAfromQsscript_helper im t_kgargs = ['-c', '/Osys;{%']=ret, out, err =f (*_ In(b"free PyDictObjects"KKphe func has no parameter[Raises(TypeError,c, TruekP@unit.skipUnless(hasattra, "getatedblocks")."4 unavailable on this build"(!< #6try0-_Ecapiexcept I  9rwith_py4 =  (iJelseB_5 = v.pymem_0ors$KO gG = (NTin (' 'xH# Some sanity checksa6ys.GIs(type(a), int9if BGreater(a,< # When WITH_PYMALLOC isn't ,p, we doknow anythingabout the underlyinga:R[mightFreturn 0 or somej1 grTs 0ilecould imagine a P2@ sesa wherenumber ofmultiple buff!K! wY!edA@sharof references# it is unlikely to happen in a normalqO run L@azgettotalrefcount+;pt Attribut Q.# A7 no 6pasgc.collectb Fb, a] c = sys.getallocatedblocks() self.assertIn(c, range(b - 50, b + 50)) 1@test.support.requires_type_collecting+@def ._is_finalizing(o!):"~js(sys./), False# Don't use the atexit module becaU_Py_Fv is only set{# after callingIUbacks)code = """if 1 im B sys!class AtExit2 =? |.print =  km|__del__bnC& t(), flush=True:# Keep a reference in__main__namespace, so" # destructor will beed at Python  >Sref =B5"""'rc, stdoutberr = !_pW_ok('-c', Y*bEqual(Gp.rstrip b''P@unit.skipUnless(hasattr , 'getandroidapilevel'),\Q'need 92()'v_$]r_.P~8Instance(?_, int*tGreater'0sys_traceNQlimituY^7f1(EY1 / 0\,2,B +y Y = %r$/f2shjcheck(C, expectedpubprocess.Popen([executable, : % Z]Estderr=sh6IPE(!ouT.communi!Y()[1]out.splitlinesI = [PF (most recent last):'b' File "<`ng>", ~ 81 767/f214111ZeroDivisionError: d by zero'Y0610,32f[:1] +H[2:]) check(1, traceback[:1] +c3:]) check(0, [1=-1]"/-1#w1<<1000{ g-#n INoneHdef test_no_duplicates_in_meta_path(self):/.assertEqual(len(sys.21), +et`)) @p.support.cpython_only class SizeofTest(unit/qCase): _setUpP = struct.calcsize('P'<longdigit.ys.int_info.01of_n im _EcapiLpgc_head:& =%.SIZEOF_PYGC_HEAD"_-Aof =>.v_e 0# C9 that the gc 0er h is added to objectscked by2.v5 palcvobj*!erKCelf. *e# bool~pare not(5kedTSc_0getOof(True), q('') + 2# but lists areb&[]`!Pnb)lerrors2BadDQ_5Lof__;"raise ValueEdR$&s(%), 1%, (XoInvali)`eturn a2Typ sentinel = [" /"]e!Isk$ U$, @) k _Float( ?4.5~ #lfp 3 OverflowG(int 2int (0max5)),E (;9Bwith ?uvC [8*f(sys.maxsize + 1)) with self.assertRaises(ValueError):,3sys.getsizeof(OverflowS-Z[$, @jk0max! -def test_default(Y0=#.support.calcvobjE`Equal(qpTrue), 3b('') +Elongdigitb]IO, -1M objecttypes# check all ! defined in O8!s/N = struc #  1 0v) Z=1 _<%ofte# bool$(r!, gr # bufferAW# XXX builtin_function_or_method%t4lena4P')) Jcelayout2# bytearraysamples = [b'', b'u'*10]%Bfor ) sv6x =^(#b%(x!An2Pix.__alloc__(_iterato0(%()n Js=n1#vx' * 10)*V# cel @get_($%42/\inner,return x25x.__closure__[0]" EcodeCG_(a, expected 8Greater?,a)Ft p Tode__I6i13<: j;2(x]0Kq4 + I('n'  co(6(0,*2d:4_descriptor (  str.lower|)3Pz# class[# membertor (descriptor object) import datetimedcheck(.delta.days, size('3PP')L# getset_descripp( |collections.defaultdict _factorywrapperint.__add__Y2smethod-a V{}.__iterV T ${} nQ/r + calc~2nP2n') + 8 + (8*2//3)*!n3@longd = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}B 16/16 # ionary-keyviewx{}.keys()y A_valueCEOitemDC Kator6({}J2nPnD0key1HOQ $?s()SR #QVproxy.slass C(3\: pas@C.__-R BaseException[ Y:5PbUnicodeEn-rr!P("", @0, 0 L5Pb 2P2nC/Ded !dbe TranslateE $kO0, 1|ellipseEi9 d]eingMapPcs, eings.iso8859_3+Bx = (.charmap_build(5 .deing_tablexaj32B2iBenumerat%5([]+n3lrevers<Fd(''; :Ufloat%(04dAsys.#info check(sys.float_info, vsize('') + self.P * len)C)) u# frameimport inspectCO_MAXBLOCKS = 204x =..currentR(dncells =x.f_code.co_Gvars+Ofree+ +Pextra+RPstack8 + nlocals +\3 0+ nfUs - 1&hx[5P2c4P3ic' + @*'3i 'PJ*'P'luunction_def func(): passx , I('12M`class 94@staticmethodkYoo():5 z@^Ebar(clsH/# $ooP/# =?bar=# generatorpget_genm]yield!Xib2PPP4K# it]t('abc')@l:callable-, yrUpre.find0V('','\ V# lisQsamplJ[[], [1,2,3 p'1', '2E3']] Bfor 53 in s+%!Pnnet")*z# sortwrapper (5XXX_# cmp*HG V?([]Bpreverse+I%dMn&in~0%1longdigit--.PyLong_BASE ** "in.bits_per_dscGint(?)2 >_**2-1C. A3|# modul:unittest:PnPd\# Non62- tIUmentedTyp;!E8objX}( xproperty (descriptor object) class C(: def getx(self): return M.__x,s,, value):," = 45del`5del1 )x = property( , l , >F, ""check(x, size('4Pi')"# PyCapsuleeW# XXXrangeiteratorX(!E(1))eldfreversb<Ed('':+nP:| ton 4\8e(66000\4(#6Z# frozensetPySet_MINSIZE = 8samples = [[], j F50)]-# =|y3nP' + X"*' '25Bfor f3 in sminused = len(-5if %= 0: tmp = 1f%# the computation o7is actually a bit mor.{licatedLbut this suffices bfof tesb)*2T0new;* =8 $dwhile *$<=K 1n$=.<&if>= 8Db4setu:, syj&V,Oelsed$ +P*calc(>y}E)W:P3nLslic("3", "eval" 9 + TODO: ad2eckaQforceZ 0 ceO F/# Mces layout of unicodefields # weakrefmimportccheck(- .ref(int), size('2Pn2P'))FXWproxy7XXXMcallable* moNAdef 2_slots(self, obj, base, extra):-expected = sys.get0of(/) + struct.calc(A@if gc.is_tracked(obj) and notS{ 0+= .gc_headkdassertEqual(r!) 8 Gtest#% all subclass{p types ned in Objects/ that0!ow`# non-empty _i%__WAelf. #!v BA(bytearray`T = 'a', 'b&c'CeBA(), F F'3P' D(dictd$D(x=[]), {'x': []}, e_L(lise%L/[]ZOS(seY%SY0setFS(frozenc'FdFjfrom collections ^OrderedDict7OD($OL w1apython ?x7!*P8/M0 = @.supJF0obj(v)v*E RFizeo# _ast.AST_fI(+)(':tryraise TypeErrorNfexcept 6 tbys.exc_info()[2]=* # =Yebackif tb isKJNoneZ;&tb}*2i|AsymtOentrSFflag[!, 1(''qP * len<)}asyncgen_hookO'olw_, Is(old.firstiter)nalizer)  firstiter = lambda *a: None sys.set_asyncgen_hooks(;= )4#0 = <g<)self.assertIs(7.P,2 ?[0]+.finalizer,X $1]&@2!{=E2[7+<JF*old  cu+9F(cur;P )) def test_main():.support.run_unit(SysModuleTest, Sizeof ) if __name__ == "_T6__"Up() """ 6 implementation of the PEP 509: dicary versionning.@ im Q fromUCort 4 #Q0 isr ed in CPython but other  s # don't require toKP it _ @capi;!_m2%('#'zclass DictV$s(.DCase@ype2d! = `setUp(+c.seen_9s;et(b! =RTcheck91quea@, my2i_5 = .#_(6cNotIn()., D.add<)ychanged, method, *args, **kwresult ='(& , rreturn VRdont_<1 M1N  2  TEqual$2,C1, "\ )d"Z [@new_J*args, **kw):  d = self.type2test(*args, **kw) %" $check_version_unique(d%return d 7@def Q_constructor(l!): [# new empty dictionaries must all have an n }A;1@new_G(!2! 3!da# non-I/so 1non?Vx='x')), y='y')a,pyZa=1, b=2>dh dont_change(d, d.copy8#"()create ay with a.|*$(dGsetitem 1ing3key[M theS.d #__q__, 'x'?y?!# nDvalu e41)a_same_  = object @sett Sa keyh0 ke|t!tok ,e. ,6/oupdate8Q,=?Qw4key'# bl_equalfclass AlwaysE!hvIa__eq__9w, other%BTruei`N`assertW(/B1 ==U2*TFalse+!+>r Zchanged(d, d.__setitem__, 'key', value1) # setting a key to a&` equalthe current>with dict._o() must change @uversion:self.check__.hd(d, dN 2Boupdate0I,L=mQd2 = @new_6B(key(/2)dd def testdefault(g%):TdzH4setQ/M'$'Odon'=1 ifLalready exists WCdont\[2P0delAMD`g# dele^Y#__\/__v0N[Q@doeswQPrassertRaises, KeyError,G  ?pop'=WO :pop'# o/no y '|3X ! "z. r+1popAz 2 isOmpty c  w[4=n{ew }Ez" # update()) calling with no argument must not change the version self.check_b_dont_3(d, d.update) 5"# "()d-`.d\, key='new value'mQd2 = new_dict(-)E 3')% l#d2_def test_clear(@%):Odx"# ? 1 if1 isUemptykz  a s ws w class D|%gpass SubtypeVd`Tests(5<(2|! =X if __name__ == "__main__"@unit1.A() #s common to and Userx import ;collections&syPBasicMappingProtocol(H.CCase# This base +can be used that an object conforms!1the 2# mt# puvR# FunGa0fulBoverride Padapt Rionark# semanticsnNone # whicheZw@ed (dwrite in sub#esN_referenceN"""Return a2 ofsz ar]variant by storag!inLDQunder A."""%rj{"1": "2", "key1":"612":(1,2,3)};'_!n *k(kIfulljc, dataV6?2N`tainedFDx_80for,Ww.items(,x[key] =,{xq_init__Y, *args, **kwR h/._7mh().copy(@# A Na) pairgtd3key,`_@.pop_other = {key:}"} e = self.reference.popitem()  self.inmapping = {key:value}%2refF[key] = % %def test_read(T!):f# Test for  only operations on 3@p = F._empty_  p1 = dict(p) #workaroundgsingleton objectsYdYEfullXlif d is p%p1U#IndexingBkey,$2 inb.'s(%WassertEqual(dkFknownkey = listp.other.keys())[0]V Raises(KeyError, lambda:d[S]fO#lenElen(p), 01i$@d), ,)6#__contains__pA8 T0vIn(k, dW A==Not@E#cmpiFp, pl d#Nop"dcU#boolRif p:Spfail("E&F must compare to False"if not dCOFullB8TruA"# h#,  rE ...check_iterand , lst, refw(hasattr(5'__next__'D =7@7xE#Rset(x)==3lst 8$(d,*r 83B1kqd*J.P  43`%),<a  o32E#get  = JX%(d{!,  5y[>4ad.get(P)8) BertNotIn(knownkey, d) def test_write(self):# Test for  operations on mapping/@p = B._empty_ %()"h#Index4\value inBreference.items(p[key] = 6_assertEqual(,,+yr=keyqBdel Im Raises(KeyError, lambda:6x%eupdatei"p..S dict(p),L2U = list(pd K:d6Efull5I#setdefault"A= next(iter(d3kno @ 5x_other>]&d.(W)t?( g7), yq>]2O#pop?Q.pop(j?keyuUNotIn0w ;dghf = 909[ !laQ5e vIK1 = Je\!N !p=7 p [constructorP   hOboolaTrue(notM53( ) is Falsej>k7 AJF| self.assertEqual(list(d.keys()), []) d = self.referenceaH"InEinmappingRU[0], `@9NotC_other?Raises(TypeErrorn, None) sdef test_values(!):s_empty_( 1. 8P:R07Oitem8O6?len@1en(d), 00get}c !d[%], :c())[0]4`#__#__5lupdate## x argument'd.U.Di;.O# No*"d,i  Y sequ"bEd)!, '#IteratorX{FIXME: Doesn't work with UserDicr# eAttributu)v532G!'42PouterK`class Simplev__init__s Z.h)M,2Bbreturn<!A?, iK 5[i]Gwd.clear &()si1 = sorted(d.items())  i2 = sorted(self.reference, assertEqual(i1, i2) N class Exc(Exception): pass$dqj_empty_mapping(FFailingUserDict:edef keys) Praise6Rs, d.update, p%=d.clear( 5  BogonIter=E__init__(Ui = 1K?terKpreturn RL?nex!ifH/.il.0r'?'a'' =tv#"0get(%,ic"5key!dQvord('a'.6iXgA <= /z'rtn = chrK/.i*?i +Q$5rtn @Stopa ,G28badseq(object&x <n b|J. )4 ValueError1[(1, 2, 3)]># no test_from2 or copy as both os.environ andves don't support it3S1getWKself.assertTrue(d.get(list(self.other.keys())[0]) is None) (assertEqualD@, 3)BAd = Freference]OTrue\Binmapping*,)`:Tvaluef;{"]~=Raises(TypeError, +,,9!) def test_setdefaul~!):8#s_empty_p([ uqpopitemr,5KeyW0O, 42k, v = kjau[k] = vz ,\ 'H=pop(k), v&len(d), 0  Kk) class TestMProtocol(BasicconstructorzC. 9P ^2not .MPtype2 (x=1, y=2), {"x": 1, "y": 2}OObool2Efull_"y"})8./MOFals >{G- :y= 2:djF, []O 1'a'2'b'k = d.keys()  self.assertIn('a', k) ; b!No?c!@def test_values(L!):_ BasicTestMappingProtocol.432d =r_full_m9o({1:2}Equal(list(d.)), [2]) WOitem3M+Sm(1, 2)}containxUemptyd!True(not o in d)(@'a' ,'V  'a': 1, 'b': d~Raises(TypeError, d.__Y#__6?len1 2Pen(d)l0get6 58d['a'], 1.@d['b$2$d['c'] = 3JE = 4JcJ3J$4$Bdel [1, {4, 'c': 3}M`L\clear `:2, 3:{"d.G?, {Pc, None`lupdate 4d##  argument#d.Tg{1:100?2:2/1:H6 -O# no Wukeyword\ssVx=1007y=2d.update(x=1, y=2, z=3) self.assertEqual(d, {"x":1, "y":2, "z":3}) 4# item sequenceAd = P_empty_mapping(nd.update([("x", 100), ("y", 20)]*H#000JBoth and keyword arguments8Q, x=1V iteratorEfullD{1:3, 2:4}kN-_02, 3:4, 5:6}).6s()>5 b126;class SimpleUserDict:Rdef __init__(b) $., {1f2sM3:3}IOkeysEbreturno!d.*f0get?, i K5[i]d.clear W1Ktest_from Ptype28.8'abc'), {'a':None, 'b c 9jTrue(not(dq_ is dR 2L`(4,5),:@{4:0 : []& Wef g(tBuyield 1R 0g()S1wY4Raises(TypeError, {}', `dictlike.f): pasb"8\9('a =/()? <1.__!__* F H3()0 my5 w__new__(cls:"Ocollections.,Juq5/b'uIsInstance(ud, collections.UserDict) self.assertRaises(TypeError, dict.fromkeys) 5class Exc(Excep\|): pass$0badE!1(htype2test):Ldef __init__* $rtV TExc, vW, [1]8BadSeq(objec?ter`eturn ?nex4a.<)2M; Wwssetitem, key, value/$2| Q_copyn1d =V._full_mapping({1:1, 2:2, 3:3}Equal(d.W?), 4dUemptyeVd&IsInstanceAd.__o/__5vc, None. bpa( pqlog2sizprange(12E size = 2**log2size  a = self._empty_mapping()*b*for i in range(x-):Pa[repr(i)] = i#if copymode < 0HLbL H>H a.pPka, vZta.popitemTassertEqual(va, int(ka)2Pkb, vtb`b`b`True(not( and ta != tD@. a'1b) def test_pop()BBasicTestMProtocol.1I0 # . s pop with specified keyt+dk, v = 'abc', 'def'j.d(4F), v0d[kvy:1:q classKHash( "):M1getmQ;L 0Exc(Exception): passoH$BadEq(objectp!a__eq__{, other%)`raise n>AChashC<eturn 24"d[%425Rs(KeyError, d.__-c__, 23  fail = Fals"ifECOelse6=/42=qx = Bad0d[xM x.0 = ac=Exc^x]fromkeysJ 1amydictL`.type2dV6{__new__(cls"r>`collec#ps.UserD[uq.F'ab'#wud, {'a':None, 'b }3self.assertI-sInstance(ud, collections.UserDict) def test_pop(self):TestMappingProtocol.,D,class Exc(Excepl|): pass$BadHash(objectoGfail = False__hash__ 0if .EQraise)^ Oelse6eturn 422d =l_empty_m'(WDx = `d[x] =Ksxf = TrupassertRsW, d.pop, xmutatingitera| #0d[11:tryfor i in dKd[i+@e RuntimeError8=~ ("changing dict size dur doesn't o"'OrepraEqual(Gd), '{}'2B9 I1: 2=Qd_P{...}c1R,3xc(Efull40{1:*q&)}P?y3, dXM_deevrange(sys.getrecursionlimit() + 100Vd0 =  p&o%d0R= , ,eqK ,G E2}), |5.?Cmp> C__eq{, otheroAf r1 1 0BadG): 1/d2/1(9xalambda3]2==1 self.ass0ertRaises(Exc, lambda: d1==d2) def test_setdefault(self): TestMappingProtocol.3R3class Exczeption): pass$BadHash(objectvGfail = False__hash__ 0if .Er)^ Oelse6eturn 422d =l_empty_m.(WDx = `d[x] =Ksxf = Tru;ass&d., x, []) import unit#rllib.parse RFC1808_BASE = "http://a/b/c/d;p?q#f"&O2396&$5398$'J' SIMPLEG; = $' # Each A_qsl8case is a two-tuple that contains # a string with the query and a list expected result. p_*_qQs = [ 1(""Q,& =('', '')])6&=aaa1aI B&a=bLbM=a+b&b=b+c#a b'), ('be:b c3W1&a=2/1-^2+b *b"  [v][0])}V8se.parse_qs(orig, keep_blank_values=False) self.assertEqual(result, expect_withoutH)s,<G "Error parsing %r" % !) 8def test_roundtrips(!):Dstr_cases = [('file:///tmp/junk.txt'&@', ' +/')8 )5('imap://mail.python.org/mbox1.} /3 @"mms://wms.sys.hinet.net/cts/Drama/09006251100.asf0mms DH c: nfserver/path/to/VJ!nf04 Asvn+ssh://svn.zope\Preposrn/ZConfig/trunk/BC/G b93gitgit@github.com/usroject.gi#(': ;?','> L'','#V/< '']_encode(treturn (t[0].$l'ascii.|tuple(x- for x in t[1]8<62])FVbytes&x)nAurl,.ed, split-7 + \$7v.checkRLP yOhttp~# urllib.Re.urltreats '? :' as an optimized special Xq# so weV both@"nd 0s:'all the following.# Three cheersRwhite box knowledge! str_cases = [ ('://www.python.org',"< (' G '',)1).O#abc3 Z 0 10?q=*1; ''^2 3// \51 2a/b/c/d;p?q#fav# pqf-;* y]def _encode(t):return (t[0].$m'ascii{/ tuple(x- for x in t[1];<E2]))bytes_ca&x)n2str!QschemQ('htt),s'^*b+ ,T@test  6 ,  -/ 1:!8L(_2s, ; A4K 'url, parsed, split3Uu6:burl = Ye + urlXB = (+C,) +m0 /.elf.checkRoundtrips(!) >-Join(self, base, rel6expectedMncomponen(3cY.assertEqualAlib. P.urljF5), zG {4bb5b 3\buL!un_~ f!'PC$./ b'x-newE ://foo.com/stuff','x://yf','/',Pe (=for u in str_cases + bytes_c7: self.assertEqual(urllib.parse.urlunsplito)), u)S^ SSTdef test_RFC1808()# "normal" from RFC .(7.checkJoin(N_BASE, 'g:h'3 1http://a/b/c/g'<?./g>(.g/=/| {/:8>g?y/?yg?y/./xDu-#sCd;p?q#sDg@:, ':!#s?g?yD;S/;x !;xp .. < x: w; HJ../.x.-< H_# "ab0 fg.>.>. ?/g.~://a/b/g')  *self.checkJoin(RFC1808_BASE, './g/.', 'http://a/b/c/g/') ?/ A _g/./hAhBCA`# RFC B and 630 disagree on these (according to)W808),K so we'll not actually ruCtests (which expect{behavior).N Vgg#:96') s XXX: The followare no longer compatible with G3986I 2../!9../! C IL/{# ]@def _RFC2368('):0Issue 11467: path that startsea number is`parsed correctlyN].assertEqual(urllib.1A.url ('mailto:1337@example.org'-7 40, ')S .96cases fromCR 23961x _ _!g:3 8m6< >.g/{  /ZW  /:8>g?y/?y--#s?d;p?q#sCgD/?yBD-;x?g;x!;xp 8F.y< x/b/') ' self.checkJoin(RFC2396_BASE, '../', 'http://a/b/') ;g<g=)..>; < 8', ?)gob/c/g. >.gf?/..\./../CO./g/>Yg/./hh//hgCA;x=1/./yy0.KEn?y/./xg0IJ/#sHy 0c/gI%) )# XXX: The following tests are no longer compatible withG3986I'.#F8SL / \1defG@_RFC((%):/ &H?y',oc/d;p? @;/;x` >`g:h',' g; u =-g/y self.checkJoin(RFC3986_BASE, '/g','http://a/g') self.check897(?yob/c/d;p?ywgA/#s?q#sCg?/?yA,;x/;x>g?31g;x q.?:/;' vt.u: bI../.v.; 0/..X # Abnormal Examples dThe 'a"!scenarios' are incompatible with RFC2986 parsingIAests6here for reference.r"  a @C!/N:#;&gx.C >=.Cg>...}~ro>/g/9/9\g/./hg/h') s)elf.checkJoin(RFC3986_BASE, 'g/../h','http://a/b/c/h') s@ ;x=1/./yCgyIJDm?y/./x0HI/#sGx gHI# g g') # strict parser H6PtrelaxedPQ# Test for issue9721 }de', ';Q;x') Cdef test_urljoins(Q!):eSIMPLE:/g: 1p?<d) }:g:/./<',g//g/x w/86?/d?A \>g>N/ .ig.: t8 s9 I../.t.u%&9/g/a>/g/g SIMPLE_BASE, 'g/ ../h','http://a/b/c/h')  self.checkJoin(SIMPLE_BASE, 6g?g? >d>-?y@/?yBgCl?y/./xgK@///', '..@/', g ~ J=./g;svn://pathtorepo/dir1@@dir2!2svn+sshU%Y "ws0','<'ws342# XXX: The following tests are no longer compatible with RFC3986 _? # b 2../.D /.')  for issue22118 duplicate slashes0A + 'gfoo', , xNon-RFC-defined@p, coverPvariations of base and trailing# i1d/eY1f/g]a ONL;hK4 1+:GU 23703: don'tfilename0 albx1deff_RFC2732(4&):Ctr_cases = [( Test.python.org:5432/fooJ0', /),K12.34.56.78GC Z[::1]= ::x [dead:beef::1]:5432/foo/', 'dead:beef::1', G), ('http://[,FEcafe:5417:affe:8FA3:deaf:feeda  C'faC ::12.34.56.78p) 'IOffffN ,::.` Test.python.orgt', NoneB> U[::1]8,n ,9BnBzA + & i > d H  1I )[ Z: / '[&C\9]: ,]B; _ ]  ?`(l  8 *']8def _encode(t):areturn t[0].#'ascii'), t[12\bytes_cases = [gx) for x in str!6url, hostname, port.7 + ] urlparsed = urllib..Y(url)self.assertEqual(#5&d.@ d.V) , (%) WVh4.56.78]/',  'http://[::1/foo/', #: 'f#bad]/bad+ O,ffff:12.34.56.78']bytes_cases = [x.encode('ascii') for x in str(=invalid_url&7 + \:qself.assertRaises(ValueError, urllib.parse.url ', i!) Odef test|pdefrag(Z)m4(python.org#B>', )E+Z'<//C, /?q/?q.pppt RFC1808_BASEa/b/c/d;6f7O23967 6N_treturn type(t)(%t)\xRurl, S , wresult =NF(url bEqual(B .g1l()32, (e)5a1Cmentfsplit_scoped_IPv6p5P[FE80::822a:a8ff:fe49:470c%tESt]:1234' Ep.hostname, "feM "G netloc, '~#b'T( b2bdef test_urlsplit_attributes(self): url = "HTTP://WWW.PYTHON.ORG/doc/#frag"0p = urllib.parse.urlsplit(url)'f.assertEqual(p.scheme, "http"+ netloc, "5 qpath, "* query, "& pment, " - `usernaONone password, +BhostV"www.python.org Lport^# geturl() won't rn exactly the original URL in this caseq# since. is alway*-normalized5We handl9is by ignoringJfirst 4 characters of5URLGSP[4:], %) 3q://User:Pass@MA:0806?O=yesj  Y   "Z "- */80 LHD# Address issue1698, which suggests  can containW# "@" . Though not RFC complianmany ftp site]7lowJand request email a,$s /s. @example.com? "P 9+hostname, "www.python.org")  self.assertEqual(p.port, 80% geturl(), url) P&# And check them all again, only with bytes this time>url = b"HTTP://WWW.PYTHON.ORG/doc/#frag"10p =lib.parse.urlsplit( scheme, b"http `netloc, 6 @path4+ Pquery,' @ment* . `usernaONone password, +BhostV?b"wV_XA[4:]\ `"://User:Pass@A:080x?[O=yes:l  H![ EQ! b"\ T b". W+$M@example.comY e q# Verify an illegal o raises ValueErrora:65536urllib.parse.urlsplit(url) )with self.assertRaisesRegex(ValueError, "out of range"):AHqp.port  def test_attributes_bad_"(i<"""Check handlingbinvalid 1Qs."""Wg for bytes in (False, TrueS(Qparse(qurllib.,,  IM1ortL"foo", "1.5 -1L0x10:_subTest(=!, u=,=Lnetloc = "www.example.net:" +B./0url8phttp:///M1"ifn S E2 = .encode("ascii"i, ?url62p =5  YhpEqual(p$Cloc,   `Bout_/ s# This  is straight from RFC 3261. It looks like it# should allow the username, host "and to be filledEin, but doesn't. Sincj's a URI CckAscheme:// syntax,&Arelated 0Dbe left empty. 0urisip:alice@atlanta.com;maddr=239.2551;ttl=15RO %i$O"'yONoneR password, ++PRgeturl()"i)/ =*?(ur! # You guessed it, repeatz  LV inpu/b"D) self.assertEqual(p.netloc, b"") -se(username, None+ password+OhostV?ortRgeturl(), uri) p = urllib.parse.url (( "def test_noslash(%):># Issue 1637: http://foo.com?query is legal4C m"NqexampleR@blah=d5"),T ('?G', '@GK)b,bbSb'', Cb'')withoutscheme@Test - .Cv754016:0goes wrong; IP:port >outH RFC 1808 specifies that 1 should staE0 //w expectsQthe scotherwise it class_ e `ion of as path.Hw6[@('',  5"//www.python.org:80p *t } :.?',' # Repeat for bytes input b"f#"', bg !f4bz($separator(self): 4 # Issue 754016 makes changes for port separator ':' from scheme # self.assertEqual(urllib.parse.url ("path:80"),;BP ('',# %)),ghttp:"),(' E[ Q$sRsJVS$://www.python.org . # As usual, need to check bytes input as well`b Bb'', b"}bPk'X%YsRZ%}| 1)) def test_usingsys(N!):S3314: sys module ied in the error6ERaises(TypeE$,, encode, "foo"2any.0790 3://foo.com/stuff has netlocZ/".j sYu*('s3', '   b"x-new   :Y?query#fragment4UX P =~Q# And#G/../b"bb%b'  ual(urllib.parse.urlp (b"x-newscheme://foo.com/stuff"), 7(b';S', b'= B %))Q self.assertEqual(urllib.?query#fragment9Z^'BCjdef test_default_(~!):## Exercise the % parameter of 3P) andfsplit(for func in ,7 DPwith .subTest(VPtion= .2result =("http://example.net/", "ftp"8iM.!, N8'tb'ubv$Pw e("path D=K#bLM )>";b<K, ""@Y_%sZ Vallow.cQs = (3 xassertEqual(O.=O, "":_True(_c0get^,Z`).ends("#" + expected)vB"", 7 Nx {B* p <  x4 )m  I def test_mixed_types_rej%(W# Several5%s that process either strings or ASCII encoded bytesx# accept multiple arguO. Check they   e inputHeRaisesRegex(TypeError, "CannotH" l ("www.python.org", b"httpIbSgf"un(-, 4"",H C ?,""P( w.python.org3","C)) *with self.assertRaisesRegex(TypeError, "Cannot mix str"):BI"urllib.parse.urlunsplit(("http", b"www.python.org?,""NBjoin8://! b My/, gdef _check_result_type(,num_args = len(str"._fieldsQbytes% =I._encoded_counterpartu,6Is(AM._de6A$tr('',) * $W/(b' (*< +_D* /ing = 'ascii'eYv'strictQEqualws d /1.L/():-O v~' B*", t/ J",  {X.e:-Qv}Oing)& B(y $ J(Dtest&Qpairs'0# CJ SQ and pbetween X B\0[) qDefragR,%S"$ PQ $]R3for$ is: self._check_result_type( ) def test_parse_qs_encoding(self):&*< = urllib.1_qs("key=\u0141%E9", H="latin-1")L[.assertEqual, {'key': ['Kv\xE9']}:JC3%A_utf-8o_ascii"aufffd\%9E9-,-;,#serrors="ignore`! l$l4![((, /)] (L %&/-';[  1urle_sequences8q# Otherfs incidentallyJ> things;% non-covered cases3# Sh and object values.4%@({'ad 1, 2], 'b': (3, 4, 5)}, TrueX# we cannot rely on ordering herewC set .split('&')) == {'a=1', 'a=22b=3425'}class Trivialw__str__n  return 'trivial' result = urllib.parse.urlencode({'a': T8()}, True)@self.assertEqual(QT, 'a=n)odef test_^_quote_via(H%):WF 'some value'}0"a=2+2"1n/another'},Q=kP1%203%2F]safe='/', 2T"/gfrom_bytes,3Raises(TypeError, Jv, 'foo'~  7 (b'archaeological arcanaI  :=%20<p'O"un/toO 6'abc%20defb/ -i` e3-1, b) 0ing='utf-8m ='strictissue14072/p1: split('tel:+31-641044153p1.scheme, 9+ path, '^/p22&2.]"#  the behavior for9 U#U~parse('tel:+31641044153') self.assertEqual(p2.scheme, 'tel+ path, '+3164]^def test_telurl_params(q!):"p1 = urllib.parse.url (:123-4;phone-context=+1-650-516 1#1.oV ?, '+1-201-555-012 !`?') K7042example.comM loU   863-1230914 rY 6+1-Quoter_reprq 1(_ALWAYS_SAFEIBIn('91', l])Ud yon.org:080')?,  ('', 'www.python.org:080'))5 self.assertEqual(splituser(:o ONoneq*User:Pass@')i ')5@example.comj| GJ!) jdef test_^ppasswd({!): # Some of the $Cord s are not sensible, but it is added toM confirming to RFC2617 and-@ressissue4675.: = urllib.parse./@0d('Hr:ab'), ( A,\nCEtEErEEfEEvEE:DC CC) 2"/ 2$!W+1:a+!+1F:Z < g>bwa 7X', ['BE5]))F H'), ['?!<  n # Normal cases are exercised by other!s; dologic6l# with no key/p pairs. (]d ensuring coverage|7dm$#('0foo"0bar@ =:a:t 0foo o, None = to_byteslresult.'http://www.python.org' Q/, :Raises(UnicodeError,y2r/medi\u00e6val'lunwrap lurl, '3 if __name__ == "__main__"@unitM.() """Units for the memoryviewCSome"!in a. Manys that require _hbuffer.ndarray B import F@.sup4sys $gc tweakrefqU$ioDcopy pickle class AbstractMRTests5bsource = b"abcdef" @propert _1 qreturn ;"SG_Fpfilter(1, [T0ro_2,b!rw]check_getitem_n#Q, tp) b = tp(self._source) oldrefcount = sys.get&(b)mCHviewY assertEqual(m[0], ord(b"a")D*IsInstance/?int)S5SfS*/-1+6+ # Bounds checking0Raises(IndexError, lambda: m[6]4 /-75 maxsize> -?o# Type( ?Non 6?0.0 57"a"5} ', !) ;def test_getitem(!):9for tp in v._types#?EQ_with+<(tpiOiterf ab = tp9_list(m), [m[i] irange(len(m))]s&_readonly/bif not,!ro-skipTest("no K-L \1 to"UQt! g(valueE1 = "ZN!, 4&65fbmemory 0:_writable0 w K  tprQP##B;'1'_contents(tp, bg1bcdefbm[0:1]7b"0I0I1:3] = tp(b"12")  self._check_contents(tp, b, b"012def") . m[1:1] = tp(b"H:F:abceL /# Overlapping copies of a view into itV3Pm[0:3em[2:5]%:cde/m[[2 = mdPababcs0 def setitem(key, value):!Pm[key2tp( # Bounds 5ing assertRaises(IndexError,t0, 6 a8/-79$sys.maxsizeB$-C# Wrong i/slice typesLType?0.09O(0,):$(0,1,1), 0G%80, JG':$<"a"# Not implemented: multidimensionalXs = (&2)FNotIp Ts0TrygPto re the memory objectHpexc = V^ if m.format == 'c' else &;7exc{ 0/ab2 i(p/b" A50,2,m = None`Equal(getrefcount(b), old!) ;"test_del'H!for tp in !._ @b fsource;a# =>U*(bBwith M0delO|H';:4] tobytes( for tp in self._types: 3m =view(tp(+source))-b = m.tobytes(# This callsRqgetitemv() on each separate F of b"abcdef"lexpected = b"".join(! hUs([c])) for cb >assertEqual(b, w*IsInstance/o!) def test_tolistI)n tpx)ll1l, '  |compare# memory#n )]e6ity with other objects# having the buffer interface.'=P_s True(m == tp=(3-9@Fals:!:&t"{sr8 q1: r 9O== mY$?[:]' P[0:6]m, B[0:5-E1# CCison which don't support5APIIt O != +W'^J +!u # Unordered=96(m,%Raises(TypeError, lambda: m < c<1c <1y/>=z(><def check_attributes_4G, tp!Wm.format,E >0eCsize2ize)  self.assertEqual(m.ndim, 1) $shape, (6,)(len(m), 6$m.strides, (iitemsizeZ m.suboffset9return m def test_attributes_readonlyo!):(bif notvro_type!skipTest("no K-L .1 tom"2m =QXcheckAwithd.q:m nm, True)writable[w~ K/pMFalsgetbuffer #  PyObject_GetB)) on a memoryview o#.for tp insab = tpu._sourceoldrefcountdys.get*(b-_ 0old=OmOs#tr(m, "utf-8~H_ contents(tp, b, s.encode(: [ s BENonen WGb), S !gcisinstanceHA# Ifs a factory rather thaRQplain ,  DlBinueclass MyView(z__init__o, base*Nd(/ tS?(tpNOpass5R {1 2# Create a reference cycle through V# This exercises mbuf_clear()+%Myw(b'abc' %%lC = M4( b.;myb.o = owr = weakref.ref(oH0 = J: #must be brokendgc.collectI(wr() is i , ; qis exercises memory_clear(). m = MyView(tp(b'abc'))#o#zObject(ym.x = m/ m.1owr = weakref.ref(oH0 = 6INone9 # The cycle must be broken'~gc.coll self.assertTrue(wr() is i , !) Jdef _check_released(=, m, tp):&9%0 = [ RaisesRegex(ValueError, "K"Qwith D: bytes(mBm.to! 8lis\Em[0]  = b'x' ?lenoformat8m.itemsiz wF.ndi* readonlyYOshapVstrides:qm6pas=@# st"pand rep still functiov5In(! ml!",ImJ1p2Equal(m, ,Q6Not"v%_source)=!tp.2test_contextmanager,for tp inj_typesrLb = e b_ as c8JIs(c/?! c# Can  explicitly inside t) * ^ #m.T(wpZ.I+be called a second time (it's a no-opy!e4writable_\ # Issue #10451:v incorrec`exposeIh # buffero causinggfault if Emmap>$tpE!ro+!ifG (yskipTest("no -< o@ to ") b = tp(self._source) Bm = fview(bi = io.BytesIO(b'ZZZZ' 6assertRaises(TypeError, i.readinto, m) odef test_getbuf_fail!): U _L, {}VLhashO# Memory4Ps of `only (/able) types are , and they#1 as(obj.tobE()).'$tpP0ro_Yif tp is NoneskipTest("no-D1 to9"}?b =!BQEqualB(m),b"abcdef")j# Releasing% mQa keepsastoredE value (as with weakrefsR1m.rR&e("@Hasha1forfirst time after it~{d# results in an e3 'V!(r"P_writ) unC>w( mB'\!WCheck/ /psl eL = []def callback(wr, b=b#L.appendDwr =Xu.ref(m,OS*qIs(wr()mYdel m.support.gc_collect<[ |L[0], breversedOaslist = (Am.to)  @&8B)), T8Km[::-1])#issue22668%a = array.('H', [256, 256, 256, s256]) x = memoryview(am = x.cast('B'b2Hc = b[0:2]]d+]6b) Fel b self.assertEqual(c[0], 256y $d$c.format, "H"L (_I m* # Variations on source objects for the buffer: bytes-lik#, n arrays # with itemsize > 1. # NOTE: supportUmulti-dimensionalsis unimplemented. class BaseBMTests(Abstract!):pro_type`5w0gets1= 1h = 'B'AANoneVrplambda )B, b:X.('i', list(b) =1.to(Gjp$)."i'@unittest.skip('XXX  should be adapted@non-zQs1def6B_getk(uOpassrFNotI2Error: to,d) only}s  }1z )pindirec9 levels:P, sliHf& # *PThis m+aant toa alloc subtleties[_R,gWgreturnC(objq:check_contentsD!tpH$, R> obj, tp(,)8S-_*s"XabcdefY"DW[1:7]M2U wB_refF3eAp in.s< !tp"._))oldrefcount = sys.get"(m)8m[1}ertEqual(sys.getrefcount(m), old ) class BaseMemorySliceTests: source_bytes = b"XabcdefY" def _view(self, obj):>Qm = m]#6return m[:7][1:]Pcheck_contentsZ!tp^$, h| .assertEqual(obj[1:7], tp(1) # Concrete test %es P(unit,.QCase,:*!s,OBD26s):Hstructorfor tp in S_type5@ob =!)YTrue(),ject=ob3Raises(TypeError,h5 =$qargumenF>*_Array,Dae|_assign# Issue #4569: segfault when mutating a with itemsize != 1Aa = n.('i', range(10 aOnew_FP9, -1Ma[:] = :"a," S+/5pas>iF i n0'C0s _POtherdB__cast15944: Allow all formats A 1to .icb>est.support.im_module("%" p6(.c_double(0.6))Ld = #H I0d).7("Bl@m[:2! p6 1m[28 p6  9d.value, 0.6) # for format in "Bbc":$with self.subTest(/)'+d = ctypes.c_double()M&m = memoryview(d).caV/J[:2]3*p64"8/2:8 =2:]8 assertEqual(d.value, 0.6) 0def test_P_hex(<# Issue #9951:.-) segfaults enon-contiguous buffers.r9x = b'0' * 20*m1!xv m2f1[::-1."m2G, '3b Lcopy fb'abc'pRaises(TypeError0b.,(m}opicklePprotobrange(H.HIGHEST_PROTOCOL + 1]dumps(m, | ) if __name__ == "__main__o@unitS.P() # l to see if openpty works. (But don't ry#Pit is available.) import os, enot hasattr("b"r3P.SkipS("os.+0() Fo"rclass O3x.CCasecH aster, slave = rTddCleanup(os.close, m?*a)!if@os.i"y( Npfail("S-end of !isAa terminal.os.writeW, b'Ping!-\os.read(x, 1024): X'X'{X`from .j_* """Units zero-argument super() & related machinery."""jszwarnings |{A.sup|echeck_(" CA&f#return 'A'@2amethod5ccm(clsl5,;)j3B(A'8m.f() + 'B{&IPcm(),IC!C return) (cls, super().cm(), 'C') class D(C, B): def f(selfereturnCf() + 'D'2 cme2 {D{3E(D5Dpass3F(Etf = E.f3G(A/QTestSunittest.uCase): tearDown# This fixes the damage that N_various___2___pathologies does.f,nonlocal -0 = st_basics_working.assertEqual(D().f1ABCYgetattrU .fY'V2subYno_override]E E.f(E()unbound_method_transfeF_F.f(Fs_stillA(A, 'A'))/ A-GXGXGX-H=3_inod = D(dVd, (DP, 'B'CDeY eYVe, (EYwith_closure# Issue4360: did not  in a functionCd# contains a aC% E1 snested(Dd"E'&7 hE%~f CPSee iGu #12370XPt5413_x = XK xX'%x.`V, 413+Uu1Lf/Is(X.x, typ with self.assertRaises(NameError) as e: exec("""class X(!__)__7~def f()37""", globals(), {})JCselfIs(type(e.exception), # Not UnboundLocalL x . Y = 42JbEqual(tUs()[".f"], 426del (XgNotIn(N, X.__dict__U@nonl-[TUtest__instancemethod(O# See issue #14857HafE.oreturnuPX().f1X) nU }3@LowWf(clsostatic4MIYd test_namespace = n + return None 4# This case shouldn't trigger the __classcell__ deprecation warningLwith check_s() as w:$ .simplefilter("always", DdWc)@q A(meta j=Meta)ei@staticmethodCodef f(7-%__>self.assertEqual(w.V, [])[*QIs(A,z B = type("B", (), test_ J0B.f-BK9P_mro(4# See issue #23722=H! =^(P$zk # P doesXwork yet...+-__dict__["f"](!super().~ nonlocalL ,q16Is(.3, A>X_expected_behaviour  __new__(cls,#c, base < P_snapshot#_.copym#ais injGQ into2 byuompiler# when at least one 9 needs it, and& be omitted otherwiseMo0[WWithoutCa?Ref EpassbiyNotIn("P" # { zero-arg Q or an explicit`__ reference,0`exact 50 to1`popula3'byG[.C@zfV YE&__f_^U]>p_closurs0.f.l^ 0len4hodI), 1) self.assertIs(class_cell, method_closure[0]) @# EnP the ." reference *doesn't* get turned into an attributeKwith self.aRaises(A)uError):0PWithCaRef.__1__ (def test__missing(nR# See issue #23722Ei`# Some aees may not passoriginal namespace to type.__new__O!We that case here by forcibly deleting D` Meta(dvQ(cls,c, base  6:i.pop('}v', None1 re super()z =# The defaul should continuIPwork %out any warningst check_z() as w6.simplefilter("always", DeprecationWd z|4outB(met=Y){Equal(w.X, [])j zero-argd0 orHexplicit%&__, we expectx# __buil_oemit a complaih Ha__ was set, and ask$if)propagatedL (.In Python 3.7, will beca Runtime(B$edE = (_~$__).* )',;)2 . /1f  CtP__ stgets set despite%(0Is(x).f(),  vyU< isge5ry9ts.catch#/s(]0k> wzd i8%__class__  def test___classcell___overwrite(self): # See issue #23722O6Iing P with nonsens? explicitly prohibitedK Meta(type__new__(cls, name, base pspace, <@/")['A'] =4.return super().}%) Efor bad_ in (None, 0, "", object()1|.subTest(C= 26assertRaises(TypeError37oaA(meta ={@o <BpassOQwrongPPPointM1the reference at Z is alsoQF>_cls =1@B = ("B", ())D1#clp, fqD+__obscure_6 _esOd }1( bRuntim6, f+PxQYdel xLc , iFX~nonlocal)__#KSX().f@_as_Q Lmeth-k+f(Wk = X>)g)UkSgQc = f@closfE_[0].2@, X.<, c_init_leak3# IR6718:"._2 _ 4ed memory if callultiple %s.# This will be caught by regr`.py -RJt)`>NOTE: Despite u\n @ a direct of super.__init__  # is not endorsed.  sp = super(float, 1.0)for i in range(1000):E<".__init__(sp, int, i) if __name__ == "__main__"Dunittest.() import #__multiprocessing from  =0supE| B.PGOqUraise`.SkipTest("B%helpful @PGO" ..installs_in_module_dict(globals(), 'fork')'' Paudios$opbyteswapN$io estruct%ys unau class S'Zj .AuPWrite)s, ,'WithSourceFileJ0 w@PCM8:(,4CasHpsndfileo = 'pluck-pcm8.au'"frames = 3307nchannel2sampwidth = 16@rateA1025n8!48pcomptyp&R'NONE{bressed F.hex("""\V0 02FF 4B00 3104 8008 CB06 4803 BF01 03FE B8FA B4F3 29EB 1AE6 \D,EDE4 C6E2 0EE0 EFE0 57E2 FBE8 13EF D8F7 97FB F5FC 08FB DFFBD&11FA 3EFB BCFC 66FF CF04 4309 C10E 5112 EE17 8216 7F1%12D 49&20D EF0F CE0F E40C 630A 080A 2B0B 5N8B11 B60E 440AD!""PPCM16.)/16/.A/i#2EFFEA 4B5C00F9 311404EF 80DB0844 CBE006B0 48AB03FGE601B5 0367FE80o8B853FA42 B4AFF351 2997EBCD 1A5AE6DC EDF9E492 C627E277 0E06E0B7 EF29E029P5759E271 FB34E83F 1377EF85 D82CF72`8EFB797FC12 0864FB9E DF30FB481183FA30 3EEAFB59 BC78FCB4 66D5FF60 CF130415 431A097D C1BA0EC7 512312A0EEE11754 8207166`FE1448{01298 49990EB7 52B40DC1 EFAD0F65 CE3A0FBEP64B70CE6 63490A57 08CC0A1D 2BBC0B09 51480E46 8BCB113C B6F60EE9 44150A5 24Test(SunauTes*t, unittest.TestCase): sndfilename = 'pluck-pcm24.au'#frames = 3307nchannel2sampwidth'60rat_Q11025n8!48pcomptyp&R'NONE{@not bressed Fbytes.fromhex("""\V' 022D65FFEB9D 4B5A0F00FA54 3113C304EE2B 80DCD6084303 <$CBDEC006B261 48A99803F2F8 BFE82401B07D 036BFBFE7B5D<$B85756FA3EC9 B4B055F3502B 299830EBCB62 1A5CA7E6D99A< ED8E491BD C625EBE27884 0E05A9E0B6CF EF2929E02922<#5758D8E27067 FB3557E83E16 1377BFEF8402 D82C5BF7272x$978F16FB7745 F5F865FC1013 086635FB9C4E DF30FCFB40EEx#117FE0FA3438 3EE6B8FB5AC3 BC77A3FCB2F4 66D6DAFF5F3#CF13B9041275 431D69097A8C C1BB600EC74E 5120B912A2B EEDF641754C0 8207001664B7 7F14453F 80e1294E6#499C1B0EB3B2 52B73E0DBCA0 EFB2B20F5FD8 CE3CDB0FBE1#E4B49C0CEA2D 6344A80A5A7C 08C8FE0A1FFE 2BB9860B0A0,$51486F0E44E1 8BCC64113B05 B6F4EC0EEB36 4413170A5B48""") class SunauPCM32( /32.4rm"BC#92#9C"405"80%E0k$400#FC"80 #92 "60 %34Lz#20"00#C00#40"A06"80!#40#"80%#A0'"A0)E+"40-8L/0;S067003"D857"009#80;"80=L?"00A#60C"10E#64G"A0I#20K"40M2OAQ#B0S*U#F0W"80Y5["80]B|_"80a#B0c"80e$00gi#00k"80mA0o"C0q6su#80w"FFy#40{"00}`T3B27002"E0#804d E13"C090 6344A8800A5A7CA0 08C8FE800A1FFEE0 2BB986C00B0A0E00 \ *51486F800E44E190 8BCC6480113B0580 B6F4EC000EEB3630 441317]V5B48AL """) class SunauULAWTest( , unittest.aCase):sndfilename = 'pluck-ulaw.au'"frames = 3307nchannel2sampwidth = 60rat^Q11025(n8!48pcomptyp&'{CCITT G.711 u-law#Ibytes.fromhex("""l022CFFE8 497C00F4 307C04DC 8284083C CB84069C$3DC BE8401AC 036CFE74B684FA24 344 2A7CEC04 19FCE704 EE04E504 C584E204 0E3CE1fF04DF8PA557C#`FB24E8G2FCEF04 D784F744 9tB64 F5C4FC24 PFBA4 L:A11FCP3E7CF5&BA84FCB4 657CFF5C CF84041C 417C09BC C1840EBC 517C12FCP216F.15FC 7D7C13,[>0DBC F0040F[XD840FP5040CBC 6|A3C 08BC0 r2C7C0B32 8A8410FCm2457-Vpif sys. order != 'big'# .Bwap(;, 2D@Misc+ps(audio;0s.A UPmoduls LowLevel](@def t _read_bad_magic_number(selfb = b'SPAPwith '.assertRaises(EOFError=..open(io.BKaIO(b))"cMd bRegex(Rlq, 'bad  ' too_small_headstruct.pack('>L2', AUDIO_FILE_MAGIC, 20, 0,k  7ENCODING_LINEAR_8, / size too  ._large L!?124"36, 1%0b +\0' * 100>#ridiculously G*wrong_encodingsstruct.pack(1'>L', sunau.AUDIO_FILE_MAGIC, 24, 011025, 1)  with self.assertRaisesRegex(PError, r'encoding not \(yet\) supported'):U\=open(io.BytesIO(b)) 'def test_read_wrong_number_of_channels(Yb = struct.pack(t 4ENCODING_LINEAR_8, 606 'bad # of ( if __name__ == "__main__"k@unitD. () # A simple module forgsthe dis0. f(): passg im c T.mockdrandom$os Dtime Upickl warnings from functools frpartialDmathlog, exp, pi, fsum, sin, factor44MfractionkF class TestBasicOpsgr# Super0_ s common to all generators.m6b4es must arrang1.ge>retrieve RL instanceKQto be6ed.AyAlist)7, n,"""Helper`ipmake a 4B zAs"""q%return [.+!()TQi in F(n)]_autoseedKN`state1qgen.get(%M.sleep(0. U # different mGs atLsj2 g#NotEqual(911, 2saverestore N = 1000Z 4seq& om&(N>ZsZ[)/# should resame seque.J qBseq,F meedarg# Seed value ba negative hashSR0 My1w(objectb" __6,__y U-1729,0argQ[None2A0, 1@-1, 10**20, -( %),AZ3.14, 1+2j, 'a', tuple('abc'),")]c6]fed(arglist(range(3)), dict(one=1)]: self.assertRaises(TypeError, gen.seed, arg)=91, 2, 3, 4@Qtype(bgen), []) z@unittest.mock.patch('random._u ') # os.9@def 8_b_when_-ness_source_not_found|#, A_l)82# RqL() uses time.0() _ an operating system specific&#  is not A. To this on machineseWre itLexists, run the above?,args(), again after 7ingK?() so that it r%^exception expectedzIavailable..p.side_effect = NotImplemented7)/RhufflTs' =] ls%[]4O(lstPEqualH/37J#837]nqs = [list(range(n)) for n inTmge(10)lOd_se<X@cs(3Mi(seq, T0zipss_k en7@), l vw:3set: :9# TKs all would pass ife was a.# no-op.E`follownon-deterministicq coversmH. Ikpd sequence of 1000 dRRnct e0smust be different fromQoriginal one. Althoughh Eathematically a zero probabilityc-Aactu:Qhappea genuinely4dom ,wi co t+negligible, give~ atp number@poss#ppermutas#8pobjects! (factori\'),EPwhich.0conrably largerePatoms7theG0uni6e.. .)m/d_)) shuffle(shd_lst) self.assertTrue(lst != -C%B%oRaises(TypeError,u, (1, 2, 3)) def test__random_argument(!):,r# Test & &4 toc.+R0 = DS.gen.#Cmockrp = unit..Mock(return_value=0.5 q = bytearray(b'abcdefghijk'(YPseq, Yp"_called_with()lchoiceL QIndexei?6([]G>dEqual($50]), 50+%In(`25, 75,[ 0amp7elf # For the entire allowable ge of 0 <= kN, validate that#Csc0 is6Tcorrect length and contains onlyque itemsMuN = 100population =&(Nfor k in'+1os(S6, kL/mmlen(s)(0uni_set(sB/EI&iV)`1}([], 0), []) # edge case N==k==[q# Excep\r[d if siz- exceedsV,&, B_, N+1H,-1_distribu 6l generates@` possiCapermut5:5popn PtrialP10000large num prevents false negatives out slowing normalp /n-expected = factoh(n) //-4%{}hKli q(?4[tuQ0pop{)] = Nonea= if_(DT) == 'YbreakECelse, self.fail() def test_sample_inputs(self):"&## SF bug #801342 -- population can be any iterableYining __len__()N]R.gen.t(set(range(20)), 2+'&0 str('abcdefghijklmnopqrst' _tuple:  Znon_dic\ assertRaises(TypeError, + , C.fromkeys wmchoice& =\?data = ['red', 'green @blueyellow']2Cstr_6R' ((4t#4)# basic functionality^Bfor EU in [:(, k=5), * Gk=5,=Zweights=Bg=Ocum_A]+Equal(len(F), 5X-Ftype.Olist1ATrue] & Q==3range(4), [= -$thH and8UZ?[15Y4f M]2kE= R# TesBht focused on a single element of the population self.assertEqual(choices('abcd', [1, 0]), ['a'])?30, B?b?B?c?!B?d?# Test consistency with random. () for emptyB2GRaises(IndexError):quVs([], k=1LI)weights=U:Jcum_Y15) def test_gauss(# Ensure thatyseed() method initializes all"hidden state. I'# particular, through 2.2.1 it failed to reset a pieceMQ used}# by (and only by)~..10 inq12, 123456, 654321P.gen.F(aUx1 = %z(#y#FEej2j #j 5jx1, x2%cy1, y2BpicklingEyPprotozarange(+e.HIGHEST_PROTOCOL + 1~ G3 = 2Bdump!, X origseq = [iE10)]Rofnewgenpaloads( frestoredj8.hS,Y abug_1727780d# verifyversion-2-7s can be Dfine, whetherAy are create[ 32-bit or 64 /# platforms, ${3{t h.;Pfiles ("2v2_32.pck", 780),))#64)?866)3&7343|p, valuesf = open(support.find((k),"rb"  1*(f{f.close  int(r.random()*1000), value) def test_bug_9025(self):!# Had problem with an uneven distribution it(n*random())EVerify the fix by checking thatJas falllin expectac%s.R`n = 10wrange = U.gen.'k5um((6755399441055744) % 3 == 2 for iY'(ncassertTrue(0.30 < k/n < .37, (k/1B tryPsom.SystemR&/ except NotImplementedError?8_availablFalse else) p @unit.skipUnless(]?, "U not ") class CTestBasicOps( %, CCaseo gep(autoseed Doesn't need to do anythi`Efail-S lsaverestoreo9Raises(,getstateBsB], NonLargs/# /<100MgauslMq_next =pYj>RQEqualOpickling2QRVproto+e.HIGHEST_PROTOCOL + 19= QVdumps,6,to653_bits_per_float# This should pZ0wheqr a C douhas 53 bit precision 0spaMu2 ** 53{ucum = 0C1R|= inP() * gAcum,$,-10bigH e r routinebuild-upIrequired number ofs#stages sohY31osiS are active>0/?rm5elf8(7hj(0 <= r <>b+E|= r<w def test_bigrand_ranges(self):  for i in [40,80, 160, 2011, 250, 375, 512, 550]=Dstart = XP.gen.ml(2 ** (i-2))p3/op2i.if stop <= l Pcontinueeelf.assertTrue(<E ,g2) < Ndef test>_limitCBM(-2,0), (-(2**60)-2, ,<+2)SEqual(set(Sh1)),([6 Q~100)]))d _nonunit_step<?rinHB0In(:0, (#, 4, 6, 8%!22X,<?, 0]errorraises = partit@R, ValueE?,# Empty BbV(3, 3+M-721EW0, -1# Non-integer/ go.14159Uv2.71828# Zero and n],epWQ0, 42_t3w9>0genb>s# Verif.s8\kLF(1, 1000%V05getvkC2**k>{@all f activH1getT @span[41, 3b31, 325>3, 54, 119, 12789ucum = 0b %93|= (!20cum, 2**+/-1rgument checkingM$M(Typ"3; , ZA } ?D@ .`elow_logicb , =log, int=int#`count  sition points: 2**i and 2**(i+1)-1 # show that: k = int(1.001 + _log(n, 2))1 is equal to or one greaterG n the number of bits in nBPfor irange(1, 1000):!n = 1 << i # check an exact pow\:two5!umoF= i+O*self.assertE1(k,6its))**(k-1)) += n - 19 Q1 bel~_e nex" In[5its?+1]True(2**k > n > 2 -Q>> 15 little fartherK  aAnotestronger &io.?1))Q class MersenneTwister_TestBasicOps( , unittest.CCase gerandom.R(N@def 3_guaranteed_stable(A# These sequences are 7Bstay!ame across versionsGpyth-c.gen.seed(3456147,2&=1S*n[<().hex() I4)],g ['0x1.ac362300d90d2p-1', 9d16f74365005 =%1ebb4352e4c4d%a7422abf9c11"quick brown fox"2G1239ddfb11b7cp-3b3cbb5c51b120p-4'68c4f55116b60f663eb525174a27]_bug_27706WPVerif7$at0 1 'cunaffected by hash vization dv'nofar'V1uB( ) == 5990528763808513177Sx88645314505ad*Bafb1f82e40a40p-52a59d2285e97`=56977142a7880p-6'(R('rachel#W-9091735575445484789lf.assertEqu"al([self.gen.random().hex() for i in range(4)],  ['0x1.0b294cc856fcdp-1', 2ad22d79e77b8p-3'=%3052b9c072678p-2=578f332106574=5]) |seed('', version=1)# hash('') == 0<assertEqu/b0580f98a7dbe84129978f9c1a#aeaa51052e9092178fb945a6def test_bug_31478( %):] # There shouldn't be an ion failure_!.R.OG) inNcase the argumentX a bad __abs__() method.8class BadInt(int= return NoneV6try%<o%))1except TypeError>BpassUW.82WVerify thato0 1 ys are unaffected by%h7domizatioTAwhenT> expressed as bytes ratherqn stringsaf(b) values lisPython2.7('# which w0u|Bing.f|b'nofarupu5990528763808513177|28645314505ad7o`afb1f82e40a40p-52a59d2285e971=56977142a7880p-6'krachel-9091735575445484789Fmbb = b'\x00\x20\x40\x60\x80\xA0\xC0\xE0\xF0'|/(b JbC501559423974936549Z.hex() for i in range(4)],  ['0x1.52c2fde444d23p-1', 875174f0daea4p-2'=%9e9b2c50e5cd2=fa57768bd321c=1]) |def test_setstate_first_arg(self):' .assertRaises(ValueError, Dgen.I, (1, None)romiddlesQtart_& =cg%()# Wrong type, s/b tuple  ?Typ 2)iblengthk?625i& 2*O2,3)m of 625 intsy('a',)*625{Last elementR anr_ alsov+0t"4+{between 0 and 624Bwith  Overflow)"((04+(wN>-1,v# Failed calls to n() should not have chgad the C.5{bits100T@randF(100: s 'QEqual>.89getZ , ed# Little trickamake "(x % (2**32) for xEinternal')"Kr wp. I canPthink?a simple wayoachieve this, # I am opting~ us a generator aseQ argu4%ofwhich attemptciPa NaN6ger _vlsU()[1]a.Xlist(X[-1] = float('nan'( = (int(xW:elf'JreferenceIYQation`# Compare python 3 results fromoriginalw# code. Create 2000 53-bit precisio2dom3s-GonlyKthe last ten ent$ries to show that the independent implementations  # are tracking. Here isAmain() func6p neededi`create%Jlist of expected random numbers:+ void b *){i;+unsigned long init[4]={61731, 24903, 614, 42143}, length=4N@_by_array(0)/for (i=0; i<200O++)  printf("%.15f ", gen_res53()b if (i%5==4)C?\n".}!= [0.45839803073713259,9n0.86057815201978782)9284833172678215)359326811QO2461R081823493762449573*1433222647016932084297823823520024S5381486467183145|0892150249119934078486196105372907] uself.gen.seed(A + (P<<32)q614<<64 e<<96))Eactual = NZ om(u)[-10:]-0a, R zip(=,) SassertAlmostEqual(a,e,places=14) def test_strong_reference_y(Tgb# Like;4I, but checks exact bit-level0# eity. Thisuld pass on any box whC double contait least 53isprecision (] underlying algorithm suffer^no round(errors -- all results%).from mathort ldexpk x0eab3258d2231fx1b89db315277a5&db622a5518016&0b7f9af0d575br029e4c4db82240L4961892f5d6x02b291598e458x11388382c1569x02dad977c9e1fe191d96d4d334c6Eq, expected):' self.assertEqual(int(ldexp(a, 53)), e) 4def test_long_seed(?!):U&# This is most interesting to run in debug mode, justmake sureK@noth:)blows up. Under the covers, a dynamically resized arrayKis allocated, consum[space proportional`number of bitsKn fortunately, that's a quadratic-time algorithm,Jso don't t9horribly big.+l = (1 << (10000 * 8)) - 1 # about 10K byteP.gen.B( 053__per_floatshould pass whenever a C double has 53, precisionpan = 2 ** 53ucum = 0Pfor i"Prange[_1 |=Wrandom() * span)NAcum,$,-10bigHVt e  routine build-uprequired : stages so*30osis are active>0/?Ar = (7h%;True(0 <= r <>b+O|= rw)_^s~[40,80, 160, 2011, 250, 375, 512, 550]_startZ(i-2)Ostop2i.1if 11<= l vcontinu _<c ,g)_limitC^B\[(-2,0), (-(2**60)-2, ,<+2)S /Aset((h&))([6 Ql100)])0gen 1# Verify cross-platform repeatabilit(12345675get97904845777343510404718956115lk@(1, ebits(k) < 2*c*k)  # Verify all bits active!1get= self.gen.getrand'for span in [1, 2, 3, 4, 31, 3@2, 53, 54, 119, 127859]:Nycum = 0ficrange(100)593|= ()FassertEqual(cum, 2**+/-1rgument checkingQMRaises(TypeError,3;_, 'a'@*A OValu ?, 0?+_def test_Kelow_logic( , =log, int=int#`count sition points: Pi and u(i+1)-1# show that: k =d(1.001 +zf(n, 2)`# is e, to or one greaterGn the number ofsns M, 10n = 1 << i an exact pow\5twoVvF= i+*t.!k,6its))w**(k-1)8+n += n - 1 01 b2/ex"sIn(k, [?+1]True(2**k > n >2 k- i -Q>> 15 little fartherK aAnoteXstronger &io.?1))QP@unit.mock.patch('om.Random.overridden #om8_Y W-K() can only use 9b() whepbuilt-i$# has been but no newBK() method was supplied.R(!om.side_effect =r.System#()?pmaxsize"<= maxsize8self.gen._randbelow()4+1,4 >:O56405 # issue 33203: test that  raises ValueError on # n == 0 also in its getits-independent branch.=Qwith qassertRj(j%):,\+ =(Q# This might be goingbfar toa single line, bu,cause of our# noble aim`achievSB100%Mcoverage we needfwrite a case i<which the followLIhRandom)Ys executed#6rem8 % olimit = R - rem) /XH =Hdom(Qpwhile rN' r7 # <== **gaz ** (z- / exp(az) * * fsum([O70.9U5183,676.5203681218835 / z -1259.139216722289 / (z+1.0)&771.3234287757674%2%-176.6150291498386&3&12.5073432400905%4%-0.138571033129652'5'34937113930748e-0K(z+6*1659470187408462e-0T7*]) class TestDistribu;s(unittest.CCasea_zeroinputs(# Verify that dW can handle a seriesM N'g = random.R(9dx"g.() for i in1pge(50)]f0.0]*5R1 = x[:].pop; g.uniform(1,10c^ -paretovariate(8_ ?exp0wweibullc/, hvonmises9Unormap?0.0pogauss(/0logi8 91o14mma71 6/20op; g.betavariate(3.0, 3.0) g.random = x[:].pop; g.triangular(041/=>def test_avg_std(self):]# Use integration to1 distribu average and standard devi4.OOnly works forF s which do not consume vas in pairsNBg = !.R(N = 5000-x = [i/float(N)~iTrange(1,N)]-x, args, mu, sigmasqrd8[.)(g.uniform, (mP10.0) 0.0+1.0)/2-**2/12),I/, p, 4.0/97 0/18mLEexpo(1.5,), 1/ /**vonmises>@23, `pi, pi3Wparety05.0y5.0/(5.0-17G /0A**2* ?2))=(g.weibull-, gamma(1+1v x222-A5& ]+1 yg3kglen(x)$:tryly.append( (*) %except IndexErrorP6pasc8s1 = s2 = N ys1 += e4 s2(e - mu) ** 2$y.assertAlmostEqual(s1/Nplaces=2 msg='%s%r' % 7.__name__ @@2/(N/, A%Ltant 12, expecteQ(", -4: `'inf')xqb@)q^(g.gaussfulognormz6 (g.lognormv ariate, (-float('inf'), 0.0+ (g.normalv>D10.05 /),6fpareto6 s@), 1u9mweibulp@?@ 6)]:for i in range(N)self.assertEqual((*args), expected) [def test_von_mises_]I`# Issue 17149: von . `s were not consistently1thek# [0, 2*PI].0g =dom.Random()uN = 100  mu]@`0.1, 3:6.2*Ukappa-2.3, 500.0*._*a'sample = g.vonQ(mu, p2VUTrue(!S0 <= h<^TWOPI5lmsg=("{}, {}) produced a result {} out"X@" of#geppi]").fyt,)Yalarge_( _#`1` W) was hang Jhsr6 v0, 1e15( ,00Sgamma~_errorsBoth alpha and beta must be > Rapp(ValueEY,ht0, -B nA*O2, 0A*S1, -3[P@unitu.mock.patch('.'t_full_code_coverageE_] c Thare three different possibilitiesqthe curimentation# (), depending on Lv1'%'. What w go5ato do is to fixGs returned by2W() togenerate cases trpprovideNt% line =rmethod.S# #1:>: we wantSfirstp number be\sl [1e-7, .9999999] range, so that the continue statement executes # once. The values of u1 and u2 will be 0.50.3, respectively.Krandom_mock.side_effect = [1e-8,D&3]3eturned_{2 = D.gammavariate(1.1, 2.3)7 self.assertAlmostEqual(rN4E53) 6# #2: alpha == 1: firstt number lessCn 1e-7 tPGbodyN!offwhile loop^Tn^.2() ws 0.45,Nwhich causes Tqto stop\1ingalgorithmerminate/450, 3.14!0731416612380c3: 0 <0< 1@is i e  complex region@codeXcoverFa7re are multiple if-elss. Let's take ab"k 6PsourcG1de,}1detnepat we need accordingly:J 1u(a#b = (_e +$G)/_eP#{p = b*uif p <= 1.0: # <=== (A^@x = p ** (1.0/! '?FBF-_log((b-p)H/u1>CjiA<= x -9)D:[break,%elTw_exp(-xJEJ FV beta` Fo,,@wantbe True. ForyM)%b*F\rYF / b# We now getSesecond)bbranchhere, sinceQs0(C) Fab6"weWXYN2(E)ixLbZd:f 'r2V&r2() *a(b*r1)h)V%_e|.%xp$5loge= 0.35P 4pha)/_e  epsilon = 0.01 !r18859296441566 # 1.0 / b'2'3678794411714 # _exp(-((b*r1) ** (1.0/alpha)))f# These four "random" values result in th#llowing trace:$# (A) True, (E) False --> [next iteration of while]<F;) loop breaks5_mock.side_effect = [r1, r2 +W", =eturned_2 = N.gammavariate()u, beta) self.assertAlmostEqual(rQu, 1.449I7544pLet's now make;"be4. If this isscase, when we get to# second if-ev0'p'= greater than 1, so (C) e@atesHkG. WeM`encoun=a] statement, (D)0ich0ordho executNmust satisfy4 foBiFqr2 <= x -#<= (-_log((b-p)6;9L)h0 --eAthat"is]r944540040889814P# And'aB) andRDN/ [5830349561760781@unittest.Kspatch('R  '@def 6_2_`_zero()(, Q)<2() > s ?rG distribu/O#[p uses iUnallyKHBsame.; .~50.0-D0.0,32.71828, 3.14159eclass TestModule(pCCaseRMagicConstantsH" NV_MAGICCONST71552776992141GTWOPI, 6.28318530718<@LOG4z38629436111989>assertAlmost:Equal(random.SG_MAGICCONST, 2.50407739677627) def test__all__(self):#s validity but not completeness of the DU listBQ.assertTrue(set0P) <= 3dir,))_subclass_with_kwargs(c .SF bug #1486663 -- this used to erroneously raise a TypeErrori# Sr!.R^o'Fr__init_C@, ne[=None-1M.;){L1P@unit.skipUnless(hasattr(os, "fork") () required"]@p_after_.EATestrglobal  instance gets reseeded in childr, w = os.pipe(y2pidw1if E= 0:F1#Z process:try-1cval = c0get bits(128p*J open(w, "w") as fV,f.write(str(val)Nofinallos._exit(01Jelsee# parentos.close(wC_r, "r_Xeval(f.read(u2NotzBval,@pid, statuswaitpid(-^[9, 0) if __name__ == "__main__"Q() import builtinso dselectUsockeMerrno fromG3no ^EEXIST 7!OSP(Npass%WithInit- , message, barS1Pbar =$vsuper()b?)?Newnew__(clsz6 = p31bazzpreturn Combined&First(Sub[>,3NewvT?NewSd a^" !An>0ExcA`WindowF(False(os.path.2s3's.unlink.,g : AttributesTest(unit.bCase):w9,org`if os. == "nt"OqIn('win]t', dir(LB?NotE e_posix|Y already ", "foo.txt^#pEqual(e2Bno, L*args[0],1str.?, "h Equal(e.winer@ror, None) @unittest.skipUnless(os.name == "nt", "Windows-specific test") C1def _errno_translation(self):i*# ERROR_ALREADY_EXISTS (183) -> E/e = OSError(0, "File already exists`foo.txH>|.assertEqual(e.wineN/, * ,Targs[0],3strh @file4, "blockingiof ~` = ("a6bcd&e"~for n in range(6Bk"IO*]F[:n]F+Wwith 5Raises(Attribute= _8e.characters_wrn3yW', 2xE = 5|S5) class ExplicitSubingTest(xbCase):_mapping# When constructing an/# sn!, F F isn't doneO4Subip, "Bad u descriptor$ Is(type(e), I init_overridde WithInit("some message?bazobar, "',, `)0kwd/ Obar=;?newlsrObar,'z' def test_init_standalone(!):$2# _#_ doesn't propagate to .&(see issue #15229 1UWithSxVInit(+ %str(e), '') if __name__ == "__main__"@unit.() """Test the secrets module. A Qst of functions in- are thin wrappers around .@ def$ elsewhere, we doW@needRem exhaustively.Tmportt" istring # === Units class Compare_Dig $s(J.CCase #.c=d=Q.""" =aePKW` Fality with > (byte/text) !s.fLAfor @("a" cdwxyz123"u-a = s*100?b0Tru W(a, bP:.encode('utf-8'), b+))P!unR@T OFals@"abcmWabcd"@bA Bxb mn_a1b2co + "q"k ! abad_typesLthat<braises50mixLB''%e'! P isin! ce6str"0b, s$eRQ(Type4, S!, rC"Lb, a<FboolT # Test that compare_digest returns a bool. self.assertIsInstance(secrets.E("abc", !),J)J+Exyz"J class Random_Tests(unittest.aCase):s0""" wrappers around SystemC methods.""" 6@def N_randbits(S!# V)errmsg = "C(%d)Xaed %d"bEpfor num` in (3, 12, 30i(i"{range(6#Dn = y\|*True(0 <= n < 2**5#, 5% (;n)) Achoi 'lfitems = [1, 2, 4, 8, 16, 32, 64]1 q(h)1  Oelow ?2, %InlBi), &i)Raises(ValueError,?, 0<(D-1) =_Token<t, function'"_defaul-p**N handle = size correctly_NVbytes.Ehex,Q.(durlsaf/%Qwith 0sub(|=.aname =0.__-__|2try6U(except Typ= fail("%s cannot be called no argument" % o NNone47` DEFAULT_ENTROPYbEqual(le#(f1)),d?5hex= 2* gQ&" n17[ V.7n=nb3# token_bytes(n), bytes) self.assertEqual(len(secrets.token_:(n)), n) Bdef test_"@hex(I!):cu# Test .for n in (1, 12, 25, 90<@Pwith T@.subKK(n=n$(Js = n IsInstance(s, str. _), 2*\ True(all(cstring.hexdigits )KurlsafeO $SPlegal oascii_letters +o+ '-_'1, 28, 76k'(7  e Z if __name__ == '__main__'@unit.a() """the linecache module """ importPtos.pathtempfileYize fromJ Z0supb FILENAME =o0.__G__ NONEXISTENT_* + '.missing' INVALID_O'!@$)(!@#_1' EMPTY = '' TEST_PATH = @.dirF(y) MODULES = "$abc".split("J) SOURCE_1r' " Doc3@ " efunction(return result '''F2F7 01 + 1 a = f()8383''' # No ending new class TempFile:\setUpsuper().pX`.NamedSPoraryX(delete=False) as fp$ p. %rfp.writW.._mMaddCleanup(.unlink, ?c)pGetLinesGoodData(!# 9list = [' \n', 'ofBgood _s\n'][ [@.joi"lfp).encode('utf-8' AM(@_get 1.op=p$aindex,*enumerate(fp1Rif noxP.endsx_('\n',4 += '\n'  cached_line = @.get (self.file_name, index + 1) G +assertEqual(A!, Pb!) 5def test_esf!):J9s*}1s, list) class GetLineTestsBadData(TempFile!# 8byte_string = b'Bad data goes here'  Raises((SyntaxError, UnicodeDe%), %\1qM PEmptyv(1Goo`, unit-.4CasU = []aSingleUU)F'\n'YU*á\n', 'bbabcdef $á z?Bady" \x80abc'1&C`/s(o   # >values forq number should return an e {Cfy (FILENAME, 2**15), EMPTY#:&-17r# Float currently rQ Type,5it?=0&, $1.05sa#%', e VINVALID_Z:# Check module loadingentry in MODULES| = os.path.join(-q_PATH, C) + '.py'^@with open(JA) as i-,|in enumerate@, !#, :!}F$that bogusCSisn'ted (issue #1309567 s('a/b/c/__init__8rtEqual(empty, []) def test_no_ending_newline(self):&* .addCleanup(support.unlink, uTESTFN)8with open2", "w") as fpfjfp.write(SOURCE_3M@s = cache.get s^3ssertEqual(/, ["\n", "Bf():return 3\n"'Qclearz ed = []for entry in MODULESilename = os.path.join(-b_PATH,C) + '.py'^v.append(fN$(-(3, 1(# Are all H!s 4%d?pJ#NoM$QD`_empty0fn  fn if fn not@r d[u# Can we B theg+\ 'in7wyQcheckE Rreate a sourceB and its contents6+_y  gxMMQ, 'w'  1R('o Keep a copy of?old@listaindex,enumerate@O /, ^V + 1)D2S# Try to updvCbogu+e.y'dummy'SCQ that4 matches~_ %2# Ubnwhether it8newL# enumerate(source):  self.assertEqual(line, get !(s8_name, index + 1))H)list.appendJ!) *def test_lazycache_no_globals(y@s = ,.s(FILENAME%Qclear0([ gFalse,\]g, None EusE_smokeNONEXISTENT_$, <. ?Tru ma1, len [R]%# Note here that we're looking up a nonexistent file with no#' : this would error if the  value wasn't resolved.G) provide_after_failed_/up"E5A!c[1f;(2uoupdateWx_checkb m.  {H(Dbad_ 8(''{D[I;already_dD- + uI4Hamemory; lines(FILENASME) self.assertTrue(linesdef raise_memoryerror(*args, **kw %):OV0! M0E0with support.swap_attrtcache, 'update.',{ k@2 = 5@.get s(FILENAQEqualy1s2,>5s) ANQclear (C3+V3, []" if __name__ == "__main__"unittest.P() im Dmath sys from 8 1 # Skip this pf the _-capi module isn't available. B.Q!_m'%('9"')v{0get_keywords, _only # > How about following counterproposal. Talso changes some ofG other format codes to be a little more regular.8 Code C type R[` check b unsigned{r 0..UCHAR_MAX!#h short SHRT_MIN.. &BGqnone **BHD6k *Plong 8I1int2INT! #% i  !l PBLONG ;K`+L@L<c G`Notes:Ri * NewA** C!d previous "r-and-a-half"" ";=[ %Q!wa`particly useful.(Plus a C API or two, e.g. PyLong_AsUMask() -> #?and3 75' #D (i at exists). LARGE = 0x7Ff VERY_FF000012?42 4, U3, U2, UEAX, \BIN, # -PY_SSIZE_(,  Ds; #FL4 0DBL!, CAX _EXP = sys.float_info.max_exp INF = ('inf') NANPnan')zPfake,7y are not defiin Python's headUUiles  = 2**63-1IN = -2**63 ULL$ONG_MAX = 2**64-1 class Int: def __int__(self)return 9951SubAC(int+B?Badz41.0{92rJTrue;3@,IFloa.f0D4.25|;486Opass&(2('q1Badt)> 4687= g> m)N3UxComplexc  T+0.5jDA **2(+3BadY1XB  v%3"=bUTuple!tzEDict%4dicn8K Unsigned_TestCase(unittest.[,_b`from _capi import getargs_b%B# b Cs 'uy char', and does range checking (0 ... UCHAR)Ol .assertRaises(TypeError,~o, 3.146Equal(99.(Int())/0.b6 (pWwith Warns(Deprecation3ingW21g2232qOverflowu/-1D0 :r@n + 1) rtEqual(42, getargs_b(42)) self.assertRaises(OverflowError, 8, VERY_LARGE) Adef test_B(H!):Z`from _capi importLB(# B returns 'unsigned char', no range checking7n KTypeB, 3.14Equal(99B(Int()/0.Subclass6Q2BadqWwith Warns(Deprecation7inggk21g22 232 eUCHAR_MAXm/-1?0* ]: 2+(42+T' &@& 'H'H?# H'_short(/H(H(.('2H, ((@"H(g(2(JSHRT(/H((/H(( ]U3 (%H(2(HG b5 & b)&H("))I)I?# I)/in'0I'I'.''I'h self.assertWarns(Deprecationwing): self.assertEqual(1, getargs_I(BadInt2()))6 202323UINT_MAX:/-1e0* \8 1+(42_42)) -VERY_LARGE & a@!Hdef test_k(w`from _capi importk# k returns 'unsigned long', no range checking7$it does not accept float, or instances with __int__>URaises(TypeErrork, 3.14Y6 OInt(k(IntSubclassp :<mtkm;JLONG</k(</k(< ]Uu2?/k(?P(@! S_TestCase(unit6.Tjhjh6# hjshort', andG h (SHRT_MIN ... /AX hB`&99 h /.:'2h, :,y,h6g>hOverflow#h,OIN-1s(INI $h-/AX8erflowError, getargs_h, SHRT_MAX+1) self.assertEqual(42,5_(42)),Raises(OverflowError8, VERY_LARGEmdef test_i(t%):W`from _capi importi()# i returns 'int', and does range checking (INT_MIN ... /AX KTypei, 3.146*&99i(Int()-/0.Subclass6c2BadqPwith ZWarns(Deprecation7ingy21g22 232e9"i,OIN-1z(IN #-AX6/AX6PiP$iP lPl6# lPOlongQ ELONGR SlSlS.S'2l, ( S@"l(gS2S%2l, T %$l($W8X#Y lY nYnYnYPy_ssize_:(PY_SSIZE_urror, getargs_n, 3.14) self.assertRaises(TypeError, getarg6_Int()7wEqual(0.(IntSubclass()6m ?Badp:2k3OverflowPY_SSIZE_T_MIN-1$ +1 2h*/AXD/AXD<oAX+1) (42/42s$VERY_LARGE) 5P Long_TestCase(unittest.!):@def 0_L(`from _capi importL>(# L returns 'long ', and does range checking (LLONGDC... /AX|_L"L, "Hello"o&99L2/.'2L, [Wwith uWarns(Deprecation7ing1g 2%$L, (IN.%Lv#/L(#9L, KKeK 'unsigned[', no;tK"?K, }KV'KV etargs_K, BadInt2()) self.assertEqual(0, getargs_K(Ba1o3())) 3ULLONG_MAX<o0*]/+1 (42/42- VERY_LARGE & cB#J class Float_TestCase(unittest.!):=Gdef kWithSign(, actual, expected5!  ,`+math.copysk1h=), z!_f`from _capi import8f[f(4.25), 0-0Raises(TypeErrorfb?+0j9!()k/2531Sub @(7.5>p=2>  1BadNWwith =Warns(Deprecation7ingD!fD[%73"for x in (FLT_MIN, -  [ INF, -INFVx), x3if X` < DBL7 &00), 6 -78BIN >/IN :]wIN), 0.%>?-@ <0 v6g!,  6r =EF(NANS#NoCr, r@@sup.requires_IEEE_754]_rounding@3.40282356e38),b T-=dd self.assertEqual(getargs_d(4.25), # _self.0-/0),Raises(TypeError, hb?+0j9 qFloat()k/253Subclass(7.5>p=2>  4BadzWwith TWarns(DeprecationUing):32 f2%73ufor x in (DBL_MIN, -  $AX INF, -INF_x), xVOverflowA31<<O_EXPD#-ElWithSign*`0.0), 1 6-1!, 86r =O(NAN#Noar, r) >def test_D(}y`from _capi importfD>V D S+0.5jy :51D(400D(Complex:+0.25j)), 7.5  K*?LcD, Bad\&() 8=&D(h:J>AGM5Sc = cWx, 1.| Vc), cO.N91.0 U+D(N * $D(0io).realEIFJ ithSign(getargs_D(complex(1.0, 0.0)).imag # self.assertEqualWithSign(getaI-J  class Paradox:\ "This statement is false."def __bool__()7raise NotI>tedErrori Boolean_TestCase(unittest.Nf,_pd`from _capi import p6(0,& (F/)).ONone-0*/0jW/''+/()+/[]+_{})) 1?Tru[ -1 *[ ,[ +/'x\ ,?(1,^ -/[1_ ,@{1:2b  .bR/s(,+(>_Tuple_.MPret =_(1, 2Rret, %&Is(type(ret), tlo*(2, 3 r)u *[]7*1Sub(}~Uh#InO(), (In(!, 5*IMz< from _testcapi import getargs_tuple Zret =(1, (2, 3))' self.assertEqual(ret, (1,2,'(# make sure invalid r arguments are handled correctlyBclass seq:def __len__()#return 28sgetitem<?, n?aise ValueErrorGoR$Rs(Typ$,:@, 1,R()) Keywords_TestCase(unit.0_kw `from _! 0(a=1, b=2 P{'a':'b': 2}0pIs(type), dict){ 2**{R, 'c': 3ZY 8 **DictSub(j} 1(hnc, ({}, None(In(!, 4 ?**{I|:positional_# using all +9sd/ku(), 3, (4,(5,6)), (7,8,9), 10),@, 4, 5, 6, 7, 8, 9- ,Y_mixed3nd ?Uarg4=_arg5=:"&Sarg1=parg2=3,''3=M?opt 1mis' p, skipp = -1, -1, -1, -C1, -W10) !) def test_required_args(self):"4$#  arg missing6try,00getG_keywords(arg1=(1,2)except TypeError as errJ.assertEqual(uhstr(err), "function ument 'arg2' (pos 2)"?lse{ffail(' should have been raised'Otoo_manyO0+ ,3,(4,(5,6)),(7,8,9),10,111F"5takes at most 54s (6 given0Htinvalid2extraneous VSarg5=10,arg666=666M8_666' is an S for this Gsurrogate\;F 3,   **{'\uDC80': 10}O9o\udc80Olrclass KOnly_TestCase(unit?.5W@posi/al 0# uJ all possible 4s  t_only(1, 2),B0 ?mix H and.,N/=33 !rl"*b=1, op/=22Ov4/, skipping tsuples self.assertEqual(!getargs_keyword_only(required=1, optional=2),:(1, 2, -1)y,/=3}V-1, 3o!) def test__(!):"-1Dn$# arg missingWwith RaisesRegex(TypeError`r"funcN ctument 'v' \(pos 1\)"jni]*~ dtoo_manyd+takes at most 2 posi al|s \(3 givent3+q/ 34!), q5qtinvalid # extraneousJ)"'monster' is an ` for this 7dL=666surrogatei "'\udc80J **{'\uDC80': 10}) class POnlyAndKs_TestCase(unit.T`from _capi import b&5_an,Ds as( 6-0# uK@ allPsible st8E3), _mixedQ#u$nd args  self.assertEqual( getargs(1, 2, keyword=3),  3)) def test_optional_9F!):"&# missing ' ' / {O-1))9 N-1, required Y $# VR posi HwithRaisesRegex(TypeError,/Q`r"funcT takes at least 1numents \(0 given\)"Ly wcempty_ "'' is an invalidL for this Q C**{'': 666}) class Bytes_TestCase(unitK.cc`from _4capi import %_c2\W/, b'abc') # len > 1C(f(b'a'), 97.ytearray89 memoryviewGB ?'s'5 4 CNoneVyy0y, O\xe9 b#b' sCValu>y>onul:\0t$;!'I  K!__star4ON44(L .assertEqual (getargs_y_star(b'nul:\0'), # self.assertEqual?ytearray(b'b !')MPmemoryview(b' RSRaises(TypeError, , None) <def test_y_hash(!):`from _!capi importP4-<' 4, 'abc\xe9')@ g4]sXs=|N P#w# ) modifies first and last  L-t4 L@?%# 36s')Qbuf =J=q A(bufY[i] Ibuf,r6 ^ X57K class String_TestCase(unit.C CqC') # len > 1B @C('a/97 -`\u20ac2 0x 6U0001f40d: ; b6 Ka=8C,  self.assertRaises(TypeError, getargs_C, 97) self.assert4 aNone) 7def test_s(>!):P`from _capi importzs(7udEqual(s('abc\xe9'), b c3\xa9' LValus, 'nul:\0; #s{_bytes:!ytearray(b'D /') memoryview(b' K!__star4( D sM{0 "P RSs*/, Ohash4d(-D  C %,  N P#zzz z z&z u;:2?z,  Is z()6z4 gs_z_star('abc\xe9'), b'a c3\xa9') self.assertEqual(getargs_z_star('nul:\0C >rb'bytes> =ytearray(G !')LPmemoryview(b' RSlIsNone1)) 1def test_z_hash([!):m`from _!capi import o4-<((&D Raises(TypeError,%,  N P /es/esq e/es+@, 'latin1n!GUnicodeEn Ees, f Oscii9NkLookup GOspamF )DoERT*pV*A*E1/ett@/et,@.t0e9' $ G ts}sC, b'bytearray'3) 'self.assertRaises(TypeError, getargs_et, memoryview(b' '), 'latin1'V ONoneA*'nul:\0'E*bF3ytearray(P tdef test_es_hash(!):`from _"capi import5.=eEqual()('abc\xe9b oc3\xa9E e#, O\NUnicodeEn W", e9_asciiSlLookupLOspamK Ipb'bytes$JT%9%Y6[-,%) ,ebuf = (b'x'*8Dj`, buf)pPIbuf,4\x00xxx')<5 @4NMValuc VOx'*4K@iti!5J i)i, E&i t_hash, 'abc\xe9', 'ascii') self.assertRaises(LookupError, getargs_et_hashA`bc\xe9LOspamKkEqual(=(b'bytes;latin1'), HytearrayR L'WOTypememoryview(b' j[$eNone, F|'nul:\0DEJ7 `buf = (b'x'*8&'aQ, bufSPIbuf,4\x00xxx')<5 D\64OValuc VOx'*4K@def test_u(!):`from _capi importu(7 %u()4u, ; uR:s}:D~DI   )p4( ?'I'? self.ass#ertRaises(TypeError, getargs_u_hash, memoryview(b' S')) self.assPaNone) <def test_Z(C!):U`from _capi importZ(7zdEqual(Z('abc\xe9'), :LValuZ, 'nul:\0'Z, b'bytes:!ytearray(D rZ IsD)4} (?''?3N} E( class Object_TestCase(unitv.SSUobj =%IszS(obj), +0S, u1=*S, 'str1S, c uYxYx&Y&Y;&Yx#Yx"Y"xUxURxCfUf&Uf targs_U, bytearray(b'byt S')) |cufffd\n8b10")m F"\x}J VPPignor u)s0"""1R case op Nick Mathewson 2/ is_jythonYcompile_command, PyCF_DONT_IMPLY_DEDENT!ioTs@ deffy_callables(dbU0n,vtd.itemsZif hasattr(v, '_I7__'E'd[n] = True}return d opb$s(2a9YV(j, str, symbol='single3'''@ iff."a APpieceu"''9if D code = compile_command(str, "", symbol) self.assertTrue(code"#if9 == "single":EPd,r = {},{}saved_stdout = sys. * = io.StringIO(q>tryAexec>, d7".&%N), r=ofinallx )elQn'eval'0ctxOn'a': 2Rd 'value': E^ctx) 0 0/ Equal(unify_callables(r),&d),Jelsepexpecteu , PyCF_DONT_IMPLY_DEDENT] U $, !) Bdef  InDPlete(^ , "='&')'''succeed iff. is the start of a valid pieceZ1'''z=), Nonel, is_syntax=1An in` O  fail("No exception raised forG",! SVErrorZ COverflowE6notPQtest_+h avlV# special case3if kojython uE""),Lg 2y("pass"-B Sf)\m/\nyGav("~Wa = 1*/\nAN, #\nF\n\n") av("def x():\n pass\n") !@if 1 A\n\n"= ^ A/\nD"! H$ l:A3**3O +pif 9==3vHelse(  U > p#a\n#b\na = L^ \na=5K9+ \\\n3") o{","eval(lambda z: \n z**3)) D\H/\n?Fa**3 \n/ " `@ = 1 4 a= = _IRdef fCtry:X finally: [x for x in (1,2)]CM#foo&@a.b.c\n.qtest_incomplete(self):@i = .assertI*i("(a **?,b,(" ){=@b + /("" <' KiPJY/1:ZI95"O s&ai S? 5lgkYX?\n ]A* #h K <O'a\\L''xy"8i("Y(/(\n","eval")  ai("(9+","eval")  _9+ \\lambda z:" >if True:\n  \n") 4;@a(O@a(b,c+ efrom a import q  } ^4 !C J[");a,b) O{'{`>{a:%:`A{a:b`c?/,cVO,c:d/d^ #" a( 6,b,'c~+a[G,a[.a[`>[b:8:s0[b: d Mdef   1 +(a (a4e<(a,' [@if a pass\nelif 3$4\n 4 see W`while = 0for nC 0try5_xcept# ofinallGW4 ?ith2 as 2^class3   ) yk[x for`@ x iI L(LLLtest_invalid(self):h0 = .assertI' @("a  @Na b !** <-= =_= 9 +-x():\n\n. "\n\n if 1: pass\n\npass") ai("a = 9+ \\\n")_'a\\ 1 21","eval5(]?())/[}/9+lambda z:6a b return 2.3if (a == 1 and b = 2): _[del 1?O(1,)?[1]<'1'[i for i in range(10)] = (1, 2, 3^ def test_filename(self):  .assertEqual(compile_command$1\n", "abc").coN,HL H @, 'single'J~/No'Ztls_active = False^ starting"# def collect_incoming_data !):+.append(% %PXfound6E0linb''.joinj.U(@str( , 'ISO-8859-1? \`cmd = >.split(' ')[0].lower(l@spac+Afind*2if "V!= -1 arT9[$F+ 1:Oelse1(""^qhasattr , 'cmd_' + cmd9nPmetho?get2Y1F(arg.-ERR unrecognized POP3 command "%s".' %handle_erroVraise+fp!, 9Aasynq | ..encode(" p") + b'r&')gCCechoSj# sends back the received str%(used bytest suiteC1Z w2use , w if != "guido"T"no such P M1password required!opython `wrong Op10 messagesOstatl10 100>?lis>NR%s %s' %  7+OKo LIST_RESP`uidl =_ 1%re 1 p%s bytelen(RETRh33topOdele marked for ;\tion.OnoopTdone nothingE/rpE0aE self.(push('+OK done nothing.') def cmd_quit(self, arg):!.ECclos@"pe_when_h(__get_capasa\b = dic~u.CAPAS)~ if c tls_active and SUPPORTS_SSLW['STLS'] = []Qrreturn #  Capability list follows'for cap, params in2{.items(:>0_ln6cap#ifT _ln.extend({ '.join(_ln))! HOutf8EI know RFC6856'"ifenable_UTF8&else '-ERR What is *$?!+if*E2stl }is FalseaqBegin TLS negotiation'`context = ssl.SSLC(s'+ .load_cert_chain(CERTFILE2tsock = =Pwrap_eu ,jserver_side=TrueA do_handshake_on_connect=_Nsuppress_ragged_eofsK0del?Onnelk#4set*IM =  NQ'starting ) in_bufferM@_do_QE  8@CommQnot permitted O9{ ?tryr. TxceptError as errS if.args[0]M(J_ERROR_WANT_READU<[WRITE S +el=>EOFR1le_` #+# TODO: SSL$does not expose alert information &elif ("SSLV3_ALERT_BAD_CERTIFICATE" in err.args[1] orFU FB_UNKNOWNJ/):I return self.handle_close()/Yraiseexcept OSError ash ifP0] ==no.ECONNABORTED6NelseAtls_active = Trud'starting = False Cdef Pread(3 P"ifDpI@_do_'RLshakl>tryPasynchat. _ [6le_2ssl.SSLEOFb  class DummyPOP3Server(ore.dispatcher, thQing.T "):[6r =GHr w__init__t , address, af=socket.AF_INET p.E+ldaemonHrcreate_R(af, .SOCK_STREAMy3Sbind( listen(5Nw_lock =rGLock,Rhost,bport = 0get name()[:2]<=_instancW3Non-0ass2notl ZP__fla~WEventJ.mM@.wai@'Hst_exceptionsy OR#s(c_proto_shortcmd, 'echo -errr=use l.|'guido'r1I, 'invalid_pass_ /'pythonJOstat41), (10, 100?lisR1_)[1:]([b'1 1', b'2 213 314 4O5 5'D ? 25%k'1').endiOK 1 1=retrexpected = (?116 bytes'[b'From: postmaster@A.org Content-Type: text/plainR b'MIME-Version: 1.0HSubject:>-Blinew y 3k6113Rfoo =y[.V'foo'&{oqTfoo, D Ttoo_long_X:r+%s' % (_MAXLINE + 10) * 'aHAdef ?del . f test_noop(self): .assertOK(client.noop()) +def test_rpop'D.]'foo'Iapop_normalP5(P, 'dummypassworda\REDOS`# Replace welcome with very long evil..# NB The upper bound on) length is currently 2048BsAt this,,jinput makes each call takeon the order of milliseconds instead3cro_= b'+OK' + (b'<' * 10)qsupport.swap_attrT.+3, 'V'e$A>4ivalid, soshould throwA Raises(poplib.error_proto, &.J, 'a', 'kb'texpected = +OK 116 bytes',,[b'From: postmaster@python.org', b'Content-Type: text/plainS b'MIME-Version: 1.0ISubject: DDQline1% 2 ?3']6113Kq3Equ.=t1, 1), 5 `?uid o UQtf8_rc_if_un!eduserver.handler.enable_UTF8 = Falsa0`Outf86TruP  I know RFC6856'result =(V5Lcapa gg('IMPLEMENTATION' in 3^.keysYLquituKrespu'u2aIsNoneaOsock,Cfile@requires_sslPstls_h > OSTLS4 }expected = b'+ OK Begin TLS negotiation'  resp = self.client.stls()"assertEqual(3, expected) *@requires_ssldef test_P_context(N!):!Fo = b'+0ctxtsl.SSLCTsl.PROTOCOL_TLS_CLIENTctx.load_verify_locs(CAFILE*.;6mode, ssl.CERT_REQUIRED= check_hostname, True3Bwith}uqRaises(eertificateError6:  iF=ctxg = poplib.POP3(" l"",server.port, timeout=3Ly= if SUPPORTS_SSLAfrom>.C ft0 im 0necclass DummyIHandler(.,$ "):BT__init__k, connzasynchat. _ 6[`secure g%t_terminator(b"\r\n")in_buffer = []nQpush(Ud"3  ready. <stamp>'btls_active =e#starting = False DTestC(f# repeat previousps by useQsetUpK*=S((HOST, })hF <v=3}I..b C_all jDIn('i ',_8 N0Oi'  QRJNONERBValu  5GIu uS, keyfile=IWOcertaises(ValueError, poplib.POP3_SSL, self.server.host, .port, keyfile=CERTFILE@ Jcert/ context=ctx) }iclient.quit(), =(9 J " OassertIsInstancewsock, ssl.SSLSocket? 7.s!, t:Trun noop().startswith(b'+OK')Ndef test_stlsq%):.sRaises(!e/c_proto$3tlsZV_& =j }\_capa" =Vc False('STLS' in *`.keys( @requires_ssl class Test@TLSC( # repeat previouss by usingg.I\setUpZ = DummySj((HOST, PORT)4 ! y MH timeout=3mQ tearDown\#"if\7 is not None and! !yN:try8` dexceptJ# happens*1the_too_long_lines case; @overo sponse will be treated as reqto QUITrLIRthis =ion!\close st?# Explicitly clearattribute toent danglethreadD{_! = 5>b?1T/s,fCase):0evtZing.Even = 2et.(.AF_INET,SOCK_STREAM1C.set(60) # Safety net. Look issue 118132 self.port = test_sup`.bind_ (#Zsock)6`thread8 Qing.T (target=9erver, args=LBevt,UV.daemon = Truex{.start(>pevt.wai5def tearDown}!):W.joinL&# Explicitly clear the attribute to prevent dangling K_ = None s ,   rv.liste se6tryconn, addr =Uh.accep4'.send(b"+ Hola mundo\n"R)Wclose exS et.timeoutApassEkfinall.Z+TQqDefault& lf.assertIsW(Bgetd3&()$s$&30% N pop = poplib.POP3(HOST, ;<nocket.v<OEqual(pop.E.get(, #> b;#, = I4' JmF \ValueG. !0_mar2s = [TestpClass, J!s,`*G_SSL.1TLS]3P_info!ing_setup CQrun_unit (*s 7gRnup(*) if __name__ == '_6__' () """This is a""" from __futurE im nested_scopes, braces 3f(x3g(y^return x + yDg print(f(2)(4)) # contains most ofkexecutable examples Guido's descr # tutorial, onc@ # # http://www.python.org/2.2/dDescrintro.html # # A few examples left implicit in the writeup were fleshed out, a >B # skipped due to lack of interest (e.g., faking super() by hand isn't # of much 7anymore), 'r fiddledlAmakePoutpuGdeterministic. from test.supporsortdict im pp# class defaul!(&`):  __init__(self,*S=None&*Iict.+)B9.b$ =B def __getiteme7key\2tryMpreturn .=\+except KeyErrorH3getkey, *argspif not  U1 = <, cQmergeHw, otherpfor key !if0in r[key] =^ =_1 = """ Here'stnew type at work:A>>> L()b# show ourB-e jk# its meta$7d7ypeJadOA=0.0N# create an instancePa) Q <+{}C?(a)IC%8/Aa.__i+__ie!f){(a) is q m6TruW0a[1F3.25L # modify Y3val{@{1: t  18K;F ?[0]Ea non-existent G50.0F"a.{1:100, 2:200}Rq# use a 5hod<haresult:l m>>> We can alsown contexts where ic only allows "real" tionaries, saclocals/globals) texec statem9!orbuilt-in function eval(): >>> print(sorted(a.keys())) a[1, 2] +1a['.B'] =8E# need theAfuncvEhereGexec("x = 3;)r(x)", au3)m , key=lambda x: (str(type(x)), x, '__builtins__', V, 'x'j a[ ( Now I'll show that defaultdict instances have dynamic variables, just like classic'es#a.][ = -1 a["noway"]! 8?000;$'u' in dir(6Trua.x1 = 1\a.x2 = 2L2.x1/8d =^U z and 'x12 kP(a.__ #__{]p: -100001': 02':}Z>>> """  2(V!):'__slots__ = [`]Qdef __init__(self,HS=NoneC2R.+.9bugetiteme7key\2tryMPretur_ct.__=+except KeyErrorH3getkey, *argspif not  U1 = <, cQmergeHw, other0for9 !if0in @[keyC p test_=FThe #declaratztakes a list of!reserves space pexactlyZ secxg. Whenusis used (@ can0be  gno#2(B=0.02a[1B&0.m W , O%Traceback (most recent call lastFile "", line 1,?JAttribute r2' object has no a-u@ A3 = Introspectingsb@-in es For! a, x.__f@__ iWPe samF((xX#([<; 'I$'>6 []V >>> list  isinstance([],/)ATrue &Bdict&OFals'Dobje)O You can get the information fromu type: rpprint.P(dir(& ))a# like0.____.keys(), but sortedL['__add__',A '__! yontains|delattrJitemi$)oc )eq +getyMibut ~)gt<IhashiJimul"*niDi>sub(:itel9len[lY zn>9new>Zreduc#+ex)pzreverser!seh K=setcjsizeof' .Ghook)eappend{Vclear7opy 5unt8ext8UindexVinser,5popgremove'] The new introspecAPI gives morAthanold one: in addi:!toregular methods, it also shows# that are nlly invoked through qial not/s, e.g. __ (+=), __tQ (lenTt (!=). }[C any{!isE directlya = ['tic', 'tac']?$.x!(a # same as len(a928a54:q# ditto)/gA (a1oe'9g#a. 'tAa Ais is justQ itfor user-defined es. """ test_4 = ScWCs an/glPmakes$possible to add sU >,. wpre easyAdescribe:py behave pretty much din C++ or Java. Here'x exampl1 C:e4..." @Y def foo(x, y)=5(("?1", - C.B1, 2) stat icmethod 1 2 >>> c = C().foo(1, 2Istat9r Class Ks use a similar pattern to declare)that receive an implicit first argument (is the *cl* for which y Winvoked. ,1 C:0...! @B @def zcls, y)6;wprint("@3", .uC/,,! < p 'test._descrtut.C'> 1R S ;D(CFpassD DWd = D<dR&a This s(s t __main__.D 1" both times; in other words, uBed aE `o#) d3O@lvedVthe call, no/e $ definition U`. But8ice this:qFE # override yE ) 2ed"L(>6(y)31+ @fHWe = E!ee41 Inb examplet) from twill seC#Jits #A E. -o be expected, sinet specifieu>0C. it stresspdiffere?`betwee#es fUs and>lAmeta_es (wherO0 upa5aEp would  s targetac). """ A5 = Attributesed by get/setxVhods V property(objectZ __R__(self,Y, set=None7&0.__=- P"!=I!$ Exinst, typezsreturn `@get(4>?...`;set`Ovalu$ifX0is eraise pError("x! aute is read-only") ...>return self.__set(inst, value) Now let's define a class with an attribute x #d by a pair of methods, getx() and s !: 3>>>TC(object):4...def __init__(( .__x = 0=  *A x<DD?, xGif x < 0: ?:d7property(,6) Here's a small demonstrationSba = C(c a.S1print(a.x$+- ,E Hmm --  is builtin now, so@try it that way too.6delD # unmask theO<'&'>TUM!=E<=@\  5->S""" test_6 = Mp resolu order This example?implicit inwriteup.  A:%# ,new-styleK 4Dsave?"called A.(7)")hUB(A):MGpassCjCjlD(B, Cmn3D()2 B =c # exEs,mR"A" 61 B" + superT).m()F#FCFC)lfFcD(C, Bf DID, self).m() >> print(D().m()) # "DCBA"  GU8U Backwards incompatibilitiesQclass A: ... def foo(self)}"called A.'8)")I7B(A59pasgCjB\^1C()*) ~^^U]Q!__S_ = {"tut1": 01, 22334455667788} # Magic name that regr.py invokes *after* importing this module. # Tworms around a bootstrap problem)3Noth0docgt! both look in sys.argv for a "-v" argument, # soworks as expected=Jways of runnh . _main(verbose=None):# Obscure: mn?._descrtut insteads#asGQplaine(`becaus ez)of^sits wayH0int$e 9examples,Cunless the fullq HPbusin+qis used3can change depend3aon how%$ i!d.WAfroms,0sup+,,S.run_([&#, )[part isn't neededR, butT directly. if ____ == "_2__".0(1)1est;JQZIP64 functionalitypzipfile35he equires " ionly reason@keepct=pseparatIM_] _ XXX(nnorwitz): disabl[vaest byRjIextralarge resourceQwhich doesirexist. 0 ta over 30 minutes to`tgeneral #r@more`k spacpan most@`buildbots. A(3l'''oAloadRdisk-s byW@a loi'c2)  u, os, unit_Dtime Ssys m Te)@aryF from test.support import TESTFN, requires_zlib 32 =!p + "2" # How much time in seconds can pass before we print a 'Still working' message. _PRINT_WORKING_MSG_INTERVAL = 5 * 60 clWTestsWithSourceFile(unittest. Case): def setUp(self# Create 6a data.1line_gen = ("Q of zipfile  %d." % i for irange(10%))Lw._ = '\n'.join(Eb).encode('ascii') 9# And write it to a fp = open(f, "wb"{1fp.? cclose(r(0zip/, f, compression:he ZIP archive+qile.Zipf"X@It wcontain enough copiesMto reach about 6 GiB of>1raw:GstorG count = 6*1024**3 // len-NQnext_=. _() + >$6num&Vx0Pstr("@fn%dkUnum, 81# P` st>]\ since this be?lly slowM6if <S%* )F)(( ' y riting %d%d, be patient...' %G(?x!),L=sys.__stdout__V v.flush(' I6# Read t 6 = rPE$assertEqual(o].readR)SS Sd9Q# TrylAtemp first. If}#do2, then it hoCgs # gigabytes of disk space for the durationUtest.@ with TemporaryFile() as f:#jself.zipTest(f, zipfile.ZIP_STORED)0assertFalse(f.closed' STESTFN2YZ@requires_zlib@def Deflated(S)Q# TryPtemp  first. If we do z,.n it hoe{oDEFLATgB[VlarDownRTfname in:,2x1if os.path.exists(8&os.remove" class Otherq`s(unit.CCaseHMoreThan64ksa# This- checks that more Qn 64k!s can be added to an archive, P# and9t1 resulting*Eread properly by ZipIH& =O( , mode="w", allowZip64=TrueGB.debug = 100[0nums = (1 << 16) * 3//2$idrange(3^c0wrir("foo%08d" % i, "% (i**3 % 57).Equal(len(NDlist()), w$19() 2./r"/2. scontent 2. !).decode('ascii'Z !QW 2P ]AppenAvCw5- 1Z`tZ aRaises%SLarge G, b'f zipf.close() pzipf =  ile.ZipFile(TESTFN, mode="a", allowZip64=False)C.debug = 100self.assertEqual(len(j.namelist()), numfilesRWwith >aRaises;SLarge%):o^writestr("foo%08d" %fV, b''kfj/clO0?TruNJ`2 = (1 << 16) * 3//2=for i in range(42jQi, "%t(i**3 % 57)r&2:s &r"H2' scontentYi2.readi).decode('ascii QZ )2.def tearDown(Vsupport.unlink0&2) if ____ == "__main__"@unit.P() imfd types $0 global_function(]inner$class LocalC ~Epass` L S%n "W)2#' creturn;{lambda:=2 FuncAttrsTest(^.GCaseP\setUp E Ba* *b33~.fi = F(f$F )Rb = b_cannot_set_attrp, obj, , value, excepDsz:try1setF @HO A Jelseail("shouldn't be able to set %s %r(* :del pass else: @self.fail("shouldn't be able to del %s" % name) class FunctionPropertiesTest(AAttr)k## Include the external setUp method that is commonyall tests1def_module(_.assertEqual C.b._0`__, __J__) RRdir_is_correct_aF fqb.known"A = 7M FIn('&a', dirME.b),15P"set mibutes not in0 listing of%%");# Test on underly)fv object97'?F.a*zfi.a), "q"implementa:2s, r@w up@next"uplicate_g _e1ityZ`# Body$`d6']act same as bf3(S'my docstring'4return 3X)No%, a 0cop___code__r(): pasn&f, None5.]# = OC3) #6 always s 3, arbitrarilyb__globals!Is0#, &()5cannot_se<7, 'nJ', 2p/ (}Error, Type )__closurea = 12Bffrint(aPc = fsJ43IsInstance(c, tupl(len(c), 1f@# dohave a type_handyuMAc[0]dass__.4w, "cell Gf, "&j", c, a U`empty_]tE2tryZ RPs_contenA+except Valu F T*read an  /!y( -0Nm! aFNcell_contents =C 9 self.assertEqual(c[0].cell_contents, 9)0?f()! aNdel c_Etry: ,except ValueError:EpassKJelsefail("shouldn't be able to read an empty "Qwith B;Raises(Nam)l/f(;UnboundLocal Cprint(a) def test___name__(3 $b.0V, 'b' a = 'c'j$ McM dMdM$# F and 2musz stringcannot_set_attrT.b, 'M', 7, Typ?pcAvailwhen in reucted mode. Exec will r NAttributh6 ifis not a_Uon f.<ps = """Pf(): 5\nf5""", exec(s, {'__builtins__': {}}# Test on methods, tooE Efi.atG, 'a2l64, "o"9*, # PEP 3155 Gp, 'Funcxs.setUp..:/__] Rglobal_function.N J*()L% 'e wy1Uinner?_Class  W %V / 'Xfunction2')  self.b.__qualname__ = 'c' "passertE%( 3,2)3 "UdU&d'U)# must be a string}cannot_set_attr8, 'D', 7, TypeError) Ddef test___code__=!):num_one, Ptwo =G8 Aa(): passbreturn 12cX9one d 9two e ) for func in [a, b, c, d, e]Ptype(;.0), `s.CodeD >oc(), 7!d!8!dgE = c b$&, =Q1r# #:try&#except Valub ? Jelsedfail("t with different bers of free vars should "-1"no8possible"% eV' =WZ`blank__defaults| 2__, None>2delD '|CT5M_arg*Qfirst(}u1a+b[5csecond6=1, b=2: |%._T" 8 9f(1, 2)]b2 = * d:,9c:,3*_3), 5+*(, C F  second_func() except TypeError:!EpassJelse%self.fail("__defaults__ does not update; deleting it"Zk*"remove requirement") class InstancemethodAttrTest(Func s1): \def test___=0__().assertEqual .fi.a.__5__.= , &.F>cannot_set_attrC5, "<"=,l)3^/.a=@.a, EBibut3/fi</fiR_non_$# Behavior should be the same when a ; is added via an [# assignAid = types.Mc?(idid(), idF.fi); # e usage|6try.unknown1  C ush*Hsf[raise`"SC and:%ons_'O', 23LArbitrary>@tion X OMN Y&b.hJ = 7 /6, 7aa:1set#on e8 %(e_0 2delcbP  /un @for R in [:.a]b H>.rexisten\M# pass  delse: #self.fail("using unknown attributes should raise "CKD "A5Error") class FunctionDictsTest(/)def test_setting_dict_to_invalid(,va.canno3_$b.b, '_?_', None, Type)from colles import User)5d =1({'$pV': 7}Qfi.a.__func__dt   H'$b.E = d #  assignmentassertIs(d, G# ... and on all the different ways of recf"method's  wF+_ [6 f-ZvaluexSEqualf.6, 7Dq /[A];Moagain,T<_names ; 2ntdelete_2trye HStaticMethodAttrsGUfunc_attributeY| @>Upass Ac = m{/(f1.__p_&f)EQs = sFsFBuiltinFuncPropertie  # XXX Not ! w:Ireally go siI can't find a#zp moduleQcific7Rfor bB_or_.g_*_lname__import time=#d `dvWlen._b, 'len'2m. 8'dict.fromkey9, ' float.__getformat__( '<ethod:  self.assertEqual(str.maketrans.__name__, 'C')  F_bytesH 5') K# builtin bound instance method:) t[1, 2, 3].appendClist {'foo': 'bar'}.popI@dictb if __! == "__main__"unittest.() crandom R#p0 (tRp1 (I3 (L2147483648L L994081831L L2806287265 228999830L L339649806995680545727392776A0920>018626244923p2129248Z177952684346910550 p5169629 125439071M77919708b165356200736521187002881s89651936M85557843'97951841648171024 q191861539930065296797147335334275Z357678257t'jf236767573P11620L L12200544348659705191211514K10370447?409690472r40914617L370165122M31582461&413860458313857648M@7890&232058221420677494q776503111482474b829555 r9020640qq93464272477108572583928216586125K@28651b29147369117188@1569328113728601>10541391S61770&6538102716t1853953q9980307r0275450K22904360e2508487223324932620353r 962494323343 32v3r4147541363634818Aq02545502678771940584[346182690q854511494346355360923902977577982253070097773945414408656dq0929479285432728&22275008eC1835a1246643%@310922350225c30130605H0254$ 29"348012634Z1839762726326081r1108889}`304505L L7315131q0543678Zs0627620q66=r13541261143573981664570@2100d2817679101210746024099152J2910119966S3090022035182366735287)dA1485288616021`4239392189270584q0679855g02745q355164836960135542270378Z19051127@33128436(0930682879535Oa769335398710079%P28836FK64529151L L965498079L L1444623093L L1372893415 536235597 341994850L L963594758L L2115295754q8209868?05343390207846984 3059765792Y753606181Ma301712M567588193529629426L L362152353302757656 1176438084096287811685746142505896429631652902106759L L76190064132918395194705093@447490282328251627&q2000373q9218681J3331403992408876024 218832631Xr8840196~p608026731430280%KP639213749821202286081572768939032005410113349548385029883421723220@171666084665g45998762269177612422503045953967741103680651405d49284110M@16615Lq7579736q5338930"27848795#Q10218CIq3505481q1768521350316602K14807991d16334662377309016&q162846735757377962417823r45489470146919352635567&187082403362425839075666tP34625 22291120J 42V0574Z15574424NS92413X1906634288045972d40658958b141426n12584501324311503`157495}a139392r30556642613cZ5317787950950550X162022749P55494c8*L79729988q2371358L320314221Hq0877453q1897151839365900R76516Lq8590806@x05745677627527881>26442289623777051H601277903404648049c324401q2799317222705937P15388 42205320b478044Q29171W`L L635$y23197632G"42eq8204732 1673151414040954a0r3217106s2406310-q9313092pP24586[q32367050326e7Gp400839431683873q6077221%125683761249424496931289959251975032r2294824105196981F1844q37610372@2363V2s329795771P57276@1958e22392079cc203424c1"05%0881ULA71640L LA4391 1Q@8193&2345100427860591728222321q9870253o306116650490c125510301263870762}`13447214108911L L2831719700L L2188615369L L373509061L L1351077504136217056L L783521095?554949468 66249955Y120382695Mp7963238'191885898A60746597Y1980450237s54007921@339781341Z2913309264228957262'413393532A4166227663Nr37180170654749058056234'83217237255613071'p1047370373401434q4904138b347233'q526668011583936@54432970q21500854dq9140381X0106  58e41593948MQ3205130996677409878446 3635222962q4175165 2020923172580754?272812252s236583652'25040785220443Nq38417149970465332491316516998759s36180970716)2426298186042929217836725031't1726434[0884]2107602188223668430529791937967986q54381334b959000\1363845992952528187418493Y188838719232869523442959858418059410877392323000545q045399211618173189867313q8600110s@94052'0808 42!16@1577 420188381905722196943955s2963q24187403517033452953456610989114(8 47q2793473@361655879q38441195742537737642215428716989`353063pL L6912q7587309%P17177?75185637r1884840L76746967'9A8630353323679P40992'0723 31 03 22 74V`226656%b018433q969968533511708$P34651u271224671q5213830#20@6179q2163575q21673019c137!0136207476&R95971{04252!97p`417427Tq974511510071239 311247762q8064615314807400 52I 8825459795`256228fq0102494A3316n321065640103I290689357- 11"87 870004401[q89830042686856403123484VP56567@0760a689843R41262Ea038554$398896355c27625679-@5440102387206%A1747=@975540337669eP29465Ab492957Zq9582716k46480515L L907760635L L1306626357L L819652378172300279 p1685131 49560107?157715330L L53422010?37732002 1672286106L L2pP19284X84238635L254605946p39457334347619444 S05055[594705582Mr90581358130334127008581169067974252889040192e549767147q2101439X268839848 q3251583 345084644I0917 q712802511325574 c417044I63988966I174637997 q4787416Y281756348 257361253a664444291160161804745411~0207h5311891406Wq8297251'363736734r9447317193440343r43019541 17351522158261821207076703 c479089p6067543355600159q3276293r103613387422812960q999174036358040K141655048127054026e42807438p3960765155254062} 29a041372!412e`713022134297005175571644Z!16@2r27314013'@2319f}28692214oa2397262251495314298608P13599Y4241432973698275020216=$q0400469eq2460771%8946756839322822309720510212881865 A0106mP974000255935540160420939564201334010 33 1780P30727>d79509135a021094&0988t$%Q87075q132726858274622>311230542e1843020682a001892110134916@4211X28666775X A6211qA3241P77319hA64950267 0429962482U167699248\347306704420579369\P40194@K`157999Q(89961799A1136347780284226Q359174q1973087q4336297Z40321427M3148041933121388r3896860329818256 90116586640268298032523523112087221080853036 1079003942824028&20410100A266755507wq6880181OP14051jr4167994 355f@1923S4359809369Bq606243810174200heA2111j5K"97P84425q840216226738077mq4072025P27379710%B4230@6840E31466272Sq5996505\ 691i1257035919L L80748529 1L L2376230687L L303659314 2642411658L L1060800443199622729 q9183451L69761136 11689733L L625123952c@2260q 9663265L L7530594c84361018c*624L tp2 Ntp3 b.def __getattr__(): "Bad one" x = 1 ) di%sbad_sig,return [] """Unit tests for the with statement specified in PEP 343.""" __author__ = "Mike Bland" __email__ = "mbland at acm dot org" import sys import unit from collections ,Tdequentextlib_GeneratorCoManager, cm class Mock+(D<Vinit__(self, *argssuper().__'! elf.enter_called = False"?xit!| = None @_{6Truz9.__Z sr , type, value, traceback3 [ .e (SWO =A  jZmock_fS(func0helx, **kwd7H , !, 50V Resource(object_o.yieldWstopp? @u$_g%! =)2try' # "8lfinall<<fNested!B "3, *2-4 = D!(19if 9ais not_raise RuntimeError(" 5reentrant"T7 ]!= I(`vars =-  0mgrM *M.append(mgr7)r)L/5@left9-jexceptj!if"@!__-_(*sys.exc_info() raise  return vars def __exit__(self, *exc_info):#'# Behave like nested with statements-first in, last outNew exceptions override old oneH@ex =*Afor mgr in .entered:try if9.7*ex"zv(None, )(f<Dsys.G(8! =[Tif ex is not _raise ex[0](ex[1])._traceback2]) class MockN((inmanagers#4?.__*_called = False"g!Dargs@_{6Truz Hk j Q Mx FailureTestCase(unittest. "NameErrory!fooNotDeclared("I foo: paspassertR~%s(d,/R)MEAttribut1QLacks/{(object, type, value,  8J7fooq 3hfoo = <N%jRegex(S, '__}'<g;2; AndExitB <  'Rn :xitX   B6Y.&<+97xitSyntaxError(self, codestr):  def shouldRaiseSyntaxError(s'. compile(s, '', 'single')Lself.assertM's(O,g3, c ItestAssignmentToNone7elf rq('with mock as D:\n pass C P(QZ):\n'%aTupleOnlyContainingL1,>,'-Ay }Afoo,_, barEnterThrows(<Khclass !gobject#0__eH,__D!rKs Runtim"Zv threw"3.S3xitRl, *arg+'9(Ict = wa.foo =I n: ct8'3{ ' 5QEqualP)AExitA (Yeturn ?__e&42Jv gt' extmanagerAionMixin(7AetUpTEST_EXCEPTION = exception"%rInWithMInvariant,_ y@PTrue('.fcalleds3LFals43 g3 f_After!, WO6 .exit_called3) self.assertEqual(mock_manager.exit_args, !) =Bdef 8AfterWithM6InvariantsNoError(e(, Z!):EJ ,<@v(None, ) InGeneratorgBTrue).yieldedNMFals1Pstopp1CE3raiseTestException>" TEST_EXCEPTION24 exc_type=nter_calle3 ) 24if 1 isWS} O[1],WxMk = .1z 0]D> # q the __ _ arguments. Issue #7853qIsInstancwDmv C2Not>"2] _fyhZR clas&a alhCase(unittest., ContextAionMixinb6eInlineaSyntax")BwithcZ_(.2FpassiuUnboundj d/ =f 6 8x B!'z as foo6foo# FIXME: Ing future, we'll try to keept names from leakingHself.assertAfter(WithGeneratorInvariantsNoError(foo) def testInline3BoundToExistingV@ble(self)::>foo = None with mock_contextmanager_g() as fooHL[.assertIn.2_After5oDotted#;)U/ / = 4 M<(&i% T p<w2NestedSingleStatementsV/_aX!/_aZ/_bQ _bU:bar|$} &_a7;b; q u::bart6J _Az9 gw7t o'r class xceptionalTestCase(unitp.,UC,AionMixinpxr;ArglSyntax<h\Jpass$zIToNonTupm# This will bind all the arguRQ to nl() into a svQ list?# assigned tos foo. with Nested(m) as:&self.assertInWithManagerInvariants(m)2._After1pNoError89 def testSingleArgBoundTo ElementParenthesizedList(l)m = mock_contextm_generator(# This will bind all the argunbs to n) into a sQ list# assigned2] G(foo@_dMultiplea Tu shouldThrowValue% O m[, barHLEpassf&vRaises(/, !) > \0Unb^ >Px/t = MockUW/;y^ D| J ?Argn,o, f, n, oa/Ln2dn8$p8 j %H,f, tmanager_generator()) with mock_nested as (m, n, o):'.self.assertInWithGenQInvariants(m[4n4 o4 xManager<_AfterxNoError:::  class ExceptionalTestCase(Contextm2AionMixin, unittest.0@def SingleResource("Bcm =_cf$_g<(SshouldThrow(HL cmf#.rt * %+(c7\{@@aise0o"R(s(Runtimec', _5 E ;=1Normalizeds)# Note this relies on the fact that 1 // 0 produces an e#4is not n immediately.6cK ZeroDivision5-, [!) NpStatemej a1b1Ua>foo)b)>bar)  >(Kat7?b?H7.fo~ C8bar se lf.raiseTestException() self.assertR( s(RuntimeError, shouldThrow5 AfterWithManagerInvariantsE(mock_a?+b? Generato?fooC-Qbar) :def testMultipleResourcesInSingleStatement(}!):6sqcm_a = contextm:$_gOcm_b/Wnested = MockN (w , N(BwithQ1as #.r@_a, bDH"b In *5959)y^ F2n?` v=Dm1 JbnhBeforeInner1bar = NoneBa as6fook` 7 ;|j ;? &b>bar-Epass&d!j # # The i&nner statement stuff should never have been touched self.assertEqual(bar, None)) False(mock_b.enter_called.?xit- [-Dargsdef testNestedExceptionAfterI S !):6WAa = contextmanager_generator((b1ygThrow(}Bwith}Qa as k6foo%)b)>bar)-GrInWithMInvariantsa7?b?GId?fooC->barC]raiseTest""R(s(RuntimeError,,_5\ZE c?'No=a=X~1 aC/_/e/pdStopItLion1W# From bug 1462485C`@e_,cmiyield %M Ew  0("fY&")d+ysRegex(@5, 'A' \@2@class cm(objectxe"___VEpassS6\5 , type, value, tracebackn<MNJ \3K# Another Q where the er hasn'tfinstantiatk(e705170J(d def shouldThrow(): |with cm"raise next(iter([])) =9self.assertR.s(StopIterationl Jrdef tes>@dGen:orExit1(^C# From bug 1462485@contextmanager_Ryield% " 0("f". ) 6,72class cm (objectQ__enter__W!EpassTc__exit5 , type, value, tracebackn<MNJ}ErrorsInBool# issue4589:  return code may Fan excep # when looking at its truthI. 'inbool_conversS !__H(-u%()% 9result = *{ t3d:a, b, cB vNbtrueAs )<lambda: Truef_qfail("S NOT see this"$j OfalsF+ A1ion', %%O1//0%ZeroDivi"ilB) NonLocalFlowControlTestCase(unitl."):WithBreak0cou<E = 0Qwhile 0,E+= 1-BI@mock$_gO}P break  counter += 100 # Not reached %self.assertEqual(6a, 11) 'def testWithContinue(8!): K6E = 0while True(,-4if H:> 25 Ybreak2with mock_contextmanager_generator(DeJ i 3L 2LlReturnJn1*^2*~r, 3) ExitSwallowsExceptionTestCase(unitO.*):h? C9nsAfrican.x ?n z:tryie (j51/0De ZeroDivisionErrorYwmfail("* should have been sv;ed"TFalseDoesnZoEurope[O\ ]3 Oelse|)BraisyNestedWithDummy(object6'in:!=Nqgobble=>6h1if *@ is - " = `{" =Ez2 = !called = & %&def __enter__(self): .enter_called = True%qreturn ,evalue def __exit__`, *exc_infok*jc@4 = p"ifjgobble 9class InitRaises(object%in@): r, RuntimeError()PE6Q YRJY pass~x }Aim 9testNoExceptionsMBwithDummy() as a,b`assert)(a) ,b, (!a.aS 'b'{InExprList:try E et \ ! D(+6fail('body of bad Aexecuted' ;els/oq not reo/(_-xiL_v = Falsnk=@ vE. u `;}Z/K O |'NotEqual V[0], NoneRlsTuple ,a=(1,2),(a1, a2), \4S0, 207kb1, b2W\1Y $2 } $_10, bI%2) if __name__ = = '__main__': unittest.() # To fully J this module, we would need a copy of the stringprep tables. # Since we don't have them, Xbchecks only a few code points. importh fromo!* class SeTests(RCase)1defS(self.assertTrue(in__a1("\u0221"))> /OFals0201 `b`00ad0\ `0e0`3map!b2p041"), O061":/:u3u&:u#c1K 20GK1bLab1bxD1_c152/1f129b1b?1_cf5j?e000"f904?fff+00`5`"d8y}07`6`Offf9M0( 7`?2ff0c8`?034`0 H# C.9 is not in5bmp!# sassertTrue(i n_table_c9(u"\U000E0001")) # self.assertFalse(i78727867Tru5d1("\u05be0fe0f0`2`)04 d00`2# This would generate a hash of all predicates. However, running 2# it is quite expensive, and only serves to detect changes in the# unicode database. Instead, stringprep.py s? version ofJ'thF aimport7lib = [k for kFdir(~) if k.startswith("0?")]Ph.sort(s\p\u:;[f = getatt~8, pH)`# CollWABMP CkpointsUX"0"] * 0x10000%ir(%)|Pif f(_hr(i)#'w[i] = "1"np".join( 4h =Y.sha1K`h.update>print p, h.hexdiges if __name__ == '__main__'unittest.a() """1 case provides supT9checking?wait behavior. To Gdifferent ", override_impl method. We wante1() semantics --t1forthread surviwchild after aK(). On some systems (e.g. Solar0ithout posix Zs) we find that;` activ{#|V{0; tis an err*S""" 0os,p, time,+0b.a LONGSLEEP = 2 SHORT0.5 NUM_THREADS = 4 class ForkWaitz.TestCase):adef setUp(%._d_key =7.Wsetup8 alIE= {}:vstop = Ms]tearDown0# SF5`1*n2$u = NoneTFh.clearX!"Qnup(*8 R)ef f(self, iSd): while not self.stop$alive[id] = os.getpid()F):try:ime.sleep(SHORTSLEEP8except OSErrorCQpass jdef wait_impl(X, cpifor i in range(10#A# shouldn't hang, but some of the buildbots seem to(K#k,forking tests. This is an attempt@1fixZproblem.Lspid, statusg,xzWNOHANG@0if ;1 == AYbreakktH2 * (_.assertEqual(ep%, 0, "cause = %d, exit R" % (T&0xffV>>8))H_ NUM_THREADS%thread = Qing.T(target=f, args=(i,)W7k.start: s.append(# busy-loop )sCpdeadlin)monotonic() + 10.0+1len.G) <  Q~:0.15if {!< *{ HFa = sortedg.keys(I*Ea, list()l0preQ_v Gg.copy(gys.platform['unixware7']J\`1Oelse, tI:= 04u# Child&[OLONGFn = 4)0key k' [key] != >:>in += 1@os._&(n-# Parent;!) import os @unitQ from. $0sup,P spw._module('d') @K.skipUnless(hasattr(os, 'geteuid') and? (),)0, 'root privileges required') class TestSpwdRoot(kCase):rgetspalaentrie0pwdT'zS>IsInstance(8I-35 7ies self.assertIsInstance(entry, spwd.struct_ ) def test_getspnam(self):!?Ries =B'Uall()"sif not ):>M.skipTest('empty shadow password database'Trandom_name =[`[0].spp}vy?TOasse7REqualQ/, l 5?[0]2v6 ,pwdp, str2 h-12nhlstchg, int4 /2h?mine,b3b/axb,b4b?war-d5d_inact.f6foexpireg/h7h?fla\-d8dWwith Raises(KeyError) as cxf$'invalid user Zstr(cx.exception), "'L!):Akfound'"9ATypeH4!?, 07# D:try7Pbytesos.fsencode(B"@ Uni$E* U`(:lse4 &, ) @unit5Unless(hasattr(os, euid') and os.get() != 0,a'non-root0required') class DSpwdNonRoot(TestCase): def test_getspnam_exception(self): name = 'bin'6try")Pwith :.assertRaises(PermissionError) as cm;?Tspwd.(s)lA KeyDC:excDzskipTest("O entry %r doesn't exist: %s" % eg, exc)k?lseYEqual(str(cm.ion), '[Errno 13]  denied') if ____ == "__main__"m@unit.`() -- cases for funcs in math. --'Each line takes the1#m:  -> BTwhereO% Qis a short identifyingy,D ia to be ed (exp, cos, asinh, ...)H  trt`represng a floating-point  `expectrideal) &<p, againtn ed1a sE qlist of l required by C99The possible )adivide-by-zero : ru`d whenainite 2 gives aDematically inf-fresultoverflow] ET thatpcoo large0fitusual range$an IEEE 754 doublevinvalids (e.g., sqrt(-1)Mignore-sign : indicat3!at2 is< unspecified; ci+dn0inf)Zn both -inf andn:0uld acyHecorrecFD may appear3any orderLines beginn '--' (like this one) start a comment,0ared. BlankTRs, or q contaia only whitespace, are alsoH M'N@were pup phelp of;0ver6@ 2.4MPFR library multiple-preci/: arcomputa>je rounding. AllB"in<Afile(modulo yet-to-be-disc#0ugsm _"lyaped, prod efpdecimal 0 be9i`terpre:a@11spo nearest IEEE X754 double-precision value. See the -- MPFR homepage at http://www.mpfr.org for more information aboutGproject. -terf: error funcN/--4 erf0000 erf 0.0 ->1-20inf031.03--40nan00nanR tiny9s@1`1e-308*1.1283791670955125. 24.4.9406564584124654e-324.A1e-1 [6small integer2h0.84270079294971489d22%99532226501895271%3%997790950300136%J20.9845827420oV5J(d984625J5{6%`3 -1-3--3-'3-'<9993-'3-kChugeT should go to +/-1, depending on sign44Q411e1jDL1e153E1.7e0[Issue 8986: inputs x with exp(-x*x) near underflow thresholdincorrectlyalled ov,ome platforms.1126."10126.926."10326."10"27EH,27x6,27x7x-"11N-D  erfc: complementary RMccM c  Mc03L$c 2L/c  2c00(c Y1+Yq8716204z2c00!c 0.15729920705028513,21 erfc 2 -> 0.0046777349810472662 erfc0022 3 -> 2.2090496998585441e-05*3*4*1.541725790028002e-08)4)5)374597944280349e-1}5*6*2.1519736712498913e-17 U"30+ -1,1.842700792949714|#31'2'995322265018952'-1.9999779095030013-'999845827421-'T84626'-0 -- as xinfinity,(x) behaves like exp(-x*x)/x/sqrt(pi)X4 20H5.3958656116079012G4 2 8.11965228e-274X%"27X2370464393526292e-319,* 28,"0.huge values(5!-442.011e1C3005\-1e156wi1.7e30|Issue 8986: inputhFwithK near the underflow threshold incorrectly signalled ov,on some platforms.#10326.P643254389461e-30#10126.h4.4017768588035426.#10126.)1.08851258@2269.#10!126.2.484962157196662.1#10127.i/5.#10"279.881312916824930\2\62 275107I1I-J1#1167#R1-6 / -%lgamma: log of absolutd$ function --t(utspecialP0000 Bma 0,Ainf divide-by-zero &D0001/-0/2/Wd-> infJ3-40nan1nanenegative integersM1XR 1/ 2^A1e300/T-1.792divide-by-zero -- small positive integers gfactorials lgam0020 ma 1 -> 0.0122369314718055994529B3)4)1.79175946922-'4'5'3.1780538303479458(5(6(4.7874917427820( -- half:3!0.d0.5723649429247000e31+-0.12078223763524522W 2,0.2846828704729191W 3+1.2009736023470743U-1.2655121234846454+-0.86004701537648096=--0.0562437164976740Z7.-1.309006684993042 nvalues near 94nT2.2527126517342064l10.0* 4.B79878042021K4k@1e-8018.K8073818020+kA1e-1+36.84136148790473B4mP1e-30X69.07755278982136B4nX-I368.Y4oY709.196208642166t4n05.69/776027137418978:5.5/`9404564167f9/\11.49879373516015-2P743.7@474052744.440071921381-6ZR2.3689613327287886X6110249927528016-84976, 6- 6-/16 6./30 6-6- 6 ! 7"7# KInega8~:0.9836.736800569677101;:1.036.0436533891171 8c u35.35050E55728q2t.34.657359027997268~*00< -331.85460524980607 lgam0085 lgamma -99.986 -> -331.85460524980596 -- large inputs CD0100L0170<701.43726380873704*1*1*6.57306224578736*2*B.624.9.78077443669895.3.5.59168294836.4.2*11.71472580228999X&120013198.9234480542U6U2.55998332785163e301.7976931348623099e+308k7@4@inf overflow585p1.7e308 ( for which (x) is tinyN2Q-100.-364.9009683094224-16.656.88005261126432\4-17.707.9984331450788.C-171713.14301641168481\D-176.38.9524759084648Z2D-177.44.13144651738037\E-178.9.3160351186001 .3B@59140701$51]3C5300s279278.66299<>3D450359962^#951.5782258434492883e+17results close to 0: positive argument ...50 @9989h6.4083812u00075e-5 1.s-1.2816762426960008e-151|{-9.3876980655431170|>2|G1.8775396131086244{+... and nega6-2.74768264675.24774081t9136e-16-2.457024733.3464637541912932e-10 -1: Gfunction -- 50---U special values gam1 0.D divide-by-zero/1/-0-1/2/&c-> infH3@b-> nanv invalid(4( 'integers0 arB#10B-xHi j1(A-1e11+ 121e3C)(Vsmallgfactorial21#23 -> 2 gam0023 gamma 4 -> 6 gam0024 5#2456120 -- half integers)#30)!0.A1.7724538509055161(1(1(0.88622692545275805)2)2)1.3293403881791370(3(3(3.3233509704478423--3.5449077018110322R-2.3632718012073548)6{--0.94530872048294197+0.27008820585!11[values near <4[19.5135076986687304[20.0)9.432585119150604[A1e-8R9.4227843434\B1e-10)]Q1e-30S.Sc88e+29.aW/+1.XT0e+16h^0#304m05.691.7857142F48e+2855.52inf overflow9)Y' )5) 23)y2)6R1-0.-10.686287021193196S- -100.5871979644107+6 - +.577215676 +,206+/-960!16-62!3026-- 6-- 6' 7) )0negative8t0"98`900719s740992.8 24503599627370495.8V r822517998136852488c2-1125899906%239q*00;+7.5400833348831090e-1498 =R40962=@largq2put $10o!17@4.260090047051y`$10b!177.257415615307-$10WR171.6,1.79421175992481041$10P125 -> inf  overflow gam0104 gamma 172 -> inf  )5)J2000* )6)w1.7e308,) -- inputs for which6(x) is tiny"20p -100.5N -3.3536908198076787e-159111615.2555464470078293e-286121713.3127395215386074e-30813111.9316265431711902e-3100dB-1760 -1.1956388629358166e-3211lB-17714.940656458412465#240sB-17804-0.~798201.0001`9`2.9999[3;>30+.3B|4503599627370495-that cause problemAthe standard reflection]Pmula,Cthanks to loss of accuracy in 1-xL463.34907872902298}4.1777971677761880e-8427.4511763294329< 1.1831110896236810e-214 -'log1p: log(1 + x), without precis osmall x --x*yspecial values Q1p 0.+1F 2S3-3nanuinvalid040(`-> nanf singularity at -1.03#103k^divide-by-zero7#F36.736800569677101cfinite: < 1.0 are 2[ 3!1.$k"-2$t21e3&! xz 1p3~ x1P54  !1!* ! !1B$15$11D1e-2 420 A^- #-|E # #!15 #h -- some (mostly) random and moderate-sizedVZ200 log1p -0.$89156889782277482 -> -2.2216403106762863 log1p0201  -0.23858496047770464<0.27257668276980057=2=011641726191307515>0117100216544956?3?090126398571693817@0905349938250076504A023442805DE2781B5554240995695C1.5672870980936349e-01662046e-56A7.96500132xq5295e-6330482740401e-6A7A2.5202948343227410e-51519170971e-8A8.2446372820745855e-1p41445599Cp1663670@9078(E&8.824230e-12C#10C7.0351735084656292e-18A5.2732161907375226hA`236188A;1.0@e-10A49.95#71`2.140166000197e-9@43099470e-91.2668914653979560e- 57e861e-8?01.607816299069H4999461317G108.3d9564583939?1450242662X~3=12<58P89997X1Q0.007[6975613736425B~0.01302623531505300}2942123564008782z%3497160797!0688552191503v2v0.02762559T13528=08974634830542r0.1417968724554487o0.1326032254099 -- large valuesL$301.7976931348623157e+30@709.78271289338393 1>690.7755278982136$30>p161.180u095832161D33.025850930040455Sother transferred from testL1 in S_mathr4+-0.63212055882855760 34)P71828a4590459$] 0.P47180C4452%40!.2379400392853803e+262.38324p395075 &-------------- -- expm1: (x) - 1, without precision loss for small x -- B# yspecial values @0000m1 0.0 ->1-20inf85inf3-E-1.040nan81nan1~ xdtiny x71`5e-324: !1! !0!01T1e-15!&15!D1e-2 420 b2- #-E # # #h-- moderate sized, where direct e( atruns into troublef1=3.S54e-1B%10:9.9Q5e-082?u0163e-8r3ihP1e-05A4?U34e-5@;Q0.007:1@069755570667648951AY0.071499208740094633@690029857448202D3105f63296004180116799?1334416373633009~6?0.02390954035597756=4197665143819942<7< 85\52649044900.089411184580357767=8=596617494741100x81596588F0148r9:30247206212075130.3531998703584867u0.745747273758v1.1080161>E3745(1i00.9`51292611.658268920737211a0.8450154566787712a1.328013797653589Z1397926032312f;-0.1304614U396061V5289932203964327@-0.42136436959231T7408326147890063=523283171247970R-0.9384776698454605O-0.60877704724085946zS1"2.465794806711A"27i532048240600.7986212!12Q2.6195173187490626e+5v"12Z]385578764662V-35.1"00<@#44treme negative5 23-0.99999999999999989 expm10200 -38.0 -> -1.017710-- the formulaB(x) = 2 * sinh(x/2) * doesn't work so -- well when& is subnormal or underflows to zero; check we'reFnot using it!1Txm1 -142F0212 5 3 /50 4 .e575u.79e308Yextreme positive values3 -> 1.9424263952412558e+13$30!701.0142320547350045e+304ynext test (  302) is disabled because it s failure onFOS X 10.4/Intel: apparently all over 709.78 produce aA on that platL. See issue #7575.qVU271289328393_1.79769313468242408V >P48402>1inf3"10[%1 %6 )weaker version of5E03027Y51.3549863193146328/ -klog2: logWbase 2 --45dspecia D0  % divide-by-71~?2 -8727fd-> infP3-9nan invalid040(p-> nan Rexact@ at B00100110.00@negasW2'p-5e-324b 2X - 2c-1.7e-Y 5` s`powersY2#102#10442.02.3"1634l3f55V6g66#12i77#25j88#51k993102m3204o1 $1 0.r!$02&20.2(#20(30.1+#20+C0.06. ` closel  v3.2034265038149171e-16301 log2 1.00001 -> 1.442695160185e-10 log20302 0 1.10878274712997e-5 0"100;0.9k-1.6017132519074588e-16<1<6w33022101r17022544056922-- tiny valuesv#40b5e-324?C074.#401 3 3 !1.B"2.4150374992789n32N32.0A4Ao#08o23.1538532253071#412.2250738585072014e-3=^$04,4.45014771701440281117 19.8319251304202 -- hugeY5Y1.7976931348623157e+5102i5i.!3.91938797167058.9884656743115795]0102selection of random6 -7.2174324841039838e+289nan invalid6-2.861319734089617e+2657 85-4.35076468940:Q2e+25p-6.671726520224e+2384w-N180237866192982581.5478221302505161e+206 68438048513136460/008783.7235198730382645e+18Q p881.04722422350957/18985.0141781956163884e+162-2.v80311603pG-7.9677558612567718e+9o 0-5.5553906194063732e+4 8016573900952607.95  P1071983710A8861806.0727115121422672 02.5406841656X57e-3t 04.9056766703267684 802.1646786075228305e-7 802.470826790488573e-7 2e0-3.x709303489064 p20-1.u496976649986e-18Q 8`p1.59354h4317996e-255 -> nan invalid log20623 -2.8750977267336654e-293 8487.607946679473258586858@3.20/3539988545e-3077-1018.15055442092136=1.674937872249e-244<809.80634755783126<7<0911259044931283e-21=R710.7G2274y8=2.0275372624809709e-15=510.55719818383272z9=7.3926087369631841e-115379.1356473531229="30=1.34801982q2423e-8f-285.2549744509443"31<8.99273846a947e-8-272.55127136401637"32<3.1452398713597487e-60197.66251564496875<T7.0706573215457351e-5179.8842008778221xX3.1258285390731669e-49x61.13023800505653\8.2253046627829942e-41<33.15898277355879[7.8691367397519897e+x165.7506820273241;Z2g0561983925013e+6214.1845353%75X4.7827254553946!+7 258.0462962844567V3.1903566496481868e+10f350.476167/41164U5.619508244950Ae+11 37 831861008250)4U9.962565651047e+12x0418 5292122874U2.7358945220961532e+14<83.1315863692344U2.785842387926931e+17f579.4936021486028T2.416917250725275<642.40529039289654T3.168909109562g682.65924T2.535995592365391e+208692.30359[E6046T`6.2011766089916e+23776.641775767309*U2t@32744"775<841.5749971744V 8.a0931n17479989.74184073981 -BEGIN PRIVATE KEY|- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCr77F9oBLYuLIb 3t4mDHPoxOEnu1h7NQaJdn9tR/KjW6AzhXXm9USh45qt3sR6Wo8sDlBIJ3vZyhyW P939qYUeGOZJahupYi4IkqVckZXARm3k9qhAI/aC4ixVFyxnxg3bNpk8Ir0AyyQV oudY+33+ZNj6+fHzeboGDJ9uE/RTcp9JqE/qo0haATZufJfY63ZCUpYFn6j5W4jG vpqg5/0hba8Cxdk62387uNknfVHSMzGkkq82zbBpud6TYQofCp3VlEPBjz9iLCz6 FFOKgLZmbk8QsdktXF6zfRJJk+vbZTh/OGH0p/eiIfW1kXOzOcuW31XRFTPnykJd 4QUX9OajAgMBAAECggEAHppmXDbuw9Z0FVPg9KLIysioTtsgz6VLiZIm8juZK4x2 glUh/D7xvWL2uDXrgN+3lh7iGUW13LkFx5SMncbbo9TIwI57Z/XKvcnkVwquve+L RfLFVc1Q5lD9lROv2rS86KTaN4LzYz3FKXi6dvMkpPAsUtfEQhMLkmISypQQq/1z EJaqo7r85OjN7e0wKazlKZpOzJEa5FQLMVRjTRFhLFNbHXX/tAet2jw+umATKbw8 hYgiuZ44TwSEd9JeIV/oSYWfI/3HetuYW0ru3caiztRF2NySNu8lcsWgNC7fIku9 mcHjtSNzs91QN1Qlu7GQvvhpt6OWDirNDCW+49WGaQKBgQDg9SDhfF0jRYslgYbH cqO4ggaFdHjrAAYpwnAgvanhFZL/zEqm5G1E7l/e2fCkJ9VOSFO0A208chvwMcr+ dCjHE2tVdE81aQ2v/Eo83VdS1RcOV4Y75yPH48rMhxPaHvxWD/FFDbf0/P2mtPB7 SZ3kIeZMkE1wxdaO3AKUbQoozwKDqYgg7kVtygyICE1mB8Hwp6nUxFTczG7y 4XcsDqMIrKmw+PbQluvkoHoStxeVrsTloDhkTjIrpmYLyAiazg+PUJdkd6xrfLSj VV6X93W0S/1egEb1F1CGFxtk8v/PWH4K76EPL2vxXdxjywz3GWlrL9yDYaB2szzS DqgwVMqx7QKBgDCD7UF0Bsoyl13RX3XoPXLvZ+SkR+e2q52Z94C4JskKVBeiwX7Y yNAS8M4pBoMArDoj0xmBm69rlKbqtjLGbnzwrTdSzDpim7cWnBQgUFLm7gAD1Elb AhZ8BCK0Bw4FnLoa2hfga4oEfdfUMgEE0W5/+SEOBgWKRUmuHUhRc911AoGAY2EN YmSDYSM5wDIvVb5k9B3EtevOiqNPSw/XnsoEZtiEC/44JnQxdltIBY93bDBrk5IQ cmoBM4h91kgQjshQwOMXMhFSwvmBKmCm/hrTbvMVytTutXfVD3ZXFKwT4DW7N0TF ElhsxBh/YzRz7mG62JVjtFt2zDN3ld2Z8YpvtXUCgYEA4EJ4ObS5YyvcXAKHJFo6 Fxmavyrf8LSm3MFA65uSnFvWukMVqqRMReQc5jvpxHKCis+XvnHzyOfL0gW9ZTi7 tWGGbBi0TRJCa8BkvgngUZxOxUlMfg/7cVxOIB0TPoUSgxFd/+qVz4GZMvr0dPu7 eAF7J/8ECVvb0wSPTUI1N3c= -----END PRIVATE KEY----- import io im Qos im threadingunittestrllib.robotparser from $ E0supMhttp.server BaseHTTPRequestHandler, S* class +RlTest: {s_txt = ''Aagen_"good = []-#ba def setUp(self)dhlines = io.StringIO# )..)!()N9H.M = u1.QFilePA;B(]!) ]Aget__and_url,g if isinstance(url, tuple#I<fvreturn $ tsy0forA in B)vzT# =$ 6urlr5Bwith-0sub.=agent=agent);: self.assertTrue(parser.can_fetch(agent, url)) Ddef test_bad_urls:)a0for0A in T6badT" =#Aget_1_anU(qo1Bwith-psubTest#a=url, :=5OFals class UserAWildcardyBaseRobot`, unit.CCaser#s_txt = """\ O-8: * Disallow: /cyberworld/map/ # This is an infinite virtual URL space C!tm8 these will soon disappearofoo.htmla1"""good = ['/', '/%!']#ba QindexN7amp/xxx gC'] QCrawlDelayAndCustom`;(X&"# l.l http://www.example.com/  -d: 1 Request-rate: 3/155 @ # Cmr knows where to go.f+}G, ('?Y)RejectAlls-ygo away gNRate+):r._ G+l"ifcu_S#oEqual(&2*%W'-),pI)i 4}IsInstance] dqurllib.X47I\./s,~l'_rate.requests  /)  self.assertEqual(&:*parser.request_rate(agent).seconds,A :32 ) class CrawlDelayAndRzRateTest(Base, unittest.#aCase):drobots_txt = """\ User-: figtree p -dqC: 3 ^-: 9/30 Disallow: /tmpa%3cd.html=2fb%7ejoe/indexg1"""C = ''? = urllib.!b(9, 30cE_A = 3Mgood = [(dq, '/foo1')]&!ba%''!2tmp! &/a+Ba%3C'D'/a%)~ %']DifferentAg(>FigTree R libwww-perl/5.04U # these are not actually D ed, but we still need to p1 it%# in orderaccommodate[` input1qameters3 ANone  oInvali%*Htmp/ /Oabananas/3zC '/a =%7Ez 3s # From bug report #523041): .3peaTBG#~says "/" should be deniqthat is!in1RFCsAnother Aalsov }Ae and Dias works well with each }F: Googlebot [: /folder1/myfile owhale/hjcRq'UaUOtingTest(BaseRobotTest, unittest.-Case): # the order of User-agent should be correct. note6at this file is in( because "Googlebot"!a;substringq$-Mobile"&robots_txt = """\ %: X Disallow: / #W$ A'"""g5= 'R'bad = ['/something.jpg'] class(A'9[(OT0ingmo'YP8URL?`(BaseRM ? also gowrong. You need# to specifyURLs from more ic'qgeneral=yfolder1/my2X.html\ gJ3goo7V!']D#uanother~GaQuerySjx sesue #6325 for details- * s/path?name=valuu+ DUseFirstWildcard`obey fI * entry (#4108)&  `#_Empty&normalize; (#17403 ?: >DefaultEequestRatee Crawl-delay: 1 RX-rate: 3/15cyberworld/map/r:_: = urllib.sparser.\b(3, 15tc_A = 1U5Q', '/  4 Qindex@!F#tt+/* >)@ # Tis an infinite4 virtual URL space # Cybermapper knows where to go. User-agent: cy+ Disallow: /some/path """ expected_output =\Q .* Crawl-delay: 1 Request-rate: 3/15world/map/ def test_string_formatting(self):.assertEqual(str$.parser), # ) class RobotHandler(BaseHTTP"):0ado_GETb send_error(403, "Forbidden access")Hlog_messageM", w, *args\EpassPasswordProtSiteTestCase(unit7.QsetUpl]server = S ((support.HOST, 0),*=threading.T ('fname='b vYing','wtarget=.)eJever.# Short poll intervalmake theF finish quickly.q# Time between ras is s\ enough that we won't wakeG up spuriously too many timess kw0={'_':0.01})W t.daemon = True # In casis function raisi>cstart(tearDown `.shutd$ [join(rtr_closeq@FRreap_!s/st 0add n"esSfurl = 'http://' + Q + ':0tr(;6[1]r "s_CB+ "/Q.txt"eZ = urllib.$.OQFileP,!0setcF(url{@2cFalse('can_fetch("*", )tNetwork @base7www.pythonMQnet/'j txq'{}else'"'.(Y|@oamethodMC8(clrires('n'5EwithtransientP0netR.23cls 0 L.1url , }wreturn '{}{}{}'.format(' self.base_url, path, '/' if not os..splitext()[1] else ''N!) def test_basic(`!):v.assertFalse .parser.disallow_all)30 yGreateremtime(), 0ccrawl_delay('*')7@requCrate8 can_fetch$:Tru#5Q'*', OPurl('where')LTNutchPH-_brian/LwebstatsO" /K y) read_404 = urllib.robot .R `FilePa ;.!i-(H.txt~8l(&( +cEqual(.O dIsNone-K 3Gif __name__=='__main__'f@unit.() This is a sample doc ` in a  file. In t-!ex), we'll rely on some silly setup:>>> import.Z_b0  .ESD0  * also hasp (random) encoded (utf-8) uni ЉЊЈЁЂ^doesn't cause a problemthe tect surrounding  s, but we include it m3 (i5N) to makeRce. :) &Tpipes o dstringshutil fromg1suptUTESTFN, run_< , unlink, reap_children if? != 'posix<Praise[BSkipTest(' module only works@2) B2 =  + "2" # tr a-z A-ZVsable, s(nranges explicit s_command = 'tr %s %s' % (/.ascii_lowercasNG2upp) class SimplePipeTests(unittest. Case): def tearDown(selffor f in (TESTFN, 2$(unlink(f) SstSimple1Zif shutil.which('tr') is NoneYP.skip)'not available')w-t = pipes.Template(.append(s_command,-STDIN_STDOUT0f = t.open''wmf.write('hello world #1"HclosWwith So) as fassertEqual(f.read(), 'HELLO WORLDkr2rU , $.2. + ' < $IN > $OUT'pFILEIN_ et.copyC> 2*[3 gr/ry $kfinallJ$f. PEmptyMline # F through e-HDlVd = 'F |e COPY'' o;d <2='S=%$Gd% l  # l"OREADl3t.#%&3(self):  # write through empty pipe Vd = 'line test WRITE'(1t =9s.Template()with t.open(TESTFN, 'w') as f:'s!f.+(d><7self.assertEqual(f.read(), d) b1defPRepr(0)z , \rBdt), "< instance, steps=[]>"t.append('tr a-z A-Z',1STDIN_STDOUT3v+ uQ'--')JSetDebug1t.d4_False(kging, -O(TruC, ReadOpenSink# check calling M'r') on a@ endX^ # a sink raises ValueError#: boguscmd?INK1Rk(k,:1, 'Fpfile', W_ourceR'2pre _OURCE ++w'ABadAp|Options # try a non-strucommand#2Typ?, 7Gj0typat isn't recognizer "s$b4'xx`shouldbbe able to :r;3s.SKkQ1twoZs$I6K'## A neex input but )u no $IN5 Pu $OUT',^  pFILEIN_ C sel#f.assertRaises(ValueError, t.append, 'boguscmd', pipes.FILEIN_STDOUT) 1# command needing file output but with no $OUT7Bt = YTemplate()?selO $IN;eSTDIN_Pdef testBadPreOptions(%):!# try a non-str#P #6Typ"p~C, 7,k type that isn't recognizeds t'tr a-z A-Z', 'xx'o`shouldebe able to = a sinkt  9INKxTcheckiTtwo sourcesqf.(zo_OURCEJ  K-in%IN5 ?X=1).bOXjEW~OpenMode Dopen&SR}OClonwF(9 8qu = t.clNotEqual(id(t), id(u)*' t.steps, u.steps) self.assertNotEqual(id(t.steps), id(u 3) 63t.debugging, u ) def test_main():Erun_unit(SimplePipeTestsgreap_children() if __name__ == "_Q2__"RJ() import errno $os drandomselectoresignalUocketqys from g0supo5imeDleep; T.mocktempfileLmonotonic as time tryresource except IRError(! = None Shasattr(s2, ' Spair'2 = .&R elsea(family=.AF_INET, typeSOCK_STREAM, proto=0vjJwithrUF3)l6l.bind((.HOST, 0)\"al.list_cv3c.connect(l.get (+addr = c) d(while Trus3a, J@l.ac(-# check that we've got the correct clientB#ifg0= cp }"return c, aJ{a.close'OSRc6@raisfind_ready_matching(c, flagiQ = []for key, events in 4$if&HO.append(key.2obj% class BaseSTCase(0.1): Pmake_P et(Prd, wO#-.addCleanup(rdN",wr"i0regVrsWoSELECTOR sqkC ))0key&.:.EVENT_READ, "data" IsInstance&, A?Key:O, rd* d%+(no Xi , "data")   # register an unknown event ! self.assertRaises(ValueError, s.Ba, 0, 9%) > binvalid FD!_@-10,ectors.EVENT_READo_twiceg?Key/rddhe same FD, but with a different objecM .fileno(),?seldef test_un(l%):P0s =Pf.SELECTOR()ddCleanup(s.closek*$wrCmake_socketpair()#(4's.'rdG&# (g dE A7%, _after_fd_O2;] (, w = rdc5 wr H(kTwAVWRITE\"rdMo-wr > w!P@unit.skipUnless(os.n== 'posix', "requires "X_and_reuseo2, wr2 os.dup2(rd2z2, rK!(wr!w!&.ao F%J tbj+h  iEAD)  s.register(wr, selectors.EVENT_WRITE) rd.close(-wrEs.unV&rd, Awr) Ydef test_modify(self):w0s =f.SELECTOR}+.addCleanup(sY>drd, wrCmake_socketpair()0key&: GREAD4"# u eventsAkey2M(K ZssertNotEqual(key.Z , S PQelf.a522, s.get_key(rd) Edatad1 = objecttd-@F, d1+ vF, d26.+ `3 c \c 2.R'junknown filee"KRaises(KeyErro.R1, 9,ose a shortcutm/d3p = unit.mock.Mock S,msO, d3fFalse(h.calleZ ,. o_( z# Make sure the fd is 0)ed in case of e1 ong~(): http://bugs.python.org/issue300146*if.__name__ == 'EpollS''p]patch(_)'T$._V_cls'/el P?S&8Dev44 V*serskipTest(""Qwith Z as m>m.return_valueR  side_effect=ZeroDivisionError) s = self.SELECTOR( addCleanup(s.close%drd, wrJmake_socketpairQ.register(7selectors.EVENT_READ] assertEqual(len(s._map), 1-Bwith2Raises(ZeroDi:s.modifyZWRITEk 10) bdef test_7(5)|~ +.zXpmappingx@.getm^ Gs-0wr,k (\;qRuntime1, skey, rd7"wn3Keyj?.__getitem__t = z?key;1keyr, "data"pvC(rd)# unknown file obj O1, 9S ??map?gFalse(keys>#?, 0' 2istKF, [])3!In$7[rd('0rd.!Ono()[ 4.values()), [key]!YtI"9]# Read-only *4`2Typ aAdel e#rdaC self.make_socketpair() s.register(rd, selectors.EVENT_READ)-wr_key = 6.wr6WWRITEearesult8a(Tfor key, events in /:w self.assertTrue(isinstance(>XSFKey)gDr$bFalse(%V & ~(d) |g ?&'Equal([(rb#],,E def test_context_manager&f)QsQSELECTORddCleanup(s.closeb($wrComake_s\with s asW~D?sely 3v3Raises(RuntimeErro@.getF, rd7#wryofilenop;if hasattr(s, 'c' fd. <fd, int)rGreater.0;NUM_SOCKETS = 12fMSG = b" This is a(.""_LEN = len(MSG`reader%[]0Mwritr2w = {}&2&{};iWange( 1 Z7]51*.append(#r2w[rd] = wr`w2r[wr&rd%3bufo-cwhile g ` _: = find_matching(1qif not 1U &=fail("no s5 Fing"e6 random.choiceh . .s bd+10[l5 ready_readers = findy_matching(Oy,  selectors.EVENT_READ)J1if dyMers:"{]break# there might be a delay between write to end andP #is reportedy1sleep(0.1Nelseself.fail("no socketbqady forcJing"L6assertEqual([w2r[wr]],2y9 7Jrd = 9[0]0buf#d.recv(MSG_LENE |len(buf), 0bufs.append' ps.unregister(r2w[rd]o "drs.removeAd , [MSG] * NUM_SOCKETS) 5@unittest.skipIf(sys.platform == 'win32''.() canno used with empty fd sets'@def w__@)5# Issue #23009: Make sure EpollS\~works when no FD is>$# y5ed.v.SELECTOR(2addCleanup(s.close!stimeout=0), []l(a"rd, wr = Vb.make__Spair(. @(wr,/ VWRITE@t = 01, 60))A ./-1/RLess(| - t, 0.5L'wrr\ hFalse(p &' /t0k e1c.t1:d190# Tolerate 2.0 secondsyvery slow buildbot;True(0.8 <= dts2.0, dt P0Unl hasattr(signal, "alarm")U",.*() requiredAthis>'Y_interrupt_excf.SELECTOR()   self.addCleanup(s.close) ! rd, wr = +make_socketpair()class InterruptSelect(Exception):S[Fpassedef handler(*args.\raise\?orig_alrm_Eqignal.s(.SIGALRM,m) 8?,, @ r :try=walarm(1* s.register(ks7ors.EVENT_READ1t = time(#rd) is ised by aq which Ods an e c@withOf.assertR+s( 9"s.?(30+waefore theout of 30 secondsRLess(  - t, 5.uofinall 0@unittest.skipUnlXshasattr81, "9"),") required for this e"_0_1_no(bsSELECTOR+4 w Jqlambda b: None JUQ, but] doesn't3#} |@, sooQshoulretries a recomputedR*ouh{)eFalse(F1.5),GreaterEqual]1] ScalableorMixIn:e issue #18963.why it's  ped on older OS X version@support.ps_mac_ver(10, 5resource, "Test needs | moduleabove_fd_setsizeS# A s implementa have no problemm%an # FD_SETSIZE file descript Since we don't know`value,6jus# try to set the soft RLIMIT_NOFILE to the hardceiling. >,*= resource.getrlimit( b)@Etry: T1sD 0, (})REself.addCleanupU, ,L( rNUM_FDS = minV2**16except (OSError, Value )Mp @# gufor already allocated FDs (stdin, stdout...UV-= 32TAs = /SELECTOR(3Gs.close)>i in range(dK// 2 Xdrd, wrmake_socketpair,?> 1 # too many , skip - note that we should only catch EMbI.# here, but apparently *BSD and Solaris can fail upon connectPor bind() with EADDRNOTAVAIL, so let's be safeTest("FD ` reached"pns.register(yselectors.EVENT_READF50wr,+ 5ZWRITE6 ^ as eif e.errno == ~.ENOSPC,C# thpbe raised by epoll if}go over<@1fs.-.max_user_wes sysctl7w]! !fdr.~+73QINVALsys.platformT'darwin'P# unexplainable~ors on macOS don't need Mtest% !Invalid argument\@ cal7 :()"02DQassertEqualT , len(fds)) class DefaultS Case(Base"):z IaE/or`'Bor @unitV.Unless(hasattr( ors, 'Poll8/')"s;"")3 PollSelectorTestCase(BaseSelecto, ScalablMixIn): SELECTOR = getattr(sBs, 'PollR', None) @unittest.skipUnless(has@(EpA!),tx "u needs ~.<") class 8D h@def _register_file85f):0# e(7) returns EPERM when given a : to watch<0s = $f.%()with temp;.NamedTemporaryFf) as f5 self.assertRaises(IOError-$s.G(f, VENT_READ0d# the +Key has been removed/?Keyget_key(fUKqueu' =) H i nbad_fdgdescriptor that'closed should ra an OS!# UEBADF upport.make_d~*cmO ^ Equal(cm.exception.errno, .jb$s.0DevYl > H j% ZSmain(kh[Default,w r ;  : % ]>sDrun_.!(*`!eap_children( if __name__ == "__2__"test_main() # -*- coding: utf-8 # IMPORTANT: this file has the)BOM signature '\xef\xbb\xbf' # at,start of it. Make s0V is preserved if any changesBre made! # Arbitrary encoded text (stolen from test_doc2.py). x = 'ЉЊЈЁЂ' def y(): """And again in a commen:(0pass import collectionnfigparser'$io o(tpathlibDwrap@unitwarnings  0sup class SortedDict(P.User1): items(selfreturn sGb.data.-&))??key>,=_value?[i[1] for i]Biter! &; % : [w'> __P__ = ZACfgP5TestCaseCallow_no_P = False0limMs = ('=', ':')_prefixe";"#"inline_)`empty_-Bs_inP3Truict_type = co._default_dictkstrict$sM DDEFAULTSECTBinterpolaz -f_UNSET%2new#, gs=None4@argu(k6 , =T. 0$de, ( .  4; B@ >= 2 &# h_)  2 0 .pinstanc*_I5(**29h#ngi qQcf = vspcf.read_N(%cfITBasicE(WTestCaseClass): def basic_test(self, cf):"E = ['Commented Bar',"_ 'FooInternationalized Stuff@Long Line0Sec> \\with$weird%characters[\t2_pacesyS2 From The BeginningI>Typ_]N0if F.allow_no_valueP$E.append('NoV%')RvE.sort(F('baz', 'qwe'), ('foogbar3')# API accessUL = cf.sNs^LoCeq =ssertEqualIveq(L, EZitems('K 6vX&F)H# mapping[T for ein cf] vdefault_> [ "].Z,ed(list(L)eF-/cfDa(len(L), Em6Xname,<L9eq(#.ceq(cf.E0s()6[Y]\use of sws in thefs serves as a# regression SourceForge bug #583248 # http://www.python.org/sf/+s;Fget( ~), 'bar1- 020  s3C$DEY  u4u 3es@key  '/k9}another=osplat!>Sint('P 'intm,42 'F"42")fRAlmos"xgetfloaikF0.44Dsm+",q-wbooleana_Falseb '123'), 'st range but acceptable') if self.allow_no_value: 'eq(cf.get('NoV ', 'option-without-8'), None) A # test vars= and fallback=#`pFoo Bar`Vfoo',.@'baz_W'bar1= u {'J!: A2}), ssertRaises(configparser.NoSecjError)k Such jOXi ano-such-i/NoYzXpDoSpacey3/r2GN]int('Types^8int^18), 42C 7?/18?%q"18"), u # sic!5 AlmostEqualHfloa@%',( 0.0), 0.44}$107X- pA"0.0C wbooleanTrue), FalseDLi"yes")  aE_p3 UOh u<, None)  eq(cf.get('NoValue', 'no-such-option-without-v  < fallback=False),  /# mapping access ['Foo Bar']['foo'], 'bar1'))oSpacey,2,0secv = cf['3 From The Beginning']b9.name, : self.assertIs(Eparser, cf*O /Raises(AttributeError):hP = 'Name is read-only'/_)aPc$eq 3#1baz:qwe"Commented4/] sRBkey =s5}another9nsplat!Long Liner 'this lin`much,  longer than my editor\nlikes it.j#if;llow_no_ -?]['v], None# test vars= and [;1z')4b'={-:,2z'}Bz1n?KeyhNo Such SK\4xS  WH; wL)whr6 ?' pTypes']int('int', 18), 42.7tint('no-such-int', 18)# eq(cf['Types'].getint('no-suc6fallback=?#q"18"),  # sic!$CJ'), None)~self.assertAlmostEqualqfloat('p', 0.0)/44I+. 0$ P3q', "0.0pq8GjP2 {boolean(' ', True), Fals;DA"yesRR:T5', T'_*[0DK! 2if pllow_no_value:\0NoV('option-without-8' GgP= WP A o/## Make sure the right things happen for remove_secmg() andE (); added to include checkK SourceForge bug #123324. P1cf[ tdefaultvr]['this'] = '1'5(at52' # API access self.assertTrue(cf.remove_section('Spaces'))5AFals6ihas_op2, 'key with sE{# 6tdefault Foo Bar', 'foo'),5"{:) failed to report existence of '"I y '|0Onon-U" that was d.vthis_value fD C~?, '<Raises(configparser.NoSError) as cm:CF('No Such ;\7Equal(cm.exceS.args, G5)) C eqget('Long Linei  line is much,p longern my editor\nlikes it.'o# mappingTdel cf['Types']7"f in cf2Keyr lnFVH >my&!][&$BF[N:-'YOm=  b[3, LZassertRaises(KeyError): del cf[self.default_section]['that_value']7Qwith 1assertRaisesa 'No Such S]']['foo'] X# Don't add new ^s below in this method as most of the opsLCand s are now removed.udef test_basic(%config_string = """\ [Foo Bar] foo{0[0]}bar1 [Spacey X bar2 From The BeginningY7foo2t3 bazqwe [Commentedc`{0[1]}bA4 {1 c%B baz0qwe 0]}another one [Long LineI^Pline f`uch, mlonger than my editorilikes it. [ \\$weird%characters[\t] [Internaalized StuffC[bg]BulgarianbD0[en)0]}English#desDeutschrps] key ssS  !0]} splat! [Types] int;q42 floa*0.44 boolean$`NO 123mstrange but acceptable """.formatzp.delimi0,^_prefixes)u"if"allow_no  E+= (?D "[NoVN]\n"T-Aout-4)Bcf =Bfrom:(,n.y_6(cfB*ctd ~fparser.DuplicateOscf.read(textwrap.dedent(( [` a`s Here +  !a L r=u/;/5G&))R[Mw:;>And Now For So completely differeHOTrue@[a9Tlarcho1S^Jelse[!W$ S option {0 [1]} with another value """.format(self.delimiters))) +cf.read_string(textwrap.dedent("""\0f[And Now For Something](completely different {0[0]} TrYthe larchN1|def test_basic_from_dic0%):Oconfig = {"Foo Bar":foo": "bar1",8}"SpaceyJ2J From The Beginning 3]0baz;qwe Commented4MkLong Line this line is much, longer than my editor\nlikes "K"it. Section\\$weird%charact=[\t BpInternaFalized Stuff8"foo[bg]Bulgarian($Default"1[enJEnglish&!de&lDeutsc& s2keys%"yW 0ksplat!1 @Type^  in*42@floaO0.44boolean": False" 123: "strange but acceptablG}|1if allow_no_.update(0NoVA0"opi-WAout-do": Non<%})Bcf =2new(YV{6(cf*ctsassertRaises(_parser.DuplicateWErrorF#'1': {'key': '''h'1)2*2+?6licateOptionError): cf.read_dict({. "Duplicate Options Here": 04!'o*': 'with a value',b2fOPTION2onother8 }O%})bJelse @'sec': {'keyiC'SEC-2.+2'/ ok'g`def test_case_sensitivity(selfhPcf = .newconfig(scf.add_xO("A"aBsL = cf.TsngL.sort$eqassertEqualeq(L, ["A", "B9a"]`set("a,beq(cf. s))ObE#gHbb"), "I "could not loXP, exp0ng 4-in"e #g namesrRaises(parser.NoSV/on9## ^[Q are }{EI@t("b*NL@True7Bhas_:o, "b")1MFals2k 2!A-2A-B`0for8 in ("a-IAa6" !8cf.Iopt)(' "') returned f ion which shWexistV>sVy %az)["JmovenF5]) # SF bug #432369fromstring(8C"[My2]\n} {} first line \n\tsecond".formatNRdelimiters[0]U |O,2, "6"'\n"!o561822! #"[|I]\n". "nekey{}nevalue\n".format(self.delimiters[0]),  defaults={"key":"value"})7TassertTrue(cf.has_option("sec ", "Key")) ;def test_case_sensitivity_mapping_access!):4Qcf = tnewconfig(cf["A"] = {}32["aT"B": !B!6SL = [T for ein cf]=gL.sort$eqUEqual/\elem_#[Count(Pq(L, [0ed(b, "B",_ , )0eq( a"].keys(), {"b"d["b"], "could not locate P, exp0ng 4-in#v names"BwithRaises(KeyError#nHQ are jhQ/0b"]'#/wA"b" GAG-R"A-B M 0optAP("a-bA a-5" NR ' "T) returned false which shWexistA$;@del a*&B" {"})# SF bug #432369fromstring()P"[MySxaon]\nOb {} first line \n\tsecond N  t 7pS/"["`'\n"o561822 "M]\n""nekey{}ne\17#"] P{"foo8Bar_ PUcf.geSPFoo")v:ar"9 {"|?: "#lf.default_s ection, "Foo"), "Bar", "could not locate op50exp@ng case-insensitive defaults") M def test_parse_errors(self):!qPcf = .newconfig()?R(cf, &r.ParsingE] ^"[Foo]\n"[ "{}val-without-opt-name\n".format.delimiters[0])1esDZ0MisZSonHeaderg LC"No 5K!\n""assertEqual(e.args, ('', 1, ?@!ifallow_no_valueO9Q4 @ wrong-indent* 21# read_file on a l  `trickyupport.find&Q("cfg7r.3l\"ifY z == '='2./ =^ 2 bed = (,!+ls imv/ 1 ' # INI  as many ` partspossible\n'6Dopen encoding='utf-8')@fTAelf.im:, fi>u'edYR8 , exc, srcaif hasattr(src, 'qWline'%0sio%rcse$io.StringIOT*.Raises(exc"*cm#0cf.F(sioIreturn cm.exce{ TRqueryRT!Bcf.ss(), []Na"new CAQer sh+phave noTined RFalse(cf.has_+( }acknowledged  "sections") with self.assertRaises(configparser.NoS9uError):=DQcf.opV_("Foo[<set("foo", "barWvalueg2e =Pget_e_(cf, (, S Equal(e.args, )+scf.add_Q O7T 1)) Fdef  , Sexc, ", =tryLget(2dexcept exc as e=return e.+ls#.fail("expectedMe type %s.%s"Dv% (exc.__module__,?0.__hname__test_boolean(|$cf>fromstring(w"[BOOLTEST]\nP"T1{et>s}12NTRUE3>rue4.oN5=yesF0NFALSFNFalsF.FF^-nOE2>foo-gE/0. AND MORE".format(=.delimiters[0]xfor x in range(1, 5O,LMTrue(cf.get'N', 't%d' % xY BC fCV7m q  ), eor_Rweird~sd2new(Q JDDuplicate*cml 2cm.5ion'str(e), "r 'Foo' already existe AYb, None"if*ctDuplicateSectionError) as cm: cf.read_string(textwrap.dedent("""\4C_[Foo]will this be added{equals}True3O[BarMhat aboutSJDoops?]won't""".format(=self.delimiters[0])), source='')Le = cm.exceptionSpassertE(str(e), "While ing from c) "G"[line 5]: sec 'Foo' al\y exists" e.args, ("Foo",i, 5)) Wwith DRaises(configparser.DuplicateOdict({'Bar': {'opt': 'val', 'OPT is6lly `opt`'}}9Q>': o6 in&Bar", "opt<t", Nonedef test_write()I = ("[Long Line]\ny"foo{0[0]} nis much, longer than my editorH likes it.[{default_}1]} another veryK @ - WComments!oM@ {0[q$we|"{c2]} cana&@also& 4_place6 _s6ii Qmultiikvalues%\n#, x _prefixe,1 B  #ifEllow_no_b +VNless-Aout-^ Bcf =' for space_around_7(w, Falseoutput = io.S6IO(Y#2cf.,,j=space_around_delimiters)  = self.Is[0]+if space_around_*:(^ = " {} ".format( expect_string = (S"[{default_section}]\n"(foo{equals}another very,\tlong line a [L4OLineAthis^ is much, ver than my editortlikes it.   - With Comments!Dtest5w _talso#tc__multie =%,^ = % g: allow_no_value +]0"[V@Olessj$ op-without-r:- passertE(output.get_I(), !) [@def 4_se~p_types(R)$cf"Bfrom0("["p1{eq}foEF[0])p# Check*t we don't get an exceK when sett>As in#.!is `ion us.slass mystr(strKEpassXcf.set("R4", fsplat"+j"12 2]+]1] Kread_returns_file_listQyqv != '='s .skipTest('incompatible V'6p1upport.find("cfgparser.11# caB0we  a mix of ahand non-T5newconfig(xd ps = cf.H ([E1, "nonexistent-&"]<M", D0tEqual(cf.get("Foo Bar", "foo"), "newbar") # check when we pass only a filename:.cf = self.newconfig(Lpparsed_7s = cf.read(1&?assertEqual(71, [/]0_cf.ge0Path object,pathlib.R]wed bothp and a 3[,@1  73qmissings,["nonexistent-"+/no3h 1]) def test__returns_list_with_by#Pring_(])R"if3delimiters[0] != '='&9.skipTest('incompatible format'Xf1|upport.findQ("cfger.1").encode o1an    ' :Onon-C,b'  GnZ/,  wI`# sharpy subclsPdget_interpolation_^pLP`fromstw(H "[Foo]W\n" '"bar{equals}something %(with1)s interpolation (1 step)F9G9)s lots ofO9OsP/10Q/10R/10S 1S1%T5=0)s))9(H'8'8%(With7'7'OITH6'6'5'f5'4'JITH4'3'f3'2'2'1'[  [Mutual Recursion]#6foo{?bary>_%(foo# W)[IT]Error}# no definizfor 'reference'Fname&.format(=self.delimiters[0])) Ndef check_items_config(1, expected):,APcf = .fromstring(""_@[sec]7; {0[0]} %(value)s"key{0[1]} |%(/9)s|!getdefault(+4""" ),_ACs={";S": "< E>"})sL = list(cf.#("", vars={'3': '})?f.sort(passertE}'(Ldvc+rRaises(parser.NoScHino such test_popE1112727273737375 4cf.9s)[0], '`/1'626"362s(KeyError):' cf.popitem() def test_clear(self):7Pcf =  .newconfig({"foo": "Bar"}),'assertEqual(JA.get` .default_section, "Foo"),S,8"could not locate op50exp@ng case-insensitiv#v names"cf['zing'] = {'I1': 'value1', 252'} 3cf.Ts(), ^r 2Fset(.keys()),w, 'foo'd2cf.c0), w)4[ ]:1setR><fromstring("""=[@)1]1 {0[0]}  7272727373737""".formalimiters), +@s={"DD 'dJ da.b I2I2I3I3I ['{E1'],c<22']<2</2'<3<3<3< -3, ' H 63'] X2BC |U  ?@AaNotIn(j G }  QC73g $ >Qu; f['section1'].keys()), {'name1'}) self.assertEqual(set(cf['section2'@/22A3A])}3cf.xUs(), F1',  Q3']) def test_invalid_multiline_value(!):,0if .allow_no& $!skipTest('if (A is :ed, ParsingErrornot raised'M = textwrap.dedent("""\+[DEFAULT]A {0} [""".format.delimiters[0]u Bcf =newconfig(BwithR"s((xparser.]cf.read_string(_]Zycf.get('R'), ' <[8"][/]8 class StrictCase(Basic`, uniti._C"= ARawC9 !erct = True |'a1X pterpola ge6+_ $eq-K3eq( "Foo", "bar"), "something N'inf (1 step)"JE9"),l- Vlots of ^9^s_/10`#/10a'TeJ(cf,3IQDepth:', ='11 =o_UNSET(e.args, ( 11_d %(_11)s j1klif isinstanc. iLegacy P]@_mis;`+8M{ Op@'  "Interpolation Error", "name") #self.assertEqual(e.reference, " 3 0secf,vn #op: 1if i== configparser._UNSET:args, ('dO', ')',EI5'%( )sL&')elif isinstance(,iLegacy)wdef test_itemsRcheck _([('default-< ?>')pS('get2>|?|@1key9_value5&5i,2, ' J)]) 5Ysafe_ B# See http://www.python.org/sf/511737UBcf ="fromstring("[E]\n"+/ "y1{eq}xxx020#%(=?)s/<k7?%%ssYnot_o;2)s/%%s".format( 1eq=delimiters[0]cf.get("J4ok"), "xxx/%s 8vz ~d@BwithURaises(TypeA\ bet_mal?ted Ufoo\n1I'4', 8Cfoo" <:Vx;, cf.set, ZW1 %JEI on1", "foo%"3) 'self.assertRaises(ValueError, cf.set, "sect", "option1 f%oo") JEqual(cf.get('<'<Z), "f<!# bug #5741: double percents are *not* malformedu(2oo%%bar" ??ndef test_set_nonstring_types(F!):(XPcf = R.from*0("[ E]\n"(, d{eq}foo\n".aat(eq=Udelimiters[0]) # Check that we get a Typ when setting non- vs# in an exis+6ion 5e4 1C&/.0E/wobject(;!f,C-E,123, "invalid opt name!;( Cadd_(S, 1236 _default6newconfig( b,}h s_keyword"""bpo-23835 fix for CParser""a={1: 2.4}[4]['1'], '2.4'?oAlmostE float('1'),L "A": 5.2#a?5.22a5.2) classTestCaseNoInterpolad(Basic`, unit.q_X"= p.'ibs = Nonei = textwrap.dedent()[numbers]0uone = 1two = %(one)s * 20hre,${common:one} * 3f[hexen]sixteen = ${numbers:tw o} * 8 """).strip() def assertMatchesIni(self, cf):$:.)Equal(cf['numbers']['one'], '1')41two4%(one)s * 2>2hret${common:one3F PhexenPsixte S, '${2:tw3'$test_no_interpolation)%Qcf = *@fromh!ng$O.iniu,cfoempty_caseEinewconfig(`IsNone(cf.read_<"")lnone_as_default lass CustomC~rParser(p .N _DEFAULT_INTERPOLATION = 'Pg |l" cTestCaseLegacyI(_P"=  B .y set_malformatted "[sect]\n"l0"op1{eq}foo\n".wA(eq=mdelimiters[0]VL 1`.get('z4', ["), "foo"<cf.set("+"+B, "%+&f <fVfoo%"ff <f %f<# bug #5741: double percents are *not* 8%ed92wO%bar  2%@ mNonStandardDN(ot = (':=' ent_prefixes# //#"#inline_* 10Sec* *_ion = 'general' mPMultidValueshd(Basic`, unit. ass = configparser.ConfigP  wonderful_spam = ("I'm having  "8< "(beaked beansI:1and, !").replace(' ', '\t\n') }def setUp(self):Pcf = Q.newc%()for i in range(100;? s = 'section{}'.format(iC&scf.add_(*(seje dBset(s, 'lovely}r2j), jwith open(support.TESTFN, 'w') as fswwrite(fDtearDownGos.unlink^ ;st_dominating_multiline_valuesS# We're readZfrom file because this is where code chdP# durB1pernce updateswPython 3.230cf_o_o UPT.^^nassertEqual(T.get(k8 E4'),K X +&.n')) class RawTestCase(Basic, unittest.I_L"= Q [I_interpolaR :get+_d$eqS%Qeq(cfT"Foo", "bar"Fp"someth; %( 1)1 (1 step)"iZ9[ 9)s lots of 1 (9csd/10e /10f/10g1g(11=tempcheck_i [('default < > S('get2>3|%(?)s|B3key;Oname8.9!%(/)sp.9 ,)]Yset_nonstN_typQ>d_section('non-string') cf.set('n, 'int', 1' 0lis(Q[0, 12, 3, 5, 8, 13]@ 0dic@{'pi': 3.14159}6self.assertEqual(cf.g)9%), k?), cf.add_section(123 123, 'this is sick', True*;)<pif cf._`configparser._default:1# would not work for SortedDict; only checkingthe most commonOk ionary (OrderQPcf.op2xform = lambda x: xXD  PA 8oadef test#s_keyword(L)- """bpo-23835 legacy behaviorARawCuPu1"""aPwith PRaises(AttributeError) as ctxs;62new(^s={1: 2.4oPerr =AQ.exceVFstr(err), "/ object has no a 'lower'"hBcf ="A": 5.2} Al9[<p]['a'],D) class \TestCaseNonStandardDelimiters(-d) = (':=', '$Tent_prefixes# //#"#inline_* PSamba*B(Cfg,C`, unit._"=  #;O----`empty_s_in_valu#aFalse sO|readingF0smbBupport.findfile("cf2o#} when we pa mix of gpable an%n-TsLfE!d_4E f.H#([, "nonexistent-'"], encos='utf-8LPpa$, Xc:r['global', 'homes', 'printers',  'print$', 'pdf-generator0tmpAgustin']Aself.assertEqual(cf.sections(), )2 get("global", "workgroup"), "MDKGROUP"D)inGmax log sizeJ/50Bhosts allow>_"127.P("tmpecho command@%cat %s; rm %s") class ConfigParserTestCaseExtendedI@polaPd(Basic#, unittest.!):ecQ_^"= p`.m-b .Edefault_@ = '1on'Xstrict = True def from0ng(:", #, Os=None, opQxformPcf = =B.new(>&(ifD7cf.`( =*%Rread_(`return cf#_e_Ytextwrap.dede%""[`|favourite Beatle = Paul9$color = greenEO[tom[band = ${J_} dayk0popIJohn9I} II9ksequeleD+}IOambv] = Georgebon of Edward VIIm<?} V6P! V4sJ stanley ${:W 7tom5}3_black$Pstate!miparanoid/@movisoylent ${vAsong0 sabbath -2 UP""").Fp())$$eqdeq(cf[6]['{P'], 'B'54S5Otom'g 2dn day') % eq(cf['tom']['favourite pope'], 'John Paul II') 4 8msequel01JambvjRBeatllnGeorgef5Qcolorp_green3son of Edward VII5i/ V8)  stanley8^black6PstateAmindparanoidABmovisoylent \1<usong'],]A ' sabbath - ( def test_endless_loop(self):!Pcf = .fromstring(textwrap.dedent("""15[one for you]ping = ${"me:pong} 'A+me@o@@you:U A:ish>!me|5me}nP""").Fp())Bwith"assertRaises(configparser.InterpolationDepthError= 0you'l;hBme']strange_ops vdollars@$var^e$value`2{%|{sick} = cannot iVBe me)[dAothe{:m4try&wO.QEqual<de+):?A{==Aexce`_classoMissingO0 ^v) as cmE  5%m.^.reference, ' !:$C `args[2$)C}}') #rawval6 case_sensitivity_basic(seclf):  ini = textwrap.dedent("""")[common]optionlower = value O 1Upp V !/[CVa better ${:v}N o;A B9 )} :z[random4foo| redefinedL4Foo"${:z- R7""").strip()cf = self.fromung(ini)o$eq"assertEqualR(cf['6G']['9Q'], ''O 111bk: ktth88 o'def test_case_sensitivity_conflicts(X9S1 = -O 5 =  D5 = /:, =}1Foo-+}- &:Bwith%pRaises(igparser.DuplicateWErrorGlb# raw Os9,*xform=lambda:s ,,,rD,'a5a-jv1foog^3F3 e! pother_e  interpolaZ failU1where's the brac(2(does_not_existt&3&wrong_secx:*141i:like:colon:characters/5 = $100 for Fail No 5! U""") 0with self.assertRaises(configparser.InterpolationSyntaxError): TXcf['i+ fail']['case1']u'MissingOp|2|h3|)m%4ua5u_Value6'] = "BLACK $ABBATH" class CPTestCaseNok(allow_no_v = TrueU TrickyFile(CfgqC, unittest.mP_"= _#delimiters = {'='}comment_prefixe#@def 3_cfp_dot_3((t = support.findf":A.3")1 cf-<2new(^UEqual(len(cf.read(l, encoding='utf-8')), 1D cf.sections(), ['strange', a'corruK7dyeah,  can be 'yindented as wellanother one!91no _s her* |Kmore?] agetint.default_t_, 'gogvars={e': '-1'}), -b>J# no will happen ?cf.P raw=zn kal(len(cf.get('strange', 'other').split('\n')), 4) self.assertEqual(len(cf.get('corruptionL]valueL&10Mlongname = 'yeah, sec? s can be indented as well'SFalseboolean([, 'are they sub`&') Clets use some Unicode'), '片仮名'Q$items('anfQ one!_5) # 4 inE andy# `go` from DEFAULTOWwith Raises(configparser.InterpolaMissingOuError):N3cf.1no os here c'tricky iq<q`do thisL0  /go/@'mor; go shopping') def test_uR_failure(f&= support.findfile("cf&3"Bcf =2new( DeRread(, encoding='ascii class Issue7005TestCase(unit.0""" output when None is set()aW allow_no_jA == .R http://bugs.python.org/i&2""" expected_C= "[#A]\no! =C\n\n6Sprepa", c_^`# Thisthe default, but that'sq point.5Icp =Q(=scp.add_#("  p.K2, "!",Lsio = io.StringIO6cp.write(sio2return sio(rnone_as!_s[\ifiedCP.OType7_L_rawq.NH8Rawt3M>;lf.3) SortedTestCase(RawConfigParserTestCase): dict_type = SortedDict ef test_sS(self7;Pcf = .fromstring("[b]\n"@%_"o4=1&?3=2&?2=3&?1=4&/[auk=v\n")output = io.S6IO(cf.write((;assertEqual!.getvalue(),d G" "k = v\n o"o1 = : o"o2 =  o"o3 =  q"o4 = 1) class Compatible;(CfC*`, unit.*rconfig_P"= pQ.RawCqcomment_prefixes = '#;'inline_#+;'7%Phandl_: = textwrap.dedent("""\u-"[Cued Bar]baz=qwe ; a qfoo: bar # not!!"# but this is! ; another\aquirk:;:;is`? space must precede an H V'""Ya 5M cfI)('7', 'foo'Z '1'j!baz'), 'qwe@"c  &')=$py d(Basic.# +Gdef ", , defaults=Nonq2new(,iscf.read (UT_copyJ #G6(cf2# we have to clean up option duplicates that appeared because of # the magic DEFAULTSECT behaviour.++qfor seccQin cf.'s(-$if,s.name =o+_I1continue  for default, value in cf[self._section].items(): 3if %[5B] ==R.==del3WPretur_copy class FakeFileRdef __init__( file_path = support.find("cfgparser.1")uwith open(&>b) as foj.lines = f.read(J '.reverse() l6 aif lendVG.popz X'' h_generator(fS"""As advisedDoc/library/confi%qrst.""" }`while .Qyield;! ?@ReadTestCase(unittest._,b[ ]6try Hv.appends[0].encode('utf8')except Uni E&ZError_p # unfortunately we can't bytes on this  si9 =  CoP+Ef assertIn("Foo Bar", 9- 5foo)[;]4bEqual(Y0 ["I], "newbar"d_iterableHCtextwrap.dedent( [GCfoo=i"").strip().split('\n'-mjMj )6Yb%"""Issue #11670md'].vRaises(Typet\Va(%8; )Ltest_source_as_bytes(self): """Issue #18260.""" lines = textwrap.dedent($[badbad]5 """).strip().split('\n'))parser = config!.C P(-Pwith .assertRaises(;DuplicateSectionError) as dsemread_file(, source=b""|eEqual(Pstr(dse.excep|)), p"While ping from b'e0' [~r 2]: s h0"alDy existsLbad = badhOKQ3]: oE' inD_?ingySk`tains e$&s:G\n\t'C'i"VqsMissingoHeaderyF!2con%no4h@s.\n , V: 1\nX  class CoverageOneHundredTestCase(unittest.)1"""6s edge casesthe codebase:@def F$_d__n  #('B', 'RO error.section, 'section')  self.assertEqual(error.op(2, ' 1source, None^olineno-uargs, (A)u2strQ), "OC in % " '"already exists") 8def test_interpolaMq_depth_`(w!):.[ = configparser.I>D=E(,,JN'rawvalz EU o b+?ingVPwith jRaises(ValueKv) as cm: qParsing.(cqcm.exce`jRequired argument `&_' notd "given."="='', filename=' ) 0Canspecify both `M5andBV. Usek K T-warnings.catch_(record=Truejwi(.simplefilter("always", Deprec<Wb7!.&6 =  F_ BCfor X Q(*6egory isTQvalid# S,er Ca'er-._string(""[&]I!inP_perc?= % reference = %(zErvariabl$does_not_\%)sW'""Yer.Interpola tionSyntaxError) as cm: parser['sec/']['invalid_percent']1self.assertEqual(str(cm.excep? ), "'%' must be followed by Eor "N "'(', found:B%")?Wwith Raises(config.Interpola (reference Xbad i variable  '%(()'") def test_readfp_deprec()sio = io.StringIO(""[o = valuen'""i9 = xCP\(warnings.catch_(record=Truewv( .simplefilter("always", DWbx@.&(sio, filename=''4Cfor tK in Z (*egory is @JBlen(F), 2 )% Q'], ''Hsafe% Wc MOSafeQCXproxy_reprW -0_st ?key *p/b), '3inconsistent_converters_state*import decimall.k#['#D'] =//.D7P1kuone = 1{:[s2% tw-2% l5In(-, C.get('s1', 'one'), 1<2', 'two'), 2)  %self.assertEqual(parser['s1'].getdecimal('one'), 1) 9? <2<0two<2<Bdel keZHwith_Raises(AttributeError):0 N(", +CIn('$',converters[<]]?Not`H['[*" class ExceptionPicklingTestCase(unittest.0""" s for issue #13760: ConfigP$ eZs are not pdable.""" @def f _ei(4hjSimpor8e0ae1 = cl('value'Nproto in range(e.HIGHEST_PROTOCOL + 1xf*2d =e.dumps(e1, Tg.&e2)Sloadsjd' e1.message, e2 5 repr(e1), ;2))NPnosecW*2NoSF`Tbqe1.args  3e1.2 5  o,OERC', '52e1.[option)   self.assertEqual(repr(e1), P2)) ,def test_duplicatesectionerror(I!):*.import picklee1 = configparser.DMSMEM'[', 'source', 123)Jfor proto in range(l.HIGHEST_PROTOCOL + 1*3d =.dumps(e1,Tg.&e2)Sloadsjd' Je1.message, e2 5Aargs2 /+2 5U4 3alineno3 3 ?I/opH7OLGdQL]:k* * 2e1.3 33 3 interpola.IJ  Fmsg'-b Z rmissing[* MW d!)',p'rawval!referenceHe.HIGHEST_PROTOCOL + 1): pickled = .dumps(e1, proto).&e2)bloads(6d'self.assertEqual(e1.message, e2 5Aargs2 /qsection2 5%op4 3referenc9 repr(e1), A2)) ^def test_interpolasyntaxerror(QcimportCe1 = configparser.IPSPEP'C', '( Fmsg'2for in range.HIGHEST_PRW9_depth7DOdh'rawval+?ing *sParsinggsourcee1.append(1, 'line12233yu  g4errors)   self.assertEqual(repr(e1), C2)) , e1 = configparser.ParsingError(filename=' '<.append(1, 'line12233!for proto in range(pickle.HIGHEST_PROTOCOL + 1):*Bd = .dumps(e1,T.&e2)Sloadsjd' Ue1.message, e2 5Aargs2 /Rsourcc 3ed 3  Qdef test_missectionheader[(cimportxDc dMQSQHQqhD, 12qJ  2e1.?1 3Y!no3 3 J class InCCommentStrippingTestCase(unitl.V0""" s issue #14590: Cer doesn't sZ! im" cnQ when'delimiter occurs earlier without preceding space..""" ; b f?g']a3eanOTrue<sg1e`-R!('Y 3W1R/K~;I DWwith Raises(AttributeError):Ksdecimal)Y!W Rsimport iconverters[' D'] =,".D45In(3*, MkIsNotNoneSz8;len87), ndec0_5_('0.5j , '0_g{8;del$q_?Notb*4[a!?get%Y!?R ?Key_dT/']7 ] class BlatantOverrideCTestCase(unittest.c"""What if somebody oGode a get)? We want to make sure that in +this case the automatic converters do not kick in.""" #`fig = Q[one]one = false>two0hre*long story shortiJO[twoX'Afour def test__at_init(self):'{ cfconfigparser.C P (B={'len': len})A.read_string`.P%u!._{len(cfgassertIsNotNone"E[z"])2inheritancewlass Strange>gettysbur P'a hiic borough in south central Pennsylvania'Igetboolean, section, op*, raw=FRp, vars= ,lKfallback=pk_UNSET7$ift3 ==v "return Tru super(). 3raw_ 4%TP_P0hO%}B._gen(2len # +?cfg:A&q'one', )6 0two667m70L#['P'] = pC_to_ 7g?, '70, .`Equal(0LO), 4 5In(gX1In('len', cfg.converters) self.assertNotIn('tysburg', cf4zIsNone(*['int']e1Ofloa3booleanhQEqualgetlen('one', O), 56Otwo'6 @hree8/16oh6/D, 't4four', fallback=0), 0CWwith ^Raises(configparser.NoOptionError):Srb][$].: 6p6 I ['a 6(l | r:0), )!) ;def test_instance_assignment(T icfg = 7CDPD(2 = lambda sece1, oma: True h2ACcfg[K"][K}read_stringq6figmX)?, 31?len0o 066E6l=)l(#[' ']Cfg._C_to_?BFalsw3get( self.assertFalse(cfg.getboolean('two', C)) self.as7?one7!n>nTEqualPlen(',!, O), 56p6 hree'), 16oh6/42# If a getter impl is assigned straight to the instance, it won't# be available on1section proxies./Wwith 5Raises(AttributeError):0g/[] j7Hj class MiscTestCase(unittest.@def __all__(blacklist = {"%"}support.checkB, configparser, G= ) if __name__ == '__main__'iP() imn4 os sys from.7ort TESTFN, rmtree, unlink, captured_stdoutA.script_helpOM_python_ok,4erttfailuretextwrap Strace}   )dmodules&mod #- Utilities ) 0# `fix_exP(file"""Given a .pyc Pvertsappropriate-1"""9%if6P.ends ('N'eyY=.Q[:-1]Cereturn0my_5_and_mod(QQ"""Th4R and Q ' of this"(_H$_)N = os.path.spli(1bas'=;)[0Ta,get_firstlineno(funcunc.__code__.co/  Target M`s for U?ing `# # # 8relative numbers51s i\'sec!majverifying #v. Please1ify-s if you change< one of the # functions. Absolute line numbers don't matter. # def traced_=_.ar(x, y): a = x Qb = y c = a + breturn c N8oopL8Lfor i in range(5mq4c +hZimporting_/x + y + testmod.>(1)simple_caller(xt)x)N + xU X9k =k ~\k~OJ(k, k}generator(num5Y # executed onces 94yield i +9Fing_vs0]0#102li@doubynum * 2-er_list_comprehension(e1 my'C = [j;i) 1k)]z: class T*C s(objectmdef __init__(selfS.\^/inst_method'9./y @ ( z.oahcI_HRx, c)z@  ?clsyu{@staticM N7I? #- Test cases ) #estLineCounts(unitd.PCCase"""White-box0ing\ -c<ing, via runV5""":QsetUp1OaddCleanup(sys.set , g"()6$2r =(2=1,A=0, s=[ers=0Lmy_py_filename = fix_ext_py(_#___ ^result = .0#r.( ?k, 2, 5assertEqual(P3, 7 Q# all _s are&PexpecA= {}Pfirstno = get_ J1\r[.a', i + i)] = 1 self.assertEqual(s"tracer.results().counts, expected) def test_1d_func_loopG!):%) V un((4c, 2, 3Z5firstlineno = get_ ?)mE = {Q.my_py_filename, U + 1): 1,7_2): 67_3): 574}h;importing>95"DHfix_ext_py(Qmod._P__),  2 2}+9lgeneratorcalling_A_( &N^I ='#?rM @0/$Rgen +< dC_list_comprehensionXgw/erD%Q/ddoubler1Mp# List HGtions work differently in 3.x, so the count  # below changed compared to 2.x. ,% (self.my_py_filename, firstlineno_calling + 2): 12,@&3@?!`ed + 1>0?}assertEqualtracer.results().counts, expected) Cdef test_ar_methodsF!):#2# XXX todo: later add 'static5C' and 'classOhere, once issue1764286 is resolved. @for  in ['instf&,] @ = T( A=1, A=0, Ufuncseers=0)|KTd_objO dC:(25)od = getattr(m:, 3"Pr.run(BR, 20)`_7 ZI = {O ~}7  " TestRunExecCP(unit.CCase"""A simple sanity@ of - ing, via runctx (exec)"""QsetUpX  = fix_ext_py(_!&__ZddCleanup(sys.set , g#()__ jWErd&code = r'''R d_[_loop(2, 5)'''-1@ile($, 0, ''V3ctx3globals(), varsdNm7675747}# When ushrough 'run', some other spuriouss are produced, liked# the ?athread;which we ignojust maksure thatBP2 foT were right{#;kg.keys(6 f.tracer.res+ults().counts[k], expected[k]) class TestFuncs(unittest. Case): """White-box !ing of f6 tracing"""-def setUp(selfBF.addCleanup(sys.set?0e, g1())K6$r = Trace(1=0,{e +=1<filemod = my_ _and_modname(-q_saved_pO+ = tearDowni=lf.Kis not NoneW N <)wst_simple_caller3 hPr.run( d_ =3, 1] A = {=JO+ ('Q',): 1,>llinear7}A{assertEqual.Tr.res dssst_loop6_importingQ@9JC A:(fix_ext_py(4Rmod._S_), '@', ''7:@skipIf(hasattr4, 'wk') and 'pre-exisBtion throws off measurements'minst_methodK4obj dC2(20F Oobj.Y%q{W,DC716CTrs\ount=0, trace=0, countcallers=1) self.filemod = my_ _and_modname() .#@unittest.skipIf(hasattr(sys, 'gettrace') and sys.1(),Bs'pre-existing ? function throws off measurements'@def b_loop_`_imporL(%):v.`Pr.rund( d_ 9J3, 1pexpecte {S((os.path.splitextV"._F_)[0] + '.py', 's T*'2+ (<',))): 1g(E csimpleB >8 `linear:|( b+>fix_ext_py(6mod[P`estmodR'}assertEqualr.results().G4s, ) # Creaseparately for issue #3821 class TestCoverage(/3aseQsetUpnddCleanupX#.sV,QLtearDownOrmtree(TESTFN5feunlink#G$_c,rr cmd='@.supx,_pprint;'_w '%8_..De.QueryD'1fun(cmd3r =r.write_ show_missing=True, summaryDdir=JK37 . with captured_stdout() as Jl. 3# =<@valu>BBIn("S.py",5N#+Icase) # from "f;s = os.listdiryV1", Ap.4s) def test_coverage_ignore(self): 1# I! all files, nothing should be traced nor printedAlibpath = os. P.norm (pdirname __dE__))A# sys.prefix does work when runnfrom a checkout@2r = .T(`dirs=[_Rbase_d,pDexecP "],f=0, count=1 with captured_stdout() as u\.(M%ifPexists(TESTFNFNs|tlistdir( massertEqual(8, ['_importlib.c*U']) _1__ PAdef Vissue9936P 40mod@ = 'X.*dmodules.Amod'|# Ensure that the +@ is uted in 7 if(i!in7s8del[]Hcmd = ("_ 5t;"9 "t.func(0); V2();"C0V, cmdR{}.seek(0readline(age = {}@for )]S ;s v,k ul@.split()[:3Hhf@ule]Y@int(5@s), cov[:-1].XXX Thisneeded to&P regr30.pyva scrip*S_full(&mx-%]. J3In(=fH)s^, (5, 100)) ### Testsdon't mess 1set and can>themselves TODO: SkipTQhDB\rinvoked-T option. class_;Q(unitxCCase.cd,"jn-U.joinfi['x', 'y.z'], [jn('fooobar')]~CTrue.xps('x.py6'x'ZMFals4y5y654 `, 'baz{) } nore.names(jn('bar', 'z.py') S')) # Matched before.self.assertTrue(ign vnames(jX%baZ0baz\> # Created for Issue 31908 -- CLI utility not writing cover files class TestCageCommandLineOutput(unittest.T'aase): @codeGp = 'tmp8verr'5def setUp(!):2$with open.], 'w') as f,0 f.e(textwrap.dedent('''\U)mx = 42Zif []W.0priMunreachable'!!'' rtearDowjunlinkI 7)*x_?_Q s_ten_no_highlight]s@argv-m trace --count'.split() + [~e]status, stdoutberr = _python_ok(*gP%os.path.exists.)8 dEqual(f.read(),"21: ?\n"""H?  4 --missing   >$ 0c! st_failure_errors = (o0(b'C is : required 9 the main optionso!-l+T'`(b'canspecify both --listfuncs and (--%$or()Q/lcR argument -R/--no-report:aTallow*3r/-'X/rRXTmust sone of , o !, Rkcallge-Xps -f/--{7-summary can only be used with --coun t or --report', '-sT'), (b'unrecognized arguments: -y4Ey'))3for message, *args in _errors:'a*_, stderr = assert_python_failure('-mcctrace'PlERself.=5In(zX!) qdef test_listfuncs_flag_success(D) with open(TESTFN, 'w') as fd&}ddCleanup(unlink, 8 fd.write("a = 1\n" astatus1out,okO'-l's b'tions called:'gAand_ =PmixedGP@a, bY*=0Pa + b\6 Q/2(Rs\gst sortnum(*nums, reverse=Falsea*0ed((-).6)F)1s(*(V7`8aclass Foo`__init__ %, ~rvk1 = k122O3setJp L!umL=:ld 2 class Keyword OnlyArgTestCase(unittest.!): def assertRaisesSyntaxError(self, codestr04ashould4 3'+compile(s, "<>", "single")'j.(U/, m Ic;ForFunctionDefini  }A ("Vf(p, *):\n pass\n ?1, *, p1=100H-_k1, kJ2H1o, **k1-J5ONoneL/(t!2)Ow}`ForManlumentss# more than 255 posbal arg4 D1 okj00fun#= )%s % ', '.join('i%d' % i for i in range(300)f([ keyword-only#?*, TD=+0TooP|Message5sf(a, b=[1, c M#g ]with cQ(Typem) as exc2f(1, 2, 3expected = "f() takes from 1 to 2F but 3 were given"Equal(str(exc.excep*4), v)dLCall6f. b"Zk=1, p2)U61=50, *(1,"ti allWithUnKAu#, w_sum, (O :nodefaultsE:Foostry: # keywordonly_sum(k2=100, non_existing_arg=200) 2self.fail("should raise TypeError"0fexcept:JEpass:trynodefaults2e<def testFunctionCall(i).assertEqual(1, posW&1),++2.,**{"2":2}8 -+3:_(2,3)7/+49z@4":4zW :w ,o1=1, k2=2)) o"qand_kwargFg/Go, k3=3 U+3+4,s h? L a":3,"b:mixedarg6q1qW+ 8_2, k1 =4\?+5,E34H57 2k 9&>"F  o+4+5+6!92, d6j(**{'k2':5, 'k3':6Foo(k1=1). $, /,p4 [1,2,3], sortnum(3,2, ["2B, reverse=True ['a','b','c'G!s(c "['$?,'a@'b', reverse=True)) self.assertEqual(['c','b','a'],(/sortwords('a',5 reverseg, ignore='A')) Qdef testKwDefaults(!):d" foo(p1,p2=0, *, k1, k2=0'+return p1 + p2 + k "k2k"\ 2, foo.__code__.co_kwonlyargcount {"k2":0}C3kwd&__7_p = {"k1;6tryv1,k1=10Lfail("__W is not properly changed"@except TypeErrorsBpass+t }_methodclass ExampleLBf=2iP().f(2), (1, 2 :3.f( ()EC uRaises(5,).fE;issue13343-# The Python compiler must scan all symbols of a function to1# determine their scope: global, locwcell...8rThis wa-done forD a value|0key>arguments in a lambda:0iniQ, andNfollowing lineCused to  with a System]P=unitYk: NonemmanglingkX ___a=45__a X[), 42_N _eOal_ordera# See /e 16967nea = 42+2Nam{) as erf(v=a, x=by=c, z=dq lstr(err.Hion), "name 'b' Ydefinw#4f =_ -p if ____ == "__main__"?.() import #&Q from 0sup18tfilecmp$os &sy ubprocesThutil+textwrap KEYWORD_FILE#= x.findfile('keyword.py') GRAMMAR_FILE = os.path.join( split(__file__)[0], 7 c'..', `Pythongraminit.c') TEST_PY'keyword_test54= 'V.3c' U_WITHOUT_KEYWORDS = 'Cmal_b]NONEXISTENT= 'not_here.txt' class Test_isEQ(unitaCase):+@def _true_is_axS(self&I.assertTrue(Z.d'J')) ZuppercasedhOFalsi>RUEinone_vale-DNone# This is probably an accident of the currimplementation, but should be# preserved for backward compatibility., changing_the_kwlist_does_Hffec0old14 = BcddCleanup(setattr,02, '23', M)= T = ['itsP0all1eggAbean 0andauslice']NjQKQGener{gUR_copy<without_g;$eds, source-0, d[t`Bi open(+'rb') as fppklines = fp.read(QQnl = [0][len( .strip()):1}O, 'w{fp.writeRX: .index(b"#--starts--" + nl) + 1]P O>endM':],} |=3mar}dtarget$_proc = sub Qess.P[sys.executable*q/ f], stderr=6IPEt =c.communicate()[1breturn% Dcode_@skipIf(notkxexists()'C only works from5 build directordef test_real_grammar_and_keyword_file(self): a._copy_without_generate>s(KEYWORD_FILE, TEST_PY)O addCleanup(support.unlink6 ssertFalse(filecmp.cmpw xBEqual((0, b''),  s(GRAMMAR, ?Trudef test-U openM !'w') as fpnW'# Some of these are probably implementation accidents.? fp.writelines(textwrap.de,Y("""\/3o{2, 1}{11, "encoding_decl", 0, 2, states_79;b "\0004"H8d", "jello"o326, 0@ oturnipA0\t{!This one is tab ino/edO{278r crazy but legalHS"also =continue" >_lemon!#_tomatGf_wigiiB"'no good'}?283  "too many spaces"}""")Xc ; 3expected = ["O '&:',"C3%# P*, ) &! M!I ]U[iQ = fp.read().splitlines() start = .index("#--keywords--") + 17?end53/dactual2[]U:end]"self.assertEqual(3, expected) ,def test_empty_grammar_results_in_no_(V!):9._copy_file_without_generated:KEYWORD_FILE,AE!PY<_WITHOUT_QS{ ddCleanup(support.unlink, B`hutil.(dys, TEST_Ev6 (0, b''), UCBos.devnull@"g PTrue(cmp.cmp(3G R65_pymarkers_produces_errorXrc, stderr = #NoY0#bRegex(u does not contain format 'umissingA@1NONEXISTENT (?ms)' + o.encode()5,Z if __name__ == "__main__"@unit=.() # # Test suite3 the textwrap module.(Original~@s wrK)n by Greg Ward . # Converted to PyUnit7Peter Hansen _O, 80 ocustom3,5#=4.def test_(%):,pe//60/ ># SF #847346: ensuretmP doesEright th even on input short enoug!itB"n'Q7 toIZR$ AMmP. Note single spacB 9:?(^GD!# X9PhairyA cas/?at #asupposA handle (Reasy stuff&Wed in<a_white () above).$JWell, Doctor?ado you/k? 56B'!\n8c'I say, chaps! Anyone for "tennis?"\nHmmph!'8 ?@# @r.wrap(text), expect) wrapper.width = 20, = ['I say, chaps!', 'Anyone for "tennis?"Hmmph!']Eself.check(krap(text) =a"d she said, "Go to hell!"\nCan you believe that?'t.AnG%',*B '\# \% q' v6v 'yFile stdio.h is nice.\*#def test_p_short(;%):0# W0ing Qmake ( lines longerP"This2a\n/paragraph.".lv, 20, [Bp"?I "g%])h4h B( _1.Test endcases> F3/."=E(1)  }]Zinitial_indent="E2") hyphenatedPbreakB*^ word ("this-is-a-useful-feature-for-"T"reformatting-posts-from-tim-peters'ly.  \.[ @ /41eq2&  ">Q# Thes current behavior but1not"parts of the API. |is-|a-|||| "ref&ormatting-|posts-|from-|tim-|peters'ly").split('|') (self.check_wrap(text, 1, expect, break_long_words=FalseA_B?/) i('e-mail', [ ]W'Jelly-O0 1# The test s current behavior but is no"ing parts of the API.half-a-crown', 'B|a-|]1def_hyphenated_numbers(w%):n1# TFhat . . (eg. dates) arebroken like  = ("Python 1.0.0 was released 994-01-26. *1*5\n"*. ">c2-15."(O 30d -',oO /'1 D'L4 ye01, )j/ = "I do all my shoppat 7-11._25, [C""i/27kW9k/em_dash$ext with em-(-esEuld be written -- thusX ? ["b "~]5q# Probeboundarieproperly[p# ie. ""98w U/ =.W? --Z"] (text, 30, expect)  self.check_wrap(text, 35, e*%6,LS["Em-dashes should be written -- thus."]) C# The improperly.eJ is handled too, becauseAit's adjacent to non-whitespace on both sides.9 = "You can also do--this or even-%."7&L = [:""AP$u5."]g1.16/-- %79* ` 2{/31'-o J.32{/Z# All of the above behaviour cdeduced by probing0E_split() methodX@Heredand--hother---and an!jLP", "  an K0em- 0and8M@0!!gA~ thi@bam! was gone 8@g@ "he5was jZdef test_unix_options (!):"x # Test that Unix-style commTline < ar(apped correctlyT0# BpOptik (onParser) BDocutils rely!px0use3 -n, --dry-run in its long form M/20  6 z// "1 run in its long"?, "form."])# self.check_wrap(text, 21E ["You should use the -n"2 "option, or --dry-ru1 in its long expect =  o" h B32, E /34*5*8*~?run!9U.41*:"4# Again, all ofabove can be deduced from _split().@AB = "|f9 the", " Z #or D!fN3 !]?( def test_funky_hyphens (<!):## Screwy edg;ses cooked up by David Goodger. All reportedFin SF bug #596434jrP"what--hey!", [1X --#  OK/--I ?.@A --"--?7]) "When I first read., this is I thoughtFwas talking about. I `wrong;Wse have always workfine. Thel problem~2 ed_ <vparens(H# below.. "--T  &: 7 ?opt Hfoo CO barC ["foocu:lFVTpunctVUOh bother,#965425 found another problem with hyphens -- #'ated words in single quotes weren't handled correctly.G$In fact, the bug is that *any* punctuation around a{IE waso%inq, except for a leading "--", whichIas special-cased6Optik and Docutils. So test a varietyGof styles of B (Ally thisb"n -report, #813077)Dself.check_split("a'wibble-wo' widget",['the', ' ', "@C", "D"'L5'])M L) ""''@" ()@)[M/']B/']R# Thes current behavior butn1not'&ApartA?APId what-d'you-call-it.U "0|1|2.a'|')) 1def_funky_par(a!):"# Second w!SFS#596434: long opN`stringGsideD]otheses rfoo (--N_) bar P["foo 8@]1Rel^stuff -- make sureBworkwmpler context0barz3/z" q"blah (edong), wubbap 5c=E? ! "GgI7drop_whitespace_false?C0 2 =F2 preservM%# SF patch #1581073Xc = " Tasentenceh@much%."BPwrap(RO, 109[nK! %v Q "with ", "much whitespace."], Qdrop_0,=False) 0def test_% _f%6_only(self)::j# Check that Bg preserves a-N string.O^ .cR_wrap(" ", 6, [ /],e"_T_indent b gets Aed (when#B is y? "sinitial_=" "  ? on#] wleading rdoes no MG (iffollowed by non-)## SF bug #622849 reported inconsistent handling ofyjZq; let'sDa bit, shall we?7text = " ThisLa sentence h%."> YNO, 50G[j/])l 3l"/."<d__line9skips the whole AQ if a# !s (of,w@abcd?Fefgh# Include|result forJYcomparisonDxS|9?jb ? applied to#} Rvspecial caseBfacteGpingH occurs before ), t="++") def test_drop_whitespace indent(self): # Check that > does no W L's.G`This cL s a special case of the facthGpingSJoccurs beforek6ingm.k _wrap("abcd efgh", 6, [" R", " %],ainitial_=" ", subsequent!) FnOspliRbEnsurestandard _1 ) method works as advertisedaA# in7comments|text = "Hello$re -- you goof-ball, use -b option!"CPresulELFCper.`)"n(6 K[mPthere H5"-- 5you "J! "%&usH&th $-b#$ "]break_on_hyphens  2 attributes yaba daba-doo"1/@, 1037 _=Truehbg]FalsePad_widthI #` <= 0 Vaught :Whatever, itfn't matter.I assertRaises(ValueError,  , R;, 05,-1"no_at_umlauo Die Empf\xe4nger-Auswahl7 3!Di AE _followed_by_das0aa - 799"Anon_Ping_sl 'ientence with non-B\N{NO-BREAK SPACE}S&.'V,20D![{'/% '& k;  ['This is a sentence', _'with! non-breaking\N{NO-BREAK SPACE}space.']c<_on_hyphens=False) def test_narrow_non_1Aing_\q(self):.text = ('Thi  '7;'oARROW ,z.check_wrap({O, 20[] &  4TruX 9q class MaxLinesTestCase(Base j = "Hello there, how are you t~fine day? I'm glad to hear it!"lsimple fO, 12ko[...]"Pmax_l5=0)euB1u6" "23s[>>U80, [6], }^?you ;& W& s) %6s# strip  before placeholderk5Zre you",  "this fine", ""day? [...]"](max_lines=4)M# placeholder at the start of /+self.check_wrap(text, 6v["Hello 2final spaces + ' ' * 10, 12 ?re, how are you( O I'mL glad to hear) ?it!16) ?def test_!): mT?...1f='...'+gj# longnd indentationQwith assertRaises(ValueError 16, initial_` ='('B(1,=' [truncated]1subsequent2> (: $@? E0  s= 4/ 2/Q80, [m6], placeholder(='.' * 1000) def test_placeholder_backtrack(self):*.*# Test special case when max_lines insufficient, but whatBwould be last wrapped = so long the h cannoDbe added*re without violence. So, text_ 's,iaddingh toQ penultimate.6S = 'Good grief Python features ar@vanc^quickly!'CRp.check_(SF, 12i[oB', 'r*/']7/=3%f ='R*') class LongWordCT(BaseA\setUp,per = TextW:r()V0''\ Did you say "supercalifragilisticexpialidocious?" How *do* 7pell that odd word, anyways? '''`break_u # E`Q s and lots of punctuation\O, 30/[' ';/ ' 9 85 T+']5( H # SF bug 797650. Prevent an infinioop by makBsureo  leone character gets split off on every passb*D'-'*10+'hello', 1I -" h-e-l-Fo subsequent_ind= ' '*15#H11460 touwrongly7the8QpreceM is exactly @shor AthaniUwidthI 5 5q '"supercalifr', 'agilisticexp) ialidocious?) " How *do*' you spell& that odd% _word," anyways?'])  def test_nobreak_long(self):!1# Test with &_os disabled.=.wrapper./?= 0*width = 3 expect = ['Did */ay''"";a o '%, L,]Presul fe.text).%bcheck(9", ^# Same thing kwargs passed to standalone j) function.k`" ="y!, M=30,/=0Ymax_lines[x_/12  +9 ) 6) [...]']=4) class IndentICases(Base"):# called before eachb methodZQsetUpA< = '''\ Thiragraph will be fidS, fir0out! ia), and thendsome (includy`a hang 5b).''' Uj M"th$()   ; #?, 4 initial_1 % parameterZ ["  "" 6=m K" J40, ="j"\n".join(expect)# result = fill(self.text, 40, initial_indent="4%")=/bcheck(H, expect) %def test_subsequentMk!):&W}# Test ( parameterR,d = '''\ * This*graph will beed, firstkwithout any ation, and then& some (including a hanging#=V).'''M6 cN* ",}|# Despite similar names, DeoCase is *not*+inverse # of I){! class?P(unit.("):assertUnc;!ed , a2"""(q that d() has no effect on '9E'"""L=`Equal(",C &))___nomargin# No lines 5ed.oQ = "Hello0re.\nHow are you?\nOh good, I'm glad.U2# S ,  a blank o\nBoo!p , but overall *) stZOzero  iG@Agai/dd /\nq?eve1All by two spaces* +% -ca?\n .$f97 H g3amedbs.0;3Now@ one7the9/ { /unL '-ly'''\ def foo(): zwhile 1 `return305''' expect = '''\ d] UMEself.assertEqual(V, dedent(text)) u# Uneven in ation with a blank line.0@ = " Foo\nQBar\n eBaz\n",{.,* (9whitespace-only URtest__declining(I3o level q" # 5 s, then 4ZD ^\  @"\n<;m m .K#) should not mangle internal tabs3 preserve_+_+ $hello\ttherehow are\tyou?[) 1/make sure that it s w Cit'sking any# changes at all s L0 in margin (i.}#3and both count as1P, butca *not* # considered equivalent)#\t ""UnFdsame efff we have 8b! 73"()removes  that can be uniformly removed! text = "\thello there\n\thow are you?"/Qexpec1 /-self.assertEqual(>, dedent(|5)) ]+ c)) e/ Pe 3# test margin is smaller than Pst in\n \tI'm fine,V/ks:8ly~H@ # TUSwrap.qclass I!Case(unit.!):# The examples used forJs. If any of7se chang5*#edHresults in, variousI cases must also be updated.>roundtrip0separate, because d doesn'tH handle Windows line endings"ROUNDTRIP_CASES = ( # Basic"Hi.\nThisSa esting.",(# Include a blank}E \nG0lea and trailingZ_ "\n #\n) + /UsC! r%\rw[Pathological9 aB PP1def_2_no_default(H # should do nothUif 'prefix'Rempty9x9 T.B?  a, ''), explicit(bsame a[ d, but H"qusCthe ' behaviour by pass2Nonche predicateA1 , d@all_s # The s&ame as test_indent_nomargin, but using the optional # predicate argument= lambda line: True&for text in self.CASES: jassertEqual((8V, '',!),N!) A;def_ s(R)e# Explicitly skip b1anysROFals:nroundtrip_spaceqA white-fix should = with de ROUNDTRIP_N )O_tab_\t\t'^mixedt{\t \t _defaultSTest ?"of> that are notEonlyo0pree= ' 'expected = ( # Basic7 ca{ " Hi.\n This is a(esting.",NInclude a blank!ShU BleadOpd trail h^0 "O+\nUse Windows0 ens [rb -\r_PathologicaloQE sN "w ^)fo", 1zipn'edR.%Y)> eude a blank eline  " Hi.\n This is a test.\nesting.",4 # Include leading and trail `blank hs5"Ok3 Ti+\nkUse WindowsT0 ens [rb ]r_Pathological casQE \ ^)for text, expect in zip(self.CASESEed):7#assertEqual(indent(Oprefix, None)D!) B1def_2Q_all_wgr# Add 'L' to allkAs, iwhitespace-only ones.j>u = ' 'eed = ( # Basic t% #&a {o |WQ4 *i 2 \40predicate = lambdaLV: Tru]N _empty`solely! X AI n MQ ie"S findfile class TestFormats(>.CCaseULdata@for Q, expected in (Q"('.8svx', (' 0, 1, 0, 8)),3Aaifc3 44100, 2Q/168 f8 8u64.nAhcom8 Q220504O, -1 Asndt: t1"voi 1wavhgG4 = A(, subdir="%?cwhat =.>)NotEqual(/u, None,i6Sequence;5-.Ftype?[0]9xramerat:1:nchannelst2:fu838AsampzrA4]) }ZMable0ile XPprotoKbrange(.HIGHEST_PROTOCOL + 1sdump = 1sHS 7`loads(=0),  """ Very minimal d!s arts of the readline module. =contextlib ExitStackUerrno$IOFloca$osselectorubprocesy @temp>unittest from test.support im _module, unlink, temp_dir, TESTFN, verbose fromJ.script_helperX assert_python_ok # Skip; s if there is no readline  =P$('') if hasattr(, "_READLINE_LIBRARY_VERSION"): is_editp= ("EditL}wrapper" in.Oo) elseS.__doc__ and "libx _") def setUpM(f|l1# PYlementations oVs than C#may not haveAthese private Eeibutes#^ VVprint(f"tsion: {TEe:#x}"){HruntimeP tRUNTIME X 1 library U(!rSCuse Q emulF? {i7r @unitkipUnless(clear_history"),\S"The %@ upd ]@ can4be run beca_the "J qr method t available.") class TestHSManip% ("CCase"""zT0s wBadded to checkt\Oq on OSX"th %l"%>same interface for(mr. That'61why< cover only a small subset o^.S CUcs(self M y1() D "4add ("first qM +dsecond,X.UEqual}D.geti_item(0), None=O1), E2E{replace3, "W/)y_item(2), "second line") self.assertEqual(read%.get_current_history_length(), 2D3eremove.item(0)ld6o, None="_1), "<1 @unittest.skipUnless(hasattr<, "append ufile"), ~ 1 not availab:9@def {p_write_w_h(!):&Thpp = temp .NamedTemporaryFile(delete=Falsg:v.close(}qname = . o~.addCleanup(unlink,+*=# p-clear-u == nopS#H!%adgt("firsto+ !(,x_E( 0a04e r%2C mwE21  1{=S* RK :3gz 3'no such 8' behaviour2os.%UWwith pRaises(NotFoundError7#  can create the target3g"nonasciii UG6try  entrée 1") except UnicodeEnrror as err: self.skipTest("Locale cannot e= test data: " + format(err))Lreadline.add_history("entrée 2"*treplace._item(1, 67Fwrit5file(TESTFNcaddCleanup(os.remove, +Tclear(L!  _wif is_edit  hX# An  ) call seems to be requiredbE getnf!# ))5registers from the 5 Wdummy8ssertEqual(7'1)1D#2D2 class RRP(unit.qCase): @&If_READLINE_VERSION < 0x0601 and ,N\ "'supported in this library version1def(`_init(I) # Issue #19884: Ensure thatANSI sequence "\033[1034h" is # ten into stdout wheBp module>#im0Nis redirecto a pipe.#3rc,fqerr = a#_python_ok('-c', 'l 6'Y f TERM='xterm-256color'V.|b, b'')Eauto7script = """\  X.set_8({}) input() print("H length:",.fcurren'r()) """!k_enabled1Poutpuqrun_pty .:.GTrue*LIn(b 1\r\n", h<?dis3OFals0 nonasciikqloc = l (.LC_CTYPE, NoneZ if30('CgPOSIX'X # bpo-29240: On FreeBSD, if^LFis C or M 1ing non-ASCII bytes/a TTY works, butAline or ncurses ignores non-ASCII bytes on read. "self.skipTest(f"the LC_CTYPE locale is {loc!r}") >Etry: R] line.add_history("\xEB\xEF")-except UnicodeEnrror as errW ""Lcannot e= test data: " + format(err)script = r"""import is_edit #0ead .__doc__ and "lib$2" iK" inserted = "[]" macro |t[after]" set_pre_input_hook = getattr(O>, "(", None) if 0or 1Tb# The _() call via Q() doFthing with E",# so include 9extra text that would have beenyqed hereCQed +  .parse_and_bind(r' ^B ed-prev-char'r5 "\t" rl_complete6-s ^A "{}"'.n)) else Control-b: backward/: set disable-5ion off;show-all-if-ambiguous>"unmodified? dM def uS_( +edredisplay(I6(,!) b0er(u, state)"ifA== ""9"if+V == 0pprint("P", ascii])#''1get_buffer()=indexes",.:begidx()1end creturn1nt"1 4x4 /!x"S (A%   substitution, matches, longest_s_length9y/Iq/))Cion_!es2(display) print("result", ascii(input())) print("history!readline.get_p_item(16c""" M! = b"\x01" # Ctrl-A, expands to "|t\xEB[after]">+?2" * len("))PMove cursor back>1t\t} Display possible completions9x8C'1e "Tx" -> tr output = run_pty(script, )yself.assertIn(b"text 't\\xeb'\r\n", L40 '[4 fnJBed]|C7Jindexes 11 13~if not is_edit|and hasattr(+, "set_pre__hook"):/ substitu @matches [BDnt',HOxt']expectedxr"'[\xeITxebxtJ U@ " +Q+W@A# We have 2 reasonVskip this testl0# -#$: fsize was added in 6.0[ See https://cnswww.cns.cwru.edu/php/chet//CHANGESB$-  r is broken on OS X 10.11.6.: Newer versQ wereqbed yet,P@unit.%Ifz ._READLINE_VERSION < 0x600,e9 "2{Q doesztsupport<-<" nP P configura(h1def}4(R_B = 1with temp_dir() a!%%rc = os.path.join(g-3, ""4aBopenLrc, "wb"jfc/f.write(b$X %d\n" %)^>Ofile' _G #P * 2 `s crasp< `@dataV"""I b"9i1Pfor idrange(B* 2) 2\{9 script = """ import os %readline history_file = os.environ["HISTORY_FILE"] 4. _8( ) input()1_write2 ' env = dict()#["INPUTRC"] = w.rc% 8 =  0run_pty(script,Tr=b"last \r", env=env)=with open, "rb") as f:mQs = fV(self.assertEqual(len()%),Osize7 ines[-1].strip(), ") def [dummyRNone)0ptyi_module('pty'output = bytearray[master, slave@pty.F=0arg$(sys.executable, '-c', *proc = sub Pess.PK(B, stdin=i 7out4erros.close(9hExitStack(rcleanup9.enter_context(E$rterminateA!:tryD.7O except ProcessLookupErrorH# Workaround for Open/Net BSD bug (Issue 16762gkEpassPcallb , ? *c", +# Avoid using DefaultSelector and Poll. Kqueue() does notq# work spseudo-ls on OS X < 10.9a20365)fKq20667).xnZp10.6 or`4Ifeitherq472). Hopefully the "deor is low enoughLbto uses#5(). dsel = { .Bors.JFor()sel.regi(&, 9EVENT_READ |VWRITEKos.set_blockingNGFals whJTrue[_, events] inq.(#if, &*<&s. _6zRchunk0v0x100001!OS/er+# Linux raises EIO when*d=2538x  if err.errno != EIO: _raise"chunk = b""$qif not 'hreturn outputH.extend(O))vents & selectors.EVENT_WRITE?tryinput = [os.write(master,=):]<except OSError as{k# Apparently means the slave was closedos8 # Stop ?ing7sel.modifyH READ) if __name__ == "__main__"^unittest.() import contextlib &$io$os eshutilUocket&ta ubproces:y tempfile9Ewrap%im` from  @ sup.!cript_helper TESTFN =9. class TestST(v.qCase): 1def__module(self)}p.%"ftplib"7.assertRQsy@Skip}, M, "foo")_fresh + get_attribut3elfdEqual(60, "_1"),n9 !3B$ w, fH@skip("failing buildbotsRoriginal_stdout  <r), sys.J lunload`G sch8YAIn(""\sC._- ?NotOlunlinkwith open(|`, "w")f=ApassQ PT;False(os.path.existsk)1 support.unlink(TESTFN) def test_rmtree(self):irpath = support.>e + 'd''Esubd*0os.4c.join(2, '$%')5os.mkdir$4Na elf.assertFalse(eexistsn2Ewithswap_attr(i, 'verbose', 0 $.-os.chmod, stat.S_IRUSR| OXUSRJU?08lforget8mod_filename = 56.py7yXopen(0, 'w') as fprint('foo = 1', b&=f#sy{ in@(0, IVurdir& imlib.invalidate_caches(&:try~mod = __?%__H(#In" , smodulesw0VF('S?NotV*kfinall1delI5[0]1!un Q'__py63__'LHOSTsEqocket.smts.bind(s.@ms.close(jfind_unused_ vy /b'\)A =jilistenB # Tests for temp_h <c0""">W that> creates and destroys its directory."""^`parentz! =Gx (@real( + = {:dir, 'temp')' self.assertFalse(os.path.isdir( )))2with support.temp_)A as 7:6sleEqual(, , 2 h 2?Truczfinallyrmtree(parent!) def test_Pdir__`_none()P"""Test passing noA."""LP)Le.23existing __quiet_default a directory that already TszEcall^S37:raise Exception("should not get here"0T! =file.mkd-("7@realMH,trfxBBRps(FileEsError, 8S# Make sure2 didelete the orig. eehutil.d#thu ^& ztmw  y= )/ vdcheck_warnings(recorderw ;i&, EFJ:B+, . = [str(w.message) for w in .-]C~ Dlen(e), 1, % =&[0PgKp.starts0(f's may fail, unable to create 'h Mvmporary {path!r}: '),  pwarn) @unittest.skipUnless(hasattr(os, "fork"), "& requires os.G@def _temp_dir__ed_child(self):+v"""Test that a + + process does not remove the directory."""N# See bpo-30028O details.%1RunE as an external script, because it usesKkD& _helper.assert_python_ok("-c", textwrap.dedent(import osAfromB 0sup( %Swith .jPcwd()FpatheWTpid =)()R 0if #N!= 0=!# parent(1has:C== 0O/`# waitG{8to terminate>(pid, status)G2pid07#if4 (qraise AionError(f"Cqfailed sVexit pD"f" indication 0x{_:x}."3Make sur5at  is still present. WheZM#aleaves'Ucwd'-con, _____()-Mmethod of0=\ mustc_oraryJ!!ifQ0os.p.isdir(T_M LdTAC""") #  change_k5d original77getCt\  2} 0newwcEqual(*"mpX  54os.#, B70 5NP__nonPstentPBpassing a non-exi2)}Wcall__q+ PExcep("shouldget here j& non_exis tent_dir = os.path.join(par, 'does_not_exist') &self.assertRaises(FileNotFoundError, call_change_cwd,BM 2nonl%) 1o Equal(os.getcwd(), originale5def test,__a__quiet_true(c%):r"""Test passing a non- ent directory with H=True."""El@support.tempf() as ,0bad%R! tcheck_warningszrecorderx| ;(, 0newIMtF. ,  < I C = [str(w.message) for w in .-] wDlen((e), 1, % =5[0]P?Kp.startsk0(f's may fail, unable to [% 'M f'the curP workJ3o {!r}: ') # Wsm(TchdirC hP whenB!()As> = TESTFN + '_\ 4 70y= 2's:Uydmsg =  ?msgE6`f'to {}3msg}NBhere !@Rname=G0Z 4@base7#),) self.assertFalse(os.path.exists(TESTFN)) Cself16Tru0qbasenamgetcwd()), here) ?def test_temp_cwd__2`_none(X!):(j """Test passing None to ;e()."""/originalVd = os.#with support.G=]) as newBNotEqual()(, y% 7 )TisdirAY 4h,g/ sortdictw R11 {3:3, 2:2, 1:1}), "{1: 1 2, 3: 3}")make_bad_fdsEfd =(yRaises(OSError*cmos.write(fd, b"foo"P cm.exception.errno, l.EBADFcheck_syntax_e 7*0, " class", lineno=1, offset=9A2ion ~=x=1pCleanIm  i 1libMUA"asyncore"2D. _module(1 <DirsOnSysPath *'foo', 'bar'1In(B, sy| +Obar"+'?NotU * T^ -captured_stdou  ,8 "print("hell <M`value(5-\n@}?err ,?errp, file=fstderrV !/in4in(*inSstdin'1'Y#jseek(0a# call+ code that consumes frome-PW = input(Y !l(captured, "hello") def test_gc_collect(self):#support." =python_is_optimizedFelf.assertIsInstance(\A|), boollswap_attrbclass ObjEpassPobj =$(()e.x = 1Twith pobj, "x", 5) as xi7Equal(obj.x-Y 'Fx, 1 F# yyy IsNone(yFalse(hasF'y'), @del y/ o-LitemD = {"x":1}2:DoD["x"]G   G OD["y  pNotIn("pD { c"@RefCMkibute1 = .2q_hidden2<__magic_1__=X_Other n3Kf2detect_api_mismatchmissing_5s =;.^,%{'Y1'}, z ~(W3', ' __ignoreH = [1&,  ~, 'not_in_ei"']O= support.detect_api_mismatch( self.RefClass, SOtherrignore=)?(assertEqual(set(), missing_items) 0  = support.de~*def test_check__all__(h%):extra = {'tempdir'}blacklist Glate! a,D kOfile' =* = BTextTestResult', 'installHandlePload_MPs', "CProgram", "BasevSuite"}" %@unitm $(")!.r_case"B  Bs,/erCImainOrunnBsignals") 0 .Raises(AionError,S$, kk@.skipUnless(hasattr(os, 'waitpid') and WNOHANG' 'need os.H(H5os.>xreap_children# Make sure that "e is no o pending C processc f !# Create aBPpid =Vfork(1if 6= 0R : do nothing, just exit3@os._'(0t0 = time.monotonicdeadline$v + 60.0was_altereenvironment:try5 = False=stderr = io.StringIO($while Truel-if4 > 04)`fail("7Kout"r&with contextlib.redir(~5O 2 # Use environment_altered to check if reap_children() found a# the ' process$if support.u:0ambreak # loop untilz completetime.sleep(0.100)\msg = "Warning --*ed %s" % pipself.assertIn(msg, stderr.getvalue())2_True(/9zfinally@:d = was# Just in case,again thathre is no other`# pend2=L|2defl_options(, args, func)code = f'from test.]0 im[ {2}; print(repr(U()))' cmd = [sys.executable, *v`'-c', m]2env = {key:  for key,Tin osv.items( R0not7.startswith('PYTHON')}oF` = sub ess.run(cmd,#S wstdout=9OPIPE68err6DEVNULL9 universal_newlines=7 venv=env .`Equal(..rstrip(), ;;`return$, l5_B_D_interpreter_flagsi# Testl.?  @optsT(#D *[]8# single  ,K'-B'0O['-sSEvbqT# sam multiple n O['-bR-vv|C# -W D~Wignore/-X3}X', 'deg4['-NO, '-'faulthandler[?"showalloccount& ?ref$ atracemLG#c=3'], w ): with self.subTest(opts= *5)check_options/, 'args_from_interpreter_flags') sdef test;/m_2(h # =.support.E )v@for U in (@# no9ion:[],O'-O'Osr5 x`match_ aQclasse __init__4,;_id.^T_id =) Q!idKBbreturnI?access = ('spos.File(s+'-o_chdir@Win32ErrorF0Jswap_attr(F, '_g_func', None!# 'I alliHG.setIFs([]massertTrue.V)=#)va using *zjthe full identifier d_.id()DOFals module nameYO_os'D  '*' patter7*~case sensitivity@filet -atch_test(test_access)) support.set_match_tests(['FileT +']3elf.assertTrue(C?(Dp q # U pattern containing '.' and a '*' metacharacterBp*xQos.*. *.*/ schdir)) # Multiples q.id(), e-6'', 'DONTMATCHEOFals;2defQfd_count(%):# We cannot) the absolute value of ?): on old LinuxH*kernel or glibc versions, os.urandom() keeps a FD open onDS/dev/,q device4Python has 4:s instead%3.Fstart = #@fd =(__file__O_RDONLY6try.MOmore_ [inall7os.close(fd]laEqual(]!- 3, 1f# XXX -follow=@list un|aed API# make_legacy_pycis_resource_enabledrrequirec# fcmpEumak0ind'check_war$EnvironmentVarGuardTransientRGt0_in/#etrun_with_localedemlimi)`bigmem$Pprecix bigaddrspace1 I7doc*threading_cleanu(Rreap_ qstrip_pb_stder#k_symlinkiskip_unlessSuppressCrashRe5 Smain(Ps = [~8Aort]a@unit*(Js) if __name__ == '__V2__'-S() #  set -- built-in funct@ im m4sys dpickleitertools # pureiPimpleOaZ (3 args only), for comparis on def pyrange(start, stopep): if ! -) // step < 0#'# replace% with next element in the sequence of integershEthat are congru91to ` modul 5ep.3< +=%&@whilaart !=zRyieldh5z+38ep 1_reversed4 :greturn!opfet-r) class RTest(unittest.CCaseassert_iterators_equal(self, xs, ys, =_id, limit=NonC# check $n L xs matchesexpected results[I# up to a givenj"if is not Axs ={tools.islice()jy- -sentinel = object(IJpairHzip_longuzQfillvalue=LBfor i, (x, y)@enum!e(]if x == y co)ue$el2{9.fail('{}:A ended unIly ']v'at position {}; 8 {}'.format(GiGyu excessH_{} at \x, i)/se>Uwrong ? /_, got7a, x)) S7elf1ERlist(+3)), [0, 1, 2]4 A1, 574o, 3, 4:07--.r1, 10, 41, 4, 7;@5, -<5, 2, -1, -`ea = 10bbc = 50/A aa, a+2  1`a+2, a<+>4>z++eseq = e(a, b, c))  self.assertIn(a, seq)   No!b!Equal(len(CW, 2) H q = list(range(b, a, -c)l In!GB-b # -&Raises(TypeError, * ,, 1, 2, 3, 48 IValue90 Q, 0.0q1n m:7 _, 1.0ne100, 1e101, "spam"yV0, 42;(0, sys.maxsize J-1))U2r =$/(-51x)f def test_large_operands(%):xP10**2fo+10, 3.z/x)$2x4 wowBw*False(x", -s/, F(*:Tru'Q# NowZ) with longsWfor x in [-2**100),""?0, %If, -1)]J&[] *a = int(10 *Cb"#c#5" `a, a+25[ 1 self.assertEqual(list(range(a+2, a, -1)), [c+1]) self.asse>4>2>W+2]) ?Hq = r, b, c)bIn(a, seqNotIn(b!0en(C?, 2G&seq[0], a$ -1%/+c blb/b- -Ob, -#j--!-%-adef test_large_%):# Check long "s (len > sys.maxsizeS #  ) is expected to fail due limitations of the __len__ protocol"'(x6try`lengthZFen(xexcept OverflowErrorBstep = x[1] - x[0]Ee1 + ((x[-,P) // C {`return6gthWa = -Kj8b =cW = b - a2x =,H?b, yRaises(>,1HTruek ,3> 6  idF%+1>1idx/idx[idx:idx+1]+1Wwith ^QIndexY 8x[-&-1VKJ]N0C?2 *Gx[0], a)  idx = sys.maxsize+1 self.assertEqual(x[idx], a+idx)( :idx+1][01Wwith ^Raises(IndexError):]x[-expected_len-1]KJ%] IUa = 0b6**1gc = 2*36[ = 1 + (b - a) // c(srange(a, b, cL InhNotIn(b, QOverflowT_, len1_True(L_~X(x), 6x"o$v(idx*c)H=j:idxs 5,wSK i w-x4def test_invalidocation(Y~TCTypeP,, 1, 2, 3, 48 IValue906int(10 *"X`a, a +M0cA., 1w 3r, 1e1001A0, "spam"7, 42, "spam"3) +# Exercise various combinations of bad arguments, to checkCrefcounting logicself.assertRaises(TypeError, range, 0.014!O.0, h4!?, 17!p1 !p!m?0, p79r"9t[def test_index(5!):2u =\/(2MEqual(u.=/0) (/1)- DValu]_, 2) _-2, 3 P(/ (vclass BadExc(ExcepQUFpass36Cmpy(a__eq__{, otherM)"ifZ == 2Dr3/return Falsea43" 2, a,gWCmp()K F`(1, 10|/(4[ 6-73-3)8:-5)b :T0**2064B1 - = w{t`2**100, 2**87 ) ;(:+ 6bAlwaysFkobjectjETruea^ _eM8 = mFaBuserq_methodVbignum = 2*sys.maxsizQsmall! 42 ! # User-defined class with an __index__ method '%I:1def2it__(self, n)#'.n = int(n)CuDArreturn H?assertEqual(list(range(I(bignum), + 1))), []J TsmallL N5]) d failing9kXIl3)aise RuntimeErrorR&(s('!, 8o, IX()n invalidN!"not a number"a2TypNTest use of es in slice indices.>l/(10)[:I(5)]v((5>Vy W20, ZFX()]OL NLKtest_countL23)./o-1), 0=0_0), 1/^/2^3sIs(type@ -13?int54 Ud10**20Z 4B(h, 2**100, 2_2**87C >+~[ZbAlwaysBkobjectE__eqj[other%n-ETrueda^ _e'8 = m1Fw0) 63lenLsys.maxsize, 0+10\1GOrepr%G' ;+)'assertEqual(repr(range(1, 2)), 'C') self.assertEqual(;;, 3>1') Bdef test_pickling(P!):bcases = [(13,), (0, 11 p-22, 10 20, 3, -1),=A=0 21~p, (-2, ;p**65, 2E+2)]@for proto in e.HIGHEST_PROTOCOL + 1u=t9 Pwith .subTest(o=,+=tX83r =&*tY libje.loads(dumps(r,/))DZQ,r)iteratorit = itorgeJ>*t)rdata = Jq'kId = $it ,-dy Qtype(3),  8Pit),  >try >onext(iexcept StopIq?ionCcontinue)UO C[1:]!exhausted_7SW0 i 2while TruecZ 4sif r ==]1=%Ybreak&i2Z), []*2+olarge_`0: if r == 1O9: Ybreak d = pickle.dumps(i, proto)'&i2(zloads(d! self.assertEqual(list(i), []*2+wdef test_odd_bug(_)+# This used to raise a "SystemError: NULL result without e"d# because the range validation step was eating%Pexcep EBforeq/returned.$ $Ras(Type([], 1, -1) I^typesNon-integer objects *e*&aany of`'s items are supposedi#3be contained in<rIn(1.0,H6(3) %OTrue&H1+0j&class C1a__eq__, other):  uC OC1()j3# OG#never coerc"tod 0 fomparison!23int1_index*NotIn(C2KB# .. if explicitly told soSaIn(intT(Check that$#__=s__ optimizYuis only#Cints, notQinstances1subM6int0 C3 L)E3(11/10C)](. strided_limit3r =;0, 101, 2BeO1, rOIn(2;/99 0y rp 2-20 d\OIn(- /-1y l?-18^Qempty0r*ertNotIn(1, Sr) r = range(0, -10)self.assertNotIn!rO-1, _def test_z_iterators(t!):$# exercise 'fast' +, that use aobject internally.Lsee issue 7298limits = [base + jiggle for M in (2**32, 2**64&*N--M, -M//2, 0, M6}e -25e1, 2)]<(start, end, step] -aU!+?end)u* (-03,  31m^A1 ; ,a2 = py` sbid = "/B{}, )".formatC # check first 100 entriesQp_equal(!1,"2,Aid, G=100K/eversed(  $_r> 8 !2p&.)+0>_invocationIbverify*gq instances cannot be created by# calling their typ! _! =60))Raises(TypeError,K, 1, 3, 1>Blong6&q@1 <<yX~w\sliceb+BstopW=None3 = H/)/E*list(r[i]) ) 15%en42en(D8nr[Y(10),VZ ( 1, 9, 3>8-# sys.maxsize+1, }]109 check(0, 20) check(1, 2_20, 32o-30, -N`-1, 10mT817-3, -1) def test_contains(self):r = range(1%.assertInrn ?1, ?5.0 NoY/5.?!_ 1a )""9$Y In?In(0S  l K; reverse_iterationfor r in [,C/0)1, 9, 3"08, # sys.maxsize+1, }]Equal(list(rd(r)), |)[::-1] issue11845*5`*slice 18H.indices(20)Hvalues = {None1j0, 2, 5, -5, 19Z4-2:+96599}ix j8!k!j - {0}D'r[i:j:k]YnmpariscxAh30),p1G~51E5, 6> M>A5, 7'N2AA0, 4X7 range(0, 5, 2), range63] test_tuples = list(map(!, ;Es)) 5 # Check that equality offs matchesthe correspondingNns for each pair from 6s above.:_eq = [a == bEHa inbG GGself.assertE(", ,?_eqF"!=ctly giveslogical negatione,=="ne!$ne, [not xBxB]should havev hashes :"lv "&2if  A(a),*(bR$s are un to other types (even sequence)n"Is0(0)(), False-('/(0- '23e[0, 1]^# Huge integern't a problem, 2**100 - 14,\Z 02.` 3e)f8kl(No(e" 1" +fR2**20hP201 -@$99 @8x} ~ F b <l ;q} Order comparison implementedRpWwith Raises(TypeError)@?<K%>K7/<=Lf.assertRaises(TypeError): range(0) >= ! # def test_attributes(selfB#! the start, stop and step :2 of` objectscSb.asserj$s(1, 0/1)-210)+?0, /-0/-11&f1F0, 353P-1), O0, -+m  as,0obj 'ep,REqualEobj.?art 0 op_/op.e.2ep),Wwith Raises(AE = 0NO,oop = 1O6eO+5del* O/opN9ep if __name__ == "__main__"@unit.() import difflib fromA.sup!Drun_<, findfile?0doce sys class TestWithAscii(9.CCase(*`one_in *Dsm =.SequenceMatcher(None, 'b' * 100, 'a' +0bAlmostdsm.ratio(k.995, places=r6list(sm.get_opcodes()),rb[ ('' (,0('e"'1?1)]sm.bpopular, set()-5@ 50:@'50Q3elf?Y5?+50h@h'1,U'm5n self.as.sertEqual(sm.bpopular, set()) def test_one_delete(self):#"sm = difflib.SequenceMatcher(None, 'a' * 40 + 'c'b )[`elf.asVAlmos ratio(), 0.994, places=3<@listget_opcodes()),mp[ ('e', 0, 40 )-"('''#410,U'8+L80)]i_bjunkd is3=lambda x: x == ' '(a=p4, b4K/t ,a  D P/20S{' '}w!@in [^_ 'b']d+!,x class TestAutoP(unit.CCase0"""s for the a2 parameter added in 2.7"""  in_homogenous_s @# By<Eaultk=True andheuristic kicksx$a T# of length 200+`seq1 = *2al2200R \/q2T@o9{'b# Now turn(6offu,_False_.9975FoSFbugsl_for_nullenaCheck clearing#SF bug 763023*o[], []:!s.o1' oquick_-^real_2 Acompp_empty_s 1fixq#979794Ngroup_gen = difflib. SequenceMatcher(None, [] ).get_grouped_opcodes() self.assertRaises(StopIteration, next, AF_gen:@diff0 = lib.unified_(j<W!) :def test_ming_blocks_cache(!):*# Issue #21635s-"abxcd", "abcd"first = sH HOcond)qEqual(se:[0].size, 2} ,1,2,0Radded_tab_hintK Check fix for bug #1488943Y = list(  Differ().compare(["\tI am aEPgy"],?"])8"- -Agy",s?[0]6 ?D--\n717 H+ \to626 6? +a,3]lm _ct_stop_ibxU33224j  _mP(["2" "3I1)),3[((1, '\x00-2\x01'), $+3fTrue)]<P) p914575_from1 = """`1. Beautiful is beTTer than ugly.%2. Explicit$$tt$"im(@3. Se&[1lex%4. Complex&icated. /to O3. zm5. Fla?nesnonasciiu=ımplıcıtSxJ$ü9!ö02)Line 1: preceded by $:[tt] to:[ssss] W.2.(ss0t11 \t232m:[sstst] to1:[s] Line 4: \thas fromPt] to s] after :+65: (&] at end\t """ patch914575_to2 = A p1: preceded byutN@ss] ,!\t.2.(ss0t1_31sbd^s%L3lf0 1234567890  *1234 changed567)8 subtract<9`short just fits in!!A two%s yup!! the  +4add $GEa(G)6g"  another long that needs to be wrappedSSclass TestSF(es(unittest.qCase): @def _html_diff(self):# Check SF N w for generating HTML @uerences@f1a = ((=<_1 + '123\n'*10)*3)3t32-to0/f1b = '456Le + f1attf1a.split,s(t|?f1b>tf2K ,/to*f V3 &to1i =lib.HtmlDjtabsize=2(k(column=14)b full = i.make_file(f1a,t1a,' ','to',context=False,num&=5v`tables \n'.join(i[r '

CVq (first within c(default))

',I [True)=%_b,t1b@t6from','to',c ontext=True,numlines=6), b'

C,% ((0)

'.i.make_table(f1a,t1a,'from','to',cJ v0vSSame {nrncOFull`+_Falsea_Empty_[],[]1b_tabsize=2#jO2,t2EdefaultK <K (wrapcolumn=14kq3.splitK(),t WKpt5  |%])actual = full.replace('','\n%s\n1 % 5s) C# temporarily uncomment next two  to base this testEwith open('_difflib_expect.html','w') as fp::fp.write(Xfindfilea)^]self.assertEquale, fp.read()p1def_recursion_limit(B))Check if the problem described in patch #1413711 exists.X = sys.getq(old = [(i%2 and "K:%d" or "V:A ) % i for ixarange(GE*2)]q?newIBI.SequenceMer(None, old, new)_opcodes(`_}_charsej7K4 = yHtmlDiff&utput = 0bc(p914575_1p"+E*toC(jAIn('@nt="/#; =utf-8"', outpu#t) def test_make_file_iso88591_charset(self):/3html_diff = lib.HtmlDiff()'output = 0.d(patch914575_from1.splitlines(),EpE/toC"`='iso-6-1' .assertIn('content="text/$; A@B"', ctusasciib_with_nonOinpuvNn2N-1us-#>? ımpl ct class TestOFormat(unit4.CCaseLtab_delimiter?args = ['one', 'twoOriginal Current''2005-01-26 23:30:50.2010-04-02 10:20:52']B'udqunified (* , toterm='tEqual(list(ud)[0:2], [`_T"--- /\t"< S"+++ ? &"]c/xt%c?****  aRno_trailing_^on_emptyOdatef(,N 8", D"kqrange_f_1 ^# Per the spec at http://www.unix.org/singleI x_(ification/u = '''\ Each <> field shall be of~C %1d", if the range contains exactly one line, Hand: "%1d,%1d", , < 1 ofs> otherwise.MaIf a ris empty, its Y shall be them8 ofQ just befor.e, or 0 ifAo~astarts7fil5'''`fmt = difflib._format_Z_unified,self.assertEqual(fmt(3,3), '3,0')* 4*4(5(/,2*6*3* 00,0*0tdef tes@@ext()$Q# PerJ* spec at http://www.unix.org/single< x_(ification/wu = '''\c Thec@ in 1&pwritten`followP0two2mEVs "*** %d,%d ****\n 0endK>1and8 =}d 9#"anXlUprece .`M isdj (. QNext,`9 2[3---O----_ }=w( /3,5R6* ') class TestBytes(un0st.CCase # don't really care aboutv$ntroutput,I1act9# that it's bq #we^Qcrash)7Qcheck#,:?p= list( ) # trigger excep bs firs{71forU7  IsInstance( line, bytes, A"all"s of diff should be4 but got: %r" %.!) Jdef test_^_content(self):!n# if we receivV strings,Aturnn= a = [b'hello', b'andr\xe9']\ # iso-8859-1Bs;b;Pc3\xa?s# utf-867unified =Clib._''xt''(pheck =  .c (VfH#s(q, a, a))1#b) # now with filenames (gnt and@are /s!va'=b=# FdateWIeaC2005 13w1ObObF O2sam\over again,!xtl1.1ba  n=vzIO{ 0somebody rR1d aG from ISO2 to UTF-8^ fnb'\xb3odz.txt'S# "ł"..cc5\x82!'|8they transcoded the t}EtimeY[Xa is a city in Poland.']..O1odz2388_#i `b, fna ;* assertDiff(expect, actual# do not compd. equal as lists, because unitXqIAuses*0lib]Rrepor< erence between lists  actual = list(") self.assertEqual(len(expect), 6 7for e, a in zip2#, -:dj h>%) (sE = [7b'--- \xb3odz.txt', +++ \xc5\x82$@@ -1 +1 @@@@-\xa] is a city}Poland..+kO1odz2 ] = difflib. _bytes(unified, a, b, fnab, lineterm=b''}LDifftL # with dates (plain ASCIIGa = b'2005-03-18'b9`check(P!a,&b)I~context I># note the mixed encodings here: thisdeeply wrong by every^+# tenet of Unicode, but it doesn't crash, it's parseable bHpatch, and+how UNIX(tm)! behaves '\t09!  S#def test_Dq_types_0nt() # &cinput ' must besistent: all str or [b'hello'J[.Eb_''xt''(O"2s to compare@str,^ $ (%)"F"._6e_error7Ob, a7n7n#arguments "( a/, 3 assert_type_error(expect, difflib. _bytes, unified, b, a) self._assert_type_Kcontext, a, bK4def test_mixeds_filenames(!):*# cannot pass 'A as A if nt is str (this may 8'beLthe right behaviour, but at least " demonstrates howFings worka = ['hello\n']/bo  fn2b'ol\xe9.txt'% # transcoded from ISO-8859-1^ fn`F5c3aH# to UTF-8+Y !"all arguments mus+W,N!: k)",>_GP, fna1b) 3dmA of consistent with &sgh_[b'foYb'bare2'1 fév'Gm+'3Y)[d$ (v)ZR nb'a', b'b',Ca)#GDinpuEqn-ASCII4s are finN%[V U_list((d!, ,x, msg, generator, *argsA+.Raises(TypeEV)K6ctxsV(UPaEqual(str(ctx.exception)) clTestJunkAPIs(unitd.CCaseis_line_junk_true@for " in ['#', '  # *']T[IS_LINE_JUNK(]r), repr _Ofals ! ##1abcMr. Moose?up!Fs0\REDOS`Revil_= ('\t' * 10v) + '##QSdcharacter(self):  for char in [' ', '\t']: self.assertTrue(difflib.IS_CHARACTER_JUNK(Kr), repr !) Jdef test_is_$acter_junk_false(c)v a#!\nfrvF\Smain(C HtmlDiff._default_prefix = 00DocRs = d .DocTestSuit;)-run_unit2(r-WithAscii, @Auto-SFpatchesYbugs,@OutputFormat&4Byt1JunkAPIs, ) if __name__ == '__2__'() import os %sy contextlib./EutildnspectVpydoc _compiletkeywordV_pick8pkg[r75stabdstringBWtempfa@.sup$%imJEtype7typK70urlEpars?xml.etre.ElementTADwrapR`threadsfrom io T! S1IO collections!bdtuple#.script_helper2_python_ok8*TESTFN, rmreap_children 2ap_s, captured_obstdoutC&stderr, unlinkMquires_doc6s )P_mod class nonaQ'Це натиниця'IApass 3HAVE_DOCSTRINGSL exwed_data2 = $1'di1arytinstance variables (if defined)':list of weak references to the object>) * 2 else'P5) _pattern = """ NAME*!p - This is aq module+_+ %s CLASSESEbuiltins.A B hC \x20+A(Kj | Hello and goodbye7$ |J MethodsC her>-__init__(iWow, I have no fun!e t-2^ Data de&orhere: |@\x20 | __dict__%s"qweakref%' class B(builtins.object) | Data descriptors defined here:'Wz- |G-2and other attributeNO_MEANING = 'eggs'[ __annotations__ = {'?B': } AX#CoMethodget_answer(self|Return say_no( is_it_trueDGelf.mMm q2-N&G2ionary for instance variables (if-%__ ^list of  references to the  b FUNCTIONSJdoc_func This  solves alliVworld's problems hungerX@lack5ePython?war'noQ DATA4Q__xyz`'X, Y Z' VERSION$1.2.3.4 AUTHOR Benjamin Peterson CREDITNobody FILE0%s """.strip() expected_text_data_docngs = tuple('\n7' + s if s else ' Us in w rhtml_pattern = """

strong>^>! .pyBTmodClasses \x20O>
a href="builtins.html#object">d <] ddfk . B_modqOA">A^TOB">BT=NC">CT/m/   Loffc8d8%0a name="A">c AOa>(<>)>//t)%rowspan=2>3! /RHello[2and pgoodbyeB<0 Data descriptor __dict__ dtd&%sj! <BweakrefEF!PBPBZPITyg width="100%2%">Data descriptors defined here:
__dict__%s and other attributeNO_MEANING< = 'eggs'annotationsV = {'P': <class 'str'>}U/td>

CY(30)MethodM -get_answer" Qself)("#():Pis_it_true.&"> :bionary{2for instancevBbles2(if &BlistUo]referenc"to#th3 <Koeeaa77%f5big1Funsb \!\nY-doc_func, a>ctt>Thi<DsolvB2allof the world's& problems:
hunger Black#"ofaPythonwar

#()
index(file:%s">%sptd>p

u"isa test&nbsp;module for test_pydoc

<table width="100%%" cellspacing=0@padd#2 border=0 summary="section">

< width="100%%" cellspacing=0@padd 2 border=0 summary="section"Mr bgcolor="#55aa55@d coRn=3 valign=bottom>Pf" face="helvetica, arial">1 on8str class.'''\n', os.linesep with bad imports bad "1@a%s - M=@NotFError: No% Wd %r"dynamicattribute_p"" Help0 DAksd %s: (builtins.object) | a descriptors defined here: |\x20 | __dict__%sweakrefM DocsHr4put, loc def get_p%ydoc_link(module): "Returns a documentation web /b of a 4"3dirname = os.path.basedir = (__file__)))pdoc = p.TextDoc(ldoc.getdocloc#, _=1r loc def get_YS_text< ! generated output as 5*(_mod) or "C ifmq"\nMODULE DOCS\n0" ++ + "\n" %=B.doc$# clean up the extra formatting thatm@ persapatt = re.compile('\b.'X~&.sub('',)"z).strip(),html_title(ZP# Bit]hack, but good enough test purposeheader, _, _ =`.parti@(""%!, y0 = )er.. Z -/!. class PBaseTest(unit.0Casrs0_re- cted_walk_packages(self,  , f@=NonD+"a `A versof pkgutil.D"()Twill }0 ito1 toJqa givenr.ldefault_0ath[ (]Gwrapper(?, prefix=\anerror)s F~Q2, oND?@@conClib. qmanager0 %_0 = .* e,NR )6tryNUyielddkfinall# tUcall_url_handlerurl, expea Pj.>8" /qPresulq# CheckCv to ensure ]n  page was not e!assertEqual( ,wH V0DocGU@oskipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above")B0@un"st.skipIf(hasattr(sys, 'gettrace'):Dsys./()'2 function introduces __locals__ unexpectedly'requires_ddef test_htmlq(self):result, docb = get_py4( 2modj4mod_file = ins0abs1 url = urllib.parse.quote(N`9 = _pattern % (UTurl, ^?) +7 i@data3sC.assertEqual(E @!) h ' flags.optimi@textd4f~!77Oloc,%W %](, /,)` ", o`enum_member__value_zeroc# Test issue #20654 to ensure I II 0 can ber# displayed. It usedGthrow KeyError: '%'.8aimportgclass BinaryInteger(.IntEnum{RE = 0@ on1adoc = q.rendero ezYIn('<'.qQ: 0>'M mixed_case_module_names_are_lowerdX16484Y_link(xml.etree.ElementTree.e.:` N8225- * no= appears for |= ll "", "MODULE DOCS incorrectly ludes a link")  def test_getpager_with_stdin_none(self): previous#q = sys./#6try07#u = None*dpydoc.() # Shouldn't fail./ofinall]  9non_str_nam# issue146386 # Treat illegal (non-str) C like no 4zclass A_t{__ = 42+B+Epass"radoc = "render_doc(A())%b%B%.assertEqual([.replace("A", "B"), N)9]t_her5missing_module = "J.i_am_no4"`result1qtr(run_(E), 'ascii'expected = -pattern %mm E", ,+"documentation forY Ys found"Q@unitpskipIf(flags.optimize >= 2ei'Docstrings are omN d z -OO and above!t_ 6 = Y'jA.non<', PYTHONIOENCODING=uAncodt7 ._|A__.e(3, 'backslashP2In(:dNPinput,ip1= " l m[.&p(e u A,id##ngs, other imple s might have different reprPtripi?r%id # egp the  &id('')=>/Bat01F65390u)# nothing to Aturnsame text1042'.""F ; flags.optimize >= 2, 'Docstrings are omitted with -O2 and above')B0@un"st.skipIf(hasattr(sys, 'gettrace'):Dsys./()2 function introduces __locals__ unexpectedlyrequires_ddef test_help_output_redirect(self):)# issue 940286, if 2 is set in Helper, then all"GfromI'.v should be y%ed+old_pattern = T_text,getpager_old = pydocU&new = lambda: ( R x: x.maxDiff = None J buS6IO(6%er(,F=buf*unused, docq = get_( 6mod4module = ".""Q_head&""R on mD A:P""".lp_wrap.dedent(}+,E_new&6trycaptured('stdout~s5, \E882err8:errk3!er(g result = bufvalue().j,?mmN % (?(jO,) +- wW_data@@@(inswabsfile.,)passertEqual('',E(8?err5 ", mkfinall^2oldIe namedtuple_public_underscoremVNT = 1('NT', ['abc', 'def']#V=True a() as /*io6(NTFo 7_ioM;In('_1',f:L &@repl,iasdictW~VsynopsisBu ddCleanup(unlink, TESTFN for encoding in ('ISO-8859-1', 'UTF-8'):  with open(TESTFN, 'w', encoH= ) as scriptAL%if14 !=j(,print('#`: {}'.format(lr, file=o)C"""line 1: h\xe9'742: hi"""4 synopsis = pydoc.+*{}self.assertEqual(21, 'w!) @unittest.skipIf(sys.flags.optimize >= 2,. 'Docstrings are omN!d -OO and above'@def o__sourceless( expected = os.__doc__.splites()[0]Dname.cached__!rN;I. `_empty ! .support.temp_cwd(J_dirinit_path d.join(/, 'foomod42.pyt6P = imwlib.util.S_from(mBo!Jfobj3.write("foo = 1"Upy_compile.eIsNone ]_y x/, fP 2T2_deoQopen(9, 'w').close().assertTrue(pydoc.isn)7os.removee!) 2defallmethods# issue 17476: ) was no longer returning unbound Q.jR# ThiC- is a bit fragile in the face of changes to object and type,Pbut I can't think;a better way@`do it out duplicat7theMPlogicAunction under%.4class TestC (G%]_ _t -1& k# What we expto get back: everyCg on*&..s4ed = dict(vars%# ...plus ourN/['F'] =.$p0... nobe non-3s03deled['__doc__']  "Q# insCresolves descriptort_T into , 5 doesn't~ so@needgupdate __sub}ahook__.__ : O YBFG  gz"= U(1DictEqual(C,A)  P ImPN(@Base"):0\setUpnbmkdir(TESTFNddCleanup(rmtree, (ilib.invali_caches(2bad/ scix for05230, where ifV! f`Xmodul~ip had anbernal c errorMwould reV5doc#kgmodname = 'Jmod_xyzzy'3pairs = (('i_am_not_;', )0L.5p_either<H".nIiN'Gi_am_not_here.{}'.format(modname), 'i_am_not_here'), ('test.: D%) Ssourcefn = os.path.join(TESTFN, + extsep + "py"Dfor importstring, expectedinmsg in epairs:6with open(, 'w') as f+/f.write("nd {}\n"A)))gresult = run_pydoco, PYTHONPATH=).decode("ascii"Kb = badt_pattern % X) Dself.assertEqual(,", 1def9_apropos_/_bad_package(J)(# Issue 7425 - -k failed when ?@ on ,opkgdir "syntaxerros.mkdir(<2bad0 O), "__init__")] #R$f nvalid python G$1\n\D0.re9tct_walk_ s("=[]i=captured_stdout(6out+ /2err/>err/3.('xyzzy'b#C# No5, no error"mout.getvalue(o S 1?err1 U# TheT is still matched 9M?err .p#B,unreadable_D{f?367B  R.$f 6, "'#J6, 0 addCleanup(os.rmdir, ]70te,Windows theectory appears to beVQD# A so this|0not1lly@1ingUitVCUaptured_stderr() as err:  pydoc.apropos('SOMEKEY')-# No result, noJ%orself.assertEqual(out.getvalue(), 'K -=err-[def test__empty_doc(E)pkgdir = os.path.join(TESTFN, 'walkpkgos.mkdir(:Y.addCleanup(rmtree, (Pinit_k u)Q, '__$G_.pyywith open(B'Ffobj.write("foo = 1"current_mode = stat.S_IMODE(os.".s'=:trylos.chmod3), _0& ~P`FEXECH;restrict_t_packages("=[]), captured_stdout ^ Nw}5In(", O[ofinall*) url_searchl_error# URL handler 2 should cope ;( that raise exceptionsz\ rV1, ",, Si7, "L , "wt", encoding="ascii" f"""V#E:"ouch")\n""l[ o2# P has to be importable for thehave any effecty}Qsaveds = tuple(sypZ*0.inB(0,  ' <[R vsRegex(,#, - A<  # Sanity check3@textKPcall_"("_?key=m,0R "P]1: S.! REs)found = (''k'K1pb1In(z , (@0[:].RP@unit.skip('causes undesir|Rside-gs (#20128)~modulesUSee Helper.list(%).num_header_lines = 2 num_module_l _min = 5 # Playing it safe.5bfooter5E = 3expected = ]Ehead(+ pR Ooutput = StringIO()helper = pydoc.H(2= -"('~&s'Presulc3.getvalue().stripr(r = len(;a.split6()) self.assertGreaterEqual(F$, .6)@unittest.skip('causes undesirable side-effects (#20128)@def >s_search(%):8b# See /S.list&()A = '_F - '+0 with captured_stdout() as 6_io%er $ =>4In(", =some buildbots are not cooperat)_E4Iterator8Tuple[int,"J]zG5...[4T =*TypeVar('T') class C(Generic[T]a0Mapuxstr]): b.assertEqual(.render_foo).splitlines()[-1'f\x08fooJC#, ,';'HA:A]C2 TC(collections.abc.O_r,)'`|builtin[for name in ('str', .translate=!s.!$'%?O# low-level fun VDIsNotNone plocate()y[Ohigh\ :try< f` except ImportErrorGfail('finding the doc of {!r} ed'.formatj 4notWDstrrrd/rrMz3 C 2wRaises(S,, ,@staticmethodA_get_summary_'(octext =XSplainJToKAs2exthG('\nQ len(,a) >= 2?qreturn 2[2]#se should include " "; unbound_python_ 8 ' wrap.TextWrapper.)4"e , 4$)"rrequires|strings,_pickle.Plr.dumpeobj, /gno longerj h:D({z.wrap),  "wrap(text) method of  .TextWrapper instance") > de)st_field_order_for_named_tuples(self):15Person = %$"('', ['nick', 'first agegroup'])Ms = pydoc.ren~Bdoc(M%elf.assertLess(s.index(k5), t)C.D)*class NonIterableF6s%KBNoneg=OHash=F[[]]=# Make sure these doesn't failM I , @requires_docstringsr=bound_builtin_ 5S=7IO( = _pickle.P6r(szQEqualV ._get_summary_line(p.dump),n"x(obj, / p # this should *never* include !hmodule_level_callOQ|os.stat(path, *, dir_fd={, follow_symlinks=True) PxServerTest(unittest.CCase0"""Ss for_start_s=2""".# Minimal ga that Is 6, n stops it.>^my_url_handler(url, content_typm = 'the URL sent was: (%s, %s)' % GuFareturnRethread (B, ho A='0.', port=07In()p.{.addressptime = .sout = 1 #seconds@whil.{:ingG.sleep(.01#if AH and" -K! >:outgO$erL7top VbreakU`error,He) BUrlH\("@Base D_errf?HRaises(TypeError, f, 'A', '')  self.assertRaises(TypeErr1B1foobar') 8def test_url_requests(J!):!\# Test for the correct title inhtml pages returned.A1hisis.different parts ofURL handler withoutDgetting too picky about:`exact vE = [G("", "Pydoc: IndexModules"),-get?key=5iW2gtopics3T xkeyword+K -pUm  .%6 asearch$ 9S Result\:7defKEYWORD  5wSTRINGS9dTOPIC  ;03 -  1qgetfile$=% I]o~ b.restrict_walk_pack@(z0wFurl,p(WAcallK(>+ppath = Png.__)__=/P " + ? -surl = "$4(a classyHelper(unit.CCase( nEqual(sorted(.^.= &8+.kwlist)) QWithMetaC/es@skipIf(sys.flags.optimize >= 2B"Docs are omd6 -O2 and2ve"! pphasattrx0, '\arace'):( 't2 function introduces __locals__ unexpectedlyqDynamic,Attribute TD(typ LP__get!__=\, nam)1!if == 'ham'A&y 'spam' su().|v1qDA(meta =K@/s. K def ham(seklf): return 'eggs'expected_text_data_docstrings = tuple('\n |P' + s if s else 'L!0for9%n s n)output = S6IO(helper = pydoc.H(2= -6(DA~' = ynamicattribute_pattern % ((__name__,) +DT EF[:2]Presul.getvalue().upself.assertEqual(", K!) @unittest.skipIf(sys.flags.optimize >= 2,.&"D`are omNd with -O2 and above" p0has;x, 'gettrace'):/()'2 function introduces __locals__ un2ly'@def _virtualClassAWithOneMeta(Sc) GtypeW__dir__(cls"SA['__K__', '__module)iLIFE']e0get=!__ , 3p!ifA =='K)42isuper().__x(p/ FQ(meta=' Epass67@ D1 % 42 = U0Two>CX/1(R?one4J~ 1s- }/__12 return ['__class__', '__module3nam wtwo'] def __getattr__(self, 2)):)4!if@ =='J!%r2>super().vp1p Meta3(!1, 2 di;clslist(sorted(set(i$Dhree'] +G6.__" + 9)))?  3iCZa1(meta= oEpassi' 8!2(:1, @3@ fail1 = 2 = False^output = StringIO(Lhelper = pydoc.H(2= -expected_textpvirtual+ibute_pattern2 % __%__Qresul@x.getvalue().stripv.assertEqual(s#, MT<2` 3@'212) d@unittest.skipIf(sys.flags.optimize >= 2,. @"Docngs are omNd with -O2 and above" p0has x, 'gettrace'):/()'2 function introduces __locals__ un|2ly'/`_buggymTgM(type=>! cpmissing GhereUyC/ 1 = 'present!'$8.C5 =  2 = 'resolve_f # Issue #23008: pydo c enum.{,Int}Enum failed # because bool(.() is False.,with captured_stdout() as help_io:+^`pydoc.%('X%')$dtext =@.getvalue(&self.assertIn('class !',7BB) TestInternalUtilities(unittest.qCase): def setUp(g)tmpdir = tempfile.TemporaryDirectoryCrgv06?Q.namehb .a$ = os.path.join(m., "nonexistent"ddCleanup4c (bbs_cura osd_get_revised_Jq, given!, @=Nonx # Checking that .0cliRctually callsj#handled via code ew (at least for now)"if@6 = oreturn )3starting#4~`# Get py of sy/ out the current dZ=H.cop 2 in 3 __-frange(ht.count(P)I-fremove. V+6A_sys_adjustment_adds_missN PPQM Ncexpect HF] + S&QEqual.j!;9), l%<!s_A_dirgp_I@leadqi[?dir%, `+T@trai++  aprotects_.Ju 7path(given_p ath, argv0=pydoc.__file__) clean_path = self._get_starting(/@leadUqdir = [6F] + TgexpectedP5bs_curdir7 \=assertEqual(SrevisR(<9), s[trail, + P ]> =Odef test_sysP_adjustment_whenT_already_included(!):Efor spel>2 in._s^bBwith(subTest(0=99R# If 0C is  present, no alterations are made at allK#R}  96!.aaIsNoneH(b)t"' =+z' c) ' m#]'[L)) @reap_th1%s bSmain(6try.support.run_unit (Pi0Doc, 0 ImI3(qDescripg`Server?3UrlHandl7_oHelpereWithMetaClgs8fInternalUtilitie9gfinallchildren() if __name__ == "__ 2__"q() from! iP findq, TESTFN, unlink Tarray "ioIJE5moc1pickle c* UnseekableIO(io.FileIO): def tell(self): raise io.UnsupportedOperation 'def seek;, *args, **kw L class AudioTestsclose_fd = Falseu1tUpveR.f = out = Non8tearDown;ilf.f is not7U.!():o= =out@unlink(TESTFN)check_params, f, nchannels, sampwidth, framAe, n %s,comptype, Lname?assertEqual(f.getnr'()l 66 6 @rate6 6 4 2 3 414 _1 = 5& &"$(np q._ 666,2 44 for proto in range(pickle.HIGHEST_PROTOCOL + 1C sdump = 1"s(},U/j`loads(?2), @8) )AMisc-(8&):Btest_openfp_deprecatedLarg = "arg"4@modewith mock.patch(f"{module.__name__}.tQ") as.5, \^N7sWarns(D0ion7ing3lbfp(arg, = X{.f_called_ 9 X_WriteY create_fileN , k  (4f, 'wb'8f.sv8n '. ''ate)  f.setcomptype(self.%, sname) return f def check_filC`, test, nframes, !):5JBwithcmodule.open(:'rb') as f48 assertEqual(f.getnchannels()?sampwidth??Erate??%= 6Areadd$s(3dN_write_params2f =bcreatefTESTFN%fA. #f #*f{J^,= _8f.close()2context_manager_calls_2nG0# CI s for a minimum header and will raise an error# if it is not set, so this proves that &5ed.AQRh.cErC7%k, 'wb'15Opassy2m@ y05-_X_  (1Ez=zi@nJ+/-/L//C.` md=16_fdy4(eC 1o,e1RFalse@Cfp()1 = k('Z*.CCCe, self.framerate) if not self.close_fd:"-assertIsNone(f.getfp()O)Equal(testfile]*d,j!) k@def )_context_manager_with_?Pname(])# If the ! doesn't get qd, thisY0 wofail, but it will~# produce a resource leak warning.+module.open(TESTFN, 'wb') as faf.setnchannels. D+sampwidth++Afram++rcomptypK.0omph8 .'GFals&[params = M(#RP&;K?O?~c??XTnBwrit2f =acreate'Lnu #_Cs#R(XcheckyqZ< _bytearrayyN o.QXk.J('h'QmemoryviewS pS in?aleted_A = #.Ob'ababagalamaga'B+ f.setnframes(self.nframes + 1) rf.write, 'close() >with open(TESTFN, 'rb') as testfile:-rassertEqual(' .read(13), b'ababagalamaga'B`check__A!, 1def_multiple_)w P( 2f =jcreate Sf.set '4izeZnchannels *ksampwidth2[:-9Kize]l+[3:48overflowed:9/ -unseekable_r5 .f(D7 LU/IOT+  LM P1RV+. Z3#S <1incomplet +!+F, f.setnframes(self. w + 1) Itry:xf.writeA <except OSErrorGIpass\moclose(\ ]with open(TESTFN, 'rb') as testfileassertEqual(' .read(13), b'ababagalamaga'B`check__A!, qB1def_unseekable_overflowed_)U0&IOw W 2f =jcreate fg-g764izenchannels *sampwidthY9- 15[:-r]) class AudioTestsWithSourceFile(1): @2amethod`setUpCKG(clspcls.sndBpath = fi)name, subdir='a0datb_b_parami qmodule.6.#*f.getfp().`<;fmQrate,_yo?pcomptyp4)/xG)fU[ ds\~._UFalseH.d.f ,D Dg'_fS7J Dfout 0, 'M 3DRaisrz fout.close()  self.assertEqual(testfile.1d, ";:_fd=V # do nothing d@def O`_read(H!):framesize =cnchannels *sampwidth4dchunk11Bb[:2 * Jize]-2- ,?: 4;f6 module.open@.snd&Fpath M f.(0), b''/ tell(), 0& UB2), 2vGwindpos0 = f.a% ),0poswlF2, 2 #ad@2f.setpos(uI5}*BwithVbRaises5FWError &-1L-cf.getn?k) + 1)Acopy%0 <TESTFN, 'wb .aarams(p )Ui = 0nwhile n > 0peei += 1({Swrite' si.en -= iA=kr;.re4get,.:7c%), w)Tg_not_from_startc1 as1Z G.(b'ababagalamagaK^0, 'rhfa8 e ("ZP= W  _&1(13GHn self.assertEqual(f.getnchannels(), self.;)  IasseCsampwidthCCframerateCCn2ssndfileFCreadF<) import __future__ unittest class FLUFLTests(.qCase): _@def 4_barry_as_bdfl(!):"code = "fromy <r; 2 {0} 3"@`mpile(H.format('<>'), '', 'exec',:~.CO_FUTURE_BARRY_AS_Cc.'Raises(SyntaxError, co %deN!=')w{!'<0_guido 'a';h aa-,} -) if __name__ == '__main__'o(contextlib$io $os lib.utilGpath9Pposix Dtime dstruct0zip1 1tem  TeraryFile#drandom!Pint, pom, get EbitsTast.sup script_helperX '(TESTFN, fi}, unlink, rmtree, C_dir ?cwd requires_zlib, 7bz2OlzmaF 0capd_stdout) B2 = c + "2"9DIRd" FIXED+_SIZE = 1000 DATAFILES_3'P_datas' SMALL_<0 = [('_zipA1q1q2w3e4r5t(Y/T2dir/<2<qawsedrftg<w3H3HazsxdcfvgbHT4T6y7u8i9o0p')] anytes(sizhreturnQ(8 * "U.to_b1, 'little')S_l("3Syield2'with TemporaryFile() as f: uyield f test.assertFalse(f.closed)#with io.BytesIOO) class AbstractTestsWithSource@(amethoddef setUpCAR(cls)*cls.line_gen = [b("Zipfile  %d. random float: %f\n" %dK3(i,8()), "ascii"2for i in5ge(FIXEDTEST_SIZE)]ndata = b''.join!) +W(self# Make a s@ AsomesBPopen(FN, "wb"pM+fp.writep.Pmake_Tr_archiv&, f, compression level=Nonekwargs = {'5*':CD}# Create the ZIP !z@.Zipj (fR", ** % ;another.name 08 2(str("str0", w!p.'@ten--w', mode='w'B "ine 7 /&1zipC= {o# Read&r"1ion   aEqual($S.read6)< "/D#  UPrint directory&@fp =`String pI@dir(:=fpY = fp.getvalue(&8.a.split + >Alen()), 5) # Number ofs + header$H@In('r Name',:[0] 1Modified0:Siz\ Kfn, date, time_, size ="1]  F'B'True(time.strp time(date, '%Y-%m-%d')) self.assertTrue(4P.strp _>H:%M:%S>Equal(size, str(len(]data))) w# Check the namelist!s = zipfp.#(u,_s), 4,In(TESTFN,|s) "another"1strfile,written-open-w3 ,@info (# (` = [i. for i in 4)s]UX :( =_j" c0get^ [x nmy d"C"")b)r:(nm5nfo/, 4at testzip doesn't raise an exception(5(?1defHa_basic`[fZ@get_s"@zip_\A(f, compressionl',)X, f, -Q.make._archiveb0*a# ReadCZIP 0Awithile.ZipFilM:"r"1 as(p0zip1 Z p.)H1KO`while $ Pread_qF.N(2563pif not %:Y*Ubreak.append(M (2 2 2J zipdata2.append(read_data) self.assertEqual(b''.join(zip0A1), % )<2<=def test_open(Z!):for f in get_files"&5A.zipC_M#(fcompression p_with_pathlike\0 = lib.Path(TESTFN2}1u@ zip.ZipFile(5?"r":1 as0pH{IsInstance0fp.\name, str'grandom.IX, f, /lQ.make\_archived0H# Read the ZIP 01f, RU = []VZ!p.N)H11while True * =F.(Hint(1, 1024)8pif not 2qf.Ybreak=m J4,F1~Bead1-*r:Qfp, \,f z/vuN1(-1hd`[   1P- J/10M read_data = zipopen.read1(10)  self.assertLessEqual(len(3_data), 9uif not ':[j]break0zipZw.appendk +b''.join(=1), $I)8def test_P1_10(")for f in get_files"5E.zipG_U#(fqcompressionx0Aline95LX, f, 6Q.make._archivek0# Read the ZIP 05@withq.ZipFilMq"r") asEp, \1T.(t(TESTFN,,mi = b''Cwhile True/3 $(RGKM!+=*0?(10 ~:V@ 9\1 # Issue #7610: calls to5() interleaved  %5(). d | _1_zipfpWGM J_gen[+ 2UBC , An+_s10zipss,T51zip.#sC:  for f in get_files(self): .zip_readlines_test(f, compression) :@def 1Giter1.X, f, 2lQ.make__archiveg0b# Read the ZIP 0@withq.ZipFilMq"r") asp~ 3p.open(TESTFN. 04@for ,Q P1zipJ.A_genA \BassertEqual(zip<,\Wz_XeSHrjozGlow_ """Check cases whereed data is larger than original."""# Createo2, "w"zipfp.wri`r("str8s", '12'`# Get pen object2rKV>objT*.(1), b'1')8< f =*^&w".b.txt", "hello world"Ma_type=OCinfo|Pp.get!('U@5'.QdV \level-?ileC&=1?a+ On,MQ% 2QC@ followsconstructor.^ a_< 9A?, 1 is overriddenb} 9%al(b_info._c'ompresslevel, 2) def test_read_return_size(self):%) # Issue #9837: ZipExtFile.:() shouldn't F more bytesEthan requested.2for| in (1, 409567, 16384Afile' =C5+ 1]&junk = getrand(:)+with zip@.ZipP(io.BIO(), "w", "#.cXqion) as86zN@.wrikr('foo', z+~T.open,1'r'_.fp]6buf = fpg_-assertEqual(len(buf),A truncated_-il!Xfp = &T.Pfp, mode='wW 50str'yddata, a_type=end_offset+Vtell("o0ileX getvalue( D 5J1 ./ 2.(F- 20)cRaises(EOFErrorQ20zip|SPwhile ?10015Bpass[/+/1(,,pr{fname = '. '8f0@get_ s>z D, 'wN5kDp(TESTFN, tr = repr(4 DIn(" G", rl a"r = repr(zipfp)+ if isinstance(f, str):'6self.assertIn('filename=%r' % f, r)8OelseNJ ~"mode='r'"w r = repr(zipfp.getinfo(f) \ 6g8._size='/1if `compression != ile.ZIP_STORED`FO_typr7sAwithcp.openf0 as&' :8/ 1o,C!<s 3[closed] 5Qfp)) def test_level_basic(Ifor f in get_s"@zip_W2_Tion, l,=91per_ l"""Check that  kin a Zip archive can have different<Us."""O].ZipFile(TESTFN2, "w"#1)*fpdp.writA4, '~:_1'. ,9'w9?@one_ r/ni49dEqual(x.:, 1 9~ : larDown cunlinkj 2) class StoredTestsWithSourceAbstract,7@unit.>CCase9c Y9E_low9.FNoneT_Gstr_permis,fq# Make sure1E and open(... mode='w') create files with  # &) 0600, when they are passed a name rather than a ZipInfoGinstance. self.make_test_archive(f, compression)/@ zipq.ZipFil-q"r") as%p:/rzinfo =@.getP('strE'\-rtEqual(> .external_attr, 0o600 << 16)@/2nwritten-open-wu2vAdef 7_estr_permi4 s() for f in get_ "5B.zipX!f,Lile.ZIP_STOREDabsolute mTESTFN2, "w"fApfp.(DD, "/"w rw- .list(), ["]$ppend_to_q """Test a*ing to an exist 5""" Z/bUaUSstr("1", oOdata %, N?non't is not a-# NOTE: this fails if len(d) < 22 because ofse first # line "fpin.seek(-22, 2)"_EndRecData2< = b'I amEU!'*10)CNq2, 'wb'cfSfw\P",  r r/jO Pd   ]p=Cread)tEqual(f.read(len(data)), ' pzipfile = f.read()#with io.BytesIO(/) as bio, .ZipFile(bio%p:Lvself.assertEqualQp.namelist(), [TESTFN]911), ^!) vdef test_'_concatenated_zip_(4) 6bio"&8ileW, 'w'IP_STOREDG1 Mr.write(",  (bio.getvalue = b'I am not a Q!'*10vCopent2!b'ff\ {c&2h !`append_to&0+uB, 'a09Lstr('str'F .r. U%, ,H % ignores_newline_at_end[_, "w"Hp24VU"\r\n\00"`Kt/r"Celf.assertIsInstance(zipfp, 8ile.ZipFile) def test_ignores_stuff_appended_past_comments(self): 9LwithX(TESTFN2, "w"vIP_STORED) as5pIM#p.k = b"this is a "-1Swriteu", })(Copen"a2, 'a'f"f.J"abcdef\r\n"HqBS1"r"S! self.assertIs:REqual!,  _default_name"""Check that calling $ Epout arcC specifiedgproduces the expected result.""KHwH[x2YR, "rbN .\Dread^A, f.)U0to_OonlyT 0tryS!to^ () on a Bqu objectXPraiseValueErrorOomode="Tstr("someftxt", "bogus"7e%$022, o R()p z+> ) )p.R3'w';@add_8_before_1980# Set atime and m to 1970-01-01@os.u[, (0, 0) p @requizlib class DeflateTestsWithSourceY(Abstract,c@unit.?CCasecompression =CIP_DEFLATED2per:  si0Ziphive can have differen_ options 'storeme'Z zipfp.write(TESTFN, 'deflateme', !ile.ZIP_DEFLATED) qsinfo =*Pp.get`('storC -d-r /self.assertEqual(m.compress_typeMSTOR FF ' @requires_bz2 class Bzip2TestsWithSourceFile(Abstract,5@ unittest.=aCase):33ion9gBZIP2 Clzma@LzmaI8cLZMA Zip64InSmall9s# These s# the ZIP64 functionality without using large fileshB# seH_Bor proper\1s. a@amethoddef setUpCC(clspline_ge(bytes("h1 of@ile # %d." % i, "ascii"Kfor i in range(0, FIXEDf_SIZE)7cls.data = b'\n'.join(m)(<z._limitG64_LIMIT*M_count4_FILECOUNT<m/Xu = 1000_# GB = 9# Make a saB somfsVU open"wb") as fp^TR<@zip_?W, f, O# Create archive ipy(f, "w"Tq, allowQ=True9  "another.nameb0W&FNS(str("str<", .o# ReadrsCread)< )D# u# Print directory&fp = io.StringIO(pIcdir(fpaUA = fs[valueFEs = ..splitlines()  -self.assertEqual(len(lines), 4) # Number of files + header AHIn('File Name', NO[0])1 Modified0:Siz\ ]fn, date, time_, size =1].split( F'another.n1PTrue(lP.strp ('%Y-%m-%d')=B_, '%H:%M:%S>Q, strzdata)))# Check the Ilist;s = zipfp#+ 6:O), 3In(TESTFN,|s) "y"10str, @info # ` = [i.h for i in 4)s]U [6[%v :!  _}"y xcx0get+ [w nmF ")P`:(nm]5nfo/, 4nat testzip doesn't raise an exception5(1defHp_basic(oIfH@get_s"@zip_\@(f, F.compressionltoo_manySa# This s that more Sn 64k<can be added toarchive,P# and9tresulting * Eread properly by ZipwIACile.c.w"*allowZip64=en.debug = 1001num59drange(%}U0wrir("foo%08d" % i, "% (i**3 % 57b |zipf.namelist()), numfiles) zipf.close() @2 = ile.ZipFile(TESTFN, "r", self.compressionUassertEqual(len(L2.namelist(for i in range(:scontent2.read("foo%08d" % i).decode('ascii'@ QA, "%@(i**3 % 57): ,def test_too_many___append(h)AUwU, allowZip64=False.debug = 100JVE = 9z@.wrirs= . Bwithk>aRaisesNESLargek%G, b'&j  aT&{?Truiz&/15 2i:2v *QE *SnoarDownA>IP64_LIMIT =e_limit*h.ZIP_FILECOUNT_LIMIT = self._filecount_limit unlink(TESTFN) 2) class StoredTestZip64InSmallFiles(Abstract,[yunittest.BaCase):6compression = zip.ZIP_STORED &def large_exception_S(W, f, M_FwithZ ipy(f, "w"3q, allow=False) as:pNq.assertRaises(LZd 4p.write, , "another.name")2(fnn?elsTfn[:-1] zipfp.writepyV b0os..basename'self.assertNotIn(bn, Z0[list(3Compiled8pwith TearyFile() as tnile.PyZipat, "w"  n__file__aif fn.endso('.pyc')>(BT, "testpackage")c"%s/%s" % (,, } K~F@def _*_python_("e email[,Udir =0dir!(+.Y.requiresWvAccess(NN42n$# Check for a couple of modules at different levels5theGhierarchy=s =K %$}J'S/__init__.py', P^{> mime/text?~ filteredJF]*m # first make sure that the  folder gives error messagesH1(on7badsyntax_... sPcaptuabstdout re&>SIOAt IO.getvalue(+qTrue('SEB'trj#1n c+/3s works cwhole  0 2 zipfp.writepy(packagedir, filterfunc=lambda whatever: False) reportStr = IO.getvalue(-self.assertTrue('SyntaxError' not inFItr) j# then check that works on individual)esC0defter(path):areturn0os.%.basename3.startswith("bad" captured_stdout() asGIO, Warns(User ?ing $if.treprint(Q hQtest__9_optimization(V imie email4 = 1dir+.__file__Y.requiresWgAccess-optlevel = 1 if __debug__ else 0ext = '.pyc'0 TeraryFileEt, \;yile.PyZip)t, "w", $e=P  I1s =r p.OlistAIn('L/__init__' + ext, =s-^9mime/text: python_directory os.mkdir(TESTFN2:tryTopen(Djoin9, "mod1.py")lY*fpD,"(" k42)\n"Xm2m"? * r(?txtCbla |SVvf -|Compiled'8 83NotkV2.txt4kfinalldrmtreeQ _tered + with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:  fp.write("print(42)\n") )m2m"? * rTemporaryFile(t, zipfile.PyZipt&py%filterfunc=lambda fn# 2not fn.ends+P('mod+')I<qnames = p.ilist()r)self.assertCompiledIn\0', <s8 3Not33lzfinallydrmtree'def test_/p_non_py()B 3KQ, 'w'fp+f!st definitely a python '4hRaises(RuntimeErrorq&Bpy, Ccunlink21-_bad_syntax8os.mkdirF2b+tr5BBad 8 in, 3#xenas are ed to stdout2captured_%"s1 7 9&QIn("S"", s.getvalue(#~qit willchave cH thes#, + # include31.pyRM.pyc0!k0c 3cd&Olike*z'7 pathlib.Path(TESTFN2) / "mod1.py") names = zipfp.^list()self.assertCompiledIn('Z0', <s8finally:rrmtree(T class ExtractTests(unittest.qCase): Fdef make_`_file()dAwithile.ZipF$nf, "w",IP_STORED) aspI& for fpath, fdata in SMALL_RZ_DATA15H0wri(r(@)"_etemp_cwd(_.t" /r"="90tenM,# sure it was K to the right place> scorrectz0os..join(os.getF, +?C@normL(cEqual(/, @. rsuOJopeny2"rbf .encode(), f.read()hunlinkx)_q_target", A"N9 = 2:|@True>P.same *, 24 g Adir(jextdirJ3uef test_extract_with_target_pathlike(self): $ temp_dir() as extdir#*6._test_extr^(^rb.Path(@1)) eIdef 8?allGcwd({Bmakeafile()[0zipP.ZipF#TESTFN2, "r"!p=. \#Pfor f, fdata in SMALL_e^_DATAX90out` = os.A.join(os.get,Y,4Sopen(Jbfs?assertEqual(.encode(), f.read(4dunlinkt,H_allc", p?ile4py "l `$7FN2  "  @ /li`check_ name, content&@True_0.is6(;)SX%a, 'rb' ^ Vsanitize_windows_~Pan = ?s/._<M# Passing 0sepallows this to work regardless of platform.N san(r',,?,C:,foo,bar/z', ','), r'_,C_QKa\b,ce|f"g?h*iL_d_e_f_g_h_i'O '../../foo Pba..rQ/Bfoo/nhackers_arcs_common_cases4-E = [;(u ),  ('foo/../bar',  G), '*obar/..Q .v}oz /%M.|x]self._test_extract_hackers_arcnames(common!) ?P@unit: .skipIf(os.path.sep != '\\ Requires \\ as " separator.')L@def K_windows_only(!)::"""Test combination ofkfixing and C sanitiz-E."""M&E = [o(r'..\foo\b(\~ r?\..*\[~/C:Z@r'C:?C:/)//conky/mountpoint`!\\8\8pq U ,?r'\ Jx?, 'JJO//?/o\\?\C: C: Z%C_ga:b\ce|f"g?h*iQb/c_d_e_f_g_h_i'7'2foo Gba.. 3   e/', r' / )_posix s'B  Dm#..p& n.names(self, hacknames): pfor arcp, fixed E in .-4content = b'foobar' +C.encode()`3with zipfile.ZipFile(TESTFN2, 'w',IP_STORED) aspQqzinfo =TKInfow*# preserve backslashes'Q.=) external_attr = 0o600 << 162pfp.writestr(j#, F)) 0 .replace(os.sep, "/"\targetpath = os. r.join('', 'subdir Jsub'Dpcorrect EDU5, *.split('/') /r' %3ten1p.extract(&, self.assertEqual(Rt,w; Smsg='~ %r: %r != %r' %>)`check_(t 2ermtree9 {Oall(u= os.getcwd()s @8"4" % xt8!?[0]GJZdunlinkh ) class OtherTests(unit.CCase@def _open_via_zip_u(p&# Create the ZIPEhive" ?"w"RL"{", "foowself.assertWarns(UserWarning): zipfp.writestr("name", "bar").self.assertEqual(;1list(), [?u] * 2) >Pwith . ile.ZipFile(TESTFN2, "r") as!prinfos =.jZdata = b""@for 21 ins[:pp.open(/26p+%o.read(+0In(1, {b"fooW0, b_Zfoo"}8*#:"fp 9@def _ _extended_local_header_issue1202(cfb1'w'o{orig_ziin 'abcdefghijklmnop'z-oAInfo g..flag_bits |= 0x08 # Include an   .EH_ ,  L\close)"""Check that theqile is 2qd after'X' block.":jwjmfpath, f6`SMALL___DATAr <@q?IsNotNoneCPfp, ' pnot open'D <9+'t } uR %_on_exception2!"ifC^`raised5theQ:try2:!54Bad$ N 2.2. unsupported_vers # ?B hasTtract- of 120 data = (b'PK\x03\x04x\x00|!p\xa1@;' $b'1x{2{3 ] d mc[ 0, 8H_5\x06[C/H"1f 5') n(self.assertRaises(NotImplementedError, zipfile.ZipFile,@  io.BytesIO(data), 'rr@requires_zlibEdef test_read_unicode_m`names(!):+l# bug #10801f+p = find: ('zip_cp437_header.zip')1Lwith(FA) asptxAfor f"in.Wlist(*/pp.open(').close(x_writeTESTFN, "w"f1zf._str("foo.txt", "Test k 1"@O\xf6AZIsInstance(zf.info9D[0].S, str! rtPEqualoao m A 1"exclusive_create_ """1 1ing a newiv5"""runlink(2a@ = 'PFcontent = b'hello, world. this is some '.9g2, "x" IP_STORED;ipfI,xwaExists ~_3(Yo?ru$ 4, []; (3)i.pe_non_e1ent9_for_appendsif os.path.3s! F9os.hme = 'testfile.txt' content = b'hello, world. this is some '5.' :Etry: Nwith zipfile.ZipFile(TESTFN, 'a') as zf59zf.writestr(=Tname,s)dexcept OSErrorGself.fail('Could not append data to a non-exis@zip n6.')HassertTrue(os.path.6s)1 rfEqual(zf.read)@def !_close_erroneous_(P)0# T0 checks that the ^structor T$eq objectx# it opens ifEre's an @r in:P. If.doesn't,H traceback holds a reference and, indirectly,Mh.On Windowsis causeos.unlink() cally91 be& underlyingAtill". jis SF bug #412214*GFQ, "w"&fpq"fp0("t"is` legalb6\n" @zf =+  6R3Bad Bpass#ois_zip @"""C~3z"or identifie$n-Us."""<@# - a$[J].dFalse(/)Z C\-like[\=lib.Path;)j_ e/rbz/fp~ fp = io.BytesIO()bfp.seek(0, 0{Ghpdamagedn } ,!s @missb fraise  Create a valid3 awith zipfile.ZipFile(fp, mode="w") as zipf:  .writestr("foo.txt", b"O, for a Muse of Fire!")@< iledata = fp.getvalue() %# - Now create copiesNit missing the last N bytes and make sureK a BadZi exception is raised when we try to open itDN in range(len(*))fp = io.B(IO+F[:N] Rself.assertRs/.,Cile.C, fp.@def _is_zip_valid_f["""Check that /() correctly identifn@zip Us.""" "paa 6namnLwith(TESTFNVBHETrueF)f objec2"rb*fp'fp}fp.seek(0, 0contents'Vread(%\-like A"fp*_kFnon_exis_s_OSError(W#Rdon't an Attribute<a partially-constructed## j instance-finalized; thisxspregressUon SF trackerQbug #403871.@The Qwe'reSr0cauRto bea3wasIdfdid no!# ye .fp member Dpnot ini7B buteeded by__del__() method. SiK  is_6,Ki ignored,z,user shouldsufficienQannoyH5message onr output@willTYnoticquickly.W{Yempty 1f =6'w'`f.closLapFile, zipfile.ZipFile, TESTFN) with open(, 'w') as fp:&-fp.write("short file")#self.assertRaises(zip$E.Badvdef test_closed_zip_rM_ValueError(j)"""Verify that@#zip() doesn't swallow inappropriate exceptions."""data = io.BytesIO(, (1, mode="w":#<>str("foo.txt", "O, for a Muse of Fire!"<# This is correct; calling .read on a 2 X should =F# a H, and so,Uzip. An earlierDpversion.+! wnit` (hany otherO#0repNrhe firs] in the archive waEupt.  wx%%, u<<%pbstr, "bogus' n zfw (' 1ile  ' @bad_constructor_RCheck1bad40s p4Ed toJ are caughtiD, "qY H+.C+9Dxr # 6,make sureej!Ow=P# unial newlines supMis removedy"Uv}E"rFy`0% +2(0)`ZipExt object returns an empty string and doesn't advance file pointer.""" with zip!.ZipFile(TESTFN, mode="w") as%:8?7.writestr("foo.txt", "O, for a Muse of Fire!")? # read the data to make sure0 is )re;V.open{fi in range(FIXEDn_SIZE)04self.assertEqual(f.(0), b'') 2 1G@def G__non_existent_item( """Check that attemptingDPcall G"() n C+tf archive raises a RuntimeErro67XRiA(Keyc,d(, O#r"n'bad_compression_% Gbad 2 methods pd9' aricaught7NotImplemented4ileY , uZ|"w", -1unsupporte #1is declaredshrunk, but actually deflatedk= (b'PK\x03\x04.\x001 e4C\xa1@"'I?#b' 2J VHx|01W23IXN H X8( Hx_5\x06W/W/5!  'Xv(io.BytesIO(a), 'r'+ )D, 'x null_byte_in_Lname ( contain a K K properly`termin {+kqqq", bH>k.list(), ['1,']struct_sizes7 ZIP internal structure sizes are calculated correctly."""  self.assertEqual(zipfile.DEndCentDir, 22)521ral5/465j_64, 57!`Locato10) def test_comments(!):"""Check that & on the archive handled properDH1# cGedefaulJ is empty)Twith b ZipFile(TESTFN, mode="w") as% .V, b''l0g@.wrir("foo.txt", "O, for a Muse of Fire!"6<rrr<a simple shorC'" = b'Bravely taking to his feet, he beat a very b+ retreat.'OY [@#|7{z~max length2 = ''.join(['%d' % (i**3 % 10)W i in range((1 << 16)-1)]M .encode("ascii",2o @& is too longrPtruncD{Warns(User 7ingOPT$ =X2 + b'oops.,uwh]Pified`appende Xb"original comment"  $zipf.writestr("foo.txt", "O, for a Muse of Fire!") ;Pwith @ile.ZipFile(TESTFN,mode="a") as$:7?6 .comment = b"an updated "1hrhself.assertEqual(y,x%) z# check thats are correctly shortened in append Ew'original's longer3do r' u@def _unicode_l(() Q "w",IP_STORED #Raises(TypeError/ 5"this is an e3" Uchang _in_empty_archiveaRFalsefilelistibZ/ "V'Js XL?nonO(kUg9 / "%?Tru 7# C"reating a 'w' or 'a' and clos&u5out)P# add1anyAs to the 0s cbes a valid A ZIP0J& =(TESTFN, mode="w") zipf.close(Etry:")&0 =  ile.ZipFile(TESTFN, mode="rWeexcept13Bad4 X"self.fail("Unable to create empty ZIP file in 'w'k5") a1F*adef test_open__ (5)j # Issue 1710703: Check that ;Ring aDwith lessn 22 bytesM# raises a  ion (rather> the previously unhelpfulNvOSErrorY1f =:7'w' .assertR(,fc$, 3'r'+M]_zipinfo_before_1980X|QValue, ZipInfo, 'seventies', (1979, 100, )C__short_extra_field"""If an $ $/header is4, skip it."""zipdata = (b'PK\x03\x04\x14\x0093\x9b\xad@\x8b\x9e'Gp\xd9\xdI1A $e,abJc?AB23B DCM$q2](Pa4\x80PL50ab\5\x06aAY1\x0I5% B dP(io.B< IO30), p1 as-?#zip returne name of first corrupt, or NoneB Is f.*Mzip(L_conflicting_handlesF# It's only possi@ one writ F at a timmsg1 = b"O1fun`harteraccountant!vAmsg25And sailVwide 0I sea333To find, explore;funds off>e" with zipfile.ZipFile(TESTFN2, 'w',IP_STORED) as7: #wiL.open('foo', mode='w'5*w23>w2.write(msg1)R =barR1Rself.assertRaises(ValueError)4hhandlem .f+"*r'c.Upstr('st7o'abcdefB0(__AP__, ' e=oclose( 1;28baz 53) O(rp [ `Equal(#R.read >), 5 5 5 "z'53&5namelist(), ['y0, 'H]def test_seek_tell(Q^p# Test functionalityYtxt = b"Where's Bruce?" bloc = txt.find(b"""r# CheckePon a AQ, "w" ]C"foo.txt",|] r]7n^"4*fp0fp.I(, os.SEEK_SET'w1fp.0), ?2]-^>CUR,^ 0/[Z,?]_!5)[7:>+5]?0>END(gQlen(txt)6 jmemorydata = io.BytesIO n1O-with zipfile.ZipFile(data, mode="r") as zipf: Awith.open("foo.txt", 4*fp2= fp.seek(bloc, os.SEEK_SET)]+ self.assertEqual(fp.tell(), ?2]-^>CUR,^ 0/[Z,?]read(5), txt[7:>+5]?0>END(gQlen(txt)) def tearDown(8)unlink(TESTFNf 2) class AbstractBadCrcTestsLdst_testzip_R_bad_crcu1"""; that files 0 bad CRCs return their name from ]A."""Z0zip0 = .|)b5ileio.BytesIO(I)-#s!of first corrup, or None 'a"',(0st_Pb-aise a Bad* exception when ej## Using Y.J(]6?RsA.K#, _0Ext1FdQ, 'r'/_UD SIQsmalls (in order to exercthe buffer_logic@" MIN_READ_SIZE = 2jGmH 8Twhilec/(208Epass>gStored<(P`, unit.%CCase`compress="IP_STORED zip_with_bad_crc = ( b'PK\003\004\024\0 \213\212;:r'0\253\377\f*2005H00af2ilehello,AworldP}R1\002}6r(\01t200\001i/!leT5\006%171 b/,%') @requires_zlib class DeflateBadCrcTests(Abstract, unittest.$aCase):compression = zipfile.ZIP_DEFLATED'zip_withx03\x04\x14\x008 n}\x0c=FAXKE\x1+ 0n,5 \xcbH\xcd\xc9W(\xcf/\xcaI9\xaV@=\x10PK\x01\x0237 8 La 6S? 71  k3bz2jWBzip2Th5_BZIP2e"c/nue bBZh91AY&SY\xd4\xa8\ Y 7fXf\x11\x80@`6D\x90 X \xa5@rP\xd9!\?S89\xac2u5:\x9 \x8b\xb9"\x9c(HjTe?jnh>;KE84> !  I Z9 4 }L[M F OClzmaOLzma@OLZMA.e@\x1b O"\t0k$0]E9I' b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK' b'\x01\x02\x14\x03 00.@\x0enu\x0c=FA=`KE\x1bn 5LC S \x801%Hafil=`ePK\x0d6#?3@> ') class DecryptionTests(unittest.aCase):O"""Check that ZIP d: works. Since the library does notCsupport ens1 at/moment, we use a pre-generated1!edG|file.""" data = ( !b':4i* n\x92i.#y\xef?& 1a L1\x0g 0,txt\xfa\x10\xa0gly|-\xc5\xc0=\xf9yOP18\xe/8r\xb3Z}Lg\xbc\xae.|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdb/0  _"0 jb6\x81Qv-= SLt `1' )!2"tDcf}38xu\xayU e20\x0o0zeroUT\a@3\xdbRG\xdaP92GUx<Te43\xc7r(f*m ip (bO'w',A) aspTV'ones', b'1117 32two3?2223  f.getvalue()[:5], b'abcPK') with zipfile.ZipFile(f, mode='r') as :;J?.open('ones459self.assertEqual(z0.read(), b'111; t?twot4a222') def test_write()for wrapper in (lambda f: f), Tellable, Unseek <T.subTest(N=l0f = io.BytesIO("f.b<bBufferedW>r(fJb (bA'w',"IP_STORED.p addCleanup(unlink, TESTFN4(&R, 'wbd/f2g7%f2Kp(^I/cT  H>f.getvalue()[:5]B'm%7&:f$w@2 rF&l self.assLertEqual(zipf.read('twos'), b'222') @requires_zlib class TestsWithMultipleOpens(unittest. Case): @6amethoddef setUpCOC(cls*.cls.data1 = b'111' + getrandbytes(10000)J12112| make_test_archive(self, f# Create the ZIP +EwPwith <ile.ZipFile(f, "w",IP_DEFLATED) aspEDPp.wrir('ones',  //12) Rp_same_fS Verify that (when is in control of c@ing N objects3# m open() calls can be made 6out interferN each other.Pfor f1gets&.f&ek mode="r"  ;.012OSzA~5%--2-Q1 += .1.  X+Y+`5ass101, 2/G41differen /# A5w 2L oleaved f in get_files(self): .make_test_archive(f)&with zipfile.ZipFile(f, mode="r") as ]h;.open('ones'0126data1 = z$.read(500) c8twoc2c:g2g2g 1:1 +/2/a/assertEqual(11,  42412) Adef E_after_closefor f in get_1-contextlib.ExitStack(s  g#'r2>ipf6i(1 = Z1.en( ~NDD _DM1M)h)n'f Jb0^Owrit^$1w',aIP_DEFLATEDO.3stry 1 2222 `j j[:500])C 2ipfB**' 0o #.?"w"oP~=6_ ritestr('twos', self.data2) with zipfile.ZipFile(f, 'r') as:2=I11 =.read('ones'\*2*outd(opt, l1 '.rADone7ingN wtar.tar+Xi_list_i.@io.StringIO(@withF.ZipFile(, 'r') as tftf.printdir(tNexpected = t.getvalue().encode('asciibackslashreplaceZ  --,PYTHONIOENCODING=:I!) z@as_zlibAocreate_ ddCleanup(unlink, TESTFNpRopen(B, 'w f.write('' 1oPos.mkB6DIR_ drmtree +os.path.joiaDIR, 'c_txt')2=Rs = []Yu*'g + '/'8W.F c"-- :try@2, *vsg8o 'oaz5 d4zf.8 >Tread(71[0]1 g> F2FBofinall{% 2qst_extract_command(self): zip_name = findfile('zipdir.zip')* for opt in '-e', '--extract'PW with temp_dir() as extdir'+`out = n~cmd(opt, ,=97assertEqual(out, b''0zipbP.ZipFb.zf: zizf.infolist(B%path = os. b.join(,L0 0zi..replace('/',RNsep)Bif zi.isw,<TTrue( isiOelse_%(` Aopen-a, 'rb'4f.read(), z zi)) if ___ == "__main__"unittest.'() from __future__ import annotations USING_STRINGS = ] # dataclass_module_2.py andA_str"re identical # except only the latter uses string". z$es, InitVar+0typEC T_CV2 = Q[int]3Q T_I(U' IV'5 @ 2 CVog4QJcv0:yQ = 20K6cv1D = 302: M2&33rnot_cv44 # When usG, this field is not recognizeda.I IVi-%1:"IV!iv&IVib0n~. # # Test script {0curv&&&doesn't actually displa0ythhvery coherent. but it'oes call (nearly) e,amethod1@funcmF ed: {def,reset}_{shell,prog}~e, getch getstr(), # init_color() # Og1ed,\getmouse@&unC # ;$os Qy  lmA.supaVrequires, ule, verbose, SaveSignalsuOptionally test curses module. This rently requires that the # '4' resource be given on$p regrte^ommand line using -u # option. If not available,h,pafter tB@willm executed. import inspect (@) #aeither ofse don't exist, skip 2s. 2 = ^!_mT.ascii') 6.textpad') try: _nses.panel except IRError,pass def__func(name)*return unit.Unless(hasattr(:!, 6,'VR%s' %= term = os.environ.get('TERM'~1new'pwas suped we could use i@teadinitscr <iexit @0If(X1or == 'unknown' "$=%r, callbi() may cam1" %S)vsys.platfo= "cygwin"q'RgsV just hangs") class TestC( as@+amethod`setUpCDC(clsiW__stdout__.i'y((,@# Ter3ary@estsqnon-ttyo*Vraisea@Skip*('l0 is a tty')Ccls.tmp = tempfile.ZFile(/Sfd = 4..'no"Belse+y = NonezK R# !Psetup] ()fCide 4u/endwin]#?s8inal breakagx.Tqfd=fd) DtearDown\.closI4delHvCW(self.save_signals = SaveS *7!if verbo!# uto make output a little more read,Wprintj td<='savetty( p 23res2~ c?p.restornst_windowsw"Xs1!s"Gsu0win<[.newwin(10,10)  win = curses.newwin(5,5, 5,5) $m win2'D15,1)* for meth in [stdscr.addch, Ustr]:3e7Aargs7('a',), A_BOLD),7;(4,4, 'a';H @ x=with self.subTest(=.__qualname__, =)F3!(*! Uclearclrtobot4frtoeol7ursyncup_delchF deleteln4UerasegetbegyxE &8kgd68key?maxEXparyx7/in ginsertFinstVis_wintouchedwin.noutrefresPredra "standout6&en*OdownH &wiu;win&()0addV('1234', 3",s3 1X' ] ^cttron(6%/ff&?set& bkgd(' 'REVERSE+jGJborder(65, 66, 67, 68l69, 70, 71, 72Fp'|', '!-/_'J '+ \\#/  asRaises(TypeErrorRW msg="Expected.`) to rO N"w&[] ^x[70"x((_n.box(b':', b'~n6x, p:2x() stdscr.clearok(1)  win4 = stdscr.derwin(2,2)" 1,1, 5,5'3.mvB79,9e^echochar('a'9, curses.A_BOLD,hline('-', IIM ! Q'~2idcb`Z:idlif hasattr(;, 'immedok'):WG . 0.insch('ctinsdellnSOPnsnstobc', 3V !  Q58? 'aW ' ] ?def J,O #U s_touched(okeypadZleave9wmove(3,mwin.mv0nodelaydnotimeoutwin2.over46winowrite(6a, 1, 2I1, 3HH. `redraw [scrolh9(  .-3{1Oetscrreg(10,1Fwin3h0sub$ $4M<@sync; and not sys.platform.startswith("sunos"dF #(, v:/'addSTANDOUT~_chgatK!(53ZVBLINKW2 ,  +G5, 8ZUNDERLINE^ refresh(( J stdscr.vline(1,1, 'a', 3, curses.A_STANDOUT) if hasattr(stdscr, 'resize'):&-.(25, 80)"HoenclosIw(10, 10self.assertRaises(ValueError, getstr, -40;2A "in{2y8x2def test_embedded_null_chars(X# reject , , bytes and 6eacters10 = L.for arg in [/Zb'a']Cwith=ubTest(arg=arg!d 1addAV'a\0'D@DE?, 1H$?ins.K.BUTTON1_PRESSED"if-Z == 0 XR stufKV+interval(1# just verify these don't cause errorPUE(0, nmK Spaneld userptr_without_setwj0newH10, p"eQ.new_ &(w# try to access {() before calling set_-- segfaults  with self.assertRaises(curses.panel.error, 0msg='userptr should fail since not set'):I#p.31() @requires_q_func('!')#def test_;_memory_leak(dBw = I.newwin(10, 10Jp"e(_ &(w&obj = object( nrefs = sys.getrefcount(obj%for i in range(1005.se<FNoneYoEqual(!, "~ Eed references"(segfault zzclass AW#|__del__|U y ] 6A()|?4newT ,1QTypeEa type() is_term_resized   &*`stdscrKPmaxyxqQ  "~( } |2tlines, colT)dLINES,ECOLS0;42 = 9- 1KR+\L , 9"jA2 2 cissue62438pungetch(1025lL;?keyN GC_wch# XXX Remove the decorator when n on OpenBSD be updatedqP@unitq.skipIfplatform.startsl("openbsd")"b#'s (v.5.7) has bug5 5mscr encoding = stdscr.# for ch in ('a', '\xe9Qu20ac U0010FFFF'):9@:try"chf$e(m)5except UnicodeEoeErrorKyontinue@uurses.unget_wch(chvE}ion as ertself.fail("N@%a) ed with %s: %s"l% (ch,,})Fread $assertEqual(5 , [m = ord c+:odefU-def test_issue10570(CCb = dtparm( igetstr("cup"), 5, 3F.Is(type(b), bytes) } {:pimport D%csK5M2.lookup<Raises(TypN%10#otyp`check(), expectedBwithj0suba(ch=c,^=: 0 QEqualb7(i)e04c45FiCrange(256c2Bhr(iab = bytes([i] T.isalnum, b /()54pha5?pha5Rdigit5 5Rlower5 5Rspace5 54uppj 5Z?, i < 128;@meta0/>=1@ctrl17< 3'cn0p or i =k7blank, cwC' \tOl scii.isgraph, 32 < i <= 126)  check(curses.ascii.isprint7=8unct, c in string.pouationy[xdigiB"he5s) Pfor if (-2, -1, 256, sys.maxunicodeE+1):Bself.assertFalsealnum(i)6?pha66_lower6_space63upplETmOctrl5n6!_blankl_graph6Y6D667 meta(-1)kdef test_(>C9 = =paEqual(('\xc1'), 'A']_ -A*4ord[1), -A'[l 1('J/\n *$0, 'U @U0U4J')] -lt,lt?altAalt(?x8a ,W l, 0xc1,rl o 1('a^ + +;V; + + +A\x7f./^?/n-J') self.assertEqual(unctrl('\0'), '^@') ?sel-ord('A')1A0"\n1'^J2# Meta-bit charactersQ'\x8a!NR'\xc10cdh5i if __name__ == '__main__':unittest.() import os &sy $sldpprintthreadingurllib.parse # Re HTTPServer to _Pso asavoid confusion with89. from http.sK(O(as^,`Simple%RequestHandler, Bas") k d0sup here = os.path.dir(__file__) HOST = 2. CERTFILE:Pjoin(N, 'keycert.pem') # This one's based on , which ibsocketr class2>(t1):  de!pinit__(", @_address, h*_P,Rtext)AW?.__L 0conY$ =c3stryreturn ('<%s %s:%s>' %"._4__.&Z6# &))Rget_r`u# override tto wrap 5SSL6tryb) , Yet.accept(N.dslconn+\.s_8(side=TrueG exX OSErrore#e! s are silenced by the calf1 m %if)kverbosh$ sys.stderr.write("Got an |:\n%s\n" % 8Uraisen1sN)nRooted"(;`# needranslate_ get a known rootX# instead of usingTcurdir, sinc-!e rcould ba# run AanywS1verA@= "T{Q/1.0"%& =1# Ay@hangswhen a  gets interruptQlientRtimeout = 5tth(self, patSh): 0"""Translate a /-separated PATH to the local filename syntax. F Components that mean special thingsKu system (e.g. drive or directory ts) are ignored. (XXX They shouldGprobably be diagnosed.)5"""-# abandon query emeters#path = urllib.parse.url (L)[2].0os.P.norm (?bnquote>)<words = 1.split('/' filter(None, 5$< = self.root]1for,1 inswN4 = (hg3Ohead2-YAjoinAYareturndef log_message(, format, *args# we overridezxsuppressIging unl"verbose0if -Cort. ''sys.stdout.write(" server (%s:%d %s):\n [%s] %s\n" %7 .G@_add,:  :Oport7request.cipher()5date_time_string;%) class StatsRHandler(BaseHTTP"""Example $ " h=r which Bs SSL statistics on GETP8!s. H_version = "kfS/1.0"ado_GET, send_body=True@"""S a{.qEsock``.raw._$pcontext'Cock.6{5@'ses_cache': 7.7 ' 0': A'comO5ion* T}$rprint.p(%.encode('utf-8 .wresponse(200D Per("CDnt-type", "Q/plain; ch!t=f"FLength", str(len(+));&s(b3 \w\#qdo_HEADvfgelf.do_GET(s+end_body=False) def log_request(self, format, *args):*.if support.verbose BaseHTTPRNHandler.a class <SServerThread(tBing.&):__init__context, host=HOST, h__W=None.flag = s( = ((\U, 0),- } or Rooted !M)x1 = ._, F.; Tdaemon = Truen3strmEreturn "<%s %s>" % "._u__.__name__,Estarz?lag J_1run1elf JeV.set(?try)ls_forever(0.059ofinall= r_close(Lstopuphutdown4 make_https_#(case, *, =Y, certfile=CERTFILEI $if^1 isG(wsl.create_default_ (ssl.Purpose.CLIENT_AUTHB# We assume thet ains both private key and'qificate-l`.load_p_chain( m6 v(A\ W=46 = jDEvenBZ.*4D.wai'cleanup(v sys.stdout.write('<Bping 2\n'w.)jFjoinii(iS.addCOd if ? == "__main__"f im argpars 5r =.ArgumentP$!r(description='Run a test65. '040'By=,urrent directory#d.y#_a('-p', '--', type=int,^_=4433 help='= to listen on (hlt: %(defaul.t)s)') parser.add_argument('-q', '--quiet', dest='verbosefault=True,GK action='store_fal<help='be less T s@stat Ause__handlerFk0trualways return `_ page- -curve-namI_type=str'(] ] for EC-based Diffie-Hellman VipherPcallowed :_ lists !dhK`dh_fil/n /@PEM C containing DH@ametS`args =As() support.0 = 2#"if s:P_clasoSRequestH,Oelse6RootedHTTP; g.root = os.getcwd( exssl.create_de_(Purpose.CLIENT_AUTHB .load_cert_chain(CERTFILE&g.set_ecdh_%([ 0 HEdh_paramsE- BsB? erver = {!SSR(("", 9), ,x:extFprint("Liste on https://localhost:{0.e}".format)[s._forever(0.1) im5 unittest.mock from  .builtins4lib$io o&dshutilsubprocess py_uuid = i.x_fresh_module('$', blocked=['6Q']) c @U>S defPable()2try ;#___#fexcept9 T2 BaseTestUUID+r = NoneY_$S(selfuPequalelf.assertE!`ascendE= [] (string, curly, hex, bytes_le, fields, integer, urn,  time, clock_seq, variant, version) in [ -3('0- )',50 '{ 1}7 1Ob'\0 2/I(0, )0'urn:uuid:  kPself.D.RESERVED_NCS, None10203-0405-0607-0809-0a0b0c0d0e0fg66kjih &x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\x0d\x0e\x#b'BJ31\0HPHPLa(0x000@, 0x607, 8, 9A v4@<  yQ0x607jv_809, +2d9e6d5-9467-382e-8f9b-9300a64ac3cd+6+6kjih 2\xd9\xe6\xd5\x94\x67\x38\x2e\x8f\x9b\x9I0\xa6\x4a\xc3\xRFN9NVNVR7 8f!9bS=FB> =9P0x82ej0=f=FC_4122, 3('12345678- - 66 66 h12\x34\x56\x78'*4>$"78 (0 D*\x v4(0xL   12 34  Z F"  \)^678',  0x67812345678, 0x , self.uuid.RESERVED_NCS, None), @('6ba7b810-9dad-11d1-80b4-00c04fd430c8'5? '{6}76kjih .b'\x6b\xa7\xb8\x10\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x3 RFNV^dVNVR4(0x 80 b4  FB>  @urn::P0x1d1j=<FC_4122, 151s56 5 f515,15=1y55  Z 5525"6 52ZV M 525225C2%55  Z 5545"6 54ZV5452459d\xd1\x11\x 80\xb4\x00\xc0\x4f\xd4\x3X8', (0x6ba7b814, 0x9dad@11d1 80b00c04fd430c8)GFB>H80b42 1'urn:uuid:-:-;-<-= P0x1d10=Pself.W.RFC_4122, 1('7d444840-9dc0sb245-5ffdce74fad2s/'{6}76kih b'\x7d\x44\x48\x40\x9d11\xd1\xb2\x45\x5f\xfe\x74\xfa\xRFN4^VNVR4(0xy b2 45  FB> 55$c0= 327e902893a-9d22-3c7e-:-d6e313b71d9f{676kjih e9\x02\x89\x3a722\x3c\x7e\xa7\xb8\xd6\xe3\x13\xb7\x1d\xRFNV^N7NVR4(0x{ a7 b87FB> 79P0xc7ej= 2773('eb424026-6f54-4ef8-a4d0-bb658a1fc6c7676kjih Peb\x4R0\x26\x6f\x5~e\xf8\xa4\xdUb\x65\x8a\x1f\xc6\xRFr02\x^NVN4R7{adS 4 0xB> 7P0xef8jv 2474('f81d4fae-7dec0-a765-00a0c91e6bf6n '{f81d4fae-7dec-11d0-a765-00a0c91e6bf6}', 2'f865432 1b'\xf8\x1d\x4f\xae\x7d\xec\x11\xd0\xa7\x65\x0 0\xc9\x1e\x6b\xf6RFNV^NVNVR4(0x@, 0x a7 65)FB>  1'urn:uuid: P0x1d0j= 27Pself.Y.RFC_4122, 1('fffefdfc- Lfbfau '{- 167l> 0dfc2 h7f\xfe\xfd\xfc\xf(7 RF&VF ,4R70dfc{ e( 0 0x:;&7-oer=g3ffe, 7ESERVED_FUTURE, NoneAff A 1@?fffA h[f'*16>]   1  fO3fff)]:equivalents = []!# Construct each UUID in several different ways.=Pfor u-[p@(string)^curlyw>v>v>v!<!<usorting (above list iszv order) re?8ed f%:]d 0.re&e(Bs$, )idef test_excep gs(selfkbadvalue = lambda f: $.assertRaises(V$Error, f0badu= FType<# Badly formed 2(: self.uuid.UUID('')) badvalue(lambda: self.uuid.UUID('abc012345678L9/89N2zM# Badly formed bytes.6 /=<6o\0'*158E7)) ?_le?_le#9#; _field0_=(1,)_6 2, 3, 4, 5A.`, 6, 7GF s out of rangX-1, 0k  EC0x10K?, 0N"*, E$J% E' J(E*"H+E-H.E0!00Version number$ '0B6, vN/=0u =6rInteger, lambda: self.uuid.UUID(int=-1)) badvalue(lambda: self11<<128)) 6&# Must supply exactly one of hex, bytes, fields, int.> h, b, f, i = '00'*16, b'\ I(0, E), 0> h ?ex=/=b> ?_le#/=fDni7Wrong number,arguments (positional)+obadtyp * t.?, b1?, f4!:, i^Duplicate !for hh in [[], [('hex', h)]]:'*(bb*' ,0-le2?_le59(ii7@int'g2(ff6f/'G9 =args = dict(hh + bble + ii + f2 pif len(Ij) != 0= / Qh, **P7  z1z.w# Immutability> object()) def test_getnode(self): @1 = d.uuid.))$assertTrue(0 < 8< (1 << 48), '%012x' %e# Test it again to ensure consistency.p\2`Equal(5!1,{2E != ".# bpo-32502: UUID1 requires a 48-bit identifier, but hardwares!# need not necessarily be 48 bits (e.g., EUI-64)|1_eui64# Confirm that *P ignoaddresses larger4An 48 . Mock out each platform's */ helper functionsgreturnNsomething justv!to. This will causeF to fall bant_randomq, whichNHgenerate a valid"uelAtoo_Hter = lambda: Mwith unitC.mock.patch.multiple(+Z),_=None, # I any cach1,deP_NODE_GETTERS_WIN32=[]m 4OUNIX3  rz    1 can use the Hde, i.e.,Y#? fe- t() rathWusingMzvalue from eX abovD&ryD9E1m=NGexcept VfError as eG`fail('H1 was given an inXC ID'W A ;e2 q# Make v%()ssC t actually version 1Zfor u in [ ) irange(10)](u.variant,RFC_4122L1:, 1 In(u.is_safe, {P.Safe._?/unA.cknown}}sally unique.# uuids = {}for u in [self."@1() irange(1000)]:;U0s[u] = 1equal(len(.keys()), B (# Make sure th pplied node ID appears UUUID.>Lu = %0) u.L', 8x123456789abcE&RfR%/f)clock sequence"  2 ) A((u._seq_hi_variant & 0x3f) << 8) | '9lowq81, 0 4 qF3fff4hA3# bpo-29925: On Mac OS X Tiger,a).is_safe returnsFASafequnknown!@support.requires_mac_ver(10, 5&@unittest.skipUnless(os.name == 'posix', 'POSIX-only 0'@1def_v1()gif notA_has0_generate_time=7JdTest(' m=G(3)'(\#FS) mayl 0 or -1 but what it2s iNdependent onZunderlying platform  At leasP0can"!beO1 (u" I<sQis buggy)5assertNotEuC^ 6;@contextlib. qmanagerOmock{ , g_value1"""?MO.EC) toc a given *T*T4if !N  ._load_system_functions(Ff._generate_time_safe if f is None:self.skipTest('need uuid._generate_tO%');with unittest.mock.patch.object(WH?, 'J,J lambda: (f()[0], _value))ayield Z@Unless(os.name == 'posix', 'POSIX-only 1def_1_unknownu # Even if the platform hasD(), let's 4a it toO# be9() and ensurej ty.D~ayAu = 4.&1("assertEqual(u.isd,:SafeUUID.)By 0MF un_/-1MCbogus_return3O <3e?pR+l # a some X version-3 ^sfor u, v in [jz .NAMESPACE_DNS, 'python.org')'6fa459ea-ee8a-3ca4-894e-db77e160355e?URL, 'http:///V '9fe8e8c4-aaa8-32a9-a55c-4535a88b748d?OID, '1.3.6.1K 'dd1a1cef-13d5-368a-ad82-eca71acd4cd?X500, 'c=ca658d3002-db6b-3040-a1d1-8ddd7d189a4d'), )]:equal(u.variant, self.uuid.RFC_4122)1ersion, 3 IUUID(v)(str(u), v) fdef test_ 4()" =passertE<# Make sure C) generates s that are actually v1 4.Ifor u in [Qirange(10)U>45thed funiqueos = {}#0Ru[u] = 1TQ(len(.keys()), 1000 5!Test some known"-5 @u, v[jz NAMESPACE_DNS, 'python.org? '886313e1-3b8a-5372-9b90-0c9aee199e5~ URL, 'http:///4c565f0d-3f5a-5890-b41b-20cf47701c5e?OID, '1.3.6.1K '1447fa61-5277-5fef-a9b3-fbc6e44f4af3?X500, 'c=caI 'cc957dd1-a972-5349-98cd-874190002798?>5u%$P@unit&.skipUnless(os.name == 'posix', 'requires PIssue8621ug# On at leap"s of OSXH4s # ssequence=!inparent and any; children started using forkdos.pipe(0pid = os./1if 6= 0S1os.close(fds[0]JTvaluetX&ros.writCA1], 7.hex.encode('latin-1'os._exit('OOelse1 self.addCleanup(os.close, fds[0])  parent_value = self.uuidy4().hex1os.waitpid(pid, 0PUchildOos.read(z , 100).decode('latin-1') aassertNotEqual(', d) class TestUUIDWithoutExtModule(Base, unittest.aCase):~` = py_ 5 @)skipUnless(c, 'requires the C ! mp/')$pInternalsBNoneJos.name == 'posix'P@def #_find_mac((;'data = ''' fake hwaddr cscotun0 Link encap:UNSPEC HW$O 00-P eth0s TEthernetV12:34:56:78:90:ab =vpopen =mock.MagicMock(*.stdout = io.BytesIO(1.en)KwithYpatch.object(shutil, 'which',o breturnJ='/sbin/ifconfig'Dubprocess, 'Pa O %9macB@command='oargs='hw_identifiers=[b'/']M get_index=lambda x: x + 1/.mac, 0x1234567890ab/=pcheck_n: , $, 5=@%ifA and.@ is '^N.(5' +C0hex%012x' %Xif support.verbose >= 2pprint(hex, e& '^True(0 E_arpu!):_t0 = i.uuid.-H(!/ar>lanscan 11f=netstat 11)ntWindows'hipconfig 2R(2 importable('win32wnet')"HznetbiosFD  1 oorandomn 0m# The multicast bit, i.e. the lesignifican  of first octet, @# muCe set for wly generated MAC addresses. See RFC 4122Ku$4.1.6.]EassertTrue(}& (1 << 40%012x' % : P-2^ KNotEqual!2,t;, 'i Eunixxif not _m') andwctypes'A T/Test("neither I extension nor A` availv"% try: # Issues 1481, 3581:I_ _time() might be None  texcept TypeErrorG ! 5 70, ' E e('ctypes'),' 'requires ctypes') def test_windll_getnode(self):#'0 = l.uuid.0N+$`check_6() class TestInternalsWithoutExtModule(Base"`, unit.CCase` = py_ 5 @)skipUnless(c,athe C ! mu/'))z if __name__ == '__main__']() """This is a""" from __futurIimport nested_scopes; string; 5\ < 3f(x]3g(yreturn x + yAg result = f(2)(4est script for ftplibr ."# Modified by Giampaolo Rodola' toQ FTP <, IPv6 and TLS # environment iasyncore4hatUsocke$ioEerrn $osthreadingrime tryssl except IRError#ssl = None&, &0sup.!`HOST, v6 TIMEOUT = 3 # dummy data server o'!channel when # RETR, LIa NL MLSD commands are issued +_DATA = 'abcde12345\r\n' * 1000 I$0foo0bar ' `w ("=cdir;perm=el;unique==keVO1+ZF4;QZ"=p= <d?3; ..:OS.unix=slink:/fooba JR4G4; Nchr-13/29 J5JodeviceJblk-11/108K6K_blockJBfile<;awr8?writabl]=cpm7CpromiscuousF 1t2; no-exec= Etwo word~ArIH4; lO spaF11Gincoming\r\n"  "type=file;perm=r;unique==keVO1+1G4; p2\r\n" 4=3=)4=) class DummyDTPHandler(asynchat. _ !): dtp_conn_closed = False ef __init__(self, ,a, basejF[ d.=)Z1Q.J& =V# .last_received_data = ''hQ_read nK1+= % recv(1024).decode('ascii')i5 j2# XXX: this method can be called many times in a row for a single#oection, including6 clear-text (non-TLS) mode.>(behaviour witneswith testAbbif not !60.push('226 transfer complete'^9> tg = Truh|g, what"if2nex1 isJNoneD 9Q%0 = Y,C[ mbreturn_when_done( ksuper(,6)gZ9.en\errorraise ExcepZ 6F6 m/cw9?siz|L1000/mky7 "%s"' %z/rm@O0 rmpA7 "p"?typ000 (t?quip021 (?kclose(J?abo@226 (T"?/st?@125 (??res =t`3w?ret(\"if{is not None&offset = in.0?els202dtp#Pnext_b_data[g&:]Y&4_when_don#! = x/liq Y( X{%LIST_DATA3/nl( /NL&Oopts000 ( 6mlsDg): self.push('125 mlsd ok') !2dtp%MLSD_DATA!close_when_done() Edef cmd_setlongretr(Uq, arg):$l# For testing. Next RETR will return Be line.8L`.next_[_data = 'x' * int(f -# class DummyFTPServer(asyncore.dispatcher, threadT "):handler =FH__init__  ddress, af=socket.AF_INET  o.E+;daemon = True)rcreate_R(af, .SOCK_STREAMyNbbind(a listen(5active = Falsw_lock =q[Lock(Hahost, bport = 0get name()[:2]_instancFNoneQstartassert notl Zi__flagWEvent mM@.wai@OEOF;R *ale_close#+# TODO: $does not expose alert informatio"SSLV3_ALERT_BAD_`IFICATE"R2erra/1].Yraise1/OS ==no.ECONNABORTED*NelseAshutdownM`: " =0.un TYBo r# Any " or" corresponds to asSYSCALL b {# from OpenSSL's:'),[]D3ed Pcondiy@. Se.sob# http://www.mail-archive.com/openssl-users@.org/msg60710.htmlIpass|if getattr, '_ccc', +B) is super(SSLCAion,!). npass def handle_read_event(self): 0if ._ssl_accepting$/%!do(Zyshake()M)elOOclosMshutdownL/seuper(SSLConnection, ). %) d_write Asendk, data>tryreturn sUO~A ex\ ssl.SSLError as erre if.args[0] in (8_ERROR_EOF,KZERO_RETURN,y} QWANT_READ<%[WRITEAv40ZraiseCrecvbuffer_sizeY$\V :PQ9b''o:, hR` $Qe  ~3! E8:ion( 6if (isinstanceXu.socket2S]) andAV4obj is not Non2_5") class DummyTLS_DTPH #B"""ABB sub[`suppor TLS/SSL."""}C__init__W, conn, baseCk1 .= H\.secure_Y_channel9 self.secur$e_connection() class DummyTLS_FTPHandler(SSLC0,#!):?CL"""AB sub[supporting TLS/SSL."""}>Rdtp_hs" =GD+ef __init__(self, Q.21J .secure_data_channel = False-E_cccdef cmd_authKline"""Set up sStrol vpush('234 AUTHJ successful')51] ?cccGxr20 Reveback to clear-text$?TruAdo_ssl_shutdowOpbsz"""Negotiate size of buffer for] transfer.'0ForH the only valid!ueGparameter is '0'GAny other6is accepted but ignored5l00 PBSZ=0:.')hOprot! Setup un/  g`arg = z.upper(U1if "V= 'C'2roti@ set-C- (=}'elP!Private Oelse "502 Unrecognized PROT type (use C or P)."tServer(L42 ~TestFTPC( 0Cas jQsetUpF\2FTP((HOST, 0)!0g.start=client = ftplib.FTP(timeout=TIMEOUTN2."ec!.sq.host, Xa!PtearDV$ YLloseOGstop# Explicitly0attribute@prevPdanglathreadgR6Nonasyncore.cR_all(4 =|Qcheck), received, expectedlf.assertEqual(len(received), expected)) self.assertEqual3%, . .def test_getwelcome(>!):P Mwclient.7), '220 G+')bsanitiz`5'foo'), repr( Cpass 12345J*'A QLPASSQP*QFeexceptionseRaises(ValueError, ~endcmd, 'echo 40\r\n0' KI6r ftplib.e__temp N:/99. Operm /50NOroto 9O Aall_x I = (yreply,  o9  )"OS A1EOF for x in ~:tryr`E x('6 not includedP$G set.@7 +j\ |et_pasv # -ive mode is supposed to be enabled by default'2Tru`.Vfserver:3#s= #V0_FalseW =0voi1 #2(&?5_ & N1O: 300') def test_login(self): .client.!!) 7Oacct6  'passwd'=orename? "'a', 'b')}server.handler_instance.next_response = '200';assertRaises(ftplib.error_reply, a&, M_delet "O'foo&?199)#, ?siz  :try.cmd('noopxVexcept (OSError, EOF ,(BTrue.a# baseR ftplib.FTP(,8 as ~E&Wk. (([/" 'BQZ`# QUITt inside the qUblock*6pf force a wrong response co{1o bAt on0: e`U_perm#1and0ionsupposed tT@Z * "fHelf.client.sendcmd('noop') 2self.server.handler_instance.next_response = '550 error on quit' Pexcept ftplib.%_perm as3:zvassertEqual(str(err),dOelseJqfail('Eion not raised# needed to give th0rea some tiQo set%attribute# which otherwise would still be == r3U.sleep(0.1  0lasceived_cmd, 'QFalse(is_client_connected()) def test_source_address()j.E.o(oport = sup .find_unused_*6tryR7VyQost, &.R,@ =(HOST, <)=[ |sock.getname()[1]G F5 1OSE5  @if e- no3errno.EADDRINUSE,skipTest("cvqn't binb %d" %  _passive*1ion b 8 =  "Bwith`transfer`list')a- parse257q0'257 "/foo/bar"'o*H` creatm?, 'P'"@R#s(dreply,%i, '250&`# The E"issY`includXe directory@I and in case it contains embeddouble-quotes>they mustc%d (see RFC-959, chapter 7, appendix 2). (self.assertEqual(ftplib.parse257('257 "/foo/b""ar"'), 'Oar')K( createdSTdef test_line_too_long(!):"dRaisesqError, client.sendcmd,=A Y'x' *50maxa * 2) :@retrs ~('SETLONGRETR %d' % .(q^received = [](, :r0, ' 4', o|.append?sto f = io.BytesIO(bY  0, ' T', f) @skipUnless(support.IPV6_ENABLED, "IPv6 not enabled") class TestIPv6Environment(TestCase): QQsetUp server = DummyFTPS((HOSTv6, 0), af=socket.AF_INET6F{.start(3 = FTP(timeout=TIMEOUT2.connect.bChost&0 aarDown6 l.closeOGstop,# Explicitly clear the attribute to prevent dangling thread})"u = Noneasyncore_all(ignore Y=True_st_afpMaf, @makeE XIwith)W Phandler_instance.last__ _ 'eprt' kfinallNE^./ddef testT7Default(.)%2# d -- use global P3et tQ>.assertIsNone(3getI3&()4M $&30% &ftp = ftplib.FTP(HOST0 Aocke j<Equal(ftp 5get(, 48wai;y zv$no\yodo not,=R4UT5.m%^Value0a vy INCr (GH1ect=oDifferentOrder=s TDirectAccessX = 30t.3#lf.evt.wait(3) ftp.close() class MiscTestCase( !):4def test__all__(selfRblacklist = {'MSG_OOB', 'FTP_PORT pMAXLINE @CRLF"B_ dI `'Error(parse150 7227 9 O57',Nprint_line/Pftpcp %'}4support.check, ftplib, = F$Smain(^Ps = [Q@FTPCk , TimeoutsIPv6Environment"DTLS_OSMixinT 6!] thread_info = ing_setup(62try +run_unit (*s.ofinall2]cleanup(*Gif __name__ == '__P2__'e`() """. program for the fcntl C module.(0 im platform$os estructyQ from. U (verbose, TESTFN, unlink, !,/_ Wcpython_only) # Skip{c if noI". =`!(''T# TODO - WriteIs.flock() and `f(). @get_Edataos.O_LARGEFILEPexcept Attributestart_len = "ll"4?lse#2qq"if (sys..Jswith(('netbsdCfree @open )8or E]sdarwin'&2if .calcsize('l').8*@off_1'l'2pidie&>Fxxxx*BZb.pack(G$+ ;+ 'hh', 0 b *.F_WRLCK, 05 el xT'gnukq@w'qqihhiux in ['aix3@aix4Qhp-uxfunixware7']`hhllli -6U!'++}_ \!ifuc3if O#(': ', repr(breturn\ata lockdat.a = get_lockdata() class BadFile: def __init__(self, fn) .fn = fn1afileno/+sreturn 2nTestFcntl(unittest.uCase): S\setUpRKv = None,tearDown/#if} and notv.closed!()unlink(TESTFN)t@st_f_# the example fromlibrary docseCopenlf, 'wb' rvtq.w3.f.~1), .F_SETFL, os.O_NONBLOCKHif verbosprint('StatusQf with Jv: ', rvQTLKW, DMring2LKWvepr(rv)UVnt_descriptorT# again, but p,r rather than numeric IlV? = } |1bad assertRaises(ValueError`)-1Sf)}?(-1o?Typo'spam',iq0@cpython_only _overflowf_capi import INT_MAX, !IN[# Issue 15989_Ot7 n? + @-rlzql.F_SETFL, os.O_NONBLOCK) with self.assertRaises(OverflowError):/6afcntl.(INT_MIN - 1, .F_SETFL, orBxBadFilez){ @unittest.skipIf( platform.machine().starts('arm') and )system() == 'Linux',OQ"ARM  returns EINVAL for F_NOTIFY DN_MULTISHOT"@def _J_64_bit(# Issue #1309352:x shouldn't fail when the third arg fits in a# C 'long' but not Uint'.):tryRcmd =z..U# This flag is larger than 2**31i64-bit builds>7sa+'except Attribute :dTest("9 or~ unavailablefos.open(os.path.dirname0abs(TESTFN))bRDONLYL @Efd, cmd,-s5kfinallyos.close(fd) 6Nlock/Solaris needs readQ filepshared =P:Af = x, 'wb+'bleno =@ f.R7no(!*Z(?_SH+/UN+ V# |f/NB;f/EXV+V Y kBValuf15, -S. F?TypEd'spam'ZI@cpython_only K#_o Timport _Acapi<7 I@.GFAX+1FO 3 Smain(#Drun_(F) if __!__ __72__'43() Dcopy $gc dpickle4sys vuwarning tweakrefinspect from x0sup`% 61 I" = None # This tests to make sure that if a SIGINT arrives just before we send into a # yield from chain, the KeyboardInterrupt is raised in the innermost # generator (see bpo-30039). @unittest.skipUnless(_testcapiWnot None and hasattr(71, "_`_then__I?"),Hu"needs G.E  class SignalAndY*FromTest(qCase): vEdef 1(self):return (yMw".2O2())I2I6tryVZRhnexcept 4"PASSED">?lse*@FAIL*+_HAand_\_fromjgen = 11()I@gen.( F(genD QBaseEion as _excQexc =assertIs(type(exc), StopIteratiom0PEqual..value, i3) ^qFinalizDJX mframe_resurrecth6# A - can be 4ved by a(G's f.Ggen(nonlocal`.  'ol+= sys._get(!0g =;wr = weakref.ref(gHnextUdel gsupport.gc_collO;Is(wr(),"QTrue(lp irefcycle `caught$a 2E geted anywayold_garbageC#c. 1[:]]ized = False  @e% 1u*r0 = 73aI gl)Greater(0get`0ounG6, 22+(=$oN self.assertEqual(gc.garbage, old_ ) def test_lambda_generator(self):%) # Issue #23192: Test that a < returning a H behavesI like the equivalent function'3f =X: (yield 1)Cg():t"##" '<Ufrom'.f2^"K g()e2f*Q3QfQ3Q*Q orD_fun in (f, g, f2, g2, f3, g3Tgen =5(r.assertnext(gen),W+Wwith 0Raises(StopItion) as cm9gen.send(2 cm.excep.value, 2) class GgP(unit.kCase):Lname$W((1Bp# check;0or OYK"R __:P__, "/"/3Z ". h..mC# modify .@ = ""?"&K % "e# must be a strond cannoudeletedTypeError, setattr,e4, 'o', 123D/__H?del ? PAs ofB` creatUM(6.__[! f$\&H  und(x for xrange(10+d~T5__,L  "*Q"GeneratorTest.test_name..") def (copy(self):'f(uyield 1%ug = f()Pwith I.assertRaises(TypeErrorOx.,(gopickle2for proto in range(^.HIGHEST_PROTOCOL + 1#, MP2ing G=(dumps(g, ) class ExceptionTest(unit.CCaseQ #  s the issue #23353: check that currently handled ee# is correc%saved/restored.pPyEval_FrameEx().=So_throwN _r P_exc_\rator]6try1MEqual(sys.Ginfo()[0], None6i0 asu# d by gen.>excpCValu  @ Is(exc.__context__s J# ensure 0ionnot lost8l we should be able toY1 ba&e Y v)make = XBPnext(0_? g_82 Qfu. VFpass[E)*cm[Iv cm` W5)0, ()s_O$ d#6@%* <B NF)N!g.slOstopiterate # See also PEP 479.@ RStopI]on yield with self.assertRaisesRegex(RuntimeError, 'rd StopIteration'):KRnext(gen())ddef test_tutorial_stopi@({D!# e " 4s the gen{ror too:dyh'f(J) 1 ` 42 # never reache2ug = f()5=bEqual(C), 1hB`dreturn_tupleZ%g!1" (gen = g"en(6z) as cm;gen.send((2,)_cm.excep.value, 3 ;o- @/(2!IsInstance(& Dbh2) class YHFromTests(unitw.CCaseb_A_gi_pOfroma binspect.getWPstate{T_b), "GEN_RUNNINGTSIsNon;. 2c@DvN_b0 ' a MD3gen_b = bl,vCREATEDP -H!SUSPENDR  code.co_name, 'a' p2MNone) $self.assertEqual(inspect.getgeneratorstate(gen_b), "GEN_SUSPENDED) RSIsNon9.gi_yieldfrom) /Q[] = [ # Exhaust{(W!OCLOS  tutorial_tests = """ Let's try a simple:>>> def f():0...!. 128for i in= print(imE2Ko0g =2hnext(g,&2 "Falling off the end" stopsCTraceback (most recent call last File "", line 1N! ?#2#g#`StopItion "return" also   To'2 # never reached$[>N3>f >q # onceFped, can't be resum7 @ How[&, 9nd % are not exactly equivalent+g1u nexcept+ )O=Plist(of&[]2Jaiseb 4C2())42] This maypsurpris}at firsC3 finallyD$3(31] acreate an altern range() function mented as ay;n]m*iW5 0,2, 3, 4] GEs alwaysx1 toa 6+er,orEr = |"81", r... return r ...>>> def caller():0...% r = creator()for i in r27 print("WE", i?GwXf! 0( 1 2 3 4 GenerQs can other g!: 5{zrange(ny qyield iOISlist(X"5)2[0, 1, 2, 3, 4] """ # The examples from PEP 255. pep_tests = "/Specification: YsRestricA not be resumed while it is actively{running"gi = next(me(`cme = g 6Traceback (most recentClast0 F "<ng>", lineTAin gValueError:already executing KbReturnKNote tha isn't always equivalto raising StopIt|1thedifference lies*how enclo9 try/except constructs are tq"ed4For',S$f12try r 033y"[]because, aqany fun", ` simplits, but;Ge2JaiseS 4h582()*42 {dcaptured by a b"m"Bs anMion.Qand E5ion Propag=98t21//`) f() # the zero divisr# p|!esdi@042 @we'll nevRt her!k&k[%5din 1,r??#2#g#f#SZeroDhvintegeror modulo::kVZ77StopIteration  >>> Specification: Try/Except/Finally , def f():0...J tryyyield 1)-121O1//053 # never get here.e ZeroDivisionErrorqX4F5Orais|j 6N7q # the "]" above stops this;kO8,9Zx = 1fi1j1>>> print(list(f())) [1, 2, 4, 5, 8, 9, 10, 11] Guido's binary tree example.9# A"dclass.F U Tree__init__(self, label, left=None, righ 5.4" =< a#0eft"?eft!f" =n#Gf__reprevel=0, indent=")"|Bvel**0 + IH2if 5eft?s = s + "\\n" +/.l$+1fg0hureturn E[4ite[CAqinorder:)Create ao from a o cnn if n == 0[8i = n // -fA[i],XH:i])ii+1:])Show it off: c("ABCDEFGHIJKLMNOPQRSTUVWXYZ"V A recursive generator that"esUhs in in-x\t\?if Rfor xML0(t. <xtE de H?/# t$JKLMNOPQRSTUVWXYZ") >>> # Print the nodes of tree in in-order.3Pfor x!t:0...N pI(' '+x, end=''h& A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ A non-recursive generatoadef in()stack = []WBwhil /K.lef!Xr.appendx `#! =`M %Syield Mabel!t%Origh>tryBpop(#except IndexErrorRmreturnF.ExerciseT""" # Examples from It-List and Python-Devc.l.py. email_tests = MThe difference between <ing NoneEiPit. Tg(): iwrange(3R2heialist(g()) [6,)] Ensurat explicitly raisBStop!ion acts liky other mion in try/S, not, 1)e -nD0Q2$31, 2, 3] Next was posted to comb(x, k""G`e all "qinationk elementn@ x." if k > len(xZ; *O== 0%[](Jelse# first, rest = x[0], x[1:4o8# A0 doSrn't contain N.o;QIf it+,r1nder is a k-1\ ?cgC(!,3 jc.insert(0,)#c&# Q, it's`seq = (a1, 5))kseq) + 2W print("%d-combs of %s:" % (k, seq)) ... for c in g,(seq, k): $print(" ", c) 0-,X[1, 2, 3, 4]: -O[] 1 "1](23O4] 29 $, 441, 71{R2/ 3[=4lN/ 4Q85* From the Iterators list, aboutAtypej these things. >>> def g(pyield 1!=(g) 0i =@ +i+2gen,0[s +s+#dir(i) if not s.startswith('_')] ['close', 'gi_cod Dfram srunning%@from@sendqthrow'] test.support imHAVE_DOCSTRINGS-i.__next__.__doc__ 0 else 'Implement 2(self).') d2ites i TrueOssinstance(i, $.G]RType)= And more, added laterSi.gi_1! 0XJ(U 8 = 42 Traceback (most reccall last)... AttributeError: readonly a(me'men xQme) 1Y # A clever union-finda $@c.l.py, due to David Eppstein. Sent: Friday, June 29, 2001 12:16 PM To: python-!@p .org Subject: Re: PEP 255: Si@ sxdisjointSetY9__init__og, nameN.! =0parn= None1 = 0!e(1) RwhileBelf.v1 iZ;x;Z=.o/orGxDC- freturn\?E", M!ifraise Valu("Sorry, I'm"a root!"|# =z S__str Gb s = "ABCDEFGHIJKLM" >>> se ts = [disjointSet(name) for 1 ins] >>> roo2sets[:] import randomSgen =!.RA(42)while 1: ... kshUprint(" %s->%s" % (s, s.find()), end='')L1qif len(8) >w`s1 = gen.choice(N#;.remove(s1[/s2@s1.union(s2<"merged", s1, "into ,Jelse:break A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M m{0 K v/ BR$BRARFRFRER F RDRCCHRMR5CJR H BRBRC>R CRCRFRGHG RGGRLRR$UC M->GRIIIII4 RIRHRHRHRHRHRHRCRHHHRHHHH """ # Emacs turd ' # Fun tests (sufficiently warped notions of "fun"). fun_7 = Y Build up to a recursive Sieve;Eratosthenes^e"r.-def firstn(g, n)return [next(girange(n)oBintsfrom(iA Zyyield ibi += 1Q5), 7) [5, 6, 7, 8, 9, 10, 11exclude_multiples(n,sg^if i % n-m3m1)), 6) [1, 2, 4, 5s(): ... prime = next(ints) ... yield primenot_divisible_by_ = exclude_multiples(*, Tfor p in sieve(O%):pR >>>3s =A^from(2)) bfirstn}s, 20) [2, 3, 5, 7, 11, 13, 1 9, 23, 29, 31, 37, 41, 43, 47, 56'9, 61, 67, 71] Another famous problem: generate allegers of the form J2**i * 3**j * 5**k in increasing order, where i,j,k >= 0. Trickier than it may look at ! Try writJit withoutors, and correctly 'Qing 3rnal resultsS each output.def times(n, gigXn * iD"10;`1)), 120, 30, 40, 50, 60, 70, 80, 90)&0]merge(g, h$ngg$nhhzwhile 1if ng < nh6)ngt"elP>P hPP/se1L ! T@llow^works, but is dopa whalePa lot redundant 2 -- it's not clear how to get+Aintew1use@@m235!share a &3le por. Note that me_Br2 (etc)AneedBee every elementBthe  sequence. So thisan examplelazy lists more natural (you can @head %a ; any number)K(X1=w22, 5%$3 %3%5%5%Pl,5 ))#5Hi Don'tnt "too many";rhese --=ation aboveextremely inefficient: c#of?` leads/3 recursive $<rin turn<`ose 3 OYso on until we've descended enough levelrqsatisfyprint stmts. VPodd: 2n I ed 5 lin*s below,Smanagcrew up Win98's malloc in "the usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting address space, and it *looked* like a very slow leak. >>> result = m235()Pfor irange(3): ... print(firstn(r<, 15)) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12&, 16, 18, 20, 24] [25, 27, 30, 3?&6, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 9V0g 08l Y 1235, 144, 1M1J 168(92] Heh. Here's one" to get a shared list, complete with an excruciat%namespace renaming trick. The *pretty* part is thatqtimes()merge() functions can bTused as-is, because?y only assumir stream argu' s are iterable -- a LazyLise same as a generator1Uclass;def __init__(self, g9=.sofar = []Ufetch = g.__next__$# cugetitemfifa$, Lu!, TYwhile i >= len( U'.append(F9())Iqreturn )A[i] N]-uyield 1=# Gack: )0 beactually refers.;1me_A2 = 1(2,G#3#3#5#5#~,+ ))#5{,@i P|pmany ofs2you-- *this* iaClmemory- efficients=(E>>>   [.1[j]*j4@15*ir*(i+1))]  [2]22X2`243, 2S0256 88@4, 3q3 384L 404B40486/5e0576y66675] Ye olde Fibonacci,c stylefibgen(a, bksum(g, h$1a(g) + h} Xtail(g): ...  pnext(g)# throw first away ...for x in g:pyield x abPsPsum(iter(fib), EFtail%*))ks >>> fib = LazyListUgen(1, 2))!FrstnNp, 17) [" , 3, 5, 8, 13, 21, 34, 5.9, 144, 233, 377, 610, 987, 1597, 2584] Running after your ` with tools.tee (new`version 2.4) The algorithms "m235" (Hamming) and Fibonacci presented above are both examples of a whole familyFP (functional progra} where a +)Qduces returns a list while the&\r suppos!0as already1ed by recursively callMitself. Foras"to work,y must: -Tp at leaqelement1outCjexistence of WP rest8`ctheir Ua lazy manner T efficientlyR begi-!offZp not be omputed over   again. This is ensuredMmost FP languag"built-in feature. In python, we have to explicitldintain%ofcqresultsabandon genuin@ity.what had been attempa&e class. OnWSblem %"attVpit keepJl`generak tfore continually grows_Qparti de=s>> def fib(): ... _isum(g, hqwhile 12yield next(g) + h)V'Zr<1(2^ fibTail) # throw first away-for res in fibHead,B0resJ realfib = _ R[PRes =l(81, 3L@turnPRes !n([, 17) [1,  , iBp, 34, 5@9, 1Q233, 377, 61 87e 978  """ # syntax_tests mostly provokes SErrors. Also fiddlj#if 0 # hackery. Q!= g`These Rfine:fb  re-:try >!fio %3pas[ ~ Q E1//0except ZeroDivision0 x*?666@.0...: C1IpVcOx = 0  [T]list(f()Ux2, 666]l): ... yield >>> type(f()) $def f(): ... if 0 /yiO)P Q! 1~ .""_ NoneT%t returnI trybJx==4Epass7-elBSy 1//0Bexcept SyntaxError{( Oelse/4while 12<"mx += 12 # don't blink2 f(a, b, c, d, e)- 0 (x Ru   g9?...@TypeKnCs<__init__(self@f927pr This one caused a crash (see SF bug 567538): for i in range(3@ Rcontinuekfinall9.i-F0g =s print(next(g)) 0+ * Traceback (most recent call last): StopItion Test the gi_code attribute05$g.Fais f._Rb__ Tru! 55l __name__A andorepr() UA 'f'K1g) ctest: +ELLIPSIS '< object f at ...>' Lambdas should2@haveir usual behavior.l=: (yield 1) >>> list(x()) [1] >>> x = lambda: ((yield 1), 12))':l, 2] """ # conjoin is a simple backtracking generator, named in honor of Icon's # "conjunction" control structure. Pass a of no-argument fu9I)that return iterable objects. Easiest to explain by exa: assume the #Xu[x, y, z]passed. Then acts like: # # def g(): # values = [None] * 3Bfor 0[0]!x6: 1 y $2$z$(nSo some 3-s] *may* beed, each time we successfully # get into? innermost loop. If ator fails (is exhausted) befor{then, it "M s"dthe next4Q froms@nearenclosing #p(6Sone "left"), and starts all over ag#atWxt # slot (pumpUfresh^). Of cours> is%useful w(Wtors have side-eff0, s>at whichjs *can adepend onied at previous@s. _p(gs): %A0len <qgen(i):/3if i >= ) uJelse'iPgs[i]0*x*'+1'xx 402&0# T?works fine, buO0curPAevel42chei/%b for #+item producs inefficient. By do'amanual,p unrollPacrosF boundaries 's possiliminate |1of `head. n't worth1bother *in l*  *0) ia core buildQblock9RCPU-intensivEor applicaYnPdnP# Do h n!revely, until#.s_# remainris diviVRby 3.j nS=elif (n-i) % 32ip1 = i+1.F[p  yield x Uelse:for x in _gen3(i)# F## Do three loop nests at a time, recursing only ifSleast7Amore6# remain. Don't call directly: this is an internal optimization forJgen's use.?defassert i < n and (n-i) % 3 == 0Lip1, ip2`3 = i++%+3&g, g1, g2 = gs[i : ip3]GfZ >= nV# These are the l, so we can xevalues.b!0[i]/g(&"p1(1) S"p2-2-1jR# At 6<; peel off 3He$ :/st iM/p34<>Wgen(0:&# And one E approach: For backtrack}apps likaKnight's Tour # solver below,_ number ofGalevelsbe enormous (one #  per square, qthat e.g. a 100x100 board # needs 10,000U s). In such cases Pythonly to run out oftack space due odSo here's a@on-frversionG conjoin too. # NOTE WELL: Tallows large problemsm"beXbd withtrivial # demands on sp. Withexplicitly resumable generators@ # m`harderyachieve. OTOH)'slower (up+a facto2) # thanfancy unrolled"3ve 0. USflat_p(gs): 1namqktansteadpn = lenE = [None] * nniters p_StopIt*= ` # makcal becausX0ughR*lot*` vwhile 1# Descendk6try 5S  it>']().__next__)-Mit()!ei += 1rexcept teration:  Tpass Uelse:assert i == nyield values $# Backtrack until an older iterator can be resumed.<ei -= 1while i >= 0:tryQ[i] =kes[i]()N## Success! Start fresh at next level38i +Ybreakdexcept _StopI>ion# Continue b1?ingy 9< 0 # A conjoin-based N-Queens solver. class def __init__(self, n)8.n Prange 8(n)Assign a unique int to each column and diagona#s: n of those, e1u# NW-SEDrs: 2n-14e44i-jminvariant along<#, smallest 8 is 0-(n-1) = 1-n, so add cqto shif'0-Ip OE-SW +$0+j a, largs(2.1For square, compute a bit veceexs it covers,#$ f\7rowXfunction thatH0genes the possibilitiesK2s i>F rowL3rowIors = []ci;* arowuse2(1 << j) | } ordinal] ' DA(n +,+)RC 2*Tp+ i+j))j1# N7C +<j]4(=)BKGF&[j"1if )!& u=*(!|=<| j J@&= ~  ors.append#$ge3# G7usUJ(IZWprow2col<.J:zprintsolF,)_An = self.n  assert n == len(row2col) sep = "+" + "-+" * nprint(sep0for i in range(n):.Rsquares = [" " .j.].[@[i]])Q"&!"||".join(i)&|"1 # A con4J-based Knight's Tour solver. This is pretty sophisticated # (e.g., when used with flat_c_ above, and passing hard=1 to the #structor, a 200x200was found quickly -- note that we'rL@reate10s of thousand generatorsz2n!) isgthy. class|s def __init__(self, m, n,0A.m, 1n =( !# Y() will set up succs[i]be a listX #i'sCuccessors.C" =x ([]zRemove i0 from eachd1itsR' fs, i.eh#,s can't go back i0 again. Return 0 if we+# detect t\pmakes a ution impossible, else rK&1.r__Ps(i0,<=le1# I9p all exC a free s,OR deadAc# evenQto it next6`'t lealtCct;1oneLmust visitc;J!somebody/Zh%to=@sinc/7ereRPonly ~adjacent,#Pre wo0way Finally,$0morz!andka'l c94ly s#em|;ingIthe otherxaF endne0 = ne1 = 0BcZs[i0]> .p:(i0"e s@if e0p:I+= 1$el:1:-1 :dVA== 06< 2vP# PutA/inD jadd_toCv6q.append`2# Gue first move.  def first(): if m < 1 or n %yreturn 7*# Since we're looking for a cycle, it doesn't matter wher3 Jstart. SG inForner makes the 2nd move easy.Dc, = self.coords2index(0, 0)- reF_from_successors(D +Olastij = " L_yieldoadd_to`@# GenerateCsecos  bassert # i.e., we Qed ine13131.@len(t"s[Zy]) == 2a+| P1, 2) B<O2, 1< # Only two choices. Whichevqe pick,0othQust b r# squar1Red onm*n, as it'oqway to get backJ2to !ave its  final so thatjs beforeL0he P knowmkept freey@i, jj(~1, (J_this B W\3-i, 3-j4!=  XQQuccs[J].appendY}> P ^#jj<S):s 3 through m*n-1?advance(len=len# If some  Q has one exit, *0tak_# Else favorDs with fewerC6candidates = []Kwt's[y]xFe = V.i]Pe > 0, "e `) prunyflawed"@if e1 ()&Jbrea@D <.sort()   for e, i in candidates: if i != self.final$, if remove_from_successors(i)26Vlastij = i~$_yield jadd_tor J# Generate s 3 through m*n-1. Alternative version using aG"stronger (but more expensive) heuristic to order .G Since the # of backtrackolevels is, a poor early onJcan take eonswundo. Smallest square board which thisGmatters a lot|V52x52def advance_hard(vmid=(m-1)/2.0, hn{len=len# If someq has onMit, must&it# Else favo\ with fewer exits6Break ties via max dist  centerpoint (e$~Acorn( nd edges whenever possible)|WY = []P|&'s[].e = len(,9i])Kassert e > 0, "e*`) pruno}flawed"Mif e == 1l 0(e,s*i))b~bc1, j1 Vindex2coord. .d = (i1 - {)**2 + (j| 4.append(j-d, i)?,@fsort()R0e, OA"(:+4*ij83w ifJ < 4,g0orsqVfirst^: , second] + \`[ I and4 or] * (m*n - 3)C]C2(g, i, jUQ0 <= i <mjn return i * self.n + j def index2coords(!,!):#'assert 0 <=" >>z cr@([lambda: iter((0, 1))#p3): ... pc) [0, ] 1 E1, 0   P] [1,H1] For efficiency typical backtracking apps,1() ssame list object each time. So if you wan'save away a &paccountTDits Gd sequence,@@needgcopy its resultsX0gen(JGatorAd\a xn '10K0allDist(qKn)))n, len(all), all[0] == [0] * n, all[-11) 0 1 TrueA 1 2 A 2 4 A 3 8 Q 4 16 H 5 3:86 6;H7 12=H8 25>H9 51? And run an 8-queens solver. >>> q = Q1(8)LIMIT = 2count = 0for row2col in q.L(): ... 0E+= 12if 1<= ].2print("Solution",.)@%!q.'s%($) 7[ 1 +-Y |Q| $",$ ,/Q|$ J$J$ $F (H=2}$i$ *=B$  ,l($ &$ $(4, "sall.") 92q $ Knight's Tour on a 10x10 board. Note that there about 20,000_BevenC26x6A, so don't d: this to exhausu 3k =s(10, 10xk Vk x,Jelse_Zbreak'O--+- | 1| 58| 27| 34| 3| 40| 29| 10| 5| 8Pt | 26| 382| 57| 28| 33| `h_0| 11T59|100| 73| 36| 4h9| 32| 9| 6T74| 25| 60| 55| 72| 37| 42| 461| 86| 99| 76| 63| 5P@8| 40P24| 72| 85| 51| 64| 51| 48| 13T87| 98| 91| 80| 7 7| 84| 53| 46| 65| 44| +--- | 90| 23| 88| 95| 70| 79| 68| 83| 14| 17T7| 92| 21| 7H@1| 9H9| 16| 45| 66T22| 89| 96| 93| 20| 69| 82| 67| 18| 15TSolution 21 1| 58| 27| 34| }E0| 5| 8p| 26| 382| 57| 28| 33| `h_0| 11TP59|10@3| 3uh9| 32| 9| P74| 2@0| 5-2| 37| 42| 4P61| 8@9| 7@3| 5P@8| 40P24| 75@5| 5@1| 6-@1| 4-3T8uX}8-}9}=9}2""" weakref_tests = """\ Generators are $ ly referencable: >>> import!1refdef gen(): ... yield 'foo!'(Dwr =9.ref(gen)P() isFQ Truep.Rproxy0?-it as well@gi =d(vbii .list(p) [1] gcoroutineiSending a value into a started\fZrprint((a01))^r 2;Sg = fnext(g) 1.send(42) 42 2 6new produces a TypeError2f()S"foo") Traceback (most recent call last% Gp can't non-None]just-A Ydby itself s @=`f()) [)]His allowed only in the outermost iterable i4n generator expression: >>> def f(): list(i for i in [(yield 26)])+type(f()) A 2ed with augmented assign .~coroutine(seq): ... count = 0bwhile V< 200-1"+=6seq.append(?)seq = [] Jc = bnext(c0Qprint 5 .sT.10!#10X# ?, 2', 30] Check some syntax errors sf=lambda: 31), 2) Traceback (most recent call last): ... SqEp1: 'm' outside functionX#x k$82 to not possible~Obar)(Scan'tu$vf Now cthrow() condiKJTrueD:try>K%))Dexcept Value_ as vCi"caugh/(%s)" % (v)Dimport sys0g = "g)n"g.{@) # o only k:("xyz")) # vC?xyzF, (1NO+matching1V2Typ\UQ# misQ!edP`, rewrd[=(1), None) explicit$ t!`TP"foo"U/# bad args: instance wqion mayhave a separate*!, C, 23,a) thirup must bBz object_"abc" snclasses or insta`nces deriving from BaseException, not str >>> g.throw(0) Traceback (most recent call last): ... TypeError: eW s must be classes or insta:intOlistlBtypeBdef (g,exc): ... 6try Praise#e$ &w*sys.exc_info())jQValuei) # do it with tincluded caught 32 ()g.send(1) 1_ ) # terminate the generator fprint(g.gi_frame) NonO2`StopIt2ionbD0,6)  on closed!Y2: 6t3f()1",7v##tjust-openy/7 Plain "Z"UVide a should preserv$(#13188). The<6have 3 levels: -`) - f(21/0/f( _yield 1g =a Hpa: ZeroDivisionV as vQ <+v) CwC6tb = w.__;!__A = 0while tb>!E+= 1qNtb.tb_next:( 3 Now let's try:q e$ GFExit"exiting""(g!g.33() 1];be no-op now >( Tbe ficIan even simpler v3! #Ve before 1ing/xCGnormally AndPalizaQ0finD)Udel g! atorExit is not caught by except Eion: >>> def f(): ... try: yield;-1rprint('%%')6vfinallyZ-"')0g =qnext(g) cdel g - Now let's try some ill-behaved generatorsG<JExit q "foo!"g.close() Traceback (most recenll last): ... RuntimeError: ignored }eY Ourcode should be invoked during GCimport sys, ioV@old,.stderr = %0.StD2IO(Y"G" ins.getvaluL!ue6sysold And e<s thrown propagate  raise Typ("fie!"! $ a : a Ensure that various expression constructs mak.deir enPfunct)ax R x +=Ztype(f()) Z? x :%lambda x=(zO): 1~bd): d[> "a")] =b!27Vdata = [1,2]gg.send(None) 'a'E?T [1, U%X0) 'b"%27#yM1GTp StopItW passeC 7] """ refleaks_tests = Prior to addcycle-GC sup to itertools.tee, this PwOU]erences. WeN0 itXthe standard suite so routine - Ttrigger ifGstarts beuncleanable again._0ef :gen __?w__(selfpreturn <<U.itemAVBgen(Ohead, tail =~bgG0 = /NAit =() Make sure to also test the involvement of.tee-internal teedataobject, which stores returned items. >>>  = next(it) Thisrleaked at one point dugenerator finalization/destruc . It was copied from Lib//[!rs _M_cycle.py beforePfile Isremoved@def F(): ... 7genwhile True)tyield g@Ag = @^ isn't really, related, but rather excep -in-cleanup ). The coroutineos (above) just happencause anR@ in 9's __del__ (tp ) method. We canI for this explicitly, withouts:ado havredirect stderr avoid printing warnings and doublecheck that we actu=Ced wwanted timport sys, ioPold =.6try3sys = io.StringIO() class Lr9CJV(self]#ke(message%*raise RuntimeError1(Q""#3l =Udel l#.getvalue().strip:$"E` ignorn" in errR":$Traceback!in)ke,l@old  pese refs should perhaps b! a2ir own, Xhscebm(@drewse out. """ __"__ = {"tut": tutorial2s, D"pep(?pep#Remail% %2fun#_ fun#asyntax& &aconjoiM 'pweakrefN ') +4s":s(} # Magic@ namaz gr$4s *after* . module. # worms around a bootstrap problem)3Noth0docg"ret both look.gPargv Oa "-v" argu@, # Jworks as expectoJ@ways0run7 regrtest. def te st_main(verbose=None): from test import sup,_generators..run_unit9(__name__)#1doc"K#, ) # This part isn't needed for regr<R, butunning the directly. if a == "_2__"HD(1) $ys $io datexit?os 3.(Tcript_helper ### s def h1(print("h1") 22334(*args, **kw `@4", #, nUraise TypeError##gSystem%1 #I class G[dlTest(~.0CasNsetUp(self.save_stdout = sys. ; &6err&;err&tream = io.StringIO(J] D Qelf.s>R4._clear() tearDown _R>&}0st_ ~# be sure are handled properly^register(h1% 4 0, 4m="abc")_dITfuncsDassertEqual.getvalue(),5  "h4 (4,) {'kw': 'abc'}\n0) { 01\nQ:ost_badA lambda: 1, 0!(xx in (1,2))0R%s(z#, `  Wst_order (!rsexecutedreverse @5s2 83 ! "h3\nh2\nht 4 23/S_unnormalizedIssue #10756: Makthat an unnormalized exception is # handled properlyatexit.register(lambda: 1 / 0) (self.assertRaises(ZeroDivisionError, MP_run_Wofuncs)DMIn("A1", gstream.getvalue()def test\(+%):] # be sure a SystemExit isk9a XQEqual.C, ''sprint_tracebacks; Issue #18776: the .p shouldIed when es occur.6u'f(]1/0 # one(g(9two(h(6hreR,yf( gh= btderr =l9o.countF), 3? lE'?two'j)>sVqa = [0]+N/#2.__ y'_oU__tear s  Z1 is Ued on#u Yexpected = b"TheMPhas pV'd!z, w = os.pipe(]  o3 nos.write({:d},xX`&""".format(w/reos.closeA  os.read(r, len(expected)), expected) os.close(r) if __name__ == "__main__":1unittest.() x = 1 __getattr6 "Surprise!" __di again!" import T` from ^ 0sup")$os &sy ubprocess SYMBOL_FILE#= L.findfile('symbol.py') GRAMMAR:= os.path.join( 0dir%0(__LA__),n c'..', pIncludegraminit.h') TEST_PY_) class TestSGeneration(].qCase): def _copywithout_g;2ed_s(self, source,a, dest )Ag open(+v) as fp&*lines = fp.read(Ig_, 'w'Lfp.writeE![:.index("#--start constants--\n") + 1]vM L!' def iter_~formats(C= ): for D in 8s#8( %)6if l@ not- ('u@') andk#(')@continueByiel@%, string_reverse(sSreturn s[::-1]+ bigendian_to_native(value47if L+Melse .) class SgTTest(.4Cas~v5_isS(self .assertEqual((.pack('=VP1)[0]80),!) gconsistencegdRaisesgserror, ucalcsize, 'Z'_z.$Q('i')"9elfmsz * 3Zw('iii')\0fmtS1cbxhhhhiillffd?'_@fmt3&3c3b18x12h6i6l6f3d3&s7fmtzG (^$'z3S !, ?, 3f? ',M3C i(TypeE)?fooNPNu#und', b'flapv'<', 1, 2Hi?, sA('?{`transiLness~vc = b'aQb = 1B<uh = 255i = 6553l6$f = 3.141%dZBTrue)l!hprefix6, '}'!'99`xcbhil, 'xcBHIL 6: max+5mat s = struct.pack(format, c, b, h, i, l, f, d, t) cp, bp, hp, ip, lp, fp, dp, tp = s])un_sJself.assertEqual([c(b(h(i(l(int(100 * fp), )>d>d>t!) def test_new_features(w!):!# Test some of the new / in detail25argument, big-endian result, littleasymmetriUs = [d('c', b'a;0),(x)"\01-(cxP"\0-s (0)helloworld2110h1292q:B1 1zdI&b'G2a+10*b'?P'WPb', 76!\7'-(2371* ,BS'1249|K2b'\ T1700-r002\274274\002', 5-6A375D3_D\3750He50x10000lil74,\035\20c @,\00DtE373\323\342? /73I0D 4l0D3', 0),  ('L', 70, b'\004,\035\200'0200,s', 0), ?D20x1E900-P373\323\342S/73Vpf', 2.00@\0@?d?K ' 0$v-"\3> !FN~?w\'3'11'LTrue*Q![](r?', RA(1,)*u0b'\*%] for fmt, arg, big, lil, asy in tests:.2!(x4@exp)&a[('>'+big), ('!<;lilT 3('=0ISBIGENDIAN and0 or*)]Dres = struct.packIarg)-self.assertEqual(res, +ccalcsizeg`), lenF)m6rev'un}res)[0]t0if 5 != ER(asy)1def_)Gexpected_I = {'b': 1, 'B h': 2, 'H i': 4, 'I l1 'L q': 8, 'Q }# standard integer s00codOyteorderSiter_2_formats(d, '<', '>7!')!p+D = bN+^o$o;  q<r[a]`# nativeP_pair0'bB hH iIl0'nN 5qQ',>(M+-+'O*@'&*FsignW (D'+ }:[0]+J/unL#1L{, unsigned_size) # # bounds for native integer sizes* self.assertEqual(struct.calc*('b'), 1)2BLess6=2, 9?h')6 46l6iIiIi _8qlIrGreater nLL!Pdef test_c s(V!):3# I}'s (bBhHiIlLqQnN).(import binascii PclassETester(unitK.GCasemq__init__, ;mat(,super(IntLAer, .?methodName='tV_one'C6.format =n!%Ecode#O[-1]'byteorder,:-aif not.45in sraise ValueError("unrecognized packingG}: %s" %P / e- =>J8$it7G=* 8"ifvin tuple('bhilqn'signed = TrueX'Pmin_vE = -(2**q".b'-14c5max<:M - 1y/eloBHILQNOFals0/se" 6)L A, x,=J,@ un*68hexlify=3.un*):n= if self.min_value <= x"ax?: expected = x!_signed and]/ 0ObSr+= 1 <<bitsizedassertGreaterEqual(JO, 0)9! = '%x' % /eif lenW_) & 1= "0" +\ y% =(.encode('ascii'unhexlifyk(b"\x00" * (F@byteh* -?) +LX'ifcorder == '<' or[1in ('', '@1=')Pnot ISBIGENDIAN)string_reverse2 aZ ,;/) # Pack work?!got = pack(format, xK Egot,7 Un]qretrievu-got)[0] 5x, KAdding any u should cause a "too big" error.z Raises((struct.5p, TypeE@2), #, ]Qb'\x01' +  POelse# x is out of range -- verify realizes thatOverflow0, V -),01 8qdef run9u@fromdom import#1# C all interest!`powers)2^s = [0for0 inx!ge.HO + 3T.append(?exp# Add somea; &SiM = 0JNjN}r7val = (val << 8) | randrange(256) values.append(val) (1# V& absorbed from other tests3W0extW[300, 70, sys.maxsize*4]pTry all those, and their negations1+-1 #0m. Note that this[power-of-2=boundaries in Cqa few out of>plu# +-(2**n +- 1).efor basea.:$(0val'-0,6,0Aincr11, 0, 1.2@x = b + 8'Pself.o_one(xSome error casesPclass_AnIntdef __int__(v)'return 42Objects with an 'Udex__' method should beMowed# to pack ategers. TXis assumingu implementIsOint'1Indexable(o:i;,/ue/Ba!._ .ueL)\A]UA# If6aises a typR,,n?tCusedq deprec; warningg1Badjf ` TypeE\2npassertRv5s((x, struct.-),H 1!, \oformat< "apNing"{KsArand_3+42jeError, struct.error),  struct.pack, self.format<NotAnInt())jKassertRaises((TypeE#, vSBadIndex # Check for legitimate values from '__i@M__'.@8obj in (fable(0), 17 :+42I J]27)):?try(N obj-oexceptM5ail("integer code ^ failed on`_ect "hX"withw method") >_bogus-Ib'a'u*'bONone{'a': 1}R[1, 2, 3]=<Z@~, byteorderSiter__Y+s(& =:+J[mt = IntTester ct.run(def test_nN_L(@w# n and N don't existstandard sizesPS(func, *args, **kw f~.@}n as cmP`(_^YIn("bad chazbAmat"aB(cm.7ionJ'nN' ('=', '<>+!'(WP.calc, ; i7?, 0:*un<$b"cSpR p ("PascalQing")'O, input, expected @back[('p', b'abc', b'\x001b'' ('1p', b'abcw\x00', gb''),  =('29)1a:?b'a:3:82ab;;4;3# 5<wcx6<@<B1000?0x'* p\xff' + b'x'*999x'*255)]:ngot = struct.pack(code, input)+self.assertEqual(got, expected,)Z'un\/goZaback) def test_705836()# SF bug . "f" had a severe rounding1@, whqa carryl)# from the low-order discarded bits could propagate into2exponentNield, causzXresult to be wroy a factor of 2.Bpfor base range(1, 33!smaller <- largest representable float less thanUgEdelta = 0.5Qwhile02 - %/ 2.0 !=.%=& K9O #b# Pack,"isPs awa#Psolid of trail 1 &ed(#, 24?ked)[0]This failed at = 2, 4,32, with Oa 1,!;andLp16, resaZively ,X 2big ?>f"`D,u _rK2se([)s`(%, Ey8ase'3# Lfinite IEEE \&le-big = (1 << 24) - 1B math.ldexp(big, 127 - 23=6big(G HH # The same, but tack on a d so it# upS!in9 5 4 Raises(OverflowError, struct.pack, ">f", big) def test_1530559(self): for code, byteorder in iter_integer_formats(7;Wmat =:+L]&p .assertRaises(struct.error, jo, 1.0)F15F;'P'?!5 un\_from`stringR'abcd01234'fmt = '4s4s =ASVF(fmt ls(s[arraydata = cls(K Equal(s.CQ), (b?',)>2, 2AA#4A; Ai {range(60, id|[i:i+4] hY, lenWO + 1~ ,p , "IdpHK >n g R, fmt"## keyword argumentswbuffer=, offset=2),FG 5(b'&Ointo Reykjavik rocks, eow!writable_buf = .('b', b' '*10TL/21M# Test withouts4(o(B, 0,11.toL()[:8]oelf.assertEqual( from_buf, test_string) # Test with offset.s.pack_into(writableL+10PN o8 = 2.tobytes()[:len(F+10]self.assertEqual(Q p[:10] +Go beyond boundaries@mall = array.('b', b' '*10) Raises((ValueError, struct.e7), 34, siE, 0,Q+'s x(2xySbogus (issue 36946b =@?Typ0?h_', sb CNone2defB@_fn(%):` = b'Reykjavik rocks, eow!'/#$fmt = '21sF = lambda *args:3!R(fmt,3out>iKHTRZvP!unPzI'1/ '@0x12345678) def test_bool(self): class ExplodingB#gobject%,Qdef _C,__E raise OSErrorcfor prefix in tuple("<>!=")+('',ifalse = (), []U'', 0Qk0tru%`[1], '', 5, -1, 0xf+9/2 CiFormat =+ '?' * len(!)4spackedFpstruct.-N?, *; un( = ?))e T/+K0, * 8*ed:(/<' j.assertEqual(T:!),_Lb)};T <)yqtlb&@f"*(t HG !F48 = ~{+'?', 19g$),Fcalcsize(J !ifh:_ != 1 P, msg='encoded ; is not one byte: %r'U % y\ , :dexceptWIpassNelse'fail("ExpectedTi(%r, "Q ?[c))" % rc[b'\x01', #7f f 0 Jf0']wv 0('>rSc)[0]vA_count_overflowAhuge" = '{}b'.f;(sys.max&+1AR#s(e %, aH2v?{}HyW//2, ?//212#trailing,,er%@storaarray.1('bc '*100Q"# A lists containing only lspec should resul1an Fxmstruct.error , struct.pack, '12345') self.assertRaises(0Uerror>)un@O, b'ECU_into`oore, 0$__fromO-# Format lists with trailing count spec should result in an J,B, 'ckO, 'x+pFbG!rJ"sts, n! pm 50) # Mixed fUtests14s42', 'spam and eggs(Q1 bl-o x-  z@def !_ST_reinitialization(%): # Issue 9422: there was a memory leak when KaDm instance. This can be used to detectj[Ee0unn^@regrE -L.)4s =1w8('i10.__P__('i9check_sizeof,_str, number_of_codes$@The 9r of 'PyxqObject'`[Qtotal&= support.calcobjg('2n3P%# Wtaken up by'[' dynamic arrayn+nkP3n0P') * (G + 1e(*5), u@python_onlx_x!__z]@for rinteger].5,( #'BHILfdspP', 9*@' * ,, ofd', 2# x'>.check_sizeof('100H', 1) self.check_sizeo%?87s%?20p$0G0c', 0) def test_boundary_error_message(!):+regex = ('pack_into requires a buffer of at least 6 ':bytes for Dbing 1 at offset 56\(actualdHv is 1\)arPwith .assertRaisesR(struct.!, "Q('b',array(1), 5S __negative_ hx_list =i0 r'no space to! 4vsO -2'#ibcp'# it$.F(b"" <1234567C# Wrong bytes length`Wwith dRaises\errorU S5'78Ur# Zero-q/M/Q12")  Eq@nextF, (0x01020304, 5R4 6070809, 105b0c0d0e, 1jBStopPion, O, it3 arbitrary_buffer21memoryview(b*a B- 3 `\_hint[rlh = ope.)Bv>3:?('>I"lh3Yk3elfZ;525!15!05) se+lf.assertEqual(lh(it), 0) def test_module_func(self): $## Sanity check for the global struct.iter_unpack();Oit =" '>IB', bytes(range(1, 11))< Bnext(0x01020304, 546070809, 105Raises(StopIteration, yO, it3  ghalf_floatf Little-endian examples from http://en.wikipedia.org/ /H`precisionjing-point_formatR_bits*__cleanRoundtrip_lis[37(b'\x00\x3c', 1.0), c0', -2!ff\x7b', 65504$ # (max % v }04', 2**-14), # ~= 6.10352 * 10**-5 (min pos nlJ1J2Jt5.96046J8J?subM0M08!7U"'+inf')_f*-*55\x35', 0.333251953125451/3]g!le, f in -FbB3 = Le[::-1]q$ $f,2OT'}}* }E }pif sys.order == 'l'HD. H Oelse&.=5# CNaN handlingO_nanl1\xfc'q!_0\xfe!/ff!_01\x7c 7c 7c formatcode, bits in format_bits__nan_list:  self.assertTrue(math.isnan(struct.unpack('Fc[::-1]LM# Check that xing produces a pattern represent$a quiet NaN# all exponent=s and the msb of fraction should5Ube 1.Sed = 16nanS`Equal(.ed[1] & 0x7e,1 ^-_(Us round-to-even behavior,3qfloat__21ing>E = [-H"(''\x00\x01', 2.0**-25 + 35), # R|s to minimum subnlT 0TIUnderflowMzero (nearest FmodeaT6TU3\xffC14 -!24K@LargJ K5VO65),4x6PSmall#3cB1.0+%111O6&o**(-10S-?!11 HS2SY#7bB6550l9+19qM:8@-U2A'UZUB+ UUbCC-1.0%11D"TTE&TFfFO-655 %] .0forrmatcodew<, f ng_list:  %self.assertEqual(bits, struct.pack(formatcode, f)) <# This overflows, and so raises an error1J_c_float__roundingE)_list = [2k# Values that 1 to infinity.-('>e', 65520.0),/36O1e308-V W-X< VU9W ]Bfor B in  :yR/#(OH  ,ar bDouble5ingdd+RrEb'\x67\xff', 0x1ffdf * 2**-26), # should be 2047, if j-ed 64>32>16, becomes*8^+?, fdgj if __name__ == '__main__'\unittest.P() # s slice objects;!particular the indices method. import itertoolsoperator%syweakref from pickle Xloads, dumps 0sup~ def evaluate__index(arg)1"""Helper functionconvert aargumentan integer$!IATypeP with=@uitamessage on failure.if hasattr,3__'>treturn K.#1)Belse- (#"0ustRs or -P"None@have_P#__"")uY(, lengthReferenc le`a\=Kg 8# Compute stepl4 assV=?BE0= 1~1is aV-!# negativeQAzero$if<< 0=Error("length should not be negative") if step == 0:raise ValueError("slice+3canLqzero") 7# Find lower and upper bounds for startQstop.6/E= -1< 0 else 0"G= length - *`Comput2artg.vis None=.7evaluate_&q_index( qkYiBmax( +,;)*2min-,rP?op Bop =ji5ep hk6 (op0?op oz*opbreturn8 , 5 ep # Class providing an _z__ method. Used}@test'indices. cG0MyIable(object)1defWit__(self, eAelf." =;3dex<5< STest(unit.0CasuZ_constructora.assertRRs(Typ!, , , 1, 2, 3, 4~?rep~ bEqual(%(JB)), VK[Lhash# Verify clearof SF bug #800796%] 6(5)_with ?edP5).__R<__(!= 0 andL_ != 0qrange(*Z GL5m[<],A9 l()g)10), (0, 10, 1MJ!, zO, 2J2J!1,J1JC,-1P9, -1C-J3J38, -J# issue 3004&s#L, -9A /10BE2--1v?0, Bce(None, -10 , -1).indices(10), (9, 03)  self.assertEqual(slice(None*1G-H2H290, 9, 1)/10A/10B T>8 9EE$F%F2-100, 100 i0b %$$dxw~ 0x",  /.uo{20, (  E2)) R glist(range )[::sys.maxsize - 1], [0]C# Check a variety of start, stopep and length values, including#` excee (see issue #14794).;vals = [B12**P-2**3]`53, -7m`1, 7, !1]PS:/ Afor  _args in itertools.product(, repeat=3):l6" =A&(*H#d` sF'c_g#s,|Q&cY), -3NegativeL should raise VUErrorQwith hR)&s(* )-1Zero step}D70, 5xUsing a $orthat can't be interpreted as an!#4gerg^aa TypeK6 ..O-N#0.!5T#2, 1XT ises(TypeErrgor): slice(0, 1.0).indices(5))with self.assertRaises(TypeErrT RE.0) U8# ... but it should be fine to use a custom class that provides index. jEqual(0), V5, 1)@0MyIhsable(0)'M%80, P1QM( Q)M,1@X*5)4def test_setl_'Sout_g(Tptmp = []?X(object*`_]aitem__Mk, i, k)-tmp.append((#ifx = X(x[1:2] = 42>ctmp, [E1, 2), 42)]XapickleAs = (V20, 30fortocol in71,2> = loads(dumps(s,4* Fs, tn#h15), t;2Notid(s), id(t)>cycmyobj(): passzCo = .Aow = weakref.ref(FENoneCsupport.gc_collect3 Is70(w( if __name__ == "__main__"4@unit.() """This is a sample moduledoesn't really- anything all& interesting. It simply haZ1few< s, some of which succeed andAfailJP's im 1anto the numbers re` const!oanotherq@ is 7@runn ofF!se%s. >>> 2+2 40 Cfoo(2"""(54  .B?barB /`_silly6/up<.10docz .SQSetup%2Trugxw_blankpNBif 1= print('a' #'b)a|b1yx_is_one""" >>> qx 1""" def y_is_one():'Q>>> y1__test__ = {'good': J1 A!42B I""",00'babc!9666K d}Esuitimport docLdreturn.DocTestS6` from , ;0supCs # Skip f _tkinter wasn't built. ..=_module('.<') I tk cannot be initializedLrequires('guiB.PruntksDmainrun_unit,(Z*DA.get* s(text=False, packages=['?])) if __name^P= '__2__'12() #T sys 1est_grammar (VALID_UNDERSCORE_LITERALS/IN<) L = [(('0', 0)Uy('1', 1Y9', 917189' () *314', 314TO314 p \t\t 5 &repr(sys.maxsize), 1x', ValueError0 1 a 1\028R""\u0200" ] class IntSub C(intHGpass"*dCases(.1): basic(selfLn.assertEqualk()B(.& 3' # Check that conversion ' float truncates towards zeroi "-3j-kH.9),&!-3'N5N'N"-3"), (O -3 *\N{EM SPACE}-3N @# Different base"10",16), 16] conversion from strings and variou omalies for s, v in L:0ign`"", "+*-"&*eprefix, , \t \t\t 9=Sss = >0+ sq&+ #ivv = v"if;b== "-" is not ValueError@[-\?try9self.assertEqual(int(ss), vv)_excepUpass E)repr(-1-sys.maxsizefAx =  _x+1, ?,IsInstance(x,TR# should returt w[1:]), 6+1)Q V1e100=->SF bug 434186: 0x80W/2 !=E>>1.# Worked by accidentWindows release build, but failed% desRF!all Linux@s& 2x >> 1, x//2CC'1' * 6u7kRaises(TypK,w1u20o123', 0), 83.x.z16), 29aBug 1679: "0x"a valid hex literal0FKO, 165 0r5_o", 8i4i_b", 2i4i## 81334662:A(, base) wrong answer3# Vesentations of 2**32 evaluated to 0# rather than+ inXv@versIG1' , 429496729 R 2002022201221111211', 3)F L', 4B self.$assertEqual(int('32244002423141', 5), 4294967296) ]self.?15501040_4', 6>21130142235=7=%40O', 8<120686574x9<_', 10<19044405w/11<9ba46159*/12;535a798893;2ca5b746v4;1a20dcd8V1WTqa7ffda9uQq704he7gO4f5aff66M3723ai4g', 2Kp281d55i2Iq1fj8b18:H1606k7icGamb994aEphek2mglrCpdnchbnm9Aab28jpd9@a8pfgihW?a76beig>`5qmcpq93=`4q0jto3<uO', 3;Q3aokq3:p2qhxjlir:p2br45qb9:a1z141z :# tests with base 0-his fails on 3.0, but in 2.x the old octal syntax is allowedHr 0o123 ', /83 0o123 ', 0)s, 83) self.assertEqual(int('000', 0)+ Co123-Yx.?291%b14- 0O123 1 0X21d 0B100b54) # without base still %10%n_), 12+0, 1/[q# tests prefix and?!= _16), 0/8)QO2), ?', ?', 3', A&he code has special checks for the first character af7theHS type Raises(ValueError, int, '0b2506!B5"k"!o8/o06!O5"k""xg/x07"X6#m# SF bug 1334662:{(string,-) wrong answers:C proper evaluation of 2**32 + 14^/10 1, 4294967297 102002022201221111213oF 4B32244002423145?15501040@5', 21130142235=7{97) self.assertEqual(int('401', 8), 4294967297) <12068657455', 9<f_', 10<19044405w/11<9ba46159/12;535a7988a3;2ca5b746v4;1a20dcd82v5;/16;qa7ffda9u7:q704he7gO4f5aff67M3723ai4h', 2Kp281d55i2Iq1fj8b18:H1606k7idGamb994aEphek2mgmrCpdnchbnn9Aab28jpd9@a8pfgihW?a76beig>`5qmcpq93=`4q0jto3<u3;Q3aokq3:2qhxjlj', 3:p2br45qc9:a1z141z :Wdef test_underscores(h!): zfor lit in VALID_UNDERSCORE_LITERALS.2if any(ch4;Cw'.eEjJ'_1continuex /Plit, %eval(lit)$5qlit.replace('_', '')SH_in IN,in '.eEjJ'):+ continueself.assertRaises(ValueError, int, lit, 0)7# Additional test cases with b != 0, only for the constructor:K~Equal(int("1_00", 3), 9w,0_100"), 100) # not valid as a_eral!s btGbyte underscor40"r3+4 1_(!hq100_") @support.cpython_1def_small_ints()# Bug #3236: Return . longs from PyLong_FromString^Nw!IsA'10'% -1%/-1% bK&b'Lmno_arg) @keywordE0# T1invokingaP() us 8 arguments.X /|a'100',rf=2), 4Regex(Typ's'x_x=1.2[E h'=1 30@int_M^_limi0"""32ed /1 of)) parameter."""5Do'HD&/37 A-909An old magic"ue"t& 2&=0-(2**234)0RO1# B2 through 36 are E in range(2,37 ;=bad_type """No&t integer types are not valid bases; issue16772.""" with self.assertRaises(TypeError):+2int('0', 5.5)E'10) Fdef test_int__indexable(class MyI!gobject#R__init__C,+ue'+a.value =%J3dexKDbreturnJK@# Check out of range.h1for in 2**100, - Z1, 37rVA43',jy?in- aEqual(J3101K=W2)), = 10>6101\@!36@ + 36**2]non_numeric_input_1# Test possiblL#n-7b the argument x, includingQ# sub es2explicitly doc=ed accepted_= CustomStr(str): passe#pBytes(b' QArray+a /Wfactories = [._,G lambda b:b.decode())- memoryview]:try7Qfrom r import 1 ex! IH @ zJelse5.append(u0('B3)NJf< Sx = f(b'100':0sub(7(x)(Ezx), 100V.if isinstance(x, x", i?m~, 2), 4nGEmsg = "can't convert non-string-VRegex_, msg(Ex_ ~R, 'inliteral'njpA' * 0x: self!.assertEqual(int(memoryview(b'123')[1:3]), 23) Oself;O\x00?( <(A<(4<def test_string_float(!):!Raises(ValueError, int, '1.2') 3TintconversionU# Test __int__(pclass CicMissingMethodsApassq 9TypR#()Dz sw(object*{ StJFoo0E return 42w*]}()), 42 | for base in , @IntOverridesTrunc(? +'Atd,__`)C5-120. ;<OJust4uExceptional3Y1 / 0?Wwith DZeroDivi# cz:presult_H<Integral(G7R'+T~}wRsNonInt 4z -|= )=D!# Check that we avoid infinite recu>.zrb NonIntegral()  class TruncReturnsNonIntegral(base): 3pdef __t9__(self)/r[ [)V?trykOint()Hexcept TypeError as eZ.assertEqual(str(e)," ted non-@"Hh (type /)"/ls fail("Failed to raisewith %s" % (", qresult_ M,)) ="# Regression test for bugs.python.org/issue16060.B~BadInt(v?intN42.0}`| VAR%s(Y ab _#1sub_l 0 My;intsL_7l6 42bTU+ my# =7)D+/, $ G(S), 42>O s, int, 'ss_vF jKrOTruet/2(u)X& < dCIntSi' 0bad& = Warns(Deprecation;ing0n =(ZOn, 1!Is1(n)YU&2(A:  n = int(bad_int) self.assertEqual(n, 1Is(type(n),K%) DU = TruncReturnsBadInt(LWwith pWarns(DeprecationUing):ZJ1goo IntSubclass5F]we5Tdef test_error_message({&check(s, base=None! Raises(ValueE^,3Pmsg="%r, %r)" % v)) as cmE!if@ is !%Fnt(sOelse1 7 )cm.excep.args[0]"invalid literal for?1() =Z %d: %r" %.K(10  C, s)f'\xbd'?123 123 456 'M7'00P"# SF bug 1545497: embedded NULs were not detectedexplicit00', 1000 245', 2! /16BA  @# byte string .b'. # non-UTF-8jXX+bd: # lone surrogate in Unicod c9ud8;Dissue31619A 1_'1_0_&)dO0b10 2_3_4_5_6_72_3', 8), 0o12345670123I08_96FxF/89D.', 32), 1144132807) if __name__ == "__main__": unittest .main() """ Test the API of symtable module.)timport   unittest TEST_CODE = \#"sys glob = 42 class Mine: instance_var = 24def a_method(p1, p2)04`pass $spam(a, b, *var, **kw*uaal barSb`!47 xk3 ' Pinternal(Dnreturn x% (4foo1namespace_"A(): f6Qind_block( , 3for ch in .get_childrenQif ch=Q() ==GH&4ch S(.qCase): Utop =.(, "?", "exec")4 # These correspond to scopes<.$F = f `top, "Q# '!4, ",+ (O# '!4, ",:foo'NRfoo")"_type(selfw.assertEqual A.top2B), "s8 9g8# <function?;$N?Coptimized(HBFalshH6is_6) B 2@has_#() /3Tru` a Onest3?is_00  c pQ\512Lfoo.2 olineno@4O), 0A3e4#11HZM_infS@elf.N q or\1@parameters()), ["aybkw", "var"])  expected = ["a", "binternal kw0varSx"] self.assertEqual(sorted(func.get_locals()),h)>Dglob?2["b/"]F frees(), ("x",)) def test_Rg!):QTrue(spam.lookup("9S").isC/()OFals? declaredH = bx EMineJinstance_e R>? referenced^GPF # @ parametersfor sym in (Fg, "kw"X1symnX ? ssymbol_1lenA.topPidentifi1)),\  :y3qRaises(KeyError, x, "not_here"BnamespaceECU (">Et@4a_methodE@4 6_Q SS,!")pB2 isn!ns" = self!.assertEqual(len(ns_test.get_namespaces()), 2) Cself;Raises(ValueError, D!) >@def a_assigned(L!):^[ATrue.spam.lookup("x").isA)=?bar?5top{?EMine@a_methodDCFalsinternalIB_onnotat`t1 = symtable. (';`f():\nx: int\n', 'Wexec'm t2J!t1-children()[0]G $t21'x'olocal( 4a8;9Kglobn t3O = 1 4I/t34 5 }o_impor+ "ysB)!VYS(), "top"K5nMh67- yx@ 4"class_infoEs$('-',^@file_correctg### Bug tickler: Syntax = > > whether e rd+Lwhile parsing or build rsymbol 24cPchecklk(brokencode, offsetg6tryH"0, "~:iexceptOas ec `$e.", bZ e.lineno, 1. 9]?elsfail("nofor %r" % f "f(x): foo)(", 14) # parse-time  0checkfilename("def f(x): global x", 10) # symtable-build-time C. ("pass", b"spam", "exec") /with self.assertWarns(Deprecationuing), \595Raises(TypeError):+ytearray()(umemoryviewv&Olisth!test_eval(:symbols =@ 42?<:") QosingleS%> U;Sareturn"p if ____ == '__main__'@unit#.() from  import mock $os platformsubproces"%sy @temp-cwarnings ~0sup class PwTTest(G.CCaseD_architectur re.+@}.skip_unless_symlink>D_via& # issue376298# On Windows, the EXE needs to know where pythonXY.dll and *.pyd is at K# so we addMdirectoryM^Apath>PYTHONPATH.tif sys.-r"win32"*b[restore_environ(old }&3os.%v.clear(#eupdateOu(.addCleanup(v, dict(q)@["Path"] = "{};{}".5at(56@.dirE(#u%>), V w|?os.\ sBget( frcmd = [}, '-c','; print( 9)']Cp&.Popen(cmd, stdout=Z.PIPEp.communic`real =J l}02abs/(.TESTFN)  os.symlink(real, 3) Etry: self.assertEqual(get:0), ?@kfinallDos.remove(. adef test_platform(k)~ for aliased in (False, True&*_terse( ,dres = t. (j!, I)]syste L% <Lnode :# 8oreleas; & >versiony & >omachin| & >processor~ (B\setUp9c.save_s = sys.Q(3git$O_git!&]arDowCx< k0ys.| % %ys %dst_sys Q# OldO.input, output/&('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 5(40809)]',U ('CPython', a 1 lkj :'))kb('Ironm 1.0.60816 on .NET 2.0.50727.42;z> N ! (Q1005.1977)&0truncation, date, tJL t ?GCC~6|{gzd) \n[GCC]',  ('CPython', '2.4.3 truncatidGCC')), A(:& (0, ) \n[GCC]'- srq]pJ)):b$# branch and revision are not "parsed", but fetched@ from sys._git. Ignore them*(name, verc,x,udSildno date, compiler) \N = platform._sys_^y(input)2self.assertEqual(P '%'Q, outmP# Tests for p_implement4(),( #-@Pbuildm45().Us = {"2.6.1 (r261:67515, Dec 6 2008, 15:26:00@ 4.01Apple Computer, Inc. 5370)]" Ptags/tiwA'), Tsave_  l2", ^ ^ <''4O'GCCA rBIron! 2.0 (2.0) on .NET .50727.3053", None, "cli"_] !(" "};), 1g o0920.0_1433)-16.1 , ~"Y7.4 (r2.7.0.4AMonoP3031932-bit).?7.459k:6107, Mar 29, 13:02:18Java HotSpot(TM) Client VM (\"&\" ('Jython', 'trunk 6107'), "java1.5.0_16") :("Jython", "25 T T-",5" (w: |Mar 26 2009), B(i2 (63378, = , 18:03:29)\n[PyPy 1.0.0] ('{ N~self.save_platformN2 W WQ", (' j/')"v} for (version_tag, scm, sys, info in \8)?s.items()Csys."3 = k L ify is NoneBhif hasattr(sys, "_git"k)0del.$ f?els\+ = 1 ?notHL9 UassertEqual(5!.p_implementation():[0]7HmA1Aebranch@2@Xrevis3Bdbuild(4?compilerB25])def test_system_alias(SUeres =  +  #(release _ _uname $..rTrue(any(res)"res[0], res.- 1-Onode+ 2+. 3.. 4.omachin 5.processornP@unit.skipUnlessy.startswith('win"windows only]wl_win32_ARCHITEW6432# Issue 7860: make sure we get architect from the correct variableB# on 64 bit W: if PROCESSORp existslshould bK using it, per # httFp://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx Rtry: with support.EnvironmentVarGuard() as e ;Aif 'PROCESSOR_ARCHITEW6432' in8<4del![E]62CTURE'] = 'foo': platform._uname_cache = None-system, node, release, version, machine, poUor = ba.()Velf.assertEqual(G1e?barkfinallMZdef test_java_ver(self)8res'ztif sys.lP == '''EuXTrue(all(res)) _win32( B?mac@&>-if.kDarwin# We're on a MacOSXcheck thatc# the right 0 inWation is returned8fd = os.popen('swvs', 'r'b@real`for lnZ*fd:if ln.starts('ProductV':'1sArip().split()[-1:[breakk.close>eFalse(p!is~ sult_list = res[0]+'.-Wexpec,;.len_diff = leni1) -P # On Snow Leopard, 0 re=s 10.6.0/ |>> 0x.extend(['0'] * TJ%re6', O##Q1] claims to contain5# (dev_stage#n_   l# Thatno longer availablqself.assertEqual(res[1], ('', W)) if sys.byteorder == 'little':*5self.assertIn_2_@i386cx86_64')):OelseL BEquaO'PowerPC') @unittest.skipUnless(platformdarwin', "OSX only 4"1def_mac_ver_with_fork()# Issue7895: b.7() crashes when using G Qout exec# Q This checks that the fixDi~v works.> pid = os.u(1if 6= 0u# childAoinfo = &os._exit(05# parent<cpid, stswaitpid(0U <?pid( Tsts, Ldist warnings.catch_(t.filter()'ignore', r'\(\) and linux_ribution'8P'func s are deprecated .*gPendingD'BionW F re(C1lib% Gimport os ifpath.isdirbutable\/% /Rexist0{+'.exe'# Cygwin horrorNnl! =M2 + O1. ?6 2< @parse_release_fileJUfor input, output in d# Examples of N N contents('SuSE Lo 9.3 (x86-64)'09.3":'))4@('SUKINUX 10.1 (XLE!#MCi586K!IFedora Core@5 (B2auxS%5"TsRed Hat8h8.0 (PsycheV 'S08.0$X9 (ShrikV9T"TEnterprise 4 (Nahant)', ('Red Hat Enterprise Linux', '4Nahant')), ('CentOS release -8NNone9VRocks8.2.1 (Cydonia)'"E 1# )), # If there's nothing.)):self.assertEqual(platform._parse__file(input), out  Kdef test_popen(Remswindows = (sys.a == "win32")Ii5if 2 command = '"{}" -c "print(\'Hello\')"'.!atjexecutable)`OelseXP"'{}'X'X"XO")'"X with warnings.catch_(.simplefilter("ignore", DeprecationWR@lG.v) as stdout8h&# = .read().strip(b.Fo.close 9^", 4@dataUplop'import sys; P=JSstdin; exit(len( 6))"kc%'"3 = 0T, 'w'5.in45in.writeb-5ret(6PIsNot,N(retif os.name)N'nt'vurncode = ret79ret;] >> 8@ "7&, p lO0_di^ bu _ereturn '"'I3error_condiy BRaises(TypeE6,Bect., 1, 2, 3=[ja()], [K)&M/"not a number" OValu&Q#-1?B# Issue #12367: http://www.freebsd.org/cgi/query-pr.cgi?pr=kern/155606 @unitt!est.skipIf(sys.platform.startswith('freebsd'), 'A because of a FreeBSD bug: kern/155606')Cdef test_errno(self):`v open(__file__, 'rb') as fp)-fd = fp.)2no(`fp.close:tryE,rselect.([fd], [0Wexcept OSError?errRf.assertEqual(err.!, k.EBADF\?lseKbfail("}ion not raised") >Xreturned_list_identityi# See issue #8329E r, w, x = 1`IsNot(@ x{  cm'for i in 0 1 2 3 4 5 6 7 8 9; do echoring...; sleep 15ne'p = os.p~0cmdyh@toutk(0, 1, 2, 4, 8, 16) + (None,)*10if support.verboprint('timed@=', m)`rfd, wxp=Iif (A`) == (mcontinue$IJline = p.read Y((,Prepr(J)%"!if! (oG'EOFYbreak#<-'Unexpected  values from{j():', i1# I16230: Crash onJ resized 00F_mutatedfaa = []2jlass FVKdel a[-1IM__stdout__@a[:]F()] * 10rj@], a"),Aa[:5)@)) tearDownModule( reap_children() if __name__A"__main__"@unit.() # Tests the attempautomatic coerc!of$C locale to a UTF-8@ imE c1$os (sy config import shutil from collections import namedtuple test.sup 8.script_helperG ( run_python_until_end,Linterpreter_requires_environment, ) # Set the list of ways we expect to be able to ask for12"C" locale EXPECTED_C_LOCALE_EQUIVALENTS = ["C", "invalid.ascii"]~Bour na(a default encoding used in~C|#0filesystem31and/standard streamsSTREAM_ENCODING = ",/FS(N 5when none is specifiedr_COERCION_IN_DEFAULTap = TrueC Apply some platform dependent overrides if sys.$.startswith("linux"):9)f ~is_android w2# A s* usQUTF-80alltQfacesdD6outf-8"4 0HelseL distros typically alias&SPOSIXY directly!C##. TODO: Once https://bugs..org/issue30672addressed, we'll beO  wcheck this case uncondi.8R0.ap!("_") el %aiP# AIXs iso8859-1, other *nixs5a ASCIIc4 0 == "darwin" F# FS2is on macOS seo8cygoC'!C.{r"# @ Work out a robust dynamicTthat doesn't rely onI:!CPc's own` handlmachinery4bm AFalsnQNote Dabov+s are still wrong( s, such as: # * Windows PYTHONLEGACYWINDOWSFS!et65AnybvAthanuses latinB1re ! iUa simplefw * G where the dnefault locale is something other than "C" # # Options for dealing with this: # * Don't set the PY_COERCE_C_LOCALE preprocessoE@finiU on # such platforms (e.g. it isXon Windows) r@Fix ltest expectaRs to matce actual[ behaviour # In ordBo ge@warnwmessageOSup ask1ed,~candidate #Khere must m ar^nrin Python/pylifecycle.c _C_UTF8_7S = ("C.UTF-8", "C.utf )Tt's no reliable cross-R way of checkalias # lists, soDonly2@know1PwhichCSthese:s will work #G`to tryEm"hB.set (). We diat in a subEn setUpModule() below to avoid alterYT qrunner. IfEevanm[ attributeist, and we're not oA@ # wf3 wePlways cerwe alsojGRt # `.nl_langinfo(CODESET)`F s,c if]RfailsfinterpretertCskip coercionthat particular t}! ___ = bool( 4ys. in ("darwinplinux")200hasO7, "a' |") ) def _set_F_in_[q_name):ucmd_fmt = "impors; print2|X.LC_CTYPE, '{}'))"N?if q"# V"reqcvalid ,`to be 1pedkHc+= "; sys; sys.exit(Osccmd = V.Fa4zresult, py_1Qrun_p_until_end("-c",L, PYTHONCCC='')MRturn T.rc == 0 _fieldspfsencod`stdin_u stdout 2err  lc_ctype sall" _EC0Det0 = dtuple("3", ) class "(QP# XXX (ncoghlan): UsAJSON[child state rer0mayless fragileCHILD_PROCESS_SCRIPT;".join([& sys, os",getfilesystemU?()).m.' + ':' + sys.stdin.errors)", "print(sys.stdout.encoding + ':' + @ ?err@@os.environ.get('LANG', 'not set') 4C_CTYPE8 ?ALL61]) *@classmethoddef get_expected_details(cls, coercionT, fs_Y, streamenv_vars):^"""Returns e child process s for a given d5"""J_o, =xv + ":{}*# stdin and out should use surrogateescape either beca5thes# triggered, o- C locale waIC_info = 2*[.format("5")]<4erraalwaysbackslashreplacp.append(r <5"))s_lang = "C", "").lower(@%if36 bc_ctype = CLI_COERCION_TARGETZOelseJ K >all_C_ALLD $nvOEang,#_l 5all}r)P dict(m*0, *UQ)._as2)kstatic_handle_outputiations(dataAdjust the /B to @P plat specific idiosyncrasiesie* Some1s report ASCII as ANSI_X3.4-196881US-D2UTF-8 instead of utf-i]0 = .S:(b"", b"ascii"293 @2ataJE rieves fsXPandar$Zrom a(Lderr_line-,3: EDqeager de?stderr_lines: 'result of calling splitlines() on the stderr output The child is run in isolated mode if@ current interpreter supportsNUthat.5""" , py_cmd =l_python_until_end(/"-X", "utf8=0 -c", cls.CHILD_PROCESS_SCRIPT,<**env_var)!rif not .rc == 0:|Rfail(?# All subprocessTs;this test case should be pure ASCIIhadjusted_! =s_handleiations(6outqstdout_; = S.decode("ascii")._encoding_details = dict(cls(*gQ)._as)5err=errrstrip(breturn ,gc # Doshared library warn@emit atwtime LEGACY_LOCALE_WARNING = !"P. initialized with LC_CTYPE=C (a locale@defa "]), which may cause Uni compatibility problems. UsC.UTF-8,Q C.Q, or  (if available) as alternative-e$leIsecommended." )_4CLIcoerciond CLI_COERCIONcM_FMTgPdetecW:c ked to {} (set anotherfor PYTHONu"EC =0:0dis Ybehavior) AVAILABLE_TARGETS = None P7 def setUpModule()n}global osw.ifY#k already d"| R = []wa# Find3ctargets)$e SasystemZBfor 7_in _C_UTF8_Ssif _set+F_in_(Gq @.app 5I4# C bis exp0to zWfirstd. =[0] CLI_COERCION_WARNING = CLI_COE_FMT.format( "TARGET) class _LocaleHandlingTestCase(unittest.): # Base =to check expected lN# hO behaviour >Qdef _3_child_encoding_details(self,,n env_vars05_fsy<ostream@'warningcoercion_dA"""C]the C}@for  given process environmentJParametersu3:sys.getfilesystem() resultN ERA standard 0sMR: stderr output to (if any)?5""" C = EDpI,_lines =Sw '(  ="W|.assertEqual(d=#if3ed_s is None}'E= [] |,eConfiguration/s(s # &Ylicit external cJA viawq@>amethod`setUpCC(clsr# This relies on *Module() ` ng been run, so it can't be`G%ed@pskipUnldecorator9if not AVAILABLE_CSeraise R@Skip-("No C-with-UTF-8available")q_V_target_S_d'")::1Exp ly!rting a Ctpshould Fsame& a`#sSuwhen im\} ng_Jthatc5maxDiff = = "utf-8'stream_encoding = "utf-8" base_var_dict = {!"LANG": "",C_CTYPE?ALLPYTHONCOERCECLOCALA}gpfor envR in (D, "L{%):-1locale_to_set7AVAILABLE_TARGETS48# XXX (ncoghlan): =UTF-8 doesn't appear to work as{Gexpected, so skip that combination ?nowMSee https://bugs.python.org/issue30672AdiscussionH%ifD2== CZ and )"continue7with self.subTest(= 83configured_= @ }.copy() 84[:] = 6_check_child_encoding_details(Y -5_fs^M/ostreamQ8warnings=None&coercion_ =False) @test.support.c_only @unitkipUnless(sys@R.get_ 5R("PY_k3_C_m)#"C  disabled at build time") class LjC2s(_HandlingCCase #  implicit re"ur `of the ironment during CLI startupDdef 3_(vh (o3e_cq_Dk .?Tru}p**extras@"""CohSvarious s}CParameters1U$: @ sysfilesystem?() resultw I8standard 4e_c_locale: setting to use for PYTHONCOERCECLOCALE None: don't set the variable at all2Cstr:'1lue5!inchild's environment<expected_warnings:   lines on stderr@tra_vars: additionalosin subprocessN5""" self.maxDiff =   if not AVAILABLE_TARGETS:"N # Locale coercion is disEQd whe `re areiany target l9Ofs_encod= EXPECTED_C__FS_ENCODINGostream< oSTREAM@_y= Falsef%if "C# = [LEGACYWARNING]n@base_dict = {W"LANG": "",C_CTYPE?ALL '}g .update(ex))"ifBe_c_ CX 6 U/["<] =P.# Check behaviourddefaul]Qwith subTest()Z=True\=5)#if_ION_IN_DEFAULT  2n> R3_5ion@? 7Oelse <s4# On Android CLI&cprinte40allX u#2 are undefined or empty. WhenHthis code pathArun $['LC_ALL'] == 'C', HO.xif (test.support.is_a9and,a?= [H]? _cR_H_details(( T <  @  _expected_warnings, *_coercionL%) D$# Check behaviour for explicitly configured locales<*_to_set in EXPECTED_C_LOCALE_EQUIVALENTS:<@penv_var:("LANG", "LC_CTYPE")15with self.subTest(C= nominal_=@PYTHONCOERCEC=f3e_cUvar_dict = basey.copy() 04[3] =6on successful ?ion=a _c _child_encoding_details(0 %fsUD&ostreamH/f/W mdef test_<@_not@(w9# This shoulde to the first available target by default\.p("utf-8} S=None9Nzero*Any* string other than "0" isj@sidejQ"set"gpurposy# and henceQresul2`ion bes en*d@settPin ("1@true\falseI-sL0setOI=* s runtime :Qclegacy(D D"" a=[CLI_wION_WARNING])  KCThe rU:disVJ CALE_FS_ENCODING, EXPECTED_C_LOCALE_STREAM_ENCOIcoerce_c_locale="0";ion_expected=False)2# Setting LC_ALL=C shouldn't make any difference to the behaviourJself._check_( /FS ER_'/"C/;def test_Y_set_to_C(P!):$o q render t ineffectiveGVONoneN=1~# And result in a warn;about a lack of mpatibility"_hings=[LEGACYBWARNING]   xSmain(i.support.run_unit(LConfigurationTests"4erc>uNceap_children() if __name__ == "__2__" =() from coll`ons ims deque  class basedP__init__qC, el .tel = elBdmyset(H-IcontainsMureturn TU?seqSugetitemRnqQ[RD][n]C(.3aseDRpcommon_ s!ea = base_set(13) b = myset(1xc = seqself.assertIn(1, b/ No0;c; Raises(TypeError, lambda: 1 in aT5 3not9 # test charestringIn('c', 'abc'z &'d%H"Dfe@@None=1def _builtin_sequence_types(!):+# a collection o=Ss on A%A A:a = range(10Pfor iadhw[/i,R/16 a gtuple(!aclass Deviant1"""Behaves st8ly when compared 1RThis Q is designed to make sure that the contains codeGRworksh)list is modified duEYheck.>9""" aL@ = G(F(15)a__eq__lw, others%"ifj == 12. 7v.remove(12o&*3*4*return 0b5(),.#)6 m_nonreflexive#ment and equalitys involving ele%s&ar # necessarilyE/themselves-XeMyNonRgobject*0FFalsBChash b$=&28 values = float('nan'), 1, +, constructorF!, & , dict.fromkeys, set, frozen d2IMs@er =(YR*erO'w0In(1,[/ Rself.assertTrue(container == constructor(values)) self.assertTru>K!) 5 def test_block_fallback(E!):#[!# Ding # with __s__ = None5class ByCs(objectW[F{{, other+/return Falsj( =h _"""Is not af('zRThis Uis a perfectly good iterable (asWUed byBlist(bc)), as wellqinherit`=romZ Crer, but prevents the usualB"toqtion in/_ protocol. ThatBis, normally, 0<bc would" F1 toRequivalenDof any(x==0 for xF)here it's{yed from do19so.9"""a!__] RwhileUZyield  bc {`(Cc! >I Raises(TypeError, lambda:) if __name= '__main__'@unit.() import  @ doc$ DocTestSuite!0supCJtweakrefgc # Modules under8 t_thread4ing ing_local JWeakp`pass qtarget(1 , W1 = @(.| 7.append(qref.ref %))PBaseL':Qx^\_refs "20y 5 7100TH3, nZ0 = .+(xQ = [] 4ihrange(OEt = !.T(=}, args=yHg.startGjoinRdel tg gc.collec9%Equal(len)Al# XXX kR keepa3!oflast stoppedf alive@deadhEQ "inist if weak() is None] self.assertIn(len(deadlist), (n-1, n)) 0-# Assignment to the same thread local frees it sometimes (!)E%.othervar ="gc.collect(7 = [weak for !in1 if (%), def test_derived(>%):# Issue 3088:eua s switch insid6e __init__G4of 2Aing.0 uq class,zCper-ydictionaryHis created but not correctly set onHwobject.:The first member.may be bogus-pimport A L %!._,P' $W.sleep(0.01Q# =eV;f(iL/e.x = i`# Simply check thatqvariabl 4 >?cEqual(g7, iwith sup(r.start_"s(TA(target=f, args=(i,) i in range(10)Bpass!_cycle_dealloc # http://bugs.python.org/iE69900s#ed = False`Ce1 =I2HEven /e2?+f(1non t-# 1) Involveha!a 0 *)aH.append( [0].foo = 'bar'>q# 2) GC. (triggersmodule.c::i_clear# before ?delXe1.seP2.wai b4) NewIs shouldPFemptCp = all(rhasattr_, 'foo') svt _th-e1?# 3"reoriginal's address. C}5ing `# them3 overwriteJstate and avoidH&buVange(10)]  e2.set()  t.join() self.assertTrue(p d!def test_arguments(0%):?# Issue 1522237class MyLocal50._l <b__init__', *args, **kw 15e6a=1Raises(TypeError, ), J/rt7 16_7Aone_ cX_failed = "No e message set or cleared."\wobj = ce1 = threading.Even/e2Q7f1(fobj.x = 'foo',y:bar@del 8y0+e1E`e2.wai,26tryp:Qfoo =kx?except Attribut?# This is expected -- we haven't}@in t,_Y yet!rv P" # )ed,Nelse >('Incorrectly got value %r from Q %r\n' %_ (foo, c)"sys.stderr.write.,t]Tg(target=fapt1.star8$e1t N2-t2N$t2Jedone; just let t1 know it can exit, and x for it.A,1n$ JFals3EA ?2ingemqZ57OA_sub X S#W R"""ToOTthat VPes be properly."" tddict_aW, cls'ls\5`Equal(#!__`_, {'x': 5}XBwith 2gTU = {}N!%  l )elf._local)  def test_dict_attribute_subclass(self):,0x LocalS#0._l*.Q"""To`d that Ves behave properly."""et/._(y!) 2cycle_collectionXBpassHqx = X()X.2 =  .8x6wr = weakref.ref(xRFdel *3gc.UkassertIsNone(wr()) ~aThread Test(unit-.Case, Base!Q = _tAV"PyX5ing:[%2ingn?5 Smain(suite = S!@.add@(Doc!'k"')e 4[Bmake:7 'V_orig_(`setUp( 4M,EtearDownH %Y ,3{=$, =  ;support.run_() if __name__ == '__<2__'BP() imG datetimeSQ from.r 2cpython_only try[capi except IgRError)"0 = ydstructDionsitertools # The cases here cover several paths through the fun calling # code. Ny depend on-METH_XXX flagis used toine a C #X , which can't be verified LP7Z. Ifb@declG orQO changes,.ss may notRright.#CF^Calls"):st_varargs0XRaises(Type, {}.__contains__ T1T 7/(0929o, 0, 1Z\0_ext^wntains__(*()3) except TypeError:!Qpass  def test_varargs1_ext(self)3{}.__contains__(*(0,))A2A6tryNR_1, 2)HJelse^raise RuntimL1_kw.assertRG%s(D+, _, x=2\0>, ya0old<0_0{}.keys(212 O?, 0Q2Q$?, 1T0B-*(y9{B1'q Z0IGT!R2"?x=2 1X [].count$-1_2(X/1_Q!,  A3/1_ +M((,R/1_1 MXgs1_0_kw(selSf): self.assertRaises(TypeError, [].count, x=2) 5def test_oldargs1_1_kw(HW/{}[ 2['ax=2, y @cpython_only class CFunctionCallsMessages(unit.TestCase):0var02msg = r"__contains__\(\) takes exactly one argument \(0 given\)"  P XRegexmsg, {}.k 2325o, 0, 13^from_bytesSat most 2 posi%al\_s \(3&Fint.t, b'a', 'little', False no keyword-_]eb3Gbool C2T8 4o^index $1[].Y 5 hasattr>X 6 ?getBX 7 Onext->U 8 Opack(Regex(TypeEr-ror, msg, struct.pack, x=2) def test_varargs9_kw(self): $msg = r"^=_into\(\) takes no keyword arguments$"<K .assertRaisesRegex(TypeEra /10 _index>collections.deque().j 1 M>S O("") 2 staticmethod@], func=id/13 _classD\4 wproductGat most 1R \(2 given\)]itertools., 0, repeat=1, foo//15 aImport2_s \(3F@namebpath=23p6 ?minp1minadefaul?key7 Oprin45F0sep1endile=3, flush=450old?0_1Gkeys&noD \(10{}.[?, 02# sertRaisesRe6gex(TypeError, msg, {}.keys, 0, 1) def test_oldargs0_1_kw(self):"&msg = r"?\(\) takes no keyword arguments"5D.assertRaisesRe ?x=22h?, y@1_0(,Wcount-exactly one. \(0 given\)91[].d5?1_2,2._, 1, ?1_0?l23/, m1 L/{}  L4x=2  6pyfunc(arg1,2return [7] 2z_noarg(."" class PythonC :Qramethodr x|? 94@u_C(cls0D#""er@staticKLI!6PYTHON_INSTANCE =' () IGNORE_RESULT = object1@cpTS_onlyfFastCallTests(unit .CCase #  calls with positionalCALLS_POSARGS = (0# (/s: tuple, result' -cq2h+(1, (d0, [2]),t##! N5outONc, (), Q sE.#Q5?"),7 89:instance methods  (PYTHON_INSTANCE.method, (1, 2), [C]), 1 2_noarg, (), " "5 eclass_m5; jstatic<= # C function: METH_NOARGS"(globalsIGNORE_RESULT), 'IO (i2"hello",), G:VAR1dirH#" |wKEYWORDmin, (5, 9), 5 FASTCALLBdivm000, 33), (30, 10)MRtype  }WGCLASint.from_byte b'\x01\x00', 'little'), 1rbpo-30524: Test that calling a C  with no argument# doesn't crash (ignore the result)datetime. ?nowh^)n#s@posial and keywords@S_KWLA = (W0# (,0s: tuple, kwargs: dict,5ePython=2E.u+2(py` (1{'arg2': 2}>-1), +1': 1, 6instanceVk=; mrax, ([];default': 9}W puorder':g}g(F:Js': P def check_XT(self, expected): %if: ish&ereturn9Z.assertEqual(rektest_fast_PyObject_FastCall(}1for:ueA in 0POS %0sub=d=q@ = _capi.pyofastcall(func, akrgs) self.check_result(, expected) 5if not args:a#=NULL, n(/=0)m = _testcapi.pyobject_fall(func, Nonen@def h[`_dict(@)# Test _PyOFastCallD-Bfor 2@ in T.CALLS_POSARGSaBwith%0subp=O=T5@# kw] TPiZ/{}3.{}"",m qqO"9r4"M :B/KWA%bP{U(keywordsK1q_names'H(.()M8"kwS ZDbject_fastcallkeywords(func, None?) self.check_result(, expected) 9# kwnames=(ZH = _testcapi.pyobject_fa/()QBfor args, kwA in QCALLS_KWARGS:Bwith$qsubTestS=V=S[=)Dr( = tuple()_.keysU1 = +3_value5m ar ` if __B__ == "__main__"@unit.P() # Hing the line trace facility. from 5 import sup T4sys tdifflib"gcMTtoolsREwrap5asyncio classrcontextB"""C manager that* s its enter and exit."""K de pinit__(R, output, ..# =&DC2" =:`}aRq.append.HAx*exc_infoK -);K @Aehronous MaNaOZ V# H].O Piter(Cablevert an 0 to6}5tor*x2blew(yield x # A very basic example. If this fails, we'reMdeep trouble. S:(return 1 .events = [(0, 'call'),P(1, '7Y0')]`Many oeRs below arxicky becausey involve p`statem2. #eFQlicitRrol fUkound a>@ (inexcept # clqsor else) under wXconditions do you set a0number # following that clause? # The entire "while 0:" statement is optimized away. No code # exists for it, so the line numbers skip directly from "del x" # to "x = 1". def arigo_example(): x = 1 8  Apass .( aJ.events = [(0, 'call'),0= (1, 'line% 2%5%return')]check thatM!s consisting of just one instruction get traced:LAone_ _M 3 14 5/ (6? (37&8def no_pop_tops():1# 0"# [a in range(2<1# 28-Cif aOE # 3\5# 4Jelse85876 }z/(6i44i2r&Pblock(y ^Rnot y1blaC ,E? ($%  ed$#d" -L#!# #G:  (-Mp (- u!] Uraise` ExcepE#Qtest_6'tr 1s()e;Bv as exc7PT1s)&_),  (-2, 'line'),  #exception( _retur%oL34"] def _settrace_and_(afunc):Dsys.(_getframe().f_back.f_E1 = MpGo  / E.events = [(1, '/')Gaise:(ra RuntimeError$ 2tryG  1: kv as excGLpass5L4(&(&*# implicit * example # This test is interesting because of the else: d# partcode. The generate for:0trui4if contains a jumpZt/i branch.XQmpileOnaFs an"None" # Ianally,W#coDavisits statement # and stores $q numbern;next instruc V? .i_()Qa = 5b if a == b1a+1):+ ^0, 'calluK  ' 'N6 'f # Tight loop with while(1) (SF #765624)t21 @item,range(0, 3) ~Qi = 0n& 1L[i]; i+=a Index6  ? (  (3, 'line'), /(4)5)exception67)return')] def tighterloop_example():items = range(1, 4)2try!Qi = 0while 1: @1[i] IndexErrorCopass `.event[(0, 'call61 2)?)CU) generator_func jyield TrueQo"continued"gfinall""i # any() will leave the 0 before its endl1x =6%!) ##Ffollowing s were not traceMfor x inl0vy = x h(/ (0 (-t? (-)? (-+-( -? (-T+1] +'[(7 (o#')] * 10>Ky) class Tem__init__(self,_v_mT=NonehopcodeA.@, =Tts s elf.trace_opcode_events = # s7*1[] def _reconfigure_frame(-!, !):)F0if }5lin{is not None/3C2.f_3Fh j5 l/!, (W, arg-)'As.append((#0.f_#no`)4greturn^ WithGenexp7(o for o in [1]4 class TTestCase(unittest."): # Disable gc collection whening, otherwise ther# deallocators may be1ed as well.*BsetUC using_gc = gc.isen&d(Bgc.d,addCleanup(sys.setS , g2())tearDownb M2gc.(K@staticmethodBmakeq'r(\"""Helper to 3 w A sub es Drs differently"""frdcompar , s_offsets, expected? = [(l ->)`(l, e)-]"ifLs !=d QUfail(="VA didSmatchNan:\n" +8\n".join(8Plib.n r([str(xx -],KK(])brun_and_Dfunco2r = @(1 "^ (*y(>1.___.co_first9/no n #/ , .Wr,O2PM YE h6 self.compare_events(func.__code__.co_firstlineno, rtracer.H!, I !) 9def test_set_and_retrieve_none(self):*fqsys.setVe(None)passert "g"P) is 'l lfn(*argsBpassSs&fn6try*%fnkfinall9 c >01_basic@P.run_d(#_02_arigo: #s_exampluB3_one_instrF '_< 4_no_pop_blocksK + J5J?topH) Fo6_call " 8n7_rais6elf|( 8 ?urn $2(2 9W V1 U10_iret (%A11_tightloop ('J2J/erL)N13_genex $VratorH# issue1265: if the  tion contains a IUY# and:d;fnotherA@that`not cotely exhausted,stopped.?aWorse:$'' clause was WXinvok7Ar = Rmake_(A .QWithGw-cI` K2VP14_onLr_ify+s(tif True: x=False el x=" % 0l( onlineWrs, [(0, 'call') (1, 'line3 return')]) l def test_15_loops(self):*# issue1750076: "while" expression is skipped by debuggerBcfor_example(]afor x in range(2#EpassO.run_and_compare(/m 7Q#2Q4!N @uB0# W should be traced on every  .Yx = 2mf x > 0ex -= 10NB44;N I6_blank_ Onamespace = {}G`exec("Df():\n" + "P* 256 |5", D)@5_["f"]/57V2 7_none_f_ZIZ 20041: fix TypeError when 9aet to None.0Opcodes2oL events enable!d""" def compare_events(self, line_offset, , expected+!):DHskip_opcodH = [e for e inC if e[1] != '/%']Erif len(nV) > 1aeelf.assertLess(-y(),F,^B umsg="No received by the tracer")Msuper().< 6B@staticmethoddRmake_z(kreturn T( z=True) class Raising0FuncTestCase(unittest.e|QsetUp :.addCleanup(sys.set , g2())L Ls, frameQW, arg_B"""Aj function that raises an excepin response to a6specificJM.A == _0OnE q ValueError # just so2ingisn't Runtim)KelseTz)f% 7Theo;f!'sEcase`we're qing, so*('T']l fires90EB Ux = 0|uy = 1/x1@run_B_fory'E .0est*at.d5Cgive5 ishandled OK/9:tryizAange4getrecursionlimit() + 1,Tb.3% w.f(2 <6pasoRail("a#no'd!C 7 L/ counter TSeset"j # &of2s4each kind of.est_callv'-'gAA- AC/ Eiion(self):  self.run_test_for_event('exception') ,Adef %trash_stack(?!): $'f(for i in range(5#print(i) # line tracing will raise an at this-Gg(frame, why, extraqif (why == 'mU' andHF0.f_" no-f.__code__.co_first;+ 2dBRuntimeError("i am cAYing")vreturn gpsys.set 6e(g.6trytk&f(% x -Q# the is really thSdoesn't segfault=import gcgc.collect:lse=.r.fail("ion not propagated") o*_argumentswYx = 0is shouldV )x.no_such_attr_'[, arg_4G @typej,0e =Vv)=assertIsInstance(4, E 8WPexist^ = bgb8 a(a - Attributis expecteEpass0fin I X# 'Jump's: assign ;to within a@func # movesDPexecuQ posi - it's how debuggers imple0 a  # command (aka. "Set next stat+"). class3bTracer"""Definesjumps from one place to another."""e__init__U$, , FBFrom ATo, =5,Pdecorg=False<% =aNI&v% =!#To*To" = L]0= N5if a else  Id=!= GB,K/ #"ifgF<2 l#G!.fu 1 ofwor whenN'function' is decorated and the d or may be written using ## multiple physical lines when it is too long. Use^Qfirst)Jtrace event in 'function' to fi;7 of%.Jif (self.+@LineANoneframe.f_code == + 5andE@== '9'):"<g$= ]-eno - 10ur H ZD}+jumpFrom#f pwhile f Fnot $ !  ?Uy.f_backX*ifU;# Cope with non-integerTo (because of^{P# no__to_non_As below).>try ZY-Toexcept TypeErrordSde= Truetbreturn. # This verifies^}-numbers-must-beas rule. defBs(outputA 7.append(2)BValuV as e 5''str(e))at you can't set f_no via _get or similar # trickeryeAout_3_W(previous_]e= sys.m,() 0./= 2;2he `ion we wanted; make surPezv messag/# talks about  s!Aif ' ' 2in &Brais[7els# Something's wrong -PexpecT asLd` AsserH0("T-`-less 2q failedail") class JumpTestCase(un4st.QsetUp%waddCleanup(1set, g"()64ys.&(A!) grcompareu$, , received%if5 !=,  A( "O@s do^match:\n" + "Expected: " + repr(expected) + "\n" + "Received: " + repr(r1)) 7def run_test(self, func, jumpFrom DTo, y, error=None,E event='line', decorated=False):1tracer = JumpT ({TM)Fqsys.setM(!r.#output = []7"if@ is (7GJelse'Pwith 4.assertRaisesRegex(*$X\ w`compare__",  _asyncaio.runjm4i<  B"""Dor that creates a `1makmS!from one place to another in the following code.95""" 3!or?b@wraps6: 5 H- \@ =,LRV=True[@areturnI`Fn Shronousk@## T!irst set of '' tests are for t#hings that are allowed: @jump_test(1, 3, [3])@def _" simple_forwards(output):+I.append(1D2-3)2, 1, [12 Oback.3, 5, [2, 5|out_of_blockfor i in20 8j8[3]: # Also s ing over a 9 4y5y6ry5, 6, 7 !&?[1]% 37%2%15^ B6 7BRasync0:"(4BE6" [HHR ,D LPiter('2]= ^!FJxB5, 2J4 6Z  2/ P mP s1to_codeless_line`# Jump2to this A should skip e next one.>to_same M f# Testwithin a finally(R, and:B4, 99 in_nested_V?try C. d \6) finally: output.append(8)! 19) !@jump_test(6, 7, [2, 7], (ZeroDivisionError, '')T@def 4_>in_nested_f2_2(n)+tr"2Y11/0ereturnh^( Q6Q 7 8"11/11-3~ K I}6&10e1 .123, 4, [1, 4]8 finite_while_loopi gH5_ TrueQ 31 J4B2, 33 forwards_out_of_with_block tracecontext#7, 1_ R 3Rasync(" l $ "  B03, A1, 2 /-2Oback H2  G  % ; 2, 5, [5 W5tryO   .45/1  btry:  output.append(3) finally: .15) @jump_test(2, 6, [6]I@def _"forwards_out_of_try_except_block(_)t/tr 2fH:O4-Qraise +63, 1, [13Oback w1 5W5, 7, [48ietweens11/0n} ZeroDivisionError 4\FloatingPoint]7 Y8547$Zwithi#""1p 67B2, 44, 5, -4pacross_ ~/ tracecontext<7, 2C4C Rasync) 5  +CN  3 bin_forfor i in [1]`.3Y. a  = ^%( $ $>f 3):  output.append(4)  5 16) 7 @jump_test(4, 5, [1, 2, 3 b-2, 6]D@def (_2out_of_with_block !in(r!):i1XG tracecontext<7, 2?* 3*. q*,Rasync0 / 6* <Ow l qGN?A5, 6, [2, 4 7jfinallym6tryz 2~I .'"4ivy6y 7i((b4D: ?caR8, 11/12g complex_nested(s for i in [1]Q 33#7j7;, 2:! > a! [k[ % c8!=  >*10? 1 25 z_assignmenE:% \Jas x j 5 % def test_jump_out_of_async_with_assignment(output): .append(1)@ @ tracecontexGe, 2) \2RV as xa e4e 15) M@jump_test(3, 6, [1R8, 9]=@def !_+over_return_in_try_finally_block?try 3rif not : # always false& :6^ 8. G9HB5, 8H3 10, 11, 13Q_breakP-while True W B 52  if 6*10 h< ,31, 7, [7, 82for_before_else  O for i in [3]  / +H7a 680!+(6" L_BXq Hiter([3] SVp# The sd set of ''Qs arethings that%allowed:@2, 3 ], (ValueError, 'after')#no`oo_far_wards ?21w_2, -2LOback3# Test each kindt except' line. @jump_te0st(2, 3, [4], (ValueError, 'except')) def test_no_jump_to_e"_1(output):*.6try ".append(2Tf- 4-1araise j@e22/ @p3:_ as e A40 bRuntim)51W VOintoTforwards_&_for_block O1"for i in 1, 2 #3)DSasyncJ4 %": `iter([]h 3, 2, [2, 2Obackw 8 & !|$2, 4, [ a_while"Qi = 1&$D_ i <=/ 0i +_`5O3, 3 +3$ i += 1  output.append(5) @jump_test(1, 3, [], (ValueError, 'into'))/@def -A_no_:forwards_&_with_block(o!):7j1P5 tracecontext<7, 2?* C3Rasync4 %#;  )i3, 2, [1/-1Oback1 2I & " -X0try_finally_6tryFb. 75_[2, 4* ~44oexceptHa ]raise 6.H   682# 'X'  variable creates an implicit S <5, 7, [retween_'3s_2j *11/0> ZeroDivisionError:  output.append(4)  5except FloatingPointError as e:E7E ^18) 7@jump_test(3, 6, [2, 5, 6], (Valuei, 'finally')S@def 7A_no_DSinto_%r_block(s)6try "2[ 3f : # still executed if the is failedR Vf6s 67>17[70._29 1R 5  5, 1, [1, 3oout_of f31, 2, -2between_withs6 tracecontext<7, 2.C4C 5Rasync5< $<  &+CN 1T*B7, 4+'6 B_for2_before_elserif not Palway1lse:for i in [3]yB} / +HszO8vU[Yq aiter([3] output.append(4) Uelse: +6+7 618) Tdef test_no_jump_to_non_integers(self)P.run_5(5, 2, "Spam", [True]owithout_trace_functionv# Must set sys.set0(None) in`Up(), .` condiHq is not# triggered. Olarged = {}\exec("""g"f( ):# line 0/Px = 0 /1/]y = 1+/2/0'''/3//%s*/s 4-10045dI10052?x +gY 10062K/!x)272return""" % ('\n' *Wf0,), d'f = d['f']> f1007, [0EPfirst.noAThisws that PDB can = back to the F&Ein a# file. See issue #1689458. ItNvonly be* Do call ifsis defined on a single=code = compile # Comments don't count. @2) &Lhere)+3):4) """, "n"`class %Y, __!__%de^]r = JumpT)r(G0j >.#namespac."{" [": []-%, .A d2are`a([2, 3W3, 4]X[@|5[1], event=' ', error=(ValueE P, "ca=e from"aA "UB U of a new frame")dU_>b1AwEwnested( 333/]5 &81, &b(Wonly jump fro,m a 'line' trace event")) def test_no_jump_from_return_*(output):04.append(1I7 )@N[(2, 1, [1],| ='exception', error=(ValueE ,@P"can only T  t]1 / 03, 2, [2)'tyield statem-Ggen(D 2K% 3uQnext(E( A5) if __name__ == "__main__"(@unit.() x = 1 t__dir__6 ['a', 'b4c']+`getatt/l0if xCyolotraise AttributQ("Deprecated, use whatever instead"f"There is {h}" y = 2 # IMPORTANT: the same@s are run"'_xml_etree_c" in order # to ensure consistency betweenXaC impl a(A andPython # . # # For this purpose,3 module-level "ET" symboltemporarily # monkey-patched whenAningJ suite. iMdt copy functoolsDhtml $io operatordpickle%sy?Etype e(0war weakref 3Aiter<ort productgsuppor.:TESTFN, findfile,r_fresh_r, gc_collect, swap_ # pyET he"e-F*2nlX!ispC accelHed version i,5A_c. O= None ET  SIMPLE_XMLFILE =1("s.xml", subdir="xml\data") try G.encode("utf-8") @ UniE>.SkipTest("j:Anot X@ableQ0utf\{/NS?-ns UTF8_BUGCexpat224_qO_bugK 4 SAR = """\ textb' id='inner'>subtext ! """ SAMPLE_SECTION = """\ <-" subtext Apples African Coffee T#80 length>12 &ENTITY_XML\ %; ]> &CEy;]ummarize_C(seq*[t.@for in seq] 0est @3amethodc`setUpC4(clQcls.m^j0{py 6ET}pickleRoundTripG2objH, dumper, loadSprotocsave_m = syl[] try:   sys.modules[name] = dumper $ temp = pickle.!s(obj, proto),SKloadSfresultU# s(iOdexceptwP~ingError as pe:z# pyET must be second, because ay(equal to) ET.FPhumanict([(ET, "cET"), (`0, "6")], raise support.TestFailed(" to round-trip %r fromito %r"Q!% y-1 P.get(3er,/),C C2)))%peLzfinallyesave_m8rreturn  def assertE Elements(self, alice, bob)m.4IsInstance(+C(ET.E, )A_bob, ?(len(listE)), zfor x, y in zip1 d s(>properties = ator.attrgetter('tag', 'tail0ext#6ib'J q([)n(_ # -0B # e tree tests class E@TreenP(unit!|fCase):Jserialize_checkF], expectedJf(@(4)5d}_interfacecS # -.F_string(J&H.H@charH   M5O), 1Tmsg=",P one-4bacter kP, got0 % Ew3new# =1J + "% &oO[:0]8@mapp9: ;0key-.(Hitem# $!keB~53 = gY[key]P"key"k"value3elf 6#, 5 )msg="expected value string, got %r" % mapping["key"]) def check_element(%):$+self.assertTrue(ET.is+3!, snot an )")I0dire = dir: #for attr in 'tag', ' ib AtextJail'0has<j,Z)),q8'no %s member' %4 30In(f,`visible by7h iJ.tagV&'*ib*$if.J@ is NNoneMW }?extT?ailT!:ailTJ?ents = ET.EG"tag*A'enItree@NTree' F5.getroot()f P("t\xe4g", key="L 1Regex(rep]c, r"^<" 'r' at 0x.*>$pa # Make sure all standardf methods exist. 9z"(x -, '__call__'""%*Aable/Xv.append%?ext% in<J oremove% getchildren* /fiOiter'#'al &U _clear$ 'gems"Okeysg Oitem$ F0get*Gatoryu# These)`returnB-ble. See bug 6472. def check_iter(it): method(it.__next__) '#?element. find("tag")),**OtreeS )P{# These aliases are provided:self.assertEqual(ET.XML, ET.fromstring0!PI/ProcessingInstruction9def test_set_attribute(NP =~E]c('tag'G4 6c.tag, .) = 'Tag'"I , I/AGI/AGuIsNone(\?extr1ext?exttpext, 'T.M?EXTM. ?ailv1ail?ailv0ail.M?AILM.N, {}{ = {'a': 'b', 'c ?d'}X?,>m AcBmC Dm>impleops# Basic r sanityA&s.E<XML("') # 1r=subuent("subtag"3) element.append(sub#self.serialize_check(& , '') # 2rinsert(0, uL 3C.removeG4rH" /e5dQwith  asgRaises(VError) as cm:2K TEqual(str(cm.exception), 'listQx): x not in 'Z&6[0:0] = [JV ]<0[1]: u1:9], [4], ;2]]AH:9:2B0B5del[?1:2,  @def test_cdata(D)D # Test CDATA handling (etc).@x5 PET.XML("Nb>helloy/")%   ]`h18?11;vE1;d$SIOFILEn./../empty-O'&"')dRpath_cache0# Ct that the + + behaves sanelyffrom xml.e5import ElementsPath  elem = ET.XML(SAMPLE_XML)"for i in range(10):/ElementTree(E).find('./'+str(i)Ccache_len_10 = len(?!._ /r0self.assertEqual(t!, |2 Greater,/60+OLessB500)def test_copy(%):p# Test  handling (etc).>XRimpor%9&e1g"hello%b%2#self.assertEqual(ET.tostring(%),t@ b'< 0a="Aval"bp2">aan asortedi.keys()), [6b'] BAitemC [ZT(", k r.attrib3b']xS'" =%1' '4c']'2' 31c c\'\rbO\r\nc\t\n\r !d!n?)a=" " b c 109;@ " d"100" /1defP_make!): +w# Test " handling. V"tag"q = {"key": "O%"}i0sub0 = .qP("subO", GWcIsNot(F1r, msg="> aliasinsdappendC eserialize_check, '<S key=P />\n' text') Wwith opene as f:(data = f.read(Er@XMLPrbRegex(1.version, r'^Expat ?$Pfeed(zOserialize_checkSOclosSbtargetjTreeBuildel7"8=J-.ddef test_PliterFelf) XML("j]*Tlist(Z b'text\n"" "_, ids = ET.XMLID(< Slen(ids), 0bP id=''l1l &Pids["_"].tag, l!) 4def test_iterparse(B!):u# Test interface.C%G"0con& =J(SIMPLE_XMLFILEaction,  = next(@% (7), ('end', 'K_ent')A[BX for XC in E], [&qC$Umpty-*[root'#].8 0, ' '#.NS o.:{namespace}/(sd; ]KPeventB(_", 84d17=W"start", "endEeJ P%('#$ J ('end', 'element'), ('start', 'empty-, ?end*=roow5]) events = ("p", "end0-ns 0end )8context = iterparse(SIMPLE_NS_XMLFILE, _7 self.assertEqual([(action, .tag) if < inK HYelse cA 3forzE], [l-ns', ('namespace') {*}c_W.(L /`]5!X{', None'?K% io.StringIO(r"< xmlns=''/>") re[  Pores, [ fbogus"with open"rb") as f:2Raises(ValueError5*cm6:Kf!VFalse(f.closed#bstr(cm.excepj), "unknown! '''"upport.check_no_resource_warning(m):!Ij F Afdel cmo.BytesIO(!b"\n"=Dbody  http://éffbot.org/ns'9C:cl\xe9='@e;> junk")1 it-terparse(@raction,= next(it self.assertEqual((2P.tag)0end&')BWwith GRaises(ET.PError) as cm:str(cm.excepz't after ent: line 1, column 12'kddCleanup(support.unlink, TESTFNRopen(a, "wb"ff.write(bTn Hcheck_no_reC_warning()&e 86del cm, itdef test_LfileL= ET.EleW("tag!.g@ = ""serialize_r(0, '/ Pext# Test tag 'uression,u = None q[ in0(0,z2Comzc "q'3!--G@--><!')5# assumes 1.32A[0] PI("key", "value Q?key 6?ydcustom_builderRr w. / /.MSIMPLE_XMLFILEdata = f.read(sclass BKlist9i,P, attrib*1append(("8"4(V$0 :   self.append(("end", tag)) def data(/, text):")Epassbuilder = B (SAparsqET.XMLP(target=9 .`.feed(.assertEqual(<5, [('start', 'root'),# oelemen&0endG$ m& J_mpty-P* 5]) with open(SIMPLE_NS_XMLFILE) as f = f.readUclass text%s" % encoding def bxml(%):#yreturn ".,e32supported_#ings = [ R'ascii', 'utf-8 D-sig &16 &be Jle',Miso8859-1% 2 3 4 5M~M739/10N11)15D6DAcp43Pcp720,5cp77>Ccp85>852B%85'0T!85Dcp86B6JK6T6T6Acp87Scp100=112lDcp123125v 12! 'l4125R2 *h#25 12 *mac-cyrillicJTgreek ticeland]latin6Troman'|turkishxiso2022-jp)-?004M-O