1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2024-12-12 10:55:20 +02:00
sap-jenkins-library/pkg/mock/example_dockerRunner_test.go
Stephan Aßmus f90a4f9eae
Provide an ExecRunner implementation for running commands in docker (#1606)
* ExecRunner implementation for executing commands within docker
* Add whole-file example as documentation
2020-06-02 14:24:06 +02:00

49 lines
1.3 KiB
Go

package mock_test
import (
"bytes"
"fmt"
"github.com/SAP/jenkins-library/pkg/command"
"github.com/SAP/jenkins-library/pkg/mock"
"io"
"strings"
)
type ExecRunner interface {
SetDir(d string)
SetEnv(e []string)
Stdout(out io.Writer)
Stderr(err io.Writer)
RunExecutable(e string, p ...string) error
}
func getMavenVersion(runner ExecRunner) (string, error) {
output := bytes.Buffer{}
runner.Stdout(&output)
err := runner.RunExecutable("mvn", "--version")
if err != nil {
return "", fmt.Errorf("failed to run maven: %w", err)
}
logLines := strings.Split(output.String(), "\n")
if len(logLines) < 1 {
return "", fmt.Errorf("failed to obtain maven output")
}
return logLines[0], nil
}
func ExampleDockerExecRunner_RunExecutable() {
// getMavenVersion(runner ExecRunner) executes the command "mvn --version"
// and returns the command output as string
runner := command.Command{}
localMavenVersion, _ := getMavenVersion(&runner)
dockerRunner := mock.DockerExecRunner{Runner: &runner}
_ = dockerRunner.AddExecConfig("mvn", mock.DockerExecConfig{
Image: "maven:3.6.1-jdk-8",
})
dockerMavenVersion, _ := getMavenVersion(&dockerRunner)
fmt.Printf("Your local mvn version is %v, while the version in docker is %v", localMavenVersion, dockerMavenVersion)
}