github.com/getong/docker@v1.13.1/api/types/strslice/strslice_test.go (about)

     1  package 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 json, expectedParts := range parts {
    37  		strs := StrSlice{"default", "values"}
    38  		if err := strs.UnmarshalJSON([]byte(json)); err != nil {
    39  			t.Fatal(err)
    40  		}
    41  
    42  		actualParts := []string(strs)
    43  		if !reflect.DeepEqual(actualParts, expectedParts) {
    44  			t.Fatalf("%#v: expected %v, got %v", json, expectedParts, actualParts)
    45  		}
    46  
    47  	}
    48  }
    49  
    50  func TestStrSliceUnmarshalString(t *testing.T) {
    51  	var e StrSlice
    52  	echo, err := json.Marshal("echo")
    53  	if err != nil {
    54  		t.Fatal(err)
    55  	}
    56  	if err := json.Unmarshal(echo, &e); err != nil {
    57  		t.Fatal(err)
    58  	}
    59  
    60  	if len(e) != 1 {
    61  		t.Fatalf("expected 1 element after unmarshal: %q", e)
    62  	}
    63  
    64  	if e[0] != "echo" {
    65  		t.Fatalf("expected `echo`, got: %q", e[0])
    66  	}
    67  }
    68  
    69  func TestStrSliceUnmarshalSlice(t *testing.T) {
    70  	var e StrSlice
    71  	echo, err := json.Marshal([]string{"echo"})
    72  	if err != nil {
    73  		t.Fatal(err)
    74  	}
    75  	if err := json.Unmarshal(echo, &e); err != nil {
    76  		t.Fatal(err)
    77  	}
    78  
    79  	if len(e) != 1 {
    80  		t.Fatalf("expected 1 element after unmarshal: %q", e)
    81  	}
    82  
    83  	if e[0] != "echo" {
    84  		t.Fatalf("expected `echo`, got: %q", e[0])
    85  	}
    86  }