...

Source file src/fmt/state_test.go

Documentation: fmt

     1  // Copyright 2022 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package fmt_test
     6  
     7  import (
     8  	"fmt"
     9  	"testing"
    10  )
    11  
    12  type testState struct {
    13  	width   int
    14  	widthOK bool
    15  	prec    int
    16  	precOK  bool
    17  	flag    map[int]bool
    18  }
    19  
    20  var _ fmt.State = testState{}
    21  
    22  func (s testState) Write(b []byte) (n int, err error) {
    23  	panic("unimplemented")
    24  }
    25  
    26  func (s testState) Width() (wid int, ok bool) {
    27  	return s.width, s.widthOK
    28  }
    29  
    30  func (s testState) Precision() (prec int, ok bool) {
    31  	return s.prec, s.precOK
    32  }
    33  
    34  func (s testState) Flag(c int) bool {
    35  	return s.flag[c]
    36  }
    37  
    38  const NO = -1000
    39  
    40  func mkState(w, p int, flags string) testState {
    41  	s := testState{}
    42  	if w != NO {
    43  		s.width = w
    44  		s.widthOK = true
    45  	}
    46  	if p != NO {
    47  		s.prec = p
    48  		s.precOK = true
    49  	}
    50  	s.flag = make(map[int]bool)
    51  	for _, c := range flags {
    52  		s.flag[int(c)] = true
    53  	}
    54  	return s
    55  }
    56  
    57  func TestFormatString(t *testing.T) {
    58  	var tests = []struct {
    59  		width, prec int
    60  		flags       string
    61  		result      string
    62  	}{
    63  		{NO, NO, "", "%x"},
    64  		{NO, 3, "", "%.3x"},
    65  		{3, NO, "", "%3x"},
    66  		{7, 3, "", "%7.3x"},
    67  		{NO, NO, " +-#0", "% +-#0x"},
    68  		{7, 3, "+", "%+7.3x"},
    69  		{7, -3, "-", "%-7.-3x"},
    70  		{7, 3, " ", "% 7.3x"},
    71  		{7, 3, "#", "%#7.3x"},
    72  		{7, 3, "0", "%07.3x"},
    73  	}
    74  	for _, test := range tests {
    75  		got := fmt.FormatString(mkState(test.width, test.prec, test.flags), 'x')
    76  		if got != test.result {
    77  			t.Errorf("%v: got %s", test, got)
    78  		}
    79  	}
    80  }
    81  

View as plain text