forked from runatlantis/atlantis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_test.go
281 lines (257 loc) · 7.41 KB
/
server_test.go
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
// Copyright 2017 HootSuite Media Inc.
//
// 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.
// Modified hereafter by contributors to runatlantis/atlantis.
package server_test
import (
"bytes"
"crypto/tls"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/gorilla/mux"
. "github.com/petergtz/pegomock/v4"
"github.com/runatlantis/atlantis/server"
"github.com/runatlantis/atlantis/server/controllers/templates"
tMocks "github.com/runatlantis/atlantis/server/controllers/templates/mocks"
"github.com/runatlantis/atlantis/server/core/locking/mocks"
"github.com/runatlantis/atlantis/server/events/models"
"github.com/runatlantis/atlantis/server/jobs"
"github.com/runatlantis/atlantis/server/logging"
. "github.com/runatlantis/atlantis/testing"
)
func TestNewServer(t *testing.T) {
t.Log("Run through NewServer constructor")
tmpDir := t.TempDir()
_, err := server.NewServer(server.UserConfig{
DataDir: tmpDir,
AtlantisURL: "http://example.com",
}, server.Config{})
Ok(t, err)
}
// todo: test what happens if we set different flags. The generated config should be different.
func TestNewServer_InvalidAtlantisURL(t *testing.T) {
tmpDir := t.TempDir()
_, err := server.NewServer(server.UserConfig{
DataDir: tmpDir,
AtlantisURL: "example.com",
}, server.Config{
AtlantisURLFlag: "atlantis-url",
})
ErrEquals(t, "parsing --atlantis-url flag \"example.com\": http or https must be specified", err)
}
func TestIndex_LockErr(t *testing.T) {
t.Log("index should return a 503 if unable to list locks")
RegisterMockTestingT(t)
l := mocks.NewMockLocker()
When(l.List()).ThenReturn(nil, errors.New("err"))
s := server.Server{
Locker: l,
}
req, _ := http.NewRequest("GET", "", bytes.NewBuffer(nil))
w := httptest.NewRecorder()
s.Index(w, req)
ResponseContains(t, w, 503, "Could not retrieve locks: err")
}
func TestIndex_Success(t *testing.T) {
t.Log("Index should render the index template successfully.")
RegisterMockTestingT(t)
l := mocks.NewMockLocker()
al := mocks.NewMockApplyLocker()
// These are the locks that we expect to be rendered.
now := time.Now()
locks := map[string]models.ProjectLock{
"lkysow/atlantis-example/./default": {
Pull: models.PullRequest{
Num: 9,
},
Project: models.Project{
RepoFullName: "lkysow/atlantis-example",
},
Time: now,
},
}
When(l.List()).ThenReturn(locks, nil)
it := tMocks.NewMockTemplateWriter()
r := mux.NewRouter()
atlantisVersion := "0.3.1"
// Need to create a lock route since the server expects this route to exist.
r.NewRoute().Path("/lock").
Queries("id", "{id}").Name(server.LockViewRouteName)
u, err := url.Parse("https://example.com")
Ok(t, err)
s := server.Server{
Locker: l,
ApplyLocker: al,
IndexTemplate: it,
Router: r,
AtlantisVersion: atlantisVersion,
AtlantisURL: u,
Logger: logging.NewNoopLogger(t),
ProjectCmdOutputHandler: &jobs.NoopProjectOutputHandler{},
}
req, _ := http.NewRequest("GET", "", bytes.NewBuffer(nil))
w := httptest.NewRecorder()
s.Index(w, req)
it.VerifyWasCalledOnce().Execute(w, templates.IndexData{
ApplyLock: templates.ApplyLockData{
Locked: false,
Time: time.Time{},
TimeFormatted: "01-01-0001 00:00:00",
},
Locks: []templates.LockIndexData{
{
LockPath: "/lock?id=lkysow%252Fatlantis-example%252F.%252Fdefault",
RepoFullName: "lkysow/atlantis-example",
PullNum: 9,
Time: now,
TimeFormatted: now.Format("02-01-2006 15:04:05"),
},
},
PullToJobMapping: []jobs.PullInfoWithJobIDs{},
AtlantisVersion: atlantisVersion,
})
ResponseContains(t, w, http.StatusOK, "")
}
func TestHealthz(t *testing.T) {
s := server.Server{}
req, _ := http.NewRequest("GET", "/healthz", bytes.NewBuffer(nil))
w := httptest.NewRecorder()
s.Healthz(w, req)
Equals(t, http.StatusOK, w.Result().StatusCode)
body, _ := io.ReadAll(w.Result().Body)
Equals(t, "application/json", w.Result().Header["Content-Type"][0])
Equals(t,
`{
"status": "ok"
}`, string(body))
}
type mockRW struct{}
var _ http.ResponseWriter = mockRW{}
var mh = http.Header{}
func (w mockRW) WriteHeader(int) {}
func (w mockRW) Write([]byte) (int, error) { return 0, nil }
func (w mockRW) Header() http.Header { return mh }
var w = mockRW{}
var s = &server.Server{}
func BenchmarkHealthz(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
s.Healthz(w, nil)
}
}
func TestGetCertificate(t *testing.T) {
s := server.Server{}
clientHelloInfo := &tls.ClientHelloInfo{}
// Initial certificate load
s.SSLCertFile = "../testdata/cert.pem"
s.SSLKeyFile = "../testdata/key.pem"
cert, err := s.GetSSLCertificate(clientHelloInfo)
Ok(t, err)
// Certificate reload
s.SSLCertFile = "../testdata/cert2.pem"
s.SSLKeyFile = "../testdata/key2.pem"
s.CertLastRefreshTime = s.CertLastRefreshTime.Add(-1 * time.Second)
s.KeyLastRefreshTime = s.KeyLastRefreshTime.Add(-1 * time.Second)
newCert, err := s.GetSSLCertificate(clientHelloInfo)
Ok(t, err)
Assert(
t,
!bytes.Equal(bytes.Join(cert.Certificate, nil), bytes.Join(newCert.Certificate, nil)),
"Certificate expected to rotate")
}
func TestParseAtlantisURL(t *testing.T) {
cases := []struct {
In string
ExpErr string
ExpURL string
}{
// Valid URLs should work.
{
In: "https://example.com",
ExpURL: "https://example.com",
},
{
In: "http://example.com",
ExpURL: "http://example.com",
},
{
In: "http://example.com/",
ExpURL: "http://example.com",
},
{
In: "http://example.com",
ExpURL: "http://example.com",
},
{
In: "http://example.com:4141",
ExpURL: "http://example.com:4141",
},
{
In: "http://example.com:4141/",
ExpURL: "http://example.com:4141",
},
{
In: "http://example.com/baseurl",
ExpURL: "http://example.com/baseurl",
},
{
In: "http://example.com/baseurl/",
ExpURL: "http://example.com/baseurl",
},
{
In: "http://example.com/baseurl/test",
ExpURL: "http://example.com/baseurl/test",
},
// Must be valid URL.
{
In: "::",
ExpErr: "parse \"::\": missing protocol scheme",
},
// Must be absolute.
{
In: "/hi",
ExpErr: "http or https must be specified",
},
// Must have http or https scheme..
{
In: "localhost/test",
ExpErr: "http or https must be specified",
},
{
In: "http0://localhost/test",
ExpErr: "http or https must be specified",
},
}
for _, c := range cases {
t.Run(c.In, func(t *testing.T) {
act, err := server.ParseAtlantisURL(c.In)
if c.ExpErr != "" {
ErrEquals(t, c.ExpErr, err)
} else {
Ok(t, err)
Equals(t, c.ExpURL, act.String())
}
})
}
}
func TestCommandRunnerVCSClientInitialized(t *testing.T) {
s, _ := server.NewServer(server.UserConfig{
AtlantisURL: "http://example.com",
},
server.Config{},
)
Assert(t, s.CommandRunner.VCSClient != nil, "VCSClient must not be nil.")
}