该类首先将具有一个通用的公共httpRequest方法:
/**
* Provides Jenkins functionality required by the other utility classes.
*/
//Info: This class helps to reduce the Jenkins plug-in specific code clutter in the utility classes.
// All the Jenkins-specific code should be present in this(and more, if required) classes.
final class JenkinsUtil {
private def script
public JenkinsUtil(def script) {
this.script = script
}
/**
*
* @param link
* @param parameters Refer the httpRequest plug-in <a href="https://jenkins.io/doc/pipeline/steps/http_request/">documentation</a> for acceptable parameters.
* @return
*/
public def initiateHttpRequest(String link, Map<String, Object> parameters) {
//Remove
script.println "Link: ${link}, parameters: ${parameters}"
String validationErrorMessage = validateHttpRequestParameters(parameters)
if(validationErrorMessage != null && !validationErrorMessage.isEmpty()){
script.println "Validation error in httpRequest ${validationErrorMessage}"
return validationErrorMessage
}
String parametersString = getAppendedParametersForHttpRequest(parameters)
script.httpRequest url: link,
parametersString
}
private String validateHttpRequestParameters(Map<String,Object>parameters){
if(parameters == null || parameters.isEmpty()){
return "Parameters for the httpRequest cannot be null/empty."
}
//TODO:If the parameters contain anything other than the keys mentioned in the official documentation, return
//TODO:If the values for any of the parameter keys deviate from what the acceptable values as per the official documentation are, return
}
private String getAppendedParametersForHttpRequest(Map<String, String> parameters){
StringBuffer parametersSb = new StringBuffer()
parameters.each{
key, value -> parametersSb << key+":"+value+","
}
parametersSb.deleteCharAt(parametersSb.length()-1)
//Remove
script.println "parameters are ${parametersSb.toString()}"
return parametersSb.toString()
}
}
假设,我尝试为上述类编写一个单元测试:
import spock.lang.Specification
class JenkinsUtilTest extends Specification {
def "InitiateHttpRequest"() {
given:
JenkinsUtil jenkinsUtil = new JenkinsUtil(/*How to create a script instance*/)
String url = "https://ci.prod-jenkins.com/cjoc/"
Map<String,Object>parameters = new HashMap<>()
parameters.put("ignoreSslErrors",true)
when:
def response = jenkinsUtil.initiateHttpRequest(url,parameters)
then:
response.contains("401")
}
}
}
}
问题: