github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/encoding/json/duration_test.go (about)

     1  package json
     2  
     3  import (
     4  	"encoding/json"
     5  	"strconv"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  func TestUnmarshalDuration(t *testing.T) {
    11  	successCases := []string{
    12  		`1000`, // this is an "integer"
    13  		`"1000ms"`,
    14  		`"1000000000ns"`,
    15  		`"1s"`,
    16  	}
    17  
    18  	for _, c := range successCases {
    19  		var dur Duration
    20  		err := json.Unmarshal([]byte(c), &dur)
    21  		if err != nil {
    22  			t.Errorf("unexpected error %v", err)
    23  		}
    24  
    25  		var want float64 = 1 // all of our inputs equal 1 second
    26  		if got := dur.Seconds(); got != want {
    27  			t.Errorf("Duration.UnmarshalJSON(%q) = %f want %f", c, got, want)
    28  		}
    29  	}
    30  
    31  	negativeCases := []string{
    32  		`-1000`,
    33  		`"-1000ms"`,
    34  	}
    35  
    36  	for _, c := range negativeCases {
    37  		var dur Duration
    38  		wantErr := "invalid json.Duration: Duration cannot be less than 0"
    39  		err := json.Unmarshal([]byte(c), &dur)
    40  		if err.Error() != wantErr {
    41  			t.Errorf("wanted error %s, got %s", wantErr, err)
    42  		}
    43  	}
    44  
    45  	// Null case
    46  	var dur Duration
    47  	err := json.Unmarshal([]byte("null"), &dur)
    48  	if err != nil {
    49  		t.Errorf("unexpected error %v", err)
    50  	}
    51  
    52  	if dur.Duration != 0 {
    53  		t.Errorf(`Duration.UnmarshalJSON("null") = %v want 0`, dur.Duration)
    54  	}
    55  }
    56  
    57  func TestMarshalDuration(t *testing.T) {
    58  	dur := Duration{
    59  		Duration: time.Second,
    60  	}
    61  	b, err := json.Marshal(dur)
    62  	if err != nil {
    63  		t.Errorf("unexpected error %v", err)
    64  	}
    65  
    66  	got, err := strconv.Atoi(string(b))
    67  	if err != nil {
    68  		t.Fatal(err)
    69  	}
    70  	want := 1000
    71  	if got != want {
    72  		t.Errorf("wanted %d, got %d", want, got)
    73  	}
    74  }