File: routing_test.go

package info (click to toggle)
golang-github-mendersoftware-go-lib-micro 0.0~git20211108.4e20429%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, experimental, forky, sid, trixie
  • size: 656 kB
  • sloc: makefile: 5
file content (179 lines) | stat: -rw-r--r-- 3,912 bytes parent folder | download
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// Copyright 2020 Northern.tech AS
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
package routing

import (
	"net/http"
	"reflect"
	"runtime"
	"testing"

	"github.com/ant0ine/go-json-rest/rest"
	rtest "github.com/ant0ine/go-json-rest/rest/test"
)

func TestSupportsMethod(t *testing.T) {

	var sets = []struct {
		exp       bool
		method    string
		supported []string
	}{
		{
			true,
			http.MethodOptions,
			[]string{
				http.MethodGet,
				http.MethodPut,
				http.MethodOptions,
			},
		},
		{
			false,
			http.MethodOptions,
			[]string{
				http.MethodGet,
				http.MethodPut,
			},
		},
	}

	for _, tv := range sets {
		if supportsMethod(tv.method, tv.supported) != tv.exp {
			t.Errorf("failed case: %+v", tv)
		}
	}
}

// We can't compare functions, so let's take the hard way and extract
// func name from runtime
func funcName(f interface{}) string {
	p := reflect.ValueOf(f).Pointer()
	rfunc := runtime.FuncForPC(p)
	return rfunc.Name()
}

func TestAutogenOptionRoutes(t *testing.T) {
	// make sure that dummy and options are different to prevent
	// the compiler making this a single symbol
	dummy := func(w rest.ResponseWriter, r *rest.Request) {
		// dummy
		w.WriteJson(struct {
			x int
		}{
			2,
		})
	}
	options := func(w rest.ResponseWriter, r *rest.Request) {
		// dummy
		w.WriteJson(struct {
			x int
		}{
			1,
		})
	}
	gen := func(methods []string) rest.HandlerFunc {
		return options
	}

	routes := []*rest.Route{
		// expecting rest.Options(..) to be added for /foo
		rest.Get("/foo", dummy),
		rest.Post("/foo", dummy),

		// no extra OPTIONS handler for /bar
		rest.Get("/bar", dummy),
		rest.Options("/bar", dummy),
	}

	augmented := AutogenOptionsRoutes(routes, gen)

	type expHandler map[string]rest.HandlerFunc
	exp := map[string]expHandler{
		"/foo": {
			http.MethodGet:     dummy,
			http.MethodPost:    dummy,
			http.MethodOptions: options,
		},
		"/bar": {
			http.MethodGet:     dummy,
			http.MethodOptions: dummy,
		},
	}

	// we're expecting 5 handlers in total
	expCount := 5
	if len(augmented) != expCount {
		t.Errorf("got %d handlers instead of %d", len(augmented), expCount)
	}

	for _, r := range augmented {
		v, ok := exp[r.PathExp]
		if ok != true {
			t.Errorf("failed with route %+v, route not present", r)
		}

		h, ok := v[r.HttpMethod]
		if ok != true {
			t.Errorf("failed with route %+v, method not present", r)
		}

		if funcName(r.Func) != funcName(h) {
			t.Errorf("failed with route %+v, different handler", r)
		}
	}
}

//
func TestAutogenOptionHeaders(t *testing.T) {

	suppmeth := []string{
		http.MethodGet,
		http.MethodPut,
	}

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, _ := rest.MakeRouter(
		rest.Options("/test", AllowHeaderOptionsGenerator(suppmeth)),
	)

	api.SetApp(router)

	rec := rtest.RunRequest(t, api.MakeHandler(),
		rtest.MakeSimpleRequest(http.MethodOptions,
			"http://1.2.3.4/test", nil))

	allowmeth := rec.Recorder.HeaderMap[http.CanonicalHeaderKey("Allow")]

	// expecting only 2 allowed methods (should OPTIONS be
	// included in Allow too?)
	if len(allowmeth) != 2 {
		t.Errorf("too many allowed methods: %+v", allowmeth)
	}

	for _, sh := range suppmeth {
		var found bool
		for _, s := range allowmeth {
			if sh == s {
				found = true
				break
			}
		}
		if !found {
			t.Errorf("supported method %s not in allowed: %+v",
				sh, allowmeth)
		}
	}
}