This repository has been archived by the owner on Aug 20, 2021. It is now read-only.
/
ApiService_ExportAsJsonTest.java
394 lines (336 loc) · 17.5 KB
/
ApiService_ExportAsJsonTest.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
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.management.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.PropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import io.gravitee.common.http.HttpMethod;
import io.gravitee.definition.jackson.datatype.GraviteeMapper;
import io.gravitee.definition.model.*;
import io.gravitee.definition.model.endpoint.HttpEndpoint;
import io.gravitee.management.model.*;
import io.gravitee.management.model.api.ApiEntity;
import io.gravitee.management.model.permissions.SystemRole;
import io.gravitee.management.service.impl.ApiServiceImpl;
import io.gravitee.management.service.jackson.filter.ApiPermissionFilter;
import io.gravitee.management.service.jackson.ser.api.*;
import io.gravitee.repository.exceptions.TechnicalException;
import io.gravitee.repository.management.api.ApiRepository;
import io.gravitee.repository.management.api.MembershipRepository;
import io.gravitee.repository.management.model.Api;
import io.gravitee.repository.management.model.Membership;
import io.gravitee.repository.management.model.MembershipReferenceType;
import io.gravitee.repository.management.model.RoleScope;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.internal.util.collections.Sets;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.context.ApplicationContext;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.when;
/**
* @author Azize Elamrani (azize.elamrani at graviteesource.com)
* @author Nicolas Geraud (nicolas.geraud at graviteesource.com)
* @author GraviteeSource Team
*/
@RunWith(MockitoJUnitRunner.class)
public class ApiService_ExportAsJsonTest {
private static final String API_ID = "id-api";
@InjectMocks
private ApiServiceImpl apiService = new ApiServiceImpl();
@Mock
private ApiRepository apiRepository;
@Mock
private MembershipRepository membershipRepository;
@Spy
private ObjectMapper objectMapper = new GraviteeMapper();
@Mock
private MembershipService membershipService;
@Mock
private PageService pageService;
@Mock
private UserService userService;
@Mock
private PlanService planService;
@Mock
private GroupService groupService;
@Mock
private ApplicationContext applicationContext;
@Before
public void setUp() throws TechnicalException {
PropertyFilter apiMembershipTypeFilter = new ApiPermissionFilter();
objectMapper.setFilterProvider(new SimpleFilterProvider(Collections.singletonMap("apiMembershipTypeFilter", apiMembershipTypeFilter)));
// register API Entity serializers
when(applicationContext.getBean(MembershipService.class)).thenReturn(membershipService);
when(applicationContext.getBean(PlanService.class)).thenReturn(planService);
when(applicationContext.getBean(PageService.class)).thenReturn(pageService);
when(applicationContext.getBean(GroupService.class)).thenReturn(groupService);
when(applicationContext.getBean(UserService.class)).thenReturn(userService);
ApiCompositeSerializer apiCompositeSerializer = new ApiCompositeSerializer();
ApiSerializer apiDefaultSerializer = new ApiDefaultSerializer();
apiDefaultSerializer.setApplicationContext(applicationContext);
//V_1_15
ApiSerializer apiPrior115VersionSerializer = new Api1_15VersionSerializer();
apiPrior115VersionSerializer.setApplicationContext(applicationContext);
//V_1_20
ApiSerializer apiPrior120VersionSerializer = new Api1_20VersionSerializer();
apiPrior120VersionSerializer.setApplicationContext(applicationContext);
apiCompositeSerializer.setSerializers(Arrays.asList(apiDefaultSerializer, apiPrior115VersionSerializer, apiPrior120VersionSerializer));
SimpleModule module = new SimpleModule();
module.addSerializer(ApiEntity.class, apiCompositeSerializer);
objectMapper.registerModule(module);
Api api = new Api();
api.setId(API_ID);
api.setDescription("Gravitee.io");
// set proxy
Proxy proxy = new Proxy();
proxy.setContextPath("/test");
proxy.setStripContextPath(false);
Logging logging = new Logging();
logging.setMode(LoggingMode.CLIENT_PROXY);
logging.setCondition("condition");
proxy.setLogging(logging);
EndpointGroup endpointGroup = new EndpointGroup();
endpointGroup.setName("default-group");
Endpoint endpoint = new HttpEndpoint("default", "http://test");
endpointGroup.setEndpoints(Collections.singleton(endpoint));
LoadBalancer loadBalancer = new LoadBalancer();
loadBalancer.setType(LoadBalancerType.ROUND_ROBIN);
endpointGroup.setLoadBalancer(loadBalancer);
proxy.setGroups(Collections.singleton(endpointGroup));
try {
io.gravitee.definition.model.Api apiDefinition = new io.gravitee.definition.model.Api();
apiDefinition.setPaths(Collections.emptyMap());
apiDefinition.setProxy(proxy);
ResponseTemplates responseTemplates = new ResponseTemplates();
ResponseTemplate responseTemplate = new ResponseTemplate();
responseTemplate.setStatusCode(400);
responseTemplate.setBody("{\"bad\":\"news\"}");
responseTemplates.setTemplates(Collections.singletonMap("*/*", responseTemplate));
apiDefinition.setResponseTemplates(Collections.singletonMap("API_KEY_MISSING", responseTemplates));
String definition = objectMapper.writeValueAsString(apiDefinition);
api.setDefinition(definition);
} catch (Exception e) {
// ignore
}
when(apiRepository.findById(API_ID)).thenReturn(Optional.of(api));
PageEntity page = new PageEntity();
page.setName("My Title");
page.setOrder(1);
page.setType(PageType.MARKDOWN.toString());
page.setContent("Read the doc");
when(pageService.search(any())).thenReturn(Collections.singletonList(page));
Membership membership = new Membership();
membership.setUserId("johndoe");
membership.setReferenceId(API_ID);
membership.setReferenceType(MembershipReferenceType.API);
membership.setRoles(Collections.singletonMap(RoleScope.API.getId(), SystemRole.PRIMARY_OWNER.name()));
when(membershipRepository.findByReferenceAndRole(eq(MembershipReferenceType.API), eq(API_ID), any(), any()))
.thenReturn(Collections.singleton(membership));
MemberEntity memberEntity = new MemberEntity();
memberEntity.setId(membership.getUserId());
memberEntity.setRole(SystemRole.PRIMARY_OWNER.name());
when(membershipService.getMembers(eq(MembershipReferenceType.API), eq(API_ID), eq(RoleScope.API)))
.thenReturn(Collections.singleton(memberEntity));
UserEntity userEntity = new UserEntity();
userEntity.setId(memberEntity.getId());
userEntity.setSource(userEntity.getId() + "-source");
userEntity.setSourceId(userEntity.getId() + "-sourceId");
when(userService.findById(memberEntity.getId())).thenReturn(userEntity);
api.setGroups(Collections.singleton("my-group"));
GroupEntity groupEntity = new GroupEntity();
groupEntity.setId("my-group");
groupEntity.setName("My Group");
when(groupService.findByIds(api.getGroups())).thenReturn(Collections.singleton(groupEntity));
PlanEntity publishedPlan = new PlanEntity();
publishedPlan.setId("plan-id");
publishedPlan.setApis(Collections.singleton(API_ID));
publishedPlan.setDescription("free plan");
publishedPlan.setType(PlanType.API);
publishedPlan.setSecurity(PlanSecurityType.API_KEY);
publishedPlan.setValidation(PlanValidationType.AUTO);
publishedPlan.setStatus(PlanStatus.PUBLISHED);
Map<String, Path> paths = new HashMap<>();
Path path = new Path();
path.setPath("/");
io.gravitee.definition.model.Rule rule = new io.gravitee.definition.model.Rule();
rule.setEnabled(true);
rule.setMethods(Sets.newSet(HttpMethod.GET));
Policy policy = new Policy();
policy.setName("rate-limit");
String ls = System.lineSeparator();
policy.setConfiguration("{" + ls +
" \"rate\": {" + ls +
" \"limit\": 1," + ls +
" \"periodTime\": 1," + ls +
" \"periodTimeUnit\": \"SECONDS\"" + ls +
" }" + ls +
" }");
rule.setPolicy(policy);
path.setRules(Collections.singletonList(rule));
paths.put("/", path);
publishedPlan.setPaths(paths);
PlanEntity closedPlan = new PlanEntity();
closedPlan.setId("closedPlan-id");
closedPlan.setApis(Collections.singleton(API_ID));
closedPlan.setDescription("free closedPlan");
closedPlan.setType(PlanType.API);
closedPlan.setSecurity(PlanSecurityType.API_KEY);
closedPlan.setValidation(PlanValidationType.AUTO);
closedPlan.setStatus(PlanStatus.CLOSED);
closedPlan.setPaths(paths);
Set<PlanEntity> set = new HashSet<>();
set.add(publishedPlan);
set.add(closedPlan);
when(planService.findByApi(API_ID)).thenReturn(set);
}
@Test
public void shouldConvertAsJsonForExport() throws TechnicalException, IOException {
shouldConvertAsJsonForExport(ApiSerializer.Version.DEFAULT, null);
}
@Test
public void shouldConvertAsJsonForExport_1_15() throws TechnicalException, IOException {
shouldConvertAsJsonForExport(ApiSerializer.Version.V_1_15, "1_15");
}
@Test
public void shouldConvertAsJsonForExport_1_20() throws TechnicalException, IOException {
shouldConvertAsJsonForExport(ApiSerializer.Version.V_1_20, "1_20");
}
@Test
public void shouldConvertAsJsonWithoutMembers() throws IOException {
shouldConvertAsJsonWithoutMembers(ApiSerializer.Version.DEFAULT, null);
}
@Test
public void shouldConvertAsJsonWithoutMembers_1_15() throws IOException {
shouldConvertAsJsonWithoutMembers(ApiSerializer.Version.V_1_15, "1_15");
}
@Test
public void shouldConvertAsJsonWithoutMembers_1_20() throws IOException {
shouldConvertAsJsonWithoutMembers(ApiSerializer.Version.V_1_20, "1_20");
}
@Test
public void shouldConvertAsJsonWithoutPages() throws IOException {
shouldConvertAsJsonWithoutPages(ApiSerializer.Version.DEFAULT, null);
}
@Test
public void shouldConvertAsJsonWithoutPages_1_15() throws IOException {
shouldConvertAsJsonWithoutPages(ApiSerializer.Version.V_1_15, "1_15");
}
@Test
public void shouldConvertAsJsonWithoutPages_1_20() throws IOException {
shouldConvertAsJsonWithoutPages(ApiSerializer.Version.V_1_20, "1_20");
}
@Test
public void shouldConvertAsJsonWithoutPlans() throws IOException {
shouldConvertAsJsonWithoutPlans(ApiSerializer.Version.DEFAULT, null);
}
@Test
public void shouldConvertAsJsonWithoutPlans_1_15() throws IOException {
shouldConvertAsJsonWithoutPlans(ApiSerializer.Version.V_1_15, "1_15");
}
@Test
public void shouldConvertAsJsonWithoutPlans_1_20() throws IOException {
shouldConvertAsJsonWithoutPlans(ApiSerializer.Version.V_1_20, "1_20");
}
@Test
public void shouldConvertAsJsonMultipleGroups_1_15() throws IOException, TechnicalException {
Api api = new Api();
api.setId(API_ID);
api.setDescription("Gravitee.io");
api.setGroups(Collections.singleton("my-group"));
// set proxy
Proxy proxy = new Proxy();
proxy.setContextPath("/test");
proxy.setStripContextPath(false);
EndpointGroup endpointGroup = new EndpointGroup();
endpointGroup.setName("default-group");
Endpoint endpoint = new HttpEndpoint("default", "http://test");
endpointGroup.setEndpoints(Collections.singleton(endpoint));
LoadBalancer loadBalancer = new LoadBalancer();
loadBalancer.setType(LoadBalancerType.ROUND_ROBIN);
endpointGroup.setLoadBalancer(loadBalancer);
EndpointGroup endpointGroup2 = new EndpointGroup();
endpointGroup2.setName("backup-group");
Endpoint endpoint2 = new HttpEndpoint("backup", "http://test2");
endpointGroup2.setEndpoints(Collections.singleton(endpoint2));
proxy.setGroups(new HashSet<>(Arrays.asList(endpointGroup, endpointGroup2)));
Failover failover = new Failover();
failover.setMaxAttempts(5);
failover.setRetryTimeout(2000);
proxy.setFailover(failover);
Cors cors = new Cors();
cors.setEnabled(true);
cors.setAccessControlAllowOrigin(Collections.singleton("*"));
cors.setAccessControlAllowHeaders(Collections.singleton("content-type"));
cors.setAccessControlAllowMethods(Collections.singleton("GET"));
proxy.setCors(cors);
try {
io.gravitee.definition.model.Api apiDefinition = new io.gravitee.definition.model.Api();
apiDefinition.setPaths(Collections.emptyMap());
apiDefinition.setProxy(proxy);
String definition = objectMapper.writeValueAsString(apiDefinition);
api.setDefinition(definition);
} catch (Exception e) {
// ignore
}
when(apiRepository.findById(API_ID)).thenReturn(Optional.of(api));
String jsonForExport = apiService.exportAsJson(API_ID, ApiSerializer.Version.V_1_15.getVersion(), SystemRole.PRIMARY_OWNER.name());
URL url = Resources.getResource("io/gravitee/management/service/export-convertAsJsonForExportMultipleEndpointGroups-1_15.json");
String expectedJson = Resources.toString(url, Charsets.UTF_8);
assertThat(jsonForExport).isNotNull();
assertThat(objectMapper.readTree(expectedJson)).isEqualTo(objectMapper.readTree(jsonForExport));
}
private void shouldConvertAsJsonForExport(ApiSerializer.Version version, String filename) throws TechnicalException, IOException {
String jsonForExport = apiService.exportAsJson(API_ID, version.getVersion(), SystemRole.PRIMARY_OWNER.name());
URL url = Resources.getResource("io/gravitee/management/service/export-convertAsJsonForExport" + (filename != null ? "-"+ filename : "") +".json");
String expectedJson = Resources.toString(url, Charsets.UTF_8);
assertThat(jsonForExport).isNotNull();
assertThat(objectMapper.readTree(expectedJson)).isEqualTo(objectMapper.readTree(jsonForExport));
}
private void shouldConvertAsJsonWithoutMembers(ApiSerializer.Version version, String filename) throws IOException {
String jsonForExport = apiService.exportAsJson(API_ID, version.getVersion(),SystemRole.PRIMARY_OWNER.name(), "members");
URL url = Resources.getResource("io/gravitee/management/service/export-convertAsJsonForExportWithoutMembers" + (filename != null ? "-"+ filename : "") +".json");
String expectedJson = Resources.toString(url, Charsets.UTF_8);
assertThat(jsonForExport).isNotNull();
assertThat(objectMapper.readTree(expectedJson)).isEqualTo(objectMapper.readTree(jsonForExport));
}
private void shouldConvertAsJsonWithoutPages(ApiSerializer.Version version, String filename) throws IOException {
String jsonForExport = apiService.exportAsJson(API_ID, version.getVersion(), SystemRole.PRIMARY_OWNER.name(), "pages");
URL url = Resources.getResource("io/gravitee/management/service/export-convertAsJsonForExportWithoutPages" + (filename != null ? "-"+ filename : "") +".json");
String expectedJson = Resources.toString(url, Charsets.UTF_8);
assertThat(jsonForExport).isNotNull();
assertThat(objectMapper.readTree(expectedJson)).isEqualTo(objectMapper.readTree(jsonForExport));
}
private void shouldConvertAsJsonWithoutPlans(ApiSerializer.Version version, String filename) throws IOException {
String jsonForExport = apiService.exportAsJson(API_ID, version.getVersion(), SystemRole.PRIMARY_OWNER.name(), "plans");
URL url = Resources.getResource("io/gravitee/management/service/export-convertAsJsonForExportWithoutPlans" + (filename != null ? "-"+ filename : "") +".json");
String expectedJson = Resources.toString(url, Charsets.UTF_8);
assertThat(jsonForExport).isNotNull();
assertThat(objectMapper.readTree(expectedJson)).isEqualTo(objectMapper.readTree(jsonForExport));
}
}