Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 171 additions & 0 deletions cmd/asyncapi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,19 @@ package cmd

import (
"bytes"
"encoding/json"
"errors"
"html"
"io"
"os"
"path/filepath"
"strings"
"testing"

"github.com/daveshanley/vacuum/model"
"github.com/daveshanley/vacuum/rulesets"
"github.com/daveshanley/vacuum/utils"
ppmodel "github.com/pb33f/doctor/printingpress/model"
"github.com/pb33f/testify/assert"
"github.com/pb33f/testify/require"
)
Expand Down Expand Up @@ -237,6 +241,173 @@ paths: {}`)
assert.True(t, docsOutputContainsFile(t, outputDir, "asyncapi.yaml"))
}

func TestRunDocsAggregateGroupsMixedContractsWithFamilyDiagnostics(t *testing.T) {
root := t.TempDir()
openAPIPath := filepath.Join(root, "services", "generic", "http", "v1", "openapi.yaml")
asyncAPIPath := filepath.Join(root, "services", "generic", "events", "v1", "asyncapi.yaml")
writeTestFile(t, openAPIPath, `openapi: 3.1.0
info:
title: Generic Catalog HTTP API
version: 1.0.0
description: HTTP contract.
x-owner:
service: Generic Catalog
paths: {}
`)
writeTestFile(t, asyncAPIPath, `asyncapi: 3.1.0
info:
title: Generic Catalog Published Events
version: 1.0.0
description: Published event contract.
x-owner:
service: Generic Catalog
tags:
- name: events
description: Published events.
servers:
production:
host: broker.example.net
protocol: mqtt
channels: {}
operations: {}
`)

configPath := filepath.Join(root, "printing-press.yaml")
writeTestFile(t, configPath, `grouping:
serviceIdentity:
metadataPointers:
- /info/x-owner/service
contractRoles:
- pattern: "**/http/**"
role: http-api
contractID: http-api
default: true
- pattern: "**/events/**"
role: published-events
contractID: published-events
`)
openAPIRuleset := writeDocsNamedRuleset(t, root, "openapi-ruleset.yaml", "custom-openapi-family-rule")
outputDir := filepath.Join(t.TempDir(), "docs")
cmd := GetDocsCommand()
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)

err := runDocs(cmd, root, &docsOptions{
outputDir: outputDir,
docsConfigPath: configPath,
openAPIRuleset: openAPIRuleset,
noLLM: true,
noJSON: true,
noLogo: true,
includeSpec: true,
})

require.NoError(t, err)
catalogHTML, err := os.ReadFile(filepath.Join(outputDir, "index.html"))
require.NoError(t, err)
defaultHTTPHref := "services/generic-catalog/versions/1-0-0/specs/generic-catalog-http-api/index.html"
assert.Contains(t, string(catalogHTML), `href="`+defaultHTTPHref+`"`)

serviceSpecsRoot := filepath.Join(outputDir, "services", "generic-catalog", "versions", "1-0-0", "specs")
httpRoot := filepath.Join(serviceSpecsRoot, "generic-catalog-http-api")
eventRoot := filepath.Join(serviceSpecsRoot, "generic-catalog-published-events")
httpOverview := readDocsContractPage(t, filepath.Join(httpRoot, "index.html"))
assert.Equal(t, "API OVERVIEW", httpOverview.overviewLabel)
assert.Equal(t, "Generic Catalog HTTP API", httpOverview.serviceName)
assertDocsContractTree(t, httpOverview.groups, "http-api")

eventOverview := readDocsContractPage(t, filepath.Join(eventRoot, "index.html"))
assert.Equal(t, "EVENT OVERVIEW", eventOverview.overviewLabel)
assert.Equal(t, "Generic Catalog HTTP API", eventOverview.serviceName)
assertDocsContractTree(t, eventOverview.groups, "published-events")

openAPIDiagnostics := readTestFile(t, filepath.Join(httpRoot, "data", "pages", "diagnostics.js"))
assert.Contains(t, openAPIDiagnostics, "custom-openapi-family-rule")
assert.NotContains(t, openAPIDiagnostics, rulesets.AsyncAPIInfoContact)
asyncAPIDiagnostics := readTestFile(t, filepath.Join(eventRoot, "data", "pages", "diagnostics.js"))
assert.Contains(t, asyncAPIDiagnostics, rulesets.AsyncAPIInfoContact)
assert.NotContains(t, asyncAPIDiagnostics, "custom-openapi-family-rule")

legacyRuleset := writeDocsNamedRuleset(t, root, "legacy-ruleset.yaml", "legacy-docs-rule")
legacyOutput := filepath.Join(t.TempDir(), "legacy-docs")
legacyCmd := GetDocsCommand()
legacyCmd.SetOut(io.Discard)
legacyCmd.SetErr(io.Discard)
legacyCmd.Flags().String("ruleset", "", "")
require.NoError(t, legacyCmd.Flags().Set("ruleset", legacyRuleset))
legacyFlags := docsLintFlags(legacyCmd)
assert.Equal(t, legacyRuleset, legacyFlags.RulesetFlag)
legacyDiagnostics, err := newDocsDiagnosticsContext(legacyFlags, utils.HTTPClientConfig{}, nil, true)
require.NoError(t, err)
legacyResults, err := legacyDiagnostics.lintSpec([]byte(docsDiagnosticsSpec("Legacy HTTP API")), openAPIPath)
require.NoError(t, err)
require.NotEmpty(t, legacyResults)
assert.Equal(t, "legacy-docs-rule", legacyResults[0].RuleId)
require.NoError(t, runDocs(legacyCmd, root, &docsOptions{
outputDir: legacyOutput,
docsConfigPath: configPath,
noLLM: true,
noJSON: true,
noLogo: true,
}))
legacyDiagnosticsPath := filepath.Join(legacyOutput, "services", "generic-catalog", "versions", "1-0-0", "specs", "generic-catalog-http-api", "data", "pages", "diagnostics.js")
assert.Contains(t, readTestFile(t, legacyDiagnosticsPath), "legacy-docs-rule")
}

type docsContractPage struct {
overviewLabel string
serviceName string
groups []*ppmodel.SiteContractGroup
}

func readDocsContractPage(t *testing.T, pagePath string) docsContractPage {
t.Helper()
rendered := readTestFile(t, pagePath)
contractPayload := docsHTMLAttribute(t, rendered, "data-pp-contracts")
var groups []*ppmodel.SiteContractGroup
require.NoError(t, json.Unmarshal([]byte(contractPayload), &groups))
return docsContractPage{
overviewLabel: docsHTMLAttribute(t, rendered, "data-pp-overview-label"),
serviceName: docsHTMLAttribute(t, rendered, "data-pp-service-name"),
groups: groups,
}
}

func docsHTMLAttribute(t *testing.T, rendered, name string) string {
t.Helper()
marker := name + `="`
start := strings.Index(rendered, marker)
require.GreaterOrEqual(t, start, 0, "missing %s", name)
valueStart := start + len(marker)
valueEnd := strings.Index(rendered[valueStart:], `"`)
require.GreaterOrEqual(t, valueEnd, 0, "unterminated %s", name)
return html.UnescapeString(rendered[valueStart : valueStart+valueEnd])
}

func assertDocsContractTree(t *testing.T, groups []*ppmodel.SiteContractGroup, activeRole string) {
t.Helper()
require.Len(t, groups, 2)
assert.Equal(t, ppmodel.ContractRoleHTTPAPI, groups[0].Role)
assert.Equal(t, "HTTP API", groups[0].Label)
require.Len(t, groups[0].Contracts, 1)
assert.Equal(t, "http-api", groups[0].Contracts[0].ID)
assert.Equal(t, "Generic Catalog HTTP API", groups[0].Contracts[0].Label)
assert.Equal(t, activeRole == "http-api", groups[0].Contracts[0].Active)
assert.Equal(t, ppmodel.ContractRolePublishedEvents, groups[1].Role)
assert.Equal(t, "Published Events", groups[1].Label)
require.Len(t, groups[1].Contracts, 1)
assert.Equal(t, "published-events", groups[1].Contracts[0].ID)
assert.Equal(t, "Generic Catalog Published Events", groups[1].Contracts[0].Label)
assert.Equal(t, activeRole == "published-events", groups[1].Contracts[0].Active)
}

func readTestFile(t *testing.T, path string) string {
t.Helper()
data, err := os.ReadFile(path)
require.NoError(t, err)
return string(data)
}

func docsOutputContainsFile(t *testing.T, root, name string) bool {
t.Helper()
found := false
Expand Down
6 changes: 4 additions & 2 deletions cmd/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ The source API contract is not shipped in generated output by default. Use
cmd.Flags().StringVar(&opts.title, "title", "", "Override the API title")
cmd.Flags().StringVar(&opts.catalogTitle, "catalog-title", "", "Override the API catalog title")
cmd.Flags().StringVar(&opts.docsConfigPath, "docs-config", "", "Path to a printing press docs config file")
cmd.Flags().StringVar(&opts.openAPIRuleset, "openapi-ruleset", "", "Ruleset for OpenAPI docs diagnostics")
cmd.Flags().StringVar(&opts.asyncAPIRuleset, "asyncapi-ruleset", "", "Ruleset for AsyncAPI docs diagnostics")
cmd.Flags().StringVar(&opts.baseURL, "base-url", "", "Base URL to use in generated HTML")
cmd.Flags().StringVar(&opts.basePath, "base-path", "", "Base path for resolving local file references")
cmd.Flags().StringVar(&opts.buildMode, "build-mode", "", "Aggregate build mode: full, fast, or watch")
Expand Down Expand Up @@ -136,7 +138,7 @@ func runDocs(cmd *cobra.Command, input string, opts *docsOptions) (err error) {
if err != nil {
return err
}
diagnostics, err := newDocsDiagnosticsContext(lintFlags, httpClientConfig, fetchConfig, !opts.noDiagnostics)
diagnostics, err := newDocsDiagnosticsContext(lintFlags, httpClientConfig, fetchConfig, !opts.noDiagnostics, docsFamilyRulesetPathsFromOptions(opts))
if err != nil {
return err
}
Expand All @@ -151,7 +153,7 @@ func runDocs(cmd *cobra.Command, input string, opts *docsOptions) (err error) {
if err != nil {
return err
}
diagnostics, err := newDocsDiagnosticsContext(lintFlags, httpClientConfig, fetchConfig, !opts.noDiagnostics)
diagnostics, err := newDocsDiagnosticsContext(lintFlags, httpClientConfig, fetchConfig, !opts.noDiagnostics, docsFamilyRulesetPathsFromOptions(opts))
if err != nil {
return err
}
Expand Down
2 changes: 2 additions & 0 deletions cmd/docs_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ type docsOptions struct {
baseURL string
basePath string
docsConfigPath string
openAPIRuleset string
asyncAPIRuleset string
buildMode string
maxPools int
workersPerPool int
Expand Down
Loading