Skip to content

Commit

Permalink
Merge pull request #60 from gruntwork-io/test-data
Browse files Browse the repository at this point in the history
Add ability to test whether test data exists.
  • Loading branch information
josh-padnick authored Mar 13, 2018
2 parents 80086cc + 0742bb2 commit 30ad0be
Show file tree
Hide file tree
Showing 3 changed files with 131 additions and 1 deletion.
13 changes: 12 additions & 1 deletion _docker-images/gruntwork-amzn-linux-test/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,15 @@ RUN yum update -y && \
sudo \
vim \
wget && \
yum clean all
yum clean all

# Installing pip with yum doesn't actually put it in the PATH, so we use easy_install instead. Pip will now be placed
# in /usr/local/bin, but amazonlinux's sudo uses a sanitzed PATH that does not include /usr/local/bin, so we symlink pip.
RUN curl https://bootstrap.pypa.io/ez_setup.py | sudo /usr/bin/python && \
easy_install pip && \
pip install --upgrade pip && \
ln -s /usr/local/bin/pip /usr/bin/pip

# Install the AWSCLI (which apparently does not come pre-bundled with Amazon Linux!)
RUN pip install --upgrade setuptools && \
pip install awscli --upgrade
66 changes: 66 additions & 0 deletions test-structure/test_structure.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,72 @@ func LoadTestData(t *testing.T, path string, value interface{}, logger *log.Logg
}
}

// Return true if a file exists at $path and the test data there is non-empty.
func IsTestDataPresent(t *testing.T, path string, logger *log.Logger) bool {
logger.Printf("Testing whether test data exists at %s", path)

bytes, err := ioutil.ReadFile(path)
if err != nil && strings.Contains(err.Error(), "no such file or directory") {
logger.Printf("No test data was found at %s", path)
return false
} else if err != nil {
t.Fatalf("Failed to load test data from %s due to unexpected error: %v", path, err)
}

if isEmptyJson(t, bytes) {
logger.Printf("No test data was found at %s", path)
return false
}

logger.Printf("Non-empty test data found at %s", path)
return true
}

// Return true if the given bytes are empty, or in a valid JSON format that can reasonably be considered empty.
// The types used are based on the type possibilities listed at https://golang.org/src/encoding/json/decode.go?s=4062:4110#L51
func isEmptyJson(t *testing.T, bytes []byte) bool {
var value interface{}

if len(bytes) == 0 {
return true
}

if err := json.Unmarshal(bytes, &value); err != nil {
t.Fatalf("Failed to parse JSON while testing whether it is empty: %v", err)
}

if value == nil {
return true
}

valueBool, ok := value.(bool)
if ok && ! valueBool {
return true
}

valueFloat64, ok := value.(float64)
if ok && valueFloat64 == 0 {
return true
}

valueString, ok := value.(string)
if ok && valueString == "" {
return true
}

valueSlice, ok := value.([]interface{})
if ok && len(valueSlice) == 0 {
return true
}

valueMap, ok := value.(map[string]interface{})
if ok && len(valueMap) == 0 {
return true
}

return false
}

// Clean up the test data at the given path
func CleanupTestData(t *testing.T, path string, logger *log.Logger) {
if files.FileExists(path) {
Expand Down
53 changes: 53 additions & 0 deletions test-structure/test_structure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ func TestSaveAndLoadTestData(t *testing.T) {

logger := terralog.NewLogger("TestSaveAndLoadTestData")

isTestDataPresent := IsTestDataPresent(t, "/file/that/does/not/exist", logger)
assert.False(t, isTestDataPresent, "Expected no test data would be present because no test data file exists.")

tmpFile, err := ioutil.TempFile("", "save-and-load-test-data")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
Expand All @@ -30,8 +33,15 @@ func TestSaveAndLoadTestData(t *testing.T) {
Bar: true,
Baz: map[string]interface{}{"abc": "def", "ghi": 1.0, "klm": false},
}

isTestDataPresent = IsTestDataPresent(t, tmpFile.Name(), logger)
assert.False(t, isTestDataPresent, "Expected no test data would be present because file exists but no data has been written yet.")

SaveTestData(t, tmpFile.Name(), expectedData, logger)

isTestDataPresent = IsTestDataPresent(t, tmpFile.Name(), logger)
assert.True(t, isTestDataPresent, "Expected test data would be present because file exists and data has been written to file.")

actualData := testData{}
LoadTestData(t, tmpFile.Name(), &actualData, logger)
assert.Equal(t, expectedData, actualData)
Expand All @@ -40,6 +50,49 @@ func TestSaveAndLoadTestData(t *testing.T) {
assert.False(t, files.FileExists(tmpFile.Name()))
}

func TestIsEmptyJson(t *testing.T) {
t.Parallel()

var jsonValue []byte
var isEmpty bool

jsonValue = []byte("null")
isEmpty = isEmptyJson(t, jsonValue)
assert.True(t, isEmpty, `The JSON literal "null" should be treated as an empty value.`)

jsonValue = []byte("false")
isEmpty = isEmptyJson(t, jsonValue)
assert.True(t, isEmpty, `The JSON literal "false" should be treated as an empty value.`)

jsonValue = []byte("true")
isEmpty = isEmptyJson(t, jsonValue)
assert.False(t, isEmpty, `The JSON literal "true" should be treated as a non-empty value.`)

jsonValue = []byte("0")
isEmpty = isEmptyJson(t, jsonValue)
assert.True(t, isEmpty, `The JSON literal "0" should be treated as an empty value.`)

jsonValue = []byte("1")
isEmpty = isEmptyJson(t, jsonValue)
assert.False(t, isEmpty, `The JSON literal "1" should be treated as a non-empty value.`)

jsonValue = []byte("{}")
isEmpty = isEmptyJson(t, jsonValue)
assert.True(t, isEmpty, `The JSON value "{}" should be treated as an empty value.`)

jsonValue = []byte(`{ "key": "val" }`)
isEmpty = isEmptyJson(t, jsonValue)
assert.False(t, isEmpty, `The JSON value { "key": "val" } should be treated as a non-empty value.`)

jsonValue = []byte(`[]`)
isEmpty = isEmptyJson(t, jsonValue)
assert.True(t, isEmpty, `The JSON value "[]" should be treated as an empty value.`)

jsonValue = []byte(`[{ "key": "val" }]`)
isEmpty = isEmptyJson(t, jsonValue)
assert.False(t, isEmpty, `The JSON value [{ "key": "val" }] should be treated as a non-empty value.`)
}

func TestSaveAndLoadTerratestOptions(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 30ad0be

Please sign in to comment.