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

     1  package util
     2  
     3  import com.lesfurets.jenkins.unit.BasePipelineTest
     4  import groovy.json.JsonSlurper
     5  import org.jenkinsci.plugins.credentialsbinding.impl.CredentialNotFoundException
     6  import org.junit.rules.TestRule
     7  import org.junit.runner.Description
     8  import org.junit.runners.model.Statement
     9  
    10  /**
    11   * By default a user "anonymous" with password "********"
    12   * is provided.
    13   *
    14   */
    15  class JenkinsCredentialsRule implements TestRule {
    16  
    17      Map credentials = [:]
    18      Map bindingTypes = [:]
    19  
    20      final BasePipelineTest testInstance
    21  
    22      JenkinsCredentialsRule(BasePipelineTest testInstance) {
    23          this.testInstance = testInstance
    24      }
    25  
    26      JenkinsCredentialsRule withCredentials(String credentialsId, String user, String passwd) {
    27          credentials.put(credentialsId, [user: user, passwd: passwd])
    28          return this
    29      }
    30  
    31      JenkinsCredentialsRule withCredentials(String credentialsId, String secretTextOrFilePath) {
    32              credentials.put(credentialsId, [token: secretTextOrFilePath])
    33              return this
    34      }
    35  
    36      JenkinsCredentialsRule reset(){
    37          credentials.clear()
    38          return this
    39      }
    40  
    41      @Override
    42      Statement apply(Statement base, Description description) {
    43          return statement(base)
    44      }
    45  
    46      private Statement statement(final Statement base) {
    47  
    48          return new Statement() {
    49  
    50              @Override
    51              void evaluate() throws Throwable {
    52  
    53                  testInstance.helper.registerAllowedMethod('usernamePassword', [Map.class],
    54                      { m ->
    55                                  if (credentials.keySet().contains(m.credentialsId)) { bindingTypes[m.credentialsId] = 'usernamePassword'; return m }
    56                                 // this is what really happens in case of an unknown credentials id,
    57                                 // checked with reality using credentials plugin 2.1.18.
    58                                 throw new CredentialNotFoundException(
    59                                     "Could not find credentials entry with ID '${m.credentialsId}'")
    60                      })
    61  
    62                  testInstance.helper.registerAllowedMethod('string', [Map.class],
    63                      { m ->
    64                                  if (credentials.keySet().contains(m.credentialsId)) { bindingTypes[m.credentialsId] = 'string'; return m }
    65                                  // this is what really happens in case of an unknown credentials id,
    66                                  // checked with reality using credentials plugin 2.1.18.
    67                                  throw new CredentialNotFoundException(
    68                                      "Could not find credentials entry with ID '${m.credentialsId}'")
    69                      })
    70  
    71                  testInstance.helper.registerAllowedMethod('file', [Map.class],
    72                      { m ->
    73                          if (credentials.keySet().contains(m.credentialsId)) { bindingTypes[m.credentialsId] = 'file'; return m }
    74                          // this is what really happens in case of an unknown credentials id,
    75                          // checked with reality using credentials plugin 2.1.18.
    76                          throw new CredentialNotFoundException(
    77                              "Could not find credentials entry with ID '${m.credentialsId}'")
    78                      })
    79  
    80                  testInstance.helper.registerAllowedMethod('withCredentials', [List, Closure], { config, closure ->
    81                      // there can be multiple credentials defined for the closure; collecting the necessary binding
    82                      // preparations and destructions before executing closure
    83                      def preparations = []
    84                      def destructions = []
    85                      config.each { cred ->
    86                          def credsId = cred.credentialsId
    87                          def credentialsBindingType = bindingTypes.get(credsId)
    88                          def creds = credentials.get(credsId)
    89  
    90                          def tokenVariable, usernameVariable, passwordVariable, prepare, destruct
    91                          if (credentialsBindingType == "usernamePassword") {
    92                              passwordVariable = cred.passwordVariable
    93                              usernameVariable = cred.usernameVariable
    94                              preparations.add({
    95                                  binding.setProperty(usernameVariable, creds?.user)
    96                                  binding.setProperty(passwordVariable, creds?.passwd)
    97                              })
    98                              destructions.add({
    99                                  binding.setProperty(usernameVariable, null)
   100                                  binding.setProperty(passwordVariable, null)
   101                              })
   102                          } else if (credentialsBindingType == "string") {
   103                              tokenVariable = cred.variable
   104                              preparations.add({
   105                                  binding.setProperty(tokenVariable, creds?.token)
   106                              })
   107                              destructions.add({
   108                                  binding.setProperty(tokenVariable, null)
   109                              })
   110                          }
   111                          else if (credentialsBindingType == "file") {
   112                              fileContentVariable = cred.variable
   113                              preparations.add({
   114                                  binding.setProperty(fileContentVariable, creds?.token)
   115                              })
   116                              destructions.add({
   117                                  binding.setProperty(fileContentVariable, null)
   118                              })
   119                          }
   120                          else {
   121                              throw new RuntimeException("Unknown binding type")
   122                          }
   123                      }
   124  
   125                      preparations.each { it() }
   126                      try {
   127                          closure()
   128                      } finally {
   129                          destructions.each { it() }
   130                      }
   131                  })
   132  
   133                  base.evaluate()
   134              }
   135          }
   136      }
   137  }