Exemple #1
0
    def test_interface_int_return(self):
        """A Java interface with an int-returning method can be defined in Python and proxied,
        including return value."""
        # To ensure Java can call into our Python proxy object and get an `int` out, we
        # ask AddOne to call a Python class which implements a Java interface with a
        # method to return an `int`.
        #
        # For consistency with previous tests, and to verify that parameter passing works
        # with int-returning interfaces, we rely on an `Example` object to store state.
        ICallbackInt = JavaInterface('org/beeware/rubicon/test/ICallbackInt')

        class GetAndIncrementExampleIntField(ICallbackInt):
            def getInt(self, example):
                example.set_int_field(example.int_field + 1)
                return example.int_field

        implementation = GetAndIncrementExampleIntField()

        # Create two `Example` objects to validate there are no weird surprises about where state goes.
        Example = JavaClass('org/beeware/rubicon/test/Example')
        example1 = Example()
        example2 = Example()

        # Validate that `AddOne` calls our Python `getInt()` implementation. The first number is 35
        # because AddOne adds 1, and getInt() adds 1, and it starts at 33.
        AddOne = JavaClass('org/beeware/rubicon/test/AddOne')
        self.assertEqual(35, AddOne().addOne(implementation, example1))
        self.assertEqual(36, AddOne().addOne(implementation, example1))
        # Validate that implementation mutates example1's state, not example2's state.
        self.assertEqual(35, AddOne().addOne(implementation, example2))
Exemple #2
0
    def test_alternatives(self):
        "A class is aware of it's type hierarchy"
        Example = JavaClass('org/beeware/rubicon/test/Example')

        self.assertEqual(Example.__dict__['_alternates'], [
            b"Lorg/beeware/rubicon/test/Example;",
            b"Lorg/beeware/rubicon/test/BaseExample;",
            b"Ljava/lang/Object;",
        ])

        AbstractCallback = JavaClass(
            'org/beeware/rubicon/test/AbstractCallback')
        self.assertEqual(AbstractCallback.__dict__['_alternates'], [
            b"Lorg/beeware/rubicon/test/AbstractCallback;",
            b"Lorg/beeware/rubicon/test/ICallback;",
            b"Ljava/lang/Object;",
        ])

        String = JavaClass('java/lang/String')

        self.assertEqual(String.__dict__['_alternates'], [
            b"Ljava/lang/String;",
            b"Ljava/io/Serializable;",
            b"Ljava/lang/Comparable;",
            b"Ljava/lang/CharSequence;",
            b"Ljava/lang/Object;",
        ])
Exemple #3
0
 def onCreate(self):
     print("started Python onCreate method")
     self._this = JavaClass(os.environ["ACTIVITY_CLASS_NAME"]).singletonThis
     self.dynamic_layout = dynamic_layout = RelativeLayout(self._this)
     scroll_view = ScrollView(self._this)
     scroll_view.addView(dynamic_layout)
     self._this.setContentView(scroll_view)
     self.button1 = button1 = Button(self._this)
     button1.setText(
         "Kale chips food truck pop-up distillery prism. Craft beer art party copper mug shaman whatever quinoa try-hard synth meditation vexillologist mixtape readymade. Poutine microdosing keffiyeh, offal 8-bit chia twee. Salvia flexitarian coloring book sriracha meggings microdosing brunch vaporware craft beer. Fam green juice everyday carry, pitchfork forage retro health goth. Banjo messenger bag mlkshk VHS mumblecore austin single-origin coffee la croix. Whatever umami lumbersexual poutine organic marfa mustache raclette yuccie try-hard kickstarter tumblr cliche brooklyn food truck."
     )
     at_most_four_hundred = View__MeasureSpec.makeMeasureSpec(
         400, View__MeasureSpec.AT_MOST)
     button1.measure(at_most_four_hundred, View__MeasureSpec.UNSPECIFIED)
     print(
         f"button1 measuredWidth after measure(), {button1.getMeasuredWidth()}"
     )
     self.button2 = button2 = Button(self._this)
     button2.setText("Zounds")
     button2.measure(View__MeasureSpec.UNSPECIFIED,
                     View__MeasureSpec.UNSPECIFIED)
     print(
         f"button2 measuredWidth after measure(), {button2.getMeasuredWidth()}"
     )
     dynamic_layout.addView(
         button1,
         RelativeLayout__LayoutParams(button1.getMeasuredWidth(),
                                      button1.getMeasuredHeight()))
     params = RelativeLayout__LayoutParams(button2.getMeasuredWidth(),
                                           button2.getMeasuredHeight())
     params.topMargin = 3000
     params.leftMargin = button1.getMeasuredWidth() + 70
     dynamic_layout.addView(button2, params)
     print("ended Python onCreate method")
Exemple #4
0
    def test_non_static_access_static(self):
        "A static field/method cannot be accessed from an instance context"
        Example = JavaClass('org/beeware/rubicon/test/Example')

        with self.assertRaises(AttributeError):
            Example.int_field

        with self.assertRaises(AttributeError):
            Example.get_int_field()
    def test_non_static_access_static(self):
        "A static field/method cannot be accessed from an instance context"
        Example = JavaClass('org/pybee/rubicon/test/Example')

        with self.assertRaises(AttributeError):
            Example.int_field

        with self.assertRaises(AttributeError):
            Example.get_int_field()
Exemple #6
0
    def test_enum_method(self):
        "A method with enum arguments can be handled."
        Example = JavaClass('org/beeware/rubicon/test/Example')
        example = Example()

        Stuff = JavaClass('org/beeware/rubicon/test/Example$Stuff')

        self.assertEqual(example.label(Stuff.FOO), "Foo")
        self.assertEqual(example.label(Stuff.BAR), "Bar")
        self.assertEqual(example.label(Stuff.WHIZ), "Whiz")
    def test_polymorphic_static_method(self):
        "Check that the right static method is activated based on arguments used"
        Example = JavaClass('org/pybee/rubicon/test/Example')

        self.assertEqual(Example.tripler(42), 126)
        self.assertEqual(Example.tripler("wibble"), "wibblewibblewibble")

        # If arguments don't match available options, an error is raised
        with self.assertRaises(ValueError):
            Example.tripler(1.234)
    def test_protected_static_method(self):
        "An attribute error is raised if you invoke a non-public static method."
        Example = JavaClass('org/pybee/rubicon/test/Example')

        # Non-public methods raise an error.
        with self.assertRaises(AttributeError):
            Example.static_invisible_method()

        # Cache warming doesn't affect anything.
        with self.assertRaises(AttributeError):
            Example.static_invisible_method()
Exemple #9
0
 def test_heterogenous_list(self):
     """A list of mixed types raise an exception when trying to find the right Java method."""
     Example = JavaClass("org/beeware/rubicon/test/Example")
     with self.assertRaises(ValueError):
         Example.sum_all_ints(["two", 3])
     with self.assertRaises(ValueError):
         Example.sum_all_ints([1, "two"])
     with self.assertRaises(ValueError):
         Example.sum_all_floats([1.0, "two"])
     with self.assertRaises(ValueError):
         Example.sum_all_doubles([1.0, "two"])
Exemple #10
0
    def test_non_existent_static_method(self):
        "An attribute error is raised if you invoke a non-existent static method."
        Example = JavaClass('org/pybee/rubicon/test/Example')

        # Non-existent methods raise an error.
        with self.assertRaises(AttributeError):
            Example.static_method_doesnt_exist()

        # Cache warming doesn't affect anything.
        with self.assertRaises(AttributeError):
            Example.static_method_doesnt_exist()
Exemple #11
0
    def test_object_array_arg(self):
        "Arrays of object can be used as arguments"
        Example = JavaClass('org/beeware/rubicon/test/Example')
        obj1 = Example()

        Thing = JavaClass('org/beeware/rubicon/test/Thing')
        thing1 = Thing('This is one', 1)
        thing2 = Thing('This is two', 2)

        self.assertEqual(
            [str(obj) for obj in obj1.doubler([thing1, thing2])],
            [str(obj) for obj in [thing1, thing1, thing2, thing2]])
Exemple #12
0
    def test_object_return(self):
        "If a method or field returns an object, you get an instance of that type returned"
        Example = JavaClass('org/beeware/rubicon/test/Example')
        example = Example()

        Thing = JavaClass('org/beeware/rubicon/test/Thing')
        thing = Thing('This is thing', 2)

        example.set_thing(thing)

        the_thing = example.get_thing()
        self.assertEqual(the_thing.toString(), "This is thing 2")
Exemple #13
0
    def test_null_return(self):
        "Returned NULL objects are typed"
        Example = JavaClass('org/beeware/rubicon/test/Example')
        obj = Example()

        Thing = JavaClass('org/beeware/rubicon/test/Thing')

        obj.set_thing(Thing.__null__)
        returned = obj.get_thing()
        # Typed null objects are always equal to equivalent typed nulls
        self.assertEqual(returned, Thing.__null__)
        # All Typed nulls are equivalent
        self.assertEqual(returned, Example.__null__)
        # Null is always false
        self.assertFalse(returned)
Exemple #14
0
    def test_polymorphic_method_null(self):
        "Polymorphic methods can be passed NULLs"
        Example = JavaClass('org/beeware/rubicon/test/Example')
        obj1 = Example()

        self.assertEqual(obj1.doubler(JavaNull(str)),
                         "Can't double NULL strings")
Exemple #15
0
    def test_convert_to_global(self):
        "An object can be converted into a global JNI reference."
        Example = JavaClass('org/beeware/rubicon/test/Example')
        obj1 = Example()

        Thing = JavaClass('org/beeware/rubicon/test/Thing')
        thing = Thing('This is thing', 2)

        ICallback__null = JavaNull(b'Lorg/beeware/rubicon/test/ICallback;')

        global_thing = thing.__global__()
        self.assertEqual(global_thing.currentCount(), 2)
        self.assertEqual(
            obj1.combiner(5, "Spam", global_thing, ICallback__null,
                          JavaNull([int])),
            "5::Spam::This is thing 2::<no callback>::<no values to count>")
    def test_static_method(self):
        "A static method on a class can be invoked."
        Example = JavaClass('org/pybee/rubicon/test/Example')

        Example.set_static_base_int_field(2288)
        Example.set_static_int_field(2299)

        self.assertEqual(Example.get_static_base_int_field(), 2288)
        self.assertEqual(Example.get_static_int_field(), 2299)
Exemple #17
0
 def test_int_array_arg(self):
     "Arrays of int can be used as arguments"
     Example = JavaClass('org/beeware/rubicon/test/Example')
     obj1 = Example()
     self.assertEqual(obj1.doubler([1, 2]), [1, 1, 2, 2])
     self.assertEqual(obj1.doubler([jlong(1), jlong(2)]), [1, 1, 2, 2])
     self.assertEqual(obj1.doubler([jshort(1), jshort(2)]), [1, 1, 2, 2])
     self.assertEqual(obj1.doubler([jint(1), jint(2)]), [1, 1, 2, 2])
    def make_button(self):
        activity_class = JavaClass("org/beeware/android/MainActivity")
        java_activity_instance = activity_class.singletonThis

        linear_layout = LinearLayout(java_activity_instance)
        java_activity_instance.setContentView(linear_layout)
        button = Button(java_activity_instance)
        button.setText("Python made this button! Click Me")
        button.setOnClickListener(OnClickRunDemoCode())
        linear_layout.addView(button)
Exemple #19
0
    def test_static_method(self):
        "A static method on a class can be invoked."
        Example = JavaClass('org/pybee/rubicon/test/Example')

        Example.set_static_base_int_field(2288)
        Example.set_static_int_field(2299)

        self.assertEqual(Example.get_static_base_int_field(), 2288)
        self.assertEqual(Example.get_static_int_field(), 2299)
Exemple #20
0
    def test_non_existent_static_field(self):
        "An attribute error is raised if you invoke a non-existent static field."
        Example = JavaClass('org/beeware/rubicon/test/Example')

        # Non-existent fields raise an error.
        with self.assertRaises(AttributeError):
            Example.static_field_doesnt_exist

        # Cache warming doesn't affect anything.
        with self.assertRaises(AttributeError):
            Example.static_field_doesnt_exist
Exemple #21
0
    def test_static_access_non_static(self):
        "An instance field/method cannot be accessed from the static context"
        Example = JavaClass('org/beeware/rubicon/test/Example')

        obj = Example()

        with self.assertRaises(AttributeError):
            obj.static_int_field

        with self.assertRaises(AttributeError):
            obj.get_static_int_field()
Exemple #22
0
    def make_button(self):
        activity_class_name = os.environ['ACTIVITY_CLASS_NAME']
        activity_class = JavaClass(activity_class_name)
        java_activity_instance = activity_class.singletonThis

        linear_layout = LinearLayout(java_activity_instance)
        java_activity_instance.setContentView(linear_layout)
        button = Button(java_activity_instance)
        button.setText("Python made this button! Click Me")
        button.setOnClickListener(OnClickRunDemoCode())
        linear_layout.addView(button)
Exemple #23
0
    def test_protected_static_field(self):
        "An attribute error is raised if you invoke a non-public static field."
        Example = JavaClass('org/beeware/rubicon/test/Example')

        # Non-public fields raise an error.
        with self.assertRaises(AttributeError):
            Example.static_invisible_field

        # Cache warming doesn't affect anything.
        with self.assertRaises(AttributeError):
            Example.static_invisible_field
Exemple #24
0
    def test_polymorphic_method(self):
        "Check that the right method is activated based on arguments used"
        Example = JavaClass('org/beeware/rubicon/test/Example')
        obj1 = Example()

        self.assertEqual(obj1.doubler(42), 84)
        self.assertEqual(obj1.doubler("wibble"), "wibblewibble")

        # If arguments don't match available options, an error is raised
        with self.assertRaises(ValueError):
            obj1.doubler(1.234)
Exemple #25
0
    def test_non_existent_method(self):
        "An attribute error is raised if you invoke a non-existent method."
        Example = JavaClass('org/beeware/rubicon/test/Example')

        obj1 = Example()

        # Non-existent methods raise an error.
        with self.assertRaises(AttributeError):
            obj1.method_doesnt_exist()

        # Cache warming doesn't affect anything.
        with self.assertRaises(AttributeError):
            obj1.method_doesnt_exist()
Exemple #26
0
    def test_float_array_arg(self):
        "Arrays of float can be used as arguments"
        Example = JavaClass('org/beeware/rubicon/test/Example')
        obj1 = Example()

        self.assertAlmostEqualList(obj1.doubler([1.1, 2.2]),
                                   [1.1, 1.1, 2.2, 2.2])
        self.assertAlmostEqualList(obj1.doubler([jfloat(1.1),
                                                 jfloat(2.2)]),
                                   [1.1, 1.1, 2.2, 2.2])
        self.assertAlmostEqualList(obj1.doubler([jdouble(1.1),
                                                 jdouble(2.2)]),
                                   [1.1, 1.1, 2.2, 2.2])
Exemple #27
0
    def test_simple_object(self):

        Stack = JavaClass('java/util/Stack')

        stack = Stack()

        stack.push("Hello")
        stack.push("World")

        # The stack methods are protyped to return java/lang/Object,
        # so we need to call toString() to get the actual content...
        self.assertEqual(stack.pop().toString(), "World")
        self.assertEqual(stack.pop().toString(), "Hello")
Exemple #28
0
    def test_method(self):
        "An instance method can be invoked."
        Example = JavaClass('org/beeware/rubicon/test/Example')

        obj = Example()
        self.assertEqual(obj.get_base_int_field(), 22)
        self.assertEqual(obj.get_int_field(), 33)

        obj.set_base_int_field(8888)
        obj.set_int_field(9999)

        self.assertEqual(obj.get_base_int_field(), 8888)
        self.assertEqual(obj.get_int_field(), 9999)
Exemple #29
0
    def test_protected_method(self):
        "An attribute error is raised if you invoke a non-public method."
        Example = JavaClass('org/beeware/rubicon/test/Example')

        obj1 = Example()

        # Non-public methods raise an error.
        with self.assertRaises(AttributeError):
            obj1.invisible_method()

        # Cache warming doesn't affect anything.
        with self.assertRaises(AttributeError):
            obj1.invisible_method()
    def test_static_field(self):
        "A static field on a class can be accessed and mutated"
        Example = JavaClass('org/pybee/rubicon/test/Example')

        Example.set_static_base_int_field(1)
        Example.set_static_int_field(11)

        self.assertEqual(Example.static_base_int_field, 1)
        self.assertEqual(Example.static_int_field, 11)

        Example.static_base_int_field = 1188
        Example.static_int_field = 1199

        self.assertEqual(Example.static_base_int_field, 1188)
        self.assertEqual(Example.static_int_field, 1199)
Exemple #31
0
    def test_field(self):
        "A field on an instance can be accessed and mutated"
        Example = JavaClass('org/beeware/rubicon/test/Example')

        obj = Example()

        self.assertEqual(obj.base_int_field, 22)
        self.assertEqual(obj.int_field, 33)

        obj.base_int_field = 8888
        obj.int_field = 9999

        self.assertEqual(obj.base_int_field, 8888)
        self.assertEqual(obj.int_field, 9999)
Exemple #32
0
    def test_type_cast(self):
        "An object can be cast to another type"
        Example = JavaClass('org/beeware/rubicon/test/Example')
        obj1 = Example()

        Thing = JavaClass('org/beeware/rubicon/test/Thing')
        thing = Thing('This is thing', 2)

        obj1.set_thing(thing)

        # Retrieve a generic reference to the object (java.lang.Object)
        obj = obj1.get_generic_thing()

        ICallback_null = JavaNull(b'Lorg/beeware/rubicon/test/ICallback;')

        # Attempting to use this generic object *as* a Thing will fail.
        with self.assertRaises(AttributeError):
            obj.currentCount()
        with self.assertRaises(ValueError):
            obj1.combiner(3, "Ham", obj, ICallback_null, JavaNull([int]))

        # ...but if we cast it to the type we know it is
        # (org.beeware.rubicon.test.Thing), the same calls will succeed.
        cast_thing = Thing.__cast__(obj)
        self.assertEqual(cast_thing.currentCount(), 2)
        self.assertEqual(
            obj1.combiner(4, "Ham", cast_thing, ICallback_null,
                          JavaNull([int])),
            "4::Ham::This is thing 2::<no callback>::<no values to count>")

        # We can also cast as a global JNI reference
        # (org.beeware.rubicon.test.Thing), the same calls will succeed.
        global_cast_thing = Thing.__cast__(obj, globalref=True)
        self.assertEqual(
            obj1.combiner(4, "Ham", global_cast_thing, ICallback_null,
                          JavaNull([int])),
            "4::Ham::This is thing 2::<no callback>::<no values to count>")
    def test_polymorphic_static_method(self):
        "Check that the right static method is activated based on arguments used"
        Example = JavaClass('org/pybee/rubicon/test/Example')

        self.assertEqual(Example.tripler(42), 126)
        self.assertEqual(Example.tripler("wibble"), "wibblewibblewibble")

        # If arguments don't match available options, an error is raised
        with self.assertRaises(ValueError):
            Example.tripler(1.234)
Exemple #34
0
    def test_static_field(self):
        "A static field on a class can be accessed and mutated"
        Example = JavaClass('org/pybee/rubicon/test/Example')

        Example.set_static_base_int_field(1)
        Example.set_static_int_field(11)

        self.assertEqual(Example.static_base_int_field, 1)
        self.assertEqual(Example.static_int_field, 11)

        Example.static_base_int_field = 1188
        Example.static_int_field = 1199

        self.assertEqual(Example.static_base_int_field, 1188)
        self.assertEqual(Example.static_int_field, 1199)
    def test_simple_object(self):

        Stack = JavaClass('java/util/Stack')

        # <AK>: added for coverage
        # Construct instance using keyword arguments raise an error.
        with self.assertRaises(ValueError):
            stack = Stack(kwarg=123)
        # </AK>

        stack = Stack()

        stack.push("Hello")
        stack.push("World")

        # The stack methods are protyped to return java/lang/Object,
        # so we need to call toString() to get the actual content...
        self.assertEqual(stack.pop().toString(), "World")
        self.assertEqual(stack.pop().toString(), "Hello")
Exemple #36
0
    def run_forever_cooperatively(self):
        # Based heavily on `BaseEventLoop.run_forever()`` in CPython.
        if self.is_running():
            raise RuntimeError(
                "Refusing to start since loop is already running.")
        if self._closed:
            raise RuntimeError("Event loop is closed. Create a new object.")
        self._set_coroutine_origin_tracking(self._debug)
        self._thread_id = threading.get_ident()

        self._old_agen_hooks = sys.get_asyncgen_hooks()
        sys.set_asyncgen_hooks(
            firstiter=self._asyncgen_firstiter_hook,
            finalizer=self._asyncgen_finalizer_hook,
        )
        asyncio.events._set_running_loop(self)

        # Create Android handler to run our own code on. We assume that we are running
        # in the main Android activity thread, and we therefore do not worry about thread safety.
        Handler = JavaClass("android/os/Handler")
        self._handler = Handler(
        )  # No-arg constructor uses main Android event loop.
        # Create a Java Runnables to tick the event loop forward. We statically create
        # Runnables to avoid creating lots of temporary objects.
        python_self = self

        class RunScheduledCallbacksThenRestartLoopRunnable(Runnable):
            def run(self):
                python_self._run_scheduled_callbacks_then_restart_loop()

        class RunEventLoopOnceCooperativelyRunnable(Runnable):
            def run(self):
                python_self._run_event_loop_once_cooperatively()

        self._runnables = {
            "_run_scheduled_callbacks_then_restart_loop":
            RunScheduledCallbacksThenRestartLoopRunnable(),
            "_run_event_loop_once_cooperatively":
            RunEventLoopOnceCooperativelyRunnable(),
        }
        self._run_event_loop_once_cooperatively()
        print("Started event loop")