我的共享库有问题。我写了一个上下文管理器来为我提供步骤对象。因此,我为steps对象编写了一个包装类,以便更轻松地对代码进行单元测试。除了withCredentials
步骤之外,我几乎包装了我需要的所有步骤。我不知道该如何关闭上下文。这是我目前执行的相关代码:
// StepExecutor.groovy
class StepExecutor implements IStepExecutor {
private def _steps
StepExecutor(steps) {
_steps = steps
}
@Override
void withCredentials(List bindings, Closure closure) {
this._steps.withCredentials(bindings, closure)
}
@Override
def usernamePassword(Map credentials) {
return this._steps.usernamePassword(credentials)
}
}
// SomeFile.groovy
steps.withCredentials([
steps.usernamePassword(
credentialsId: "Sharepoint365",
passwordVariable: "pass",
usernameVariable: "user"
)
]) {
// Do something with pass and user
}
对应的代码是withCredentials
,我在其中传递闭包,该闭包将被执行,并且我想在其中设置pass
和user
变量。我该怎么做?我试图通过查看此处的代码https://github.com/jenkinsci/credentials-binding-plugin来解决它,但是我必须承认,我不知道他们在这里做什么。
我知道我可以直接在对象上调用withCredentials,但是我想将其包装,但是我将此解决方案作为最后的选择。
谢谢。
答案 0 :(得分:0)
我发现了为什么无法直接访问pass
和user
的原因。变量存储在步骤对象本身(甚至是env?)中,因此我必须通过步骤对象访问这些变量。
因此,我编写了一个函数,它像这样调用steps.<name>
:
// StepExecutor.groovy
class StepExecutor implements IStepExecutor {
...
@Override
String get(String name) {
return this._steps."${name}"
}
}
要访问这些文件,我刚在封包内部调用了StepExecutor.get("pass/user")
。