test_new.py 2.13 KB
Newer Older
1
from test_support import verbose, verify
2 3 4 5 6
import sys
import new

class Eggs:
    def get_yolks(self):
7
        return self.yolks
8

9
print 'new.module()'
10
m = new.module('Spam')
11 12
if verbose:
    print m
13 14 15 16 17 18 19
m.Eggs = Eggs
sys.modules['Spam'] = m
import Spam

def get_more_yolks(self):
    return self.yolks + 3

20
print 'new.classobj()'
21
C = new.classobj('Spam', (Spam.Eggs,), {'get_more_yolks': get_more_yolks})
22 23 24
if verbose:
    print C
print 'new.instance()'
25
c = new.instance(C, {'yolks': 3})
26 27
if verbose:
    print c
28 29 30 31 32 33 34 35
o = new.instance(C)
verify(o.__dict__ == {},
       "new __dict__ should be empty")
del o
o = new.instance(C, None)
verify(o.__dict__ == {},
       "new __dict__ should be empty")
del o
36 37 38

def break_yolks(self):
    self.yolks = self.yolks - 2
39
print 'new.instancemethod()'
40
im = new.instancemethod(break_yolks, c, C)
41 42
if verbose:
    print im
43

44 45
verify(c.get_yolks() == 3 and c.get_more_yolks() == 6,
       'Broken call of hand-crafted class instance')
46
im()
47 48
verify(c.get_yolks() == 1 and c.get_more_yolks() == 4,
       'Broken call of hand-crafted instance method')
49

50 51 52 53
# It's unclear what the semantics should be for a code object compiled at
# module scope, but bound and run in a function.  In CPython, `c' is global
# (by accident?) while in Jython, `c' is local.  The intent of the test
# clearly is to make `c' global, so let's be explicit about it.
54
codestr = '''
55
global c
56 57 58 59 60 61
a = 1
b = 2
c = a + b
'''

ccode = compile(codestr, '<string>', 'exec')
62 63 64
# Jython doesn't have a __builtins__, so use a portable alternative
import __builtin__
g = {'c': 0, '__builtins__': __builtin__}
65
# this test could be more robust
66
print 'new.function()'
67
func = new.function(ccode, g)
68 69
if verbose:
    print func
70
func()
71 72
verify(g['c'] == 3,
       'Could not create a proper function object')
73

74
print 'new.code()'
75
# bogus test of new.code()
76 77 78 79 80 81 82 83 84
# Note: Jython will never have new.code()
if hasattr(new, 'code'):
    d = new.code(3, 3, 3, 3, codestr, (), (), (),
                 "<string>", "<name>", 1, "", (), ())
    # test backwards-compatibility version with no freevars or cellvars
    d = new.code(3, 3, 3, 3, codestr, (), (), (),
                 "<string>", "<name>", 1, "")
    if verbose:
        print d