Alpha
Alpha

Reputation: 14026

How to identify compilation errors in Jenkins pipeline's groovy script?

I am writing Jenkins pipeline and my pipeline is quite big hence for testing purpose I create small one with new code that I add and want to test.

After testing that code in small testing pipeline, I copy/paste that code in original big pipeline. And when run big pipeline, after running for hours, it fails with trivial causes like variable is not defined which was missed during copy/paste from testing pipeline.

These kind of trivial errors are identified neither in Jenkins Pipeline UI nor in Intellij Idea(which I use)

Could someone please help me how these kind of trivial mistakes can be avoided so that pipeline after running long time does not fail?

Upvotes: 2

Views: 1490

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42174

You should consider setting unit tests for your pipeline using Pipeline Unit Test library. It allows you to compile and mock execution of the complex pipeline in less than 1 second. Of course, you may need to spend some time to configure your unit test correctly, but this is the kind of effort worth investing.

You could start with a simple test that prints the call stack, like:

import com.lesfurets.jenkins.unit.BasePipelineTest

class TestExampleJob extends BasePipelineTest {

        //...

        @Test
        void should_execute_without_errors() throws Exception {
            def script = loadScript("job/exampleJob.jenkins")
            script.execute()
            printCallStack()
        }
}

If you see no errors in the call stack, you can add assertJobStatusSuccess() to verify if the execution of the pipeline didn't cause changing the build status. And then, you can start adding things like assertCallStackContains(str) to start verifying if specific command or stage was present during the execution.

This unit test should also catch any (or at least most) compilation issues. There are some rare corner cases where pipeline unit test passes, but the pipeline executed on Jenkins fails. I use this library for two years in my Jenkins Shared Library, it saved me hundreds of hours of manual testing and catching simple bugs.

Upvotes: 2

Related Questions