Dylan Nicholson
Dylan Nicholson

Reputation: 1368

How to test a Jenkins pipeline (or other jenkins script) that makes use of the branch name?

If I have a Jenkins pipeline script (though the principle could apply to any Jenkins script really) that has different behaviours depending on which branch is getting built, how can I test that it's working properly without merging it into that branch? In the pipeline script it's tested both using the branch keyword and by testing env.BRANCH_NAME. I'd think the latter might be something you could override somehow but I can see how.

Just to clarify, I have this at the top of my Jenkinsfile:

def isSpecialBranch = env.BRANCH_NAME ==~ *reg-ex*

Plus there are also a number of nodes that have

when { 
    branch 'xxxxx'
}

Basically I want to test that the pipeline will behave correctly once the changes are merged to a branch-name that does fit the pattern.

Upvotes: 0

Views: 2372

Answers (2)

dcalap
dcalap

Reputation: 1072

You can use Jenkins Pipeline Unit in order to mock the branches.

You can even mock Jenkins variables and that kind of stuff.

Anyway, the proper way to write the when expression is something like this (e.g to match master):

when {
       expression { (branch == 'origin/master') }
}

or (e.g. to match develop, feature or hotfix)

when {
     expression { (branch == 'origin/develop' || branch.matches('origin\\/(feature|hotfix)+\\/.*')) }
}

Hope it helps.

Upvotes: 2

uncletall
uncletall

Reputation: 6842

You can try this:

static def getBranchName(scm)
{
  return scm.branches[0].name
}

This need to run with elevated privileges so this is part of my Utilities class in my shared library.

Upvotes: -1

Related Questions