github.com/rawahars/moby@v24.0.4+incompatible/api/types/strslice/strslice_test.go (about) 1 package strslice // import "github.com/docker/docker/api/types/strslice" 2 3 import ( 4 "encoding/json" 5 "reflect" 6 "testing" 7 ) 8 9 func TestStrSliceMarshalJSON(t *testing.T) { 10 for _, testcase := range []struct { 11 input StrSlice 12 expected string 13 }{ 14 // MADNESS(stevvooe): No clue why nil would be "" but empty would be 15 // "null". Had to make a change here that may affect compatibility. 16 {input: nil, expected: "null"}, 17 {StrSlice{}, "[]"}, 18 {StrSlice{"/bin/sh", "-c", "echo"}, `["/bin/sh","-c","echo"]`}, 19 } { 20 data, err := json.Marshal(testcase.input) 21 if err != nil { 22 t.Fatal(err) 23 } 24 if string(data) != testcase.expected { 25 t.Fatalf("%#v: expected %v, got %v", testcase.input, testcase.expected, string(data)) 26 } 27 } 28 } 29 30 func TestStrSliceUnmarshalJSON(t *testing.T) { 31 parts := map[string][]string{ 32 "": {"default", "values"}, 33 "[]": {}, 34 `["/bin/sh","-c","echo"]`: {"/bin/sh", "-c", "echo"}, 35 } 36 for input, expected := range parts { 37 strs := StrSlice{"default", "values"} 38 if err := strs.UnmarshalJSON([]byte(input)); err != nil { 39 t.Fatal(err) 40 } 41 42 actualParts := []string(strs) 43 if !reflect.DeepEqual(actualParts, expected) { 44 t.Fatalf("%#v: expected %v, got %v", input, expected, actualParts) 45 } 46 } 47 } 48 49 func TestStrSliceUnmarshalString(t *testing.T) { 50 var e StrSlice 51 echo, err := json.Marshal("echo") 52 if err != nil { 53 t.Fatal(err) 54 } 55 if err := json.Unmarshal(echo, &e); err != nil { 56 t.Fatal(err) 57 } 58 59 if len(e) != 1 { 60 t.Fatalf("expected 1 element after unmarshal: %q", e) 61 } 62 63 if e[0] != "echo" { 64 t.Fatalf("expected `echo`, got: %q", e[0]) 65 } 66 } 67 68 func TestStrSliceUnmarshalSlice(t *testing.T) { 69 var e StrSlice 70 echo, err := json.Marshal([]string{"echo"}) 71 if err != nil { 72 t.Fatal(err) 73 } 74 if err := json.Unmarshal(echo, &e); err != nil { 75 t.Fatal(err) 76 } 77 78 if len(e) != 1 { 79 t.Fatalf("expected 1 element after unmarshal: %q", e) 80 } 81 82 if e[0] != "echo" { 83 t.Fatalf("expected `echo`, got: %q", e[0]) 84 } 85 }