Merge pull request #583 from Jimdo/fix_quoting_nonstring

Quote non-string Values
This commit is contained in:
Damien Mathieu 2017-07-12 18:14:13 +02:00 committed by GitHub
commit 3f40c78a45
2 changed files with 31 additions and 16 deletions

View File

@ -169,22 +169,15 @@ func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interf
} }
func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) { func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
switch value := value.(type) { stringVal, ok := value.(string)
case string: if !ok {
if !f.needsQuoting(value) { stringVal = fmt.Sprint(value)
b.WriteString(value)
} else {
b.WriteString(f.quoteString(value))
} }
case error:
errmsg := value.Error() if !f.needsQuoting(stringVal) {
if !f.needsQuoting(errmsg) { b.WriteString(stringVal)
b.WriteString(errmsg)
} else { } else {
b.WriteString(f.quoteString(errmsg)) b.WriteString(f.quoteString(stringVal))
}
default:
fmt.Fprint(b, value)
} }
} }

View File

@ -6,6 +6,7 @@ import (
"strings" "strings"
"testing" "testing"
"time" "time"
"fmt"
) )
func TestQuoting(t *testing.T) { func TestQuoting(t *testing.T) {
@ -83,6 +84,27 @@ func TestEscaping_DefaultQuoteCharacter(t *testing.T) {
} }
} }
func TestEscaping_Interface(t *testing.T) {
tf := &TextFormatter{DisableColors: true}
ts := time.Now()
testCases := []struct {
value interface{}
expected string
}{
{ts, fmt.Sprintf("\"%s\"", ts.String())},
{errors.New("error: something went wrong"), "\"error: something went wrong\""},
}
for _, tc := range testCases {
b, _ := tf.Format(WithField("test", tc.value))
if !bytes.Contains(b, []byte(tc.expected)) {
t.Errorf("escaping expected for %q (result was %q instead of %q)", tc.value, string(b), tc.expected)
}
}
}
func TestEscaping_CustomQuoteCharacter(t *testing.T) { func TestEscaping_CustomQuoteCharacter(t *testing.T) {
tf := &TextFormatter{DisableColors: true} tf := &TextFormatter{DisableColors: true}