def test_cast(self): from java.lang import Boolean, Object b = Boolean(True) b_Object = cast(Object, b) self.assertIsNot(b, b_Object) self.assertEqual(b, b_Object) self.assertIs(Boolean.getClass(), b.getClass()) self.assertIs(Boolean.getClass(), b_Object.getClass()) self.assertIsNot(Object.getClass(), b_Object.getClass()) self.assertIs(b_Object, cast(Object, b)) self.assertIs(b, cast(Boolean, b_Object)) for obj in [Boolean, "Ljava/lang/Boolean;"]: with self.subTest(obj=obj): with self.assertRaisesRegex(TypeError, "cannot create java.lang.Boolean " "proxy from java.lang.Object instance"): cast(obj, Object()) with self.assertRaisesRegex(jclass("java.lang.NoClassDefFoundError"), "java.lang.Nonexistent"): cast("Ljava/lang/Nonexistent;", Object()) with self.assertRaisesRegex(ValueError, "Invalid JNI signature: 'java.lang.Object'"): cast("java.lang.Object", Object()) for obj in [0, True, None, int, str]: with self.subTest(obj=obj): with self.assertRaisesRegex(TypeError, f"{obj!r} is not a Java type"): cast(obj, Object())
def __init__(self, file): Object.__init__(self) self.file = file self.init() self.read(file)
def test_explicit(self): "Tests explicit method calls, please don't do this in application code" x = Object() slock = x.synchronized() slock.__enter__() y = 5 + 3 slock.__exit__() self.assertEqual(y, 8)
def test_access_call(self): from java.util import ArrayList start_memory = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss obj = Object() for i in xrange(0,iterations,1): b = obj.hashCode() end_memory = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss if start_memory*failure_threshold < end_memory: percent = end_memory*100/start_memory - 100 raise Exception('Called methods are leaking memory, process size increased %d%% over %d iterations.' % (percent, iterations))
def __init__(self, resources): Object.__init__(self) # Obtain the keys and values to be used to create the symbols # dictionary from the application's resources. symbols = resources.getStringArray(R.array.symbols) resourceIDs = resources.getIntArray(R.array.resourceIDs) self.symbols = dict(symbols, resourceIDs)
def test_access_call(self): from java.util import ArrayList start_memory = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss obj = Object() for i in xrange(0, iterations, 1): b = obj.hashCode() end_memory = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss if start_memory * failure_threshold < end_memory: percent = end_memory * 100 / start_memory - 100 raise Exception( 'Called methods are leaking memory, process size increased %d%% over %d iterations.' % (percent, iterations))
def test_with_exception_unlocks(self): "Tests that the end of the with block will unlock even if an exception occurred" x = Object() slock = x.synchronized() try: with slock: from java.fake import ArrayList except ImportError as exc: pass with self.assertRaises(RuntimeError): # you cannot unlock that which has been unlocked slock.__exit__()
def test_instance(self): with self.assertRaisesRegex(AttributeError, "has no attribute"): self.t.nonexistent with self.assertRaisesRegex(AttributeError, "has no attribute"): self.t.nonexistent = True with self.assertRaisesRegex(AttributeError, "final"): self.t.fieldFinalZ = True with self.assertRaisesRegex(AttributeError, "not a field"): self.t.setZ = True with self.assertRaisesRegex(TypeError, "not callable"): self.t.fieldZ() with self.assertRaisesRegex(TypeError, r"takes 0 arguments \(1 given\)"): self.t.noArgs(True) with self.assertRaisesRegex(TypeError, r"takes at least 1 argument \(0 given\)"): self.t.varargs1() with self.assertRaisesRegex(TypeError, r"takes at least 1 argument \(0 given\)"): self.Test.varargs1(self.t) with self.assertRaisesRegex(TypeError, r"takes 1 argument \(0 given\)"): self.t.setZ() Object = jclass("java.lang.Object") with self.assertRaisesRegex(AttributeError, "static context"): self.Test.fieldZ with self.assertRaisesRegex(AttributeError, "static context"): self.Test.fieldZ = True with self.assertRaisesRegex(TypeError, "must be called with .*TestBasics instance " r"as first argument \(got nothing instead\)"): self.Test.getZ() with self.assertRaisesRegex(TypeError, "must be called with .*TestBasics instance " r"as first argument \(got Object instance instead\)"): self.Test.getZ(Object()) self.assertEqual(False, self.Test.getZ(self.t))
def test_construction(self): from java.lang import Object refcount1 = sys.gettotalrefcount() result = Object() del result refcount2 = sys.gettotalrefcount() self.assertEquals(refcount1, refcount2 - 1)
def test_cast(self): from java.lang import Boolean, Object b = Boolean(True) b_Object = cast(Object, b) self.assertIsNot(b, b_Object) self.assertEqual(b, b_Object) self.assertIs(Boolean.getClass(), b.getClass()) self.assertIs(Boolean.getClass(), b_Object.getClass()) self.assertIsNot(Object.getClass(), b_Object.getClass()) self.assertIs(b_Object, cast(Object, b)) self.assertIs(b, cast(Boolean, b_Object)) with self.assertRaisesRegexp( TypeError, "cannot create java.lang.Boolean proxy from " "java.lang.Object instance"): cast(Boolean, Object())
def convert(value): "Return python object from java Object." if util.BytesRef.instance_(value): return util.BytesRef.cast_(value).utf8ToString() if not Number.instance_(value): return value.toString() if Object.instance_(value) else value value = Number.cast_(value) return value.doubleValue() if Float.instance_(value) or Double.instance_(value) else int(value.longValue())
def test_java_lang_object_methods(self): # Passing a PyFunction to Object.toString, .hashCode, etc # should not result in the function itself being called def return42(): return 42 s = Object.toString(return42) self.assertNotEqual(s, 42) self.assertTrue(s.startswith('<function return42'))
def convert(value): """Return python object from java Object.""" if util.BytesRef.instance_(value): return util.BytesRef.cast_(value).utf8ToString() if not Number.instance_(value): return value.toString() if Object.instance_(value) else value value = Number.cast_(value) return value.doubleValue() if Float.instance_(value) or Double.instance_( value) else int(value.longValue())
def __init__(self, file, name, mode): self.lockerObject = Object() type = Type.WRITE if mode == 'r': type = Type.READ self.file = file locked = FileLocker.lock(self.lockerObject, file, type) # log if not locked, because that's bad super(File, self).__init__(file.getAbsolutePath(), mode)
def __init__(self): Object.__init__(self) # Define low and high tone waveforms. self.low_tone = [] self.high_tone = [] self.gap = [] i = 0 dx = 2 * Math.PI / self.SAMPLES_PER_BIT while i < self.SAMPLES_PER_BIT: low = Math.sin(i * dx) if low >= 0: self.low_tone.add(short(16384)) else: self.low_tone.add(short(-16384)) high = Math.sin(2 * i * dx) if high >= 0: self.high_tone.add(short(16384)) else: self.high_tone.add(short(-16384)) self.gap.add(short(0)) i += 1 # Define a track with a capacity large enough to fit five bytes of # encoded data. # data (bits) bytes per short capacity = 60 * self.SAMPLES_PER_BIT * 2 self.track = AudioTrack(AudioManager.STREAM_MUSIC, self.SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, capacity, AudioTrack.MODE_STREAM) self.track.play()
def parse(code): EOF = Object() ret = None thread = Thread.currentThread() # Evaluate all tokens in code, one by one while not thread.isInterrupted(): r = LispReader.read(LineNumberingPushbackReader(StringReader(code)), False, EOF, False) if EOF == r: break ret = Compiler.eval(r) # Return the result of evaluating the last token return ret
def test_cast(self): Object = jclass("java.lang.Object") Boolean = jclass("java.lang.Boolean") Boolean_array = jarray(Boolean)([True, False]) Boolean_array_Object_array = cast(jarray(Object), Boolean_array) self.assertIsNot(Boolean_array, Boolean_array_Object_array) self.assertEqual(Boolean_array, Boolean_array_Object_array) self.assertIs(Boolean_array_Object_array, cast(jarray(Object), Boolean_array)) self.assertIs(Boolean_array, cast(jarray(Boolean), Boolean_array_Object_array)) Boolean_array_Object = cast(Object, Boolean_array) self.assertIsNot(Boolean_array, Boolean_array_Object) self.assertEqual(Boolean_array, Boolean_array_Object) self.assertIs(Boolean_array_Object, cast(Object, Boolean_array)) self.assertIs(Boolean_array, cast(jarray(Boolean), Boolean_array_Object)) with self.assertRaisesRegexp( TypeError, "cannot create boolean\[\] proxy from " "java.lang.Boolean\[\] instance"): cast(jarray(jboolean), Boolean_array) with self.assertRaisesRegexp( TypeError, "cannot create java.lang.Object\[\] proxy from " "java.lang.Object instance"): cast(jarray(Object), Object()) Object_array = jarray(Object)([]) with self.assertRaisesRegexp( TypeError, "cannot create java.lang.Boolean proxy from " "java.lang.Object\[\] instance"): cast(Boolean, Object_array) with self.assertRaisesRegexp( TypeError, "cannot create java.lang.Boolean\[\] proxy from " "java.lang.Object\[\] instance"): cast(jarray(Boolean), Object_array) Z_array = jarray(jboolean)([True, False]) with self.assertRaisesRegexp( TypeError, "cannot create java.lang.Boolean\[\] proxy from " "boolean\[\] instance"): cast(jarray(Boolean), Z_array) with self.assertRaisesRegexp( TypeError, "cannot create java.lang.Object\[\] proxy from " "boolean\[\] instance"): cast(jarray(Object), Z_array)
def test_identity(self): from java.lang import Object, String Object_klass, String_klass = Object.getClass(), String.getClass() self.assertIsNot(Object_klass, String_klass) self.t.fieldKlass = Object_klass self.assertIs(Object_klass, self.t.fieldKlass) self.t.setKlass(String_klass) self.assertIs(String_klass, self.t.getKlass()) a1, a2 = [jarray(String)(x) for x in [["one", "two"], ["three", "four"]]] self.assertIsNot(a1, a2) self.t.fieldStringArray = a1 self.assertIs(a1, self.t.fieldStringArray) self.t.setStringArray(a2) self.assertIs(a2, self.t.getStringArray())
class TestMethodMemory(unittest.TestCase): def setUp(self): from java.lang import Object self.obj = Object() def test_repeated_call(self): method = self.obj.hashCode test_leak(self, lambda:method(), "Called method") def test_access_call(self): test_leak(self, lambda:self.obj.hashCode(), "Access and call method") def test_access_no_call(self): test_leak(self, lambda:self.obj.hashCode, "Access method")
def test_str_repr(self): Object = jclass('java.lang.Object') String = jclass('java.lang.String') o = Object() object_str = str(o) self.assertRegex(object_str, "^java.lang.Object@") self.assertEqual("<" + object_str + ">", repr(o)) str_u = "abc olé 中文" repr_u = "<java.lang.String '{}'>".format(str_u) s = String(str_u) self.assertEqual(str_u, str(s)) self.assertEqual(repr_u, repr(s)) self.assertEqual("cast('Ljava/lang/Object;', None)", repr(cast(Object, None))) self.assertEqual("cast('Ljava/lang/String;', None)", repr(cast(String, None)))
def test_modify(self): Object = jclass("java.lang.Object") array_Z = jarray(jboolean)([True, False]) with self.assertRaisesRegex(TypeError, "Cannot convert int object to boolean"): array_Z[0] = 1 with self.assertRaisesRegex(TypeError, "Cannot convert Object object to boolean"): array_Z[0] = Object() Boolean = jclass("java.lang.Boolean") array_Boolean = jarray(Boolean)([True, False]) with self.assertRaisesRegex(TypeError, "Cannot convert int object to java.lang.Boolean"): array_Boolean[0] = 1 with self.assertRaisesRegex(TypeError, "Cannot convert int object to java.lang.Boolean"): cast(jarray(Object), array_Boolean)[0] = 1 array_Object = jarray(Object)([True, False]) array_Object[0] = 1 self.assertEqual([1, False], array_Object)
def set_scanner_table_model(self, scanner_issue, issue_name, issue_param, vuln_param): key = issue_name + "." + vuln_param scanner_issue_id = str( scanner_issue.getRequestResponse()).split("@")[1] scanner_table_model = self.scanner_table_models[key] # Using the addRow() method requires that the data type being passed to be of type # Vector() or Object(). Passing a Python object of type list in addRow causes a type # conversion error of sorts which presents as an ArrayOutOfBoundsException. Therefore, # row is an instantiation of Object() to avoid this error. row = Object() row = [ False, issue_param, scanner_issue.getHttpService().getHost(), scanner_issue.getPath(), scanner_issue_id ] try: scanner_table_model.addRow(row) except Exception as e: print e
def test_object_methods_implemented(self): from java.lang import Object class Implemented(dynamic_proxy(TP.Adder)): def toString(self): return "Override " + Object.toString(self) def hashCode(self): return Object.hashCode(self) + 1 def equals(self, other): return True a1, a2 = Implemented(), Implemented() ts = cast(TP.Adder, a1).toString() self.assertRegexpMatches(ts, r"^Override .*\$Proxy.*@") self.assertEqual(ts, str(a1)) self.assertNotEqual(str(a1), str(a2)) self.assertTrue(a1.equals(a1)) self.assertTrue(a1.equals(a2)) self.assertEqual(Object.hashCode(a1) + 1, a1.hashCode())
def test_str_repr(self): Object = jclass('java.lang.Object') String = jclass('java.lang.String') o = Object() object_str = str(o) self.assertRegexpMatches(object_str, "^java.lang.Object@") self.assertEqual("<" + object_str + ">", repr(o)) str_u = u"abc olé 中文" repr_u = u"<java.lang.String '{}'>".format(str_u) s = String(str_u) if sys.version_info[0] < 3: self.assertEqual(str_u.encode("utf-8"), str(s)) self.assertEqual(str_u, unicode(s)) # noqa: F821 self.assertEqual(repr_u.encode("utf-8"), repr(s)) else: self.assertEqual(str_u, str(s)) self.assertEqual(repr_u, repr(s)) self.assertEqual("cast('Ljava/lang/Object;', None)", repr(cast(Object, None))) self.assertEqual("cast('Ljava/lang/String;', None)", repr(cast(String, None)))
def setUp(self): from java.lang import Object self.obj = Object()
class TestPythonRefCounts(unittest.TestCase): def setUp(self): from java.lang import Object self.obj = Object() def test_method_binding(self): refcount1 = sys.gettotalrefcount() result = self.obj.hashCode del result refcount2 = sys.gettotalrefcount() self.assertEquals(refcount1, refcount2 - 1) def test_method_call(self): # First call to hashCode will cache info about the hashCode method self.obj.hashCode() refcount1 = sys.gettotalrefcount() result = self.obj.hashCode() del result refcount2 = sys.gettotalrefcount() self.assertEquals(refcount1, refcount2 - 1) def test_package_import(self): refcount1 = sys.gettotalrefcount() import java.lang as result del result refcount2 = sys.gettotalrefcount() self.assertEquals(refcount1, refcount2 - 1) def test_class_import(self): refcount1 = sys.gettotalrefcount() from java.lang import Object as result del result refcount2 = sys.gettotalrefcount() self.assertEquals(refcount1, refcount2 - 1) def test_construction(self): from java.lang import Object refcount1 = sys.gettotalrefcount() result = Object() del result refcount2 = sys.gettotalrefcount() self.assertEquals(refcount1, refcount2 - 1) def test_field_access(self): from java.lang import System # First time will cache info about the PrintStream class result = System.out del result refcount1 = sys.gettotalrefcount() result = System.out del result refcount2 = sys.gettotalrefcount() self.assertEquals(refcount1, refcount2 - 1) def test_array_creation(self): from jep import jarray from java.lang import Object refcount1 = sys.gettotalrefcount() result = jarray(1, Object) del result refcount2 = sys.gettotalrefcount() self.assertEquals(refcount1, refcount2 - 1) def test_array_assignment(self): from jep import jarray from java.lang import Object arr = jarray(1, Object) refcount1 = sys.gettotalrefcount() arr[0] = self.obj refcount2 = sys.gettotalrefcount() self.assertEquals(refcount1, refcount2 - 1) def test_array_access(self): from jep import jarray from java.lang import Object arr = jarray(1, Object) arr[0] = self.obj refcount1 = sys.gettotalrefcount() result = arr[0] del result refcount2 = sys.gettotalrefcount() self.assertEquals(refcount1, refcount2 - 1) def test_number_compare(self): x = 5 from java.lang import Integer y = Integer(9) refcount1 = sys.gettotalrefcount() result = x < y del result refcount2 = sys.gettotalrefcount() self.assertEquals(refcount1, refcount2 - 1) def test_list_setslice(self): from java.util import ArrayList jlist = ArrayList() for i in range(5): jlist.add(i) refcount1 = sys.gettotalrefcount() jlist[2:4] = [7, 19] refcount2 = sys.gettotalrefcount() self.assertEquals(refcount1, refcount2 - 1) def test_dir_class(self): from java.util import ArrayList refcount1 = sys.gettotalrefcount() result = dir(ArrayList) del result refcount2 = sys.gettotalrefcount() self.assertEquals(refcount1, refcount2 - 1)
def hashCode(self): return Object.hashCode(self) + 1
def toString(self): return "Override " + Object.toString(self)
def __init__(self, time, forecasts): Object.__init__(self) self.time = time self.forecasts = forecasts
def getColumnClass(self, c): return Object.getClass(self.getValueAt(0, c))
def __init__(self, position, view): Object.__init__(self) self.position = position self.view = view
def __init__(self, name, bitmap): Object.__init__(self) self.name = name self.bitmap = bitmap
def test_with(self): "Simple test illustrating basic usage" x = Object() with x.synchronized(): y = 5 + 3 self.assertEqual(y, 8)
def returnsObject(self): return Object()
def test_bad_form(self): "Tests attempting unlock of a non-locked object, please don't do this in application code" x = Object() slock = x.synchronized() with self.assertRaises(RuntimeError): slock.__exit__()