github.com/microsoft/moc@v0.17.1/pkg/marshal/marshal_test.go (about)

     1  // Copyright (c) Microsoft Corporation.
     2  // Licensed under the Apache v2.0 license.
     3  package marshal
     4  
     5  import (
     6  	"os"
     7  	"testing"
     8  )
     9  
    10  type testStruct struct {
    11  	StringVal string
    12  	IntVal    int
    13  }
    14  
    15  var tmp *testStruct
    16  
    17  func init() {
    18  	tmp = &testStruct{
    19  		StringVal: "strVal",
    20  		IntVal:    134,
    21  	}
    22  	os.MkdirAll("/tmp/marshal", os.ModePerm)
    23  }
    24  
    25  func Test_ToJSON(t *testing.T) {
    26  	str, err := ToJSON(tmp)
    27  	if err != nil {
    28  		t.Errorf("Failed to Marshal to JSON")
    29  	}
    30  	t.Logf("%+v", str)
    31  }
    32  func Test_ToJSONFile(t *testing.T) {
    33  	err := ToJSONFile(tmp, "/tmp/marshal/tmp.json")
    34  	if err != nil {
    35  		t.Errorf("Failed to Marshal to JSON")
    36  	}
    37  }
    38  func Test_FromJSONFile(t *testing.T) {
    39  	newTmp := testStruct{}
    40  	err := FromJSONFile("/tmp/marshal/tmp.json", &newTmp)
    41  	if err != nil {
    42  		t.Errorf("Failed to Marshal to JSON")
    43  	}
    44  	t.Logf("%+v", newTmp)
    45  }
    46  
    47  func Test_FromJSON(t *testing.T) {
    48  	var result struct {
    49  		Value string `json:"value,omitempty"`
    50  		Data  int    `json:"Data,omitempty"`
    51  	}
    52  
    53  	err := FromJSON(`{"value": "test", "Data": 1234}`, &result)
    54  	if err != nil {
    55  		t.Errorf("Failed to Marshal from JSON - %v", err)
    56  	}
    57  	str, err := ToJSON(result)
    58  	t.Logf("%s", str)
    59  }
    60  func Test_ToYAML(t *testing.T) {
    61  	str, err := ToYAML(tmp)
    62  	if err != nil {
    63  		t.Errorf("Failed to Marshal to YAML")
    64  	}
    65  	t.Logf("%+v", str)
    66  
    67  }
    68  func Test_FromYAML(t *testing.T) {}
    69  
    70  func Test_ToYAMLFile(t *testing.T) {
    71  	err := ToYAMLFile(tmp, "/tmp/marshal/tmp.json")
    72  	if err != nil {
    73  		t.Errorf("Failed to Marshal to JSON")
    74  	}
    75  }
    76  func Test_FromYAMLFile(t *testing.T) {
    77  	newTmp := testStruct{}
    78  	err := FromYAMLFile("/tmp/marshal/tmp.json", &newTmp)
    79  	if err != nil {
    80  		t.Errorf("Failed to Marshal to JSON")
    81  	}
    82  	t.Logf("%+v", newTmp)
    83  }
    84  
    85  func Test_ToString(t *testing.T) {
    86  	str := ToString(tmp)
    87  	if len(str) == 0 {
    88  		t.Errorf("Failed to Marshal to String")
    89  	}
    90  	t.Logf("%+v", str)
    91  
    92  }
    93  
    94  func Test_Duplicate(t *testing.T) {
    95  	tmp1 := &testStruct{}
    96  	err := Duplicate(tmp, tmp1)
    97  	if err != nil {
    98  		t.Errorf("Failed to Duplicate struct ")
    99  	}
   100  	t.Logf("Src: [%s], Dst [%s]", ToString(tmp), ToString(tmp1))
   101  
   102  }