github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/test/groovy/util/JenkinsSetupRule.groovy (about)

     1  package util
     2  
     3  import com.lesfurets.jenkins.unit.BasePipelineTest
     4  import com.lesfurets.jenkins.unit.global.lib.LibraryConfiguration
     5  import org.junit.rules.TestRule
     6  import org.junit.runner.Description
     7  import org.junit.runners.model.Statement
     8  
     9  class JenkinsSetupRule implements TestRule {
    10  
    11      def library = SharedLibraryCreator.implicitLoadedLibrary
    12  
    13      final BasePipelineTest testInstance
    14  
    15      JenkinsSetupRule(BasePipelineTest testInstance) {
    16          this(testInstance, null)
    17      }
    18  
    19      JenkinsSetupRule(BasePipelineTest testInstance, LibraryConfiguration configuration) {
    20          this.testInstance = testInstance
    21          if(configuration)
    22              this.library = configuration
    23      }
    24  
    25      @Override
    26      Statement apply(Statement base, Description description) {
    27          return statement(base)
    28      }
    29  
    30      private Statement statement(final Statement base) {
    31          return new Statement() {
    32              @Override
    33              void evaluate() throws Throwable {
    34  
    35                  testInstance.scriptRoots += "vars/"
    36                  testInstance.setUp()
    37                  // register library
    38                  testInstance.helper.registerSharedLibrary(library)
    39                  // set jenkins job mock variables
    40                  testInstance.binding.setVariable('env', [
    41                      JOB_NAME    : 'p',
    42                      BUILD_NUMBER: '1',
    43                      BUILD_URL   : 'http://build.url',
    44                      BRANCH_NAME: 'master',
    45                      WORKSPACE: 'any/path'
    46                  ])
    47  
    48                  base.evaluate()
    49  
    50              }
    51          }
    52      }
    53  }