Skip to content

Commit

Permalink
add test coverage for duplicate patterns
Browse files Browse the repository at this point in the history
  • Loading branch information
crhntr committed Aug 19, 2024
1 parent ea81762 commit fc1edf6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
4 changes: 3 additions & 1 deletion pattern.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (

func TemplatePatterns(ts *template.Template) ([]Pattern, error) {
var patterns []Pattern
routes := make(map[string]struct{})
for _, t := range ts.Templates() {
pat, err, ok := NewPattern(t.Name())
if !ok {
Expand All @@ -25,9 +26,10 @@ func TemplatePatterns(ts *template.Template) ([]Pattern, error) {
if err != nil {
return patterns, err
}
if slices.ContainsFunc(patterns, pat.sameRoute) {
if _, exists := routes[pat.Method+pat.Path]; exists {
return patterns, fmt.Errorf("duplicate route pattern: %s", pat.Route)
}
routes[pat.Method+pat.Path] = struct{}{}
patterns = append(patterns, pat)
}
slices.SortFunc(patterns, Pattern.byPathThenMethod)
Expand Down
14 changes: 14 additions & 0 deletions pattern_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package muxt_test

import (
"html/template"
"net/http"
"testing"

Expand All @@ -10,6 +11,19 @@ import (
"github.com/crhntr/muxt"
)

func TestTemplatePatterns(t *testing.T) {
t.Run("when one of the template names is a malformed pattern", func(t *testing.T) {
ts := template.Must(template.New("").Parse(`{{define "HEAD /"}}{{end}}`))
_, err := muxt.TemplatePatterns(ts)
require.Error(t, err)
})
t.Run("when the pattern is not unique", func(t *testing.T) {
ts := template.Must(template.New("").Parse(`{{define "GET / F1()"}}a{{end}} {{define "GET / F2()"}}b{{end}}`))
_, err := muxt.TemplatePatterns(ts)
require.Error(t, err)
})
}

func TestNewPattern(t *testing.T) {
for _, tt := range []struct {
Name string
Expand Down

0 comments on commit fc1edf6

Please sign in to comment.