u-ways / software-engineering-work-experience

A Practical & Relevant Work Experience Project For Students Who Are Interested In Software Development.
MIT License
2 stars 7 forks source link

Add support for Python Solutions #6

Open u-ways opened 1 year ago

u-ways commented 1 year ago

Background

Currently the project does not support users supplementing a solution written in Python despite being a popular choice for beginners. This forces the learner to dive deep into learning Kotlin, which is not a bad thing, but giving choice to a familiar language can allow a subset of users to complete all challenges in an adequate time and allow them present something they can share with their school colleagues without having to explain a new language semantics.

Requirements

It's possible to refactor the project to introduce a ScriptEngine which allows you to run different language specifications within the JVM.

Given all we do is assert on STDOUT, it would be fairly easy for us to capture their solutions output and run the same tests on them with appropriate modifications.

This is a ticket to apply such changes.

u-ways commented 1 year ago

It's also possible to refactor the project to introduce Chaquopy, which is a solution to allow you to run Python scripts within Java/Kotlin code.

u-ways commented 1 year ago

Notes & Ideas

Jython

Jython (https://www.jython.org) is one available solutions based on the JSR-223 Scripting Engine. The problem is I cannot find an 3.x implementation.

Process Builder

We can also use the ProcessBuilder to just call Python from the container:

@Test
public void givenPythonScript_whenPythonProcessInvoked_thenSuccess() throws Exception {
    ProcessBuilder processBuilder = new ProcessBuilder("python", resolvePythonScriptPath("hello.py"));
    processBuilder.redirectErrorStream(true);

    Process process = processBuilder.start();
    List<String> results = readProcessOutput(process.getInputStream());

    assertThat("Results should not be empty", results, is(not(empty())));
    assertThat("Results should contain output of script: ", results, hasItem(
      containsString("Hello Baeldung Readers!!")));

    int exitCode = process.waitFor();
    assertEquals("No errors should be detected", 0, exitCode);
}

We can also use Apache Commons Exec library for a better API.

You can read more here: How to Call Python From Java) for further details.