File: node_test.go

package info (click to toggle)
golang-github-getkin-kin-openapi 0.124.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,288 kB
  • sloc: sh: 344; makefile: 4
file content (81 lines) | stat: -rw-r--r-- 2,372 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package pathpattern

import (
	"testing"
)

func TestPatterns(t *testing.T) {
	DefaultOptions.SupportRegExp = true
	rootNode := &Node{}
	add := func(path, value string) {
		rootNode.MustAdd(path, value, nil)
	}
	add("GET /abc", "GET METHOD")
	add("POST /abc", "POST METHOD")

	add("/abc", "SIMPLE")
	add("/abc/fixedString", "FIXED STRING")
	add("/abc/{param}", "FILE")
	add("/abc/{param*}", "DEEP FILE")
	add("/abc/{fileName|(.*)\\.jpeg}", "JPEG")
	add("/abc/{fileName|some_prefix_(.*)\\.jpeg}", "PREFIXED JPEG")
	add("/root/{path*}", "DIRECTORY")
	add("/impossible_route", "IMPOSSIBLE")

	add(PathFromHost("www.nike.com", true), "WWW-HOST")
	add(PathFromHost("{other}.nike.com", true), "OTHER-HOST")

	expect := func(uri string, expected string, expectedArgs ...string) {
		actually := "not found"
		node, actualArgs := rootNode.Match(uri)
		if node != nil {
			if s, ok := node.Value.(string); ok {
				actually = s
			}
		}
		if actually != expected {
			t.Fatalf("Wrong path!\nInput: %s\nExpected: %q\nActually: %q\nTree:\n%s\n\n", uri, expected, actually, rootNode.String())
			return
		}
		if !argsEqual(expectedArgs, actualArgs) {
			t.Fatalf("Wrong variable values!\nInput: %s\nExpected: %q\nActually: %q\nTree:\n%s\n\n", uri, expectedArgs, actualArgs, rootNode.String())
			return
		}
	}
	expect("", "not found")
	expect("/", "not found")

	expect("GET /abc", "GET METHOD")
	expect("GET /abc/", "GET METHOD")
	expect("POST /abc", "POST METHOD")

	expect("/url_without_handler", "not found")
	expect("/abc", "SIMPLE")
	expect("/abc/fixedString", "FIXED STRING")
	expect("/abc/09az", "FILE", "09az")
	expect("/abc/09az/1/2/3", "DEEP FILE", "09az/1/2/3")
	expect("/abc/09az/1/2/3/", "DEEP FILE", "09az/1/2/3")
	expect("/abc/someFile.jpeg", "JPEG", "someFile")
	expect("/abc/someFile.old.jpeg", "JPEG", "someFile.old")
	expect("/abc/some_prefix_someFile.jpeg", "PREFIXED JPEG", "someFile")

	expect("/root", "DIRECTORY", "")
	expect("/root/", "DIRECTORY", "")
	expect("/root/a/b/c", "DIRECTORY", "a/b/c")

	expect(PathFromHost("www.nike.com", true), "WWW-HOST")
	expect(PathFromHost("example.nike.com", true), "OTHER-HOST", "example")
	expect(PathFromHost("subdomain.example.nike.com", true), "not found")
}

func argsEqual(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}
	for i, ai := range a {
		if ai != b[i] {
			return false
		}
	}
	return true
}