diff --git a/common/general/general.go b/common/general/general.go index 499baa1..b7b3131 100644 --- a/common/general/general.go +++ b/common/general/general.go @@ -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) diff --git a/common/general/general_test.go b/common/general/general_test.go index 01f1709..b553bcc 100644 --- a/common/general/general_test.go +++ b/common/general/general_test.go @@ -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" @@ -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 { @@ -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) } diff --git a/samples/simple_file.txt b/samples/simple_file.txt new file mode 100644 index 0000000..0a90125 --- /dev/null +++ b/samples/simple_file.txt @@ -0,0 +1 @@ +Testing \ No newline at end of file