package offline import ( "archive/zip" "bytes" "encoding/json" "os" "path/filepath" "strings" "testing" ) func TestOfflineBundleIncludesLocalAssetsAndSeparatedSpecs(t *testing.T) { files, err := Build() if err != nil { t.Fatal(err) } for _, name := range []string{"index.html", "admin.html", "customer.html", "all.html", "assets/swagger-ui.css", "assets/swagger-ui-bundle.js", "specs/admin.json", "specs/admin.yaml", "specs/customer.json", "specs/customer.yaml", "specs/all.json", "specs/all.yaml", "README.txt", "THIRD_PARTY_LICENSE.txt"} { if len(files[name]) == 0 { t.Errorf("missing bundle file %s", name) } } for _, audience := range []string{"admin", "customer", "all"} { html := string(files[audience+".html"]) if !strings.Contains(html, "validatorUrl:null") || !strings.Contains(html, "supportedSubmitMethods:[]") { t.Errorf("%s is not configured for offline viewing", audience) } if strings.Contains(html, `src="http`) || strings.Contains(html, `href="https://cdn`) { t.Errorf("%s depends on remote assets", audience) } if !strings.Contains(html, "spec:") || strings.Contains(html, "url: 'specs/") { t.Errorf("%s must embed its spec to support file URLs", audience) } var spec struct { Paths map[string]any `json:"paths"` } if err := json.Unmarshal(files["specs/"+audience+".json"], &spec); err != nil { t.Fatal(err) } if len(spec.Paths) == 0 { t.Errorf("empty %s spec", audience) } for path := range spec.Paths { if audience == "admin" && !strings.HasPrefix(path, "/api/v1/admin/") { t.Errorf("foreign path in admin spec: %s", path) } if audience == "customer" && strings.HasPrefix(path, "/api/v1/admin/") { t.Errorf("admin path in customer spec: %s", path) } } } } func TestExportCreatesPortableZIPWithoutUnrelatedFiles(t *testing.T) { output := filepath.Join(t.TempDir(), "swagger-offline") if err := os.MkdirAll(output, 0755); err != nil { t.Fatal(err) } unrelated := filepath.Join(output, "private-notes.txt") if err := os.WriteFile(unrelated, []byte("preserve"), 0600); err != nil { t.Fatal(err) } archive, err := Export(output) if err != nil { t.Fatal(err) } if !strings.HasSuffix(archive, ".zip") { t.Fatal("missing ZIP archive") } raw, err := os.ReadFile(archive) if err != nil { t.Fatal(err) } reader, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw))) if err != nil { t.Fatal(err) } foundIndex := false for _, file := range reader.File { if file.Name == "swagger-offline/index.html" { foundIndex = true } if strings.Contains(file.Name, "private-notes") { t.Error("export included an unrelated local file") } if strings.Contains(file.Name, "..") || strings.Contains(file.Name, "\\") { t.Errorf("unsafe archive path %s", file.Name) } } if !foundIndex { t.Error("ZIP does not contain the documentation index") } if data, err := os.ReadFile(unrelated); err != nil || string(data) != "preserve" { t.Error("export changed an unrelated file") } }