Debian Codegraph @

funcr/funcr_test.go

raw
1 /*
2 Copyright 2021 The logr Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package funcr
18
19 import (
20 "encoding/json"
21 "fmt"
22 "path/filepath"
23 "reflect"
24 "runtime"
25 "testing"
26
27 "github.com/go-logr/logr"
28 )
29
30 // Will be handled via reflection instead of type assertions.
31 type substr string
32
33 func ptrint(i int) *int {
34 return &i
35 }
36 func ptrstr(s string) *string {
37 return &s
38 }
39
40 // point implements encoding.TextMarshaler and can be used as a map key.
41 type point struct{ x, y int }
42
43 func (p point) MarshalText() ([]byte, error) {
44 return []byte(fmt.Sprintf("(%d, %d)", p.x, p.y)), nil
45 }
46
47 // pointErr implements encoding.TextMarshaler but returns an error.
48 type pointErr struct{ x, y int }
49
50 func (p pointErr) MarshalText() ([]byte, error) {
51 return nil, fmt.Errorf("uh oh: %d, %d", p.x, p.y)
52 }
53
54 // Logging this should result in the MarshalLog() value.
55 type Tmarshaler struct{ val string }
56
57 func (t Tmarshaler) MarshalLog() any {
58 return struct{ Inner string }{"I am a logr.Marshaler"}
59 }
60
61 func (t Tmarshaler) String() string {
62 return "String(): you should not see this"
63 }
64
65 func (t Tmarshaler) Error() string {
66 return "Error(): you should not see this"
67 }
68
69 // Logging this should result in a panic.
70 type Tmarshalerpanic struct{ val string }
71
72 func (t Tmarshalerpanic) MarshalLog() any {
73 panic("Tmarshalerpanic")
74 }
75
76 // Logging this should result in the String() value.
77 type Tstringer struct{ val string }
78
79 func (t Tstringer) String() string {
80 return "I am a fmt.Stringer"
81 }
82
83 func (t Tstringer) Error() string {
84 return "Error(): you should not see this"
85 }
86
87 // Logging this should result in a panic.
88 type Tstringerpanic struct{ val string }
89
90 func (t Tstringerpanic) String() string {
91 panic("Tstringerpanic")
92 }
93
94 // Logging this should result in the Error() value.
95 type Terror struct{ val string }
96
97 func (t Terror) Error() string {
98 return "I am an error"
99 }
100
101 // Logging this should result in a panic.
102 type Terrorpanic struct{ val string }
103
104 func (t Terrorpanic) Error() string {
105 panic("Terrorpanic")
106 }
107
108 type TjsontagsString struct {
109 String0 string `json:"-"` // first field ignored
110 String1 string `json:"string1"` // renamed
111 String2 string `json:"-"` // ignored
112 // "'_'" is what staticcheck suggests:
113 // should encoding/json ignore this field or name it "-"? Either use `json:"-"` to ignore the field or use `json:"'-',"` to specify "-" as the name
114 // However, json.Marshal then uses "String3" as name, so this is a wrong suggestion?!
115 //
116 //nolint:staticcheck
117 String3 string `json:"-,"` // named "-"
118 String4 string `json:"string4,omitempty"` // renamed, ignore if empty
119 //nolint:staticcheck // SA5008: malformed `json` tag: invalid trailing ',' character
120 String5 string `json:","` // no-op
121 String6 string `json:",omitempty"` // ignore if empty
122 }
123
124 type TjsontagsBool struct {
125 Bool0 bool `json:"-"` // first field ignored
126 Bool1 bool `json:"bool1"` // renamed
127 Bool2 bool `json:"-"` // ignored
128 //nolint:staticcheck // SA5008: should encoding/json ignore this field or name it "-"? Either use `json:"-"` to ignore the field or use `json:"'-',"` to specify "-" as the name
129 Bool3 bool `json:"-,"` // named "-"
130 Bool4 bool `json:"bool4,omitempty"` // renamed, ignore if empty
131 //nolint:staticcheck // SA5008: malformed `json` tag: invalid trailing ',' character
132 Bool5 bool `json:","` // no-op
133 Bool6 bool `json:",omitempty"` // ignore if empty
134 }
135
136 type TjsontagsInt struct {
137 Int0 int `json:"-"` // first field ignored
138 Int1 int `json:"int1"` // renamed
139 Int2 int `json:"-"` // ignored
140 //nolint:staticcheck // SA5008: should encoding/json ignore this field or name it "-"? Either use `json:"-"` to ignore the field or use `json:"'-',"` to specify "-" as the name
141 Int3 int `json:"-,"` // named "-"
142 Int4 int `json:"int4,omitempty"` // renamed, ignore if empty
143 //nolint:staticcheck // SA5008: malformed `json` tag: invalid trailing ',' character
144 Int5 int `json:","` // no-op
145 Int6 int `json:",omitempty"` // ignore if empty
146 }
147
148 type TjsontagsUint struct {
149 Uint0 int `json:"-"` // first field ignored
150 Uint1 uint `json:"uint1"` // renamed
151 Uint2 uint `json:"-"` // ignored
152 //nolint:staticcheck // SA5008: should encoding/json ignore this field or name it "-"? Either use `json:"-"` to ignore the field or use `json:"'-',"` to specify "-" as the name
153 Uint3 uint `json:"-,"` // named "-"
154 Uint4 uint `json:"uint4,omitempty"` // renamed, ignore if empty
155 //nolint:staticcheck // SA5008: malformed `json` tag: invalid trailing ',' character
156 Uint5 uint `json:","` // no-op
157 Uint6 uint `json:",omitempty"` // ignore if empty
158 }
159
160 type TjsontagsFloat struct {
161 Float0 float64 `json:"-"` // first field ignored
162 Float1 float64 `json:"float1"` // renamed
163 Float2 float64 `json:"-"` // ignored
164 //nolint:staticcheck // SA5008: should encoding/json ignore this field or name it "-"? Either use `json:"-"` to ignore the field or use `json:"'-',"` to specify "-" as the name
165 Float3 float64 `json:"-,"` // named "-"
166 Float4 float64 `json:"float4,omitempty"` // renamed, ignore if empty
167 //nolint:staticcheck // SA5008: malformed `json` tag: invalid trailing ',' character
168 Float5 float64 `json:","` // no-op
169 Float6 float64 `json:",omitempty"` // ignore if empty
170 }
171
172 type TjsontagsComplex struct {
173 Complex0 complex128 `json:"-"` // first field ignored
174 Complex1 complex128 `json:"complex1"` // renamed
175 Complex2 complex128 `json:"-"` // ignored
176 //nolint:staticcheck // SA5008: should encoding/json ignore this field or name it "-"? Either use `json:"-"` to ignore the field or use `json:"'-',"` to specify "-" as the name
177 Complex3 complex128 `json:"-,"` // named "-"
178 Complex4 complex128 `json:"complex4,omitempty"` // renamed, ignore if empty
179 //nolint:staticcheck // SA5008: malformed `json` tag: invalid trailing ',' character
180 Complex5 complex128 `json:","` // no-op
181 Complex6 complex128 `json:",omitempty"` // ignore if empty
182 }
183
184 type TjsontagsPtr struct {
185 Ptr0 *string `json:"-"` // first field ignored
186 Ptr1 *string `json:"ptr1"` // renamed
187 Ptr2 *string `json:"-"` // ignored
188 //nolint:staticcheck // SA5008: should encoding/json ignore this field or name it "-"? Either use `json:"-"` to ignore the field or use `json:"'-',"` to specify "-" as the name
189 Ptr3 *string `json:"-,"` // named "-"
190 Ptr4 *string `json:"ptr4,omitempty"` // renamed, ignore if empty
191 //nolint:staticcheck // SA5008: malformed `json` tag: invalid trailing ',' character
192 Ptr5 *string `json:","` // no-op
193 Ptr6 *string `json:",omitempty"` // ignore if empty
194 }
195
196 type TjsontagsArray struct {
197 Array0 [2]string `json:"-"` // first field ignored
198 Array1 [2]string `json:"array1"` // renamed
199 Array2 [2]string `json:"-"` // ignored
200 //nolint:staticcheck // SA5008: should encoding/json ignore this field or name it "-"? Either use `json:"-"` to ignore the field or use `json:"'-',"` to specify "-" as the name
201 Array3 [2]string `json:"-,"` // named "-"
202 Array4 [2]string `json:"array4,omitempty"` // renamed, ignore if empty
203 //nolint:staticcheck // SA5008: malformed `json` tag: invalid trailing ',' character
204 Array5 [2]string `json:","` // no-op
205 Array6 [2]string `json:",omitempty"` // ignore if empty
206 }
207
208 type TjsontagsSlice struct {
209 Slice0 []string `json:"-"` // first field ignored
210 Slice1 []string `json:"slice1"` // renamed
211 Slice2 []string `json:"-"` // ignored
212 //nolint:staticcheck // SA5008: should encoding/json ignore this field or name it "-"? Either use `json:"-"` to ignore the field or use `json:"'-',"` to specify "-" as the name
213 Slice3 []string `json:"-,"` // named "-"
214 Slice4 []string `json:"slice4,omitempty"` // renamed, ignore if empty
215 //nolint:staticcheck // SA5008: malformed `json` tag: invalid trailing ',' character
216 Slice5 []string `json:","` // no-op
217 Slice6 []string `json:",omitempty"` // ignore if empty
218 }
219
220 type TjsontagsMap struct {
221 Map0 map[string]string `json:"-"` // first field ignored
222 Map1 map[string]string `json:"map1"` // renamed
223 Map2 map[string]string `json:"-"` // ignored
224 //nolint:staticcheck // SA5008: should encoding/json ignore this field or name it "-"? Either use `json:"-"` to ignore the field or use `json:"'-',"` to specify "-" as the name
225 Map3 map[string]string `json:"-,"` // named "-"
226 Map4 map[string]string `json:"map4,omitempty"` // renamed, ignore if empty
227 //nolint:staticcheck // SA5008: malformed `json` tag: invalid trailing ',' character
228 Map5 map[string]string `json:","` // no-op
229 Map6 map[string]string `json:",omitempty"` // ignore if empty
230 }
231
232 type Tinnerstruct struct {
233 Inner string
234 }
235 type Tinnerint int
236 type Tinnermap map[string]string
237 type Tinnerslice []string
238
239 type Tembedstruct struct {
240 Tinnerstruct
241 Outer string
242 }
243
244 type Tembednonstruct struct {
245 Tinnerint
246 Tinnermap
247 Tinnerslice
248 }
249
250 type Tinner1 Tinnerstruct
251 type Tinner2 Tinnerstruct
252 type Tinner3 Tinnerstruct
253 type Tinner4 Tinnerstruct
254 type Tinner5 Tinnerstruct
255 type Tinner6 Tinnerstruct
256
257 type Tembedjsontags struct {
258 Outer string
259 Tinner1 `json:"inner1"`
260 Tinner2 `json:"-"`
261 //nolint:staticcheck // SA5008: should encoding/json ignore this field or name it "-"? Either use `json:"-"` to ignore the field or use `json:"'-',"` to specify "-" as the name
262 Tinner3 `json:"-,"`
263 Tinner4 `json:"inner4,omitempty"`
264 //nolint:staticcheck // SA5008: malformed `json` tag: invalid trailing ',' character
265 Tinner5 `json:","`
266 Tinner6 `json:"inner6,omitempty"`
267 }
268
269 type Trawjson struct {
270 Message json.RawMessage `json:"message"`
271 }
272
273 type Trecursive struct {
274 Ptr *Trecursive `json:"ptr"`
275 }
276
277 // line returns the line number of the caller, if possible. This is useful in
278 // tests with a large number of cases - when something goes wrong you can find
279 // which case more easily.
280 func line() string {
281 _, _, line, ok := runtime.Caller(1)
282 var s string
283 if ok {
284 s = fmt.Sprintf("%d", line)
285 }
286 return s
287 }
288
289 func TestPretty(t *testing.T) {
290 // used below
291 newStr := func(s string) *string {
292 return &s
293 }
294
295 cases := []struct {
296 val any
297 exp string // used in cases where JSON can't handle it
298 line string
299 }{{
300 line: line(),
301 val: "strval",
302 }, {
303 line: line(),
304 val: "strval\nwith\t\"escapes\"",
305 }, {
306 line: line(),
307 val: substr("substrval"),
308 }, {
309 line: line(),
310 val: substr("substrval\nwith\t\"escapes\""),
311 }, {
312 line: line(),
313 val: true,
314 }, {
315 line: line(),
316 val: false,
317 }, {
318 line: line(),
319 val: int(93),
320 }, {
321 line: line(),
322 val: int8(93),
323 }, {
324 line: line(),
325 val: int16(93),
326 }, {
327 line: line(),
328 val: int32(93),
329 }, {
330 line: line(),
331 val: int64(93),
332 }, {
333 line: line(),
334 val: int(-93),
335 }, {
336 line: line(),
337 val: int8(-93),
338 }, {
339 line: line(),
340 val: int16(-93),
341 }, {
342 line: line(),
343 val: int32(-93),
344 }, {
345 line: line(),
346 val: int64(-93),
347 }, {
348 line: line(),
349 val: uint(93),
350 }, {
351 line: line(),
352 val: uint8(93),
353 }, {
354 line: line(),
355 val: uint16(93),
356 }, {
357 line: line(),
358 val: uint32(93),
359 }, {
360 line: line(),
361 val: uint64(93),
362 }, {
363 line: line(),
364 val: uintptr(93),
365 }, {
366 line: line(),
367 val: float32(93.76),
368 }, {
369 line: line(),
370 val: float64(93.76),
371 }, {
372 line: line(),
373 val: complex64(93i),
374 exp: `"(0+93i)"`,
375 }, {
376 line: line(),
377 val: complex128(93i),
378 exp: `"(0+93i)"`,
379 }, {
380 line: line(),
381 val: ptrint(93),
382 }, {
383 line: line(),
384 val: ptrstr("pstrval"),
385 }, {
386 line: line(),
387 val: []int{},
388 }, {
389 line: line(),
390 val: []int(nil),
391 exp: `[]`,
392 }, {
393 line: line(),
394 val: []int{9, 3, 7, 6},
395 }, {
396 line: line(),
397 val: []string{"str", "with\tescape"},
398 }, {
399 line: line(),
400 val: []substr{"substr", "with\tescape"},
401 }, {
402 line: line(),
403 val: [4]int{9, 3, 7, 6},
404 }, {
405 line: line(),
406 val: [2]string{"str", "with\tescape"},
407 }, {
408 line: line(),
409 val: [2]substr{"substr", "with\tescape"},
410 }, {
411 line: line(),
412 val: struct {
413 Int int
414 notExported string
415 String string
416 }{
417 93, "you should not see this", "seventy-six",
418 },
419 }, {
420 line: line(),
421 val: map[string]int{},
422 }, {
423 line: line(),
424 val: map[string]int(nil),
425 exp: `{}`,
426 }, {
427 line: line(),
428 val: map[string]int{
429 "nine": 3,
430 },
431 }, {
432 line: line(),
433 val: map[string]int{
434 "with\tescape": 76,
435 },
436 }, {
437 line: line(),
438 val: map[substr]int{
439 "nine": 3,
440 },
441 }, {
442 line: line(),
443 val: map[substr]int{
444 "with\tescape": 76,
445 },
446 }, {
447 line: line(),
448 val: map[int]int{
449 9: 3,
450 },
451 }, {
452 line: line(),
453 val: map[float64]int{
454 9.5: 3,
455 },
456 exp: `{"9.5":3}`,
457 }, {
458 line: line(),
459 val: map[point]int{
460 {x: 1, y: 2}: 3,
461 },
462 }, {
463 line: line(),
464 val: map[pointErr]int{
465 {x: 1, y: 2}: 3,
466 },
467 exp: `{"<error-MarshalText: uh oh: 1, 2>":3}`,
468 }, {
469 line: line(),
470 val: struct {
471 X int `json:"x"`
472 Y int `json:"y"`
473 }{
474 93, 76,
475 },
476 }, {
477 line: line(),
478 val: struct {
479 X []int
480 Y map[int]int
481 Z struct{ P, Q int }
482 }{
483 []int{9, 3, 7, 6},
484 map[int]int{9: 3},
485 struct{ P, Q int }{9, 3},
486 },
487 }, {
488 line: line(),
489 val: []struct{ X, Y string }{
490 {"nine", "three"},
491 {"seven", "six"},
492 {"with\t", "\tescapes"},
493 },
494 }, {
495 line: line(),
496 val: struct {
497 A *int
498 B *int
499 C any
500 D any
501 }{
502 B: ptrint(1),
503 D: any(2),
504 },
505 }, {
506 line: line(),
507 val: Tmarshaler{"foobar"},
508 exp: `{"Inner":"I am a logr.Marshaler"}`,
509 }, {
510 line: line(),
511 val: &Tmarshaler{"foobar"},
512 exp: `{"Inner":"I am a logr.Marshaler"}`,
513 }, {
514 line: line(),
515 val: (*Tmarshaler)(nil),
516 exp: `"<panic: value method github.com/go-logr/logr/funcr.Tmarshaler.MarshalLog called using nil *Tmarshaler pointer>"`,
517 }, {
518 line: line(),
519 val: Tmarshalerpanic{"foobar"},
520 exp: `"<panic: Tmarshalerpanic>"`,
521 }, {
522 line: line(),
523 val: Tstringer{"foobar"},
524 exp: `"I am a fmt.Stringer"`,
525 }, {
526 line: line(),
527 val: &Tstringer{"foobar"},
528 exp: `"I am a fmt.Stringer"`,
529 }, {
530 line: line(),
531 val: (*Tstringer)(nil),
532 exp: `"<panic: value method github.com/go-logr/logr/funcr.Tstringer.String called using nil *Tstringer pointer>"`,
533 }, {
534 line: line(),
535 val: Tstringerpanic{"foobar"},
536 exp: `"<panic: Tstringerpanic>"`,
537 }, {
538 line: line(),
539 val: Terror{"foobar"},
540 exp: `"I am an error"`,
541 }, {
542 line: line(),
543 val: &Terror{"foobar"},
544 exp: `"I am an error"`,
545 }, {
546 line: line(),
547 val: (*Terror)(nil),
548 exp: `"<panic: value method github.com/go-logr/logr/funcr.Terror.Error called using nil *Terror pointer>"`,
549 }, {
550 line: line(),
551 val: Terrorpanic{"foobar"},
552 exp: `"<panic: Terrorpanic>"`,
553 }, {
554 line: line(),
555 val: TjsontagsString{
556 String1: "v1",
557 String2: "v2",
558 String3: "v3",
559 String4: "v4",
560 String5: "v5",
561 String6: "v6",
562 },
563 }, {
564 line: line(),
565 val: TjsontagsString{},
566 }, {
567 line: line(),
568 val: TjsontagsBool{
569 Bool1: true,
570 Bool2: true,
571 Bool3: true,
572 Bool4: true,
573 Bool5: true,
574 Bool6: true,
575 },
576 }, {
577 line: line(),
578 val: TjsontagsBool{},
579 }, {
580 line: line(),
581 val: TjsontagsInt{
582 Int1: 1,
583 Int2: 2,
584 Int3: 3,
585 Int4: 4,
586 Int5: 5,
587 Int6: 6,
588 },
589 }, {
590 line: line(),
591 val: TjsontagsInt{},
592 }, {
593 line: line(),
594 val: TjsontagsUint{
595 Uint1: 1,
596 Uint2: 2,
597 Uint3: 3,
598 Uint4: 4,
599 Uint5: 5,
600 Uint6: 6,
601 },
602 }, {
603 line: line(),
604 val: TjsontagsUint{},
605 }, {
606 line: line(),
607 val: TjsontagsFloat{
608 Float1: 1.1,
609 Float2: 2.2,
610 Float3: 3.3,
611 Float4: 4.4,
612 Float5: 5.5,
613 Float6: 6.6,
614 },
615 }, {
616 line: line(),
617 val: TjsontagsFloat{},
618 }, {
619 line: line(),
620 val: TjsontagsComplex{
621 Complex1: 1i,
622 Complex2: 2i,
623 Complex3: 3i,
624 Complex4: 4i,
625 Complex5: 5i,
626 Complex6: 6i,
627 },
628 exp: `{"complex1":"(0+1i)","-":"(0+3i)","complex4":"(0+4i)","Complex5":"(0+5i)","Complex6":"(0+6i)"}`,
629 }, {
630 line: line(),
631 val: TjsontagsComplex{},
632 exp: `{"complex1":"(0+0i)","-":"(0+0i)","Complex5":"(0+0i)"}`,
633 }, {
634 line: line(),
635 val: TjsontagsPtr{
636 Ptr1: newStr("1"),
637 Ptr2: newStr("2"),
638 Ptr3: newStr("3"),
639 Ptr4: newStr("4"),
640 Ptr5: newStr("5"),
641 Ptr6: newStr("6"),
642 },
643 }, {
644 line: line(),
645 val: TjsontagsPtr{},
646 }, {
647 line: line(),
648 val: TjsontagsArray{
649 Array1: [2]string{"v1", "v1"},
650 Array2: [2]string{"v2", "v2"},
651 Array3: [2]string{"v3", "v3"},
652 Array4: [2]string{"v4", "v4"},
653 Array5: [2]string{"v5", "v5"},
654 Array6: [2]string{"v6", "v6"},
655 },
656 }, {
657 line: line(),
658 val: TjsontagsArray{},
659 }, {
660 line: line(),
661 val: TjsontagsSlice{
662 Slice1: []string{"v1", "v1"},
663 Slice2: []string{"v2", "v2"},
664 Slice3: []string{"v3", "v3"},
665 Slice4: []string{"v4", "v4"},
666 Slice5: []string{"v5", "v5"},
667 Slice6: []string{"v6", "v6"},
668 },
669 }, {
670 line: line(),
671 val: TjsontagsSlice{},
672 exp: `{"slice1":[],"-":[],"Slice5":[]}`,
673 }, {
674 line: line(),
675 val: TjsontagsMap{
676 Map1: map[string]string{"k1": "v1"},
677 Map2: map[string]string{"k2": "v2"},
678 Map3: map[string]string{"k3": "v3"},
679 Map4: map[string]string{"k4": "v4"},
680 Map5: map[string]string{"k5": "v5"},
681 Map6: map[string]string{"k6": "v6"},
682 },
683 }, {
684 line: line(),
685 val: TjsontagsMap{},
686 exp: `{"map1":{},"-":{},"Map5":{}}`,
687 }, {
688 line: line(),
689 val: Tembedstruct{},
690 }, {
691 line: line(),
692 val: Tembednonstruct{},
693 exp: `{"Tinnerint":0,"Tinnermap":{},"Tinnerslice":[]}`,
694 }, {
695 line: line(),
696 val: Tembedjsontags{},
697 }, {
698 line: line(),
699 val: PseudoStruct(makeKV("f1", 1, "f2", true, "f3", []int{})),
700 exp: `{"f1":1,"f2":true,"f3":[]}`,
701 }, {
702 line: line(),
703 val: map[TjsontagsString]int{
704 {String1: `"quoted"`, String4: `unquoted`}: 1,
705 },
706 exp: `{"{\"string1\":\"\\\"quoted\\\"\",\"-\":\"\",\"string4\":\"unquoted\",\"String5\":\"\"}":1}`,
707 }, {
708 line: line(),
709 val: map[TjsontagsInt]int{
710 {Int1: 1, Int2: 2}: 3,
711 },
712 exp: `{"{\"int1\":1,\"-\":0,\"Int5\":0}":3}`,
713 }, {
714 line: line(),
715 val: map[[2]struct{ S string }]int{
716 {{S: `"quoted"`}, {S: "unquoted"}}: 1,
717 },
718 exp: `{"[{\"S\":\"\\\"quoted\\\"\"},{\"S\":\"unquoted\"}]":1}`,
719 }, {
720 line: line(),
721 val: TjsontagsComplex{},
722 exp: `{"complex1":"(0+0i)","-":"(0+0i)","Complex5":"(0+0i)"}`,
723 }, {
724 line: line(),
725 val: TjsontagsPtr{
726 Ptr1: newStr("1"),
727 Ptr2: newStr("2"),
728 Ptr3: newStr("3"),
729 Ptr4: newStr("4"),
730 Ptr5: newStr("5"),
731 Ptr6: newStr("6"),
732 },
733 }, {
734 line: line(),
735 val: TjsontagsPtr{},
736 }, {
737 line: line(),
738 val: TjsontagsArray{
739 Array1: [2]string{"v1", "v1"},
740 Array2: [2]string{"v2", "v2"},
741 Array3: [2]string{"v3", "v3"},
742 Array4: [2]string{"v4", "v4"},
743 Array5: [2]string{"v5", "v5"},
744 Array6: [2]string{"v6", "v6"},
745 },
746 }, {
747 line: line(),
748 val: TjsontagsArray{},
749 }, {
750 line: line(),
751 val: TjsontagsSlice{
752 Slice1: []string{"v1", "v1"},
753 Slice2: []string{"v2", "v2"},
754 Slice3: []string{"v3", "v3"},
755 Slice4: []string{"v4", "v4"},
756 Slice5: []string{"v5", "v5"},
757 Slice6: []string{"v6", "v6"},
758 },
759 }, {
760 line: line(),
761 val: TjsontagsSlice{},
762 exp: `{"slice1":[],"-":[],"Slice5":[]}`,
763 }, {
764 line: line(),
765 val: TjsontagsMap{
766 Map1: map[string]string{"k1": "v1"},
767 Map2: map[string]string{"k2": "v2"},
768 Map3: map[string]string{"k3": "v3"},
769 Map4: map[string]string{"k4": "v4"},
770 Map5: map[string]string{"k5": "v5"},
771 Map6: map[string]string{"k6": "v6"},
772 },
773 }, {
774 line: line(),
775 val: TjsontagsMap{},
776 exp: `{"map1":{},"-":{},"Map5":{}}`,
777 }, {
778 line: line(),
779 val: Tembedstruct{},
780 }, {
781 line: line(),
782 val: Tembednonstruct{},
783 exp: `{"Tinnerint":0,"Tinnermap":{},"Tinnerslice":[]}`,
784 }, {
785 line: line(),
786 val: Tembedjsontags{},
787 }, {
788 line: line(),
789 val: PseudoStruct(makeKV("f1", 1, "f2", true, "f3", []int{})),
790 exp: `{"f1":1,"f2":true,"f3":[]}`,
791 }, {
792 line: line(),
793 val: map[TjsontagsString]int{
794 {String1: `"quoted"`, String4: `unquoted`}: 1,
795 },
796 exp: `{"{\"string1\":\"\\\"quoted\\\"\",\"-\":\"\",\"string4\":\"unquoted\",\"String5\":\"\"}":1}`,
797 }, {
798 line: line(),
799 val: map[TjsontagsInt]int{
800 {Int1: 1, Int2: 2}: 3,
801 },
802 exp: `{"{\"int1\":1,\"-\":0,\"Int5\":0}":3}`,
803 }, {
804 line: line(),
805 val: map[[2]struct{ S string }]int{
806 {{S: `"quoted"`}, {S: "unquoted"}}: 1,
807 },
808 exp: `{"[{\"S\":\"\\\"quoted\\\"\"},{\"S\":\"unquoted\"}]":1}`,
809 }, {
810 line: line(),
811 val: func() any {
812 v := &Trecursive{}
813 v.Ptr = v
814 return v
815 }(),
816 exp: `{"ptr":{"ptr":{"ptr":{"ptr":{"ptr":"<max-log-depth-exceeded>"}}}}}`,
817 }, {
818 line: line(),
819 val: func() any {
820 v := make([]any, 1)
821 v[0] = v
822 return v
823 }(),
824 exp: `[[[[["<max-log-depth-exceeded>"]]]]]`,
825 }, {
826 line: line(),
827 val: func() any {
828 type T []T
829 v := make(T, 1)
830 v[0] = v
831 return v
832 }(),
833 exp: `[[[[["<max-log-depth-exceeded>"]]]]]`,
834 }, {
835 line: line(),
836 val: func() any {
837 v := make(map[string]any)
838 v["v"] = v
839 return v
840 }(),
841 exp: `{"v":{"v":{"v":{"v":{"v":"<max-log-depth-exceeded>"}}}}}`,
842 }, {
843 line: line(),
844 val: func() any {
845 type T map[string]T
846 v := make(T)
847 v["v"] = v
848 return v
849 }(),
850 exp: `{"v":{"v":{"v":{"v":{"v":"<max-log-depth-exceeded>"}}}}}`,
851 }, {
852 line: line(),
853 val: func() any {
854 v := make(map[any]string)
855 k := &Trecursive{}
856 k.Ptr = k
857 v[k] = "v"
858 return v
859 }(),
860 exp: `{"{\"ptr\":{\"ptr\":{\"ptr\":{\"ptr\":{\"ptr\":\"<max-log-depth-exceeded>\"}}}}}":"v"}`,
861 }, {
862 line: line(),
863 val: func() any {
864 var v any
865 v = &v
866 return v
867 }(),
868 exp: `"<max-log-depth-exceeded>"`,
869 }, {
870 line: line(),
871 val: func() any {
872 type P *P
873 var a, b P
874 a, b = &b, &a
875 return a
876 }(),
877 exp: `"<max-log-depth-exceeded>"`,
878 }}
879
880 f := NewFormatterJSON(Options{MaxLogDepth: 4})
881 for i, tc := range cases {
882 ours := f.pretty(tc.val)
883 want := ""
884 if tc.line == "" {
885 t.Fatalf("testcase %d has no line number", i)
886 }
887 loc := "case @L" + tc.line
888 if tc.exp != "" {
889 want = tc.exp
890 } else {
891 jb, err := json.Marshal(tc.val)
892 if err != nil {
893 t.Fatalf("%s: unexpected error: %v\ngot: %q", loc, err, ours)
894 }
895 want = string(jb)
896 }
897 if ours != want {
898 t.Errorf("%s:\n\texpected %q\n\tgot %q", loc, want, ours)
899 }
900 }
901 }
902
903 func makeKV(args ...any) []any {
904 return args
905 }
906
907 func TestRender(t *testing.T) {
908 // used below
909 raw := &Trawjson{}
910 marshal := &TjsontagsInt{}
911 var err error
912 raw.Message, err = json.Marshal(marshal)
913 if err != nil {
914 t.Fatalf("json.Marshal error: %v", err)
915 }
916
917 testCases := []struct {
918 name string
919 builtins []any
920 values []any
921 args []any
922 expectKV string
923 expectJSON string
924 }{{
925 name: "nil",
926 expectKV: "",
927 expectJSON: "{}",
928 }, {
929 name: "empty",
930 builtins: []any{},
931 values: []any{},
932 args: []any{},
933 expectKV: "",
934 expectJSON: "{}",
935 }, {
936 name: "primitives",
937 builtins: makeKV("int1", 1, "int2", 2),
938 values: makeKV("str1", "ABC", "str2", "DEF"),
939 args: makeKV("bool1", true, "bool2", false),
940 expectKV: `"int1"=1 "int2"=2 "str1"="ABC" "str2"="DEF" "bool1"=true "bool2"=false`,
941 expectJSON: `{"int1":1,"int2":2,"str1":"ABC","str2":"DEF","bool1":true,"bool2":false}`,
942 }, {
943 name: "pseudo structs",
944 builtins: makeKV("int", PseudoStruct(makeKV("intsub", 1))),
945 values: makeKV("str", PseudoStruct(makeKV("strsub", "2"))),
946 args: makeKV("bool", PseudoStruct(makeKV("boolsub", true))),
947 expectKV: `"int"={"intsub"=1} "str"={"strsub"="2"} "bool"={"boolsub"=true}`,
948 expectJSON: `{"int":{"intsub":1},"str":{"strsub":"2"},"bool":{"boolsub":true}}`,
949 }, {
950 name: "escapes",
951 builtins: makeKV("\"1\"", 1), // will not be escaped, but should never happen
952 values: makeKV("\tstr", "ABC"), // escaped
953 args: makeKV("bool\n", true), // escaped
954 expectKV: `""1""=1 "\tstr"="ABC" "bool\n"=true`,
955 expectJSON: `{""1"":1,"\tstr":"ABC","bool\n":true}`,
956 }, {
957 name: "missing value",
958 builtins: makeKV("builtin"),
959 values: makeKV("value"),
960 args: makeKV("arg"),
961 expectKV: `"builtin"="<no-value>" "value"="<no-value>" "arg"="<no-value>"`,
962 expectJSON: `{"builtin":"<no-value>","value":"<no-value>","arg":"<no-value>"}`,
963 }, {
964 name: "non-string key int",
965 builtins: makeKV(123, "val"), // should never happen
966 values: makeKV(456, "val"),
967 args: makeKV(789, "val"),
968 expectKV: `"<non-string-key: 123>"="val" "<non-string-key: 456>"="val" "<non-string-key: 789>"="val"`,
969 expectJSON: `{"<non-string-key: 123>":"val","<non-string-key: 456>":"val","<non-string-key: 789>":"val"}`,
970 }, {
971 name: "non-string key struct",
972 builtins: makeKV(struct { // will not be escaped, but should never happen
973 F1 string
974 F2 int
975 }{"builtin", 123}, "val"),
976 values: makeKV(struct {
977 F1 string
978 F2 int
979 }{"value", 456}, "val"),
980 args: makeKV(struct {
981 F1 string
982 F2 int
983 }{"arg", 789}, "val"),
984 expectKV: `"<non-string-key: {"F1"="builtin" >"="val" "<non-string-key: {\"F1\"=\"value\" \"F>"="val" "<non-string-key: {\"F1\"=\"arg\" \"F2\">"="val"`,
985 expectJSON: `{"<non-string-key: {"F1":"builtin",>":"val","<non-string-key: {\"F1\":\"value\",\"F>":"val","<non-string-key: {\"F1\":\"arg\",\"F2\">":"val"}`,
986 }, {
987 name: "json rendering with json.RawMessage",
988 args: makeKV("key", raw),
989 expectKV: `"key"={"message"=[123 34 105 110 116 49 34 58 48 44 34 45 34 58 48 44 34 73 110 116 53 34 58 48 125]}`,
990 expectJSON: `{"key":{"message":{"int1":0,"-":0,"Int5":0}}}`,
991 }, {
992 name: "byte array not json.RawMessage",
993 args: makeKV("key", []byte{1, 2, 3, 4}),
994 expectKV: `"key"=[1 2 3 4]`,
995 expectJSON: `{"key":[1,2,3,4]}`,
996 }, {
997 name: "json rendering with empty json.RawMessage",
998 args: makeKV("key", &Trawjson{}),
999 expectKV: `"key"={"message"=[]}`,
1000 expectJSON: `{"key":{"message":null}}`,
1001 }}
1002
1003 for _, tc := range testCases {
1004 t.Run(tc.name, func(t *testing.T) {
1005 test := func(t *testing.T, formatter Formatter, expect string) {
1006 formatter.AddValues(tc.values)
1007 r := formatter.render(tc.builtins, tc.args)
1008 if r != expect {
1009 t.Errorf("wrong output:\nexpected %q\n got %q", expect, r)
1010 }
1011 }
1012 t.Run("KV", func(t *testing.T) {
1013 test(t, NewFormatter(Options{}), tc.expectKV)
1014 })
1015 t.Run("JSON", func(t *testing.T) {
1016 test(t, NewFormatterJSON(Options{}), tc.expectJSON)
1017 })
1018 })
1019 }
1020 }
1021
1022 func TestSanitize(t *testing.T) {
1023 testCases := []struct {
1024 name string
1025 kv []any
1026 expect []any
1027 }{{
1028 name: "empty",
1029 kv: []any{},
1030 expect: []any{},
1031 }, {
1032 name: "already sane",
1033 kv: makeKV("int", 1, "str", "ABC", "bool", true),
1034 expect: makeKV("int", 1, "str", "ABC", "bool", true),
1035 }, {
1036 name: "missing value",
1037 kv: makeKV("key"),
1038 expect: makeKV("key", "<no-value>"),
1039 }, {
1040 name: "non-string key int",
1041 kv: makeKV(123, "val"),
1042 expect: makeKV("<non-string-key: 123>", "val"),
1043 }, {
1044 name: "non-string key struct",
1045 kv: makeKV(struct {
1046 F1 string
1047 F2 int
1048 }{"f1", 8675309}, "val"),
1049 expect: makeKV(`<non-string-key: {"F1":"f1","F2":>`, "val"),
1050 }}
1051
1052 f := NewFormatterJSON(Options{})
1053 for _, tc := range testCases {
1054 t.Run(tc.name, func(t *testing.T) {
1055 r := f.sanitize(tc.kv)
1056 if !reflect.DeepEqual(r, tc.expect) {
1057 t.Errorf("wrong output:\nexpected %q\n got %q", tc.expect, r)
1058 }
1059 })
1060 }
1061 }
1062
1063 func TestEnabled(t *testing.T) {
1064 t.Run("default V", func(t *testing.T) {
1065 log := newSink(func(_, _ string) {}, NewFormatter(Options{}))
1066 if !log.Enabled(0) {
1067 t.Errorf("expected true")
1068 }
1069 if log.Enabled(1) {
1070 t.Errorf("expected false")
1071 }
1072 })
1073 t.Run("V=9", func(t *testing.T) {
1074 log := newSink(func(_, _ string) {}, NewFormatter(Options{Verbosity: 9}))
1075 if !log.Enabled(8) {
1076 t.Errorf("expected true")
1077 }
1078 if !log.Enabled(9) {
1079 t.Errorf("expected true")
1080 }
1081 if log.Enabled(10) {
1082 t.Errorf("expected false")
1083 }
1084 })
1085 }
1086
1087 type capture struct {
1088 log string
1089 }
1090
1091 func (c *capture) Func(prefix, args string) {
1092 space := " "
1093 if len(prefix) == 0 {
1094 space = ""
1095 }
1096 c.log = prefix + space + args
1097 }
1098
1099 func TestInfo(t *testing.T) {
1100 testCases := []struct {
1101 name string
1102 args []any
1103 expectKV string
1104 expectJSON string
1105 }{{
1106 name: "just msg",
1107 args: makeKV(),
1108 expectKV: `"level"=0 "msg"="msg"`,
1109 expectJSON: `{"logger":"","level":0,"msg":"msg"}`,
1110 }, {
1111 name: "primitives",
1112 args: makeKV("int", 1, "str", "ABC", "bool", true),
1113 expectKV: `"level"=0 "msg"="msg" "int"=1 "str"="ABC" "bool"=true`,
1114 expectJSON: `{"logger":"","level":0,"msg":"msg","int":1,"str":"ABC","bool":true}`,
1115 }}
1116
1117 for _, tc := range testCases {
1118 t.Run("KV: "+tc.name, func(t *testing.T) {
1119 capt := &capture{}
1120 sink := newSink(capt.Func, NewFormatter(Options{}))
1121 sink.Info(0, "msg", tc.args...)
1122 if capt.log != tc.expectKV {
1123 t.Errorf("\nexpected %q\n got %q", tc.expectKV, capt.log)
1124 }
1125 })
1126 t.Run("JSON: "+tc.name, func(t *testing.T) {
1127 capt := &capture{}
1128 sink := newSink(capt.Func, NewFormatterJSON(Options{}))
1129 sink.Info(0, "msg", tc.args...)
1130 if capt.log != tc.expectJSON {
1131 t.Errorf("\nexpected %q\n got %q", tc.expectJSON, capt.log)
1132 }
1133 })
1134 }
1135 }
1136
1137 func TestInfoWithCaller(t *testing.T) {
1138 t.Run("KV: LogCaller=All", func(t *testing.T) {
1139 capt := &capture{}
1140 sink := newSink(capt.Func, NewFormatter(Options{LogCaller: All}))
1141 sink.Info(0, "msg")
1142 _, file, line, _ := runtime.Caller(0)
1143 expect := fmt.Sprintf(`"caller"={"file"=%q "line"=%d} "level"=0 "msg"="msg"`, filepath.Base(file), line-1)
1144 if capt.log != expect {
1145 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1146 }
1147 sink.Error(fmt.Errorf("error"), "msg")
1148 _, file, line, _ = runtime.Caller(0)
1149 expect = fmt.Sprintf(`"caller"={"file"=%q "line"=%d} "msg"="msg" "error"="error"`, filepath.Base(file), line-1)
1150 if capt.log != expect {
1151 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1152 }
1153 })
1154 t.Run("JSON: LogCaller=All", func(t *testing.T) {
1155 capt := &capture{}
1156 sink := newSink(capt.Func, NewFormatterJSON(Options{LogCaller: All}))
1157 sink.Info(0, "msg")
1158 _, file, line, _ := runtime.Caller(0)
1159 expect := fmt.Sprintf(`{"logger":"","caller":{"file":%q,"line":%d},"level":0,"msg":"msg"}`, filepath.Base(file), line-1)
1160 if capt.log != expect {
1161 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1162 }
1163 sink.Error(fmt.Errorf("error"), "msg")
1164 _, file, line, _ = runtime.Caller(0)
1165 expect = fmt.Sprintf(`{"logger":"","caller":{"file":%q,"line":%d},"msg":"msg","error":"error"}`, filepath.Base(file), line-1)
1166 if capt.log != expect {
1167 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1168 }
1169 })
1170 t.Run("KV: LogCaller=All, LogCallerFunc=true", func(t *testing.T) {
1171 thisFunc := "github.com/go-logr/logr/funcr.TestInfoWithCaller.func3"
1172 capt := &capture{}
1173 sink := newSink(capt.Func, NewFormatter(Options{LogCaller: All, LogCallerFunc: true}))
1174 sink.Info(0, "msg")
1175 _, file, line, _ := runtime.Caller(0)
1176 expect := fmt.Sprintf(`"caller"={"file"=%q "line"=%d "function"=%q} "level"=0 "msg"="msg"`, filepath.Base(file), line-1, thisFunc)
1177 if capt.log != expect {
1178 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1179 }
1180 sink.Error(fmt.Errorf("error"), "msg")
1181 _, file, line, _ = runtime.Caller(0)
1182 expect = fmt.Sprintf(`"caller"={"file"=%q "line"=%d "function"=%q} "msg"="msg" "error"="error"`, filepath.Base(file), line-1, thisFunc)
1183 if capt.log != expect {
1184 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1185 }
1186 })
1187 t.Run("JSON: LogCaller=All, LogCallerFunc=true", func(t *testing.T) {
1188 thisFunc := "github.com/go-logr/logr/funcr.TestInfoWithCaller.func4"
1189 capt := &capture{}
1190 sink := newSink(capt.Func, NewFormatterJSON(Options{LogCaller: All, LogCallerFunc: true}))
1191 sink.Info(0, "msg")
1192 _, file, line, _ := runtime.Caller(0)
1193 expect := fmt.Sprintf(`{"logger":"","caller":{"file":%q,"line":%d,"function":%q},"level":0,"msg":"msg"}`, filepath.Base(file), line-1, thisFunc)
1194 if capt.log != expect {
1195 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1196 }
1197 sink.Error(fmt.Errorf("error"), "msg")
1198 _, file, line, _ = runtime.Caller(0)
1199 expect = fmt.Sprintf(`{"logger":"","caller":{"file":%q,"line":%d,"function":%q},"msg":"msg","error":"error"}`, filepath.Base(file), line-1, thisFunc)
1200 if capt.log != expect {
1201 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1202 }
1203 })
1204 t.Run("LogCaller=Info", func(t *testing.T) {
1205 capt := &capture{}
1206 sink := newSink(capt.Func, NewFormatter(Options{LogCaller: Info}))
1207 sink.Info(0, "msg")
1208 _, file, line, _ := runtime.Caller(0)
1209 expect := fmt.Sprintf(`"caller"={"file"=%q "line"=%d} "level"=0 "msg"="msg"`, filepath.Base(file), line-1)
1210 if capt.log != expect {
1211 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1212 }
1213 sink.Error(fmt.Errorf("error"), "msg")
1214 expect = `"msg"="msg" "error"="error"`
1215 if capt.log != expect {
1216 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1217 }
1218 })
1219 t.Run("LogCaller=Error", func(t *testing.T) {
1220 capt := &capture{}
1221 sink := newSink(capt.Func, NewFormatter(Options{LogCaller: Error}))
1222 sink.Info(0, "msg")
1223 expect := `"level"=0 "msg"="msg"`
1224 if capt.log != expect {
1225 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1226 }
1227 sink.Error(fmt.Errorf("error"), "msg")
1228 _, file, line, _ := runtime.Caller(0)
1229 expect = fmt.Sprintf(`"caller"={"file"=%q "line"=%d} "msg"="msg" "error"="error"`, filepath.Base(file), line-1)
1230 if capt.log != expect {
1231 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1232 }
1233 })
1234 t.Run("LogCaller=None", func(t *testing.T) {
1235 capt := &capture{}
1236 sink := newSink(capt.Func, NewFormatter(Options{LogCaller: None}))
1237 sink.Info(0, "msg")
1238 expect := `"level"=0 "msg"="msg"`
1239 if capt.log != expect {
1240 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1241 }
1242 sink.Error(fmt.Errorf("error"), "msg")
1243 expect = `"msg"="msg" "error"="error"`
1244 if capt.log != expect {
1245 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1246 }
1247 })
1248 }
1249
1250 func TestError(t *testing.T) {
1251 testCases := []struct {
1252 name string
1253 args []any
1254 expectKV string
1255 expectJSON string
1256 }{{
1257 name: "just msg",
1258 args: makeKV(),
1259 expectKV: `"msg"="msg" "error"="err"`,
1260 expectJSON: `{"logger":"","msg":"msg","error":"err"}`,
1261 }, {
1262 name: "primitives",
1263 args: makeKV("int", 1, "str", "ABC", "bool", true),
1264 expectKV: `"msg"="msg" "error"="err" "int"=1 "str"="ABC" "bool"=true`,
1265 expectJSON: `{"logger":"","msg":"msg","error":"err","int":1,"str":"ABC","bool":true}`,
1266 }}
1267
1268 for _, tc := range testCases {
1269 t.Run("KV: "+tc.name, func(t *testing.T) {
1270 capt := &capture{}
1271 sink := newSink(capt.Func, NewFormatter(Options{}))
1272 sink.Error(fmt.Errorf("err"), "msg", tc.args...)
1273 if capt.log != tc.expectKV {
1274 t.Errorf("\nexpected %q\n got %q", tc.expectKV, capt.log)
1275 }
1276 })
1277 t.Run("JSON: "+tc.name, func(t *testing.T) {
1278 capt := &capture{}
1279 sink := newSink(capt.Func, NewFormatterJSON(Options{}))
1280 sink.Error(fmt.Errorf("err"), "msg", tc.args...)
1281 if capt.log != tc.expectJSON {
1282 t.Errorf("\nexpected %q\n got %q", tc.expectJSON, capt.log)
1283 }
1284 })
1285 }
1286 }
1287
1288 func TestErrorWithCaller(t *testing.T) {
1289 t.Run("KV: LogCaller=All", func(t *testing.T) {
1290 capt := &capture{}
1291 sink := newSink(capt.Func, NewFormatter(Options{LogCaller: All}))
1292 sink.Error(fmt.Errorf("err"), "msg")
1293 _, file, line, _ := runtime.Caller(0)
1294 expect := fmt.Sprintf(`"caller"={"file"=%q "line"=%d} "msg"="msg" "error"="err"`, filepath.Base(file), line-1)
1295 if capt.log != expect {
1296 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1297 }
1298 })
1299 t.Run("JSON: LogCaller=All", func(t *testing.T) {
1300 capt := &capture{}
1301 sink := newSink(capt.Func, NewFormatterJSON(Options{LogCaller: All}))
1302 sink.Error(fmt.Errorf("err"), "msg")
1303 _, file, line, _ := runtime.Caller(0)
1304 expect := fmt.Sprintf(`{"logger":"","caller":{"file":%q,"line":%d},"msg":"msg","error":"err"}`, filepath.Base(file), line-1)
1305 if capt.log != expect {
1306 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1307 }
1308 })
1309 t.Run("LogCaller=Error", func(t *testing.T) {
1310 capt := &capture{}
1311 sink := newSink(capt.Func, NewFormatter(Options{LogCaller: Error}))
1312 sink.Error(fmt.Errorf("err"), "msg")
1313 _, file, line, _ := runtime.Caller(0)
1314 expect := fmt.Sprintf(`"caller"={"file"=%q "line"=%d} "msg"="msg" "error"="err"`, filepath.Base(file), line-1)
1315 if capt.log != expect {
1316 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1317 }
1318 })
1319 t.Run("LogCaller=Info", func(t *testing.T) {
1320 capt := &capture{}
1321 sink := newSink(capt.Func, NewFormatter(Options{LogCaller: Info}))
1322 sink.Error(fmt.Errorf("err"), "msg")
1323 expect := `"msg"="msg" "error"="err"`
1324 if capt.log != expect {
1325 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1326 }
1327 })
1328 t.Run("LogCaller=None", func(t *testing.T) {
1329 capt := &capture{}
1330 sink := newSink(capt.Func, NewFormatter(Options{LogCaller: None}))
1331 sink.Error(fmt.Errorf("err"), "msg")
1332 expect := `"msg"="msg" "error"="err"`
1333 if capt.log != expect {
1334 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1335 }
1336 })
1337 }
1338
1339 func TestInfoWithName(t *testing.T) {
1340 testCases := []struct {
1341 name string
1342 names []string
1343 args []any
1344 expectKV string
1345 expectJSON string
1346 }{{
1347 name: "one",
1348 names: []string{"pfx1"},
1349 args: makeKV("k", "v"),
1350 expectKV: `pfx1 "level"=0 "msg"="msg" "k"="v"`,
1351 expectJSON: `{"logger":"pfx1","level":0,"msg":"msg","k":"v"}`,
1352 }, {
1353 name: "two",
1354 names: []string{"pfx1", "pfx2"},
1355 args: makeKV("k", "v"),
1356 expectKV: `pfx1/pfx2 "level"=0 "msg"="msg" "k"="v"`,
1357 expectJSON: `{"logger":"pfx1/pfx2","level":0,"msg":"msg","k":"v"}`,
1358 }}
1359
1360 for _, tc := range testCases {
1361 t.Run("KV: "+tc.name, func(t *testing.T) {
1362 capt := &capture{}
1363 sink := newSink(capt.Func, NewFormatter(Options{}))
1364 for _, n := range tc.names {
1365 sink = sink.WithName(n)
1366 }
1367 sink.Info(0, "msg", tc.args...)
1368 if capt.log != tc.expectKV {
1369 t.Errorf("\nexpected %q\n got %q", tc.expectKV, capt.log)
1370 }
1371 })
1372 t.Run("JSON: "+tc.name, func(t *testing.T) {
1373 capt := &capture{}
1374 sink := newSink(capt.Func, NewFormatterJSON(Options{}))
1375 for _, n := range tc.names {
1376 sink = sink.WithName(n)
1377 }
1378 sink.Info(0, "msg", tc.args...)
1379 if capt.log != tc.expectJSON {
1380 t.Errorf("\nexpected %q\n got %q", tc.expectJSON, capt.log)
1381 }
1382 })
1383 }
1384 }
1385
1386 func TestErrorWithName(t *testing.T) {
1387 testCases := []struct {
1388 name string
1389 names []string
1390 args []any
1391 expectKV string
1392 expectJSON string
1393 }{{
1394 name: "one",
1395 names: []string{"pfx1"},
1396 args: makeKV("k", "v"),
1397 expectKV: `pfx1 "msg"="msg" "error"="err" "k"="v"`,
1398 expectJSON: `{"logger":"pfx1","msg":"msg","error":"err","k":"v"}`,
1399 }, {
1400 name: "two",
1401 names: []string{"pfx1", "pfx2"},
1402 args: makeKV("k", "v"),
1403 expectKV: `pfx1/pfx2 "msg"="msg" "error"="err" "k"="v"`,
1404 expectJSON: `{"logger":"pfx1/pfx2","msg":"msg","error":"err","k":"v"}`,
1405 }}
1406
1407 for _, tc := range testCases {
1408 t.Run("KV: "+tc.name, func(t *testing.T) {
1409 capt := &capture{}
1410 sink := newSink(capt.Func, NewFormatter(Options{}))
1411 for _, n := range tc.names {
1412 sink = sink.WithName(n)
1413 }
1414 sink.Error(fmt.Errorf("err"), "msg", tc.args...)
1415 if capt.log != tc.expectKV {
1416 t.Errorf("\nexpected %q\n got %q", tc.expectKV, capt.log)
1417 }
1418 })
1419 t.Run("JSON: "+tc.name, func(t *testing.T) {
1420 capt := &capture{}
1421 sink := newSink(capt.Func, NewFormatterJSON(Options{}))
1422 for _, n := range tc.names {
1423 sink = sink.WithName(n)
1424 }
1425 sink.Error(fmt.Errorf("err"), "msg", tc.args...)
1426 if capt.log != tc.expectJSON {
1427 t.Errorf("\nexpected %q\n got %q", tc.expectJSON, capt.log)
1428 }
1429 })
1430 }
1431 }
1432
1433 func TestInfoWithValues(t *testing.T) {
1434 testCases := []struct {
1435 name string
1436 values []any
1437 args []any
1438 expectKV string
1439 expectJSON string
1440 }{{
1441 name: "zero",
1442 values: makeKV(),
1443 args: makeKV("k", "v"),
1444 expectKV: `"level"=0 "msg"="msg" "k"="v"`,
1445 expectJSON: `{"logger":"","level":0,"msg":"msg","k":"v"}`,
1446 }, {
1447 name: "one",
1448 values: makeKV("one", 1),
1449 args: makeKV("k", "v"),
1450 expectKV: `"level"=0 "msg"="msg" "one"=1 "k"="v"`,
1451 expectJSON: `{"logger":"","level":0,"msg":"msg","one":1,"k":"v"}`,
1452 }, {
1453 name: "two",
1454 values: makeKV("one", 1, "two", 2),
1455 args: makeKV("k", "v"),
1456 expectKV: `"level"=0 "msg"="msg" "one"=1 "two"=2 "k"="v"`,
1457 expectJSON: `{"logger":"","level":0,"msg":"msg","one":1,"two":2,"k":"v"}`,
1458 }, {
1459 name: "dangling",
1460 values: makeKV("dangling"),
1461 args: makeKV("k", "v"),
1462 expectKV: `"level"=0 "msg"="msg" "dangling"="<no-value>" "k"="v"`,
1463 expectJSON: `{"logger":"","level":0,"msg":"msg","dangling":"<no-value>","k":"v"}`,
1464 }}
1465
1466 for _, tc := range testCases {
1467 t.Run("KV: "+tc.name, func(t *testing.T) {
1468 capt := &capture{}
1469 sink := newSink(capt.Func, NewFormatter(Options{}))
1470 sink = sink.WithValues(tc.values...)
1471 sink.Info(0, "msg", tc.args...)
1472 if capt.log != tc.expectKV {
1473 t.Errorf("\nexpected %q\n got %q", tc.expectKV, capt.log)
1474 }
1475 })
1476 t.Run("JSON: "+tc.name, func(t *testing.T) {
1477 capt := &capture{}
1478 sink := newSink(capt.Func, NewFormatterJSON(Options{}))
1479 sink = sink.WithValues(tc.values...)
1480 sink.Info(0, "msg", tc.args...)
1481 if capt.log != tc.expectJSON {
1482 t.Errorf("\nexpected %q\n got %q", tc.expectJSON, capt.log)
1483 }
1484 })
1485 }
1486 }
1487
1488 func TestErrorWithValues(t *testing.T) {
1489 testCases := []struct {
1490 name string
1491 values []any
1492 args []any
1493 expectKV string
1494 expectJSON string
1495 }{{
1496 name: "zero",
1497 values: makeKV(),
1498 args: makeKV("k", "v"),
1499 expectKV: `"msg"="msg" "error"="err" "k"="v"`,
1500 expectJSON: `{"logger":"","msg":"msg","error":"err","k":"v"}`,
1501 }, {
1502 name: "one",
1503 values: makeKV("one", 1),
1504 args: makeKV("k", "v"),
1505 expectKV: `"msg"="msg" "error"="err" "one"=1 "k"="v"`,
1506 expectJSON: `{"logger":"","msg":"msg","error":"err","one":1,"k":"v"}`,
1507 }, {
1508 name: "two",
1509 values: makeKV("one", 1, "two", 2),
1510 args: makeKV("k", "v"),
1511 expectKV: `"msg"="msg" "error"="err" "one"=1 "two"=2 "k"="v"`,
1512 expectJSON: `{"logger":"","msg":"msg","error":"err","one":1,"two":2,"k":"v"}`,
1513 }, {
1514 name: "dangling",
1515 values: makeKV("dangling"),
1516 args: makeKV("k", "v"),
1517 expectKV: `"msg"="msg" "error"="err" "dangling"="<no-value>" "k"="v"`,
1518 expectJSON: `{"logger":"","msg":"msg","error":"err","dangling":"<no-value>","k":"v"}`,
1519 }}
1520
1521 for _, tc := range testCases {
1522 t.Run("KV: "+tc.name, func(t *testing.T) {
1523 capt := &capture{}
1524 sink := newSink(capt.Func, NewFormatter(Options{}))
1525 sink = sink.WithValues(tc.values...)
1526 sink.Error(fmt.Errorf("err"), "msg", tc.args...)
1527 if capt.log != tc.expectKV {
1528 t.Errorf("\nexpected %q\n got %q", tc.expectKV, capt.log)
1529 }
1530 })
1531 t.Run("JSON: "+tc.name, func(t *testing.T) {
1532 capt := &capture{}
1533 sink := newSink(capt.Func, NewFormatterJSON(Options{}))
1534 sink = sink.WithValues(tc.values...)
1535 sink.Error(fmt.Errorf("err"), "msg", tc.args...)
1536 if capt.log != tc.expectJSON {
1537 t.Errorf("\nexpected %q\n got %q", tc.expectJSON, capt.log)
1538 }
1539 })
1540 }
1541 }
1542
1543 func TestInfoWithCallDepth(t *testing.T) {
1544 t.Run("one", func(t *testing.T) {
1545 capt := &capture{}
1546 sink := newSink(capt.Func, NewFormatter(Options{LogCaller: All}))
1547 dSink, _ := sink.(logr.CallDepthLogSink)
1548 sink = dSink.WithCallDepth(1)
1549 sink.Info(0, "msg")
1550 _, file, line, _ := runtime.Caller(1)
1551 expect := fmt.Sprintf(`"caller"={"file"=%q "line"=%d} "level"=0 "msg"="msg"`, filepath.Base(file), line)
1552 if capt.log != expect {
1553 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1554 }
1555 })
1556 }
1557
1558 func TestErrorWithCallDepth(t *testing.T) {
1559 t.Run("one", func(t *testing.T) {
1560 capt := &capture{}
1561 sink := newSink(capt.Func, NewFormatter(Options{LogCaller: All}))
1562 dSink, _ := sink.(logr.CallDepthLogSink)
1563 sink = dSink.WithCallDepth(1)
1564 sink.Error(fmt.Errorf("err"), "msg")
1565 _, file, line, _ := runtime.Caller(1)
1566 expect := fmt.Sprintf(`"caller"={"file"=%q "line"=%d} "msg"="msg" "error"="err"`, filepath.Base(file), line)
1567 if capt.log != expect {
1568 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1569 }
1570 })
1571 }
1572
1573 func TestOptionsTimestampFormat(t *testing.T) {
1574 capt := &capture{}
1575 // This timestamp format contains none of the characters that are
1576 // considered placeholders, so will produce a constant result.
1577 sink := newSink(capt.Func, NewFormatter(Options{LogTimestamp: true, TimestampFormat: "TIMESTAMP"}))
1578 dSink, _ := sink.(logr.CallDepthLogSink)
1579 sink = dSink.WithCallDepth(1)
1580 sink.Info(0, "msg")
1581 expect := `"ts"="TIMESTAMP" "level"=0 "msg"="msg"`
1582 if capt.log != expect {
1583 t.Errorf("\nexpected %q\n got %q", expect, capt.log)
1584 }
1585 }
1586
1587 func TestOptionsLogInfoLevel(t *testing.T) {
1588 testCases := []struct {
1589 name string
1590 level *string
1591 expect string
1592 }{
1593 {
1594 name: "custom key",
1595 level: ptrstr("info_level"),
1596 expect: `"info_level"=0 "msg"="msg"`,
1597 },
1598 {
1599 name: "no level",
1600 level: ptrstr(""),
1601 expect: `"msg"="msg"`,
1602 },
1603 {
1604 name: "default",
1605 level: nil,
1606 expect: `"level"=0 "msg"="msg"`,
1607 },
1608 }
1609
1610 for _, tc := range testCases {
1611 t.Run("Run: "+tc.name, func(t *testing.T) {
1612 capt := &capture{}
1613 sink := newSink(capt.Func, NewFormatter(Options{LogInfoLevel: tc.level}))
1614 dSink, _ := sink.(logr.CallDepthLogSink)
1615 sink = dSink.WithCallDepth(1)
1616 sink.Info(0, "msg")
1617 if capt.log != tc.expect {
1618 t.Errorf("\nexpected %q\n got %q", tc.expect, capt.log)
1619 }
1620 })
1621 }
1622 }