1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2025-03-11 14:59:27 +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
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
47 changed files with 245 additions and 723 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -221,16 +221,12 @@ func TestGetResultATCRun(t *testing.T) {
func TestParseATCResult(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")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
bodyString := `<?xml version="1.0" encoding="UTF-8"?>
<checkstyle>
@ -246,26 +242,22 @@ func TestParseATCResult(t *testing.T) {
</file>
</checkstyle>`
body := []byte(bodyString)
err = logAndPersistATCResult(body, "ATCResults.xml", false)
err := logAndPersistATCResult(body, "ATCResults.xml", false)
assert.Equal(t, nil, err)
})
t.Run("succes case: test parsing empty XML result", func(t *testing.T) {
dir, err := ioutil.TempDir("", "test get result ATC run")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
bodyString := `<?xml version="1.0" encoding="UTF-8"?>
<checkstyle>
</checkstyle>`
body := []byte(bodyString)
err = logAndPersistATCResult(body, "ATCResults.xml", false)
err := logAndPersistATCResult(body, "ATCResults.xml", false)
assert.Equal(t, nil, err)
})
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")
})
t.Run("failure case: html response", func(t *testing.T) {
dir, err := ioutil.TempDir("", "test get result ATC run")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
bodyString := `<html><head><title>HTMLTestResponse</title</head></html>`
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")
})
}
@ -413,16 +401,12 @@ func TestResolveConfiguration(t *testing.T) {
AtcConfig: "atc.yml",
}
dir, err := ioutil.TempDir("", "atcDir")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
yamlBody := `checkvariant: MY_TEST
@ -437,7 +421,7 @@ atcobjects:
- 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) {
bodyString, err := buildATCRequestBody(config)
assert.Equal(t, nil, err)
@ -452,16 +436,12 @@ atcobjects:
AtcConfig: "atc.yml",
}
dir, err := ioutil.TempDir("", "atcDir")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
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>"
err = ioutil.WriteFile(config.AtcConfig, []byte(yamlBody), 0644)
err := ioutil.WriteFile(config.AtcConfig, []byte(yamlBody), 0644)
if assert.Equal(t, err, nil) {
bodyString, err := buildATCRequestBody(config)
assert.Equal(t, nil, err)
@ -494,16 +474,12 @@ objectset:
Repositories: "repo.yml",
}
dir, err := ioutil.TempDir("", "test parse AUnit yaml config2")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
yamlBody := `repositories:
@ -511,7 +487,7 @@ objectset:
- 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) {
bodyString, err := buildATCRequestBody(config)
assert.Equal(t, nil, err)

View File

@ -260,16 +260,12 @@ func TestBuildAUnitRequestBody(t *testing.T) {
Repositories: "repositories.yml",
}
dir, err := ioutil.TempDir("", "test parse AUnit yaml config2")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
repositories := `repositories:
@ -277,7 +273,7 @@ func TestBuildAUnitRequestBody(t *testing.T) {
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>"
err = ioutil.WriteFile(config.Repositories, []byte(repositories), 0644)
err := ioutil.WriteFile(config.Repositories, []byte(repositories), 0644)
if assert.Equal(t, err, nil) {
bodyString, err := buildAUnitRequestBody(config)
assert.Equal(t, nil, err)
@ -292,16 +288,12 @@ func TestBuildAUnitRequestBody(t *testing.T) {
AUnitConfig: "aunit.yml",
}
dir, err := ioutil.TempDir("", "test parse AUnit yaml config2")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
yamlBody := `title: My AUnit run
@ -313,7 +305,7 @@ objectset:
- 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>"
err = ioutil.WriteFile(config.AUnitConfig, []byte(yamlBody), 0644)
err := ioutil.WriteFile(config.AUnitConfig, []byte(yamlBody), 0644)
if assert.Equal(t, err, nil) {
bodyString, err := buildAUnitRequestBody(config)
assert.Equal(t, nil, err)
@ -328,16 +320,12 @@ objectset:
AUnitConfig: "aunit.yml",
}
dir, err := ioutil.TempDir("", "test parse AUnit yaml config2")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
yamlBody := `title: My AUnit run
@ -351,7 +339,7 @@ objectset:
- 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>"
err = ioutil.WriteFile(config.AUnitConfig, []byte(yamlBody), 0644)
err := ioutil.WriteFile(config.AUnitConfig, []byte(yamlBody), 0644)
if assert.Equal(t, err, nil) {
bodyString, err := buildAUnitRequestBody(config)
assert.Equal(t, nil, err)
@ -400,16 +388,12 @@ func TestTriggerAUnitrun(t *testing.T) {
URL: "https://api.endpoint.com/Entity/",
}
dir, err := ioutil.TempDir("", "test parse AUnit yaml config")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
yamlBody := `title: My AUnit run
@ -434,7 +418,7 @@ objectset:
- 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) {
_, err := triggerAUnitrun(config, con, client)
assert.Equal(t, nil, err)
@ -458,16 +442,12 @@ objectset:
URL: "https://api.endpoint.com/Entity/",
}
dir, err := ioutil.TempDir("", "test parse AUnit yaml config2")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
yamlBody := `title: My AUnit run
@ -493,7 +473,7 @@ objectset:
- 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) {
_, err := triggerAUnitrun(config, con, client)
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) {
dir, err := ioutil.TempDir("", "test get result AUnit test run")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = 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>`
body := []byte(bodyString)
err = persistAUnitResult(body, "AUnitResults.xml", false)
err := persistAUnitResult(body, "AUnitResults.xml", false)
assert.Equal(t, nil, err)
})
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")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
bodyString := `<?xml version="1.0" encoding="UTF-8"?>`
body := []byte(bodyString)
err = persistAUnitResult(body, "AUnitResults.xml", false)
err := persistAUnitResult(body, "AUnitResults.xml", false)
assert.Equal(t, nil, err)
})

View File

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

View File

@ -342,14 +342,9 @@ func TestZipFolder(t *testing.T) {
t.Run("zip files successfully", func(t *testing.T) {
t.Parallel()
dir, err := ioutil.TempDir("", "test zip files")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
dir := t.TempDir()
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)
err = ioutil.WriteFile(filepath.Join(dir, "abcd.yaml"), []byte("abcd.yaml"), 0700)
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.Parallel()
dir, err := ioutil.TempDir("", "test zip files")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
dir := t.TempDir()
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)
err = os.Mkdir(filepath.Join(dir, "somepath"), 0700)
assert.NoError(t, err)
@ -406,14 +396,9 @@ func TestZipFolder(t *testing.T) {
t.Run("error on os stat", func(t *testing.T) {
t.Parallel()
dir, err := ioutil.TempDir("", "test zip files")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
dir := t.TempDir()
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)
err = os.Mkdir(filepath.Join(dir, "somepath"), 0700)
assert.NoError(t, err)
@ -434,14 +419,9 @@ func TestZipFolder(t *testing.T) {
t.Run("error on os Open", func(t *testing.T) {
t.Parallel()
dir, err := ioutil.TempDir("", "test zip files")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
dir := t.TempDir()
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)
err = os.Mkdir(filepath.Join(dir, "somepath"), 0700)
assert.NoError(t, err)
@ -486,12 +466,7 @@ func TestGetDetailedResults(t *testing.T) {
</Result>
</Query>
</CxXMLResults>`)}
dir, err := ioutil.TempDir("", "test detailed results")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
dir := t.TempDir()
result, err := getDetailedResults(sys, filepath.Join(dir, "abc.xml"), 2635, newCheckmarxExecuteScanUtilsMock())
assert.NoError(t, err, "error occurred but none expected")
assert.Equal(t, "2", result["ProjectId"], "Project ID incorrect")
@ -524,15 +499,10 @@ func TestGetDetailedResults(t *testing.T) {
</Result>
</Query>
</CxXMLResults>`)}
dir, err := ioutil.TempDir("", "test detailed results")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
dir := t.TempDir()
utils := newCheckmarxExecuteScanUtilsMock()
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")
})
}
@ -542,13 +512,8 @@ func TestRunScan(t *testing.T) {
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}
workspace, err := ioutil.TempDir("", "workspace1")
if err != nil {
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)
workspace := t.TempDir()
err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err)
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 />`)}
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")
if err != nil {
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)
workspace := t.TempDir()
err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err)
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 />`)}
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")
if err != nil {
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)
workspace := t.TempDir()
err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err)
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 />`)}
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")
if err != nil {
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
workspace := t.TempDir()
influx := checkmarxExecuteScanInflux{}
utilsMock := newCheckmarxExecuteScanUtilsMock()
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.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 />`)}
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")
if err != nil {
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
workspace := t.TempDir()
influx := checkmarxExecuteScanInflux{}
@ -678,7 +623,7 @@ func TestVerifyOnly_errorOnWriteFileDoesNotBlock(t *testing.T) {
utilsMock.workspace = workspace
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")
}
@ -687,13 +632,8 @@ func TestRunScanWOtherCycle(t *testing.T) {
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}
workspace, err := ioutil.TempDir("", "workspace2")
if err != nil {
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)
workspace := t.TempDir()
err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err)
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}
options := checkmarxExecuteScanOptions{VulnerabilityThresholdUnit: "percentage", FullScanCycle: "3", Incremental: true, FullScansScheduled: true, Preset: "123", TeamID: "16", VulnerabilityThresholdEnabled: true, GeneratePdfReport: true}
workspace, err := ioutil.TempDir("", "workspace2")
if err != nil {
t.Fatal("Failed to create temporary workspace directory")
}
// clean up tmp dir
defer os.RemoveAll(workspace)
workspace := t.TempDir()
influx := checkmarxExecuteScanInflux{}
@ -727,7 +662,7 @@ func TestRunScanErrorInZip(t *testing.T) {
utilsMock.workspace = workspace
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")
}
@ -736,13 +671,8 @@ func TestRunScanForPullRequest(t *testing.T) {
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}
workspace, err := ioutil.TempDir("", "workspace3")
if err != nil {
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)
workspace := t.TempDir()
err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err)
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}
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")
if err != nil {
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)
workspace := t.TempDir()
err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err)
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}
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")
if err != nil {
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)
workspace := t.TempDir()
err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err)
options.FilterPattern = "**/abcd.go"
@ -832,13 +752,8 @@ func TestRunScanHighViolationPercentage(t *testing.T) {
</Query>
</CxXMLResults>`)}
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")
if err != nil {
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)
workspace := t.TempDir()
err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err)
options.FilterPattern = "**/abcd.go"
@ -875,13 +790,8 @@ func TestRunScanHighViolationAbsolute(t *testing.T) {
</Query>
</CxXMLResults>`)}
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")
if err != nil {
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)
workspace := t.TempDir()
err := ioutil.WriteFile(filepath.Join(workspace, "abcd.go"), []byte("abcd.go"), 0700)
assert.NoError(t, err)
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) {
defer cfMockCleanup(m)
dir, err := ioutil.TempDir("", "test variable substitution")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
manifestFileString := `
@ -146,7 +142,8 @@ func TestCloudFoundryCreateService(t *testing.T) {
plan: "testPlan"`
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"}
@ -171,16 +168,12 @@ func TestCloudFoundryCreateService(t *testing.T) {
t.Run("Create service: variable substitution with variable substitution manifest file", func(t *testing.T) {
defer cfMockCleanup(m)
dir, err := ioutil.TempDir("", "test variable substitution")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
varsFileString := `name: test1
name2: test2`
@ -202,9 +195,12 @@ func TestCloudFoundryCreateService(t *testing.T) {
varsFileStringBody := []byte(varsFileString)
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)
assert.NoError(t, err)
err = ioutil.WriteFile("manifestTest.yml", manifestFileStringBody, 0644)
assert.NoError(t, err)
var manifestVariablesFiles = []string{"varsTest.yml", "varsTest2.yml"}
config := cloudFoundryCreateServiceOptions{

View File

@ -2,7 +2,6 @@ package cmd
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -45,15 +44,11 @@ func TestRunContainerSaveImage(t *testing.T) {
t.Run("failure - download image", func(t *testing.T) {
config := containerSaveImageOptions{}
tmpFolder, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
tmpFolder := t.TempDir()
dClient := mock.DownloadMock{ReturnError: "download error"}
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")
})
}

View File

@ -553,16 +553,12 @@ func TestAnalyseUnauditedIssues(t *testing.T) {
func TestTriggerFortifyScan(t *testing.T) {
t.Run("maven", func(t *testing.T) {
dir, err := ioutil.TempDir("", "test trigger fortify scan")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
utils := newFortifyTestUtilsBundle()
@ -588,16 +584,12 @@ func TestTriggerFortifyScan(t *testing.T) {
})
t.Run("pip", func(t *testing.T) {
dir, err := ioutil.TempDir("", "test trigger fortify scan")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
utils := newFortifyTestUtilsBundle()
@ -625,16 +617,12 @@ func TestTriggerFortifyScan(t *testing.T) {
})
t.Run("invalid buildTool", func(t *testing.T) {
dir, err := ioutil.TempDir("", "test trigger fortify scan")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
utils := newFortifyTestUtilsBundle()
@ -642,7 +630,7 @@ func TestTriggerFortifyScan(t *testing.T) {
BuildTool: "docker",
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.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) {
t.Run("success pip", func(t *testing.T) {
utils := newFortifyTestUtilsBundle()
dir, err := ioutil.TempDir("", "classpath")
assert.NoError(t, err, "Unexpected error detected")
defer os.RemoveAll(dir)
dir := t.TempDir()
file := filepath.Join(dir, "cp.txt")
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) {
utils := newFortifyTestUtilsBundle()
dir, err := ioutil.TempDir("", "classpath")
assert.NoError(t, err, "Unexpected error detected")
defer os.RemoveAll(dir)
dir := t.TempDir()
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.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) {
utils := newFortifyTestUtilsBundle()
dir, err := ioutil.TempDir("", "classpath")
assert.NoError(t, err, "Unexpected error detected")
defer os.RemoveAll(dir)
dir := t.TempDir()
file := filepath.Join(dir, "cp.txt")
result, err := autoresolveMavenClasspath(fortifyExecuteScanOptions{BuildDescriptorFile: "pom.xml"}, file, &utils)

View File

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

View File

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

View File

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

View File

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

View File

@ -205,13 +205,11 @@ func TestGetProjectConfigFile(t *testing.T) {
for run, test := range tt {
t.Run(fmt.Sprintf("Run %v", run), func(t *testing.T) {
dir, err := ioutil.TempDir("", "")
defer os.RemoveAll(dir) // clean up
assert.NoError(t, err)
dir := t.TempDir()
if len(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)
}

View File

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

View File

@ -155,9 +155,7 @@ func TestRunSonar(t *testing.T) {
t.Run("default", func(t *testing.T) {
// init
tmpFolder, err := ioutil.TempDir(".", "test-sonar-")
require.NoError(t, err)
defer os.RemoveAll(tmpFolder)
tmpFolder := t.TempDir()
createTaskReportFile(t, tmpFolder)
sonar = sonarSettings{
@ -177,7 +175,7 @@ func TestRunSonar(t *testing.T) {
}
fileUtilsExists = mockFileUtilsExists(true)
// test
err = runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
err := runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
// assert
assert.NoError(t, err)
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) {
// init
tmpFolder, err := ioutil.TempDir(".", "test-sonar-")
require.NoError(t, err)
defer os.RemoveAll(tmpFolder)
tmpFolder := t.TempDir()
createTaskReportFile(t, tmpFolder)
sonar = sonarSettings{
@ -210,16 +206,14 @@ func TestRunSonar(t *testing.T) {
fileUtilsExists = FileUtils.FileExists
}()
// test
err = runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
err := runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
// assert
assert.NoError(t, err)
assert.Contains(t, sonar.options, "-Dsonar.projectKey=piper")
})
t.Run("with binaries option", func(t *testing.T) {
// init
tmpFolder, err := ioutil.TempDir(".", "test-sonar-")
require.NoError(t, err)
defer func() { _ = os.RemoveAll(tmpFolder) }()
tmpFolder := t.TempDir()
createTaskReportFile(t, tmpFolder)
sonar = sonarSettings{
@ -250,7 +244,7 @@ func TestRunSonar(t *testing.T) {
PullRequestProvider: "GitHub",
}
// test
err = runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
err := runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
// assert
assert.NoError(t, err)
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) {
// init
tmpFolder, err := ioutil.TempDir(".", "test-sonar-")
require.NoError(t, err)
defer func() { _ = os.RemoveAll(tmpFolder) }()
tmpFolder := t.TempDir()
createTaskReportFile(t, tmpFolder)
sonar = sonarSettings{
@ -292,7 +284,7 @@ func TestRunSonar(t *testing.T) {
PullRequestProvider: "GitHub",
}
// test
err = runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
err := runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
// assert
assert.NoError(t, err)
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) {
// init
tmpFolder, err := ioutil.TempDir(".", "test-sonar-")
require.NoError(t, err)
defer os.RemoveAll(tmpFolder)
tmpFolder := t.TempDir()
createTaskReportFile(t, tmpFolder)
sonar = sonarSettings{
@ -326,7 +316,7 @@ func TestRunSonar(t *testing.T) {
fileUtilsExists = FileUtils.FileExists
}()
// test
err = runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
err := runSonar(options, &mockDownloadClient, &mockRunner, apiClient, &sonarExecuteScanInflux{})
// assert
assert.NoError(t, err)
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
// Changes to the test require peer review by core-team members involved in the project.
func TestGenerator(t *testing.T) {
dir, err := ioutil.TempDir("", "")
defer os.RemoveAll(dir) // clean up
assert.NoError(t, err, "Error when creating temp dir")
dir := t.TempDir()
metadata := `metadata:
name: test

View File

@ -27,8 +27,7 @@ func TestKarmaIntegration(t *testing.T) {
pwd = filepath.Dir(pwd)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("")
defer os.RemoveAll(tempDir) // clean up
tempDir, err := createTmpDir(t)
assert.NoError(t, err, "Error when creating temp dir")
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)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("")
defer os.RemoveAll(tempDir) // clean up
tempDir, err := createTmpDir(t)
assert.NoError(t, err, "Error when creating temp dir")
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.")
}
//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
cd /test
/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.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"))
if err != nil {
t.Fatal("Could not read test-log.txt.", err)

View File

@ -33,12 +33,10 @@ func TestPiperGithubPublishRelease(t *testing.T) {
if len(repository) == 0 {
repository = "piper-integration"
}
dir, err := ioutil.TempDir("", "")
defer os.RemoveAll(dir) // clean up
assert.NoError(t, err, "Error when creating temp dir")
dir := t.TempDir()
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")
test2Asset := filepath.Join(dir, "test2.txt")
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)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("")
defer os.RemoveAll(tempDir) // clean up
tempDir, err := createTmpDir(t)
assert.NoError(t, err, "Error when creating temp dir")
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)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("")
defer os.RemoveAll(tempDir) // clean up
tempDir, err := createTmpDir(t)
assert.NoError(t, err, "Error when creating temp dir")
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)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("")
defer os.RemoveAll(tempDir) // clean up
tempDir, err := createTmpDir(t)
assert.NoError(t, err, "Error when creating temp dir")
err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "runScriptsWithOptions"), tempDir)
@ -77,8 +76,7 @@ func TestRegistrySetInFlags(t *testing.T) {
pwd = filepath.Dir(pwd)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("")
defer os.RemoveAll(tempDir) // clean up
tempDir, err := createTmpDir(t)
assert.NoError(t, err, "Error when creating temp dir")
err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "registrySetInFlags"), tempDir)
@ -128,8 +126,7 @@ func TestRegistrySetInNpmrc(t *testing.T) {
pwd = filepath.Dir(pwd)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("")
defer os.RemoveAll(tempDir) // clean up
tempDir, err := createTmpDir(t)
assert.NoError(t, err, "Error when creating temp dir")
err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "registrySetInNpmrc"), tempDir)
@ -179,8 +176,7 @@ func TestRegistryWithTwoModules(t *testing.T) {
pwd = filepath.Dir(pwd)
// using custom createTmpDir function to avoid issues with symlinks on Docker for Mac
tempDir, err := createTmpDir("")
defer os.RemoveAll(tempDir) // clean up
tempDir, err := createTmpDir(t)
assert.NoError(t, err, "Error when creating temp dir")
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.")
pwd = filepath.Dir(pwd)
tempDir, err := createTmpDir("")
defer os.RemoveAll(tempDir) // clean up
tempDir, err := createTmpDir(t)
assert.NoError(t, err, "Error when creating temp dir")
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())
}
func createTmpDir(prefix string) (string, error) {
dirName := os.TempDir()
tmpDir, err := filepath.EvalSymlinks(dirName)
// createTmpDir calls t.TempDir() and returns the path name after the evaluation
// of any symbolic links.
//
// 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 {
return "", err
}
tmpDir = filepath.Clean(tmpDir)
path, err := ioutil.TempDir(tmpDir, prefix)
if err != nil {
return "", err
}
return path, nil
return tmpDir, nil
}

View File

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

View File

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

View File

@ -1,7 +1,6 @@
package metadata
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -37,11 +36,9 @@ func TestWriteProjectMetadata(t *testing.T) {
"branch": "main",
}
dir, err := ioutil.TempDir("", "")
dir := t.TempDir()
err := os.MkdirAll(filepath.Join(dir, "commonPipelineEnvironment", "git"), os.ModePerm)
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 {
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.Parallel()
tmpdir, err := ioutil.TempDir("", "cpe")
assert.NoError(t, err)
defer os.RemoveAll(tmpdir)
tmpdir := t.TempDir()
err = os.MkdirAll(filepath.Join(tmpdir, "commonPipelineEnvironment", "git"), os.ModePerm)
err := os.MkdirAll(filepath.Join(tmpdir, "commonPipelineEnvironment", "git"), os.ModePerm)
assert.NoError(t, err)
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.Parallel()
tmpdir, err := ioutil.TempDir("", "cpe")
assert.NoError(t, err)
defer os.RemoveAll(tmpdir)
tmpdir := t.TempDir()
err = os.MkdirAll(filepath.Join(tmpdir, "commonPipelineEnvironment", "github"), os.ModePerm)
err := os.MkdirAll(filepath.Join(tmpdir, "commonPipelineEnvironment", "github"), os.ModePerm)
assert.NoError(t, err)
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("", "")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
dir := t.TempDir()
piperenv.SetParameter(filepath.Join(dir, "commonPipelineEnvironment"), "test_pe1", "pe1_val")
@ -249,13 +243,7 @@ steps:
{Name: "p0", ResourceRef: []ResourceReference{{Name: "commonPipelineEnvironment", Param: "p0"}}},
}}}}
dir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
dir := t.TempDir()
stepConfig, err := c.GetStepConfig(map[string]interface{}{}, "", myConfig, defaults, false, filters, stepMeta, stepMeta.GetResourceParameters(dir, "commonPipelineEnvironment"), "stage1", "step1")
@ -382,15 +370,9 @@ steps:
steps:
step1:
gcsBucketId: gcsBucketId_value`))}
dir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
dir := t.TempDir()
cpeDir := filepath.Join(dir, "commonPipelineEnvironment/custom")
err = os.MkdirAll(cpeDir, 0700)
err := os.MkdirAll(cpeDir, 0700)
if err != nil {
t.Fatal("Failed to create sub directory")
}
@ -456,14 +438,6 @@ stages:
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")
assert.Equal(t, nil, err, "error occurred but none expected")
@ -506,14 +480,6 @@ stages:
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")
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("package.json", []byte(packageJson))
dir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
dir := t.TempDir()
cpeDir := filepath.Join(dir, "commonPipelineEnvironment")
err = os.MkdirAll(cpeDir, 0700)
err := os.MkdirAll(cpeDir, 0700)
if err != nil {
t.Fatal("Failed to create sub directory")
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,15 +1,16 @@
package piperutils
import (
"github.com/stretchr/testify/assert"
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
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)
if err != nil {
t.Fatal("failed to create test dir in temporary dir")
@ -18,7 +19,7 @@ func TestFileExists(t *testing.T) {
assert.NoError(t, err)
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")
assert.NoError(t, err)
result, err := FileExists(file.Name())
@ -28,7 +29,7 @@ func TestFileExists(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)
if err != nil {
t.Fatal("failed to create test dir in temporary dir")
@ -50,7 +51,7 @@ func TestDirExists(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"
err := ioutil.WriteFile(file, []byte{byte(1), byte(2), byte(3)}, 0700)
if err != nil {
@ -61,7 +62,7 @@ func TestCopy(t *testing.T) {
assert.NoError(t, err, "Didn't expert error but got one")
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")
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)) {
dir, err := ioutil.TempDir("", tempDirPattern)
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
func runInTempDir(t *testing.T, nameOfRun string, run func(t *testing.T)) {
t.Run(nameOfRun, func(t *testing.T) {
dir := t.TempDir()
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
t.Cleanup(func() {
_ = os.Chdir(oldCWD)
})
t.Run(nameOfRun, run)
run(t)
})
}
func TestExcludeFiles(t *testing.T) {

View File

@ -8,7 +8,7 @@ import (
)
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"
src, err := os.OpenFile(srcName, os.O_CREATE|os.O_RDWR, 0700)
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, 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"
src, err := os.OpenFile(srcName, os.O_CREATE|os.O_RDWR, 0700)
if err != nil {
@ -73,7 +73,7 @@ func TestCopyData(t *testing.T) {
assert.NoError(t, err, "Didn't expect error but got one")
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"
src, err := os.OpenFile(srcName, os.O_CREATE|os.O_RDWR, 0700)
if err != nil {
@ -100,7 +100,7 @@ func TestCopyData(t *testing.T) {
assert.Error(t, err, "Expected error but got none")
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"
src, err := os.OpenFile(srcName, os.O_CREATE|os.O_RDWR, 0700)
if err != nil {

View File

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

View File

@ -1,8 +1,6 @@
package toolrecord_test
import (
"io/ioutil"
"os"
"testing"
"github.com/SAP/jenkins-library/pkg/toolrecord"
@ -10,11 +8,7 @@ import (
)
func TestToolRecord(t *testing.T) {
workspace, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("Failed to create temporary workspace directory")
}
defer os.RemoveAll(workspace)
workspace := t.TempDir()
t.Run("Check toolrecord", func(t *testing.T) {
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) {
dir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
dir := t.TempDir()
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 {
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) {
dir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("Failed to create temporary directory")
}
// clean up tmp dir
defer os.RemoveAll(dir)
dir := t.TempDir()
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 {
t.Fatal("Failed to create test file")
}

View File

@ -11,11 +11,7 @@ import (
func TestGradleGetVersion(t *testing.T) {
t.Run("success case", func(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
tmpFolder := t.TempDir()
gradlePropsFilePath := filepath.Join(tmpFolder, "gradle.properties")
ioutil.WriteFile(gradlePropsFilePath, []byte("version = 1.2.3"), 0666)
@ -32,11 +28,7 @@ func TestGradleGetVersion(t *testing.T) {
func TestGradleSetVersion(t *testing.T) {
t.Run("success case", func(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
tmpFolder := t.TempDir()
gradlePropsFilePath := filepath.Join(tmpFolder, "gradle.properties")
ioutil.WriteFile(gradlePropsFilePath, []byte("version = 0.0.1"), 0666)
@ -46,7 +38,7 @@ func TestGradleSetVersion(t *testing.T) {
path: gradlePropsFilePath,
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.Contains(t, string(content), "version = 1.2.3")

View File

@ -5,7 +5,6 @@ import (
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/magiconair/properties"
@ -14,11 +13,7 @@ import (
func TestPropertiesFileGetVersion(t *testing.T) {
t.Run("success case", func(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
tmpFolder := t.TempDir()
propsFilePath := filepath.Join(tmpFolder, "my.props")
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) {
tmpFolder, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
tmpFolder := t.TempDir()
propsFilePath := filepath.Join(tmpFolder, "my.props")
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) {
tmpFolder, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
tmpFolder := t.TempDir()
propsFilePath := filepath.Join(tmpFolder, "my.props")
propsfile := PropertiesFile{
path: propsFilePath,
}
_, err = propsfile.GetVersion()
_, err := propsfile.GetVersion()
assert.Contains(t, fmt.Sprint(err), "failed to load")
})
t.Run("error case - no version found", func(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
tmpFolder := t.TempDir()
propsFilePath := filepath.Join(tmpFolder, "my.props")
ioutil.WriteFile(propsFilePath, []byte("versionx = 1.2.3"), 0666)
@ -82,7 +65,7 @@ func TestPropertiesFileGetVersion(t *testing.T) {
propsfile := PropertiesFile{
path: propsFilePath,
}
_, err = propsfile.GetVersion()
_, err := propsfile.GetVersion()
assert.EqualError(t, err, "no version found in field version")
})
@ -90,11 +73,7 @@ func TestPropertiesFileGetVersion(t *testing.T) {
func TestPropertiesFileSetVersion(t *testing.T) {
t.Run("success case", func(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal("failed to create temp dir")
}
defer os.RemoveAll(tmpFolder)
tmpFolder := t.TempDir()
propsFilePath := filepath.Join(tmpFolder, "my.props")
ioutil.WriteFile(propsFilePath, []byte("version = 0.0.1"), 0666)
@ -104,7 +83,7 @@ func TestPropertiesFileSetVersion(t *testing.T) {
path: propsFilePath,
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.Contains(t, string(content), "version = 1.2.3")