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 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
|
import copy
import operator
import os
import unittest
import subprocess
import sys
import re
from collections import deque
from test import test_support
from java.lang import (
ClassCastException, ExceptionInInitializerError, UnsupportedOperationException,
String, Runnable, System, Runtime, Math, Byte)
from java.math import BigDecimal, BigInteger
from java.io import (ByteArrayInputStream, ByteArrayOutputStream, File, FileInputStream,
FileNotFoundException, FileOutputStream, FileWriter, ObjectInputStream,
ObjectOutputStream, OutputStreamWriter, UnsupportedEncodingException)
from java.util import ArrayList, Date, HashMap, Hashtable, StringTokenizer, Vector
from java.awt import Dimension, Color, Component, Container
from java.awt.event import ComponentEvent
from javax.swing.tree import TreePath
from org.python.core.util import FileUtil
from org.python.tests import (BeanImplementation, Child, Child2,
CustomizableMapHolder, Listenable, ToUnicode)
from org.python.tests.mro import (ConfusedOnGetitemAdd, FirstPredefinedGetitem, GetitemAdder)
from javatests import Issue1833
from javatests.ProxyTests import NullToString, Person
class InstantiationTest(unittest.TestCase):
def test_cant_instantiate_abstract(self):
self.assertRaises(TypeError, Component)
def test_no_public_constructors(self):
self.assertRaises(TypeError, Math)
def test_invalid_self_to_java_constructor(self):
self.assertRaises(TypeError, Color.__init__, 10, 10, 10)
def test_str_doesnt_coerce_to_int(self):
self.assertRaises(TypeError, Date, '99-01-01', 1, 1)
def test_class_in_failed_constructor(self):
try:
Dimension(123, 456, 789)
except TypeError, exc:
self.failUnless("java.awt.Dimension" in exc.message)
class BeanTest(unittest.TestCase):
def test_shared_names(self):
self.failUnless(callable(Vector.size),
'size method should be preferred to writeonly field')
def test_multiple_listeners(self):
'''Check that multiple BEP can be assigned to a single cast listener'''
m = Listenable()
called = []
def f(evt, called=called):
called.append(0)
m.componentShown = f
m.componentHidden = f
m.fireComponentShown(ComponentEvent(Container(), 0))
self.assertEquals(1, len(called))
m.fireComponentHidden(ComponentEvent(Container(), 0))
self.assertEquals(2, len(called))
def test_bean_interface(self):
b = BeanImplementation()
self.assertEquals("name", b.getName())
self.assertEquals("name", b.name)
# Tests for #610576
class SubBean(BeanImplementation):
def __init__(bself):
self.assertEquals("name", bself.getName())
SubBean()
def test_inheriting_half_bean(self):
c = Child()
self.assertEquals("blah", c.value)
c.value = "bleh"
self.assertEquals("bleh", c.value)
self.assertEquals(7, c.id)
c.id = 16
self.assertEquals(16, c.id)
def test_inheriting_half_bean_issue1333(self):
# http://bugs.jython.org/issue1333
c = Child2()
self.assertEquals("blah", c.value)
c.value = "bleh"
self.assertEquals("Child2 bleh", c.value)
def test_awt_hack(self):
# We ignore several deprecated methods in java.awt.* in favor of bean properties that were
# addded in Java 1.1. This tests that one of those bean properties is visible.
c = Container()
c.size = 400, 300
self.assertEquals(Dimension(400, 300), c.size)
class SysIntegrationTest(unittest.TestCase):
def setUp(self):
self.orig_stdout = sys.stdout
def tearDown(self):
sys.stdout = self.orig_stdout
def test_stdout_outputstream(self):
out = FileOutputStream(test_support.TESTFN)
sys.stdout = out
print 'hello',
out.close()
f = open(test_support.TESTFN)
self.assertEquals('hello', f.read())
f.close()
class IOTest(unittest.TestCase):
def test_io_errors(self):
"Check that IOException isn't mangled into an IOError"
self.assertRaises(UnsupportedEncodingException, OutputStreamWriter, System.out, "garbage")
self.assertRaises(IOError, OutputStreamWriter, System.out, "garbage")
def test_fileio_error(self):
self.assertRaises(FileNotFoundException, FileInputStream, "garbage")
def test_unsupported_tell(self):
fp = FileUtil.wrap(System.out)
self.assertRaises(IOError, fp.tell)
class JavaReservedNamesTest(unittest.TestCase):
"Access to reserved words"
def test_system_in(self):
s = System.in
self.assert_("java.io.BufferedInputStream" in str(s))
def test_runtime_exec(self):
e = Runtime.getRuntime().exec
self.assert_(re.search("method .*exec", str(e)) is not None)
def test_byte_class(self):
b = Byte(10)
self.assert_("java.lang.Byte" in str(b.class))
class Keywords(object):
pass
Keywords.in = lambda self: "in"
Keywords.exec = lambda self: "exec"
Keywords.class = lambda self: "class"
Keywords.print = lambda self: "print"
Keywords.and = lambda self: "and"
Keywords.as = lambda self: "as"
Keywords.assert = lambda self: "assert"
Keywords.break = lambda self: "break"
Keywords.continue = lambda self: "continue"
Keywords.def = lambda self: "def"
Keywords.del = lambda self: "del"
Keywords.elif = lambda self: "elif"
Keywords.else = lambda self: "else"
Keywords.except = lambda self: "except"
Keywords.finally = lambda self: "finally"
Keywords.from = lambda self: "from"
Keywords.for = lambda self: "for"
Keywords.global = lambda self: "global"
Keywords.if = lambda self: "if"
Keywords.import = lambda self: "import"
Keywords.is = lambda self: "is"
Keywords.lambda = lambda self: "lambda"
Keywords.pass = lambda self: "pass"
Keywords.print = lambda self: "print"
Keywords.raise = lambda self: "raise"
Keywords.return = lambda self: "return"
Keywords.try = lambda self: "try"
Keywords.while = lambda self: "while"
Keywords.with = lambda self: "with"
Keywords.yield = lambda self: "yield"
class PyReservedNamesTest(unittest.TestCase):
"Access to reserved words"
def setUp(self):
self.kws = Keywords()
def test_in(self):
self.assertEquals(self.kws.in(), "in")
def test_exec(self):
self.assertEquals(self.kws.exec(), "exec")
def test_class(self):
self.assertEquals(self.kws.class(), "class")
def test_print(self):
self.assertEquals(self.kws.print(), "print")
def test_and(self):
self.assertEquals(self.kws.and(), "and")
def test_as(self):
self.assertEquals(self.kws.as(), "as")
def test_assert(self):
self.assertEquals(self.kws.assert(), "assert")
def test_break(self):
self.assertEquals(self.kws.break(), "break")
def test_continue(self):
self.assertEquals(self.kws.continue(), "continue")
def test_def(self):
self.assertEquals(self.kws.def(), "def")
def test_del(self):
self.assertEquals(self.kws.del(), "del")
def test_elif(self):
self.assertEquals(self.kws.elif(), "elif")
def test_else(self):
self.assertEquals(self.kws.else(), "else")
def test_except(self):
self.assertEquals(self.kws.except(), "except")
def test_finally(self):
self.assertEquals(self.kws.finally(), "finally")
def test_from(self):
self.assertEquals(self.kws.from(), "from")
def test_for(self):
self.assertEquals(self.kws.for(), "for")
def test_global(self):
self.assertEquals(self.kws.global(), "global")
def test_if(self):
self.assertEquals(self.kws.if(), "if")
def test_import(self):
self.assertEquals(self.kws.import(), "import")
def test_is(self):
self.assertEquals(self.kws.is(), "is")
def test_lambda(self):
self.assertEquals(self.kws.lambda(), "lambda")
def test_pass(self):
self.assertEquals(self.kws.pass(), "pass")
def test_print(self):
self.assertEquals(self.kws.print(), "print")
def test_raise(self):
self.assertEquals(self.kws.raise(), "raise")
def test_return(self):
self.assertEquals(self.kws.return(), "return")
def test_try(self):
self.assertEquals(self.kws.try(), "try")
def test_while(self):
self.assertEquals(self.kws.while(), "while")
def test_with(self):
self.assertEquals(self.kws.with(), "with")
def test_yield(self):
self.assertEquals(self.kws.yield(), "yield")
class ImportTest(unittest.TestCase):
def test_bad_input_exception(self):
self.assertRaises(ValueError, __import__, '')
def test_broken_static_initializer(self):
self.assertRaises(ExceptionInInitializerError, __import__, "org.python.tests.BadStaticInitializer")
class ColorTest(unittest.TestCase):
def test_assigning_over_method(self):
self.assertRaises(TypeError, setattr, Color.RED, "getRGB", 4)
def test_static_fields(self):
self.assertEquals(Color(255, 0, 0), Color.RED)
# The bean accessor for getRed should be active on instances, but the static field red
# should be visible on the class
self.assertEquals(255, Color.red.red)
self.assertEquals(Color(0, 0, 255), Color.blue)
def test_is_operator(self):
red = Color.red
self.assert_(red is red)
self.assert_(red is Color.red)
class TreePathTest(unittest.TestCase):
def test_overloading(self):
treePath = TreePath([1,2,3])
self.assertEquals(len(treePath.path), 3, "Object[] not passed correctly")
self.assertEquals(TreePath(treePath.path).path, treePath.path, "Object[] not passed and returned correctly")
class BigNumberTest(unittest.TestCase):
def test_coerced_bigdecimal(self):
from javatests import BigDecimalTest
x = BigDecimal("123.4321")
y = BigDecimalTest().asBigDecimal()
self.assertEqual(type(x), type(y), "BigDecimal coerced")
self.assertEqual(x, y, "coerced BigDecimal not equal to directly created version")
def test_biginteger_in_long(self):
'''Checks for #608628, that long can take a BigInteger in its constructor'''
ns = '10000000000'
self.assertEquals(ns, str(long(BigInteger(ns))))
class JavaStringTest(unittest.TestCase):
def test_string_not_iterable(self):
x = String('test')
self.assertRaises(TypeError, list, x)
class JavaDelegationTest(unittest.TestCase):
def test_list_delegation(self):
for c in ArrayList, Vector:
a = c()
self.assertRaises(IndexError, a.__getitem__, 0)
a.add("blah")
self.assertTrue("blah" in a)
self.assertEquals(1, len(a))
n = 0
for i in a:
n += 1
self.assertEquals("blah", i)
self.assertEquals(1, n)
self.assertEquals("blah", a[0])
a[0] = "bleh"
del a[0]
self.assertEquals(0, len(a))
def test_map_delegation(self):
m = HashMap()
m["a"] = "b"
self.assertTrue("a" in m)
self.assertEquals("b", m["a"])
n = 0
for k in m:
n += 1
self.assertEquals("a", k)
self.assertEquals(1, n)
del m["a"]
self.assertEquals(0, len(m))
def test_enumerable_delegation(self):
tokenizer = StringTokenizer('foo bar')
self.assertEquals(list(iter(tokenizer)), ['foo', 'bar'])
def test_vector_delegation(self):
class X(Runnable):
pass
v = Vector()
v.addElement(1)
v.indexOf(X())# Compares the Java object in the vector to a Python subclass
for i in v:
pass
def test_comparable_delegation(self):
first_file = File("a")
first_date = Date(100)
for a, b, c in [(first_file, File("b"), File("c")), (first_date, Date(1000), Date())]:
self.assertTrue(a.compareTo(b) < 0)
self.assertEquals(-1, cmp(a, b))
self.assertTrue(a.compareTo(c) < 0)
self.assertEquals(-1, cmp(a, c))
self.assertEquals(0, a.compareTo(a))
self.assertEquals(0, cmp(a, a))
self.assertTrue(b.compareTo(a) > 0)
self.assertEquals(1, cmp(b, a))
self.assertTrue(c.compareTo(b) > 0)
self.assertEquals(1, cmp(c, b))
self.assertTrue(a < b)
self.assertTrue(a <= a)
self.assertTrue(b > a)
self.assertTrue(c >= a)
self.assertTrue(a != b)
l = [b, c, a]
self.assertEquals(a, min(l))
self.assertEquals(c, max(l))
l.sort()
self.assertEquals([a, b, c], l)
# Check that we fall back to the default comparison(class name) instead of using compareTo
# on non-Comparable types
self.assertRaises(ClassCastException, first_file.compareTo, first_date)
self.assertEquals(-1, cmp(first_file, first_date))
self.assertTrue(first_file < first_date)
self.assertTrue(first_file <= first_date)
self.assertTrue(first_date > first_file)
self.assertTrue(first_date >= first_file)
def test_equals(self):
# Test for bug #1338
a = range(5)
x = ArrayList()
x.addAll(a)
y = Vector()
y.addAll(a)
z = ArrayList()
z.addAll(range(1, 6))
self.assertTrue(x.equals(y))
self.assertEquals(x, y)
self.assertTrue(not (x != y))
self.assertTrue(not x.equals(z))
self.assertNotEquals(x, z)
self.assertTrue(not (x == z))
class SecurityManagerTest(unittest.TestCase):
def test_nonexistent_import_with_security(self):
if os._name == 'nt':
# http://bugs.jython.org/issue1371
return
script = test_support.findfile("import_nonexistent.py")
home = os.path.realpath(sys.prefix)
if not os.path.commonprefix((home, os.path.realpath(script))) == home:
# script must lie within python.home for this test to work
return
policy = test_support.findfile("python_home.policy")
self.assertEquals(subprocess.call([sys.executable, "-J-Dpython.cachedir.skip=true",
"-J-Djava.security.manager", "-J-Djava.security.policy=%s" % policy, script]),
0)
class JavaWrapperCustomizationTest(unittest.TestCase):
def tearDown(self):
CustomizableMapHolder.clearAdditions()
def test_adding_item_access(self):
m = CustomizableMapHolder()
self.assertRaises(TypeError, operator.getitem, m, "initial")
CustomizableMapHolder.addGetitem()
self.assertEquals(m.held["initial"], m["initial"])
# dict would throw a KeyError here, but Map returns null for a missing key
self.assertEquals(None, m["nonexistent"])
self.assertRaises(TypeError, operator.setitem, m, "initial")
CustomizableMapHolder.addSetitem()
m["initial"] = 12
self.assertEquals(12, m["initial"])
def test_adding_attributes(self):
m = CustomizableMapHolder()
self.assertRaises(AttributeError, getattr, m, "initial")
CustomizableMapHolder.addGetattribute()
self.assertEquals(7, m.held["initial"], "Existing fields should still be accessible")
self.assertEquals(7, m.initial)
self.assertEquals(None, m.nonexistent, "Nonexistent fields should be passed on to the Map")
def test_adding_on_interface(self):
GetitemAdder.addPredefined()
class UsesInterfaceMethod(FirstPredefinedGetitem):
pass
self.assertEquals("key", UsesInterfaceMethod()["key"])
def test_add_on_mro_conflict(self):
"""Adding same-named methods to Java classes with MRO conflicts produces TypeError"""
GetitemAdder.addPredefined()
self.assertRaises(TypeError, __import__, "org.python.tests.mro.ConfusedOnImport")
self.assertRaises(TypeError, GetitemAdder.addPostdefined)
def test_null_tostring(self):
# http://bugs.jython.org/issue1819
nts = NullToString()
self.assertEqual(repr(nts), '')
self.assertEqual(str(nts), '')
self.assertEqual(unicode(nts), '')
def roundtrip_serialization(obj):
"""Returns a deep copy of an object, via serializing it
see http://weblogs.java.net/blog/emcmanus/archive/2007/04/cloning_java_ob.html
"""
output = ByteArrayOutputStream()
serializer = CloneOutput(output)
serializer.writeObject(obj)
serializer.close()
input = ByteArrayInputStream(output.toByteArray())
unserializer = CloneInput(input, serializer) # to get the list of classes seen, in order
return unserializer.readObject()
class CloneOutput(ObjectOutputStream):
def __init__(self, output):
ObjectOutputStream.__init__(self, output)
self.classQueue = deque()
def annotateClass(self, c):
self.classQueue.append(c)
def annotateProxyClass(self, c):
self.classQueue.append(c)
class CloneInput(ObjectInputStream):
def __init__(self, input, output):
ObjectInputStream.__init__(self, input)
self.output = output
def resolveClass(self, obj_stream_class):
return self.output.classQueue.popleft()
def resolveProxyClass(self, interfaceNames):
return self.output.classQueue.popleft()
class SerializationTest(unittest.TestCase):
def test_java_serialization(self):
date_list = [Date(), Date()]
self.assertEqual(date_list, roundtrip_serialization(date_list))
def test_java_serialization_pycode(self):
def universal_answer():
return 42
serialized_code = roundtrip_serialization(universal_answer.func_code)
self.assertEqual(eval(serialized_code), universal_answer())
def test_java_serialization_pyfunction(self):
# Not directly supported due to lack of general utility
# (globals will usually be in the function object in
# func_globals), and problems with unserialization
# vulnerabilities. Users can always subclass from PyFunction
# for specific cases, as seen in PyCascading
import new
def f():
return 6 * 7 + max(0, 1, 2)
# However, using the new module, it's possible to create a
# function with no globals, which means the globals will come
# from the current context
g = new.function(f.func_code, {}, "g")
# But still forbid Java deserialization of this function
# object. Use pickling or other support instead.
with self.assertRaises(UnsupportedOperationException):
roundtrip_serialization(g)
def test_builtin_names(self):
import __builtin__
names = [x for x in dir(__builtin__)]
self.assertEqual(names, roundtrip_serialization(names))
class CopyTest(unittest.TestCase):
def test_copy(self):
fruits = ArrayList(["apple", "banana"])
fruits_copy = copy.copy(fruits)
self.assertEqual(fruits, fruits_copy)
self.assertNotEqual(id(fruits), id(fruits_copy))
def test_deepcopy(self):
items = ArrayList([ArrayList(["apple", "banana"]),
ArrayList(["trs80", "vic20"])])
items_copy = copy.deepcopy(items)
self.assertEqual(items, items_copy)
self.assertNotEqual(id(items), id(items_copy))
self.assertNotEqual(id(items[0]), id(items_copy[0]))
self.assertNotEqual(id(items[1]), id(items_copy[1]))
def test_copy_when_not_cloneable(self):
bdfl = Person("Guido", "von Rossum")
self.assertRaises(TypeError, copy.copy, bdfl)
# monkeypatching in a __copy__ should now work
Person.__copy__ = lambda p: Person(p.firstName, p.lastName)
copy_bdfl = copy.copy(bdfl)
self.assertEqual(str(bdfl), str(copy_bdfl))
def test_copy_when_not_serializable(self):
bdfl = Person("Guido", "von Rossum")
self.assertRaises(TypeError, copy.deepcopy, bdfl)
# monkeypatching in a __deepcopy__ should now work
Person.__deepcopy__ = lambda p, memo: Person(p.firstName, p.lastName)
copy_bdfl = copy.deepcopy(bdfl)
self.assertEqual(str(bdfl), str(copy_bdfl))
def test_immutable(self):
abc = String("abc")
abc_copy = copy.copy(abc)
self.assertEqual(id(abc), id(abc_copy))
fruits = ArrayList([String("apple"), String("banana")])
fruits_copy = copy.copy(fruits)
self.assertEqual(fruits, fruits_copy)
self.assertNotEqual(id(fruits), id(fruits_copy))
class UnicodeTest(unittest.TestCase):
def test_unicode_conversion(self):
test = unicode(ToUnicode())
self.assertEqual(type(test), unicode)
self.assertEqual(test, u"Circle is 360\u00B0")
class BeanPropertyTest(unittest.TestCase):
def test_issue1833(self):
class TargetClass(object):
def _getattribute(self):
return self.__attribute
def _setattribute(self, value):
self.__attribute = value
attribute = property(_getattribute, _setattribute)
target = TargetClass()
test = Issue1833(target=target)
value = ('bleh', 'blah')
test.value = value
self.assertEqual(target.attribute, value)
def test_main():
test_support.run_unittest(InstantiationTest,
BeanTest,
SysIntegrationTest,
IOTest,
JavaReservedNamesTest,
PyReservedNamesTest,
ImportTest,
ColorTest,
TreePathTest,
BigNumberTest,
JavaStringTest,
JavaDelegationTest,
SecurityManagerTest,
JavaWrapperCustomizationTest,
SerializationTest,
CopyTest,
UnicodeTest,
BeanPropertyTest)
if __name__ == "__main__":
test_main()
|