public void testMethodIndirection() throws Exception {
    PythonScriptEngineInitializer initializer = new PythonScriptEngineInitializer();
    ScriptEngine engine = initializer.instantiate(Collections.<String>emptySet(), null);

    Bindings bindings = engine.createBindings();
    Tester tester = new Tester();
    bindings.put("tester", tester);

    engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

    engine.eval("tester.increment()");

    Assert.assertEquals(tester.getInvocationCoung(), 1, "Unexpected number of tester invocations.");

    Map<String, Set<Method>> methods = getMethodsByName(Tester.class);
    for (Set<Method> ms : methods.values()) {
      Set<String> fns = initializer.generateIndirectionMethods("tester", ms);
      for (String fn : fns) {
        engine.eval(fn);
      }
    }

    engine.eval("increment()");
    Assert.assertEquals(
        tester.getInvocationCoung(),
        2,
        "Unexpected number of tester invocations after calling an indirected method.");
  }
  public void testEngineInitialization() throws Exception {
    PythonScriptEngineInitializer initializer = new PythonScriptEngineInitializer();
    ScriptEngine engine = initializer.instantiate(Collections.<String>emptySet(), null);

    // just some code to test out this is python
    engine.eval("from java.util import HashMap\nHashMap()");
  }
  public void testSourceProvider() throws Exception {
    PythonScriptEngineInitializer initializer = new PythonScriptEngineInitializer();

    ScriptEngine engine = initializer.instantiate(Collections.<String>emptySet(), null);

    StringWriter wrt = new StringWriter();

    engine.getContext().setWriter(wrt);

    initializer.installScriptSourceProvider(engine, new SourceProvider());

    engine.eval(
        "import sys\nsys.path.append('__rhq__:test-unsupported/')\nsys.path.append('__rhq__:test/')\nimport test_module");

    Assert.assertEquals(
        wrt.toString(), EXPECTED_OUTPUT + "\n", "Unexpected output from a custom module.");
  }
  public void testSecuredEngine() throws Exception {
    PythonScriptEngineInitializer initializer = new PythonScriptEngineInitializer();

    // jython seems to need these two..
    Permissions perms = new Permissions();
    perms.add(new RuntimePermission("createClassLoader"));
    perms.add(new RuntimePermission("getProtectionDomain"));

    // add permission to read files so that modules can be loaded, but writing should fail
    perms.add(new FilePermission("<<ALL FILES>>", "read"));

    ScriptEngine engine = initializer.instantiate(Collections.<String>emptySet(), perms);

    try {
      engine.eval("import os\nfp = open('pom.xml', 'w')");
      Assert.fail("Opening a file for writing should have failed with a security exception.");
    } catch (ScriptException e) {
      checkIsCausedByAccessControlException(e);
    }
  }