11# Test the pickle module
22
3+ # break into multiple strings to please font-lock-mode
34DATA = """(lp0
45I0
56aL1L
67aF2.0
78ac__builtin__
89complex
910p1
10- (F3.0
11+ """ \
12+ """(F3.0
1113F0.0
1214tp2
1315Rp3
1416a(S'abc'
1517p4
1618g4
17- (i__main__
19+ """ \
20+ """(i__main__
1821C
1922p5
20- (dp6
23+ """ \
24+ """(dp6
2125S'foo'
2226p7
2327I1
3337
3438BINDATA = ']q\000 (K\000 L1L\012 G@\000 \000 \000 \000 \000 \000 \000 c__builtin__\012 complex\012 q\001 (G@\010 \000 \000 \000 \000 \000 \000 G\000 \000 \000 \000 \000 \000 \000 \000 tq\002 Rq\003 (U\003 abcq\004 h\004 (c__main__\012 C\012 q\005 oq\006 }q\007 (U\003 fooq\010 K\001 U\003 barq\011 K\002 ubh\006 tq\012 h\012 K\005 e.'
3539
36- import pickle
37-
3840class C :
3941 def __cmp__ (self , other ):
4042 return cmp (self .__dict__ , other .__dict__ )
4143
4244import __main__
4345__main__ .C = C
4446
45- def dotest ():
47+ def dotest (pickle ):
4648 c = C ()
4749 c .foo = 1
4850 c .bar = 2
@@ -51,6 +53,8 @@ def dotest():
5153 x .append (y )
5254 x .append (y )
5355 x .append (5 )
56+ r = []
57+ r .append (r )
5458 print "dumps()"
5559 s = pickle .dumps (x )
5660 print "loads()"
@@ -71,5 +75,66 @@ def dotest():
7175 x2 = pickle .loads (BINDATA )
7276 if x2 == x : print "ok"
7377 else : print "bad"
78+ s = pickle .dumps (r )
79+ print "dumps() RECURSIVE"
80+ x2 = pickle .loads (s )
81+ if x2 == r : print "ok"
82+ else : print "bad"
7483
75- dotest ()
84+ # Test protection against closed files
85+ import tempfile , os
86+ fn = tempfile .mktemp ()
87+ f = open (fn , "w" )
88+ f .close ()
89+ try :
90+ pickle .dump (123 , f )
91+ except ValueError :
92+ pass
93+ else :
94+ print "dump to closed file should raise ValueError"
95+ f = open (fn , "r" )
96+ f .close ()
97+ try :
98+ pickle .load (f )
99+ except ValueError :
100+ pass
101+ else :
102+ print "load from closed file should raise ValueError"
103+ os .remove (fn )
104+
105+ # Test specific bad cases
106+ for i in range (10 ):
107+ try :
108+ x = pickle .loads ('garyp' )
109+ except KeyError , y :
110+ # pickle
111+ del y
112+ except pickle .BadPickleGet , y :
113+ # cPickle
114+ del y
115+ else :
116+ print "unexpected success!"
117+ break
118+
119+ # Test insecure strings
120+ insecure = ["abc" , "2 + 2" , # not quoted
121+ "'abc' + 'def'" , # not a single quoted string
122+ "'abc" , # quote is not closed
123+ "'abc\" " , # open quote and close quote don't match
124+ "'abc' ?" , # junk after close quote
125+ # some tests of the quoting rules
126+ "'abc\" \' '" ,
127+ "'\\ \\ a\' \' \' \\ \' \\ \\ \' '" ,
128+ ]
129+ for s in insecure :
130+ buf = "S" + s + "\012 p0\012 ."
131+ try :
132+ x = pickle .loads (buf )
133+ except ValueError :
134+ pass
135+ else :
136+ print "accepted insecure string: %s" % repr (buf )
137+
138+
139+ import pickle
140+ dotest (pickle )
0 commit comments