py-cvs-rel2_1 (Rev 1.2) merge
[python/dscho.git] / Lib / test / test_new.py
blobab5eedec47f48d9252743f656cce6a39ea0f168c
1 from test_support import verbose, verify
2 import sys
3 import new
5 class Eggs:
6 def get_yolks(self):
7 return self.yolks
9 print 'new.module()'
10 m = new.module('Spam')
11 if verbose:
12 print m
13 m.Eggs = Eggs
14 sys.modules['Spam'] = m
15 import Spam
17 def get_more_yolks(self):
18 return self.yolks + 3
20 print 'new.classobj()'
21 C = new.classobj('Spam', (Spam.Eggs,), {'get_more_yolks': get_more_yolks})
22 if verbose:
23 print C
24 print 'new.instance()'
25 c = new.instance(C, {'yolks': 3})
26 if verbose:
27 print c
28 o = new.instance(C)
29 verify(o.__dict__ == {},
30 "new __dict__ should be empty")
31 del o
32 o = new.instance(C, None)
33 verify(o.__dict__ == {},
34 "new __dict__ should be empty")
35 del o
37 def break_yolks(self):
38 self.yolks = self.yolks - 2
39 print 'new.instancemethod()'
40 im = new.instancemethod(break_yolks, c, C)
41 if verbose:
42 print im
44 verify(c.get_yolks() == 3 and c.get_more_yolks() == 6,
45 'Broken call of hand-crafted class instance')
46 im()
47 verify(c.get_yolks() == 1 and c.get_more_yolks() == 4,
48 'Broken call of hand-crafted instance method')
50 # It's unclear what the semantics should be for a code object compiled at
51 # module scope, but bound and run in a function. In CPython, `c' is global
52 # (by accident?) while in Jython, `c' is local. The intent of the test
53 # clearly is to make `c' global, so let's be explicit about it.
54 codestr = '''
55 global c
56 a = 1
57 b = 2
58 c = a + b
59 '''
61 ccode = compile(codestr, '<string>', 'exec')
62 # Jython doesn't have a __builtins__, so use a portable alternative
63 import __builtin__
64 g = {'c': 0, '__builtins__': __builtin__}
65 # this test could be more robust
66 print 'new.function()'
67 func = new.function(ccode, g)
68 if verbose:
69 print func
70 func()
71 verify(g['c'] == 3,
72 'Could not create a proper function object')
74 # bogus test of new.code()
75 # Note: Jython will never have new.code()
76 if hasattr(new, 'code'):
77 print 'new.code()'
78 d = new.code(3, 3, 3, 3, codestr, (), (), (),
79 "<string>", "<name>", 1, "", (), ())
80 # test backwards-compatibility version with no freevars or cellvars
81 d = new.code(3, 3, 3, 3, codestr, (), (), (),
82 "<string>", "<name>", 1, "")
83 if verbose:
84 print d