// Package fixtures manages the real product pages the plugin tests run on. // // Which pages to use is tracked, in testdata//cases.toml. The pages // themselves change over time and may contain personal data, so they are // not tracked: `dibs fixtures` fetches them into testdata//pages/, // next to the report dibs produced for each. The tests then check that the // plugin still reads every saved page the same way. package fixtures import ( "bytes" "encoding/json" "fmt" "os" "path/filepath" "regexp" "github.com/pelletier/go-toml/v2" ) // Case is one page to test with. type Case struct { Name string `toml:"name"` URL string `toml:"url"` // Note says what the page is for, e.g. "only a used offer". Note string `toml:"note"` } // Suite is the cases of one shop. type Suite struct { // Shop is the plugin to use, named after the directory. Shop string Dir string Cases []Case } var nameRe = regexp.MustCompile(`^[a-z0-9-]+$`) // Load reads every dir//cases.toml. func Load(dir string) ([]Suite, error) { files, err := filepath.Glob(filepath.Join(dir, "*", "cases.toml")) if err != nil { return nil, err } var suites []Suite for _, f := range files { data, err := os.ReadFile(f) if err != nil { return nil, err } var doc struct { Cases []Case `toml:"case"` } dec := toml.NewDecoder(bytes.NewReader(data)) dec.DisallowUnknownFields() if err := dec.Decode(&doc); err != nil { return nil, fmt.Errorf("%s: %w", f, err) } seen := map[string]bool{} for _, c := range doc.Cases { switch { case !nameRe.MatchString(c.Name): return nil, fmt.Errorf("%s: case name %q must contain only a-z, 0-9 and -", f, c.Name) case seen[c.Name]: return nil, fmt.Errorf("%s: duplicate case %q", f, c.Name) case c.URL == "": return nil, fmt.Errorf("%s: case %q has no url", f, c.Name) } seen[c.Name] = true } suiteDir := filepath.Dir(f) suites = append(suites, Suite{Shop: filepath.Base(suiteDir), Dir: suiteDir, Cases: doc.Cases}) } return suites, nil } func (s Suite) PagePath(c Case) string { return filepath.Join(s.Dir, "pages", c.Name+".html") } func (s Suite) ReportPath(c Case) string { return filepath.Join(s.Dir, "pages", c.Name+".json") } // Save writes a fetched page and its report. func (s Suite) Save(c Case, page []byte, report any) error { data, err := EncodeReport(report) if err != nil { return err } if err := os.MkdirAll(filepath.Join(s.Dir, "pages"), 0o700); err != nil { return err } if err := os.WriteFile(s.PagePath(c), page, 0o600); err != nil { return err } return os.WriteFile(s.ReportPath(c), data, 0o600) } // EncodeReport is the one way reports are written, so saved and fresh ones // compare byte for byte. func EncodeReport(report any) ([]byte, error) { var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetIndent("", " ") enc.SetEscapeHTML(false) if err := enc.Encode(report); err != nil { return nil, err } return b.Bytes(), nil }