-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
DefaultContractTest.java
643 lines (500 loc) · 20.1 KB
/
DefaultContractTest.java
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
/*
* Copyright 2013 Netflix, 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.
*/
package feign;
import com.google.gson.reflect.TypeToken;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.net.URI;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static feign.assertj.FeignAssertions.assertThat;
import static java.util.Arrays.asList;
import static org.assertj.core.data.MapEntry.entry;
/**
* Tests interfaces defined per {@link Contract.Default} are interpreted into expected {@link feign
* .RequestTemplate template} instances.
*/
public class DefaultContractTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
Contract.Default contract = new Contract.Default();
@Test
public void httpMethods() throws Exception {
assertThat(parseAndValidateMetadata(Methods.class, "post").template())
.hasMethod("POST");
assertThat(parseAndValidateMetadata(Methods.class, "put").template())
.hasMethod("PUT");
assertThat(parseAndValidateMetadata(Methods.class, "get").template())
.hasMethod("GET");
assertThat(parseAndValidateMetadata(Methods.class, "delete").template())
.hasMethod("DELETE");
}
@Test
public void bodyParamIsGeneric() throws Exception {
MethodMetadata md = parseAndValidateMetadata(BodyParams.class, "post", List.class);
assertThat(md.bodyIndex())
.isEqualTo(0);
assertThat(md.bodyType())
.isEqualTo(new TypeToken<List<String>>() {
}.getType());
}
@Test
public void tooManyBodies() throws Exception {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Method has too many Body");
parseAndValidateMetadata(BodyParams.class, "tooMany", List.class, List.class);
}
@Test
public void customMethodWithoutPath() throws Exception {
assertThat(parseAndValidateMetadata(CustomMethod.class, "patch").template())
.hasMethod("PATCH")
.hasUrl("");
}
@Test
public void queryParamsInPathExtract() throws Exception {
assertThat(parseAndValidateMetadata(WithQueryParamsInPath.class, "none").template())
.hasUrl("/")
.hasQueries();
assertThat(parseAndValidateMetadata(WithQueryParamsInPath.class, "one").template())
.hasUrl("/")
.hasQueries(
entry("Action", asList("GetUser"))
);
assertThat(parseAndValidateMetadata(WithQueryParamsInPath.class, "two").template())
.hasUrl("/")
.hasQueries(
entry("Action", asList("GetUser")),
entry("Version", asList("2010-05-08"))
);
assertThat(parseAndValidateMetadata(WithQueryParamsInPath.class, "three").template())
.hasUrl("/")
.hasQueries(
entry("Action", asList("GetUser")),
entry("Version", asList("2010-05-08")),
entry("limit", asList("1"))
);
assertThat(parseAndValidateMetadata(WithQueryParamsInPath.class, "twoAndOneEmpty").template())
.hasUrl("/")
.hasQueries(
entry("flag", asList(new String[]{null})),
entry("Action", asList("GetUser")),
entry("Version", asList("2010-05-08"))
);
assertThat(parseAndValidateMetadata(WithQueryParamsInPath.class, "oneEmpty").template())
.hasUrl("/")
.hasQueries(
entry("flag", asList(new String[]{null}))
);
assertThat(parseAndValidateMetadata(WithQueryParamsInPath.class, "twoEmpty").template())
.hasUrl("/")
.hasQueries(
entry("flag", asList(new String[]{null})),
entry("NoErrors", asList(new String[]{null}))
);
}
@Test
public void bodyWithoutParameters() throws Exception {
MethodMetadata md = parseAndValidateMetadata(BodyWithoutParameters.class, "post");
assertThat(md.template())
.hasBody("<v01:getAccountsListOfUser/>");
}
@Test
public void headersOnMethodAddsContentTypeHeader() throws Exception {
MethodMetadata md = parseAndValidateMetadata(BodyWithoutParameters.class, "post");
assertThat(md.template())
.hasHeaders(
entry("Content-Type", asList("application/xml")),
entry("Content-Length", asList(String.valueOf(md.template().body().length)))
);
}
@Test
public void headersOnTypeAddsContentTypeHeader() throws Exception {
MethodMetadata md = parseAndValidateMetadata(HeadersOnType.class, "post");
assertThat(md.template())
.hasHeaders(
entry("Content-Type", asList("application/xml")),
entry("Content-Length", asList(String.valueOf(md.template().body().length)))
);
}
@Test
public void withPathAndURIParam() throws Exception {
MethodMetadata md = parseAndValidateMetadata(WithURIParam.class,
"uriParam", String.class, URI.class, String.class);
assertThat(md.indexToName())
.containsExactly(
entry(0, asList("1")),
// Skips 1 as it is a url index!
entry(2, asList("2"))
);
assertThat(md.urlIndex()).isEqualTo(1);
}
@Test
public void pathAndQueryParams() throws Exception {
MethodMetadata md = parseAndValidateMetadata(WithPathAndQueryParams.class,
"recordsByNameAndType", int.class, String.class,
String.class);
assertThat(md.template())
.hasQueries(entry("name", asList("{name}")), entry("type", asList("{type}")));
assertThat(md.indexToName()).containsExactly(
entry(0, asList("domainId")),
entry(1, asList("name")),
entry(2, asList("type"))
);
}
@Test
public void bodyWithTemplate() throws Exception {
MethodMetadata md = parseAndValidateMetadata(FormParams.class,
"login", String.class, String.class, String.class);
assertThat(md.template())
.hasBodyTemplate(
"%7B\"customer_name\": \"{customer_name}\", \"user_name\": \"{user_name}\", \"password\": \"{password}\"%7D");
}
@Test
public void formParamsParseIntoIndexToName() throws Exception {
MethodMetadata md = parseAndValidateMetadata(FormParams.class,
"login", String.class, String.class, String.class);
assertThat(md.formParams())
.containsExactly("customer_name", "user_name", "password");
assertThat(md.indexToName()).containsExactly(
entry(0, asList("customer_name")),
entry(1, asList("user_name")),
entry(2, asList("password"))
);
}
/**
* Body type is only for the body param.
*/
@Test
public void formParamsDoesNotSetBodyType() throws Exception {
MethodMetadata md = parseAndValidateMetadata(FormParams.class,
"login", String.class, String.class, String.class);
assertThat(md.bodyType()).isNull();
}
@Test
public void headerParamsParseIntoIndexToName() throws Exception {
MethodMetadata md = parseAndValidateMetadata(HeaderParams.class, "logout", String.class);
assertThat(md.template())
.hasHeaders(entry("Auth-Token", asList("{authToken}", "Foo")));
assertThat(md.indexToName())
.containsExactly(entry(0, asList("authToken")));
assertThat(md.formParams()).isEmpty();
}
@Test
public void headerParamsParseIntoIndexToNameNotAtStart() throws Exception {
MethodMetadata md = parseAndValidateMetadata(HeaderParamsNotAtStart.class, "logout", String.class);
assertThat(md.template())
.hasHeaders(entry("Authorization", asList("Bearer {authToken}", "Foo")));
assertThat(md.indexToName())
.containsExactly(entry(0, asList("authToken")));
assertThat(md.formParams()).isEmpty();
}
@Test
public void customExpander() throws Exception {
MethodMetadata md = parseAndValidateMetadata(CustomExpander.class, "date", Date.class);
assertThat(md.indexToExpanderClass())
.containsExactly(entry(0, DateToMillis.class));
}
@Test
public void slashAreEncodedWhenNeeded() throws Exception {
MethodMetadata md = parseAndValidateMetadata(SlashNeedToBeEncoded.class,
"getQueues", String.class);
assertThat(md.template().decodeSlash()).isFalse();
md = parseAndValidateMetadata(SlashNeedToBeEncoded.class, "getZone", String.class);
assertThat(md.template().decodeSlash()).isTrue();
}
interface Methods {
@RequestLine("POST /")
void post();
@RequestLine("PUT /")
void put();
@RequestLine("GET /")
void get();
@RequestLine("DELETE /")
void delete();
}
interface BodyParams {
@RequestLine("POST")
Response post(List<String> body);
@RequestLine("POST")
Response tooMany(List<String> body, List<String> body2);
}
interface CustomMethod {
@RequestLine("PATCH")
Response patch();
}
interface WithQueryParamsInPath {
@RequestLine("GET /")
Response none();
@RequestLine("GET /?Action=GetUser")
Response one();
@RequestLine("GET /?Action=GetUser&Version=2010-05-08")
Response two();
@RequestLine("GET /?Action=GetUser&Version=2010-05-08&limit=1")
Response three();
@RequestLine("GET /?flag&Action=GetUser&Version=2010-05-08")
Response twoAndOneEmpty();
@RequestLine("GET /?flag")
Response oneEmpty();
@RequestLine("GET /?flag&NoErrors")
Response twoEmpty();
}
interface BodyWithoutParameters {
@RequestLine("POST /")
@Headers("Content-Type: application/xml")
@Body("<v01:getAccountsListOfUser/>")
Response post();
}
@Headers("Content-Type: application/xml")
interface HeadersOnType {
@RequestLine("POST /")
@Body("<v01:getAccountsListOfUser/>")
Response post();
}
interface WithURIParam {
@RequestLine("GET /{1}/{2}")
Response uriParam(@Param("1") String one, URI endpoint, @Param("2") String two);
}
interface WithPathAndQueryParams {
@RequestLine("GET /domains/{domainId}/records?name={name}&type={type}")
Response recordsByNameAndType(@Param("domainId") int id, @Param("name") String nameFilter,
@Param("type") String typeFilter);
}
interface FormParams {
@RequestLine("POST /")
@Body("%7B\"customer_name\": \"{customer_name}\", \"user_name\": \"{user_name}\", \"password\": \"{password}\"%7D")
void login(
@Param("customer_name") String customer,
@Param("user_name") String user, @Param("password") String password);
}
interface HeaderParams {
@RequestLine("POST /")
@Headers({"Auth-Token: {authToken}", "Auth-Token: Foo"})
void logout(@Param("authToken") String token);
}
interface HeaderParamsNotAtStart {
@RequestLine("POST /")
@Headers({"Authorization: Bearer {authToken}", "Authorization: Foo"})
void logout(@Param("authToken") String token);
}
interface CustomExpander {
@RequestLine("POST /?date={date}")
void date(@Param(value = "date", expander = DateToMillis.class) Date date);
}
class DateToMillis implements Param.Expander {
@Override
public String expand(Object value) {
return String.valueOf(((Date) value).getTime());
}
}
interface SlashNeedToBeEncoded {
@RequestLine(value = "GET /api/queues/{vhost}", decodeSlash = false)
String getQueues(@Param("vhost") String vhost);
@RequestLine("GET /api/{zoneId}")
String getZone(@Param("ZoneId") String vhost);
}
@Headers("Foo: Bar")
interface SimpleParameterizedBaseApi<M> {
@RequestLine("GET /api/{zoneId}")
M get(@Param("key") String key);
}
interface SimpleParameterizedApi extends SimpleParameterizedBaseApi<String> {
}
@Test
public void simpleParameterizedBaseApi() throws Exception {
List<MethodMetadata> md = contract.parseAndValidatateMetadata(SimpleParameterizedApi.class);
assertThat(md).hasSize(1);
assertThat(md.get(0).configKey())
.isEqualTo("SimpleParameterizedApi#get(String)");
assertThat(md.get(0).returnType())
.isEqualTo(String.class);
assertThat(md.get(0).template())
.hasHeaders(entry("Foo", asList("Bar")));
}
@Test
public void parameterizedApiUnsupported() throws Exception {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Parameterized types unsupported: SimpleParameterizedBaseApi");
contract.parseAndValidatateMetadata(SimpleParameterizedBaseApi.class);
}
interface OverrideParameterizedApi extends SimpleParameterizedBaseApi<String> {
@Override
@RequestLine("GET /api/{zoneId}")
String get(@Param("key") String key);
}
@Test
public void overrideBaseApiUnsupported() throws Exception {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Overrides unsupported: OverrideParameterizedApi#get(String)");
contract.parseAndValidatateMetadata(OverrideParameterizedApi.class);
}
interface Child<T> extends SimpleParameterizedBaseApi<List<T>> {
}
interface GrandChild extends Child<String> {
}
@Test
public void onlySingleLevelInheritanceSupported() throws Exception {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Only single-level inheritance supported: GrandChild");
contract.parseAndValidatateMetadata(GrandChild.class);
}
@Headers("Foo: Bar")
interface ParameterizedBaseApi<K, M> {
@RequestLine("GET /api/{key}")
Entity<K, M> get(@Param("key") K key);
@RequestLine("POST /api")
Entities<K, M> getAll(Keys<K> keys);
}
static class Keys<K> {
List<K> keys;
}
static class Entity<K, M> {
K key;
M model;
}
static class Entities<K, M> {
private List<Entity<K, M>> entities;
}
@Headers("Version: 1")
interface ParameterizedApi extends ParameterizedBaseApi<String, Long> {
}
@Test
public void parameterizedBaseApi() throws Exception {
List<MethodMetadata> md = contract.parseAndValidatateMetadata(ParameterizedApi.class);
Map<String, MethodMetadata> byConfigKey = new LinkedHashMap<String, MethodMetadata>();
for (MethodMetadata m : md) {
byConfigKey.put(m.configKey(), m);
}
assertThat(byConfigKey)
.containsOnlyKeys("ParameterizedApi#get(String)", "ParameterizedApi#getAll(Keys)");
assertThat(byConfigKey.get("ParameterizedApi#get(String)").returnType())
.isEqualTo(new TypeToken<Entity<String, Long>>() {
}.getType());
assertThat(byConfigKey.get("ParameterizedApi#get(String)").template()).hasHeaders(
entry("Version", asList("1")),
entry("Foo", asList("Bar"))
);
assertThat(byConfigKey.get("ParameterizedApi#getAll(Keys)").returnType())
.isEqualTo(new TypeToken<Entities<String, Long>>() {
}.getType());
assertThat(byConfigKey.get("ParameterizedApi#getAll(Keys)").bodyType())
.isEqualTo(new TypeToken<Keys<String>>() {
}.getType());
assertThat(byConfigKey.get("ParameterizedApi#getAll(Keys)").template()).hasHeaders(
entry("Version", asList("1")),
entry("Foo", asList("Bar"))
);
}
@Headers("Authorization: {authHdr}")
interface ParameterizedHeaderExpandApi {
@RequestLine("GET /api/{zoneId}")
@Headers("Accept: application/json")
String getZone(@Param("zoneId") String vhost, @Param("authHdr") String authHdr);
}
@Test
public void parameterizedHeaderExpandApi() throws Exception {
List<MethodMetadata> md = contract.parseAndValidatateMetadata(ParameterizedHeaderExpandApi.class);
assertThat(md).hasSize(1);
assertThat(md.get(0).configKey())
.isEqualTo("ParameterizedHeaderExpandApi#getZone(String,String)");
assertThat(md.get(0).returnType())
.isEqualTo(String.class);
assertThat(md.get(0).template())
.hasHeaders(entry("Authorization", asList("{authHdr}")), entry("Accept", asList("application/json")));
// Ensure that the authHdr expansion was properly detected and did not create a formParam
assertThat(md.get(0).formParams())
.isEmpty();
}
@Test
public void parameterizedHeaderNotStartingWithCurlyBraceExpandApi() throws Exception {
List<MethodMetadata>
md =
contract.parseAndValidatateMetadata(
ParameterizedHeaderNotStartingWithCurlyBraceExpandApi.class);
assertThat(md).hasSize(1);
assertThat(md.get(0).configKey())
.isEqualTo("ParameterizedHeaderNotStartingWithCurlyBraceExpandApi#getZone(String,String)");
assertThat(md.get(0).returnType())
.isEqualTo(String.class);
assertThat(md.get(0).template())
.hasHeaders(entry("Authorization", asList("Bearer {authHdr}")),
entry("Accept", asList("application/json")));
// Ensure that the authHdr expansion was properly detected and did not create a formParam
assertThat(md.get(0).formParams())
.isEmpty();
}
@Headers("Authorization: Bearer {authHdr}")
interface ParameterizedHeaderNotStartingWithCurlyBraceExpandApi {
@RequestLine("GET /api/{zoneId}")
@Headers("Accept: application/json")
String getZone(@Param("zoneId") String vhost, @Param("authHdr") String authHdr);
}
@Headers("Authorization: {authHdr}")
interface ParameterizedHeaderBase {
}
interface ParameterizedHeaderExpandInheritedApi extends ParameterizedHeaderBase {
@RequestLine("GET /api/{zoneId}")
@Headers("Accept: application/json")
String getZoneAccept(@Param("zoneId") String vhost, @Param("authHdr") String authHdr);
@RequestLine("GET /api/{zoneId}")
String getZone(@Param("zoneId") String vhost, @Param("authHdr") String authHdr);
}
@Test
public void parameterizedHeaderExpandApiBaseClass() throws Exception {
List<MethodMetadata> mds = contract.parseAndValidatateMetadata(ParameterizedHeaderExpandInheritedApi.class);
Map<String, MethodMetadata> byConfigKey = new LinkedHashMap<String, MethodMetadata>();
for (MethodMetadata m : mds) {
byConfigKey.put(m.configKey(), m);
}
assertThat(byConfigKey)
.containsOnlyKeys("ParameterizedHeaderExpandInheritedApi#getZoneAccept(String,String)",
"ParameterizedHeaderExpandInheritedApi#getZone(String,String)");
MethodMetadata md = byConfigKey.get("ParameterizedHeaderExpandInheritedApi#getZoneAccept(String,String)");
assertThat(md.returnType())
.isEqualTo(String.class);
assertThat(md.template())
.hasHeaders(entry("Authorization", asList("{authHdr}")), entry("Accept", asList("application/json")));
// Ensure that the authHdr expansion was properly detected and did not create a formParam
assertThat(md.formParams())
.isEmpty();
md = byConfigKey.get("ParameterizedHeaderExpandInheritedApi#getZone(String,String)");
assertThat(md.returnType())
.isEqualTo(String.class);
assertThat(md.template())
.hasHeaders(entry("Authorization", asList("{authHdr}")));
assertThat(md.formParams())
.isEmpty();
}
private MethodMetadata parseAndValidateMetadata(Class<?> targetType, String method,
Class<?>... parameterTypes)
throws NoSuchMethodException {
return contract.parseAndValidateMetadata(targetType,
targetType.getMethod(method, parameterTypes));
}
interface MissingMethod {
@RequestLine("/path?queryParam={queryParam}")
Response updateSharing(@Param("queryParam") long queryParam, String bodyParam);
}
/** Let's help folks not lose time when they mistake request line for a URI! */
@Test
public void missingMethod() throws Exception {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("RequestLine annotation didn't start with an HTTP verb on method updateSharing");
contract.parseAndValidatateMetadata(MissingMethod.class);
}
}