gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/log/json_test.go (about)

     1  // Copyright 2018 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package log
    16  
    17  import (
    18  	"encoding/json"
    19  	"testing"
    20  )
    21  
    22  // Tests that Level can marshal/unmarshal properly.
    23  func TestLevelMarshal(t *testing.T) {
    24  	lvs := []Level{Warning, Info, Debug}
    25  	for _, lv := range lvs {
    26  		bs, err := lv.MarshalJSON()
    27  		if err != nil {
    28  			t.Errorf("error marshaling %v: %v", lv, err)
    29  		}
    30  		var lv2 Level
    31  		if err := lv2.UnmarshalJSON(bs); err != nil {
    32  			t.Errorf("error unmarshaling %v: %v", bs, err)
    33  		}
    34  		if lv != lv2 {
    35  			t.Errorf("marshal/unmarshal level got %v wanted %v", lv2, lv)
    36  		}
    37  	}
    38  }
    39  
    40  // Test that integers can be properly unmarshaled.
    41  func TestUnmarshalFromInt(t *testing.T) {
    42  	tcs := []struct {
    43  		i    int
    44  		want Level
    45  	}{
    46  		{0, Warning},
    47  		{1, Info},
    48  		{2, Debug},
    49  	}
    50  
    51  	for _, tc := range tcs {
    52  		j, err := json.Marshal(tc.i)
    53  		if err != nil {
    54  			t.Errorf("error marshaling %v: %v", tc.i, err)
    55  		}
    56  		var lv Level
    57  		if err := lv.UnmarshalJSON(j); err != nil {
    58  			t.Errorf("error unmarshaling %v: %v", j, err)
    59  		}
    60  		if lv != tc.want {
    61  			t.Errorf("marshal/unmarshal %v got %v want %v", tc.i, lv, tc.want)
    62  		}
    63  	}
    64  }