@Override
  public void cancel(InterpreterContext context) throws InterpreterException {
    String shinyApp = context.getStringLocalProperty("app", DEFAULT_APP_NAME);
    IRInterpreter irInterpreter = getIRInterpreter(shinyApp);
    irInterpreter.cancel(context);
  }
@Test
  void testInvalidShinyApp()
          throws IOException, InterpreterException, InterruptedException, UnirestException {
    InterpreterContext context = getInterpreterContext();
    context.getLocalProperties().put("type", "ui");
    InterpreterResult result =
            interpreter.interpret(IOUtils.toString(getClass().getResource("/invalid_ui.R"), StandardCharsets.UTF_8), context);
    assertEquals(InterpreterResult.Code.SUCCESS, result.code());

    context = getInterpreterContext();
    context.getLocalProperties().put("type", "server");
    result = interpreter.interpret(IOUtils.toString(getClass().getResource("/server.R"), StandardCharsets.UTF_8), context);
    assertEquals(InterpreterResult.Code.SUCCESS, result.code());

    final InterpreterContext context2 = getInterpreterContext();
    context2.getLocalProperties().put("type", "run");
    Thread thread = new Thread(() -> {
      try {
        interpreter.interpret("", context2);
      } catch (Exception e) {
        e.printStackTrace();
      }
    });
    thread.start();
    // wait for the shiny app start
    Thread.sleep(5 * 1000);
    List<InterpreterResultMessage> resultMessages = context2.out.toInterpreterResultMessage();
    assertEquals(1, resultMessages.size(), resultMessages.toString());
    assertEquals(InterpreterResult.Type.HTML, resultMessages.get(0).getType());
    String resultMessageData = resultMessages.get(0).getData();
    assertTrue(resultMessageData.contains("<iframe"), resultMessageData);
    Pattern urlPattern = Pattern.compile(".*src=\"(http\\S*)\".*", Pattern.DOTALL);
    Matcher matcher = urlPattern.matcher(resultMessageData);
    if (!matcher.matches()) {
      fail("Unable to extract url: " + resultMessageData);
    }
    String shinyURL = matcher.group(1);

    // call shiny app via rest api
    HttpResponse<String> response = Unirest.get(shinyURL).asString();
    assertEquals(500, response.getStatus());

    resultMessages = context2.out.toInterpreterResultMessage();
    assertTrue(resultMessages.get(1).getData().contains("Invalid_code"),
        resultMessages.get(1).getData());
    // depends on JVM language
    // assertTrue(resultMessages.get(1).getData().contains("object 'Invalid_code' not found"),
    // resultMessages.get(1).getData());

    // cancel paragraph to stop shiny app
    interpreter.cancel(getInterpreterContext());
    // wait for shiny app to be stopped
    Thread.sleep(1000);
    try {
      Unirest.get(shinyURL).asString();
      fail("Should fail to connect to shiny app");
    } catch (Exception e) {
      assertTrue(e.getMessage().contains("Connection refused"), e.getMessage());
    }
  }