| 1 |
package tests |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
"strconv" |
| 7 |
"testing" |
| 8 |
|
| 9 |
"github.com/olekukonko/tablewriter" |
| 10 |
"github.com/olekukonko/tablewriter/renderer" |
| 11 |
"github.com/olekukonko/tablewriter/tw" |
| 12 |
) |
| 13 |
|
| 14 |
// Employee represents a struct for employee data, simulating a database record. |
| 15 |
type Employee struct { |
| 16 |
ID int |
| 17 |
Name string |
| 18 |
Age int |
| 19 |
Department string |
| 20 |
Salary float64 |
| 21 |
} |
| 22 |
|
| 23 |
// dummyDatabase simulates a database with employee records. |
| 24 |
type dummyDatabase struct { |
| 25 |
records []Employee |
| 26 |
} |
| 27 |
|
| 28 |
// fetchEmployees simulates fetching data from a database. |
| 29 |
func (db *dummyDatabase) fetchEmployees() []Employee { |
| 30 |
return db.records |
| 31 |
} |
| 32 |
|
| 33 |
// employeeStringer converts an Employee struct to a slice of strings for table rendering. |
| 34 |
func employeeStringer(e interface{}) []string { |
| 35 |
emp, ok := e.(Employee) |
| 36 |
if !ok { |
| 37 |
return []string{"Error: Invalid type"} |
| 38 |
} |
| 39 |
return []string{ |
| 40 |
strconv.Itoa(emp.ID), |
| 41 |
emp.Name, |
| 42 |
strconv.Itoa(emp.Age), |
| 43 |
emp.Department, |
| 44 |
strconv.FormatFloat(emp.Salary, 'f', 2, 64), |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
// TestStructTableWithDB tests rendering a table from struct data fetched from a dummy database. |
| 49 |
func TestStructTableWithDB(t *testing.T) { |
| 50 |
// Initialize dummy database with sample data |
| 51 |
db := &dummyDatabase{ |
| 52 |
records: []Employee{ |
| 53 |
{ID: 1, Name: "Alice Smith", Age: 28, Department: "Engineering", Salary: 75000.50}, |
| 54 |
{ID: 2, Name: "Bob Johnson", Age: 34, Department: "Marketing", Salary: 62000.00}, |
| 55 |
{ID: 3, Name: "Charlie Brown", Age: 45, Department: "HR", Salary: 80000.75}, |
| 56 |
}, |
| 57 |
} |
| 58 |
|
| 59 |
// Configure table with custom settings |
| 60 |
config := tablewriter.Config{ |
| 61 |
Header: tw.CellConfig{ |
| 62 |
Formatting: tw.CellFormatting{ |
| 63 |
AutoFormat: tw.On, |
| 64 |
}, |
| 65 |
Alignment: tw.CellAlignment{Global: tw.AlignCenter}, |
| 66 |
}, |
| 67 |
Row: tw.CellConfig{ |
| 68 |
Alignment: tw.CellAlignment{Global: tw.AlignLeft}, |
| 69 |
}, |
| 70 |
Footer: tw.CellConfig{ |
| 71 |
Alignment: tw.CellAlignment{Global: tw.AlignRight}, |
| 72 |
}, |
| 73 |
} |
| 74 |
|
| 75 |
// Create table with buffer and custom renderer |
| 76 |
var buf bytes.Buffer |
| 77 |
table := tablewriter.NewTable(&buf, |
| 78 |
tablewriter.WithConfig(config), |
| 79 |
tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{ |
| 80 |
Symbols: tw.NewSymbols(tw.StyleRounded), // Use rounded Unicode style |
| 81 |
Settings: tw.Settings{ |
| 82 |
Separators: tw.Separators{ |
| 83 |
BetweenColumns: tw.On, |
| 84 |
BetweenRows: tw.Off, |
| 85 |
}, |
| 86 |
Lines: tw.Lines{ |
| 87 |
ShowHeaderLine: tw.On, |
| 88 |
}, |
| 89 |
}, |
| 90 |
})), |
| 91 |
tablewriter.WithStringer(employeeStringer), |
| 92 |
) |
| 93 |
|
| 94 |
// Set header |
| 95 |
table.Header([]string{"ID", "Name", "Age", "Department", "Salary"}) |
| 96 |
|
| 97 |
// Fetch data from "database" and append to table |
| 98 |
employees := db.fetchEmployees() |
| 99 |
for _, emp := range employees { |
| 100 |
if err := table.Append(emp); err != nil { |
| 101 |
t.Fatalf("Failed to append employee: %v", err) |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
// Add a footer with a total salary |
| 106 |
totalSalary := 0.0 |
| 107 |
for _, emp := range employees { |
| 108 |
totalSalary += emp.Salary |
| 109 |
} |
| 110 |
table.Footer([]string{"", "", "", "Total", fmt.Sprintf("%.2f", totalSalary)}) |
| 111 |
|
| 112 |
// Render the table |
| 113 |
if err := table.Render(); err != nil { |
| 114 |
t.Fatalf("Failed to render table: %v", err) |
| 115 |
} |
| 116 |
|
| 117 |
// Expected output |
| 118 |
expected := ` |
| 119 |
╭────┬───────────────┬─────┬─────────────┬───────────╮ |
| 120 |
│ ID │ NAME │ AGE │ DEPARTMENT │ SALARY │ |
| 121 |
├────┼───────────────┼─────┼─────────────┼───────────┤ |
| 122 |
│ 1 │ Alice Smith │ 28 │ Engineering │ 75000.50 │ |
| 123 |
│ 2 │ Bob Johnson │ 34 │ Marketing │ 62000.00 │ |
| 124 |
│ 3 │ Charlie Brown │ 45 │ HR │ 80000.75 │ |
| 125 |
├────┼───────────────┼─────┼─────────────┼───────────┤ |
| 126 |
│ │ │ │ Total │ 217001.25 │ |
| 127 |
╰────┴───────────────┴─────┴─────────────┴───────────╯ |
| 128 |
` |
| 129 |
|
| 130 |
// Visual check |
| 131 |
if !visualCheck(t, "StructTableWithDB", buf.String(), expected) { |
| 132 |
t.Log(table.Debug()) |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
func TestAutoHeaderScenarios(t *testing.T) { |
| 137 |
// Legacy/Standard Structs |
| 138 |
type Basic struct { |
| 139 |
Foo int |
| 140 |
Bar string |
| 141 |
baz bool // unexported |
| 142 |
} |
| 143 |
|
| 144 |
type WithTags struct { |
| 145 |
ID int `json:"id"` |
| 146 |
Name string `json:"name,omitempty"` |
| 147 |
Age int `json:"-"` |
| 148 |
City string `json:"location"` |
| 149 |
} |
| 150 |
|
| 151 |
type Omitted struct { |
| 152 |
SkipMe string `json:"-"` |
| 153 |
KeepMe string |
| 154 |
} |
| 155 |
|
| 156 |
type NoTags struct { |
| 157 |
Field1 string |
| 158 |
field2 int // unexported |
| 159 |
} |
| 160 |
|
| 161 |
type Embedded struct { |
| 162 |
WithTags |
| 163 |
Extra string |
| 164 |
} |
| 165 |
|
| 166 |
type PointerTest struct { |
| 167 |
Value string |
| 168 |
} |
| 169 |
|
| 170 |
// Alignment & Header Alignment Tests |
| 171 |
type TWAlign struct { |
| 172 |
LeftCol string `tw:"name=Left Col, align=left, header_align=center"` |
| 173 |
CenterCol string `tw:"name=Center Col, align=center, header_align=right"` |
| 174 |
RightCol string `tw:"name=Right Col, align=right, header_align=left"` |
| 175 |
} |
| 176 |
|
| 177 |
// Advanced Padding Tests |
| 178 |
type TWPadding struct { |
| 179 |
PadA string `tw:"name=Pad A, pad_left=>, pad_right=<"` |
| 180 |
PadB string `tw:"name=Pad B, pad_left=-, pad_right=-"` |
| 181 |
PadC string `tw:"name=Pad C, pad_left=, pad_right=*"` |
| 182 |
} |
| 183 |
|
| 184 |
// Per-Column Width Tests |
| 185 |
type TWPerColumnMaxWidth struct { |
| 186 |
Narrow string `tw:"name=Narrow, max_width=8, wrap=truncate"` |
| 187 |
Medium string `tw:"name=Medium, max_width=12, wrap=truncate"` |
| 188 |
Wide string `tw:"name=Wide, max_width=16, wrap=truncate"` |
| 189 |
} |
| 190 |
|
| 191 |
// Table-Wide Formatting Overrides |
| 192 |
type TWTableWideOverrides struct { |
| 193 |
Raw string `tw:"name=my_raw_header, auto_format=false"` |
| 194 |
Space string `tw:"name=Spaced, trim_space=false"` |
| 195 |
Tab string `tw:"name=Tabbed, trim_tab=false"` |
| 196 |
} |
| 197 |
|
| 198 |
// Tag Fallbacks & Composites |
| 199 |
type TWComposite struct { |
| 200 |
A string `json:"json_name" tw:"align=right"` |
| 201 |
B string `db:"db_name" tw:"-"` |
| 202 |
C string `json:"ignore_me" tw:"name=tw_name"` |
| 203 |
} |
| 204 |
|
| 205 |
tests := []struct { |
| 206 |
name string |
| 207 |
data interface{} |
| 208 |
enable bool |
| 209 |
preHeaders []string |
| 210 |
expected string |
| 211 |
}{ |
| 212 |
// Legacy Tests |
| 213 |
{ |
| 214 |
name: "BasicStruct", |
| 215 |
data: []Basic{{1, "test", true}, {2, "test2", false}}, |
| 216 |
enable: true, |
| 217 |
expected: ` |
| 218 |
┌─────┬───────┐ |
| 219 |
│ FOO │ BAR │ |
| 220 |
├─────┼───────┤ |
| 221 |
│ 1 │ test │ |
| 222 |
│ 2 │ test2 │ |
| 223 |
└─────┴───────┘ |
| 224 |
`, |
| 225 |
}, |
| 226 |
{ |
| 227 |
name: "WithTags", |
| 228 |
data: []WithTags{{1, "John", 30, "NY"}, {2, "", 0, "LA"}}, |
| 229 |
enable: true, |
| 230 |
expected: ` |
| 231 |
┌────┬──────┬──────────┐ |
| 232 |
│ ID │ NAME │ LOCATION │ |
| 233 |
├────┼──────┼──────────┤ |
| 234 |
│ 1 │ John │ NY │ |
| 235 |
│ 2 │ │ LA │ |
| 236 |
└────┴──────┴──────────┘ |
| 237 |
`, |
| 238 |
}, |
| 239 |
{ |
| 240 |
name: "OmittedFields", |
| 241 |
data: []Omitted{{"skip", "keep"}, {"skip2", "keep2"}}, |
| 242 |
enable: true, |
| 243 |
expected: ` |
| 244 |
┌────────┐ |
| 245 |
│ KEEPME │ |
| 246 |
├────────┤ |
| 247 |
│ keep │ |
| 248 |
│ keep2 │ |
| 249 |
└────────┘ |
| 250 |
`, |
| 251 |
}, |
| 252 |
{ |
| 253 |
name: "NoTags", |
| 254 |
data: []NoTags{{"val1", 42}, {"val2", 43}}, |
| 255 |
enable: true, |
| 256 |
expected: ` |
| 257 |
┌─────────┐ |
| 258 |
│ FIELD 1 │ |
| 259 |
├─────────┤ |
| 260 |
│ val1 │ |
| 261 |
│ val2 │ |
| 262 |
└─────────┘ |
| 263 |
`, |
| 264 |
}, |
| 265 |
{ |
| 266 |
name: "Embedded", |
| 267 |
data: []Embedded{{WithTags{1, "John", 30, "NY"}, "Extra"}, {WithTags{2, "Doe", 25, "LA"}, "Value"}}, |
| 268 |
enable: true, |
| 269 |
expected: ` |
| 270 |
┌────┬──────┬──────────┬───────┐ |
| 271 |
│ ID │ NAME │ LOCATION │ EXTRA │ |
| 272 |
├────┼──────┼──────────┼───────┤ |
| 273 |
│ 1 │ John │ NY │ Extra │ |
| 274 |
│ 2 │ Doe │ LA │ Value │ |
| 275 |
└────┴──────┴──────────┴───────┘ |
| 276 |
`, |
| 277 |
}, |
| 278 |
{ |
| 279 |
name: "PointerToStruct", |
| 280 |
data: []*PointerTest{{"Value1"}, {"Value2"}}, |
| 281 |
enable: true, |
| 282 |
expected: ` |
| 283 |
┌────────┐ |
| 284 |
│ VALUE │ |
| 285 |
├────────┤ |
| 286 |
│ Value1 │ |
| 287 |
│ Value2 │ |
| 288 |
└────────┘ |
| 289 |
`, |
| 290 |
}, |
| 291 |
{ |
| 292 |
name: "SliceOfPointers", |
| 293 |
data: []*WithTags{{1, "John", 30, "NY"}, {2, "Doe", 25, "LA"}}, |
| 294 |
enable: true, |
| 295 |
expected: ` |
| 296 |
┌────┬──────┬──────────┐ |
| 297 |
│ ID │ NAME │ LOCATION │ |
| 298 |
├────┼──────┼──────────┤ |
| 299 |
│ 1 │ John │ NY │ |
| 300 |
│ 2 │ Doe │ LA │ |
| 301 |
└────┴──────┴──────────┘ |
| 302 |
`, |
| 303 |
}, |
| 304 |
{ |
| 305 |
name: "NonStruct", |
| 306 |
data: [][]string{{"A", "B"}, {"C", "D"}}, |
| 307 |
enable: false, |
| 308 |
expected: ` |
| 309 |
┌───┬───┐ |
| 310 |
│ A │ B │ |
| 311 |
│ C │ D │ |
| 312 |
└───┴───┘ |
| 313 |
`, |
| 314 |
}, |
| 315 |
{ |
| 316 |
name: "EmptySlice", |
| 317 |
data: []WithTags{}, |
| 318 |
expected: ``, |
| 319 |
}, |
| 320 |
{ |
| 321 |
name: "enabled", |
| 322 |
data: []WithTags{{1, "John", 30, "NY"}}, |
| 323 |
enable: true, |
| 324 |
expected: ` |
| 325 |
┌────┬──────┬──────────┐ |
| 326 |
│ ID │ NAME │ LOCATION │ |
| 327 |
├────┼──────┼──────────┤ |
| 328 |
│ 1 │ John │ NY │ |
| 329 |
└────┴──────┴──────────┘ |
| 330 |
`, |
| 331 |
}, |
| 332 |
{ |
| 333 |
name: "Disabled", |
| 334 |
data: []WithTags{{1, "John", 30, "NY"}}, |
| 335 |
enable: false, |
| 336 |
expected: ` |
| 337 |
┌───┬──────┬────┐ |
| 338 |
│ 1 │ John │ NY │ |
| 339 |
└───┴──────┴────┘ |
| 340 |
`, |
| 341 |
}, |
| 342 |
{ |
| 343 |
name: "PreExistingHeaders", |
| 344 |
data: []WithTags{{1, "John", 30, "NY"}}, |
| 345 |
preHeaders: []string{"CustomID", "CustomName", "CustomCity"}, |
| 346 |
enable: true, |
| 347 |
expected: ` |
| 348 |
┌───────────┬─────────────┬─────────────┐ |
| 349 |
│ CUSTOM ID │ CUSTOM NAME │ CUSTOM CITY │ |
| 350 |
├───────────┼─────────────┼─────────────┤ |
| 351 |
│ 1 │ John │ NY │ |
| 352 |
└───────────┴─────────────┴─────────────┘ |
| 353 |
`, |
| 354 |
}, |
| 355 |
|
| 356 |
// New 'tw' Tag Features Tests |
| 357 |
|
| 358 |
{ |
| 359 |
name: "TW_Alignment_Independence", |
| 360 |
data: []TWAlign{{"A", "B", "C"}}, |
| 361 |
enable: true, |
| 362 |
expected: ` |
| 363 |
┌──────────┬────────────┬───────────┐ |
| 364 |
│ LEFT COL │ CENTER COL │ RIGHT COL │ |
| 365 |
├──────────┼────────────┼───────────┤ |
| 366 |
│ A │ B │ C │ |
| 367 |
└──────────┴────────────┴───────────┘ |
| 368 |
`, |
| 369 |
}, |
| 370 |
{ |
| 371 |
name: "TW_Advanced_Padding", |
| 372 |
data: []TWPadding{{"1", "2", "3"}}, |
| 373 |
enable: true, |
| 374 |
expected: ` |
| 375 |
┌───────┬───────┬──────┐ |
| 376 |
│>PAD A<│-PAD B-│PAD C*│ |
| 377 |
├───────┼───────┼──────┤ |
| 378 |
│>1<<<<<│-2-----│3*****│ |
| 379 |
└───────┴───────┴──────┘ |
| 380 |
`, |
| 381 |
}, |
| 382 |
{ |
| 383 |
name: "TW_Per_Column_Max_Width", |
| 384 |
data: []TWPerColumnMaxWidth{{"LongTextHere", "LongTextHere", "LongTextHere"}}, |
| 385 |
enable: true, |
| 386 |
expected: ` |
| 387 |
┌────────┬───────────┬──────────────┐ |
| 388 |
│ NARROW │ MEDIUM │ WIDE │ |
| 389 |
├────────┼───────────┼──────────────┤ |
| 390 |
│ Long… │ LongText… │ LongTextHere │ |
| 391 |
└────────┴───────────┴──────────────┘ |
| 392 |
`, |
| 393 |
}, |
| 394 |
{ |
| 395 |
name: "TW_Table_Wide_Formatting_Overrides", |
| 396 |
data: []TWTableWideOverrides{{"data", " spaced ", "\ttabbed\t"}}, |
| 397 |
enable: true, |
| 398 |
expected: ` |
| 399 |
┌───────────────┬────────────┬────────────────┐ |
| 400 |
│ my_raw_header │ Spaced │ Tabbed │ |
| 401 |
├───────────────┼────────────┼────────────────┤ |
| 402 |
│ data │ spaced │ tabbed │ |
| 403 |
└───────────────┴────────────┴────────────────┘ |
| 404 |
`, |
| 405 |
}, |
| 406 |
{ |
| 407 |
name: "TW_Tag_Fallback_And_Composites", |
| 408 |
data: []TWComposite{{"A", "B", "C"}}, |
| 409 |
enable: true, |
| 410 |
expected: ` |
| 411 |
┌───────────┬─────────┐ |
| 412 |
│ JSON NAME │ TW NAME │ |
| 413 |
├───────────┼─────────┤ |
| 414 |
│ A │ C │ |
| 415 |
└───────────┴─────────┘ |
| 416 |
`, |
| 417 |
}, |
| 418 |
} |
| 419 |
|
| 420 |
for _, tt := range tests { |
| 421 |
t.Run(tt.name, func(t *testing.T) { |
| 422 |
var buf bytes.Buffer |
| 423 |
table := tablewriter.NewTable(&buf) |
| 424 |
|
| 425 |
// Always enable auto header for these tests |
| 426 |
if tt.enable { |
| 427 |
table.Configure(func(cfg *tablewriter.Config) { |
| 428 |
cfg.Behavior.Structs.AutoHeader = tw.On |
| 429 |
}) |
| 430 |
} |
| 431 |
|
| 432 |
if len(tt.preHeaders) > 0 { |
| 433 |
table.Header(tt.preHeaders) |
| 434 |
} |
| 435 |
|
| 436 |
err := table.Bulk(tt.data) |
| 437 |
if err != nil { |
| 438 |
t.Fatalf("Bulk failed: %v", err) |
| 439 |
} |
| 440 |
table.Render() |
| 441 |
|
| 442 |
if !visualCheck(t, tt.name, buf.String(), tt.expected) { |
| 443 |
t.Logf("Failed visual check. Output generated:\n%s", buf.String()) |
| 444 |
} |
| 445 |
}) |
| 446 |
} |
| 447 |
} |
| 448 |
|
| 449 |
func TestTwTagMaxWidthAppliesOnFreshTable(t *testing.T) { |
| 450 |
type Row struct { |
| 451 |
Col string `tw:"max_width=5"` |
| 452 |
} |
| 453 |
|
| 454 |
var buf bytes.Buffer |
| 455 |
table := tablewriter.NewTable(&buf) |
| 456 |
table.Configure(func(cfg *tablewriter.Config) { |
| 457 |
cfg.Behavior.Structs.AutoHeader = tw.On |
| 458 |
}) |
| 459 |
|
| 460 |
if err := table.Bulk([]Row{{"abcdefgh"}}); err != nil { |
| 461 |
t.Fatalf("Bulk failed: %v", err) |
| 462 |
} |
| 463 |
|
| 464 |
cfg := table.Config() |
| 465 |
width, ok := cfg.Row.ColMaxWidths.PerColumn.OK(0) |
| 466 |
if !ok || width != 5 { |
| 467 |
t.Fatalf("expected Row.ColMaxWidths.PerColumn[0] == 5, got ok=%v width=%v (max_width tag did not apply)", ok, width) |
| 468 |
} |
| 469 |
} |
| 470 |
|
| 471 |
func TestTwTagSkipDoesNotLeakConfigToNextColumn(t *testing.T) { |
| 472 |
type Row struct { |
| 473 |
Hidden string `tw:"align=right,-"` |
| 474 |
Kept string |
| 475 |
} |
| 476 |
|
| 477 |
var buf bytes.Buffer |
| 478 |
table := tablewriter.NewTable(&buf) |
| 479 |
table.Configure(func(cfg *tablewriter.Config) { |
| 480 |
cfg.Behavior.Structs.AutoHeader = tw.On |
| 481 |
}) |
| 482 |
|
| 483 |
if err := table.Bulk([]Row{{"x", "y"}}); err != nil { |
| 484 |
t.Fatalf("Bulk failed: %v", err) |
| 485 |
} |
| 486 |
|
| 487 |
cfg := table.Config() |
| 488 |
for i, a := range cfg.Row.Alignment.PerColumn { |
| 489 |
if a == tw.AlignRight { |
| 490 |
t.Fatalf("column %d unexpectedly inherited the skipped field's right alignment: %#v", i, cfg.Row.Alignment.PerColumn) |
| 491 |
} |
| 492 |
} |
| 493 |
} |