1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
|
# -*- coding: utf-8 -*-
import test.test_support, unittest
from test.test_support import TESTFN, unlink
import sys, UserDict
from codecs import BOM_UTF8
class BuiltinTest(unittest.TestCase):
def test_in_sys_modules(self):
self.assert_("__builtin__" in sys.modules,
"__builtin__ not found in sys.modules")
def test_hasattr_swallows_exceptions(self):
class Foo(object):
def __getattr__(self, name):
raise TypeError()
self.assert_(not hasattr(Foo(), 'bar'))
def test_getattr_custom_AttributeError(self):
class Foo(object):
def __getattr__(self, name):
raise AttributeError('baz')
try:
getattr(Foo(), 'bar')
except AttributeError, ae:
self.assertEqual(str(ae), 'baz')
else:
self.assertTrue(False)
def test_dir(self):
# for http://bugs.jython.org/issue1196
class Foo(object):
def __getattribute__(self, name):
return name
self.assertEqual(dir(Foo()), [])
def test_numeric_cmp(self):
# http://bugs.jython.org/issue1449
for numeric in 1, 2L, 3.0, 4j:
self.assertTrue(numeric < Ellipsis)
self.assertTrue(Ellipsis > numeric)
class LoopTest(unittest.TestCase):
def test_break(self):
while 1:
i = 0
while i<10:
i = i+1
else:
break
class DebugTest(unittest.TestCase):
def test_debug(self):
"__debug__ exists"
try:
foo = __debug__
except NameError, e:
self.assert_(False)
class GetSliceTest(unittest.TestCase):
def test_getslice(self):
class F:
def __getitem__(self,*args): return '__getitem__ '+repr(args)
def __getslice__(self,*args): return '__getslice__ '+repr(args)
self.failUnless("__getslice__ (1, 1)" in F()[1:1])
class ChrTest(unittest.TestCase):
def test_debug(self):
"chr(None) throws TypeError"
foo = False
try:
chr(None)
except TypeError, e:
foo = True
self.assert_(foo)
class ReturnTest(unittest.TestCase):
def test_finally(self):
'''return in finally causes java.lang.VerifyError at compile time'''
def timeit(f):
t0 = time.clock()
try:
f()
finally:
t1 = time.clock()
return t1 - t0
class ReprTest(unittest.TestCase):
def test_unbound(self):
"Unbound methods indicated properly in repr"
class Foo:
def bar(s):
pass
self.failUnless(repr(Foo.bar).startswith('<unbound method'))
class CallableTest(unittest.TestCase):
def test_callable_oldstyle(self):
class Foo:
pass
self.assert_(callable(Foo))
self.assert_(not callable(Foo()))
class Bar:
def __call__(self):
return None
self.assert_(callable(Bar()))
class Baz:
def __getattr__(self, name):
return None
self.assert_(callable(Baz()))
def test_callable_newstyle(self):
class Foo(object):
pass
self.assert_(callable(Foo))
self.assert_(not callable(Foo()))
class Bar(object):
def __call__(self):
return None
self.assert_(callable(Bar()))
class Baz(object):
def __getattr__(self, name):
return None
self.assert_(not callable(Baz()))
class ConversionTest(unittest.TestCase):
class Foo(object):
def __int__(self):
return 3
def __float__(self):
return 3.14
foo = Foo()
def test_range_non_int(self):
self.assertEqual(range(self.foo), [0, 1, 2])
def test_xrange_non_int(self):
self.assertEqual(list(xrange(self.foo)), [0, 1, 2])
def test_round_non_float(self):
self.assertEqual(round(self.Foo(), 1), 3.1)
# 2.5/2.5.1 regression
self.assertRaises(TypeError, round, '1.5')
class ExecEvalTest(unittest.TestCase):
def test_eval_bom(self):
self.assertEqual(eval(BOM_UTF8 + '"foo"'), 'foo')
# Actual BOM ignored, so causes a SyntaxError
self.assertRaises(SyntaxError, eval,
BOM_UTF8.decode('iso-8859-1') + '"foo"')
def test_parse_str_eval(self):
foo = 'föö'
for code, expected in (
("'%s'" % foo.decode('utf-8'), foo),
("# coding: utf-8\n'%s'" % foo, foo),
("%s'%s'" % (BOM_UTF8, foo), foo),
("'\rfoo\r'", '\rfoo\r')
):
mod = compile(code, 'test.py', 'eval')
result = eval(mod)
self.assertEqual(result, expected)
result = eval(code)
self.assertEqual(result, expected)
def test_parse_str_exec(self):
foo = 'föö'
for code, expected in (
("bar = '%s'" % foo.decode('utf-8'), foo),
("# coding: utf-8\nbar = '%s'" % foo, foo),
("%sbar = '%s'" % (BOM_UTF8, foo), foo),
("bar = '\rfoo\r'", '\rfoo\r')
):
ns = {}
exec code in ns
self.assertEqual(ns['bar'], expected)
def test_general_eval(self):
# Tests that general mappings can be used for the locals argument
class M:
"Test mapping interface versus possible calls from eval()."
def __getitem__(self, key):
if key == 'a':
return 12
raise KeyError
def keys(self):
return list('xyz')
m = M()
g = globals()
self.assertEqual(eval('a', g, m), 12)
self.assertRaises(NameError, eval, 'b', g, m)
self.assertEqual(eval('dir()', g, m), list('xyz'))
self.assertEqual(eval('globals()', g, m), g)
self.assertEqual(eval('locals()', g, m), m)
#XXX: the following assert holds in CPython because globals must be a
# real dict. Should Jython be as strict?
#self.assertRaises(TypeError, eval, 'a', m)
class A:
"Non-mapping"
pass
m = A()
self.assertRaises(TypeError, eval, 'a', g, m)
# Verify that dict subclasses work as well
class D(dict):
def __getitem__(self, key):
if key == 'a':
return 12
return dict.__getitem__(self, key)
def keys(self):
return list('xyz')
d = D()
self.assertEqual(eval('a', g, d), 12)
self.assertRaises(NameError, eval, 'b', g, d)
self.assertEqual(eval('dir()', g, d), list('xyz'))
self.assertEqual(eval('globals()', g, d), g)
self.assertEqual(eval('locals()', g, d), d)
# Verify locals stores (used by list comps)
eval('[locals() for i in (2,3)]', g, d)
eval('[locals() for i in (2,3)]', g, UserDict.UserDict())
class SpreadSheet:
"Sample application showing nested, calculated lookups."
_cells = {}
def __setitem__(self, key, formula):
self._cells[key] = formula
def __getitem__(self, key):
return eval(self._cells[key], globals(), self)
ss = SpreadSheet()
ss['a1'] = '5'
ss['a2'] = 'a1*6'
ss['a3'] = 'a2*7'
self.assertEqual(ss['a3'], 210)
# Verify that dir() catches a non-list returned by eval
# SF bug #1004669
class C:
def __getitem__(self, item):
raise KeyError(item)
def keys(self):
return 'a'
self.assertRaises(TypeError, eval, 'dir()', globals(), C())
# Done outside of the method test_z to get the correct scope
z = 0
f = open(TESTFN, 'w')
f.write('z = z+1\n')
f.write('z = z*2\n')
f.close()
execfile(TESTFN)
def test_execfile(self):
globals = {'a': 1, 'b': 2}
locals = {'b': 200, 'c': 300}
class M:
"Test mapping interface versus possible calls from execfile()."
def __init__(self):
self.z = 10
def __getitem__(self, key):
if key == 'z':
return self.z
raise KeyError
def __setitem__(self, key, value):
if key == 'z':
self.z = value
return
raise KeyError
locals = M()
locals['z'] = 0
execfile(TESTFN, globals, locals)
self.assertEqual(locals['z'], 2)
self.assertRaises(TypeError, execfile)
self.assertRaises(TypeError, execfile, TESTFN, {}, ())
unlink(TESTFN)
class ModuleNameTest(unittest.TestCase):
"""Tests that the module when imported has the same __name__"""
def test_names(self):
for name in sys.builtin_module_names:
if name not in ('time', '_random', 'array', '_collections', '_ast'):
module = __import__(name)
self.assertEqual(name, module.__name__)
def test_main():
test.test_support.run_unittest(BuiltinTest,
LoopTest,
DebugTest,
GetSliceTest,
ChrTest,
ReturnTest,
ReprTest,
CallableTest,
ConversionTest,
ExecEvalTest,
ModuleNameTest,
)
if __name__ == "__main__":
test_main()
|