1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2025-09-16 09:26:22 +02:00

test: use T.TempDir to create temporary test directory (#3721)

This commit replaces `ioutil.TempDir` with `t.TempDir` in tests. The
directory created by `t.TempDir` is automatically removed when the test
and all its subtests complete.

Prior to this commit, temporary directory created using `ioutil.TempDir`
needs to be removed manually by calling `os.RemoveAll`, which is omitted
in some tests. The error handling boilerplate e.g.
	defer func() {
		if err := os.RemoveAll(dir); err != nil {
			t.Fatal(err)
		}
	}
is also tedious, but `t.TempDir` handles this for us nicely.

Reference: https://pkg.go.dev/testing#T.TempDir
Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>

Co-authored-by: Oliver Nocon <33484802+OliverNocon@users.noreply.github.com>
This commit is contained in:
Eng Zer Jun
2022-07-12 21:19:12 +08:00
committed by GitHub
parent b7c0831b7f
commit 0f4e30e9db
47 changed files with 245 additions and 723 deletions

View File

@@ -152,17 +152,13 @@ func TestCheckoutBranchStep(t *testing.T) {
StatusCode: 200, StatusCode: 200,
} }
dir, err := ioutil.TempDir("", "test checkout branches") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
manifestFileString := ` manifestFileString := `
@@ -174,7 +170,7 @@ repositories:
- name: 'testRepo3' - name: 'testRepo3'
branch: 'testBranch3'` branch: 'testBranch3'`
err = ioutil.WriteFile("repositoriesTest.yml", []byte(manifestFileString), 0644) err := ioutil.WriteFile("repositoriesTest.yml", []byte(manifestFileString), 0644)
config := abapEnvironmentCheckoutBranchOptions{ config := abapEnvironmentCheckoutBranchOptions{
CfAPIEndpoint: "https://api.endpoint.com", CfAPIEndpoint: "https://api.endpoint.com",
@@ -206,22 +202,18 @@ repositories:
StatusCode: 200, StatusCode: 200,
} }
dir, err := ioutil.TempDir("", "test checkout branches") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
manifestFileString := `` manifestFileString := ``
manifestFileStringBody := []byte(manifestFileString) manifestFileStringBody := []byte(manifestFileString)
err = ioutil.WriteFile("repositoriesTest.yml", manifestFileStringBody, 0644) err := ioutil.WriteFile("repositoriesTest.yml", manifestFileStringBody, 0644)
config := abapEnvironmentCheckoutBranchOptions{ config := abapEnvironmentCheckoutBranchOptions{
CfAPIEndpoint: "https://api.endpoint.com", CfAPIEndpoint: "https://api.endpoint.com",
@@ -256,16 +248,12 @@ repositories:
StatusCode: 200, StatusCode: 200,
} }
dir, err := ioutil.TempDir("", "test checkout branches") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
manifestFileString := ` manifestFileString := `
@@ -273,7 +261,7 @@ repositories:
- repo: 'testRepo2'` - repo: 'testRepo2'`
manifestFileStringBody := []byte(manifestFileString) manifestFileStringBody := []byte(manifestFileString)
err = ioutil.WriteFile("repositoriesTest.yml", manifestFileStringBody, 0644) err := ioutil.WriteFile("repositoriesTest.yml", manifestFileStringBody, 0644)
config := abapEnvironmentCheckoutBranchOptions{ config := abapEnvironmentCheckoutBranchOptions{
CfAPIEndpoint: "https://api.endpoint.com", CfAPIEndpoint: "https://api.endpoint.com",

View File

@@ -41,16 +41,12 @@ func TestCloneStep(t *testing.T) {
autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com" autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com"
autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken" autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken"
dir, errDir := ioutil.TempDir("", "test read addon descriptor") dir := t.TempDir()
if errDir != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
body := `--- body := `---
@@ -190,16 +186,12 @@ func TestCloneStepErrorMessages(t *testing.T) {
autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com" autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com"
autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken" autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken"
dir, errDir := ioutil.TempDir("", "test read addon descriptor") dir := t.TempDir()
if errDir != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
body := `--- body := `---

View File

@@ -49,16 +49,12 @@ func TestRunAbapEnvironmentCreateSystem(t *testing.T) {
ServiceManifest: "customManifest.yml", ServiceManifest: "customManifest.yml",
} }
dir, err := ioutil.TempDir("", "test variable substitution") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
manifestFileString := ` manifestFileString := `
@@ -77,7 +73,7 @@ func TestRunAbapEnvironmentCreateSystem(t *testing.T) {
plan: "testPlan"` plan: "testPlan"`
manifestFileStringBody := []byte(manifestFileString) manifestFileStringBody := []byte(manifestFileString)
err = ioutil.WriteFile("customManifest.yml", manifestFileStringBody, 0644) err := ioutil.WriteFile("customManifest.yml", manifestFileStringBody, 0644)
err = runAbapEnvironmentCreateSystem(&config, nil, cf, u) err = runAbapEnvironmentCreateSystem(&config, nil, cf, u)
if assert.NoError(t, err) { if assert.NoError(t, err) {
@@ -110,16 +106,12 @@ func TestManifestGeneration(t *testing.T) {
AddonDescriptorFileName: "addon.yml", AddonDescriptorFileName: "addon.yml",
} }
dir, err := ioutil.TempDir("", "test variable substitution") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
addonYML := `addonProduct: myProduct addonYML := `addonProduct: myProduct
@@ -129,7 +121,7 @@ repositories:
` `
addonYMLBytes := []byte(addonYML) addonYMLBytes := []byte(addonYML)
err = ioutil.WriteFile("addon.yml", addonYMLBytes, 0644) err := ioutil.WriteFile("addon.yml", addonYMLBytes, 0644)
expectedResult := `create-services: expectedResult := `create-services:
- broker: testService - broker: testService
@@ -165,16 +157,12 @@ repositories:
IncludeAddon: true, IncludeAddon: true,
} }
dir, err := ioutil.TempDir("", "test variable substitution") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
addonYML := `addonProduct: myProduct addonYML := `addonProduct: myProduct
@@ -184,7 +172,7 @@ repositories:
` `
addonYMLBytes := []byte(addonYML) addonYMLBytes := []byte(addonYML)
err = ioutil.WriteFile("addon.yml", addonYMLBytes, 0644) err := ioutil.WriteFile("addon.yml", addonYMLBytes, 0644)
expectedResult := `create-services: expectedResult := `create-services:
- broker: testService - broker: testService
@@ -219,16 +207,12 @@ repositories:
AddonDescriptorFileName: "addon.yml", AddonDescriptorFileName: "addon.yml",
} }
dir, err := ioutil.TempDir("", "test variable substitution") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
addonYML := `addonProduct: myProduct addonYML := `addonProduct: myProduct
@@ -238,7 +222,7 @@ repositories:
` `
addonYMLBytes := []byte(addonYML) addonYMLBytes := []byte(addonYML)
err = ioutil.WriteFile("addon.yml", addonYMLBytes, 0644) err := ioutil.WriteFile("addon.yml", addonYMLBytes, 0644)
expectedResult := `create-services: expectedResult := `create-services:
- broker: testService - broker: testService
@@ -274,16 +258,12 @@ repositories:
IncludeAddon: true, IncludeAddon: true,
} }
dir, err := ioutil.TempDir("", "test variable substitution") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
addonYML := `addonProduct: myProduct addonYML := `addonProduct: myProduct
@@ -293,7 +273,7 @@ repositories:
` `
addonYMLBytes := []byte(addonYML) addonYMLBytes := []byte(addonYML)
err = ioutil.WriteFile("addon.yml", addonYMLBytes, 0644) err := ioutil.WriteFile("addon.yml", addonYMLBytes, 0644)
expectedResult := `create-services: expectedResult := `create-services:
- broker: testService - broker: testService

View File

@@ -1,7 +1,6 @@
package cmd package cmd
import ( import (
"io/ioutil"
"os" "os"
"testing" "testing"
@@ -22,16 +21,12 @@ func TestRunAbapEnvironmentCreateTag(t *testing.T) {
autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com" autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com"
autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken" autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken"
dir, errDir := ioutil.TempDir("", "test read addon descriptor") dir := t.TempDir()
if errDir != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
body := `--- body := `---
@@ -92,16 +87,12 @@ repositories:
autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com" autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com"
autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken" autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken"
dir, errDir := ioutil.TempDir("", "test read addon descriptor") dir := t.TempDir()
if errDir != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
body := `--- body := `---
@@ -209,16 +200,12 @@ func TestRunAbapEnvironmentCreateTagConfigurations(t *testing.T) {
autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com" autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com"
autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken" autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken"
dir, errDir := ioutil.TempDir("", "test read addon descriptor") dir := t.TempDir()
if errDir != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
body := `--- body := `---
@@ -279,10 +266,7 @@ repositories:
autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com" autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com"
autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken" autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken"
dir, errDir := ioutil.TempDir("", "test read addon descriptor") dir := t.TempDir()
if errDir != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir

View File

@@ -112,17 +112,13 @@ func TestPullStep(t *testing.T) {
StatusCode: 200, StatusCode: 200,
} }
dir, err := ioutil.TempDir("", "test pull repos") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
manifestFileString := ` manifestFileString := `
@@ -135,7 +131,7 @@ repositories:
- name: 'testRepo3' - name: 'testRepo3'
branch: 'testBranch3'` branch: 'testBranch3'`
err = ioutil.WriteFile("repositoriesTest.yml", []byte(manifestFileString), 0644) err := ioutil.WriteFile("repositoriesTest.yml", []byte(manifestFileString), 0644)
config := abapEnvironmentPullGitRepoOptions{ config := abapEnvironmentPullGitRepoOptions{
CfAPIEndpoint: "https://api.endpoint.com", CfAPIEndpoint: "https://api.endpoint.com",
@@ -159,16 +155,12 @@ repositories:
autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com" autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com"
autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken" autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken"
dir, errDir := ioutil.TempDir("", "test read addon descriptor") dir := t.TempDir()
if errDir != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
body := `--- body := `---
@@ -220,16 +212,12 @@ repositories:
autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com" autils.ReturnedConnectionDetailsHTTP.URL = "https://example.com"
autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken" autils.ReturnedConnectionDetailsHTTP.XCsrfToken = "xcsrftoken"
dir, errDir := ioutil.TempDir("", "test read addon descriptor") dir := t.TempDir()
if errDir != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
body := `--- body := `---
@@ -368,22 +356,18 @@ repositories:
StatusCode: 200, StatusCode: 200,
} }
dir, err := ioutil.TempDir("", "test pull repos") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
manifestFileString := `` manifestFileString := ``
manifestFileStringBody := []byte(manifestFileString) manifestFileStringBody := []byte(manifestFileString)
err = ioutil.WriteFile("repositoriesTest.yml", manifestFileStringBody, 0644) err := ioutil.WriteFile("repositoriesTest.yml", manifestFileStringBody, 0644)
config := abapEnvironmentPullGitRepoOptions{ config := abapEnvironmentPullGitRepoOptions{
CfAPIEndpoint: "https://api.endpoint.com", CfAPIEndpoint: "https://api.endpoint.com",
@@ -419,16 +403,12 @@ repositories:
StatusCode: 200, StatusCode: 200,
} }
dir, err := ioutil.TempDir("", "test pull repos") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
manifestFileString := ` manifestFileString := `
@@ -436,7 +416,7 @@ repositories:
- repo: 'testRepo2'` - repo: 'testRepo2'`
manifestFileStringBody := []byte(manifestFileString) manifestFileStringBody := []byte(manifestFileString)
err = ioutil.WriteFile("repositoriesTest.yml", manifestFileStringBody, 0644) err := ioutil.WriteFile("repositoriesTest.yml", manifestFileStringBody, 0644)
config := abapEnvironmentPullGitRepoOptions{ config := abapEnvironmentPullGitRepoOptions{
CfAPIEndpoint: "https://api.endpoint.com", CfAPIEndpoint: "https://api.endpoint.com",

View File

@@ -510,24 +510,20 @@ func TestRunAbapEnvironmentPushATCSystemConfig(t *testing.T) {
StatusCode: 200, StatusCode: 200,
} }
dir, err := ioutil.TempDir("", "test dir for test file with ATC System Configuration") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
config := abapEnvironmentPushATCSystemConfigOptions{AtcSystemConfigFilePath: "atcSystemConfig.json"} config := abapEnvironmentPushATCSystemConfigOptions{AtcSystemConfigFilePath: "atcSystemConfig.json"}
atcSystemConfigFileString := `` atcSystemConfigFileString := ``
err = ioutil.WriteFile(config.AtcSystemConfigFilePath, []byte(atcSystemConfigFileString), 0644) err := ioutil.WriteFile(config.AtcSystemConfigFilePath, []byte(atcSystemConfigFileString), 0644)
if err != nil { if err != nil {
t.Fatal("Failed to write File: " + config.AtcSystemConfigFilePath) t.Fatal("Failed to write File: " + config.AtcSystemConfigFilePath)
} }
@@ -555,17 +551,13 @@ func TestRunAbapEnvironmentPushATCSystemConfig(t *testing.T) {
StatusCode: 200, StatusCode: 200,
} }
dir, err := ioutil.TempDir("", "test dir for test file with ATC System Configuration") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
config := abapEnvironmentPushATCSystemConfigOptions{AtcSystemConfigFilePath: "atcSystemConfig.json"} config := abapEnvironmentPushATCSystemConfigOptions{AtcSystemConfigFilePath: "atcSystemConfig.json"}
@@ -593,7 +585,7 @@ func TestRunAbapEnvironmentPushATCSystemConfig(t *testing.T) {
] ]
} }
` `
err = ioutil.WriteFile(config.AtcSystemConfigFilePath, []byte(atcSystemConfigFileString), 0644) err := ioutil.WriteFile(config.AtcSystemConfigFilePath, []byte(atcSystemConfigFileString), 0644)
if err != nil { if err != nil {
t.Fatal("Failed to write File: " + config.AtcSystemConfigFilePath) t.Fatal("Failed to write File: " + config.AtcSystemConfigFilePath)
} }
@@ -621,17 +613,13 @@ func TestRunAbapEnvironmentPushATCSystemConfig(t *testing.T) {
StatusCode: 200, StatusCode: 200,
} }
dir, err := ioutil.TempDir("", "test dir for test file with ATC System Configuration") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
config := abapEnvironmentPushATCSystemConfigOptions{AtcSystemConfigFilePath: "atcSystemConfig.json"} config := abapEnvironmentPushATCSystemConfigOptions{AtcSystemConfigFilePath: "atcSystemConfig.json"}
@@ -659,7 +647,7 @@ func TestRunAbapEnvironmentPushATCSystemConfig(t *testing.T) {
] ]
} }
` `
err = ioutil.WriteFile(config.AtcSystemConfigFilePath, []byte(atcSystemConfigFileString), 0644) err := ioutil.WriteFile(config.AtcSystemConfigFilePath, []byte(atcSystemConfigFileString), 0644)
if err != nil { if err != nil {
t.Fatal("Failed to write File: " + config.AtcSystemConfigFilePath) t.Fatal("Failed to write File: " + config.AtcSystemConfigFilePath)
} }

View File

@@ -221,16 +221,12 @@ func TestGetResultATCRun(t *testing.T) {
func TestParseATCResult(t *testing.T) { func TestParseATCResult(t *testing.T) {
t.Run("succes case: test parsing example XML result", func(t *testing.T) { t.Run("succes case: test parsing example XML result", func(t *testing.T) {
dir, err := ioutil.TempDir("", "test get result ATC run") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
bodyString := `<?xml version="1.0" encoding="UTF-8"?> bodyString := `<?xml version="1.0" encoding="UTF-8"?>
<checkstyle> <checkstyle>
@@ -246,26 +242,22 @@ func TestParseATCResult(t *testing.T) {
</file> </file>
</checkstyle>` </checkstyle>`
body := []byte(bodyString) body := []byte(bodyString)
err = logAndPersistATCResult(body, "ATCResults.xml", false) err := logAndPersistATCResult(body, "ATCResults.xml", false)
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
}) })
t.Run("succes case: test parsing empty XML result", func(t *testing.T) { t.Run("succes case: test parsing empty XML result", func(t *testing.T) {
dir, err := ioutil.TempDir("", "test get result ATC run") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
bodyString := `<?xml version="1.0" encoding="UTF-8"?> bodyString := `<?xml version="1.0" encoding="UTF-8"?>
<checkstyle> <checkstyle>
</checkstyle>` </checkstyle>`
body := []byte(bodyString) body := []byte(bodyString)
err = logAndPersistATCResult(body, "ATCResults.xml", false) err := logAndPersistATCResult(body, "ATCResults.xml", false)
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
}) })
t.Run("failure case: parsing empty xml", func(t *testing.T) { t.Run("failure case: parsing empty xml", func(t *testing.T) {
@@ -276,20 +268,16 @@ func TestParseATCResult(t *testing.T) {
assert.EqualError(t, err, "Parsing ATC result failed: Body is empty, can't parse empty body") assert.EqualError(t, err, "Parsing ATC result failed: Body is empty, can't parse empty body")
}) })
t.Run("failure case: html response", func(t *testing.T) { t.Run("failure case: html response", func(t *testing.T) {
dir, err := ioutil.TempDir("", "test get result ATC run") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
bodyString := `<html><head><title>HTMLTestResponse</title</head></html>` bodyString := `<html><head><title>HTMLTestResponse</title</head></html>`
body := []byte(bodyString) body := []byte(bodyString)
err = logAndPersistATCResult(body, "ATCResults.xml", false) err := logAndPersistATCResult(body, "ATCResults.xml", false)
assert.EqualError(t, err, "The Software Component could not be checked. Please make sure the respective Software Component has been cloned successfully on the system") assert.EqualError(t, err, "The Software Component could not be checked. Please make sure the respective Software Component has been cloned successfully on the system")
}) })
} }
@@ -413,16 +401,12 @@ func TestResolveConfiguration(t *testing.T) {
AtcConfig: "atc.yml", AtcConfig: "atc.yml",
} }
dir, err := ioutil.TempDir("", "atcDir") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
yamlBody := `checkvariant: MY_TEST yamlBody := `checkvariant: MY_TEST
@@ -437,7 +421,7 @@ atcobjects:
- name: /DMO/SWC - name: /DMO/SWC
` `
err = ioutil.WriteFile(config.AtcConfig, []byte(yamlBody), 0644) err := ioutil.WriteFile(config.AtcConfig, []byte(yamlBody), 0644)
if assert.Equal(t, err, nil) { if assert.Equal(t, err, nil) {
bodyString, err := buildATCRequestBody(config) bodyString, err := buildATCRequestBody(config)
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
@@ -452,16 +436,12 @@ atcobjects:
AtcConfig: "atc.yml", AtcConfig: "atc.yml",
} }
dir, err := ioutil.TempDir("", "atcDir") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
yamlBody := `checkvariant: MY_TEST yamlBody := `checkvariant: MY_TEST
@@ -479,7 +459,7 @@ objectset:
` `
expectedBodyString := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><atc:runparameters xmlns:atc=\"http://www.sap.com/adt/atc\" xmlns:obj=\"http://www.sap.com/adt/objectset\" checkVariant=\"MY_TEST\" configuration=\"MY_CONFIG\"><osl:objectSet xsi:type=\"multiPropertySet\" xmlns:osl=\"http://www.sap.com/api/osl\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><osl:package name=\"Z_TEST\"/><osl:package name=\"Z_TEST_TREE\" includeSubpackages=\"true\"/><osl:softwareComponent name=\"Z_TEST\"/><osl:softwareComponent name=\"/DMO/SWC\"/></osl:objectSet></atc:runparameters>" expectedBodyString := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><atc:runparameters xmlns:atc=\"http://www.sap.com/adt/atc\" xmlns:obj=\"http://www.sap.com/adt/objectset\" checkVariant=\"MY_TEST\" configuration=\"MY_CONFIG\"><osl:objectSet xsi:type=\"multiPropertySet\" xmlns:osl=\"http://www.sap.com/api/osl\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><osl:package name=\"Z_TEST\"/><osl:package name=\"Z_TEST_TREE\" includeSubpackages=\"true\"/><osl:softwareComponent name=\"Z_TEST\"/><osl:softwareComponent name=\"/DMO/SWC\"/></osl:objectSet></atc:runparameters>"
err = ioutil.WriteFile(config.AtcConfig, []byte(yamlBody), 0644) err := ioutil.WriteFile(config.AtcConfig, []byte(yamlBody), 0644)
if assert.Equal(t, err, nil) { if assert.Equal(t, err, nil) {
bodyString, err := buildATCRequestBody(config) bodyString, err := buildATCRequestBody(config)
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
@@ -494,16 +474,12 @@ objectset:
Repositories: "repo.yml", Repositories: "repo.yml",
} }
dir, err := ioutil.TempDir("", "test parse AUnit yaml config2") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
yamlBody := `repositories: yamlBody := `repositories:
@@ -511,7 +487,7 @@ objectset:
- name: /DMO/SWC - name: /DMO/SWC
` `
err = ioutil.WriteFile(config.Repositories, []byte(yamlBody), 0644) err := ioutil.WriteFile(config.Repositories, []byte(yamlBody), 0644)
if assert.Equal(t, err, nil) { if assert.Equal(t, err, nil) {
bodyString, err := buildATCRequestBody(config) bodyString, err := buildATCRequestBody(config)
assert.Equal(t, nil, err) assert.Equal(t, nil, err)

View File

@@ -260,16 +260,12 @@ func TestBuildAUnitRequestBody(t *testing.T) {
Repositories: "repositories.yml", Repositories: "repositories.yml",
} }
dir, err := ioutil.TempDir("", "test parse AUnit yaml config2") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
repositories := `repositories: repositories := `repositories:
@@ -277,7 +273,7 @@ func TestBuildAUnitRequestBody(t *testing.T) {
branch: main branch: main
` `
expectedBodyString := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><aunit:run title=\"AUnit Test Run\" context=\"ABAP Environment Pipeline\" xmlns:aunit=\"http://www.sap.com/adt/api/aunit\"><aunit:options><aunit:measurements type=\"none\"/><aunit:scope ownTests=\"true\" foreignTests=\"true\"/><aunit:riskLevel harmless=\"true\" dangerous=\"true\" critical=\"true\"/><aunit:duration short=\"true\" medium=\"true\" long=\"true\"/></aunit:options><osl:objectSet xsi:type=\"multiPropertySet\" xmlns:osl=\"http://www.sap.com/api/osl\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><osl:softwareComponent name=\"/DMO/REPO\"/></osl:objectSet></aunit:run>" expectedBodyString := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><aunit:run title=\"AUnit Test Run\" context=\"ABAP Environment Pipeline\" xmlns:aunit=\"http://www.sap.com/adt/api/aunit\"><aunit:options><aunit:measurements type=\"none\"/><aunit:scope ownTests=\"true\" foreignTests=\"true\"/><aunit:riskLevel harmless=\"true\" dangerous=\"true\" critical=\"true\"/><aunit:duration short=\"true\" medium=\"true\" long=\"true\"/></aunit:options><osl:objectSet xsi:type=\"multiPropertySet\" xmlns:osl=\"http://www.sap.com/api/osl\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><osl:softwareComponent name=\"/DMO/REPO\"/></osl:objectSet></aunit:run>"
err = ioutil.WriteFile(config.Repositories, []byte(repositories), 0644) err := ioutil.WriteFile(config.Repositories, []byte(repositories), 0644)
if assert.Equal(t, err, nil) { if assert.Equal(t, err, nil) {
bodyString, err := buildAUnitRequestBody(config) bodyString, err := buildAUnitRequestBody(config)
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
@@ -292,16 +288,12 @@ func TestBuildAUnitRequestBody(t *testing.T) {
AUnitConfig: "aunit.yml", AUnitConfig: "aunit.yml",
} }
dir, err := ioutil.TempDir("", "test parse AUnit yaml config2") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
yamlBody := `title: My AUnit run yamlBody := `title: My AUnit run
@@ -313,7 +305,7 @@ objectset:
- name: /DMO/SWC - name: /DMO/SWC
` `
expectedBodyString := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><aunit:run title=\"My AUnit run\" context=\"ABAP Environment Pipeline\" xmlns:aunit=\"http://www.sap.com/adt/api/aunit\"><aunit:options><aunit:measurements type=\"none\"/><aunit:scope ownTests=\"true\" foreignTests=\"true\"/><aunit:riskLevel harmless=\"true\" dangerous=\"true\" critical=\"true\"/><aunit:duration short=\"true\" medium=\"true\" long=\"true\"/></aunit:options><osl:objectSet xsi:type=\"multiPropertySet\" xmlns:osl=\"http://www.sap.com/api/osl\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><osl:package name=\"Z_TEST\"/><osl:softwareComponent name=\"Z_TEST\"/><osl:softwareComponent name=\"/DMO/SWC\"/></osl:objectSet></aunit:run>" expectedBodyString := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><aunit:run title=\"My AUnit run\" context=\"ABAP Environment Pipeline\" xmlns:aunit=\"http://www.sap.com/adt/api/aunit\"><aunit:options><aunit:measurements type=\"none\"/><aunit:scope ownTests=\"true\" foreignTests=\"true\"/><aunit:riskLevel harmless=\"true\" dangerous=\"true\" critical=\"true\"/><aunit:duration short=\"true\" medium=\"true\" long=\"true\"/></aunit:options><osl:objectSet xsi:type=\"multiPropertySet\" xmlns:osl=\"http://www.sap.com/api/osl\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><osl:package name=\"Z_TEST\"/><osl:softwareComponent name=\"Z_TEST\"/><osl:softwareComponent name=\"/DMO/SWC\"/></osl:objectSet></aunit:run>"
err = ioutil.WriteFile(config.AUnitConfig, []byte(yamlBody), 0644) err := ioutil.WriteFile(config.AUnitConfig, []byte(yamlBody), 0644)
if assert.Equal(t, err, nil) { if assert.Equal(t, err, nil) {
bodyString, err := buildAUnitRequestBody(config) bodyString, err := buildAUnitRequestBody(config)
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
@@ -328,16 +320,12 @@ objectset:
AUnitConfig: "aunit.yml", AUnitConfig: "aunit.yml",
} }
dir, err := ioutil.TempDir("", "test parse AUnit yaml config2") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
yamlBody := `title: My AUnit run yamlBody := `title: My AUnit run
@@ -351,7 +339,7 @@ objectset:
- name: /DMO/SWC - name: /DMO/SWC
` `
expectedBodyString := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><aunit:run title=\"My AUnit run\" context=\"ABAP Environment Pipeline\" xmlns:aunit=\"http://www.sap.com/adt/api/aunit\"><aunit:options><aunit:measurements type=\"none\"/><aunit:scope ownTests=\"true\" foreignTests=\"true\"/><aunit:riskLevel harmless=\"true\" dangerous=\"true\" critical=\"true\"/><aunit:duration short=\"true\" medium=\"true\" long=\"true\"/></aunit:options><osl:objectSet xsi:type=\"multiPropertySet\" xmlns:osl=\"http://www.sap.com/api/osl\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><osl:package name=\"Z_TEST\"/><osl:softwareComponent name=\"Z_TEST\"/><osl:softwareComponent name=\"/DMO/SWC\"/></osl:objectSet></aunit:run>" expectedBodyString := "<?xml version=\"1.0\" encoding=\"UTF-8\"?><aunit:run title=\"My AUnit run\" context=\"ABAP Environment Pipeline\" xmlns:aunit=\"http://www.sap.com/adt/api/aunit\"><aunit:options><aunit:measurements type=\"none\"/><aunit:scope ownTests=\"true\" foreignTests=\"true\"/><aunit:riskLevel harmless=\"true\" dangerous=\"true\" critical=\"true\"/><aunit:duration short=\"true\" medium=\"true\" long=\"true\"/></aunit:options><osl:objectSet xsi:type=\"multiPropertySet\" xmlns:osl=\"http://www.sap.com/api/osl\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><osl:package name=\"Z_TEST\"/><osl:softwareComponent name=\"Z_TEST\"/><osl:softwareComponent name=\"/DMO/SWC\"/></osl:objectSet></aunit:run>"
err = ioutil.WriteFile(config.AUnitConfig, []byte(yamlBody), 0644) err := ioutil.WriteFile(config.AUnitConfig, []byte(yamlBody), 0644)
if assert.Equal(t, err, nil) { if assert.Equal(t, err, nil) {
bodyString, err := buildAUnitRequestBody(config) bodyString, err := buildAUnitRequestBody(config)
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
@@ -400,16 +388,12 @@ func TestTriggerAUnitrun(t *testing.T) {
URL: "https://api.endpoint.com/Entity/", URL: "https://api.endpoint.com/Entity/",
} }
dir, err := ioutil.TempDir("", "test parse AUnit yaml config") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
yamlBody := `title: My AUnit run yamlBody := `title: My AUnit run
@@ -434,7 +418,7 @@ objectset:
- name: Z_TEST - name: Z_TEST
` `
err = ioutil.WriteFile(config.AUnitConfig, []byte(yamlBody), 0644) err := ioutil.WriteFile(config.AUnitConfig, []byte(yamlBody), 0644)
if assert.Equal(t, err, nil) { if assert.Equal(t, err, nil) {
_, err := triggerAUnitrun(config, con, client) _, err := triggerAUnitrun(config, con, client)
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
@@ -458,16 +442,12 @@ objectset:
URL: "https://api.endpoint.com/Entity/", URL: "https://api.endpoint.com/Entity/",
} }
dir, err := ioutil.TempDir("", "test parse AUnit yaml config2") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
yamlBody := `title: My AUnit run yamlBody := `title: My AUnit run
@@ -493,7 +473,7 @@ objectset:
- name: Z_TEST_SC - name: Z_TEST_SC
` `
err = ioutil.WriteFile(config.AUnitConfig, []byte(yamlBody), 0644) err := ioutil.WriteFile(config.AUnitConfig, []byte(yamlBody), 0644)
if assert.Equal(t, err, nil) { if assert.Equal(t, err, nil) {
_, err := triggerAUnitrun(config, con, client) _, err := triggerAUnitrun(config, con, client)
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
@@ -506,39 +486,31 @@ func TestParseAUnitResult(t *testing.T) {
t.Run("succes case: test parsing example XML result", func(t *testing.T) { t.Run("succes case: test parsing example XML result", func(t *testing.T) {
dir, err := ioutil.TempDir("", "test get result AUnit test run") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
bodyString := `<?xml version="1.0" encoding="utf-8"?><testsuites title="My AUnit run" system="TST" client="100" executedBy="TESTUSER" time="000.000" timestamp="2021-01-01T00:00:00Z" failures="2" errors="2" skipped="0" asserts="0" tests="2"><testsuite name="" tests="2" failures="2" errors="0" skipped="0" asserts="0" package="testpackage" timestamp="2021-01-01T00:00:00ZZ" time="0.000" hostname="test"><testcase classname="test" name="execute" time="0.000" asserts="2"><failure message="testMessage1" type="Assert Failure">Test1</failure><failure message="testMessage2" type="Assert Failure">Test2</failure></testcase></testsuite></testsuites>` bodyString := `<?xml version="1.0" encoding="utf-8"?><testsuites title="My AUnit run" system="TST" client="100" executedBy="TESTUSER" time="000.000" timestamp="2021-01-01T00:00:00Z" failures="2" errors="2" skipped="0" asserts="0" tests="2"><testsuite name="" tests="2" failures="2" errors="0" skipped="0" asserts="0" package="testpackage" timestamp="2021-01-01T00:00:00ZZ" time="0.000" hostname="test"><testcase classname="test" name="execute" time="0.000" asserts="2"><failure message="testMessage1" type="Assert Failure">Test1</failure><failure message="testMessage2" type="Assert Failure">Test2</failure></testcase></testsuite></testsuites>`
body := []byte(bodyString) body := []byte(bodyString)
err = persistAUnitResult(body, "AUnitResults.xml", false) err := persistAUnitResult(body, "AUnitResults.xml", false)
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
}) })
t.Run("succes case: test parsing empty AUnit run XML result", func(t *testing.T) { t.Run("succes case: test parsing empty AUnit run XML result", func(t *testing.T) {
dir, err := ioutil.TempDir("", "test get result AUnit test run") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
bodyString := `<?xml version="1.0" encoding="UTF-8"?>` bodyString := `<?xml version="1.0" encoding="UTF-8"?>`
body := []byte(bodyString) body := []byte(bodyString)
err = persistAUnitResult(body, "AUnitResults.xml", false) err := persistAUnitResult(body, "AUnitResults.xml", false)
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
}) })

View File

@@ -1,8 +1,6 @@
package cmd package cmd
import ( import (
"io/ioutil"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -19,11 +17,7 @@ func TestRunApiProxyDownload(t *testing.T) {
t.Parallel() t.Parallel()
t.Run("Successfull Download of API Proxy", func(t *testing.T) { t.Run("Successfull Download of API Proxy", func(t *testing.T) {
tempDir, tmpErr := ioutil.TempDir("", "") tempDir := t.TempDir()
defer os.RemoveAll(tempDir) // clean up
if tmpErr != nil {
t.Fatal("Failed to create temporary directory")
}
apiServiceKey := `{ apiServiceKey := `{
"oauth": { "oauth": {
"url": "https://demo", "url": "https://demo",

View File

@@ -342,14 +342,9 @@ func TestZipFolder(t *testing.T) {
t.Run("zip files successfully", func(t *testing.T) { t.Run("zip files successfully", func(t *testing.T) {
t.Parallel() t.Parallel()
dir, err := ioutil.TempDir("", "test zip files") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
err = ioutil.WriteFile(filepath.Join(dir, "abcd.go"), []byte("abcd.go"), 0700) err := ioutil.WriteFile(filepath.Join(dir, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
err = ioutil.WriteFile(filepath.Join(dir, "abcd.yaml"), []byte("abcd.yaml"), 0700) err = ioutil.WriteFile(filepath.Join(dir, "abcd.yaml"), []byte("abcd.yaml"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
@@ -378,14 +373,9 @@ func TestZipFolder(t *testing.T) {
t.Run("error on query file info header", func(t *testing.T) { t.Run("error on query file info header", func(t *testing.T) {
t.Parallel() t.Parallel()
dir, err := ioutil.TempDir("", "test zip files") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
err = ioutil.WriteFile(filepath.Join(dir, "abcd.go"), []byte("abcd.go"), 0700) err := ioutil.WriteFile(filepath.Join(dir, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
err = os.Mkdir(filepath.Join(dir, "somepath"), 0700) err = os.Mkdir(filepath.Join(dir, "somepath"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
@@ -406,14 +396,9 @@ func TestZipFolder(t *testing.T) {
t.Run("error on os stat", func(t *testing.T) { t.Run("error on os stat", func(t *testing.T) {
t.Parallel() t.Parallel()
dir, err := ioutil.TempDir("", "test zip files") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
err = ioutil.WriteFile(filepath.Join(dir, "abcd.go"), []byte("abcd.go"), 0700) err := ioutil.WriteFile(filepath.Join(dir, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
err = os.Mkdir(filepath.Join(dir, "somepath"), 0700) err = os.Mkdir(filepath.Join(dir, "somepath"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
@@ -434,14 +419,9 @@ func TestZipFolder(t *testing.T) {
t.Run("error on os Open", func(t *testing.T) { t.Run("error on os Open", func(t *testing.T) {
t.Parallel() t.Parallel()
dir, err := ioutil.TempDir("", "test zip files") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
err = ioutil.WriteFile(filepath.Join(dir, "abcd.go"), []byte("abcd.go"), 0700) err := ioutil.WriteFile(filepath.Join(dir, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
err = os.Mkdir(filepath.Join(dir, "somepath"), 0700) err = os.Mkdir(filepath.Join(dir, "somepath"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
@@ -486,12 +466,7 @@ func TestGetDetailedResults(t *testing.T) {
</Result> </Result>
</Query> </Query>
</CxXMLResults>`)} </CxXMLResults>`)}
dir, err := ioutil.TempDir("", "test detailed results") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
result, err := getDetailedResults(sys, filepath.Join(dir, "abc.xml"), 2635, newCheckmarxExecuteScanUtilsMock()) result, err := getDetailedResults(sys, filepath.Join(dir, "abc.xml"), 2635, newCheckmarxExecuteScanUtilsMock())
assert.NoError(t, err, "error occurred but none expected") assert.NoError(t, err, "error occurred but none expected")
assert.Equal(t, "2", result["ProjectId"], "Project ID incorrect") assert.Equal(t, "2", result["ProjectId"], "Project ID incorrect")
@@ -524,15 +499,10 @@ func TestGetDetailedResults(t *testing.T) {
</Result> </Result>
</Query> </Query>
</CxXMLResults>`)} </CxXMLResults>`)}
dir, err := ioutil.TempDir("", "test detailed results") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
utils := newCheckmarxExecuteScanUtilsMock() utils := newCheckmarxExecuteScanUtilsMock()
utils.errorOnWriteFile = true utils.errorOnWriteFile = true
_, err = getDetailedResults(sys, filepath.Join(dir, "abc.xml"), 2635, utils) _, err := getDetailedResults(sys, filepath.Join(dir, "abc.xml"), 2635, utils)
assert.EqualError(t, err, "failed to write file: error on WriteFile") assert.EqualError(t, err, "failed to write file: error on WriteFile")
}) })
} }
@@ -542,13 +512,8 @@ func TestRunScan(t *testing.T) {
sys := &systemMockForExistingProject{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`)} sys := &systemMockForExistingProject{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`)}
options := checkmarxExecuteScanOptions{ProjectName: "TestExisting", VulnerabilityThresholdUnit: "absolute", FullScanCycle: "2", Incremental: true, FullScansScheduled: true, Preset: "10048", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true} options := checkmarxExecuteScanOptions{ProjectName: "TestExisting", VulnerabilityThresholdUnit: "absolute", FullScanCycle: "2", Incremental: true, FullScansScheduled: true, Preset: "10048", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true}
workspace, err := ioutil.TempDir("", "workspace1") workspace := t.TempDir()
if err != nil { err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
err = ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
options.FilterPattern = "**/abcd.go" options.FilterPattern = "**/abcd.go"
@@ -570,13 +535,8 @@ func TestRunScan_nonNumeralPreset(t *testing.T) {
sys := &systemMockForExistingProject{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`)} sys := &systemMockForExistingProject{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`)}
options := checkmarxExecuteScanOptions{ProjectName: "TestExisting", VulnerabilityThresholdUnit: "absolute", FullScanCycle: "2", Incremental: true, FullScansScheduled: true, Preset: "SAP_JS_Default", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true} options := checkmarxExecuteScanOptions{ProjectName: "TestExisting", VulnerabilityThresholdUnit: "absolute", FullScanCycle: "2", Incremental: true, FullScansScheduled: true, Preset: "SAP_JS_Default", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true}
workspace, err := ioutil.TempDir("", "workspace1") workspace := t.TempDir()
if err != nil { err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
err = ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
options.FilterPattern = "**/abcd.go" options.FilterPattern = "**/abcd.go"
@@ -594,13 +554,8 @@ func TestRunOptimizedScan(t *testing.T) {
sys := &systemMockForExistingProject{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`)} sys := &systemMockForExistingProject{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`)}
options := checkmarxExecuteScanOptions{IsOptimizedAndScheduled: true, ProjectName: "TestExisting", VulnerabilityThresholdUnit: "absolute", FullScanCycle: "1", Incremental: true, FullScansScheduled: true, Preset: "10048", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true} options := checkmarxExecuteScanOptions{IsOptimizedAndScheduled: true, ProjectName: "TestExisting", VulnerabilityThresholdUnit: "absolute", FullScanCycle: "1", Incremental: true, FullScansScheduled: true, Preset: "10048", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true}
workspace, err := ioutil.TempDir("", "workspace1") workspace := t.TempDir()
if err != nil { err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
err = ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
options.FilterPattern = "**/abcd.go" options.FilterPattern = "**/abcd.go"
@@ -643,19 +598,14 @@ func TestVerifyOnly(t *testing.T) {
sys := &systemMockForExistingProject{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`)} sys := &systemMockForExistingProject{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`)}
options := checkmarxExecuteScanOptions{VerifyOnly: true, ProjectName: "TestExisting", VulnerabilityThresholdUnit: "absolute", FullScanCycle: "2", Incremental: true, FullScansScheduled: true, Preset: "10048", TeamName: "OpenSource/Cracks/15", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true} options := checkmarxExecuteScanOptions{VerifyOnly: true, ProjectName: "TestExisting", VulnerabilityThresholdUnit: "absolute", FullScanCycle: "2", Incremental: true, FullScansScheduled: true, Preset: "10048", TeamName: "OpenSource/Cracks/15", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true}
workspace, err := ioutil.TempDir("", "workspace1") workspace := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
influx := checkmarxExecuteScanInflux{} influx := checkmarxExecuteScanInflux{}
utilsMock := newCheckmarxExecuteScanUtilsMock() utilsMock := newCheckmarxExecuteScanUtilsMock()
utilsMock.workspace = workspace utilsMock.workspace = workspace
err = runScan(options, sys, &influx, utilsMock) err := runScan(options, sys, &influx, utilsMock)
assert.NoError(t, err, "error occurred but none expected") assert.NoError(t, err, "error occurred but none expected")
assert.Equal(t, false, sys.scanProjectCalled, "ScanProject was invoked but shouldn't") assert.Equal(t, false, sys.scanProjectCalled, "ScanProject was invoked but shouldn't")
} }
@@ -665,12 +615,7 @@ func TestVerifyOnly_errorOnWriteFileDoesNotBlock(t *testing.T) {
sys := &systemMockForExistingProject{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`)} sys := &systemMockForExistingProject{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`)}
options := checkmarxExecuteScanOptions{VerifyOnly: true, ProjectName: "TestExisting", VulnerabilityThresholdUnit: "absolute", FullScanCycle: "2", Incremental: true, FullScansScheduled: true, Preset: "10048", TeamName: "OpenSource/Cracks/15", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true} options := checkmarxExecuteScanOptions{VerifyOnly: true, ProjectName: "TestExisting", VulnerabilityThresholdUnit: "absolute", FullScanCycle: "2", Incremental: true, FullScansScheduled: true, Preset: "10048", TeamName: "OpenSource/Cracks/15", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true}
workspace, err := ioutil.TempDir("", "workspace1") workspace := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
influx := checkmarxExecuteScanInflux{} influx := checkmarxExecuteScanInflux{}
@@ -678,7 +623,7 @@ func TestVerifyOnly_errorOnWriteFileDoesNotBlock(t *testing.T) {
utilsMock.workspace = workspace utilsMock.workspace = workspace
utilsMock.errorOnWriteFile = true utilsMock.errorOnWriteFile = true
err = runScan(options, sys, &influx, utilsMock) err := runScan(options, sys, &influx, utilsMock)
assert.EqualError(t, err, "scan, upload, and result validation returned an error: project TestExisting not compliant: failed to get detailed results: failed to write file: error on WriteFile") assert.EqualError(t, err, "scan, upload, and result validation returned an error: project TestExisting not compliant: failed to get detailed results: failed to write file: error on WriteFile")
} }
@@ -687,13 +632,8 @@ func TestRunScanWOtherCycle(t *testing.T) {
sys := &systemMock{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`), createProject: true} sys := &systemMock{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`), createProject: true}
options := checkmarxExecuteScanOptions{VulnerabilityThresholdUnit: "percentage", FullScanCycle: "3", Incremental: true, FullScansScheduled: true, Preset: "123", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true} options := checkmarxExecuteScanOptions{VulnerabilityThresholdUnit: "percentage", FullScanCycle: "3", Incremental: true, FullScansScheduled: true, Preset: "123", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true}
workspace, err := ioutil.TempDir("", "workspace2") workspace := t.TempDir()
if err != nil { err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
err = ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
options.FilterPattern = "**/abcd.go" options.FilterPattern = "**/abcd.go"
@@ -714,12 +654,7 @@ func TestRunScanErrorInZip(t *testing.T) {
sys := &systemMock{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`), createProject: true} sys := &systemMock{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`), createProject: true}
options := checkmarxExecuteScanOptions{VulnerabilityThresholdUnit: "percentage", FullScanCycle: "3", Incremental: true, FullScansScheduled: true, Preset: "123", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true} options := checkmarxExecuteScanOptions{VulnerabilityThresholdUnit: "percentage", FullScanCycle: "3", Incremental: true, FullScansScheduled: true, Preset: "123", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true}
workspace, err := ioutil.TempDir("", "workspace2") workspace := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
influx := checkmarxExecuteScanInflux{} influx := checkmarxExecuteScanInflux{}
@@ -727,7 +662,7 @@ func TestRunScanErrorInZip(t *testing.T) {
utilsMock.workspace = workspace utilsMock.workspace = workspace
utilsMock.errorOnFileInfoHeader = true utilsMock.errorOnFileInfoHeader = true
err = runScan(options, sys, &influx, utilsMock) err := runScan(options, sys, &influx, utilsMock)
assert.EqualError(t, err, "scan, upload, and result validation returned an error: failed to zip workspace files: failed to compact folder: error on FileInfoHeader") assert.EqualError(t, err, "scan, upload, and result validation returned an error: failed to zip workspace files: failed to compact folder: error on FileInfoHeader")
} }
@@ -736,13 +671,8 @@ func TestRunScanForPullRequest(t *testing.T) {
sys := &systemMock{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`)} sys := &systemMock{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`)}
options := checkmarxExecuteScanOptions{PullRequestName: "PR-19", ProjectName: "Test", VulnerabilityThresholdUnit: "percentage", FullScanCycle: "3", Incremental: true, FullScansScheduled: true, Preset: "123", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true, AvoidDuplicateProjectScans: false} options := checkmarxExecuteScanOptions{PullRequestName: "PR-19", ProjectName: "Test", VulnerabilityThresholdUnit: "percentage", FullScanCycle: "3", Incremental: true, FullScansScheduled: true, Preset: "123", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true, AvoidDuplicateProjectScans: false}
workspace, err := ioutil.TempDir("", "workspace3") workspace := t.TempDir()
if err != nil { err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
err = ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
options.FilterPattern = "**/abcd.go" options.FilterPattern = "**/abcd.go"
@@ -762,13 +692,8 @@ func TestRunScanForPullRequestProjectNew(t *testing.T) {
sys := &systemMock{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`), createProject: true} sys := &systemMock{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`), createProject: true}
options := checkmarxExecuteScanOptions{PullRequestName: "PR-17", ProjectName: "Test", AvoidDuplicateProjectScans: true, VulnerabilityThresholdUnit: "percentage", FullScanCycle: "3", Incremental: true, FullScansScheduled: true, Preset: "10048", TeamName: "OpenSource/Cracks/15", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true} options := checkmarxExecuteScanOptions{PullRequestName: "PR-17", ProjectName: "Test", AvoidDuplicateProjectScans: true, VulnerabilityThresholdUnit: "percentage", FullScanCycle: "3", Incremental: true, FullScansScheduled: true, Preset: "10048", TeamName: "OpenSource/Cracks/15", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true}
workspace, err := ioutil.TempDir("", "workspace4") workspace := t.TempDir()
if err != nil { err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
err = ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
options.FilterPattern = "**/abcd.go" options.FilterPattern = "**/abcd.go"
@@ -789,13 +714,8 @@ func TestRunScanForPullRequestProjectNew_nonNumeralPreset(t *testing.T) {
sys := &systemMock{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`), createProject: true} sys := &systemMock{response: []byte(`<?xml version="1.0" encoding="utf-8"?><CxXMLResults />`), createProject: true}
options := checkmarxExecuteScanOptions{PullRequestName: "PR-17", ProjectName: "Test", AvoidDuplicateProjectScans: true, VulnerabilityThresholdUnit: "percentage", FullScanCycle: "3", Incremental: true, FullScansScheduled: true, Preset: "SAP_JS_Default", TeamName: "OpenSource/Cracks/15", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true} options := checkmarxExecuteScanOptions{PullRequestName: "PR-17", ProjectName: "Test", AvoidDuplicateProjectScans: true, VulnerabilityThresholdUnit: "percentage", FullScanCycle: "3", Incremental: true, FullScansScheduled: true, Preset: "SAP_JS_Default", TeamName: "OpenSource/Cracks/15", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true}
workspace, err := ioutil.TempDir("", "workspace4") workspace := t.TempDir()
if err != nil { err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
err = ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
options.FilterPattern = "**/abcd.go" options.FilterPattern = "**/abcd.go"
@@ -832,13 +752,8 @@ func TestRunScanHighViolationPercentage(t *testing.T) {
</Query> </Query>
</CxXMLResults>`)} </CxXMLResults>`)}
options := checkmarxExecuteScanOptions{VulnerabilityThresholdUnit: "percentage", VulnerabilityThresholdResult: "FAILURE", VulnerabilityThresholdHigh: 100, FullScanCycle: "10", FullScansScheduled: true, Preset: "10048", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true} options := checkmarxExecuteScanOptions{VulnerabilityThresholdUnit: "percentage", VulnerabilityThresholdResult: "FAILURE", VulnerabilityThresholdHigh: 100, FullScanCycle: "10", FullScansScheduled: true, Preset: "10048", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true}
workspace, err := ioutil.TempDir("", "workspace5") workspace := t.TempDir()
if err != nil { err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
err = ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
options.FilterPattern = "**/abcd.go" options.FilterPattern = "**/abcd.go"
@@ -875,13 +790,8 @@ func TestRunScanHighViolationAbsolute(t *testing.T) {
</Query> </Query>
</CxXMLResults>`)} </CxXMLResults>`)}
options := checkmarxExecuteScanOptions{VulnerabilityThresholdUnit: "absolute", VulnerabilityThresholdResult: "FAILURE", VulnerabilityThresholdLow: 1, FullScanCycle: "10", FullScansScheduled: true, Preset: "10048", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true} options := checkmarxExecuteScanOptions{VulnerabilityThresholdUnit: "absolute", VulnerabilityThresholdResult: "FAILURE", VulnerabilityThresholdLow: 1, FullScanCycle: "10", FullScansScheduled: true, Preset: "10048", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true}
workspace, err := ioutil.TempDir("", "workspace6") workspace := t.TempDir()
if err != nil { err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
err = ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err) assert.NoError(t, err)
options.FilterPattern = "**/abcd.go" options.FilterPattern = "**/abcd.go"

View File

@@ -118,16 +118,12 @@ func TestCloudFoundryCreateService(t *testing.T) {
t.Run("Create service: variable substitution in-line", func(t *testing.T) { t.Run("Create service: variable substitution in-line", func(t *testing.T) {
defer cfMockCleanup(m) defer cfMockCleanup(m)
dir, err := ioutil.TempDir("", "test variable substitution") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
manifestFileString := ` manifestFileString := `
@@ -146,7 +142,8 @@ func TestCloudFoundryCreateService(t *testing.T) {
plan: "testPlan"` plan: "testPlan"`
manifestFileStringBody := []byte(manifestFileString) manifestFileStringBody := []byte(manifestFileString)
err = ioutil.WriteFile("manifestTest.yml", manifestFileStringBody, 0644) err := ioutil.WriteFile("manifestTest.yml", manifestFileStringBody, 0644)
assert.NoError(t, err)
var manifestVariables = []string{"name1=Test1", "name2=Test2"} var manifestVariables = []string{"name1=Test1", "name2=Test2"}
@@ -171,16 +168,12 @@ func TestCloudFoundryCreateService(t *testing.T) {
t.Run("Create service: variable substitution with variable substitution manifest file", func(t *testing.T) { t.Run("Create service: variable substitution with variable substitution manifest file", func(t *testing.T) {
defer cfMockCleanup(m) defer cfMockCleanup(m)
dir, err := ioutil.TempDir("", "test variable substitution") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
varsFileString := `name: test1 varsFileString := `name: test1
name2: test2` name2: test2`
@@ -202,9 +195,12 @@ func TestCloudFoundryCreateService(t *testing.T) {
varsFileStringBody := []byte(varsFileString) varsFileStringBody := []byte(varsFileString)
manifestFileStringBody := []byte(manifestFileString) manifestFileStringBody := []byte(manifestFileString)
err = ioutil.WriteFile("varsTest.yml", varsFileStringBody, 0644) err := ioutil.WriteFile("varsTest.yml", varsFileStringBody, 0644)
assert.NoError(t, err)
err = ioutil.WriteFile("varsTest2.yml", varsFileStringBody, 0644) err = ioutil.WriteFile("varsTest2.yml", varsFileStringBody, 0644)
assert.NoError(t, err)
err = ioutil.WriteFile("manifestTest.yml", manifestFileStringBody, 0644) err = ioutil.WriteFile("manifestTest.yml", manifestFileStringBody, 0644)
assert.NoError(t, err)
var manifestVariablesFiles = []string{"varsTest.yml", "varsTest2.yml"} var manifestVariablesFiles = []string{"varsTest.yml", "varsTest2.yml"}
config := cloudFoundryCreateServiceOptions{ config := cloudFoundryCreateServiceOptions{

View File

@@ -2,7 +2,6 @@ package cmd
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -45,15 +44,11 @@ func TestRunContainerSaveImage(t *testing.T) {
t.Run("failure - download image", func(t *testing.T) { t.Run("failure - download image", func(t *testing.T) {
config := containerSaveImageOptions{} config := containerSaveImageOptions{}
tmpFolder, err := ioutil.TempDir("", "") tmpFolder := t.TempDir()
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
dClient := mock.DownloadMock{ReturnError: "download error"} dClient := mock.DownloadMock{ReturnError: "download error"}
files := mock.FilesMock{} files := mock.FilesMock{}
_, err = runContainerSaveImage(&config, &telemetryData, filepath.Join(tmpFolder, "cache"), tmpFolder, &dClient, &files) _, err := runContainerSaveImage(&config, &telemetryData, filepath.Join(tmpFolder, "cache"), tmpFolder, &dClient, &files)
assert.EqualError(t, err, "failed to download docker image: download error") assert.EqualError(t, err, "failed to download docker image: download error")
}) })
} }

View File

@@ -553,16 +553,12 @@ func TestAnalyseUnauditedIssues(t *testing.T) {
func TestTriggerFortifyScan(t *testing.T) { func TestTriggerFortifyScan(t *testing.T) {
t.Run("maven", func(t *testing.T) { t.Run("maven", func(t *testing.T) {
dir, err := ioutil.TempDir("", "test trigger fortify scan") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
utils := newFortifyTestUtilsBundle() utils := newFortifyTestUtilsBundle()
@@ -588,16 +584,12 @@ func TestTriggerFortifyScan(t *testing.T) {
}) })
t.Run("pip", func(t *testing.T) { t.Run("pip", func(t *testing.T) {
dir, err := ioutil.TempDir("", "test trigger fortify scan") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
utils := newFortifyTestUtilsBundle() utils := newFortifyTestUtilsBundle()
@@ -625,16 +617,12 @@ func TestTriggerFortifyScan(t *testing.T) {
}) })
t.Run("invalid buildTool", func(t *testing.T) { t.Run("invalid buildTool", func(t *testing.T) {
dir, err := ioutil.TempDir("", "test trigger fortify scan") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
utils := newFortifyTestUtilsBundle() utils := newFortifyTestUtilsBundle()
@@ -642,7 +630,7 @@ func TestTriggerFortifyScan(t *testing.T) {
BuildTool: "docker", BuildTool: "docker",
AutodetectClasspath: true, AutodetectClasspath: true,
} }
err = triggerFortifyScan(config, &utils, "test", "testLabel", "my.group-myartifact") err := triggerFortifyScan(config, &utils, "test", "testLabel", "my.group-myartifact")
assert.Error(t, err) assert.Error(t, err)
assert.Equal(t, "buildTool 'docker' is not supported by this step", err.Error()) assert.Equal(t, "buildTool 'docker' is not supported by this step", err.Error())
@@ -874,9 +862,7 @@ func TestScanProject(t *testing.T) {
func TestAutoresolveClasspath(t *testing.T) { func TestAutoresolveClasspath(t *testing.T) {
t.Run("success pip", func(t *testing.T) { t.Run("success pip", func(t *testing.T) {
utils := newFortifyTestUtilsBundle() utils := newFortifyTestUtilsBundle()
dir, err := ioutil.TempDir("", "classpath") dir := t.TempDir()
assert.NoError(t, err, "Unexpected error detected")
defer os.RemoveAll(dir)
file := filepath.Join(dir, "cp.txt") file := filepath.Join(dir, "cp.txt")
result, err := autoresolvePipClasspath("python2", []string{"-c", "import sys;p=sys.path;p.remove('');print(';'.join(p))"}, file, &utils) result, err := autoresolvePipClasspath("python2", []string{"-c", "import sys;p=sys.path;p.remove('');print(';'.join(p))"}, file, &utils)
@@ -895,21 +881,17 @@ func TestAutoresolveClasspath(t *testing.T) {
t.Run("error pip command", func(t *testing.T) { t.Run("error pip command", func(t *testing.T) {
utils := newFortifyTestUtilsBundle() utils := newFortifyTestUtilsBundle()
dir, err := ioutil.TempDir("", "classpath") dir := t.TempDir()
assert.NoError(t, err, "Unexpected error detected")
defer os.RemoveAll(dir)
file := filepath.Join(dir, "cp.txt") file := filepath.Join(dir, "cp.txt")
_, err = autoresolvePipClasspath("python2", []string{"-c", "invalid"}, file, &utils) _, err := autoresolvePipClasspath("python2", []string{"-c", "invalid"}, file, &utils)
assert.Error(t, err) assert.Error(t, err)
assert.Equal(t, "failed to run classpath autodetection command python2 with parameters [-c invalid]: Invalid command", err.Error()) assert.Equal(t, "failed to run classpath autodetection command python2 with parameters [-c invalid]: Invalid command", err.Error())
}) })
t.Run("success maven", func(t *testing.T) { t.Run("success maven", func(t *testing.T) {
utils := newFortifyTestUtilsBundle() utils := newFortifyTestUtilsBundle()
dir, err := ioutil.TempDir("", "classpath") dir := t.TempDir()
assert.NoError(t, err, "Unexpected error detected")
defer os.RemoveAll(dir)
file := filepath.Join(dir, "cp.txt") file := filepath.Join(dir, "cp.txt")
result, err := autoresolveMavenClasspath(fortifyExecuteScanOptions{BuildDescriptorFile: "pom.xml"}, file, &utils) result, err := autoresolveMavenClasspath(fortifyExecuteScanOptions{BuildDescriptorFile: "pom.xml"}, file, &utils)

View File

@@ -4,7 +4,6 @@ import (
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
@@ -13,7 +12,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
flag "github.com/spf13/pflag" flag "github.com/spf13/pflag"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func configOpenFileMock(name string, tokens map[string]string) (io.ReadCloser, error) { func configOpenFileMock(name string, tokens map[string]string) (io.ReadCloser, error) {
@@ -295,10 +293,7 @@ func TestPrepareOutputEnvironment(t *testing.T) {
}, },
} }
dir, tempDirErr := ioutil.TempDir("", "") dir := t.TempDir()
defer os.RemoveAll(dir)
require.NoError(t, tempDirErr)
require.DirExists(t, dir, "Failed to create temporary directory")
prepareOutputEnvironment(outputResources, dir) prepareOutputEnvironment(outputResources, dir)
assert.DirExists(t, filepath.Join(dir, "commonPipelineEnvironment", "path1")) assert.DirExists(t, filepath.Join(dir, "commonPipelineEnvironment", "path1"))

View File

@@ -613,11 +613,9 @@ func TestReportGolangTestCoverage(t *testing.T) {
func TestPrepareLdflags(t *testing.T) { func TestPrepareLdflags(t *testing.T) {
t.Parallel() t.Parallel()
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
defer os.RemoveAll(dir) // clean up
assert.NoError(t, err, "Error when creating temp dir")
err = os.Mkdir(filepath.Join(dir, "commonPipelineEnvironment"), 0777) err := os.Mkdir(filepath.Join(dir, "commonPipelineEnvironment"), 0777)
assert.NoError(t, err, "Error when creating folder structure") assert.NoError(t, err, "Error when creating folder structure")
err = ioutil.WriteFile(filepath.Join(dir, "commonPipelineEnvironment", "artifactVersion"), []byte("1.2.3"), 0666) err = ioutil.WriteFile(filepath.Join(dir, "commonPipelineEnvironment", "artifactVersion"), []byte("1.2.3"), 0666)

View File

@@ -1,8 +1,6 @@
package cmd package cmd
import ( import (
"io/ioutil"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -27,9 +25,7 @@ func TestRunIntegrationArtifactDownload(t *testing.T) {
t.Parallel() t.Parallel()
t.Run("Successfull Download of Integration flow Artifact", func(t *testing.T) { t.Run("Successfull Download of Integration flow Artifact", func(t *testing.T) {
tempDir, tmpErr := ioutil.TempDir("", "") tempDir := t.TempDir()
defer os.RemoveAll(tempDir) // clean up
assert.NoError(t, tmpErr, "Error when creating temp dir")
apiServiceKey := `{ apiServiceKey := `{
"oauth": { "oauth": {
"url": "https://demo", "url": "https://demo",

View File

@@ -2,7 +2,6 @@ package cmd
import ( import (
"io/ioutil" "io/ioutil"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -81,9 +80,7 @@ func TestRunIntegrationArtifactTriggerIntegrationTest(t *testing.T) {
}) })
t.Run("MessageBodyPath, ContentType, and file good (SUCCESS) callIFlowURL", func(t *testing.T) { t.Run("MessageBodyPath, ContentType, and file good (SUCCESS) callIFlowURL", func(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
defer os.RemoveAll(dir) // clean up
assert.NoError(t, err, "Error when creating temp dir")
//init //init
iFlowServiceKey := `{ iFlowServiceKey := `{
"oauth": { "oauth": {
@@ -106,7 +103,7 @@ func TestRunIntegrationArtifactTriggerIntegrationTest(t *testing.T) {
httpClient := httpMockCpis{CPIFunction: "TriggerIntegrationTest", ResponseBody: ``, TestType: "Positive"} httpClient := httpMockCpis{CPIFunction: "TriggerIntegrationTest", ResponseBody: ``, TestType: "Positive"}
//test //test
err = callIFlowURL(&config, nil, utils, &httpClient, "https://my-service.com/endpoint") err := callIFlowURL(&config, nil, utils, &httpClient, "https://my-service.com/endpoint")
//assert //assert
assert.NoError(t, err) assert.NoError(t, err)
@@ -147,9 +144,7 @@ func TestRunIntegrationArtifactTriggerIntegrationTest(t *testing.T) {
}) })
t.Run("nil fileBody (SUCCESS) callIFlowURL", func(t *testing.T) { t.Run("nil fileBody (SUCCESS) callIFlowURL", func(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
defer os.RemoveAll(dir) // clean up
assert.NoError(t, err, "Error when creating temp dir")
//init //init
iFlowServiceKey := `{ iFlowServiceKey := `{
"oauth": { "oauth": {
@@ -172,7 +167,7 @@ func TestRunIntegrationArtifactTriggerIntegrationTest(t *testing.T) {
httpClient := httpMockCpis{CPIFunction: "TriggerIntegrationTest", ResponseBody: ``, TestType: "Positive"} httpClient := httpMockCpis{CPIFunction: "TriggerIntegrationTest", ResponseBody: ``, TestType: "Positive"}
//test //test
err = callIFlowURL(&config, nil, utils, &httpClient, "") err := callIFlowURL(&config, nil, utils, &httpClient, "")
//assert //assert
assert.NoError(t, err) assert.NoError(t, err)

View File

@@ -205,13 +205,11 @@ func TestGetProjectConfigFile(t *testing.T) {
for run, test := range tt { for run, test := range tt {
t.Run(fmt.Sprintf("Run %v", run), func(t *testing.T) { t.Run(fmt.Sprintf("Run %v", run), func(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
defer os.RemoveAll(dir) // clean up
assert.NoError(t, err)
if len(test.filesAvailable) > 0 { if len(test.filesAvailable) > 0 {
configFolder := filepath.Join(dir, filepath.Dir(test.filesAvailable[0])) configFolder := filepath.Join(dir, filepath.Dir(test.filesAvailable[0]))
err = os.MkdirAll(configFolder, 0700) err := os.MkdirAll(configFolder, 0700)
assert.NoError(t, err) assert.NoError(t, err)
} }

View File

@@ -1,8 +1,6 @@
package cmd package cmd
import ( import (
"testing"
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
@@ -12,6 +10,7 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"testing"
"time" "time"
piperHttp "github.com/SAP/jenkins-library/pkg/http" piperHttp "github.com/SAP/jenkins-library/pkg/http"
@@ -338,9 +337,7 @@ func TestExecuteProtecodeScan(t *testing.T) {
func TestCorrectDockerConfigEnvVar(t *testing.T) { func TestCorrectDockerConfigEnvVar(t *testing.T) {
t.Run("with credentials", func(t *testing.T) { t.Run("with credentials", func(t *testing.T) {
// init // init
testDirectory, _ := ioutil.TempDir(".", "") testDirectory := t.TempDir()
require.DirExists(t, testDirectory)
defer os.RemoveAll(testDirectory)
dockerConfigDir := filepath.Join(testDirectory, "myConfig") dockerConfigDir := filepath.Join(testDirectory, "myConfig")
os.Mkdir(dockerConfigDir, 0755) os.Mkdir(dockerConfigDir, 0755)

View File

@@ -155,9 +155,7 @@ func TestRunSonar(t *testing.T) {
t.Run("default", func(t *testing.T) { t.Run("default", func(t *testing.T) {
// init // init
tmpFolder, err := ioutil.TempDir(".", "test-sonar-") tmpFolder := t.TempDir()
require.NoError(t, err)
defer os.RemoveAll(tmpFolder)
createTaskReportFile(t, tmpFolder) createTaskReportFile(t, tmpFolder)
sonar = sonarSettings{ sonar = sonarSettings{
@@ -177,7 +175,7 @@ func TestRunSonar(t *testing.T) {
} }
fileUtilsExists = mockFileUtilsExists(true) fileUtilsExists = mockFileUtilsExists(true)
// test // test
err = runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{}) err := runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
// assert // assert
assert.NoError(t, err) assert.NoError(t, err)
assert.Contains(t, sonar.options, "-Dsonar.projectVersion=1") assert.Contains(t, sonar.options, "-Dsonar.projectVersion=1")
@@ -190,9 +188,7 @@ func TestRunSonar(t *testing.T) {
}) })
t.Run("with custom options", func(t *testing.T) { t.Run("with custom options", func(t *testing.T) {
// init // init
tmpFolder, err := ioutil.TempDir(".", "test-sonar-") tmpFolder := t.TempDir()
require.NoError(t, err)
defer os.RemoveAll(tmpFolder)
createTaskReportFile(t, tmpFolder) createTaskReportFile(t, tmpFolder)
sonar = sonarSettings{ sonar = sonarSettings{
@@ -210,16 +206,14 @@ func TestRunSonar(t *testing.T) {
fileUtilsExists = FileUtils.FileExists fileUtilsExists = FileUtils.FileExists
}() }()
// test // test
err = runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{}) err := runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
// assert // assert
assert.NoError(t, err) assert.NoError(t, err)
assert.Contains(t, sonar.options, "-Dsonar.projectKey=piper") assert.Contains(t, sonar.options, "-Dsonar.projectKey=piper")
}) })
t.Run("with binaries option", func(t *testing.T) { t.Run("with binaries option", func(t *testing.T) {
// init // init
tmpFolder, err := ioutil.TempDir(".", "test-sonar-") tmpFolder := t.TempDir()
require.NoError(t, err)
defer func() { _ = os.RemoveAll(tmpFolder) }()
createTaskReportFile(t, tmpFolder) createTaskReportFile(t, tmpFolder)
sonar = sonarSettings{ sonar = sonarSettings{
@@ -250,7 +244,7 @@ func TestRunSonar(t *testing.T) {
PullRequestProvider: "GitHub", PullRequestProvider: "GitHub",
} }
// test // test
err = runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{}) err := runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
// assert // assert
assert.NoError(t, err) assert.NoError(t, err)
assert.Contains(t, sonar.options, fmt.Sprintf("-Dsonar.java.binaries=%s,%s,%s", assert.Contains(t, sonar.options, fmt.Sprintf("-Dsonar.java.binaries=%s,%s,%s",
@@ -260,9 +254,7 @@ func TestRunSonar(t *testing.T) {
}) })
t.Run("with binaries option already given", func(t *testing.T) { t.Run("with binaries option already given", func(t *testing.T) {
// init // init
tmpFolder, err := ioutil.TempDir(".", "test-sonar-") tmpFolder := t.TempDir()
require.NoError(t, err)
defer func() { _ = os.RemoveAll(tmpFolder) }()
createTaskReportFile(t, tmpFolder) createTaskReportFile(t, tmpFolder)
sonar = sonarSettings{ sonar = sonarSettings{
@@ -292,7 +284,7 @@ func TestRunSonar(t *testing.T) {
PullRequestProvider: "GitHub", PullRequestProvider: "GitHub",
} }
// test // test
err = runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{}) err := runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
// assert // assert
assert.NoError(t, err) assert.NoError(t, err)
assert.NotContains(t, sonar.options, fmt.Sprintf("-Dsonar.java.binaries=%s", assert.NotContains(t, sonar.options, fmt.Sprintf("-Dsonar.java.binaries=%s",
@@ -301,9 +293,7 @@ func TestRunSonar(t *testing.T) {
}) })
t.Run("projectKey, coverageExclusions, m2Path, verbose", func(t *testing.T) { t.Run("projectKey, coverageExclusions, m2Path, verbose", func(t *testing.T) {
// init // init
tmpFolder, err := ioutil.TempDir(".", "test-sonar-") tmpFolder := t.TempDir()
require.NoError(t, err)
defer os.RemoveAll(tmpFolder)
createTaskReportFile(t, tmpFolder) createTaskReportFile(t, tmpFolder)
sonar = sonarSettings{ sonar = sonarSettings{
@@ -326,7 +316,7 @@ func TestRunSonar(t *testing.T) {
fileUtilsExists = FileUtils.FileExists fileUtilsExists = FileUtils.FileExists
}() }()
// test // test
err = runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{}) err := runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
// assert // assert
assert.NoError(t, err) assert.NoError(t, err)
assert.Contains(t, sonar.options, "-Dsonar.projectKey=mock-project-key") assert.Contains(t, sonar.options, "-Dsonar.projectKey=mock-project-key")

View File

@@ -18,9 +18,7 @@ func TestCommandContract(t *testing.T) {
// Test provided by consumer: SAP InnerSource project // Test provided by consumer: SAP InnerSource project
// Changes to the test require peer review by core-team members involved in the project. // Changes to the test require peer review by core-team members involved in the project.
func TestGenerator(t *testing.T) { func TestGenerator(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
defer os.RemoveAll(dir) // clean up
assert.NoError(t, err, "Error when creating temp dir")
metadata := `metadata: metadata := `metadata:
name: test name: test

View File

@@ -27,8 +27,7 @@ func TestKarmaIntegration(t *testing.T) {
pwd = filepath.Dir(pwd) pwd = filepath.Dir(pwd)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac // using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("") tempDir, err := createTmpDir(t)
defer os.RemoveAll(tempDir) // clean up
assert.NoError(t, err, "Error when creating temp dir") assert.NoError(t, err, "Error when creating temp dir")
err = copyDir(filepath.Join(pwd, "integration", "testdata", t.Name()), tempDir) err = copyDir(filepath.Join(pwd, "integration", "testdata", t.Name()), tempDir)

View File

@@ -29,8 +29,7 @@ func runTest(t *testing.T, languageRunner string) {
pwd = filepath.Dir(pwd) pwd = filepath.Dir(pwd)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac // using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("") tempDir, err := createTmpDir(t)
defer os.RemoveAll(tempDir) // clean up
assert.NoError(t, err, "Error when creating temp dir") assert.NoError(t, err, "Error when creating temp dir")
err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestGaugeIntegration", "gauge-"+languageRunner), tempDir) err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestGaugeIntegration", "gauge-"+languageRunner), tempDir)
@@ -38,7 +37,7 @@ func runTest(t *testing.T, languageRunner string) {
t.Fatal("Failed to copy test project.") t.Fatal("Failed to copy test project.")
} }
//workaround to use test script util it is possible to set workdir for Exec call //workaround to use test script until it is possible to set workdir for Exec call
testScript := fmt.Sprintf(`#!/bin/sh testScript := fmt.Sprintf(`#!/bin/sh
cd /test cd /test
/piperbin/piper gaugeExecuteTests --installCommand="%v" --languageRunner=%v --runCommand="run" >test-log.txt 2>&1 /piperbin/piper gaugeExecuteTests --installCommand="%v" --languageRunner=%v --runCommand="run" >test-log.txt 2>&1
@@ -63,6 +62,15 @@ cd /test
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, 0, code) assert.Equal(t, 0, code)
t.Cleanup(func() {
// Remove files that are created by the container. t.TempDir() will
// fail to remove them since it does not have the root permission
_, err := nodeContainer.Exec(ctx, []string{"sh", "-c", "find /test -name . -o -prune -exec rm -rf -- {} +"})
assert.NoError(t, err)
assert.NoError(t, nodeContainer.Terminate(ctx))
})
content, err := ioutil.ReadFile(filepath.Join(tempDir, "/test-log.txt")) content, err := ioutil.ReadFile(filepath.Join(tempDir, "/test-log.txt"))
if err != nil { if err != nil {
t.Fatal("Could not read test-log.txt.", err) t.Fatal("Could not read test-log.txt.", err)

View File

@@ -33,12 +33,10 @@ func TestPiperGithubPublishRelease(t *testing.T) {
if len(repository) == 0 { if len(repository) == 0 {
repository = "piper-integration" repository = "piper-integration"
} }
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
defer os.RemoveAll(dir) // clean up
assert.NoError(t, err, "Error when creating temp dir")
testAsset := filepath.Join(dir, "test.txt") testAsset := filepath.Join(dir, "test.txt")
err = ioutil.WriteFile(testAsset, []byte("Test"), 0644) err := ioutil.WriteFile(testAsset, []byte("Test"), 0644)
assert.NoError(t, err, "Error when writing temporary file") assert.NoError(t, err, "Error when writing temporary file")
test2Asset := filepath.Join(dir, "test2.txt") test2Asset := filepath.Join(dir, "test2.txt")
err = ioutil.WriteFile(test2Asset, []byte("Test"), 0644) err = ioutil.WriteFile(test2Asset, []byte("Test"), 0644)

View File

@@ -26,8 +26,7 @@ func TestGradleExecuteBuild_JavaProject_BOMCreation_UsingWrapper(t *testing.T) {
pwd = filepath.Dir(pwd) pwd = filepath.Dir(pwd)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac // using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("") tempDir, err := createTmpDir(t)
defer os.RemoveAll(tempDir) // clean up
assert.NoError(t, err, "Error when creating temp dir") assert.NoError(t, err, "Error when creating temp dir")
err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestGradleIntegration", "java-project"), tempDir) err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestGradleIntegration", "java-project"), tempDir)
@@ -99,8 +98,7 @@ func TestGradleExecuteBuild_JavaProjectWithBomPlugin(t *testing.T) {
pwd = filepath.Dir(pwd) pwd = filepath.Dir(pwd)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac // using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("") tempDir, err := createTmpDir(t)
defer os.RemoveAll(tempDir) // clean up
assert.NoError(t, err, "Error when creating temp dir") assert.NoError(t, err, "Error when creating temp dir")
err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestGradleIntegration", "java-project-with-bom-plugin"), tempDir) err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestGradleIntegration", "java-project-with-bom-plugin"), tempDir)

View File

@@ -25,8 +25,7 @@ func TestRunScriptsWithOptions(t *testing.T) {
pwd = filepath.Dir(pwd) pwd = filepath.Dir(pwd)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac // using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("") tempDir, err := createTmpDir(t)
defer os.RemoveAll(tempDir) // clean up
assert.NoError(t, err, "Error when creating temp dir") assert.NoError(t, err, "Error when creating temp dir")
err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "runScriptsWithOptions"), tempDir) err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "runScriptsWithOptions"), tempDir)
@@ -77,8 +76,7 @@ func TestRegistrySetInFlags(t *testing.T) {
pwd = filepath.Dir(pwd) pwd = filepath.Dir(pwd)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac // using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("") tempDir, err := createTmpDir(t)
defer os.RemoveAll(tempDir) // clean up
assert.NoError(t, err, "Error when creating temp dir") assert.NoError(t, err, "Error when creating temp dir")
err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "registrySetInFlags"), tempDir) err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "registrySetInFlags"), tempDir)
@@ -128,8 +126,7 @@ func TestRegistrySetInNpmrc(t *testing.T) {
pwd = filepath.Dir(pwd) pwd = filepath.Dir(pwd)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac // using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("") tempDir, err := createTmpDir(t)
defer os.RemoveAll(tempDir) // clean up
assert.NoError(t, err, "Error when creating temp dir") assert.NoError(t, err, "Error when creating temp dir")
err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "registrySetInNpmrc"), tempDir) err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "registrySetInNpmrc"), tempDir)
@@ -179,8 +176,7 @@ func TestRegistryWithTwoModules(t *testing.T) {
pwd = filepath.Dir(pwd) pwd = filepath.Dir(pwd)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac // using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("") tempDir, err := createTmpDir(t)
defer os.RemoveAll(tempDir) // clean up
assert.NoError(t, err, "Error when creating temp dir") assert.NoError(t, err, "Error when creating temp dir")
err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "registryWithTwoModules"), tempDir) err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "registryWithTwoModules"), tempDir)

View File

@@ -24,8 +24,7 @@ func TestBuildPythonProject(t *testing.T) {
assert.NoError(t, err, "Getting current working directory failed.") assert.NoError(t, err, "Getting current working directory failed.")
pwd = filepath.Dir(pwd) pwd = filepath.Dir(pwd)
tempDir, err := createTmpDir("") tempDir, err := createTmpDir(t)
defer os.RemoveAll(tempDir) // clean up
assert.NoError(t, err, "Error when creating temp dir") assert.NoError(t, err, "Error when creating temp dir")
err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestPythonIntegration", "python-project"), tempDir) err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestPythonIntegration", "python-project"), tempDir)

View File

@@ -112,16 +112,15 @@ func copyFile(source, target string) error {
return os.Chmod(target, sourceInfo.Mode()) return os.Chmod(target, sourceInfo.Mode())
} }
func createTmpDir(prefix string) (string, error) { // createTmpDir calls t.TempDir() and returns the path name after the evaluation
dirName := os.TempDir() // of any symbolic links.
tmpDir, err := filepath.EvalSymlinks(dirName) //
// On Docker for Mac, t.TempDir() returns e.g.
// /var/folders/bl/wbxjgtzx7j5_mjsmfr3ynlc00000gp/T/<the-test-name>/001
func createTmpDir(t *testing.T) (string, error) {
tmpDir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil { if err != nil {
return "", err return "", err
} }
tmpDir = filepath.Clean(tmpDir) return tmpDir, nil
path, err := ioutil.TempDir(tmpDir, prefix)
if err != nil {
return "", err
}
return path, nil
} }

View File

@@ -66,16 +66,12 @@ repositories:
func TestReadAddonDescriptor(t *testing.T) { func TestReadAddonDescriptor(t *testing.T) {
t.Run("Test: success case", func(t *testing.T) { t.Run("Test: success case", func(t *testing.T) {
dir, err := ioutil.TempDir("", "test read addon descriptor") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
file, _ := os.Create("filename.yaml") file, _ := os.Create("filename.yaml")
@@ -125,16 +121,12 @@ func TestReadAddonDescriptor(t *testing.T) {
expectedErrorMessage := "AddonDescriptor doesn't contain any repositories" expectedErrorMessage := "AddonDescriptor doesn't contain any repositories"
expectedRepositoryList := AddonDescriptor{Repositories: []Repository{{}, {}}} expectedRepositoryList := AddonDescriptor{Repositories: []Repository{{}, {}}}
dir, err := ioutil.TempDir("", "test abap utils") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir // clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
manifestFileString := ` manifestFileString := `
@@ -142,7 +134,7 @@ func TestReadAddonDescriptor(t *testing.T) {
- repo: 'testRepo' - repo: 'testRepo'
- repo: 'testRepo2'` - repo: 'testRepo2'`
err = ioutil.WriteFile("repositories.yml", []byte(manifestFileString), 0644) err := ioutil.WriteFile("repositories.yml", []byte(manifestFileString), 0644)
assert.NoError(t, err) assert.NoError(t, err)
addonDescriptor, err := ReadAddonDescriptor("repositories.yml") addonDescriptor, err := ReadAddonDescriptor("repositories.yml")

View File

@@ -129,17 +129,12 @@ func TestGetRepositories(t *testing.T) {
Name: "testRepository", Name: "testRepository",
}} }}
dir, err := ioutil.TempDir("", "test abap utils") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
manifestFileString := ` manifestFileString := `
@@ -151,7 +146,7 @@ repositories:
- name: 'testRepo3' - name: 'testRepo3'
branch: 'testBranch3'` branch: 'testBranch3'`
err = ioutil.WriteFile("repositoriesTest.yml", []byte(manifestFileString), 0644) err := ioutil.WriteFile("repositoriesTest.yml", []byte(manifestFileString), 0644)
config := RepositoriesConfig{ config := RepositoriesConfig{
BranchName: "testBranch", BranchName: "testBranch",
@@ -169,17 +164,12 @@ repositories:
expectedRepositoryList := []Repository([]Repository{}) expectedRepositoryList := []Repository([]Repository{})
expectedErrorMessage := "Error in config file repositoriesTest.yml, AddonDescriptor doesn't contain any repositories" expectedErrorMessage := "Error in config file repositoriesTest.yml, AddonDescriptor doesn't contain any repositories"
dir, err := ioutil.TempDir("", "test abap utils") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
manifestFileString := ` manifestFileString := `
@@ -187,7 +177,7 @@ repositories:
- repo: 'testRepo' - repo: 'testRepo'
- repo: 'testRepo2'` - repo: 'testRepo2'`
err = ioutil.WriteFile("repositoriesTest.yml", []byte(manifestFileString), 0644) err := ioutil.WriteFile("repositoriesTest.yml", []byte(manifestFileString), 0644)
config := RepositoriesConfig{ config := RepositoriesConfig{
Repositories: "repositoriesTest.yml", Repositories: "repositoriesTest.yml",
@@ -202,17 +192,12 @@ repositories:
expectedRepositoryList := []Repository([]Repository{}) expectedRepositoryList := []Repository([]Repository{})
expectedErrorMessage := "Error in config file repositoriesTest.yml, AddonDescriptor doesn't contain any repositories" expectedErrorMessage := "Error in config file repositoriesTest.yml, AddonDescriptor doesn't contain any repositories"
dir, err := ioutil.TempDir("", "test abap utils") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd() oldCWD, _ := os.Getwd()
_ = os.Chdir(dir) _ = os.Chdir(dir)
// clean up tmp dir
defer func() { defer func() {
_ = os.Chdir(oldCWD) _ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}() }()
manifestFileString := ` manifestFileString := `
@@ -220,7 +205,7 @@ repositories:
- repo: 'testRepo' - repo: 'testRepo'
- repo: 'testRepo2'` - repo: 'testRepo2'`
err = ioutil.WriteFile("repositoriesTest.yml", []byte(manifestFileString), 0644) err := ioutil.WriteFile("repositoriesTest.yml", []byte(manifestFileString), 0644)
config := RepositoriesConfig{ config := RepositoriesConfig{
Repositories: "repositoriesTest.yml", Repositories: "repositoriesTest.yml",

View File

@@ -1,7 +1,6 @@
package metadata package metadata
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -37,11 +36,9 @@ func TestWriteProjectMetadata(t *testing.T) {
"branch": "main", "branch": "main",
} }
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
err := os.MkdirAll(filepath.Join(dir, "commonPipelineEnvironment", "git"), os.ModePerm)
assert.NoError(t, err) assert.NoError(t, err)
err = os.MkdirAll(filepath.Join(dir, "commonPipelineEnvironment", "git"), os.ModePerm)
assert.NoError(t, err)
defer os.RemoveAll(dir)
for file, content := range cpeFiles { for file, content := range cpeFiles {
err = fileutils.FileWrite(filepath.Join(dir, "commonPipelineEnvironment", "git", file), []byte(content), os.ModePerm) err = fileutils.FileWrite(filepath.Join(dir, "commonPipelineEnvironment", "git", file), []byte(content), os.ModePerm)

View File

@@ -56,11 +56,9 @@ func TestGetImageName(t *testing.T) {
t.Run("Image name is taken from git repo", func(t *testing.T) { t.Run("Image name is taken from git repo", func(t *testing.T) {
t.Parallel() t.Parallel()
tmpdir, err := ioutil.TempDir("", "cpe") tmpdir := t.TempDir()
assert.NoError(t, err)
defer os.RemoveAll(tmpdir)
err = os.MkdirAll(filepath.Join(tmpdir, "commonPipelineEnvironment", "git"), os.ModePerm) err := os.MkdirAll(filepath.Join(tmpdir, "commonPipelineEnvironment", "git"), os.ModePerm)
assert.NoError(t, err) assert.NoError(t, err)
err = ioutil.WriteFile(filepath.Join(tmpdir, "commonPipelineEnvironment", "git", "repository"), []byte("repo-name"), os.ModePerm) err = ioutil.WriteFile(filepath.Join(tmpdir, "commonPipelineEnvironment", "git", "repository"), []byte("repo-name"), os.ModePerm)
@@ -75,11 +73,9 @@ func TestGetImageName(t *testing.T) {
t.Run("Image name is taken from github repo", func(t *testing.T) { t.Run("Image name is taken from github repo", func(t *testing.T) {
t.Parallel() t.Parallel()
tmpdir, err := ioutil.TempDir("", "cpe") tmpdir := t.TempDir()
assert.NoError(t, err)
defer os.RemoveAll(tmpdir)
err = os.MkdirAll(filepath.Join(tmpdir, "commonPipelineEnvironment", "github"), os.ModePerm) err := os.MkdirAll(filepath.Join(tmpdir, "commonPipelineEnvironment", "github"), os.ModePerm)
assert.NoError(t, err) assert.NoError(t, err)
err = ioutil.WriteFile(filepath.Join(tmpdir, "commonPipelineEnvironment", "github", "repository"), []byte("repo-name"), os.ModePerm) err = ioutil.WriteFile(filepath.Join(tmpdir, "commonPipelineEnvironment", "github", "repository"), []byte("repo-name"), os.ModePerm)

View File

@@ -179,13 +179,7 @@ steps:
}, },
} }
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
piperenv.SetParameter(filepath.Join(dir, "commonPipelineEnvironment"), "test_pe1", "pe1_val") piperenv.SetParameter(filepath.Join(dir, "commonPipelineEnvironment"), "test_pe1", "pe1_val")
@@ -249,13 +243,7 @@ steps:
{Name: "p0", ResourceRef: []ResourceReference{{Name: "commonPipelineEnvironment", Param: "p0"}}}, {Name: "p0", ResourceRef: []ResourceReference{{Name: "commonPipelineEnvironment", Param: "p0"}}},
}}}} }}}}
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
stepConfig, err := c.GetStepConfig(map[string]interface{}{}, "", myConfig, defaults, false, filters, stepMeta, stepMeta.GetResourceParameters(dir, "commonPipelineEnvironment"), "stage1", "step1") stepConfig, err := c.GetStepConfig(map[string]interface{}{}, "", myConfig, defaults, false, filters, stepMeta, stepMeta.GetResourceParameters(dir, "commonPipelineEnvironment"), "stage1", "step1")
@@ -382,15 +370,9 @@ steps:
steps: steps:
step1: step1:
gcsBucketId: gcsBucketId_value`))} gcsBucketId: gcsBucketId_value`))}
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
cpeDir := filepath.Join(dir, "commonPipelineEnvironment/custom") cpeDir := filepath.Join(dir, "commonPipelineEnvironment/custom")
err = os.MkdirAll(cpeDir, 0700) err := os.MkdirAll(cpeDir, 0700)
if err != nil { if err != nil {
t.Fatal("Failed to create sub directory") t.Fatal("Failed to create sub directory")
} }
@@ -456,14 +438,6 @@ stages:
myConfig := ioutil.NopCloser(strings.NewReader(testConfig)) myConfig := ioutil.NopCloser(strings.NewReader(testConfig))
dir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
stepConfig, err := c.GetStageConfig(paramJSON, myConfig, defaults, false, acceptedParams, "stage1") stepConfig, err := c.GetStageConfig(paramJSON, myConfig, defaults, false, acceptedParams, "stage1")
assert.Equal(t, nil, err, "error occurred but none expected") assert.Equal(t, nil, err, "error occurred but none expected")
@@ -506,14 +480,6 @@ stages:
myConfig := ioutil.NopCloser(strings.NewReader(testConfig)) myConfig := ioutil.NopCloser(strings.NewReader(testConfig))
dir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
stepConfig, err := c.GetStageConfig(paramJSON, myConfig, defaults, false, acceptedParams, "stage1") stepConfig, err := c.GetStageConfig(paramJSON, myConfig, defaults, false, acceptedParams, "stage1")
assert.Equal(t, nil, err, "error occurred but none expected") assert.Equal(t, nil, err, "error occurred but none expected")

View File

@@ -379,15 +379,10 @@ func TestEvaluateV1(t *testing.T) {
filesMock.AddFile("my.postman_collection.json", []byte("{}")) filesMock.AddFile("my.postman_collection.json", []byte("{}"))
filesMock.AddFile("package.json", []byte(packageJson)) filesMock.AddFile("package.json", []byte(packageJson))
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
cpeDir := filepath.Join(dir, "commonPipelineEnvironment") cpeDir := filepath.Join(dir, "commonPipelineEnvironment")
err = os.MkdirAll(cpeDir, 0700) err := os.MkdirAll(cpeDir, 0700)
if err != nil { if err != nil {
t.Fatal("Failed to create sub directory") t.Fatal("Failed to create sub directory")
} }

View File

@@ -91,15 +91,10 @@ func TestReportingParams_GetResourceParameters(t *testing.T) {
}, },
} }
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
cpeDir := filepath.Join(dir, "commonPipelineEnvironment") cpeDir := filepath.Join(dir, "commonPipelineEnvironment")
err = os.MkdirAll(cpeDir, 0700) err := os.MkdirAll(cpeDir, 0700)
if err != nil { if err != nil {
t.Fatal("Failed to create sub directory") t.Fatal("Failed to create sub directory")
} }

View File

@@ -666,15 +666,10 @@ func TestGetResourceParameters(t *testing.T) {
}, },
} }
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
cpeDir := filepath.Join(dir, "commonPipelineEnvironment") cpeDir := filepath.Join(dir, "commonPipelineEnvironment")
err = os.MkdirAll(cpeDir, 0700) err := os.MkdirAll(cpeDir, 0700)
if err != nil { if err != nil {
t.Fatal("Failed to create sub directory") t.Fatal("Failed to create sub directory")
} }

View File

@@ -4,7 +4,6 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -24,16 +23,11 @@ func TestDownloadRequest(t *testing.T) {
logger: log.Entry().WithField("package", "SAP/jenkins-library/pkg/http"), logger: log.Entry().WithField("package", "SAP/jenkins-library/pkg/http"),
} }
workingDir, err := ioutil.TempDir("", "test detailed results") workingDir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(workingDir)
targetFile := filepath.Join(workingDir, "abc/123/abc.xml") targetFile := filepath.Join(workingDir, "abc/123/abc.xml")
// function under test // function under test
err = client.DownloadFile(server.URL, targetFile, nil, nil) err := client.DownloadFile(server.URL, targetFile, nil, nil)
// asserts // asserts
assert.NoError(t, err, "Error occurred but none expected") assert.NoError(t, err, "Error occurred but none expected")
assert.FileExists(t, targetFile, "File not found") assert.FileExists(t, targetFile, "File not found")

View File

@@ -2,7 +2,6 @@ package log
import ( import (
"io/ioutil" "io/ioutil"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -16,12 +15,7 @@ func TestFatalHookLevels(t *testing.T) {
} }
func TestFatalHookFire(t *testing.T) { func TestFatalHookFire(t *testing.T) {
workspace, err := ioutil.TempDir("", "") workspace := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
t.Run("with step name", func(t *testing.T) { t.Run("with step name", func(t *testing.T) {
hook := FatalHook{ hook := FatalHook{

View File

@@ -21,12 +21,8 @@ func Test_writeMapToDisk(t *testing.T) {
"number": 5, "number": 5,
} }
tmpDir, err := ioutil.TempDir(os.TempDir(), "test-data-*") tmpDir := t.TempDir()
require.NoError(t, err) err := testMap.WriteToDisk(tmpDir)
t.Cleanup(func() {
os.RemoveAll(tmpDir)
})
err = testMap.WriteToDisk(tmpDir)
require.NoError(t, err) require.NoError(t, err)
testData := []struct { testData := []struct {
@@ -59,13 +55,9 @@ func Test_writeMapToDisk(t *testing.T) {
func TestCPEMap_LoadFromDisk(t *testing.T) { func TestCPEMap_LoadFromDisk(t *testing.T) {
t.Parallel() t.Parallel()
tmpDir, err := ioutil.TempDir(os.TempDir(), "test-data-*") tmpDir := t.TempDir()
require.NoError(t, err)
t.Cleanup(func() {
os.RemoveAll(tmpDir)
})
err = ioutil.WriteFile(path.Join(tmpDir, "Foo"), []byte("Bar"), 0644) err := ioutil.WriteFile(path.Join(tmpDir, "Foo"), []byte("Bar"), 0644)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(path.Join(tmpDir, "Hello"), []byte("World"), 0644) err = ioutil.WriteFile(path.Join(tmpDir, "Hello"), []byte("World"), 0644)
require.NoError(t, err) require.NoError(t, err)
@@ -92,14 +84,10 @@ func TestCPEMap_LoadFromDisk(t *testing.T) {
func TestNumbersArePassedCorrectly(t *testing.T) { func TestNumbersArePassedCorrectly(t *testing.T) {
t.Parallel() t.Parallel()
tmpDir, err := ioutil.TempDir(os.TempDir(), "test-data-*") tmpDir := t.TempDir()
require.NoError(t, err)
t.Cleanup(func() {
os.RemoveAll(tmpDir)
})
const jsonNumber = "5.5000" const jsonNumber = "5.5000"
err = ioutil.WriteFile(path.Join(tmpDir, "test.json"), []byte(jsonNumber), 0644) err := ioutil.WriteFile(path.Join(tmpDir, "test.json"), []byte(jsonNumber), 0644)
require.NoError(t, err) require.NoError(t, err)
cpeMap := CPEMap{} cpeMap := CPEMap{}

View File

@@ -2,7 +2,6 @@ package piperenv
import ( import (
"io/ioutil" "io/ioutil"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -33,11 +32,7 @@ func TestSetResourceParameter(t *testing.T) {
for _, testCase := range tests { for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) { t.Run(testCase.name, func(t *testing.T) {
// init // init
dir, tempDirErr := ioutil.TempDir("", "") dir := t.TempDir()
require.NoError(t, tempDirErr)
require.DirExists(t, dir, "Failed to create temporary directory")
// clean up tmp dir
defer os.RemoveAll(dir)
targetFile := filepath.Join(dir, testCase.args.resourceName, testCase.args.paramName) targetFile := filepath.Join(dir, testCase.args.resourceName, testCase.args.paramName)
// test // test
err := SetResourceParameter(dir, testCase.args.resourceName, testCase.args.paramName, testCase.args.value) err := SetResourceParameter(dir, testCase.args.resourceName, testCase.args.paramName, testCase.args.value)
@@ -73,11 +68,6 @@ func TestGetResourceParameter(t *testing.T) {
} }
for _, testCase := range tests { for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) { t.Run(testCase.name, func(t *testing.T) {
// init
dir, tempDirErr := ioutil.TempDir("", "")
defer os.RemoveAll(dir) // clean up
require.NoError(t, tempDirErr)
require.DirExists(t, dir, "Failed to create temporary directory")
// test // test
result := GetResourceParameter(testCase.args.path, testCase.args.resourceName, testCase.args.paramName) result := GetResourceParameter(testCase.args.path, testCase.args.resourceName, testCase.args.paramName)
// assert // assert
@@ -87,28 +77,16 @@ func TestGetResourceParameter(t *testing.T) {
} }
func TestSetParameter(t *testing.T) { func TestSetParameter(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir err := SetParameter(dir, "testParam", "testVal")
defer os.RemoveAll(dir)
err = SetParameter(dir, "testParam", "testVal")
assert.NoError(t, err, "Error occurred but none expected") assert.NoError(t, err, "Error occurred but none expected")
assert.Equal(t, "testVal", GetParameter(dir, "testParam")) assert.Equal(t, "testVal", GetParameter(dir, "testParam"))
} }
func TestReadFromDisk(t *testing.T) { func TestReadFromDisk(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
assert.Equal(t, "", GetParameter(dir, "testParamNotExistingYet")) assert.Equal(t, "", GetParameter(dir, "testParamNotExistingYet"))
} }

View File

@@ -1,15 +1,16 @@
package piperutils package piperutils
import ( import (
"github.com/stretchr/testify/assert"
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestFileExists(t *testing.T) { func TestFileExists(t *testing.T) {
runInTempDir(t, "testing dir returns false", "dir", func(t *testing.T) { runInTempDir(t, "testing dir returns false", func(t *testing.T) {
err := os.Mkdir("test", 0777) err := os.Mkdir("test", 0777)
if err != nil { if err != nil {
t.Fatal("failed to create test dir in temporary dir") t.Fatal("failed to create test dir in temporary dir")
@@ -18,7 +19,7 @@ func TestFileExists(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
assert.False(t, result) assert.False(t, result)
}) })
runInTempDir(t, "testing file returns true", "dir", func(t *testing.T) { runInTempDir(t, "testing file returns true", func(t *testing.T) {
file, err := ioutil.TempFile("", "testFile") file, err := ioutil.TempFile("", "testFile")
assert.NoError(t, err) assert.NoError(t, err)
result, err := FileExists(file.Name()) result, err := FileExists(file.Name())
@@ -28,7 +29,7 @@ func TestFileExists(t *testing.T) {
} }
func TestDirExists(t *testing.T) { func TestDirExists(t *testing.T) {
runInTempDir(t, "testing dir exists", "dir-exists", func(t *testing.T) { runInTempDir(t, "testing dir exists", func(t *testing.T) {
err := os.Mkdir("test", 0777) err := os.Mkdir("test", 0777)
if err != nil { if err != nil {
t.Fatal("failed to create test dir in temporary dir") t.Fatal("failed to create test dir in temporary dir")
@@ -50,7 +51,7 @@ func TestDirExists(t *testing.T) {
} }
func TestCopy(t *testing.T) { func TestCopy(t *testing.T) {
runInTempDir(t, "copying file succeeds", "dir2", func(t *testing.T) { runInTempDir(t, "copying file succeeds", func(t *testing.T) {
file := "testFile" file := "testFile"
err := ioutil.WriteFile(file, []byte{byte(1), byte(2), byte(3)}, 0700) err := ioutil.WriteFile(file, []byte{byte(1), byte(2), byte(3)}, 0700)
if err != nil { if err != nil {
@@ -61,7 +62,7 @@ func TestCopy(t *testing.T) {
assert.NoError(t, err, "Didn't expert error but got one") assert.NoError(t, err, "Didn't expert error but got one")
assert.Equal(t, int64(3), result, "Expected true but got false") assert.Equal(t, int64(3), result, "Expected true but got false")
}) })
runInTempDir(t, "copying directory fails", "dir3", func(t *testing.T) { runInTempDir(t, "copying directory fails", func(t *testing.T) {
src := filepath.Join("some", "file") src := filepath.Join("some", "file")
dst := filepath.Join("another", "file") dst := filepath.Join("another", "file")
@@ -81,20 +82,17 @@ func TestCopy(t *testing.T) {
}) })
} }
func runInTempDir(t *testing.T, nameOfRun, tempDirPattern string, run func(t *testing.T)) { func runInTempDir(t *testing.T, nameOfRun string, run func(t *testing.T)) {
dir, err := ioutil.TempDir("", tempDirPattern) t.Run(nameOfRun, func(t *testing.T) {
if err != nil { dir := t.TempDir()
t.Fatal("Failed to create temporary directory") oldCWD, _ := os.Getwd()
} _ = os.Chdir(dir)
oldCWD, _ := os.Getwd() t.Cleanup(func() {
_ = os.Chdir(dir) _ = os.Chdir(oldCWD)
// clean up tmp dir })
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
t.Run(nameOfRun, run) run(t)
})
} }
func TestExcludeFiles(t *testing.T) { func TestExcludeFiles(t *testing.T) {

View File

@@ -8,7 +8,7 @@ import (
) )
func TestCopyData(t *testing.T) { func TestCopyData(t *testing.T) {
runInTempDir(t, "copying file succeeds small", "dir1", func(t *testing.T) { runInTempDir(t, "copying file succeeds small", func(t *testing.T) {
srcName := "testFileSrc" srcName := "testFileSrc"
src, err := os.OpenFile(srcName, os.O_CREATE|os.O_RDWR, 0700) src, err := os.OpenFile(srcName, os.O_CREATE|os.O_RDWR, 0700)
if err != nil { if err != nil {
@@ -46,7 +46,7 @@ func TestCopyData(t *testing.T) {
assert.Equal(t, int64(3), result, "Expected true but got false") assert.Equal(t, int64(3), result, "Expected true but got false")
assert.Equal(t, data, dataRead, "data written %v is different to data read %v") assert.Equal(t, data, dataRead, "data written %v is different to data read %v")
}) })
runInTempDir(t, "copying file succeeds larger", "dir2", func(t *testing.T) { runInTempDir(t, "copying file succeeds larger", func(t *testing.T) {
srcName := "testFile" srcName := "testFile"
src, err := os.OpenFile(srcName, os.O_CREATE|os.O_RDWR, 0700) src, err := os.OpenFile(srcName, os.O_CREATE|os.O_RDWR, 0700)
if err != nil { if err != nil {
@@ -73,7 +73,7 @@ func TestCopyData(t *testing.T) {
assert.NoError(t, err, "Didn't expect error but got one") assert.NoError(t, err, "Didn't expect error but got one")
assert.Equal(t, int64(300), result, "Expected true but got false") assert.Equal(t, int64(300), result, "Expected true but got false")
}) })
runInTempDir(t, "copying file fails on read", "dir3", func(t *testing.T) { runInTempDir(t, "copying file fails on read", func(t *testing.T) {
srcName := "testFileExcl" srcName := "testFileExcl"
src, err := os.OpenFile(srcName, os.O_CREATE|os.O_RDWR, 0700) src, err := os.OpenFile(srcName, os.O_CREATE|os.O_RDWR, 0700)
if err != nil { if err != nil {
@@ -100,7 +100,7 @@ func TestCopyData(t *testing.T) {
assert.Error(t, err, "Expected error but got none") assert.Error(t, err, "Expected error but got none")
assert.Equal(t, int64(0), result, "Expected true but got false") assert.Equal(t, int64(0), result, "Expected true but got false")
}) })
runInTempDir(t, "copying file fails on write", "dir4", func(t *testing.T) { runInTempDir(t, "copying file fails on write", func(t *testing.T) {
srcName := "testFileExcl" srcName := "testFileExcl"
src, err := os.OpenFile(srcName, os.O_CREATE|os.O_RDWR, 0700) src, err := os.OpenFile(srcName, os.O_CREATE|os.O_RDWR, 0700)
if err != nil { if err != nil {

View File

@@ -3,7 +3,6 @@ package piperutils
import ( import (
"encoding/json" "encoding/json"
"io/ioutil" "io/ioutil"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -13,10 +12,7 @@ import (
func TestPersistReportAndLinks(t *testing.T) { func TestPersistReportAndLinks(t *testing.T) {
t.Run("default", func(t *testing.T) { t.Run("default", func(t *testing.T) {
workspace, err := ioutil.TempDir("", "workspace5") workspace := t.TempDir()
require.NoError(t, err, "Failed to create temporary workspace directory")
// clean up tmp dir
defer os.RemoveAll(workspace)
reports := []Path{{Target: "testFile1.json", Mandatory: true}, {Target: "testFile2.json"}} reports := []Path{{Target: "testFile1.json", Mandatory: true}, {Target: "testFile2.json"}}
links := []Path{{Target: "https://1234568.com/test", Name: "Weblink"}} links := []Path{{Target: "https://1234568.com/test", Name: "Weblink"}}
@@ -55,10 +51,7 @@ func TestPersistReportAndLinks(t *testing.T) {
t.Run("empty list", func(t *testing.T) { t.Run("empty list", func(t *testing.T) {
// init // init
workspace, err := ioutil.TempDir("", "sonar-") workspace := t.TempDir()
require.NoError(t, err, "Failed to create temporary workspace directory")
// clean up tmp dir
defer os.RemoveAll(workspace)
reportsJSONPath := filepath.Join(workspace, "sonarExecuteScan_reports.json") reportsJSONPath := filepath.Join(workspace, "sonarExecuteScan_reports.json")
linksJSONPath := filepath.Join(workspace, "sonarExecuteScan_links.json") linksJSONPath := filepath.Join(workspace, "sonarExecuteScan_links.json")

View File

@@ -1,8 +1,6 @@
package toolrecord_test package toolrecord_test
import ( import (
"io/ioutil"
"os"
"testing" "testing"
"github.com/SAP/jenkins-library/pkg/toolrecord" "github.com/SAP/jenkins-library/pkg/toolrecord"
@@ -10,11 +8,7 @@ import (
) )
func TestToolRecord(t *testing.T) { func TestToolRecord(t *testing.T) {
workspace, err := ioutil.TempDir("", "") workspace := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary workspace directory")
}
defer os.RemoveAll(workspace)
t.Run("Check toolrecord", func(t *testing.T) { t.Run("Check toolrecord", func(t *testing.T) {
tr := toolrecord.New(workspace, "dummyTool", "dummyInstance") tr := toolrecord.New(workspace, "dummyTool", "dummyInstance")

View File

@@ -41,14 +41,9 @@ func TestDockerGetVersion(t *testing.T) {
t.Run("success case - buildTool", func(t *testing.T) { t.Run("success case - buildTool", func(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
filePath := filepath.Join(dir, "package.json") filePath := filepath.Join(dir, "package.json")
err = ioutil.WriteFile(filePath, []byte(`{"version": "1.2.3"}`), 0700) err := ioutil.WriteFile(filePath, []byte(`{"version": "1.2.3"}`), 0700)
if err != nil { if err != nil {
t.Fatal("Failed to create test file") t.Fatal("Failed to create test file")
} }
@@ -123,14 +118,9 @@ func TestDockerSetVersion(t *testing.T) {
}) })
t.Run("success case - buildTool", func(t *testing.T) { t.Run("success case - buildTool", func(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
filePath := filepath.Join(dir, "package.json") filePath := filepath.Join(dir, "package.json")
err = ioutil.WriteFile(filePath, []byte(`{"version": "1.2.3"}`), 0700) err := ioutil.WriteFile(filePath, []byte(`{"version": "1.2.3"}`), 0700)
if err != nil { if err != nil {
t.Fatal("Failed to create test file") t.Fatal("Failed to create test file")
} }

View File

@@ -11,11 +11,7 @@ import (
func TestGradleGetVersion(t *testing.T) { func TestGradleGetVersion(t *testing.T) {
t.Run("success case", func(t *testing.T) { t.Run("success case", func(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "") tmpFolder := t.TempDir()
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
gradlePropsFilePath := filepath.Join(tmpFolder, "gradle.properties") gradlePropsFilePath := filepath.Join(tmpFolder, "gradle.properties")
ioutil.WriteFile(gradlePropsFilePath, []byte("version = 1.2.3"), 0666) ioutil.WriteFile(gradlePropsFilePath, []byte("version = 1.2.3"), 0666)
@@ -32,11 +28,7 @@ func TestGradleGetVersion(t *testing.T) {
func TestGradleSetVersion(t *testing.T) { func TestGradleSetVersion(t *testing.T) {
t.Run("success case", func(t *testing.T) { t.Run("success case", func(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "") tmpFolder := t.TempDir()
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
gradlePropsFilePath := filepath.Join(tmpFolder, "gradle.properties") gradlePropsFilePath := filepath.Join(tmpFolder, "gradle.properties")
ioutil.WriteFile(gradlePropsFilePath, []byte("version = 0.0.1"), 0666) ioutil.WriteFile(gradlePropsFilePath, []byte("version = 0.0.1"), 0666)
@@ -46,7 +38,7 @@ func TestGradleSetVersion(t *testing.T) {
path: gradlePropsFilePath, path: gradlePropsFilePath,
writeFile: func(filename string, filecontent []byte, mode os.FileMode) error { content = filecontent; return nil }, writeFile: func(filename string, filecontent []byte, mode os.FileMode) error { content = filecontent; return nil },
} }
err = gradle.SetVersion("1.2.3") err := gradle.SetVersion("1.2.3")
assert.NoError(t, err) assert.NoError(t, err)
assert.Contains(t, string(content), "version = 1.2.3") assert.Contains(t, string(content), "version = 1.2.3")

View File

@@ -5,7 +5,6 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/magiconair/properties" "github.com/magiconair/properties"
@@ -14,11 +13,7 @@ import (
func TestPropertiesFileGetVersion(t *testing.T) { func TestPropertiesFileGetVersion(t *testing.T) {
t.Run("success case", func(t *testing.T) { t.Run("success case", func(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "") tmpFolder := t.TempDir()
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
propsFilePath := filepath.Join(tmpFolder, "my.props") propsFilePath := filepath.Join(tmpFolder, "my.props")
ioutil.WriteFile(propsFilePath, []byte("version = 1.2.3"), 0666) ioutil.WriteFile(propsFilePath, []byte("version = 1.2.3"), 0666)
@@ -33,11 +28,7 @@ func TestPropertiesFileGetVersion(t *testing.T) {
}) })
t.Run("success case - custom version field", func(t *testing.T) { t.Run("success case - custom version field", func(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "") tmpFolder := t.TempDir()
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
propsFilePath := filepath.Join(tmpFolder, "my.props") propsFilePath := filepath.Join(tmpFolder, "my.props")
ioutil.WriteFile(propsFilePath, []byte("customversion = 1.2.3"), 0666) ioutil.WriteFile(propsFilePath, []byte("customversion = 1.2.3"), 0666)
@@ -53,28 +44,20 @@ func TestPropertiesFileGetVersion(t *testing.T) {
}) })
t.Run("error case - file not found", func(t *testing.T) { t.Run("error case - file not found", func(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "") tmpFolder := t.TempDir()
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
propsFilePath := filepath.Join(tmpFolder, "my.props") propsFilePath := filepath.Join(tmpFolder, "my.props")
propsfile := PropertiesFile{ propsfile := PropertiesFile{
path: propsFilePath, path: propsFilePath,
} }
_, err = propsfile.GetVersion() _, err := propsfile.GetVersion()
assert.Contains(t, fmt.Sprint(err), "failed to load") assert.Contains(t, fmt.Sprint(err), "failed to load")
}) })
t.Run("error case - no version found", func(t *testing.T) { t.Run("error case - no version found", func(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "") tmpFolder := t.TempDir()
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
propsFilePath := filepath.Join(tmpFolder, "my.props") propsFilePath := filepath.Join(tmpFolder, "my.props")
ioutil.WriteFile(propsFilePath, []byte("versionx = 1.2.3"), 0666) ioutil.WriteFile(propsFilePath, []byte("versionx = 1.2.3"), 0666)
@@ -82,7 +65,7 @@ func TestPropertiesFileGetVersion(t *testing.T) {
propsfile := PropertiesFile{ propsfile := PropertiesFile{
path: propsFilePath, path: propsFilePath,
} }
_, err = propsfile.GetVersion() _, err := propsfile.GetVersion()
assert.EqualError(t, err, "no version found in field version") assert.EqualError(t, err, "no version found in field version")
}) })
@@ -90,11 +73,7 @@ func TestPropertiesFileGetVersion(t *testing.T) {
func TestPropertiesFileSetVersion(t *testing.T) { func TestPropertiesFileSetVersion(t *testing.T) {
t.Run("success case", func(t *testing.T) { t.Run("success case", func(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "") tmpFolder := t.TempDir()
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
propsFilePath := filepath.Join(tmpFolder, "my.props") propsFilePath := filepath.Join(tmpFolder, "my.props")
ioutil.WriteFile(propsFilePath, []byte("version = 0.0.1"), 0666) ioutil.WriteFile(propsFilePath, []byte("version = 0.0.1"), 0666)
@@ -104,7 +83,7 @@ func TestPropertiesFileSetVersion(t *testing.T) {
path: propsFilePath, path: propsFilePath,
writeFile: func(filename string, filecontent []byte, mode os.FileMode) error { content = filecontent; return nil }, writeFile: func(filename string, filecontent []byte, mode os.FileMode) error { content = filecontent; return nil },
} }
err = propsfile.SetVersion("1.2.3") err := propsfile.SetVersion("1.2.3")
assert.NoError(t, err) assert.NoError(t, err)
assert.Contains(t, string(content), "version = 1.2.3") assert.Contains(t, string(content), "version = 1.2.3")