Debian Codegraph @

tablewriter_test.go

raw
1 package tablewriter
2
3 import (
4 "bytes"
5 "database/sql"
6 "errors"
7 "fmt"
8 "os"
9 "reflect"
10 "sync"
11 "testing"
12
13 "github.com/olekukonko/ll"
14 "github.com/olekukonko/tablewriter/pkg/twcache"
15 "github.com/olekukonko/tablewriter/tw"
16 )
17
18 // TestBuildPaddingLineContents tests the buildPaddingLineContents function with various configurations.
19 // It verifies padding line construction with different widths and merge states.
20 func TestBuildPaddingLineContents(t *testing.T) {
21 table := NewTable(os.Stdout)
22 widths := tw.NewMapper[int, int]()
23 widths.Set(0, 5)
24 widths.Set(1, 10)
25 merges := map[int]tw.MergeState{
26 1: {Horizontal: tw.MergeStateOption{Present: true, Start: false}},
27 }
28 t.Run("Basic Padding", func(t *testing.T) {
29 line := table.buildPaddingLineContents("-", widths, 2, nil)
30 expected := []string{"-----", "----------"}
31 if !reflect.DeepEqual(line, expected) {
32 t.Errorf("Expected %v, got %v", expected, line)
33 }
34 })
35 t.Run("With Merge", func(t *testing.T) {
36 line := table.buildPaddingLineContents("-", widths, 2, merges)
37 expected := []string{"-----", ""}
38 if !reflect.DeepEqual(line, expected) {
39 t.Errorf("Expected %v, got %v", expected, line)
40 }
41 })
42 t.Run("Zero Width", func(t *testing.T) {
43 widths.Set(0, 0)
44 line := table.buildPaddingLineContents("-", widths, 2, nil)
45 expected := []string{"", "----------"}
46 if !reflect.DeepEqual(line, expected) {
47 t.Errorf("Expected %v, got %v", expected, line)
48 }
49 })
50 }
51
52 // TestCalculateContentMaxWidth tests the calculateContentMaxWidth function in batch and streaming modes.
53 // It verifies width calculations with various constraints and padding settings.
54 func TestCalculateContentMaxWidth(t *testing.T) {
55 table := NewTable(os.Stdout)
56 config := tw.CellConfig{
57 Formatting: tw.CellFormatting{
58 AutoWrap: tw.WrapTruncate,
59 Alignment: tw.AlignLeft,
60 AutoFormat: tw.Off,
61 },
62 ColMaxWidths: tw.CellWidth{Global: 10},
63 Padding: tw.CellPadding{
64 Global: tw.Padding{Left: " ", Right: " "},
65 },
66 }
67 t.Run("Batch Mode with MaxWidth", func(t *testing.T) {
68 got := table.calculateContentMaxWidth(0, config, 1, 1, false, 1)
69 if got != 8 { // 10 - 1 (left) - 1 (right)
70 t.Errorf("Expected width 8, got %d", got)
71 }
72 })
73 t.Run("Streaming Mode", func(t *testing.T) {
74 table.streamWidths = map[int]int{0: 12}
75 table.config.Stream.Enable = true
76 table.hasPrinted = true
77 got := table.calculateContentMaxWidth(0, config, 1, 1, true, 1)
78 if got != 10 { // 12 - 1 (left) - 1 (right)
79 t.Errorf("Expected width 10, got %d", got)
80 }
81 })
82 t.Run("No Constraint in Batch", func(t *testing.T) {
83 config.ColMaxWidths.Global = 0
84 got := table.calculateContentMaxWidth(0, config, 1, 1, false, 1)
85 if got != 0 {
86 t.Errorf("Expected width 0, got %d", got)
87 }
88 })
89 }
90
91 // TestCallStringer tests the convertToStringer function with caching enabled and disabled.
92 // It verifies stringer invocation and cache behavior for custom types.
93 func TestCallStringer(t *testing.T) {
94 table := &Table{
95 logger: ll.New("test").Disable(),
96 stringer: func(s interface{}) []string { return []string{fmt.Sprintf("%v", s)} },
97 stringerCache: twcache.NewLRU[reflect.Type, reflect.Value](tw.DefaultCacheStringCapacity),
98 }
99 input := struct{ Name string }{Name: "test"}
100 cells, err := table.convertToStringer(input)
101 if err != nil {
102 t.Errorf("convertToStringer failed: %v", err)
103 }
104 if len(cells) != 1 || cells[0] != "{test}" {
105 t.Errorf("convertToStringer returned unexpected cells: %v", cells)
106 }
107
108 // Test cache hit
109 cells, err = table.convertToStringer(input)
110 if err != nil {
111 t.Errorf("convertToStringer failed on cache hit: %v", err)
112 }
113 if len(cells) != 1 || cells[0] != "{test}" {
114 t.Errorf("convertToStringer returned unexpected cells on cache hit: %v", cells)
115 }
116
117 // Test disabled cache
118 cells, err = table.convertToStringer(input)
119 if err != nil {
120 t.Errorf("convertToStringer failed without cache: %v", err)
121 }
122 if len(cells) != 1 || cells[0] != "{test}" {
123 t.Errorf("convertToStringer returned unexpected cells without cache: %v", cells)
124 }
125 }
126
127 // TestCallStringerConcurrent tests the convertToStringer function under concurrent access.
128 // It verifies thread-safety of the stringer cache with multiple goroutines.
129 func TestCallStringerConcurrent(t *testing.T) {
130 table := &Table{
131 logger: ll.New("test").Disable(),
132 stringer: func(s interface{}) []string { return []string{fmt.Sprintf("%v", s)} },
133 stringerCache: twcache.NewLRU[reflect.Type, reflect.Value](tw.DefaultCacheStringCapacity),
134 }
135 var wg sync.WaitGroup
136 for i := 0; i < 100; i++ {
137 wg.Add(1)
138 go func(i int) {
139 defer wg.Done()
140 input := struct{ ID int }{ID: i}
141 cells, err := table.convertToStringer(input)
142 if err != nil {
143 t.Errorf("convertToStringer failed for ID %d: %v", i, err)
144 }
145 expected := fmt.Sprintf("{%d}", i)
146 if len(cells) != 1 || cells[0] != expected {
147 t.Errorf("convertToStringer returned unexpected cells for ID %d: got %v, want [%s]", i, cells, expected)
148 }
149 }(i)
150 }
151 wg.Wait()
152 }
153
154 // TestCallbacks tests the CellCallbacks functionality with the hybrid configuration approach.
155 // It verifies callbacks are triggered during rendering using WithConfig, Configure, and ConfigBuilder.
156 func TestCallbacks(t *testing.T) {
157 tests := []struct {
158 name string
159 setup func(*Table) // How to configure the table
160 expectedGlob int // Expected global callback count
161 expectedCol0 int // Expected column 0 callback count
162 }{
163 // Test case: Using WithConfig Option
164 {
165 name: "WithConfig",
166 setup: func(t *Table) {
167 t.Header([]string{"Name", "Email", "Age"})
168 t.Append([]string{"Alice", "[email protected]", "25"})
169 },
170 expectedGlob: 1, // One header line
171 expectedCol0: 1, // One callback for column 0
172 },
173 // Test case: Using Configure method
174 {
175 name: "Configure",
176 setup: func(t *Table) {
177 t.Configure(func(cfg *Config) {
178 cfg.Header.Callbacks = tw.CellCallbacks{
179 Global: t.config.Header.Callbacks.Global, // Preserve from base
180 PerColumn: []func(){
181 t.config.Header.Callbacks.PerColumn[0], // Preserve column 0
182 nil,
183 nil,
184 },
185 }
186 })
187 t.Header([]string{"Name", "Email", "Age"})
188 t.Append([]string{"Bob", "[email protected]", "30"})
189 },
190 expectedGlob: 1,
191 expectedCol0: 1,
192 },
193 // Test case: Using ConfigBuilder
194 {
195 name: "ConfigBuilder",
196 setup: func(t *Table) {
197 config := NewConfigBuilder().
198 Header().
199 Build().
200 Build()
201 t.config = mergeConfig(t.config, config) // Apply builder config
202 t.Header([]string{"Name", "Email", "Age"})
203 t.Append([]string{"Charlie", "[email protected]", "35"})
204 },
205 expectedGlob: 1,
206 expectedCol0: 1,
207 },
208 }
209
210 for _, tt := range tests {
211 t.Run(tt.name, func(t *testing.T) {
212 var buf bytes.Buffer
213 globalCount := 0
214 col0Count := 0
215
216 // Base configuration with callbacks
217 baseConfig := Config{
218 Header: tw.CellConfig{
219 Callbacks: tw.CellCallbacks{
220 Global: func() { globalCount++ },
221 PerColumn: []func(){
222 func() { col0Count++ }, // Callback for column 0
223 nil,
224 nil,
225 },
226 },
227 },
228 }
229
230 // Create table with base config
231 table := NewTable(&buf, WithConfig(baseConfig))
232
233 // Apply test-specific setup
234 tt.setup(table)
235
236 // Render to trigger callbacks
237 table.Render()
238
239 // Verify callback counts
240 if globalCount != tt.expectedGlob {
241 t.Errorf("%s: Expected global callback to run %d time(s), got %d", tt.name, tt.expectedGlob, globalCount)
242 }
243 if col0Count != tt.expectedCol0 {
244 t.Errorf("%s: Expected column 0 callback to run %d time(s), got %d", tt.name, tt.expectedCol0, col0Count)
245 }
246 })
247 }
248 }
249
250 // TestConvertToString tests the convertToString function with various input types.
251 // It verifies correct string conversion for nil, strings, SQL null types, and errors.
252 func TestConvertToString(t *testing.T) {
253 table := &Table{logger: ll.New("test").Disable()}
254 tests := []struct {
255 input interface{}
256 expected string
257 }{
258 {nil, ""},
259 {"test", "test"},
260 {[]byte("bytes"), "bytes"},
261 {errors.New("err"), "err"},
262 {sql.NullString{String: "valid", Valid: true}, "valid"},
263 {sql.NullString{Valid: false}, ""},
264 // Add more cases
265 }
266 for _, tt := range tests {
267 result := table.convertToString(tt.input)
268 if tt.expected != result {
269 t.Errorf("ConvertToString: expected %v, got '%v'", tt.expected, result)
270 }
271 }
272 }
273
274 // TestEnsureStreamWidthsCalculated tests the ensureStreamWidthsCalculated function.
275 // It verifies stream width initialization in streaming mode with various inputs.
276 func TestEnsureStreamWidthsCalculated(t *testing.T) {
277 table := NewTable(os.Stdout, WithStreaming(tw.StreamConfig{Enable: true}))
278 sampleData := []string{"A", "B"}
279 config := tw.CellConfig{}
280 t.Run("Already Initialized", func(t *testing.T) {
281 table.streamWidths = tw.NewMapper[int, int]().Set(0, 5).Set(1, 5)
282 table.streamNumCols = 2
283 err := table.ensureStreamWidthsCalculated(sampleData, config)
284 if err != nil {
285 t.Errorf("Expected nil, got %v", err)
286 }
287 })
288 t.Run("Initialize New", func(t *testing.T) {
289 table.streamWidths = nil
290 table.streamNumCols = 0
291 err := table.ensureStreamWidthsCalculated(sampleData, config)
292 if err != nil {
293 t.Errorf("Expected nil, got %v", err)
294 }
295 if table.streamNumCols != 2 {
296 t.Errorf("Expected streamNumCols=2, got %d", table.streamNumCols)
297 }
298 if table.streamWidths.Len() < 2 {
299 t.Errorf("Expected at least 2 widths, got %d", table.streamWidths.Len())
300 }
301 })
302 t.Run("Zero Columns", func(t *testing.T) {
303 table.streamWidths = nil
304 table.streamNumCols = 0
305 err := table.ensureStreamWidthsCalculated([]string{}, config)
306 if err == nil || err.Error() != "failed to determine column count for streaming" {
307 t.Errorf("Expected error for zero columns, got %v", err)
308 }
309 })
310 }
311
312 // Helper to get a fresh default CellConfig for a section.
313 // This uses the defaultConfig() function from the tablewriter package.
314 func getTestSectionDefaultConfig(section string) tw.CellConfig {
315 fullDefaultCfg := defaultConfig()
316 switch section {
317 case "header":
318 return fullDefaultCfg.Header
319 case "row":
320 return fullDefaultCfg.Row
321 case "footer":
322 return fullDefaultCfg.Footer
323 default:
324 return fullDefaultCfg.Row
325 }
326 }
327
328 // TestMergeCellConfig comprehensively tests the mergeCellConfig function.
329 func TestMergeCellConfig(t *testing.T) {
330 tests := []struct {
331 name string
332 baseConfig func() tw.CellConfig
333 inputConfig tw.CellConfig
334 expectedConfig func() tw.CellConfig
335 }{
336 {
337 name: "EmptyInput_OnRowDefaultBase",
338 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") },
339 inputConfig: tw.CellConfig{},
340 expectedConfig: func() tw.CellConfig {
341 cfg := getTestSectionDefaultConfig("row")
342 // src.AutoFormat is 0 (Pending) from empty CellConfig.
343 // mergeCellConfig assigns src.AutoFormat to dst.AutoFormat.
344 cfg.Formatting.AutoFormat = tw.Pending // Should be 0
345 return cfg
346 },
347 },
348 {
349 name: "OverrideMergeModeNone_OnRowDefaultBase",
350 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") },
351 inputConfig: tw.CellConfig{
352 Merging: tw.CellMerging{Mode: tw.MergeNone},
353 },
354 expectedConfig: func() tw.CellConfig {
355 cfg := getTestSectionDefaultConfig("row")
356 cfg.Merging.Mode = tw.MergeNone
357 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
358 return cfg
359 },
360 },
361 {
362 name: "OverrideMergeModeVertical_OnRowDefaultBase",
363 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") },
364 inputConfig: tw.CellConfig{
365 Formatting: tw.CellFormatting{MergeMode: tw.MergeVertical},
366 },
367 expectedConfig: func() tw.CellConfig {
368 cfg := getTestSectionDefaultConfig("row")
369 cfg.Formatting.MergeMode = tw.MergeVertical
370 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
371 return cfg
372 },
373 },
374 {
375 name: "OverrideMergeModeHorizontal_OnRowDefaultBase",
376 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") },
377 inputConfig: tw.CellConfig{
378 Formatting: tw.CellFormatting{MergeMode: tw.MergeHorizontal},
379 },
380 expectedConfig: func() tw.CellConfig {
381 cfg := getTestSectionDefaultConfig("row")
382 cfg.Formatting.MergeMode = tw.MergeHorizontal
383 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
384 return cfg
385 },
386 },
387 {
388 name: "OverrideMergeModeBoth_OnRowDefaultBase",
389 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") },
390 inputConfig: tw.CellConfig{
391 Formatting: tw.CellFormatting{MergeMode: tw.MergeBoth},
392 },
393 expectedConfig: func() tw.CellConfig {
394 cfg := getTestSectionDefaultConfig("row")
395 cfg.Formatting.MergeMode = tw.MergeBoth
396 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
397 return cfg
398 },
399 },
400 {
401 name: "OverrideMergeModeHierarchical_OnRowDefaultBase",
402 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") },
403 inputConfig: tw.CellConfig{
404 Formatting: tw.CellFormatting{MergeMode: tw.MergeHierarchical},
405 },
406 expectedConfig: func() tw.CellConfig {
407 cfg := getTestSectionDefaultConfig("row")
408 cfg.Formatting.MergeMode = tw.MergeHierarchical
409 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
410 return cfg
411 },
412 },
413 {
414 name: "ConfigBuilderOutput_MergingIntoRowDefault",
415 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") }, // Base AutoFormat = tw.Off (-1)
416 inputConfig: NewConfigBuilder().
417 WithHeaderAlignment(tw.AlignCenter).
418 WithHeaderMergeMode(tw.MergeHorizontal).
419 Build().Header, // Src AutoFormat = tw.On (1) from defaultConfig().Header
420 expectedConfig: func() tw.CellConfig {
421 cfg := getTestSectionDefaultConfig("row")
422 cfg.Alignment.Global = tw.AlignCenter
423 cfg.Formatting.AutoWrap = tw.WrapTruncate // from defaultConfig().Header
424 cfg.Formatting.AutoFormat = tw.On // from src (Builder's Header)
425 cfg.Formatting.MergeMode = tw.MergeHorizontal
426 // Padding.Global is same in default row and header, so it's effectively overwritten by itself.
427 return cfg
428 },
429 },
430 {
431 name: "Row_EmptyInput_OnRowBase",
432 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") },
433 inputConfig: tw.CellConfig{},
434 expectedConfig: func() tw.CellConfig {
435 cfg := getTestSectionDefaultConfig("row")
436 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
437 return cfg
438 },
439 },
440 {
441 name: "Row_OverrideAlignment_OnRowBase",
442 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") },
443 inputConfig: tw.CellConfig{
444 Formatting: tw.CellFormatting{Alignment: tw.AlignCenter},
445 },
446 expectedConfig: func() tw.CellConfig {
447 cfg := getTestSectionDefaultConfig("row")
448 cfg.Formatting.Alignment = tw.AlignCenter
449 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
450 return cfg
451 },
452 },
453 {
454 name: "Row_OverrideColumnAligns_OnRowBase_WithSkip",
455 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") },
456 inputConfig: tw.CellConfig{
457 ColumnAligns: []tw.Align{tw.AlignRight, tw.Skip, tw.AlignLeft},
458 },
459 expectedConfig: func() tw.CellConfig {
460 cfg := getTestSectionDefaultConfig("row")
461 cfg.ColumnAligns = []tw.Align{tw.AlignRight, tw.Empty, tw.AlignLeft}
462 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
463 return cfg
464 },
465 },
466 {
467 name: "Row_OverrideAutoWrap_OnRowBase",
468 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") },
469 inputConfig: tw.CellConfig{
470 Formatting: tw.CellFormatting{AutoWrap: tw.WrapTruncate},
471 },
472 expectedConfig: func() tw.CellConfig {
473 cfg := getTestSectionDefaultConfig("row")
474 cfg.Formatting.AutoWrap = tw.WrapTruncate
475 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
476 return cfg
477 },
478 },
479 {
480 name: "Row_OverrideAutoFormat_InputOff_BaseOff",
481 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") }, // Base AutoFormat = tw.Off (-1)
482 inputConfig: tw.CellConfig{
483 Formatting: tw.CellFormatting{AutoFormat: tw.Off}, // Src AutoFormat = tw.Off (-1)
484 },
485 expectedConfig: func() tw.CellConfig {
486 cfg := getTestSectionDefaultConfig("row")
487 cfg.Formatting.AutoFormat = tw.Off // Expected -1
488 return cfg
489 },
490 },
491 {
492 name: "Row_OverrideAutoFormat_InputOn_BaseOff",
493 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") }, // Base AutoFormat = tw.Off (-1)
494 inputConfig: tw.CellConfig{
495 Formatting: tw.CellFormatting{AutoFormat: tw.On}, // Src AutoFormat = tw.On (1)
496 },
497 expectedConfig: func() tw.CellConfig {
498 cfg := getTestSectionDefaultConfig("row")
499 cfg.Formatting.AutoFormat = tw.On // Expected 1
500 return cfg
501 },
502 },
503 {
504 name: "Header_ConfigBuilderOutput_MergingIntoHeaderDefault",
505 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("header") }, // Base AutoFormat = tw.On (1)
506 inputConfig: NewConfigBuilder().
507 WithHeaderAlignment(tw.AlignCenter).
508 WithHeaderMergeMode(tw.MergeHorizontal).
509 Build().Header, // Src AutoFormat = tw.On (1)
510 expectedConfig: func() tw.CellConfig {
511 cfg := getTestSectionDefaultConfig("header")
512 cfg.Formatting.MergeMode = tw.MergeHorizontal
513 cfg.Formatting.AutoFormat = tw.On
514 return cfg
515 },
516 },
517 {
518 name: "OverrideColMaxWidthGlobal_OnRowDefault",
519 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") },
520 inputConfig: tw.CellConfig{
521 ColMaxWidths: tw.CellWidth{Global: 50},
522 },
523 expectedConfig: func() tw.CellConfig {
524 cfg := getTestSectionDefaultConfig("row")
525 cfg.ColMaxWidths.Global = 50
526 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
527 return cfg
528 },
529 },
530 {
531 name: "MergeColMaxWidthPerColumn_NewEntries_OnRowDefault",
532 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") },
533 inputConfig: tw.CellConfig{
534 ColMaxWidths: tw.CellWidth{PerColumn: map[int]int{0: 10, 2: 20}},
535 },
536 expectedConfig: func() tw.CellConfig {
537 cfg := getTestSectionDefaultConfig("row")
538 cfg.ColMaxWidths.PerColumn = map[int]int{0: 10, 2: 20}
539 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
540 return cfg
541 },
542 },
543 {
544 name: "MergeColMaxWidthPerColumn_OverwriteAndAdd_OnExisting",
545 baseConfig: func() tw.CellConfig {
546 cfg := getTestSectionDefaultConfig("row")
547 cfg.ColMaxWidths.PerColumn = map[int]int{0: 5, 1: 15}
548 return cfg
549 },
550 inputConfig: tw.CellConfig{
551 ColMaxWidths: tw.CellWidth{PerColumn: map[int]int{0: 10, 2: 20, 1: 0}},
552 },
553 expectedConfig: func() tw.CellConfig {
554 cfg := getTestSectionDefaultConfig("row")
555 cfg.ColMaxWidths.PerColumn = map[int]int{0: 10, 1: 15, 2: 20}
556 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
557 return cfg
558 },
559 },
560 {
561 name: "MergePaddingPerColumn_NewEntries_OnRowDefault",
562 baseConfig: func() tw.CellConfig { return getTestSectionDefaultConfig("row") },
563 inputConfig: tw.CellConfig{
564 Padding: tw.CellPadding{PerColumn: []tw.Padding{
565 {Left: "L0", Right: "R0"},
566 {},
567 {Left: "L2", Right: "R2"},
568 }},
569 },
570 expectedConfig: func() tw.CellConfig {
571 cfg := getTestSectionDefaultConfig("row")
572 cfg.Padding.PerColumn = []tw.Padding{
573 {Left: "L0", Right: "R0"},
574 {},
575 {Left: "L2", Right: "R2"},
576 }
577 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
578 return cfg
579 },
580 },
581 {
582 name: "MergePaddingPerColumn_OverwriteExtendAndPreserve_OnExisting",
583 baseConfig: func() tw.CellConfig {
584 cfg := getTestSectionDefaultConfig("row")
585 cfg.Padding.PerColumn = []tw.Padding{
586 {Left: "BASE_L0"}, {Left: "BASE_L1"}, {Left: "BASE_L2"},
587 }
588 return cfg
589 },
590 inputConfig: tw.CellConfig{
591 Padding: tw.CellPadding{PerColumn: []tw.Padding{
592 {Left: "SRC_L0"},
593 {},
594 }},
595 },
596 expectedConfig: func() tw.CellConfig {
597 cfg := getTestSectionDefaultConfig("row")
598 cfg.Padding.PerColumn = []tw.Padding{
599 {Left: "SRC_L0"}, {Left: "BASE_L1"}, {Left: "BASE_L2"},
600 }
601 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
602 return cfg
603 },
604 },
605 {
606 name: "MergeColumnAligns_SrcShorterThanDst_WithSkipAndEmpty",
607 baseConfig: func() tw.CellConfig {
608 cfg := getTestSectionDefaultConfig("row")
609 cfg.ColumnAligns = []tw.Align{tw.AlignCenter, tw.AlignRight, tw.AlignCenter}
610 return cfg
611 },
612 inputConfig: tw.CellConfig{
613 ColumnAligns: []tw.Align{tw.AlignLeft, tw.Skip},
614 },
615 expectedConfig: func() tw.CellConfig {
616 cfg := getTestSectionDefaultConfig("row")
617 cfg.ColumnAligns = []tw.Align{tw.AlignLeft, tw.AlignRight, tw.AlignCenter}
618 cfg.Formatting.AutoFormat = tw.Pending // src.AutoFormat is 0
619 return cfg
620 },
621 },
622 }
623
624 for _, tt := range tests {
625 t.Run(tt.name, func(t *testing.T) {
626 baseForTest := tt.baseConfig()
627 expected := tt.expectedConfig()
628
629 got := mergeCellConfig(baseForTest, tt.inputConfig)
630
631 // Use a more verbose comparison for Formatting if DeepEqual fails to pinpoint AutoFormat
632 if !reflect.DeepEqual(got.Formatting, expected.Formatting) {
633 if got.Formatting.Alignment != expected.Formatting.Alignment ||
634 got.Formatting.AutoWrap != expected.Formatting.AutoWrap ||
635 got.Formatting.MergeMode != expected.Formatting.MergeMode ||
636 got.Formatting.AutoFormat != expected.Formatting.AutoFormat { // Key comparison
637 t.Errorf("Formatting mismatch:\nexpected: Alignment:%v, AutoWrap:%d, MergeMode:%d, AutoFormat:%d (%s)\ngot: Alignment:%v, AutoWrap:%d, MergeMode:%d, AutoFormat:%d (%s)",
638 expected.Formatting.Alignment, expected.Formatting.AutoWrap, expected.Formatting.MergeMode, expected.Formatting.AutoFormat, expected.Formatting.AutoFormat.String(),
639 got.Formatting.Alignment, got.Formatting.AutoWrap, got.Formatting.MergeMode, got.Formatting.AutoFormat, got.Formatting.AutoFormat.String())
640 } else {
641 // Fallback if the above doesn't catch it (shouldn't happen for simple fields)
642 t.Errorf("Formatting mismatch (DeepEqual failed):\nexpected: %+v\ngot: %+v", expected.Formatting, got.Formatting)
643 }
644 }
645
646 if !reflect.DeepEqual(got.Padding.Global, expected.Padding.Global) {
647 t.Errorf("Padding.Global mismatch\nexpected: %+v\ngot: %+v", expected.Padding.Global, got.Padding.Global)
648 }
649 if !reflect.DeepEqual(got.Padding.PerColumn, expected.Padding.PerColumn) {
650 t.Errorf("Padding.PerColumn mismatch\nexpected: %#v\ngot: %#v", expected.Padding.PerColumn, got.Padding.PerColumn)
651 }
652 if !reflect.DeepEqual(got.ColMaxWidths.Global, expected.ColMaxWidths.Global) {
653 t.Errorf("ColMaxWidths.Global mismatch\nexpected: %d\ngot: %d", expected.ColMaxWidths.Global, got.ColMaxWidths.Global)
654 }
655 if !reflect.DeepEqual(got.ColMaxWidths.PerColumn, expected.ColMaxWidths.PerColumn) {
656 t.Errorf("ColMaxWidths.PerColumn mismatch\nexpected: %#v\ngot: %#v", expected.ColMaxWidths.PerColumn, got.ColMaxWidths.PerColumn)
657 }
658 if !reflect.DeepEqual(got.ColumnAligns, expected.ColumnAligns) {
659 t.Errorf("ColumnAligns mismatch\nexpected: %#v\ngot: %#v", expected.ColumnAligns, got.ColumnAligns)
660 }
661
662 if (got.Callbacks.Global == nil) != (expected.Callbacks.Global == nil) {
663 t.Errorf("Callbacks.Global nilness mismatch\nexpected nil: %t, got nil: %t",
664 expected.Callbacks.Global == nil, got.Callbacks.Global == nil)
665 }
666 if len(got.Callbacks.PerColumn) != len(expected.Callbacks.PerColumn) {
667 t.Errorf("Callbacks.PerColumn length mismatch\nexpected: %d, got: %d",
668 len(expected.Callbacks.PerColumn), len(got.Callbacks.PerColumn))
669 } else {
670 for i := range got.Callbacks.PerColumn {
671 if (got.Callbacks.PerColumn[i] == nil) != (expected.Callbacks.PerColumn[i] == nil) {
672 t.Errorf("Callbacks.PerColumn[%d] nilness mismatch\nexpected nil: %t, got nil: %t",
673 i, expected.Callbacks.PerColumn[i] == nil, got.Callbacks.PerColumn[i] == nil)
674 break
675 }
676 }
677 }
678 if (got.Filter.Global == nil) != (expected.Filter.Global == nil) {
679 t.Errorf("Filter.Global nilness mismatch\nexpected nil: %t, got nil: %t",
680 expected.Filter.Global == nil, got.Filter.Global == nil)
681 }
682 if len(got.Filter.PerColumn) != len(expected.Filter.PerColumn) {
683 t.Errorf("Filter.PerColumn length mismatch\nexpected: %d, got: %d",
684 len(expected.Filter.PerColumn), len(got.Filter.PerColumn))
685 } else {
686 for i := range got.Filter.PerColumn {
687 if (got.Filter.PerColumn[i] == nil) != (expected.Filter.PerColumn[i] == nil) {
688 t.Errorf("Filter.PerColumn[%d] nilness mismatch\nexpected nil: %t, got nil: %t",
689 i, expected.Filter.PerColumn[i] == nil, got.Filter.PerColumn[i] == nil)
690 break
691 }
692 }
693 }
694 })
695 }
696 }
697
698 func TestParseTwAlign(t *testing.T) {
699 tbl := NewTable(nil)
700 cases := map[string]tw.Align{
701 "center": tw.AlignCenter,
702 "CENTER": tw.AlignCenter,
703 "left": tw.AlignLeft,
704 "right": tw.AlignRight,
705 "": tw.AlignDefault,
706 "bogus": tw.AlignDefault,
707 }
708 for in, want := range cases {
709 if got := tbl.parseTwAlign(in); got != want {
710 t.Errorf("parseTwAlign(%q) = %v, want %v", in, got, want)
711 }
712 }
713 }
714
715 func TestParseTwState(t *testing.T) {
716 tbl := NewTable(nil)
717 cases := map[string]tw.State{
718 "true": tw.On,
719 "TRUE": tw.On,
720 "false": tw.Off,
721 "": tw.Off,
722 "bogus": tw.Off,
723 }
724 for in, want := range cases {
725 if got := tbl.parseTwState(in); got != want {
726 t.Errorf("parseTwState(%q) = %v, want %v", in, got, want)
727 }
728 }
729 }
730
731 func TestSetTwColumnAlignmentUnknownPositionIsNoop(t *testing.T) {
732 tbl := NewTable(nil)
733 tbl.setTwColumnAlignment(tw.Position("bogus"), 0, tw.AlignCenter)
734
735 if len(tbl.config.Header.Alignment.PerColumn) != 0 {
736 t.Errorf("Header.Alignment.PerColumn should be untouched, got %#v", tbl.config.Header.Alignment.PerColumn)
737 }
738 if len(tbl.config.Row.Alignment.PerColumn) != 0 {
739 t.Errorf("Row.Alignment.PerColumn should be untouched, got %#v", tbl.config.Row.Alignment.PerColumn)
740 }
741 if len(tbl.config.Footer.Alignment.PerColumn) != 0 {
742 t.Errorf("Footer.Alignment.PerColumn should be untouched, got %#v", tbl.config.Footer.Alignment.PerColumn)
743 }
744 }
745
746 func TestExtractFieldsAndValuesFromStruct_NilPointer(t *testing.T) {
747 tbl := NewTable(nil)
748 type S struct{ A string }
749
750 var nilPtr *S
751 headers, values := tbl.extractFieldsAndValuesFromStruct(nilPtr)
752 if headers != nil || values != nil {
753 t.Errorf("expected nil, nil for a nil pointer, got headers=%#v values=%#v", headers, values)
754 }
755 }
756
757 func TestExtractFieldsAndValuesFromStruct_NonStruct(t *testing.T) {
758 tbl := NewTable(nil)
759 headers, values := tbl.extractFieldsAndValuesFromStruct(42)
760 if headers != nil || values != nil {
761 t.Errorf("expected nil, nil for a non-struct input, got headers=%#v values=%#v", headers, values)
762 }
763 }
764
765 func TestTwTagBareKeyPartIsIgnored(t *testing.T) {
766 type Row struct {
767 Col string `tw:"bareword,name=Visible"`
768 }
769
770 tbl := NewTable(nil)
771 tbl.Configure(func(cfg *Config) {
772 cfg.Behavior.Structs.AutoHeader = tw.On
773 })
774
775 headers := tbl.extractHeadersFromStruct(Row{Col: "x"})
776 if len(headers) != 1 || headers[0] != "Visible" {
777 t.Errorf("expected a single header %q, got %#v", "Visible", headers)
778 }
779 }
780
781 func TestTwTagWrapAllModes(t *testing.T) {
782 type RowNone struct {
783 Col string `tw:"wrap=none"`
784 }
785 type RowNormal struct {
786 Col string `tw:"wrap=normal"`
787 }
788 type RowTruncate struct {
789 Col string `tw:"wrap=truncate"`
790 }
791 type RowBreak struct {
792 Col string `tw:"wrap=break"`
793 }
794
795 cases := []struct {
796 token string
797 row interface{}
798 want int
799 }{
800 {"none", RowNone{Col: "x"}, tw.WrapNone},
801 {"normal", RowNormal{Col: "x"}, tw.WrapNormal},
802 {"truncate", RowTruncate{Col: "x"}, tw.WrapTruncate},
803 {"break", RowBreak{Col: "x"}, tw.WrapBreak},
804 }
805
806 for _, c := range cases {
807 tbl := NewTable(nil)
808 tbl.Configure(func(cfg *Config) {
809 cfg.Behavior.Structs.AutoHeader = tw.On
810 })
811 tbl.extractFieldsAndValuesFromStruct(c.row)
812 if got := tbl.config.Row.Formatting.AutoWrap; got != c.want {
813 t.Errorf("wrap=%s: AutoWrap = %v, want %v", c.token, got, c.want)
814 }
815 }
816 }