1package fileio23import (4 "context"5 "os"6 "path/filepath"7 "strings"8 "testing"910 "src.rest/cat/012/internal/sheet"11)1213// Formats without widths of their own fit their columns to the header14// and the rows below it, capped, and leave narrow columns at the15// default; read from a stream too.16func TestImportFitsWidths(t *testing.T) {17 long := strings.Repeat("x", 60)18 files := map[string]string{19 "t.csv": "Item,Qty,Note\nStapler with a long name,3," + long + "\n",20 "t.tsv": "Item\tQty\tNote\nStapler with a long name\t3\t" + long + "\n",21 "t.json": `[{"Item":"Stapler with a long name","Qty":3,"Note":"` + long + `"}]`,22 "t.nuon": `[[Item, Qty, Note]; ["Stapler with a long name", 3, "` + long + `"]]`,23 "t.jsonl": `{"Item":"Stapler with a long name","Qty":3,"Note":"` + long + `"}`,24 }25 check := func(t *testing.T, s *sheet.Sheet) {26 t.Helper()27 if got := s.ColWidth(0); got != len("Stapler with a long name")+2 {28 t.Errorf("Item is %d wide", got)29 }30 if got := s.ColWidth(1); got != sheet.DefaultWidth {31 t.Errorf("Qty is %d wide, want the default", got)32 }33 if got := s.ColWidth(2); got != 30 {34 t.Errorf("Note is %d wide, want the cap", got)35 }36 }37 dir := t.TempDir()38 for name, text := range files {39 t.Run(name, func(t *testing.T) {40 path := filepath.Join(dir, name)41 os.WriteFile(path, []byte(text), 0o600)42 r, err := Import(context.Background(), path, Options{})43 if err != nil {44 t.Fatal(err)45 }46 check(t, r.Sheet)47 r, err = ImportReader(context.Background(), "stdin", strings.NewReader(text), Options{})48 if err != nil {49 t.Fatal(err)50 }51 check(t, r.Sheet)52 })53 }54}5556// A format that keeps widths keeps them, and columns it leaves at the57// default stay there.58func TestImportKeepsFileWidths(t *testing.T) {59 s := sheet.New()60 s.Set(sheet.Addr{}, strings.Repeat("x", 40))61 path := filepath.Join(t.TempDir(), "t.xlsx")62 if _, err := Export(context.Background(), path, XLSX, SnapBook(s), ExportOptions{}); err != nil {63 t.Fatal(err)64 }65 r, err := Import(context.Background(), path, Options{})66 if err != nil {67 t.Fatal(err)68 }69 if got := r.Sheet.ColWidth(0); got != sheet.DefaultWidth {70 t.Errorf("A is %d wide, want the file's default", got)71 }72}