Возможно ли модульное тестирование для классов с использованием плагинов - PullRequest
0 голосов
/ 11 марта 2019

Этот класс, для начала, будет иметь общий, открытый метод 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")
    }
}

}
}

Вопросы:

  1. Как создать экземпляр сценария для передачи в JenkinsUtil (может быть, экземпляр Expando или Script)
  2. Есть ли способ (скажем, путем включения некоторых зависимостей Jenkins в build.gradle) для имитации вызова 'script.httpRequest', т.е. для имитации плагина Jenkins httpRequest
  3. Правильно ли даже думать о юнит-тестировании такого класса
  4. Правильно ли даже думать о создании такого класса
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...