-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ApplicationTests.swift
1208 lines (1045 loc) · 40.2 KB
/
ApplicationTests.swift
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import XCTVapor
import COperatingSystem
final class ApplicationTests: XCTestCase {
func testApplicationStop() throws {
let test = Environment(name: "testing", arguments: ["vapor"])
let app = Application(environment: test)
try app.boot()
DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
app.running?.stop()
}
try app.run()
}
// func testURLSession() throws {
// let app = Application.create(routes: { r, c in
// let client = try c.make(URLSession.self)
// r.get("client") { request -> EventLoopFuture<String> in
// let promise = request.eventLoop.makePromise(of: String.self)
// let url = URL(string: "http://httpbin.org/status/201")!
// client.dataTask(with: URLRequest(url: url)) { data, response, error in
// if let error = error {
// promise.fail(error)
// } else if let response = response as? HTTPURLResponse {
// promise.succeed(response.statusCode.description)
// } else {
// promise.fail(Abort(.internalServerError))
// }
// }.resume()
// return promise.futureResult
// }
// })
// defer { app.shutdown() }
//
// try app.testable().inMemory()
// .test(.GET, "/client") { res in
// XCTAssertEqual(res.status, .ok)
// XCTAssertEqual(res.body.string, "201")
// }
// .test(.GET, "/foo") { res in
// XCTAssertEqual(res.status, .notFound)
// XCTAssertContains(res.body.string, "Not Found")
// }
// }
func testContent() throws {
let request = Request(
collectedBody: .init(string: #"{"hello": "world"}"#),
on: EmbeddedEventLoop()
)
request.headers.contentType = .json
try XCTAssertEqual(request.content.get(at: "hello"), "world")
}
func testComplexContent() throws {
// http://adobe.github.io/Spry/samples/data_region/JSONDataSetSample.html
let complexJSON = """
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
"""
let request = Request(collectedBody: .init(string: complexJSON), on: EmbeddedEventLoop())
request.headers.contentType = .json
try XCTAssertEqual(request.content.get(at: "batters", "batter", 1, "type"), "Chocolate")
}
func testQuery() throws {
let request = Request(on: EmbeddedEventLoop())
request.headers.contentType = .json
request.url.path = "/foo"
print(request.url.string)
request.url.query = "hello=world"
print(request.url.string)
try XCTAssertEqual(request.query.get(String.self, at: "hello"), "world")
}
func testQueryGet() throws {
var req: Request
//
req = Request(method: .GET, url: .init(string: "/path?foo=a"), on: EmbeddedEventLoop())
XCTAssertEqual(try req.query.get(String.self, at: "foo"), "a")
XCTAssertThrowsError(try req.query.get(Int.self, at: "foo")) { error in
if case .typeMismatch(_, let context) = error as? DecodingError {
XCTAssertEqual(context.debugDescription, "Data found at 'foo' was not Int")
} else {
XCTFail("Catched error \"\(error)\", but not the expected: \"DecodingError.typeMismatch\"")
}
}
XCTAssertThrowsError(try req.query.get(String.self, at: "bar")) { error in
if case .valueNotFound(_, let context) = error as? DecodingError {
XCTAssertEqual(context.debugDescription, "No String was found at 'bar'")
} else {
XCTFail("Catched error \"\(error)\", but not the expected: \"DecodingError.valueNotFound\"")
}
}
XCTAssertEqual(req.query[String.self, at: "foo"], "a")
XCTAssertEqual(req.query[String.self, at: "bar"], nil)
//
req = Request(method: .GET, url: .init(string: "/path"), on: EmbeddedEventLoop())
XCTAssertThrowsError(try req.query.get(Int.self, at: "foo")) { error in
if let error = error as? Abort {
XCTAssertEqual(error.status, .unsupportedMediaType)
} else {
XCTFail("Catched error \"\(error)\", but not the expected: \"\(Abort(.unsupportedMediaType))\"")
}
}
XCTAssertEqual(req.query[String.self, at: "foo"], nil)
}
func testParameter() throws {
let app = Application.create(routes: { r, c in
r.get("hello", ":a") { req in
return req.parameters.get("a") ?? ""
}
r.get("hello", ":a", ":b") { req in
return [req.parameters.get("a") ?? "", req.parameters.get("b") ?? ""]
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/hello/vapor") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertContains(res.body.string, "vapor")
}.test(.POST, "/hello/vapor") { res in
XCTAssertEqual(res.status, .notFound)
}.test(.GET, "/hello/vapor/development") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, #"["vapor","development"]"#)
}
}
func testJSON() throws {
let app = Application.create(routes: { r, c in
r.get("json") { req -> [String: String] in
print(req)
return ["foo": "bar"]
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/json") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, #"{"foo":"bar"}"#)
}
}
func testRootGet() throws {
do {
let app = Application.create(routes: { r, c in
r.get("") { req -> String in
return "root"
}
r.get("foo") { req -> String in
return "foo"
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, "root")
}
.test(.GET, "/foo") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, "foo")
}
}
do {
let app = Application.create(routes: { r, c in
r.get { req -> String in
return "root"
}
r.get("foo") { req -> String in
return "foo"
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, "root")
}
.test(.GET, "/foo") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, "foo")
}
}
}
func testLiveServer() throws {
let app = Application.create(routes: { r, c in
r.get("ping") { req -> String in
return "123"
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/ping") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, "123")
}
}
// https://github.com/vapor/vapor/issues/1537
func testQueryStringRunning() throws {
let app = Application.create(routes: { r, c in
r.get("todos") { req in
return "hi"
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/todos?a=b") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, "hi")
}
}
func testGH1534() throws {
let data = """
{"name":"hi","bar":"asdf"}
"""
let app = Application.create(routes: { r, c in
r.get("decode_error") { req -> String in
struct Foo: Decodable {
var name: String
var bar: Int
}
let foo = try JSONDecoder().decode(Foo.self, from: Data(data.utf8))
return foo.name
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/decode_error") { res in
XCTAssertEqual(res.status, .badRequest)
XCTAssertContains(res.body.string, "Value of type 'Int' required for key 'bar'")
}
}
func testContentContainer() throws {
struct FooContent: Content {
var message: String = "hi"
}
struct FooEncodable: Encodable {
var message: String = "hi"
}
let app = Application.create(routes: { r, c in
r.get("encode") { req -> Response in
let res = Response()
try res.content.encode(FooContent())
try res.content.encode(FooContent(), as: .json)
try res.content.encode(FooEncodable(), as: .json)
return res
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/encode") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertContains(res.body.string, "hi")
}
}
func testMultipartDecode() throws {
let data = """
--123\r
Content-Disposition: form-data; name="name"\r
\r
Vapor\r
--123\r
Content-Disposition: form-data; name="age"\r
\r
3\r
--123\r
Content-Disposition: form-data; name="image"; filename="droplet.png"\r
\r
<contents of image>\r
--123--\r
"""
let expected = User(name: "Vapor", age: 3, image: File(data: "<contents of image>", filename: "droplet.png"))
struct User: Content, Equatable {
var name: String
var age: Int
var image: File
}
let app = Application.create(routes: { r, c in
r.get("multipart") { req -> User in
let decoded = try req.content.decode(User.self)
XCTAssertEqual(decoded, expected)
return decoded
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/multipart", headers: [
"Content-Type": "multipart/form-data; boundary=123"
], body: .init(string: data)) { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqualJSON(res.body.string, expected)
}
}
func testMultipartEncode() throws {
struct User: Content {
static var defaultContentType: HTTPMediaType = .formData
var name: String
var age: Int
var image: File
}
let app = Application.create(routes: { r, c in
r.get("multipart") { req -> User in
return User(name: "Vapor", age: 3, image: File(data: "<contents of image>", filename: "droplet.png"))
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/multipart") { res in
XCTAssertEqual(res.status, .ok)
let boundary = res.headers.contentType?.parameters["boundary"] ?? "none"
XCTAssertContains(res.body.string, "Content-Disposition: form-data; name=\"name\"")
XCTAssertContains(res.body.string, "--\(boundary)")
XCTAssertContains(res.body.string, "filename=\"droplet.png\"")
XCTAssertContains(res.body.string, "name=\"image\"")
}
}
func testWebSocketClient() throws {
let app = Application.create(routes: { r, c in
r.get("ws") { req -> EventLoopFuture<String> in
let promise = req.eventLoop.makePromise(of: String.self)
WebSocket.connect(
to: "ws://echo.websocket.org/",
on: req.eventLoop
) { ws in
ws.send("Hello, world!")
ws.onText { ws, text in
promise.succeed(text)
ws.close().cascadeFailure(to: promise)
}
}.cascadeFailure(to: promise)
return promise.futureResult
}
})
defer { app.shutdown() }
let server = try app.testable().start(method: .inMemory)
defer { server.shutdown() }
try server.test(.GET, "/ws") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, "Hello, world!")
}
}
func testViewResponse() throws {
var data = ByteBufferAllocator().buffer(capacity: 0)
data.writeString("<h1>hello</h1>")
let app = Application.create(routes: { r, c in
let client = try c.make(Client.self)
r.get("view") { req -> View in
return View(data: data)
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/view") { res in
XCTAssertEqual(res.status.code, 200)
XCTAssertEqual(res.headers.contentType, .html)
XCTAssertEqual(res.body.string, "<h1>hello</h1>")
}
}
func testURLEncodedFormDecode() throws {
struct User: Content {
var name: String
var age: Int
var luckyNumbers: [Int]
}
let app = Application.create(routes: { r, c in
r.get("urlencodedform") { req -> HTTPStatus in
let foo = try req.content.decode(User.self)
XCTAssertEqual(foo.name, "Vapor")
XCTAssertEqual(foo.age, 3)
XCTAssertEqual(foo.luckyNumbers, [5, 7])
return .ok
}
})
defer { app.shutdown() }
var headers = HTTPHeaders()
headers.contentType = .urlEncodedForm
var body = ByteBufferAllocator().buffer(capacity: 0)
body.writeString("name=Vapor&age=3&luckyNumbers[]=5&luckyNumbers[]=7")
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/urlencodedform", headers: headers, body: body) { res in
XCTAssertEqual(res.status.code, 200)
}
}
func testURLEncodedFormEncode() throws {
struct User: Content {
static let defaultContentType: HTTPMediaType = .urlEncodedForm
var name: String
var age: Int
var luckyNumbers: [Int]
}
let app = Application.create(routes: { r, c in
r.get("urlencodedform") { req -> User in
return User(name: "Vapor", age: 3, luckyNumbers: [5, 7])
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/urlencodedform") { res in
debugPrint(res)
XCTAssertEqual(res.status.code, 200)
XCTAssertEqual(res.headers.contentType, .urlEncodedForm)
XCTAssertContains(res.body.string, "luckyNumbers[]=5")
XCTAssertContains(res.body.string, "luckyNumbers[]=7")
XCTAssertContains(res.body.string, "age=3")
XCTAssertContains(res.body.string, "name=Vapor")
}
}
func testURLEncodedFormDecodeQuery() throws {
struct User: Content {
var name: String
var age: Int
var luckyNumbers: [Int]
}
let app = Application.create(routes: { r, c in
r.get("urlencodedform") { req -> HTTPStatus in
debugPrint(req)
let foo = try req.query.decode(User.self)
XCTAssertEqual(foo.name, "Vapor")
XCTAssertEqual(foo.age, 3)
XCTAssertEqual(foo.luckyNumbers, [5, 7])
return .ok
}
})
defer { app.shutdown() }
let server = try app.testable().start(method: .inMemory)
defer { server.shutdown() }
let data = "name=Vapor&age=3&luckyNumbers[]=5&luckyNumbers[]=7"
try server.test(.GET, "/urlencodedform?\(data)") { res in
XCTAssertEqual(res.status.code, 200)
}
}
func testVaporURI() throws {
do {
var uri = URI(string: "http://vapor.codes/foo?bar=baz#qux")
XCTAssertEqual(uri.scheme, "http")
XCTAssertEqual(uri.host, "vapor.codes")
XCTAssertEqual(uri.path, "/foo")
XCTAssertEqual(uri.query, "bar=baz")
XCTAssertEqual(uri.fragment, "qux")
uri.query = "bar=baz&test=1"
XCTAssertEqual(uri.string, "http://vapor.codes/foo?bar=baz&test=1#qux")
uri.query = nil
XCTAssertEqual(uri.string, "http://vapor.codes/foo#qux")
}
do {
let uri = URI(string: "/foo/bar/baz")
XCTAssertEqual(uri.path, "/foo/bar/baz")
}
do {
let uri = URI(string: "ws://echo.websocket.org/")
XCTAssertEqual(uri.scheme, "ws")
XCTAssertEqual(uri.host, "echo.websocket.org")
XCTAssertEqual(uri.path, "/")
}
do {
let uri = URI(string: "http://foo")
XCTAssertEqual(uri.scheme, "http")
XCTAssertEqual(uri.host, "foo")
XCTAssertEqual(uri.path, "")
}
do {
let uri = URI(string: "foo")
XCTAssertEqual(uri.scheme, "foo")
XCTAssertEqual(uri.host, nil)
XCTAssertEqual(uri.path, "")
}
}
func testStreamFile() throws {
let app = Application.create(routes: { r, c in
let fileio = try c.make(FileIO.self)
r.get("file-stream") { req -> Response in
return fileio.streamFile(at: #file, for: req)
}
})
defer { app.shutdown() }
let server = try app.testable().start(method: .running)
defer { server.shutdown() }
try server.test(.GET, "/file-stream") { res in
let test = "the quick brown fox"
XCTAssertNotNil(res.headers.firstValue(name: .eTag))
XCTAssertContains(res.body.string, test)
}
}
func testStreamFileConnectionClose() throws {
let app = Application.create(routes: { r, c in
let fileio = try c.make(FileIO.self)
r.get("file-stream") { req -> Response in
return fileio.streamFile(at: #file, for: req)
}
})
defer { app.shutdown() }
let server = try app.testable().start(method: .running)
defer { server.shutdown() }
var headers = HTTPHeaders()
headers.replaceOrAdd(name: .connection, value: "close")
try server.test(.GET, "/file-stream", headers: headers) { res in
let test = "the quick brown fox"
XCTAssertNotNil(res.headers.firstValue(name: .eTag))
XCTAssertContains(res.body.string, test)
}
}
func testCustomEncode() throws {
let app = Application.create(routes: { r, c in
r.get("custom-encode") { req -> Response in
var res = Response(status: .ok)
var jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .prettyPrinted
try res.content.encode(["hello": "world"], using: jsonEncoder)
return res
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/custom-encode") { res in
XCTAssertEqual(res.body.string, """
{
"hello" : "world"
}
""")
}
}
// https://github.com/vapor/vapor/issues/1609
func testGH1609() throws {
struct DecodeFail: Content {
var here: String
var missing: String
}
let app = Application.create(routes: { r, c in
r.post("decode-fail") { req -> String in
let fail = try req.content.decode(DecodeFail.self)
return "ok"
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
var body = ByteBufferAllocator().buffer(capacity: 0)
body.writeString(#"{"here":"hi"}"#)
var headers = HTTPHeaders()
headers.replaceOrAdd(name: .contentLength, value: body.readableBytes.description)
headers.contentType = .json
try server.test(.POST, "/decode-fail", headers: headers, body: body) { res in
XCTAssertEqual(res.status, .badRequest)
XCTAssertContains(res.body.string, "missing")
}
}
func testValidationError() throws {
struct User: Content, Validatable {
static func validations() -> Validations {
var validations = Validations()
validations.add("email", as: String.self, is: .email)
return validations
}
var name: String
var email: String
}
let app = Application.create(routes: { r, c in
r.post("users") { req -> String in
try User.validate(req)
let user = try req.content.decode(User.self)
return "ok"
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.POST, "/users", json: ["name": "vapor", "email": "foo"]) { res in
XCTAssertEqual(res.status, .badRequest)
XCTAssertContains(res.body.string, "email is not a valid email address")
}
}
func testAnyResponse() throws {
let app = Application.create(routes: { r, c in
r.get("foo") { req -> AnyResponse in
if try req.query.get(String.self, at: "number") == "true" {
return AnyResponse(42)
} else {
return AnyResponse("string")
}
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/foo?number=true") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, "42")
}.test(.GET, "/foo?number=false") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, "string")
}
}
func testEnumResponse() throws {
enum IntOrString: ResponseEncodable {
case int(Int)
case string(String)
func encodeResponse(for req: Request) -> EventLoopFuture<Response> {
switch self {
case .int(let i):
return i.encodeResponse(for: req)
case .string(let s):
return s.encodeResponse(for: req)
}
}
}
let app = Application.create(routes: { r, c in
r.get("foo") { req -> IntOrString in
if try req.query.get(String.self, at: "number") == "true" {
return .int(42)
} else {
return .string("string")
}
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/foo?number=true") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, "42")
}.test(.GET, "/foo?number=false") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, "string")
}
}
func testVaporProvider() throws {
final class FooProvider: Provider {
var registerFlag: Bool = false
var willBootFlag: Bool = false
var didBootFlag: Bool = false
var willShutdownFlag: Bool = false
func register(_ services: inout Services) {
self.registerFlag = true
}
func willBoot(_ c: Container) -> EventLoopFuture<Void> {
self.willBootFlag = true
return c.eventLoop.makeSucceededFuture(())
}
func didBoot(_ c: Container) -> EventLoopFuture<Void> {
self.didBootFlag = true
return c.eventLoop.makeSucceededFuture(())
}
func willShutdown(_ c: Container) {
self.willShutdownFlag = true
}
}
let foo = FooProvider()
XCTAssertEqual(foo.registerFlag, false)
XCTAssertEqual(foo.willBootFlag, false)
XCTAssertEqual(foo.didBootFlag, false)
XCTAssertEqual(foo.willShutdownFlag, false)
let app = Application.create(configure: { s in
s.provider(foo)
XCTAssertEqual(foo.registerFlag, true)
XCTAssertEqual(foo.willBootFlag, false)
XCTAssertEqual(foo.didBootFlag, false)
XCTAssertEqual(foo.willShutdownFlag, false)
}, routes: { r, c in
// no routes
})
defer { app.shutdown() }
let container = try app.makeContainer().wait()
XCTAssertEqual(foo.registerFlag, true)
XCTAssertEqual(foo.willBootFlag, true)
XCTAssertEqual(foo.didBootFlag, true)
XCTAssertEqual(foo.willShutdownFlag, false)
container.shutdown()
XCTAssertEqual(foo.registerFlag, true)
XCTAssertEqual(foo.willBootFlag, true)
XCTAssertEqual(foo.didBootFlag, true)
XCTAssertEqual(foo.willShutdownFlag, true)
}
func testResponseEncodableStatus() throws {
struct User: Content {
var name: String
}
let app = Application.create(routes: { r, c in
r.post("users") { req -> EventLoopFuture<Response> in
return try req.content
.decode(User.self)
.encodeResponse(status: .created, for: req)
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.POST, "/users", json: ["name": "vapor"]) { res in
XCTAssertEqual(res.status, .created)
XCTAssertEqual(res.headers.contentType, .json)
XCTAssertEqual(res.body.string, """
{"name":"vapor"}
""")
}
}
func testHeadRequest() throws {
let app = Application.create(routes: { r, c in
r.get("hello") { req -> String in
XCTAssertEqual(req.method, .HEAD)
return "hi"
}
})
defer { app.shutdown() }
let server = try app.testable().start(method: .running)
defer { server.shutdown() }
try server.test(.HEAD, "/hello") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.headers.firstValue(name: .contentLength), "2")
XCTAssertEqual(res.body.count, 0)
}
}
func testInvalidCookie() throws {
let app = Application.create(routes: { r, c in
let sessions = try c.make(SessionsMiddleware.self)
r.grouped(sessions).get("get") { req -> String in
return req.session.data["name"] ?? "n/a"
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
var headers = HTTPHeaders()
headers.cookie["vapor-session"] = "asdf"
try server.test(.GET, "/get", headers: headers) { res in
XCTAssertEqual(res.status, .ok)
XCTAssertNotNil(res.headers[.setCookie])
XCTAssertEqual(res.body.string, "n/a")
}
}
func testMiddlewareOrder() throws {
final class OrderMiddleware: Middleware {
static var order: [String] = []
let pos: String
init(_ pos: String) {
self.pos = pos
}
func respond(to req: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
OrderMiddleware.order.append(pos)
return next.respond(to: req)
}
}
let app = Application.create(routes: { r, c in
r.grouped(
OrderMiddleware("a"), OrderMiddleware("b"), OrderMiddleware("c")
).get("order") { req -> String in
return "done"
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/order") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(OrderMiddleware.order, ["a", "b", "c"])
XCTAssertEqual(res.body.string, "done")
}
}
func testSessionDestroy() throws {
final class MockKeyedCache: Sessions {
static var ops: [String] = []
let eventLoop: EventLoop
init(on eventLoop: EventLoop) {
self.eventLoop = eventLoop
}
func createSession(_ data: SessionData) -> EventLoopFuture<SessionID> {
Self.ops.append("create \(data)")
return self.eventLoop.makeSucceededFuture(.init(string: "a"))
}
func readSession(_ sessionID: SessionID) -> EventLoopFuture<SessionData?> {
Self.ops.append("read \(sessionID)")
return self.eventLoop.makeSucceededFuture(SessionData())
}
func updateSession(_ sessionID: SessionID, to data: SessionData) -> EventLoopFuture<SessionID> {
Self.ops.append("update \(sessionID) to \(data)")
return self.eventLoop.makeSucceededFuture(sessionID)
}
func deleteSession(_ sessionID: SessionID) -> EventLoopFuture<Void> {
Self.ops.append("delete \(sessionID)")
return self.eventLoop.makeSucceededFuture(())
}
}
var cookie: HTTPCookies.Value?
let app = Application.create(configure: { s in
s.register(Sessions.self) { c in
return MockKeyedCache(on: c.eventLoop)
}
}, routes: { r, c in
let sessions = try r.grouped(c.make(SessionsMiddleware.self))
sessions.get("set") { req -> String in
req.session.data["foo"] = "bar"
return "set"
}
sessions.get("del") { req -> String in
req.destroySession()
return "del"
}
})
defer { app.shutdown() }
let server = try app.testable().start()
defer { server.shutdown() }
try server.test(.GET, "/set") { res in
XCTAssertEqual(res.body.string, "set")
cookie = res.headers.setCookie["vapor-session"]
XCTAssertNotNil(cookie)
XCTAssertEqual(MockKeyedCache.ops, [
#"create SessionData(storage: ["foo": "bar"])"#,
])
MockKeyedCache.ops = []
}
XCTAssertEqual(cookie?.string, "a")
var headers = HTTPHeaders()
headers.cookie["vapor-session"] = cookie
try server.test(.GET, "/del", headers: headers) { res in
XCTAssertEqual(res.body.string, "del")
XCTAssertEqual(MockKeyedCache.ops, [
#"read SessionID(string: "a")"#,
#"delete SessionID(string: "a")"#
])
}
}
// https://github.com/vapor/vapor/issues/1687
func testRequestQueryStringPercentEncoding() throws {
struct TestQueryStringContainer: Content {
var name: String
}
let req = Request(on: EmbeddedEventLoop())
try req.query.encode(TestQueryStringContainer(name: "Vapor Test"))
XCTAssertEqual(req.url.query, "name=Vapor%20Test")
}
// https://github.com/vapor/vapor/issues/1787
func testGH1787() throws {
let app = Application.create(routes: { r, c in
r.get("no-content") { req -> String in
throw Abort(.noContent)