Skip to content

Commit

Permalink
feat: add function to read data from files
Browse files Browse the repository at this point in the history
  • Loading branch information
Sashwat-K committed May 13, 2024
1 parent 301906a commit 3c178b8
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 5 deletions.
16 changes: 16 additions & 0 deletions common/general/general.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,22 @@ func ExecCommand(name string, stdinInput string, args ...string) (string, error)
return out.String(), nil
}

// ReadDataFromFile - function to read data from file
func ReadDataFromFile(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()

content, err := io.ReadAll(file)
if err != nil {
return "", err
}

return string(content), nil
}

// CreateTempFile - function to create temp file
func CreateTempFile(data string) (string, error) {
trimmedData := strings.TrimSpace(data)
Expand Down
22 changes: 17 additions & 5 deletions common/general/general_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ import (
)

const (
simpleSampleText = "Testing"
simpleSampleTextPath = "../../samples/simple_file.txt"

simpleContractPath = "../../samples/simple_contract.yaml"
certificateDownloadUrl = "https://cloud.ibm.com/media/docs/downloads/hyper-protect-container-runtime/ibm-hyper-protect-container-runtime-1-0-s390x-15-encrypt.crt"

Expand Down Expand Up @@ -52,10 +55,20 @@ func TestExecCommandUserInput(t *testing.T) {
assert.NoError(t, err)
}

// Testcase to check if ReadDataFromFile() can read data from file
func TestReadDataFromFile(t *testing.T) {
content, err := ReadDataFromFile(simpleSampleTextPath)
if err != nil {
fmt.Println(err)
}

assert.Equal(t, content, simpleSampleText)
assert.NoError(t, err)
}

// Testcase to check if CreateTempFile() can create and modify temp files
func TestCreateTempFile(t *testing.T) {
text := "Testing"
tmpfile, err := CreateTempFile(text)
tmpfile, err := CreateTempFile(simpleSampleText)

file, err1 := os.Open(tmpfile)
if err1 != nil {
Expand All @@ -73,14 +86,13 @@ func TestCreateTempFile(t *testing.T) {
fmt.Println(err1)
}

assert.Equal(t, text, string(content))
assert.Equal(t, simpleSampleText, string(content))
assert.NoError(t, err)
}

// Testcase to check TestRemoveTempFile() removes a file
func TestRemoveTempFile(t *testing.T) {
text := "Testing"
tmpfile, err := CreateTempFile(text)
tmpfile, err := CreateTempFile(simpleSampleText)
if err != nil {
fmt.Println(err)
}
Expand Down
1 change: 1 addition & 0 deletions samples/simple_file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Testing

0 comments on commit 3c178b8

Please sign in to comment.