github.com/wikibal01/hashicorp-terraform@v0.11.12-beta1/helper/structure/normalize_json_test.go (about) 1 package structure 2 3 import ( 4 "testing" 5 ) 6 7 func TestNormalizeJsonString_valid(t *testing.T) { 8 // Well formatted and valid. 9 validJson := `{ 10 "abc": { 11 "def": 123, 12 "xyz": [ 13 { 14 "a": "ホリネズミ" 15 }, 16 { 17 "b": "1\\n2" 18 } 19 ] 20 } 21 }` 22 expected := `{"abc":{"def":123,"xyz":[{"a":"ホリネズミ"},{"b":"1\\n2"}]}}` 23 24 actual, err := NormalizeJsonString(validJson) 25 if err != nil { 26 t.Fatalf("Expected not to throw an error while parsing JSON, but got: %s", err) 27 } 28 29 if actual != expected { 30 t.Fatalf("Got:\n\n%s\n\nExpected:\n\n%s\n", actual, expected) 31 } 32 33 // Well formatted but not valid, 34 // missing closing square bracket. 35 invalidJson := `{ 36 "abc": { 37 "def": 123, 38 "xyz": [ 39 { 40 "a": "1" 41 } 42 } 43 } 44 }` 45 actual, err = NormalizeJsonString(invalidJson) 46 if err == nil { 47 t.Fatalf("Expected to throw an error while parsing JSON, but got: %s", err) 48 } 49 50 // We expect the invalid JSON to be shown back to us again. 51 if actual != invalidJson { 52 t.Fatalf("Got:\n\n%s\n\nExpected:\n\n%s\n", actual, invalidJson) 53 } 54 55 // Verify that it leaves strings alone 56 testString := "2016-07-28t04:07:02z\nsomething else" 57 expected = "2016-07-28t04:07:02z\nsomething else" 58 actual, err = NormalizeJsonString(testString) 59 if err == nil { 60 t.Fatalf("Expected to throw an error while parsing JSON, but got: %s", err) 61 } 62 63 if actual != expected { 64 t.Fatalf("Got:\n\n%s\n\nExpected:\n\n%s\n", actual, expected) 65 } 66 } 67 68 func TestNormalizeJsonString_invalid(t *testing.T) { 69 // Well formatted but not valid, 70 // missing closing squre bracket. 71 invalidJson := `{ 72 "abc": { 73 "def": 123, 74 "xyz": [ 75 { 76 "a": "1" 77 } 78 } 79 } 80 }` 81 expected := `{"abc":{"def":123,"xyz":[{"a":"ホリネズミ"},{"b":"1\\n2"}]}}` 82 actual, err := NormalizeJsonString(invalidJson) 83 if err == nil { 84 t.Fatalf("Expected to throw an error while parsing JSON, but got: %s", err) 85 } 86 87 // We expect the invalid JSON to be shown back to us again. 88 if actual != invalidJson { 89 t.Fatalf("Got:\n\n%s\n\nExpected:\n\n%s\n", expected, invalidJson) 90 } 91 }