/
DoEverythingServerFeatureTest.scala
2493 lines (2127 loc) · 70.8 KB
/
DoEverythingServerFeatureTest.scala
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
package com.twitter.finatra.http.tests.integration.doeverything.test
import com.fasterxml.jackson.databind.JsonNode
import com.twitter.finagle.http.MediaType
import com.google.inject.name.Names
import com.google.inject.{Key, TypeLiteral}
import com.twitter.finagle.http.Method._
import com.twitter.finagle.http.Status._
import com.twitter.finagle.http._
import com.twitter.finagle.http.codec.HttpCodec
import com.twitter.finagle.{Failure, FailureFlags}
import com.twitter.finatra.http.{EmbeddedHttpServer, RouteHint}
import com.twitter.finatra.http.tests.integration.doeverything.main.DoEverythingServer
import com.twitter.finatra.http.tests.integration.doeverything.main.domain.SomethingStreamedResponse
import com.twitter.finatra.http.tests.integration.doeverything.main.services.DoEverythingService
import com.twitter.finatra.httpclient.{HttpClient, RequestBuilder}
import com.twitter.finatra.json.JsonDiff._
import com.twitter.inject.Mockito
import com.twitter.inject.server.FeatureTest
import com.twitter.io.{Buf, StreamIO}
import com.twitter.util.{Future, Time}
import com.twitter.{logging => ctl}
import java.net.{ConnectException, InetSocketAddress, SocketAddress}
import org.scalatest.exceptions.TestFailedException
import scala.util.parsing.json.JSON
object DoEverythingServerFeatureTest {
private val TestFailureRemoteAddr: SocketAddress = new InetSocketAddress("localhost", 1234)
private val ConnectionFailedFailure =
Failure(
why = "Connection refused: localhost/127.0.0.1:1234 at remote address: localhost/127.0.0.1:1234. Remote Info: Not Available",
cause =
new com.twitter.finagle.ConnectionFailedException(
Some(new TestConnectException(new ConnectException(), TestFailureRemoteAddr)),
Some(TestFailureRemoteAddr)) {
override def logLevel: ctl.Level = ctl.Level.INFO
},
flags = 8
)
private class TestConnectException(
exception: ConnectException,
remoteAddress: SocketAddress)
extends ConnectException(exception.getMessage + ": " + remoteAddress) {
initCause(exception)
setStackTrace(exception.getStackTrace)
override def fillInStackTrace(): Throwable = this
}
}
class DoEverythingServerFeatureTest extends FeatureTest with Mockito {
val httpClient: HttpClient = smartMock[HttpClient]
override val server: EmbeddedHttpServer = new EmbeddedHttpServer(
args = Array("-magicNum=1", "-moduleMagicNum=2"),
twitterServer = new DoEverythingServer,
disableTestLogging = true
).bind[HttpClient].toInstance(httpClient)
val doEverythingService: DoEverythingService = server.injector.instance[DoEverythingService]
val namedExampleString: String = server.injector.instance[String](Names.named("example"))
private def deserializeRequest(name: String) = {
val requestBytes = StreamIO.buffer(getClass.getResourceAsStream(name)).toByteArray
HttpCodec.decodeBytesToRequest(requestBytes)
}
private def counter(key: String): Long = {
server.inMemoryStatsReceiver.counter(key.split("/"): _*)()
}
private def stat(key: String): Seq[Float] = {
server.inMemoryStatsReceiver.stat(key.split("/"): _*)()
}
override protected def beforeEach(): Unit = {
super.beforeEach()
server.inMemoryStatsReceiver.clear()
}
test("named string") {
namedExampleString should equal("named")
}
/* Admin routes */
/* Note that tests against the Global Singleton HttpMuxer break when multiple servers are started in process */
test("GET /admin/foo") {
// NOT on the admin
server.httpGet("/admin/foo", routeHint = RouteHint.AdminServer, andExpect = Status.NotFound)
// on the external
server.httpGet(
"/admin/foo",
routeHint = RouteHint.ExternalServer,
andExpect = Status.Ok,
withBody = "on the external interface"
)
}
test("GET /admin/registry.json") {
val response = server.httpGetAdmin(
"/admin/registry.json",
andExpect = Status.Ok)
val json: Map[String, Any] =
JSON.parseFull(response.contentString).get.asInstanceOf[Map[String, Any]]
val registry = json("registry").asInstanceOf[Map[String, Any]]
registry.contains("library") should be(true)
registry("library").asInstanceOf[Map[String, String]].contains("finatra") should be(true)
}
test("GET /admin/external/filtered") {
// NOT on the admin
server.httpGet(
"/admin/external/filtered",
routeHint = RouteHint.AdminServer,
andExpect = Status.NotFound
)
// on the external and reads headers appended by external filters
server.httpGet(
"/admin/external/filtered",
routeHint = RouteHint.ExternalServer,
andExpect = Ok,
withBody = "01"
)
}
test("respond to /example") {
server.httpGet("/example/routing/always", withBody = "always response")
server.httpGet("/example/routing/always2", withBody = "always response")
}
test("GET /plaintext") {
val response1 = server.httpGet("/plaintext", withBody = "Hello, World!")
response1.contentType should equal(Some(MediaType.PlainTextUtf8))
val response2 = server.httpGet("/plaintext/", withBody = "Hello, World!")
response2.contentType should equal(Some(MediaType.PlainTextUtf8))
}
test("/plaintext (prefixed)") {
val response = server.httpGet("/1.1/plaintext", withBody = "Hello, World!")
response.contentType should equal(Some(MediaType.PlainTextUtf8))
}
test("/forbiddenByFilter (prefixed)") {
server.httpGet(
"/1.1/forbiddenByFilter",
andExpect = Forbidden
)
}
test("/forbiddenByFilter (prefixed outer)") {
server.httpGet(
"/1.1/forbiddenByFilterPrefilter",
andExpect = Forbidden
)
}
test("/forbiddenByFilter (nested prefixed outer)") {
server.httpGet(
"/1.1/forbiddenByFilterPrefilter-nested",
andExpect = Forbidden
)
}
test("/appendMultiplePrefixed (prefixed)") {
server.httpGet(
"/1.1/appendMultiplePrefixed",
withBody = "12"
)
}
test("/freestyleWithHeader (prefixed)") {
server.httpGet(
"/1.1/freestyleWithHeader",
withBody = "bang"
)
}
test("/1.1/waterfall/users (cascading prefixes)") {
server.httpGet(
"/1.1/waterfall/users/",
andExpect = Ok,
withBody = "ok!"
)
}
test("GET /bytearray") {
val response = server.httpGet("/bytearray")
response.contentType should equal(Some(MediaType.OctetStream))
}
test("GET /inputstream") {
val response = server.httpGet("/inputstream")
response.contentType should equal(Some(MediaType.OctetStream))
}
test("GET /useragent") {
server.httpGet("/useragent", headers = Map("User-Agent" -> "Firefox"), withBody = "Firefox")
}
test("GET /acceptHeaders") {
server.httpGet(
"/acceptHeaders",
headers = Map("Accept" -> "text/plain", "Accept-Charset" -> "utf-8", "Accept-Encoding" -> "gzip, deflate"),
withJsonBody =
"""
|{
| "Accept": "text/plain",
| "Accept-Charset": "utf-8",
| "Accept-Charset-Again": "utf-8",
| "Accept-Encoding": "gzip, deflate"
|}
""".stripMargin)
}
test("response should contain server/date headers") {
val response = server.httpGet("/example/routing/always")
response.statusCode should equal(200)
response.contentString should equal("always response")
response.headerMap.get("Date") should not be empty
response.headerMap.get("Server") should not be empty
}
test("json response to /example") {
val response = server.httpGet("/example/routing/json/1")
response.statusCode should equal(200)
jsonDiff(response.contentString, """{"id":"1","name":"bob","magic":"1","module_magic":"2"}""")
}
test("GET /stringMap") {
server.httpGet("/stringMap", andExpect = Ok, withJsonBody = """{"message":"Hello, World!"}""")
}
test("GET /ok") {
server.httpGet("/ok", andExpect = Ok)
}
test("GET /created") {
server.httpGet("/created", andExpect = Created)
}
test("respond to /accepted") {
server.httpGet("/accepted", andExpect = Accepted, withBody = "accepted")
server.httpGet("/accepted2", andExpect = Accepted, withBody = "accepted")
}
test("GET /json") {
server.httpGet("/json", withJsonBody = "{}")
}
test("GET /json2") {
server.httpGet("/json2", withJsonBody = "{}")
}
test("GET /none") {
server.httpGet("/none", withBody = "")
}
test("GET /bodyunit") {
server.httpGet("/bodyunit", withBody = "")
}
test("GET /bodynull") {
server.httpGet("/bodynull", withBody = "")
}
test("GET /bodyEmptyString") {
server.httpGet("/bodyEmptyString", withBody = "")
}
test("GET /routeParamGetAll/:id") {
server.httpGet("/routeParamGetAll/1", withJsonBody = """
[
"1",
"1"
]
""")
}
test("GET /notfound") {
server.httpGet("/notfound", andExpect = NotFound)
}
test("GET /notfound2") {
server.httpGet("/notfound2", andExpect = NotFound)
}
test("GET /notfoundexception") {
server.httpGet("/notfoundexception", andExpect = NotFound)
}
test("GET /notfoundexception2") {
server.httpGet("/notfoundexception2", andExpect = NotFound)
}
test("GET /badrequest") {
server.httpGet("/badrequest", andExpect = BadRequest)
}
test("GET /BadRequestException") {
server.httpGet("/BadRequestException", andExpect = BadRequest)
}
test("GET /forbidden") {
server.httpGet("/forbidden", andExpect = Forbidden)
}
test("GET /ForbiddenException") {
server.httpGet("/ForbiddenException", andExpect = Forbidden)
}
test("GET /ForbiddenException2") {
server.httpGet("/ForbiddenException2", andExpect = Forbidden)
}
test("GET /methodnotallowed") {
server.httpGet("/methodnotallowed", andExpect = MethodNotAllowed)
}
test("GET /unavailable") {
server.httpGet("/unavailable", andExpect = ServiceUnavailable)
}
test("GET /unauthorized") {
server.httpGet("/unauthorized", andExpect = Unauthorized)
}
test("GET /conflict") {
server.httpGet("/conflict", andExpect = Conflict)
}
test("GET /ConflictException") {
server.httpGet("/ConflictException", andExpect = Conflict)
}
test("GET /ConflictException2") {
server.httpGet("/ConflictException2", andExpect = Conflict)
}
test("GET /ConflictException3") {
server.httpGet("/ConflictException3", andExpect = Conflict)
}
test("GET /servererrorexception") {
server.httpGet("/servererrorexception", andExpect = InternalServerError)
}
test("GET /serviceunavailableexception") {
server.httpGet("/serviceunavailableexception", andExpect = ServiceUnavailable)
}
test("GET /serviceunavailableexception2") {
server.httpGet("/serviceunavailableexception2", andExpect = ServiceUnavailable)
}
test("GET /responsebuilder_status_code") {
server.httpGet("/responsebuilder_status_code", andExpect = ServiceUnavailable)
}
test("GET /responsebuilder_status") {
server.httpGet("/responsebuilder_status", andExpect = ServiceUnavailable)
}
test("GET /redirect") {
server.httpGet("/redirect", andExpect = TemporaryRedirect)
}
test("GET /found") {
server.httpGet("/found", andExpect = Found)
}
test("GET /future") {
server.httpGet("/future", andExpect = Ok, withBody = "future")
}
test("POST /foo") {
server.httpPost("/foo", postBody = "", andExpect = Ok, withBody = "bar")
}
test("POST /foo (prefixed)") {
server.httpPost("/1.1/foo", postBody = "", andExpect = Ok, withBody = "bar")
}
test("POST /formPost") {
server.httpFormPost(
"/formPost",
params = Map("name" -> "bob", "age" -> "18"),
andExpect = Ok,
withBody = "bob"
)
}
test("POST /multipartParamsEcho") {
val request = deserializeRequest("/multipart/request-POST-android.bytes")
request.uri = "/multipartParamsEcho"
server.httpRequest(
request = request,
suppress = true,
andExpect = Ok,
withJsonBody = """["banner"]"""
)
}
test("POST /formPostMultipart") {
server.httpMultipartFormPost(
"/formPostMultipart",
params = Seq(
FileElement(
"file",
Buf.ByteArray.Owned("hi".getBytes()),
Some("text/plain"),
Some("hi.txt")
)
),
andExpect = Ok,
withBody = "text/plain"
)
}
test("PUT /multipartParamsPutEcho") {
val request = deserializeRequest("/multipart/request-POST-android.bytes")
request.uri = "/multipartParamsPutEcho"
request.method = Method.Put
server.httpRequest(
request = request,
suppress = true,
andExpect = Ok,
withJsonBody = """["banner"]"""
)
}
test("POST /formPostView") {
server.httpFormPost(
"/formPostView",
params = Map("name" -> "bob", "age" -> "18"),
andExpect = Ok,
withBody = "age:18\nname:bob\nuser1\nuser2\n"
)
}
test("GET /getView") {
server.httpGet(
"/getView?age=18&name=bob",
andExpect = Ok,
withBody = "age:18\nname:bob\nuser1\nuser2\n"
)
}
test("POST /formPostViewFromBuilderView (from BuilderView with diff template than annotation)") {
server.httpFormPost(
"/formPostViewFromBuilderView",
params = Map("name" -> "bob", "age" -> "18"),
andExpect = Ok,
withBody = "age2:18\nname2:bob\nuser1\nuser2\n"
)
}
test("POST /formPostViewFromBuilderHtml") {
server.httpFormPost(
"/formPostViewFromBuilderHtml",
params = Map("name" -> "bob", "age" -> "18"),
andExpect = Ok,
withBody = "age:18\nname:bob\nuser1\nuser2\n"
)
}
test("POST /formPostViewFromBuilderCreatedView") {
val response = server.httpFormPost(
"/formPostViewFromBuilderCreatedView",
params = Map("name" -> "bob", "age" -> "18"),
andExpect = Created,
withBody = "age2:18\nname2:bob\nuser1\nuser2\n"
)
response.location should equal(Some(server.fullHttpURI("/foo/1")))
}
test("POST /formPostViewFromBuilderCreatedHtml") {
val response = server.httpFormPost(
"/formPostViewFromBuilderCreatedHtml",
params = Map("name" -> "bob", "age" -> "18"),
andExpect = Created,
withBody = "age:18\nname:bob\nuser1\nuser2\n"
)
response.location should equal(Some(server.fullHttpURI("/foo/1")))
}
test("POST user with injected group_id from route param") {
server.httpPost(
"/groups/123/users",
postBody = """
{
"name" : "Bob"
}
"""",
andExpect = Created,
withJsonBody = """
{
"group_id":123,
"name":"Bob"
}
"""
)
}
test("POST /multipleRouteParams") {
server.httpPost("/multipleRouteParams", "", andExpect = InternalServerError)
}
test("POST /caseClassWithRequestField") {
server.httpPost("/caseClassWithRequestField", "", andExpect = Ok)
}
test("GET /null") {
server.httpGet("/null", andExpect = Ok, withBody = "")
}
test("GET /empty") {
server.httpGet("/empty", andExpect = Ok, withBody = "")
}
test("GET /unit") {
val response = server.httpGet("/unit", andExpect = Ok, withBody = "")
response.contentLength should equal(Some(0))
// no content-type as there is no content-body
response.contentType should equal(None)
}
test("GET not found path") {
server.httpGet("/sdafasdfsadfsadfsafd", andExpect = NotFound, withBody = "")
}
test("GET complex path") {
server.httpGet("/complexpath/steve", andExpect = Ok, withBody = "done steve 5000")
}
test("GET complex query") {
server.httpGet("/complexquery?name=fred", andExpect = Ok, withBody = "done fred 5000")
}
test("GET /testfile") {
server.httpGet("/testfile", andExpect = Ok, withBody = "testfile123")
}
test("GET /testfileWhenNotfound") {
server.httpGet(
"/testfileWhenNotfound",
andExpect = NotFound,
withBody = "/doesntexist.txt not found"
)
}
test("GET /exception") {
server.httpGet("/exception", andExpect = InternalServerError)
}
test("GET /pathUrl") {
val request = server.httpGet("/pathUrl", andExpect = Ok)
request.contentString should endWith("/pathUrl/")
}
test("GET /path") {
val request = server.httpGet("/path", andExpect = Ok)
request.contentString should endWith("/path/")
}
test("GET /put (NotFound)") {
server.httpGet("/put", andExpect = NotFound) //TODO: Should be 405 Method Not Allowed
}
test("putJson") {
server.httpPutJson[JsonNode](
"/putJson/123",
putBody = """{"name": "Steve"}""",
andExpect = Ok,
withJsonBody = """{"id": 123, "name": "Steve"}"""
)
}
test("putJson without type param") {
val e = intercept[TestFailedException] {
server.httpPutJson(
"/putJson/123",
putBody = """{"name": "Steve"}""",
andExpect = Ok,
withJsonBody = """{"id": 123, "name": "Steve"}"""
)
}
e.getMessage() should include("requires a type-param")
}
test("PUT body with multi-byte characters") {
val musicalNote = "\uD83C\uDFB5"
val body = s"${musicalNote} ${musicalNote}"
server.httpPut(
"/echo",
putBody = body,
contentType = MediaType.PlainTextUtf8,
andExpect = Ok,
withBody = body
)
}
test("PUT") {
server.httpPut("/put/123", putBody = "asdf", andExpect = Ok, withBody = "123_asdf")
}
test("PUT with RouteParam and non-json body") {
server.httpPut(
"/put_route_param/123",
contentType = "plain/text",
putBody = "asdf",
andExpect = Ok,
withBody = "123_asdf"
)
}
test("PUT with RouteParam and json body") {
server.httpPut("/put_route_param/123", putBody = "{}", andExpect = Ok, withBody = "123_{}")
}
test("PUT with RouteParam and empty body") {
server.httpPut("/put_route_param/123", putBody = "", andExpect = Ok, withBody = "123_")
}
test("PUT /put_route_param_and_name") {
server.httpPut(
"/put_route_param_and_name/123",
putBody = """{"name": "bob"}""",
andExpect = Ok,
withBody = "123_bob"
)
}
test("PUT /put_route_param_and_name (with empty PUT body)") {
server.httpPut(
"/put_route_param_and_name/123",
putBody = "",
andExpect = BadRequest,
withJsonBody = """
{
"errors" : [
"name: field is required"
]
}"""
)
}
test("PUT /put_route_param_and_name (with non-json PUT body)") {
server.httpPut(
"/put_route_param_and_name/123",
putBody = "foo",
contentType = "plain/text",
andExpect = BadRequest,
withJsonBody = """
{
"errors" : [
"name: field is required"
]
}"""
)
}
test("PUT /put_id_ignoring_body") {
val response = server.httpPut(
"/put_id_ignoring_body/42",
putBody = "invalid JSON",
andExpect = Ok,
withJsonBody = "42"
)
response.contentType should equal(Some(MediaType.PlainTextUtf8))
}
test("PUT /put_id_not_ignoring_body") {
server.httpPut(
"/put_id_not_ignoring_body/42",
putBody = "invalid JSON",
andExpect = BadRequest,
withJsonBody = """
{
"errors":[
"Unrecognized token 'invalid': was expecting ('true', 'false' or 'null')"
]
}"""
)
}
test("POST /putAndPost") {
server.httpPost("/putAndPost", postBody = "1", andExpect = Ok, withBody = "POST1")
}
test("PUT /putAndPost") {
server.httpPut("/putAndPost", putBody = "2", andExpect = Ok, withBody = "PUT2")
}
test("GET /putAndPost (NotFound)") {
server.httpGet("/putAndPost", andExpect = NotFound) //TODO: Should be 405 Method Not Allowed
}
test("POST /postAndPut") {
server.httpPost("/postAndPut", postBody = "1", andExpect = Ok, withBody = "POST1")
}
test("PUT /postAndPut") {
server.httpPut("/postAndPut", putBody = "2", andExpect = Ok, withBody = "PUT2")
}
test("GET /postAndPut (NotFound)") {
server.httpGet("/postAndPut", andExpect = NotFound) //TODO: Should be 405 Method Not Allowed
}
test("GET /true") {
server.httpGet("/true", andExpect = Ok, withBody = "true")
}
test("GET /index (root)") {
server.httpGet("/index/", andExpect = Ok, withBody = "testindex")
}
test("GET index file without extension") {
server.httpGet("/index/testfile", andExpect = Ok, withBody = "testindex")
}
test("GET index file with extension") {
server.httpGet("/index/testfile.txt", andExpect = Ok, withBody = "testfile123")
}
test("GET /implicitOkAndException (when ok)") {
server.httpGet("/implicitOkAndException?hi", andExpect = Ok)
}
test("GET /implicitOkAndException (when bad request exception)") {
server.httpGet("/implicitOkAndException", andExpect = BadRequest)
}
test("nack") {
val ff = intercept[Throwable] {
server.httpGet("/nack", andExpect = ServiceUnavailable)
}
assert(FailureFlags.isFlagged(FailureFlags.Rejected)(ff))
}
test("response builder") {
val response = server.httpGet(
"/builderCreatedWithHeader",
andExpect = Created,
withLocation = "http://foo.com/1"
)
response.headerMap.get("a") should equal(Some("b"))
}
test("request injection") {
server.httpGet(
"/requestInjection?id=5&id2=6&id3&id4=7",
andExpect = Ok,
withJsonBody = """
{
"id" : 5,
"id2" : 6,
"id4" : 7,
"default_string" : "default string",
"default_prod_string" : "prod string",
"default_opt_string" : "default option string",
"default_opt_prod_string" : "prod option string"
}"""
)
}
test("request injections not found") {
server.httpGet(
"/requestInjectionsNotFound",
andExpect = InternalServerError,
withErrors = Seq("internal server error")
)
}
test("GET request injections not available") {
server.httpGet(
"/requestInjectionsNotAvailable",
andExpect = InternalServerError,
withErrors = Seq("internal server error")
)
}
test("POST request injections not available") {
server.httpPost(
"/requestInjectionsNotAvailable",
"{}",
andExpect = InternalServerError,
withErrors = Seq("internal server error")
)
}
test("POST empty json request injections not available") {
server.httpPost(
"/requestInjectionsNotAvailable",
"",
andExpect = InternalServerError,
withErrors = Seq("internal server error")
)
}
test("POST invalid json request injections not available") {
server.httpPost(
"/requestInjectionsNotAvailable",
"{abc",
andExpect = BadRequest,
withErrors =
Seq("Unexpected character ('a' (code 97)): was expecting double-quote to start field name")
)
}
test("GET json user") {
val response =
server.httpGet("/users/mary", andExpect = Ok, withJsonBody = """{ "name" : "mary" }""")
response.headerMap("content-type") should equal(MediaType.JsonUtf8)
}
test("POST json user") {
server.httpPost("/users", """
{
"name" : "bob"
}
""", andExpect = Ok, withBody = "bob")
}
test("POST json user with missing required field") {
server.httpPost("/users", """
{
}
""", andExpect = BadRequest, withErrors = Seq("name: field is required"))
}
test("POST body with multi-byte characters") {
val musicalNote = "\uD83C\uDFB5"
val body = s"${musicalNote} ${musicalNote}"
server.httpPost(
"/echo",
postBody = body,
contentType = MediaType.PlainTextUtf8,
andExpect = Ok,
withBody = body
)
}
test("POST json user with failed field validation") {
server.httpPost("/users", """
{
"name": "a"
}
""", andExpect = BadRequest, withErrors = Seq("name: size [1] is not between 2 and 20"))
}
test("POST json user with null required field") {
server.httpPost("/users", """
{
"name": null
}
""", andExpect = BadRequest, withErrors = Seq("name: field is required"))
}
test("POST json with failed array element validation") {
server.httpPost(
"/arrayElementValidation",
"""
{
"seq": [0]
}
""",
andExpect = BadRequest,
withErrors = Seq("seq.value: [0] is not greater than or equal to 1")
)
}
test("POST json with null array element") {
server.httpPost(
"/arrayElementValidation",
"""
{
"seq": [null]
}
""",
andExpect = BadRequest,
withErrors = Seq("seq: Literal null values are not allowed as json array elements.")
)
}
test("POST json user with failed method validation") {
server.httpPost("/users", """
{
"name": "foo"
}
""", andExpect = BadRequest, withErrors = Seq("name cannot be foo"))
}
test("POST json user with invalid field validation") {
server.httpPost(
"/userWithInvalidFieldValidation",
"""
{
"name": "a"
}
""",
andExpect = InternalServerError,
withErrors = Seq("internal server error")
)
}
test("POST json user with invalid method validation") {
server.httpPost(
"/userWithInvalidMethodValidation",
"""
{
"name": "foo"
}
""",
andExpect = InternalServerError,
withErrors = Seq("internal server error")
)
}
test("POST json user with invalid content type") {
server.httpPost("/users", """
{
"name" : "bob"
}
""", contentType = "foo", andExpect = BadRequest)
}
test(
"POST json user with missing required field when message body reader uses intermediate JsonNode"
) {
server.httpPost("/userWithMessageBodyReader", """
{
}
""", andExpect = BadRequest, withErrors = Seq("name: field is required"))
}
test(
"POST json user with method validation error when message body reader uses intermediate JsonNode"
) {
server.httpPost(
"/userWithMessageBodyReader",
"""
{
"name": "foo"
}
""",
andExpect = BadRequest,
withErrors = Seq("name cannot be foo")
)
}
test("POST invalid JSON") {
server.httpPost("/userWithMessageBodyReader", """
[{
"name": "foo"
}]
""", andExpect = BadRequest)
}
test("injector test") {
server.injector.instance[String]("example") should equal("named")
val exampleService = server.injector.instance[DoEverythingService]
exampleService should not equal null
server.injector.instance(classOf[DoEverythingService]) should equal(exampleService)
val key = Key.get(new TypeLiteral[DoEverythingService]() {})
server.injector.instance(key) should equal(exampleService)
}
test("GET /array") {
server.httpGet("/array", andExpect = Ok, withJsonBody = """["a", "b"]""")
}