In GraalPy project, where I translate Java codes into Python, I have encountered an error when performing unit testing. When the entire code consists of Java code, JUnit performs successfully, even when Java code is combined with Python, in methods which call the constructor not using Python code, unit test passes:

Point(int x, int y) {
     this(x, y, false);
}

However, when JUnit tries to test the methods which uses the constructor where Python file is called, it throws an "IllegalAccessError". I believe I have successfully integrated Python with Java as when I am testing inside "public static void main" I get the results I want. The contents of some files are below.

The content of src/main/java/my/pack/Point.java file with pure Java code in which JUnit succeeds:

package my.pack;

import java.lang.Math;

class Point {
    int x;
    int y;

    Point(int x, int y) {
        this(x, y, false);
    }

    static final double EPS = 0.0001;

    Point(double r, double a/* ngle */, boolean polar) {
        double x = polar ? r * Math.cos(a) : r;
        double y = polar ? r * Math.sin(a) : a;
        this.x = (int) x;
        this.y = (int) y;
        if (Math.abs(this.x - x) >= EPS || Math.abs(this.y - y) >= EPS) {
            throw new IllegalArgumentException("Likely not integers!");
        }
    }

    int getX() {
        return x;
    }

    int getY() {
        return y;
    }

    public String toString() {
        return "(" + x + ", " + y + ")";
    }
}

src/test/java/my/pack/PointTest.java file:

package my.pack;

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class PointTest {
    @Test
    public void testIntegers() {
        Point p = new Point(1, 2, false);
        assertEquals(1, p.getX());
        assertEquals(2, p.getY());
    }

    @Test
    public void testDoublesWorking() {
        Point p = new Point(Math.sqrt(2), Math.PI / 4, true);
        assertEquals(1, p.getX());
        assertEquals(1, p.getY());
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDoublesNotWorking() {
        new Point(Math.sqrt(2), Math.PI / 2, true);
    }

    @Test
    public void testToString() {
        Point p = new Point(1, 2, false);
        assertEquals("(1, 2)", p.toString());
    }
}

The content of src/main/java/my/pack/Point.java file with pure Java code in which JUnit fails:

package my.pack;

import org.graalvm.polyglot.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Set;

public class Point {
    int x;
    int y;

    String string = new String("");
    static final double EPS = 0.0001;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public Point(double r, double a, boolean polar) {
        try (Context context = Context.newBuilder().allowAllAccess(true).build()) {
            // Load the Python script from the Python file
            Source source = Source.newBuilder("python", Paths.get("src/main/resources/Point.py").toFile()).build();
            context.eval(source);

            // Access the Point class defined in Python
            Value pointClass = context.getBindings("python").getMember("Point");

            try {
                String polOrNot = "";
                if (polar)
                {
                    polOrNot = "True";
                } else {
                    polOrNot = "False";
                }
                Value pointInstance = pointClass.newInstance(r, a, polOrNot);
                // Call methods on the Python Point instance
                int newX = pointInstance.getMember("getX").execute().asInt();
                int newY = pointInstance.getMember("getY").execute().asInt();
                String toStringResult = pointInstance.getMember("toString").execute().asString();
                System.out.print("New x: ");
                System.out.println(newX);
                System.out.print("New y: ");
                System.out.println(newY);
                // Update the x and y values from Python
                this.x = newX;
                this.y = newY;
                this.string = toStringResult;
            } catch (PolyglotException e) {
                throw new IllegalArgumentException("Likely not integers!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public String toString() {
        return "(" + x + ", " + y + ")";
    }

    public static void main(String[] args) throws IOException {
        System.out.println("Testing 'testIntegers()' method of 'PointTest' class:");
        Point p1 = new Point(1, 2);
        System.out.println("Expected: 1 -- Result: " + p1.getX());
        System.out.println("Expected: 2 -- Result: " + p1.getY());

        System.out.println("\n---------------------------------------\n");

        System.out.println("Testing 'testDoublesWorking()' method of 'PointTest' class:");
        Point p2 = new Point(Math.sqrt(2), Math.PI / 4, true);
        System.out.println("Expected: 1 -- Result: " + p2.getX());
        System.out.println("Expected: 1 -- Result: " + p2.getY());

        System.out.println("\n---------------------------------------\n");

        System.out.println("Testing 'testToString() ' method of 'PointTest' class:");
        Point p3 = new Point(1, 2);
        System.out.println("Expected: (1, 2) -- Result: " + p3.toString());

        System.out.println("\n---------------------------------------\n");

        System.out.println("Testing 'testDoublesNotWorking()' method of 'PointTest' class (Error expected):");
        Point p4 = new Point(Math.sqrt(2), Math.PI / 2, true);


        System.out.println("\n---------------------------------------\n");
    }
}

Point.py file:

import math

class Point:
    EPS = 0.0001

    def __init__(self, r, a, polar=False):
        if(polar == "False"):
            polar = False
        else:
            polar = True
        x = r * math.cos(a) if polar else r
        y = r * math.sin(a) if polar else a
        self.x = int(x)
        self.y = int(y)
        if abs(self.x - x) >= Point.EPS or abs(self.y - y) >= Point.EPS:
            raise ValueError("Likely not integers!")

    def getX(self):
        return self.x

    def getY(self):
        return self.y

    def toString(self):
        return f"({self.x}, {self.y})"

Error:

java.lang.Exception: Unexpected exception, expected<java.lang.IllegalArgumentException> but was<java.lang.IllegalAccessError>

    at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:30)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)
Caused by: java.lang.IllegalAccessError: superclass access check failed: class com.oracle.truffle.polyglot.PolyglotImpl (in unnamed module @0x6fc6f14e) cannot access class org.graalvm.polyglot.impl.AbstractPolyglotImpl (in module org.graalvm.polyglot) because module org.graalvm.polyglot does not export org.graalvm.polyglot.impl to unnamed module @0x6fc6f14e
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)

The pom.xml file: `

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>embedding</artifactId>
    <version>1.0-SNAPSHOT</version>
    <repositories>
    </repositories>

    <properties>
        <!-- Select the GraalVM version to use. -->
        <graalvm.version>23.1.0</graalvm.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.graalvm.polyglot</groupId>
            <artifactId>polyglot</artifactId>
            <version>${graalvm.version}</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.graalvm.polyglot</groupId>
            <artifactId>python</artifactId>
            <version>${graalvm.version}</version>
            <type>pom</type>
        </dependency>


         <dependency>
             <groupId>org.graalvm.polyglot</groupId>
             <artifactId>tools</artifactId>
             <version>${graalvm.version}</version>
             <type>pom</type>
         </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.1.2</version>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>no-runtime-compilation</id>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                        <configuration>
                            <executable>${java.home}/bin/java</executable>
                            <arguments>
                                <argument>--module-path</argument>
                                <modulepath/>
                                <argument>-m</argument>
                                <argument>my.pack.Point</argument>
                            </arguments>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <executable>${java.home}/bin/java</executable>
                    <arguments>
                        <argument>--module-path</argument>
                        <modulepath/>
                        <argument>-m</argument>
                        <argument>my.pack.Point</argument>
                    </arguments>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-jlink-plugin</artifactId>
                <version>3.1.0</version>
                <extensions>true</extensions>
                <configuration>
                    <ignoreSigningInformation>true</ignoreSigningInformation>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>native</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.graalvm.buildtools</groupId>
                        <artifactId>native-maven-plugin</artifactId>
                        <version>0.9.25</version>
                        <extensions>true</extensions>
                        <executions>
                            <execution>
                                <id>build-native</id>
                                <goals>
                                    <goal>compile-no-fork</goal>
                                </goals>
                                <phase>package</phase>
                            </execution>
                        </executions>
                        <configuration>
                            <imageName>${project.artifactId}</imageName>
                            <mainClass>my.pack.Point</mainClass>
                            <buildArgs>
                                <buildArg>--no-fallback</buildArg>
                                <buildArg>-J-Xmx20g</buildArg>
                            </buildArgs>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <profile>
            <id>not-graalvm-jdk</id>
            <activation>
                <file>
                    <missing>${java.home}/lib/graalvm</missing>
                </file>
            </activation>

            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-dependency-plugin</artifactId>
                        <version>3.6.0</version>
                        <executions>
                            <execution>
                                <id>copy-dependencies</id>
                                <phase>process-resources</phase>
                                <goals>
                                    <goal>copy</goal>
                                </goals>
                                <configuration>
                                    <outputDirectory>
                                        ${project.build.directory}/compiler
                                    </outputDirectory>
                                    <artifactItems>
                                        <artifactItem>
                                            <groupId>org.graalvm.sdk</groupId>
                                            <artifactId>collections</artifactId>
                                            <version>${graalvm.version}</version>
                                            <type>jar</type>
                                            <destFileName>collections.jar</destFileName>
                                        </artifactItem>
                                        <artifactItem>
                                            <groupId>org.graalvm.sdk</groupId>
                                            <artifactId>word</artifactId>
                                            <version>${graalvm.version}</version>
                                            <type>jar</type>
                                            <destFileName>word.jar</destFileName>
                                        </artifactItem>
                                        <artifactItem>
                                            <groupId>org.graalvm.truffle</groupId>
                                            <artifactId>truffle-compiler</artifactId>
                                            <version>${graalvm.version}</version>
                                            <type>jar</type>
                                            <destFileName>truffle-compiler.jar</destFileName>
                                        </artifactItem>
                                        <artifactItem>
                                            <groupId>org.graalvm.compiler</groupId>
                                            <artifactId>compiler</artifactId>
                                            <version>${graalvm.version}</version>
                                            <type>jar</type>
                                            <destFileName>compiler.jar</destFileName>
                                        </artifactItem>
                                    </artifactItems>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>

                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>3.1.2</version>
                        <configuration>
                            <argLine>
                                -XX:+UnlockExperimentalVMOptions
                                -XX:+EnableJVMCI
                                --upgrade-module-path=${project.build.directory}/compiler
                            </argLine>
                        </configuration>
                    </plugin>

                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
                        <version>1.6.0</version>
                        <executions>
                            <execution>
                                <id>default-cli</id>
                                <goals>
                                    <goal>exec</goal>
                                </goals>
                                <configuration>
                                    <executable>${java.home}/bin/java</executable>
                                    <arguments>
                                        <argument>--module-path</argument>
                                        <modulepath/>
                                        <argument>-XX:+UnlockExperimentalVMOptions</argument>
                                        <argument>-XX:+EnableJVMCI</argument>
                                        <argument>--upgrade-module-path=${project.build.directory}/compiler/</argument>
                                        <argument>-m</argument>
                                        <argument>embedding</argument>
                                    </arguments>
                                </configuration>
                            </execution>
                            <execution>
                                <id>no-runtime-compilation</id>
                                <goals>
                                    <goal>exec</goal>
                                </goals>
                                <configuration>
                                    <executable>${java.home}/bin/java</executable>
                                    <arguments>
                                        <argument>--module-path</argument>
                                        <modulepath/>
                                        <argument>-m</argument>
                                        <argument>my.pack.Point</argument>
                                    </arguments>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>

    </profiles>

</project>


Intellij does not recognize

<plugin>
       <artifactId>maven-jlink-plugin</artifactId>
       <version>3.1.0</version>
       <extensions>true</extensions>
       <configuration>
             <ignoreSigningInformation>true</ignoreSigningInformation>
       </configuration>
</plugin>

Where does the problem that prevents unit tests from performing successfully in all cases stem from? How can I resolve this problem?

0

There are 0 best solutions below