github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/log/level_test.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package log
     7  
     8  import (
     9  	"fmt"
    10  	"testing"
    11  
    12  	"github.com/gitbundle/modules/json"
    13  
    14  	"github.com/stretchr/testify/assert"
    15  )
    16  
    17  type testLevel struct {
    18  	Level Level `json:"level"`
    19  }
    20  
    21  func TestLevelMarshalUnmarshalJSON(t *testing.T) {
    22  	levelBytes, err := json.Marshal(testLevel{
    23  		Level: INFO,
    24  	})
    25  	assert.NoError(t, err)
    26  	assert.Equal(t, string(makeTestLevelBytes(INFO.String())), string(levelBytes))
    27  
    28  	var testLevel testLevel
    29  	err = json.Unmarshal(levelBytes, &testLevel)
    30  	assert.NoError(t, err)
    31  	assert.Equal(t, INFO, testLevel.Level)
    32  
    33  	err = json.Unmarshal(makeTestLevelBytes(`FOFOO`), &testLevel)
    34  	assert.NoError(t, err)
    35  	assert.Equal(t, INFO, testLevel.Level)
    36  
    37  	err = json.Unmarshal([]byte(fmt.Sprintf(`{"level":%d}`, 2)), &testLevel)
    38  	assert.NoError(t, err)
    39  	assert.Equal(t, INFO, testLevel.Level)
    40  
    41  	err = json.Unmarshal([]byte(fmt.Sprintf(`{"level":%d}`, 10012)), &testLevel)
    42  	assert.NoError(t, err)
    43  	assert.Equal(t, INFO, testLevel.Level)
    44  
    45  	err = json.Unmarshal([]byte(`{"level":{}}`), &testLevel)
    46  	assert.NoError(t, err)
    47  	assert.Equal(t, INFO, testLevel.Level)
    48  
    49  	assert.Equal(t, INFO.String(), Level(1001).String())
    50  
    51  	err = json.Unmarshal([]byte(`{"level":{}`), &testLevel.Level)
    52  	assert.Error(t, err)
    53  }
    54  
    55  func makeTestLevelBytes(level string) []byte {
    56  	return []byte(fmt.Sprintf(`{"level":"%s"}`, level))
    57  }