コード例 #1
0
ファイル: test_array.py プロジェクト: morristech/chaquopy
    def test_str_repr(self):
        Object = jclass("java.lang.Object")
        for func in [str, repr]:
            self.assertEqual("cast('[Z', None)",
                             func(cast(jarray(jboolean), None)))
            self.assertEqual("cast('[[Z', None)",
                             func(cast(jarray(jarray(jboolean)), None)))
            self.assertEqual("cast('[Ljava/lang/Object;', None)",
                             func(cast(jarray(Object), None)))
            self.assertEqual("cast('[[Ljava/lang/Object;', None)",
                             func(cast(jarray(jarray(Object)), None)))

            self.assertEqual("jarray('Z')([])", func(jarray(jboolean)([])))
            self.assertEqual("jarray('Ljava/lang/Object;')([])",
                             func(jarray(Object)([])))

            self.assertEqual("jarray('Z')([True])",
                             func(jarray(jboolean)([True])))
            self.assertEqual("jarray('Z')([True])",
                             func(jarray(jboolean)((True, ))))
            self.assertEqual("jarray('Z')([True, False])",
                             func(jarray(jboolean)([True, False])))
            self.assertEqual(
                "jarray('[Z')([[True], [False, True]])",
                func(jarray(jarray(jboolean))([[True], [False, True]])))
コード例 #2
0
    def test_unimplemented(self):
        class A(dynamic_proxy(TP.Adder)):
            pass

        with self.assertRaisesRegexp(PyException,
                                     r"TestProxy\$Adder.add is abstract"):
            cast(TP.Adder, A()).add(5)
コード例 #3
0
    def test_basic(self):
        class AddN(dynamic_proxy(TP.Adder)):
            def __init__(self, n):
                super(AddN, self).__init__()
                self.n = n

            def add(self, x):
                return self.n + x

        a2, a3 = AddN(2), AddN(3)
        self.assertEqual(2, a2.n)
        self.assertEqual(
            5,
            cast(TP.Adder,
                 a2).add(3))  # cast() ensures the call goes through Java.
        self.assertEqual(6, cast(TP.Adder, a3).add(3))
        self.assertEqual(5, cast(TP.Adder, a2).add(3))

        from .test_utils import Object_names
        Proxy_names = Object_names | {
            "getInvocationHandler", "getProxyClass", "isProxyClass",
            "newProxyInstance", "h"
        }  # reflect.Proxy instance field
        Adder_names = Object_names | {"constant", "add"}
        AddN_names = Proxy_names | Adder_names
        self.assertDir(TP.Adder, Adder_names)
        self.assertDir(AddN, AddN_names)

        AddN_instance_names = AddN_names | {"n"}  # Python instance field
        self.assertDir(a2, AddN_instance_names)
        a2.foo = 42
        self.assertDir(a2, AddN_instance_names | {"foo"})
コード例 #4
0
    def test_object_methods_final(self):
        from java.lang import IllegalMonitorStateException

        class C(dynamic_proxy(TP.Adder)):
            def wait(self):
                return "Python override"

        c = C()
        self.assertEqual("Python override", c.wait())
        with self.assertRaises(IllegalMonitorStateException):
            cast(TP.Adder, c).wait()
コード例 #5
0
ファイル: test_overload.py プロジェクト: qjoner/chaquopy
    def test_class(self):
        Parent = jclass("com.chaquo.python.TestOverload$Parent")
        Child = jclass("com.chaquo.python.TestOverload$Child")
        Object = jclass("java.lang.Object")
        Float = jclass("java.lang.Float")
        String = jclass("java.lang.String")
        Integer = jclass("java.lang.Integer")
        s = String()
        i = Integer(42)
        f = Float(1.23)
        child = Child()
        parent = Parent()

        self.assertEqual(parent.resolve(s), 'Parent Object')
        self.assertEqual(parent.resolve(i), 'Parent Integer')
        self.assertEqual(parent.resolve(f), 'Parent Object')
        self.assertEqual(parent.resolve(f, s), 'Parent Object, String')

        self.assertEqual(child.resolve(s), 'Child String')
        self.assertEqual(child.resolve(i), 'Child Integer')
        self.assertEqual(child.resolve(f), 'Child Object')
        self.assertEqual(child.resolve(cast(Object, s)), 'Child Object')
        self.assertEqual(child.resolve(cast(String, cast(Object, s))),
                         'Child String')

        # Casting of None
        with self.ambiguous:
            child.resolve(None)
        self.assertEqual(child.resolve(cast(String, None)), 'Child String')
        self.assertEqual(child.resolve(cast(Object, None)), 'Child Object')
        self.assertEqual(child.resolve(cast(String, cast(Object, None))),
                         'Child String')

        self.assertEqual(child.resolve(s, i), 'Child String, Object')
        self.assertEqual(child.resolve(i, s), 'Parent Object, String')
        with self.inapplicable:
            child.resolve(i, i)

        # Casting of method parameters
        with self.ambiguous:
            child.resolve(s, s)
        self.assertEqual(child.resolve(cast(Object, s), s),
                         'Parent Object, String')
        self.assertEqual(child.resolve(s, cast(Object, s)),
                         'Child String, Object')

        # Casting of object on which method is called should limit visibility of overloads, but
        # subclass overrides of visible overloads should still be called.
        child_Parent = cast(Parent, child)
        self.assertEqual(child_Parent.resolve(s), 'Child Object')
        self.assertEqual(child_Parent.resolve(s, s), 'Parent Object, String')
        with self.inapplicable:
            child_Parent.resolve(s, i)
コード例 #6
0
ファイル: test_reflect.py プロジェクト: samc30496/chaquopy
    def test_call_interface(self):
        CI = TR.CallInterface

        # No interfaces.
        with self.no_fi():
            CI.NoInterfaces()()

        # A non-functional interface.
        with self.no_fi():
            CI.NoMethods()()
        with self.no_fi():
            CI.TwoMethods()()

        # A single functional interface.
        self.assertEqual("A1.a", CI.A1()())
        self.assertEqual("Aint.a 42", CI.Aint()(42))

        # Multiple functional interfaces with the same method.
        self.assertEqual("A1A2.a", CI.A1A2()())

        # Multiple functional interfaces with different method names.
        a1b1 = CI.A1B()
        with self.multi_fi(CI.IA1, CI.IB):
            a1b1()
        self.assertEqual("A1B.a", cast(CI.IA1, a1b1)())
        self.assertEqual("A1B.b", cast(CI.IB, a1b1)())

        # Multiple functional interfaces with the same method name but different signatures.
        a1aint = CI.A1Aint()
        with self.multi_fi(CI.IA1, CI.IAint):
            a1aint()
        self.assertEqual("A1Aint.a", cast(CI.IA1, a1aint)())
        self.assertEqual("A1Aint.a 42", cast(CI.IAint, a1aint)(42))

        # Both functional and non-functional interfaces.
        self.assertEqual("A1TwoMethods.a", CI.A1TwoMethods()())

        # An abstract class which would be functional if it was an interface.
        with self.no_fi():
            CI.C()()

        # Public Object methods don't stop an interface from being functional, but protected
        # Object methods do.
        self.assertEqual("PublicObjectMethod.a", CI.PublicObjectMethod()())
        with self.no_fi():
            CI.ProtectedObjectMethod()()

        # If an interface declares one method, and a sub-interface adds a second one, then
        # the sub-interface is not functional.
        ab = CI.AB()
        self.assertEqual("AB.a", ab())
        self.assertEqual("AB.a", cast(CI.IAB, ab)())
コード例 #7
0
    def test_varargs(self):
        obj = jclass("com.chaquo.python.TestOverload$Varargs")()

        self.assertEqual("", obj.resolve_empty_single_I())
        self.assertEqual("int... []", obj.resolve_empty_single_I([]))
        self.assertEqual("int... null", obj.resolve_empty_single_I(None))
        self.assertEqual("int 1", obj.resolve_empty_single_I(1))
        self.assertEqual("int... [1]", obj.resolve_empty_single_I([1]))
        self.assertEqual("int... [1, 2]", obj.resolve_empty_single_I(1, 2))
        self.assertEqual("int... [1, 2]", obj.resolve_empty_single_I([1, 2]))

        self.assertEqual("int... []", obj.resolve_ID())  # int is more specific than double.
        with self.ambiguous:
            obj.resolve_ID(None)                    # But int[] is not more specific than double[].
        self.assertEqual("int... null", obj.resolve_ID(cast(jarray(jint), None)))
        self.assertEqual("double... null", obj.resolve_ID(cast(jarray(jdouble), None)))
        with self.inapplicable:
            obj.resolve_ID(None, None)
        self.assertEqual("int 42", obj.resolve_ID(42))
        self.assertEqual("double 42.0", obj.resolve_ID(42.0))
        self.assertEqual("double... [1.0, 2.0]", obj.resolve_ID(jarray(jdouble)([1, 2])))
        self.assertEqual("double... [1.0, 2.0]", obj.resolve_ID(1.0, 2.0))
        self.assertEqual("double... [1.0, 2.0]", obj.resolve_ID(1, 2.0))
        self.assertEqual("double... [1.0, 2.0]", obj.resolve_ID(1.0, 2))

        Long = jclass("java.lang.Long")
        with self.ambiguous:
            obj.resolve_I_Long()        # Neither int nor Long are more specific.
        with self.ambiguous:
            obj.resolve_I_Long(None)    # Neither int[] nor Long[] are more specific.
        self.assertEqual("Long... [null, null]", obj.resolve_I_Long(None, None))
        with self.ambiguous:
            obj.resolve_I_Long(42)
        with self.inapplicable:
            obj.resolve_I_Long(42.0)
        self.assertEqual("int... [42]", obj.resolve_I_Long(jint(42)))
        self.assertEqual("Long... [42]", obj.resolve_I_Long(jlong(42)))
        self.assertEqual("Long... [42]", obj.resolve_I_Long(Long(42)))

        Number = jclass("java.lang.Number")
        # Long[] is more specific than Number[].
        self.assertEqual("Long... []", obj.resolve_Number_Long())
        self.assertEqual("Long... [42]", obj.resolve_Number_Long(42))
        self.assertEqual("Long... null", obj.resolve_Number_Long(None))
        self.assertEqual("Long... [null]", obj.resolve_Number_Long([None]))
        self.assertEqual("Long... [null, null]", obj.resolve_Number_Long(None, None))
        self.assertEqual("Number... [42]", obj.resolve_Number_Long(cast(Number, Long(42))))
        self.assertEqual("Number... null", obj.resolve_Number_Long(cast(jarray(Number), None)))
        self.assertEqual("Number... [null]", obj.resolve_Number_Long(cast(Number, None)))
        self.assertEqual("Number... [42]", obj.resolve_Number_Long(jarray(Number)([42])))
        self.assertEqual("Number... [null]", obj.resolve_Number_Long(jarray(Number)([None])))
コード例 #8
0
    def test_exception_indirect(self):
        from java.lang import Integer, NumberFormatException

        ref_line = traceback.extract_stack()[-1][
            1]  # Line number of THIS line.

        class E(dynamic_proxy(TP.Exceptions)):
            def parse(self, s):
                return self.indirect_parse(s)

            def indirect_parse(self, s):
                return Integer.parseInt(s)

        e_cast = cast(TP.Exceptions, E())

        self.assertEqual(42, e_cast.parse("42"))
        try:
            e_cast.parse("abc")
        except NumberFormatException as e:
            self.assertHasFrames(
                e,
                [("java.lang.Integer", "parseInt", None, None),
                 ("<python>.chaquopy.test.test_proxy", "indirect_parse",
                  "test_proxy.py", ref_line + 5),
                 ("<python>.chaquopy.test.test_proxy", "parse",
                  "test_proxy.py", ref_line + 3),
                 ("com.chaquo.python.PyObject", "callAttrThrows", None, None)])
        else:
            self.fail()
コード例 #9
0
ファイル: test_reflect.py プロジェクト: yqq836438958/chaquopy
    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())
コード例 #10
0
ファイル: test_reflect.py プロジェクト: yqq836438958/chaquopy
    def test_interface(self):
        with self.assertRaisesRegexp(
                TypeError, "Interface is abstract and cannot be instantiated"):
            TR.Interface()

        self.assertEqual("Interface constant", TR.Interface.iConstant)
        with self.assertRaisesRegexp(AttributeError, "final"):
            TR.Interface.iConstant = "not constant"

        c = TR.Child()
        abstract = self.assertRaisesRegexp(
            NotImplementedError, "Interface.iMethod is abstract "
            "and cannot be called")
        with abstract:
            TR.Interface.iMethod()
        with abstract:
            TR.Interface.iMethod(c)

        # Getting an Object method directly from an interface class should return the Object
        # implementation.
        self.assertRegexpMatches(TR.Interface.toString(c),
                                 r"^com.chaquo.python.TestReflect\$Child@")

        # But calling an Object method through an interface cast should be done virtually.
        self.assertEqual("Child object", cast(TR.Interface, c).toString())
コード例 #11
0
ファイル: test_reflect.py プロジェクト: samc30496/chaquopy
    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)))
コード例 #12
0
    def test_python_base(self):
        class B(object):
            def forty_two(self):
                return 42

        class C(dynamic_proxy(TP.Adder), B):
            def add(self, x):
                return x + self.forty_two()

        self.assertEqual(47, cast(TP.Adder, C()).add(5))
コード例 #13
0
    def test_gc(self):
        from .pyobjecttest import DelTrigger as DT

        test = self

        class A(dynamic_proxy(TP.Adder)):
            def __init__(self, n):
                self.before_init_n = n
                test.assertEqual(n, self.before_init_n)
                super(A, self).__init__()
                self.after_init_n = -n
                self.dt = DT()

            def add(self, x):
                return self.before_init_n + x

        DT.reset()
        a = A(5)
        DT.assertTriggered(self, False)
        TP.a1 = a
        a = None
        DT.assertTriggered(self, False)
        a = TP.a1
        self.assertIsInstance(a, A)
        self.assertEqual(5, a.before_init_n)
        self.assertEqual(-5, a.after_init_n)
        self.assertEqual(7, cast(TP.Adder, a).add(2))

        a_Adder = cast(TP.Adder, a)
        self.assertNotIsInstance(a_Adder, A)
        self.assertFalse(hasattr(a_Adder, "before_init_n"))
        a = None
        DT.assertTriggered(self, False)
        a = cast(A, a_Adder)
        self.assertIsInstance(a, A)
        self.assertEqual(5, a.before_init_n)
        a_Adder = None

        TP.a1 = None
        DT.assertTriggered(self, False)
        a = None
        DT.assertTriggered(self, True)
コード例 #14
0
    def test_use_before_init(self):
        class A(dynamic_proxy(TP.Adder)):
            def __init__(self):
                pass

        a = A()
        error = self.assertRaisesRegexp(
            AttributeError, "'A' object's superclass __init__ must be "
            "called before using it as a Java object")
        with error:
            TP.a1 = a
        with error:
            a.toString()
        with error:
            cast(TP.Adder, a)

        super(A, a).__init__()
        TP.a1 = a
        a.toString()
        cast(TP.Adder, a)
コード例 #15
0
ファイル: test_reflect.py プロジェクト: samc30496/chaquopy
    def test_call_interface_default(self):
        CI = TR.CallInterface
        CID = TR.CallInterfaceDefault

        # If an interface declares two methods, and a sub-interface provides a default
        # implementation for one of them, then the sub-interface is functional.
        om = CID.OneMethod()
        self.assertEqual("IOneMethod.a", om.a())
        self.assertEqual("OneMethod.b", om.b())
        self.assertEqual("OneMethod.b", om())

        # If an interface declares one method, and a sub-interface provides a default
        # implementation of it while also adding a second method, then both interfaces are
        # functional.
        abd = CID.ABDefault()
        self.assertEqual("IABDefault.a", abd.a())
        self.assertEqual("ABDefault.b", abd.b())
        with self.multi_fi(CID.IABDefault, CI.IA1):
            abd()
        self.assertEqual("IABDefault.a", cast(CI.IA1, abd)())
        self.assertEqual("ABDefault.b", cast(CID.IABDefault, abd)())
コード例 #16
0
ファイル: test_proxy.py プロジェクト: theteebox/chaquopy
    def test_exception(self):
        from java.io import FileNotFoundException, EOFException
        from java.lang import RuntimeException
        from java.lang.reflect import UndeclaredThrowableException
        from com.chaquo.python import PyException

        ref_line_no = traceback.extract_stack()[-1][
            1]  # Line number of THIS line.

        class E(dynamic_proxy(TP.Exceptions)):
            def fnf(self):
                raise E.exc_cls("fnf")

        e_cast = cast(TP.Exceptions, E())

        fnf_frames = [("<python>.chaquopy.test.test_proxy", "fnf",
                       "test_proxy.py", ref_line_no + 3),
                      ("com.chaquo.python.PyObject", "callAttrThrows", None,
                       None),
                      ("com.chaquo.python.PyInvocationHandler", "invoke",
                       "PyInvocationHandler.java", None)]

        def assertFnfThrows(message,
                            throw_cls,
                            catch_cls=None,
                            check_cause=False):
            if catch_cls is None:
                catch_cls = throw_cls
            E.exc_cls = throw_cls
            try:
                e_cast.fnf()
            except catch_cls as e:
                # There should be no chaining at the Python level.
                self.assertIsNone(e.__cause__)
                self.assertTrue(e.__suppress_context__)

                check_e = e.getCause() if check_cause else e
                self.assertEqual(message, check_e.getMessage())
                self.assertHasFrames(check_e, fnf_frames)
            else:
                self.fail()

        assertFnfThrows("fnf",
                        FileNotFoundException)  # Declared checked exception
        assertFnfThrows(
            "fnf",
            EOFException,  # Undeclared checked exception
            UndeclaredThrowableException,
            check_cause=True)
        assertFnfThrows("fnf", RuntimeException)  # Unchecked exception
        assertFnfThrows("TypeError: fnf", TypeError,
                        PyException)  # Python exception
コード例 #17
0
def scale_data(raw_data, load_scaler=False, save_scaler=False):
    '''
    :param raw_data: 2D array if before reshape [n,9]  if after gen feature [n, 64]
    :return: scaled data by column or None
    '''
    python_raw_data = java.cast(java.jarray(java.jarray(java.jfloat)), raw_data)
    files_dir = str(Python.getPlatform().getApplication().getFilesDir())
    X = np.array(python_raw_data)
    if load_scaler:
        scaler_min_max_array = np.load(join(files_dir,"scaler.npy"))
        return _scale_data(X, data_min_=scaler_min_max_array[0], data_max_=scaler_min_max_array[1])
    else:
        return _scale_data(X, save_scaler=save_scaler)
コード例 #18
0
    def test_exception_in_init(self):
        from java.lang import Runnable
        ref_line_no = traceback.extract_stack()[-1][
            1]  # Line number of THIS line.

        class C(dynamic_proxy(Runnable)):
            def run(self):
                from . import exception_in_init  # noqa: F401

        c = C()
        try:
            cast(Runnable, c).run()
        except PyException as e:
            self.assertEqual("ValueError: Exception in __init__.py",
                             e.getMessage())
            self.assertHasFrames(
                e,
                [("<python>.chaquopy.test.exception_in_init", "<module>",
                  "__init__.py", 3),
                 ("<python>.java.chaquopy", "import_override", "import.pxi",
                  None),
                 ("<python>.chaquopy.test.test_proxy", "run", "test_proxy.py",
                  ref_line_no + 3),
                 ("com.chaquo.python.PyObject", "callAttrThrows", None, None)])
コード例 #19
0
ファイル: test_reflect.py プロジェクト: yqq836438958/chaquopy
    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)))
コード例 #20
0
    def test_args(self):
        from java.lang import String
        test = self

        class C(dynamic_proxy(TP.Args)):
            def tooMany(self):
                pass

            def tooFew(self, a):
                pass

            def addDuck(self, a, b):
                return a + b

            def star(self, *args):
                return ",".join(args)

            def varargs(self, delim, args):
                test.assertIsInstance(args, jarray(String))
                return delim.join(args)

        c = C()
        c_Args = cast(TP.Args, c)

        with self.assertRaisesRegexp(PyException, args_error(1, 2)):
            c_Args.tooMany(42)
        with self.assertRaisesRegexp(PyException, args_error(2, 1)):
            c_Args.tooFew()

        self.assertEqual(3, c_Args.addDuck(jint(1), jint(2)))
        self.assertAlmostEqual(3.5, c_Args.addDuck(jfloat(1), jfloat(2.5)))
        self.assertEqual("helloworld", c_Args.addDuck("hello", "world"))

        self.assertEqual("", c_Args.star())
        self.assertEqual("hello", c_Args.star("hello"))
        self.assertEqual("hello,world", c_Args.star("hello", "world"))
        with self.assertRaisesRegexp(TypeError, "cannot be applied"):
            c_Args.star("hello", "world", "again")
        self.assertEqual("hello,world,again", c.star("hello", "world",
                                                     "again"))

        with self.assertRaisesRegexp(TypeError, args_error(1, 0,
                                                           varargs=True)):
            c_Args.varargs()
        self.assertEqual("", c_Args.varargs(":"))
        self.assertEqual("hello", c_Args.varargs("|", "hello"))
        self.assertEqual("hello|world", c_Args.varargs("|", "hello", "world"))
コード例 #21
0
    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)
コード例 #22
0
ファイル: test_overload.py プロジェクト: pyscrape/chaquopy
    def test_array(self):
        obj = jclass("com.chaquo.python.TestOverload$TestArray")()

        # Arrays of primitives are always ambiguous, irrespective of the values in the array.
        for l in [None, [True, False], [1, 2]]:
            with self.ambiguous:
                obj.resolve_ZB(l)
        self.assertEqual("boolean[] [true, false]",
                         obj.resolve_ZB(jarray(jboolean)([True, False])))
        self.assertEqual("byte[] [1, 2]",
                         obj.resolve_ZB(jarray(jbyte)([1, 2])))
        self.assertEqual("boolean[] []", obj.resolve_ZB(jarray(jboolean)([])))
        self.assertEqual("byte[] []", obj.resolve_ZB(jarray(jbyte)([])))
        self.assertEqual("boolean[] null",
                         obj.resolve_ZB(cast(jarray(jboolean), None)))
        self.assertEqual("byte[] null",
                         obj.resolve_ZB(cast(jarray(jbyte), None)))

        # Arrays of parent/child classes: prefer the most derived class.
        Object = jclass("java.lang.Object")
        Integer = jclass("java.lang.Integer")
        self.assertEqual("Number[] [1, 2]", obj.resolve_Object_Number([1, 2]))
        self.assertEqual("Number[] [1, 2]",
                         obj.resolve_Object_Number(jarray(Integer)([1, 2])))
        self.assertEqual("Object[] [1, 2]",
                         obj.resolve_Object_Number(jarray(Object)([1, 2])))

        # Arrays of sibling classes are always ambiguous.
        Long = jclass("java.lang.Long")
        with self.ambiguous:
            obj.resolve_Integer_Long([1, 2])
        self.assertEqual("Integer[] [1, 2]",
                         obj.resolve_Integer_Long(jarray(Integer)([1, 2])))
        self.assertEqual("Long[] [1, 2]",
                         obj.resolve_Integer_Long(jarray(Long)([1, 2])))

        # Arrays are preferred over Object.
        array_Z = jarray(jboolean)([True, False])
        self.assertEqual("boolean[] null", obj.resolve_Z_Object(None))
        self.assertEqual("Object null",
                         obj.resolve_Z_Object(cast(Object, None)))
        self.assertEqual("boolean[] [true, false]",
                         obj.resolve_Z_Object([True, False]))
        self.assertEqual("boolean[] [true, false]",
                         obj.resolve_Z_Object(array_Z))
        self.assertEqual("Object [true, false]",
                         obj.resolve_Z_Object(cast(Object, array_Z)))
        self.assertEqual(
            "boolean[] [true, false]",
            obj.resolve_Z_Object(cast(jarray(jboolean), cast(Object,
                                                             array_Z))))
コード例 #23
0
    def test_return(self):
        from java.lang import Runnable, ClassCastException, NullPointerException

        class C(dynamic_proxy(Runnable, TP.Adder, TP.GetString)):
            def run(self):
                return self.result  # returns void

            def add(self, x):
                return self.result  # returns int

            def getString(self):
                return self.result  # returns String

        c = C()
        c_Runnable, c_Adder, c_GS = [
            cast(cls, c) for cls in [Runnable, TP.Adder, TP.GetString]
        ]
        c.result = None
        self.assertIsNone(c_Runnable.run())
        with self.assertRaises(NullPointerException):
            c_Adder.add(42)
        self.assertIsNone(c_GS.getString())

        c.result = 42
        with self.assertRaisesRegexp(ClassCastException,
                                     "Cannot convert int object to void"):
            c_Runnable.run()
        self.assertEqual(42, c_Adder.add(99))
        with self.assertRaisesRegexp(
                ClassCastException, "Cannot convert int object to "
                "java.lang.String"):
            c_GS.getString()

        c.result = "hello"
        with self.assertRaisesRegexp(ClassCastException,
                                     "Cannot convert str object to void"):
            c_Runnable.run()
        with self.assertRaisesRegexp(
                ClassCastException, "Cannot convert str object to "
                "java.lang.Integer"):
            c_Adder.add(99)
        self.assertEqual("hello", c_GS.getString())
コード例 #24
0
    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())
コード例 #25
0
    def test_object_methods_unimplemented(self):
        class Unimplemented(dynamic_proxy(TP.Adder)):
            pass

        a1, a2 = Unimplemented(), Unimplemented()

        ts = cast(TP.Adder, a1).toString()
        self.assertRegexpMatches(ts, r"\$Proxy.*@")
        self.assertEqual(ts, str(a1))
        self.assertNotEqual(str(a1), str(a2))

        self.assertTrue(a1.equals(a1))
        self.assertFalse(a1.equals(a2))
        self.assertTrue(a1 == a1)
        self.assertFalse(a1 == a2)
        self.assertNotEqual(a1.hashCode(), a2.hashCode())
        self.assertNotEqual(hash(a1), hash(a2))

        a1.foo = 99
        for name in ["toString", "equals", "hashCode"]:
            with self.assertRaisesRegexp(AttributeError,
                                         name + " is not a field"):
                setattr(a1, name, 99)
コード例 #26
0
def reshape(raw_data, window_size, step_width):
    '''
    input: 
        [n_input,9]
            n_input = n_sec * frequence
            9, data from 3 sensors
    
    output: 
        [n_output, window_size, 9]
            n_output = 
    '''
    python_raw_data = java.cast(java.jarray(java.jarray(java.jfloat)), raw_data)
    raw_data = np.array(python_raw_data)
    new_feat_count = ((raw_data.shape[0] - window_size) // step_width) + 1
    reshaped_feat = np.empty((new_feat_count, window_size, 9))
    for idx, window in enumerate(
        utils_gen_windows(raw_data.shape[0], window_size, step_width)
    ):
        new_row = raw_data[window[0] : window[1]]
        if idx < new_feat_count:
            reshaped_feat[idx, :] = new_row

    return reshaped_feat
コード例 #27
0
ファイル: test_array.py プロジェクト: morristech/chaquopy
    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)
コード例 #28
0
ファイル: nfc.py プロジェクト: danielsocials/python-trezor
 def __init__(self) -> None:
     self.device = cast(Tag, NFCHandle.device)
     self.handle = None  # type: Optional[IsoDep]
コード例 #29
0
ファイル: test_reflect.py プロジェクト: samc30496/chaquopy
    def test_inheritance(self):
        Object = jclass("java.lang.Object")
        Interface = self.nested_cls("Interface")
        SubInterface = self.nested_cls("SubInterface")
        Parent = self.nested_cls("Parent")
        Child = self.nested_cls("Child")

        self.assertEqual((object,), Object.__bases__)
        self.assertEqual((Object,), Interface.__bases__)
        self.assertEqual((Interface,), SubInterface.__bases__)
        self.assertEqual((Object,), Parent.__bases__)
        self.assertEqual((Parent, Interface), Child.__bases__)

        from .test_utils import Object_names
        Interface_names = Object_names | {"iConstant", "iMethod"}
        Parent_names = Object_names | {"pStaticField", "pField", "pStaticMethod", "pMethod",
                                       "oStaticField", "oField", "oStaticMethod", "oMethod"}
        Child_names = Parent_names | Interface_names

        self.assertDir(Object, Object_names)
        self.assertDir(Interface, Interface_names)
        self.assertDir(Parent, Parent_names)
        self.assertDir(Child, Child_names)

        self.assertEqual("Interface constant", Child.iConstant)
        self.verify_field(Child, "pStaticField", "Parent static field")
        self.assertEqual("Parent static method", Child.pStaticMethod())
        self.verify_field(Child, "oStaticField", "Overridden static field")
        self.assertEqual("Overridden static method", Child.oStaticMethod())

        c = Child()
        self.assertTrue(isinstance(c, Child))
        self.assertTrue(isinstance(c, Parent))
        self.assertTrue(isinstance(c, Interface))
        self.assertTrue(isinstance(c, Object))
        self.assertDir(c, Child_names)
        self.assertEqual("Interface constant", c.iConstant)
        self.assertEqual("Implemented method", c.iMethod())
        self.verify_field(c, "pStaticField", "Parent static field")
        self.verify_field(c, "pField", "Parent field")
        self.assertEqual("Parent static method", c.pStaticMethod())
        self.assertEqual("Parent method", c.pMethod())
        self.verify_field(c, "oStaticField", "Overridden static field")
        self.verify_field(c, "oField", "Overridden field")
        self.assertEqual("Overridden static method", c.oStaticMethod())
        self.assertEqual("Overridden method", c.oMethod())

        c_Interface = cast(Interface, c)
        self.assertFalse(isinstance(c_Interface, Child))
        self.assertFalse(isinstance(c_Interface, Parent))
        self.assertTrue(isinstance(c_Interface, Interface))
        self.assertTrue(isinstance(c_Interface, Object))
        self.assertDir(c_Interface, Interface_names)
        self.assertEqual("Interface constant", c_Interface.iConstant)
        self.assertEqual("Implemented method", c_Interface.iMethod())

        c_Parent = cast(Parent, c)
        self.assertFalse(isinstance(c_Parent, Child))
        self.assertTrue(isinstance(c_Parent, Parent))
        self.assertFalse(isinstance(c_Parent, Interface))
        self.assertTrue(isinstance(c_Parent, Object))
        self.assertDir(c_Parent, Parent_names)
        with self.assertRaisesRegex(AttributeError, "has no attribute"):
            c_Parent.iConstant
        with self.assertRaisesRegex(AttributeError, "has no attribute"):
            c_Parent.iMethod()
        self.verify_field(c_Parent, "pStaticField", "Parent static field")
        self.verify_field(c_Parent, "pField", "Parent field")
        self.assertEqual("Parent static method", c_Parent.pStaticMethod())
        self.assertEqual("Parent method", c_Parent.pMethod())
        self.verify_field(c_Parent, "oStaticField", "Non-overridden static field")
        self.verify_field(c_Parent, "oField", "Non-overridden field")
        self.assertEqual("Non-overridden static method", c_Parent.oStaticMethod())
        self.assertEqual("Overridden method", c_Parent.oMethod())
コード例 #30
0
ファイル: test_reflect.py プロジェクト: samc30496/chaquopy
    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())