Testing Jenkins Jelly template HTML output

77 Views Asked by At

I am trying to test Jelly templates of a Jenkins plugin for their HTML rendering without having to rely on using some interactive session or similar.

This is my current code:

import java.io.OutputStream;
import java.io.ByteArrayOutputStream;

import org.apache.commons.jelly.Script;
import org.apache.commons.jelly.XMLOutput;
import org.apache.commons.jelly.test.BaseJellyTest;

import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.containsString;

public class JellyTest extends BaseJellyTest {

    public JellyTest() {
        super("dummy");
    }

    public int getKey() {
        return 42;
    }

    public String getDescription(Object job) {
        return "abc";
    }

    @Test
    public void testRendering() throws Exception {
        setUpScript("/testing.jelly");
        Script script = getJelly().compileScript();
        getJellyContext().setVariable("it", this);

        OutputStream outputStream = new ByteArrayOutputStream();
        XMLOutput output = XMLOutput.createXMLOutput(outputStream);
        script.run(getJellyContext(), output);
        output.flush();
        String result = outputStream.toString();

        assertThat(result, containsString("42"));
    }

}

The corresponding testing.jelly looks something like this:

<?jelly escape-by-default='true?>
<j:jelly xmlns:j="jelly:core" xmlns:l="/lib/layout">
    <j:set var="key" value="${it.getKey()}"/>
    <j:set var="description" value="${it.getDescription(job)}"/>
    <p>${key}</p>
    <j:if test="${description}">
        <j:out value="${description}"/>
    </j:if>
    <p>${%translationKey}</p>
</j:jelly>

The test will not succeed and fail with

org.apache.commons.jelly.JellyException: could not parse Jelly script

due to using the Jenkins-specific ${# syntax for translations. If I remove this section, the error goes away, but this does not allow for Jenkins-specific functionality inside the templates at all.

Expected result:

<p>42</p>
<p>abc</p>

What is the correct approach to write such tests? How to inject a custom Job instance to the template?

0

There are 0 best solutions below