-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUserControllerIntegrationTest.java
More file actions
943 lines (748 loc) · 38.7 KB
/
UserControllerIntegrationTest.java
File metadata and controls
943 lines (748 loc) · 38.7 KB
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
/*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* 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 org.breedinginsight.api.v1.controller;
import static io.micronaut.http.HttpRequest.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.google.gson.*;
import io.kowalski.fannypack.FannyPack;
import io.micronaut.http.*;
import io.micronaut.http.client.RxHttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.http.netty.cookies.NettyCookie;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import io.micronaut.test.annotation.MockBean;
import io.reactivex.Flowable;
import org.opentest4j.AssertionFailedError;
import lombok.SneakyThrows;
import org.breedinginsight.DatabaseTest;
import org.breedinginsight.TestUtils;
import org.breedinginsight.api.auth.AuthenticatedUser;
import org.breedinginsight.api.model.v1.request.query.FilterRequest;
import org.breedinginsight.api.model.v1.request.query.SearchRequest;
import org.breedinginsight.api.v1.controller.metadata.SortOrder;
import org.breedinginsight.dao.db.tables.daos.*;
import org.breedinginsight.dao.db.tables.pojos.*;
import org.breedinginsight.model.User;
import org.breedinginsight.services.UserService;
import org.breedinginsight.utilities.email.EmailUtil;
import org.jooq.DSLContext;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.*;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
/*
* Integration tests of UserController endpoints using test database and mocked Micronaut authentication
*/
@MicronautTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class UserControllerIntegrationTest extends DatabaseTest {
private String testUserUUID;
private List<ProgramEntity> validPrograms;
private RoleEntity validRole;
private AuthenticatedUser actingUser;
private Integer numUsers;
private List<ProgramUserRoleEntity> validProgramRoles;
@Inject
@Client("/${micronaut.bi.api.version}")
private RxHttpClient client;
private FannyPack fp = FannyPack.fill("src/test/resources/sql/UserControllerIntegrationTest.sql");
@Inject
private DSLContext dsl;
@Inject
private BiUserDao biUserDao;
@Inject
private SystemRoleDao systemRoleDao;
@Inject
private RoleDao roleDao;
@Inject
private ProgramDao programDao;
@Inject
private ProgramUserRoleDao programUserRoleDao;
@Inject
private UserService userService;
// Micronaut is naming this mock under 'orcid' for some reason.
@Named("")
@MockBean(bean = EmailUtil.class)
EmailUtil emailUtil() { return mock(EmailUtil.class); }
private BiUserEntity testUser;
private BiUserEntity otherTestUser;
private SystemRoleEntity validSystemRole;
private String invalidUUID = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
@BeforeAll
void setup() {
// Skip our emails
doNothing().when(emailUtil()).sendEmail(any(String.class), any(String.class), any(String.class));
// Insert our traits into the db
dsl.execute(fp.get("InsertProgram"));
dsl.execute(fp.get("InsertUserProgramAssociations"));
testUser = biUserDao.fetchByOauthId(TestTokenValidator.TEST_USER_ORCID).get(0);
otherTestUser = biUserDao.fetchByOauthId(TestTokenValidator.OTHER_TEST_USER_ORCID).get(0);
validSystemRole = systemRoleDao.findAll().get(0);
validRole = roleDao.findAll().get(0);
validPrograms = programDao.findAll();
validProgramRoles = programUserRoleDao.fetchByUserId(testUser.getId());
actingUser = getActingUser();
dsl.execute(fp.get("InsertSystemRoleAdmin"), testUser.getId().toString());
dsl.execute(fp.get("InsertSystemRoleAdmin"), otherTestUser.getId().toString());
}
public AuthenticatedUser getActingUser() {
UUID id = testUser.getId();
List<String> systemRoles = new ArrayList<>();
systemRoles.add(validRole.getDomain());
return new AuthenticatedUser("test_user", systemRoles, id, new ArrayList<>());
}
@Test
@Order(1)
public void getUsersExistingId() {
// TODO: depends on db setup
Flowable<HttpResponse<String>> call = client.exchange(
GET("/users/" + testUser.getId()).cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
JsonObject result = JsonParser.parseString(response.body()).getAsJsonObject().getAsJsonObject("result");
assertEquals(testUser.getId().toString(), result.get("id").getAsString(), "Wrong id");
assertEquals("Test User", result.get("name").getAsString(), "Wrong name");
assertEquals(testUser.getOauthId(), result.get("oauthId").getAsString(), "Wrong OAuthId");
assertEquals("test@test.com", result.get("email").getAsString(), "Wrong email");
JsonArray resultRoles = (JsonArray) result.get("systemRoles");
assertEquals(true, resultRoles != null, "Empty roles list was not returned.");
assertEquals(true, resultRoles.size() == 1, "Roles list was not empty.");
JsonArray resultProgramRoles = (JsonArray) result.get("programRoles");
assertEquals(true, resultProgramRoles != null, "Empty programs list was not returned.");
assertEquals(true, resultProgramRoles.size() == 2, "Wrong number of programs.");
Boolean programOneSeen = false;
Boolean programTwoSeen = false;
for (JsonElement resultProgramRole: resultProgramRoles) {
JsonObject jsonProgram = resultProgramRole.getAsJsonObject().get("program").getAsJsonObject();
ProgramEntity programEntity;
ProgramUserRoleEntity programUserRoleEntity;
if (jsonProgram.get("id").getAsString().equals(validPrograms.get(0).getId().toString())){
programOneSeen = true;
programEntity = validPrograms.get(0);
} else if (jsonProgram.get("id").getAsString().equals(validPrograms.get(1).getId().toString())) {
programTwoSeen = true;
programEntity = validPrograms.get(1);
} else {
throw new AssertionFailedError("Program does not match any programs in database");
}
programUserRoleEntity = validProgramRoles.stream().filter((programUserRoleEntity1 ->
programUserRoleEntity1.getProgramId().toString().equals(programEntity.getId().toString())))
.collect(Collectors.toList()).get(0);
assertEquals(programEntity.getName(), jsonProgram.get("name").getAsString(), "Program names do not match");
assertEquals(programUserRoleEntity.getActive(), resultProgramRole.getAsJsonObject().get("active").getAsBoolean(), "Role active status does not match");
}
if (!programOneSeen || !programTwoSeen) {
throw new AssertionFailedError("Both programs were not returned");
}
}
@Test
public void getUsersNotExistingId() {
Flowable<HttpResponse<String>> call = client.exchange(
GET("/users/e91f816b-b7aa-4444-9d00-3e25fdc00e15").cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.NOT_FOUND, e.getStatus());
}
@Test
@SneakyThrows
void postUsersRolesNotFound() {
String name = "Test User4";
String email = "test4@test.com";
String oAuthId = "0000-0000-0000-0000";
JsonObject requestBody = new JsonObject();
requestBody.addProperty("name", name);
requestBody.addProperty("email", email);
requestBody.addProperty("oauthId", oAuthId);
JsonObject role = new JsonObject();
role.addProperty("id", invalidUUID);
JsonArray roles = new JsonArray();
roles.add(role);
requestBody.add("systemRoles", roles);
Flowable<HttpResponse<String>> call = client.exchange(
POST("/users", requestBody.toString())
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, e.getStatus());
}
@Test
public void postUsersMissingEmail() {
String name = "Test User2";
JsonObject requestBody = new JsonObject();
requestBody.addProperty("name", name);
Flowable<HttpResponse<String>> call = client.exchange(
POST("/users", requestBody.toString())
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.BAD_REQUEST, e.getStatus());
}
@Test
public void postUsersMissingName() {
String email = "test@test.com";
JsonObject requestBody = new JsonObject();
requestBody.addProperty("email", email);
Flowable<HttpResponse<String>> call = client.exchange(
POST("/users", requestBody.toString())
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.BAD_REQUEST, e.getStatus());
}
@Test
public void postUsersEmptyBody() {
Flowable<HttpResponse<String>> call = client.exchange(
POST("/users", "")
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.BAD_REQUEST, e.getStatus());
}
@Test
public void postUsersEmailAlreadyExists() {
JsonObject requestBody = new JsonObject();
requestBody.addProperty("name", "Test User");
requestBody.addProperty("email", "test@test.com");
Flowable<HttpResponse<String>> call = client.exchange(
POST("/users", requestBody.toString())
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.CONFLICT, e.getStatus());
}
@Test
@SneakyThrows
@Order(1)
void postUsersWithRolesSuccess() {
String name = "Test User3";
String email = "test3@test.com";
JsonObject requestBody = new JsonObject();
requestBody.addProperty("name", name);
requestBody.addProperty("email", email);
JsonObject role = new JsonObject();
role.addProperty("id", validSystemRole.getId().toString());
JsonArray roles = new JsonArray();
roles.add(role);
requestBody.add("systemRoles", roles);
Flowable<HttpResponse<String>> call = client.exchange(
POST("/users", requestBody.toString())
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
try {
JsonObject result = JsonParser.parseString(response.getBody().get()).getAsJsonObject().getAsJsonObject("result");
assertEquals(name, result.get("name").getAsString(), "Wrong name");
assertEquals(email, result.get("email").getAsString(), "Wrong email");
JsonArray resultRoles = (JsonArray) result.get("systemRoles");
assertEquals(true, resultRoles.size() == 1, "Wrong number of roles attached to user");
JsonObject adminRole = (JsonObject) resultRoles.get(0);
assertEquals(validSystemRole.getId().toString(), adminRole.get("id").getAsString(), "Inserted role id doesn't match what was passed.");
} catch (IllegalStateException e) {
Assertions.fail(e.getMessage());
}
}
@Test
@Order(1)
public void postUsersNoRolesSuccess() {
String name = "Test User2";
String email = "test2@test.com";
JsonObject requestBody = new JsonObject();
requestBody.addProperty("name", name);
requestBody.addProperty("email", email);
Flowable<HttpResponse<String>> call = client.exchange(
POST("/users", requestBody.toString())
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
try {
JsonObject result = JsonParser.parseString(response.getBody().get()).getAsJsonObject().getAsJsonObject("result");
assertEquals(name, result.get("name").getAsString(), "Wrong name");
assertEquals(email, result.get("email").getAsString(), "Wrong email");
JsonArray resultRoles = (JsonArray) result.get("systemRoles");
assertEquals(true, resultRoles != null, "Empty roles list was not returned.");
assertEquals(true, resultRoles.size() == 0, "Roles list was not empty.");
testUserUUID = result.get("id").getAsString();
} catch (IllegalStateException e) {
Assertions.fail(e.getMessage());
}
}
@Test
@Order(2)
public void getUsersAllExisting() {
Flowable<HttpResponse<String>> call = client.exchange(
GET("/users").cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
JsonArray data = JsonParser.parseString(response.body()).getAsJsonObject().getAsJsonObject("result").getAsJsonArray("data");
// TODO: depends on db setup
assertTrue(data.size() >= 1, "Wrong number users");
JsonObject exampleUser = (JsonObject) data.get(0);
JsonArray resultRoles = (JsonArray) exampleUser.get("systemRoles");
assertEquals(true, resultRoles != null, "Roles list was not returned.");
JsonArray resultProgramRoles = (JsonArray) exampleUser.get("programRoles");
assertEquals(true, resultProgramRoles != null, "Empty programs list was not returned.");
numUsers = data.size();
}
@Test
@Order(3)
public void putUsersEmailAlreadyExists() {
JsonObject requestBody = new JsonObject();
requestBody.addProperty("name", "Test User2");
requestBody.addProperty("email", "test@test.com");
Flowable<HttpResponse<String>> call = client.exchange(
PUT("/users/" + testUserUUID, requestBody.toString())
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.CONFLICT, e.getStatus());
}
@Test
@Order(3)
public void putUsersOwnEmailAlreadyExists() {
String name = "Test Update 5";
String email = "testedited@test.com";
JsonObject requestBody = new JsonObject();
requestBody.addProperty("name", name);
requestBody.addProperty("email", email);
Flowable<HttpResponse<String>> call = client.exchange(
PUT("/users/" + testUserUUID, requestBody.toString())
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "other-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
try {
JsonObject result = JsonParser.parseString(response.getBody().get()).getAsJsonObject().getAsJsonObject("result");
assertEquals(name, result.get("name").getAsString(), "Wrong name");
assertEquals(email, result.get("email").getAsString(), "Wrong email");
JsonArray resultRoles = (JsonArray) result.get("systemRoles");
assertEquals(true, resultRoles != null, "Empty roles list was not returned.");
assertEquals(true, resultRoles.size() == 0, "Roles list was not empty.");
} catch (IllegalStateException e) {
Assertions.fail(e.getMessage());
}
}
@Test
@Order(3)
public void putUsersEmptyBody() {
Flowable<HttpResponse<String>> call = client.exchange(
PUT("/users/" + testUserUUID, "")
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.BAD_REQUEST, e.getStatus());
}
@Test
@Order(3)
public void putUsersEmptyName() {
JsonObject requestBody = new JsonObject();
requestBody.addProperty("email", "emptyname@test.com");
Flowable<HttpResponse<String>> call = client.exchange(
PUT("/users/" + testUserUUID, requestBody.toString())
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.BAD_REQUEST, e.getStatus());
}
@Test
@SneakyThrows
void putUsersRolesNotExist() {
JsonObject requestBody = new JsonObject();
JsonObject role = new JsonObject();
role.addProperty("id", invalidUUID);
JsonArray roles = new JsonArray();
roles.add(role);
requestBody.add("systemRoles", roles);
Flowable<HttpResponse<String>> call = client.exchange(
PUT("/users/" + otherTestUser.getId().toString() + "/roles", requestBody.toString())
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, e.getStatus());
}
@Test
@SneakyThrows
@Order(3)
void putUserRolesOwnRoles() {
JsonObject requestBody = new JsonObject();
JsonObject role = new JsonObject();
role.addProperty("id", validSystemRole.getId().toString());
JsonArray roles = new JsonArray();
roles.add(role);
requestBody.add("systemRoles", roles);
Flowable<HttpResponse<String>> call = client.exchange(
PUT("/users/" + testUser.getId().toString() + "/roles", requestBody.toString())
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.FORBIDDEN, e.getStatus(), "Unauthorized exception not returned.");
}
@Test
@SneakyThrows
@Order(3)
void putUserRolesOtherUserSuccess() {
JsonObject requestBody = new JsonObject();
JsonObject role = new JsonObject();
role.addProperty("id", validSystemRole.getId().toString());
JsonArray roles = new JsonArray();
roles.add(role);
requestBody.add("systemRoles", roles);
Flowable<HttpResponse<String>> call = client.exchange(
PUT("/users/" + otherTestUser.getId().toString() + "/roles", requestBody.toString())
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
JsonObject result = JsonParser.parseString(response.getBody().get()).getAsJsonObject().getAsJsonObject("result");
// System roles should not be modified
JsonArray resultRoles = (JsonArray) result.get("systemRoles");
assertEquals(true, resultRoles != null, "Empty roles list was not returned.");
assertEquals(true, resultRoles.size() == 1, "Roles list has wrong number of entries.");
JsonObject resultRole = (JsonObject) resultRoles.get(0);
assertEquals(validSystemRole.getId().toString(), resultRole.get("id").getAsString(), "Wrong role id was returned.");
}
@Test
@Order(4)
public void getUserInfoRegisteredUser() {
Flowable<HttpResponse<String>> call = client.exchange(
GET("/userinfo").cookie(new NettyCookie("phylo-token", "other-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
JsonObject result = JsonParser.parseString(response.body()).getAsJsonObject().getAsJsonObject("result");
assertEquals(otherTestUser.getName(), result.get("name").getAsString(), "Wrong name");
assertEquals(otherTestUser.getOauthId(), result.get("oauthId").getAsString(), "Wrong orcid");
assertEquals(otherTestUser.getEmail(), result.get("email").getAsString(), "Wrong email");
assertEquals(otherTestUser.getId().toString(), result.get("id").getAsString(), "Wrong id");
JsonArray resultRoles = (JsonArray) result.get("systemRoles");
assertEquals(true, resultRoles != null, "Empty roles list was not returned.");
assertEquals(true, resultRoles.size() == 1, "One role was not returned in response");
JsonObject role = (JsonObject) resultRoles.get(0);
assertEquals(validSystemRole.getId().toString(), role.get("id").getAsString(), "Role id was incorrect");
assertEquals(validSystemRole.getDomain(), role.get("domain").getAsString(), "Role domain was incorrect");
JsonArray resultProgramRoles = (JsonArray) result.get("programRoles");
assertEquals(true, resultProgramRoles != null, "Empty roles list was not returned.");
assertEquals(2, resultProgramRoles.size(), "Wrong number of program roles.");
Boolean programOneSeen = false;
Boolean programTwoSeen = false;
for (JsonElement resultProgramRole: resultProgramRoles) {
JsonObject jsonProgram = resultProgramRole.getAsJsonObject().get("program").getAsJsonObject();
ProgramEntity programEntity;
ProgramUserRoleEntity programUserRoleEntity;
if (jsonProgram.get("id").getAsString().equals(validPrograms.get(0).getId().toString())){
programOneSeen = true;
programEntity = validPrograms.get(0);
} else if (jsonProgram.get("id").getAsString().equals(validPrograms.get(1).getId().toString())) {
programTwoSeen = true;
programEntity = validPrograms.get(1);
} else {
throw new AssertionFailedError("Program does not match any programs in database");
}
programUserRoleEntity = validProgramRoles.stream().filter((programUserRoleEntity1 ->
programUserRoleEntity1.getProgramId().toString().equals(programEntity.getId().toString())))
.collect(Collectors.toList()).get(0);
assertEquals(programEntity.getName(), jsonProgram.get("name").getAsString(), "Program names do not match");
assertEquals(programUserRoleEntity.getActive(), resultProgramRole.getAsJsonObject().get("active").getAsBoolean(), "Role active status does not match");
}
if (!programOneSeen || !programTwoSeen) {
throw new AssertionFailedError("Both programs were not returned");
}
}
@Test
@Order(4)
public void putUserRolesNullSuccess() {
JsonObject requestBody = new JsonObject();
Flowable<HttpResponse<String>> call = client.exchange(
PUT("/users/" + otherTestUser.getId().toString() + "/roles", requestBody.toString())
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.BAD_REQUEST, e.getStatus(), "Unauthorized exception not returned.");
}
@Test
@SneakyThrows
@Order(4)
void putUserRolesDuplicateRoles() {
JsonObject requestBody = new JsonObject();
JsonObject role = new JsonObject();
role.addProperty("id", validSystemRole.getId().toString());
JsonArray roles = new JsonArray();
roles.add(role);
roles.add(role);
requestBody.add("systemRoles", roles);
Flowable<HttpResponse<String>> call = client.exchange(
PUT("/users/" + otherTestUser.getId().toString() + "/roles", requestBody.toString())
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
JsonObject result = JsonParser.parseString(response.getBody().get()).getAsJsonObject().getAsJsonObject("result");
// System roles should not be modified
JsonArray resultRoles = (JsonArray) result.get("systemRoles");
assertEquals(true, resultRoles != null, "Empty roles list was not returned.");
assertEquals(true, resultRoles.size() == 1, "Roles list did not have 1 entry in it.");
}
@Test
@SneakyThrows
@Order(4)
void putUsersRolesEmptyRoles() {
JsonObject requestBody = new JsonObject();
JsonArray roles = new JsonArray();
requestBody.add("systemRoles", roles);
Flowable<HttpResponse<String>> call = client.exchange(
PUT("/users/" + otherTestUser.getId().toString() + "/roles", requestBody.toString())
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
JsonObject result = JsonParser.parseString(response.getBody().get()).getAsJsonObject().getAsJsonObject("result");
// System roles should not be modified
JsonArray resultRoles = (JsonArray) result.get("systemRoles");
assertEquals(true, resultRoles != null, "Empty roles list was not returned.");
assertEquals(true, resultRoles.size() == 0, "Roles list was not empty.");
}
@Test
public void putUsersNotExistingId() {
JsonObject requestBody = new JsonObject();
requestBody.addProperty("name", "Test User2");
requestBody.addProperty("email", "test@test.com");
Flowable<HttpResponse<String>> call = client.exchange(
PUT("/users/e91f816b-b7aa-4444-9d00-3e25fdc00e15", requestBody.toString())
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.NOT_FOUND, e.getStatus());
}
@Test
@SneakyThrows
@Order(4)
public void archiveUserActiveInProgram() {
Flowable<HttpResponse<String>> call = client.exchange(
DELETE("/users/" + testUserUUID).cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
}
@Test
@SneakyThrows
@Order(4)
public void archiveUserSelf() {
Flowable<HttpResponse<String>> call = client.exchange(
DELETE("/users/" + otherTestUser.getId()).cookie(new NettyCookie("phylo-token", "other-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.FORBIDDEN, e.getStatus());
}
@Test
@Order(4)
public void archiveUsersNoActivePrograms() {
// Add test user to that program
Flowable<HttpResponse<String>> call = client.exchange(
DELETE("/users/"+testUserUUID).cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
}
@Test
public void archiveUsersNotExistingId() {
Flowable<HttpResponse<String>> call = client.exchange(
DELETE("/users/e91f816b-b7aa-4e89-9d00-3e25fdc00e14").cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> {
HttpResponse<String> response = call.blockingFirst();
});
assertEquals(HttpStatus.NOT_FOUND, e.getStatus());
}
@Test
@Order(5)
public void getUsersInactiveNotReturned() {
Flowable<HttpResponse<String>> call = client.exchange(
GET("/users").cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
JsonArray data = JsonParser.parseString(response.body()).getAsJsonObject().getAsJsonObject("result").getAsJsonArray("data");
// TODO: depends on db setup
assertEquals(numUsers - 1, data.size(), "Wrong number users");
for (JsonElement jsonUser : data.getAsJsonArray()){
JsonObject exampleUser = (JsonObject) jsonUser;
// Work around for the system user
if (exampleUser.get("id") != null){
assertNotEquals(testUserUUID, exampleUser.get("id").toString(), "Inactive user was returned");
}
}
}
@Test
@Order(6)
public void getUserInfoInactiveProgramsNotReturned() {
String testProgramName = "Test Program";
// Deactive program
dsl.execute(fp.get("DeactivateProgram"));
Flowable<HttpResponse<String>> call = client.exchange(
GET("/userinfo").cookie(new NettyCookie("phylo-token", "other-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
JsonObject result = JsonParser.parseString(response.body()).getAsJsonObject().getAsJsonObject("result");
JsonArray resultProgramRoles = (JsonArray) result.get("programRoles");
assertEquals(true, resultProgramRoles != null, "Empty roles list was not returned.");
assertEquals(1, resultProgramRoles.size(), "Deactivated program was returned in roles");
JsonObject jsonProgram = resultProgramRoles.get(0).getAsJsonObject().get("program").getAsJsonObject();
assertNotEquals(testProgramName, jsonProgram.get("name").getAsString(), "Deactivated program was included in roles");
}
@Test
@Order(7)
public void getUsersInactiveProgramsNotReturned() {
Flowable<HttpResponse<String>> call = client.exchange(
GET("/users").cookie(new NettyCookie("phylo-token", "other-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
JsonObject result = JsonParser.parseString(response.body()).getAsJsonObject().getAsJsonObject("result");
Boolean testUserSeen = false;
for (JsonElement resultUser: result.get("data").getAsJsonArray()) {
JsonObject jsonUser = (JsonObject) resultUser;
if (jsonUser.get("id") != null){
if (jsonUser.get("id").getAsString().equals(otherTestUser.getId().toString())){
testUserSeen = true;
assertEquals(1, jsonUser.get("programRoles").getAsJsonArray().size(), "Deactivated program was included in roles");
}
}
}
if (!testUserSeen) {
throw new AssertionFailedError("User was not seen in the response");
}
}
@Test
@Order(7)
public void getUserInactiveProgramsNotReturned() {
Flowable<HttpResponse<String>> call = client.exchange(
GET("/users/" + otherTestUser.getId().toString()).cookie(new NettyCookie("phylo-token", "other-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
JsonObject result = JsonParser.parseString(response.body()).getAsJsonObject().getAsJsonObject("result");
JsonArray resultProgramRoles = (JsonArray) result.get("programRoles");
assertEquals(true, resultProgramRoles != null, "Empty roles list was not returned.");
assertEquals(1, resultProgramRoles.size(), "Deactivated program was returned in roles");
}
@Test
@Order(9)
public void getUsersQuery() {
dsl.execute(fp.get("InsertManyUsers"));
List<User> allUsers = userService.getAll();
Flowable<HttpResponse<String>> call = client.exchange(
GET("/users?sortField=programs&sortOrder=ASC").cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
JsonObject result = JsonParser.parseString(response.body()).getAsJsonObject().getAsJsonObject("result");
JsonArray data = result.get("data").getAsJsonArray();
assertEquals(allUsers.size(), data.size(), "Wrong page size");
TestUtils.checkStringListSorting(getPrograms(data), SortOrder.ASC);
JsonObject pagination = JsonParser.parseString(response.body()).getAsJsonObject().getAsJsonObject("metadata").getAsJsonObject("pagination");
assertEquals(1, pagination.get("totalPages").getAsInt(), "Wrong number of pages");
assertEquals(allUsers.size(), pagination.get("totalCount").getAsInt(), "Wrong total count");
assertEquals(1, pagination.get("currentPage").getAsInt(), "Wrong current page");
}
@Test
@Order(10)
public void searchUsers() {
SearchRequest searchRequest = new SearchRequest();
searchRequest.setFilters(new ArrayList<>());
searchRequest.getFilters().add(new FilterRequest("programs", "test program2"));
Flowable<HttpResponse<String>> call = client.exchange(
POST("/users/search?page=1&pageSize=20&sortField=name&sortOrder=DESC", searchRequest).cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
JsonObject result = JsonParser.parseString(response.body()).getAsJsonObject().getAsJsonObject("result");
JsonArray data = result.get("data").getAsJsonArray();
// Expect user2, user20->user29
assertEquals(11, data.size(), "Wrong page size");
TestUtils.checkStringSorting(data, "name", SortOrder.DESC);
}
private List<List<String>> getPrograms(JsonArray data) {
List<List<String>> roleResults = new ArrayList<>();
for (JsonElement el : data) {
JsonObject programUser = (JsonObject) el;
JsonArray programRoles = programUser.get("programRoles").getAsJsonArray();
List<String> userRoles = new ArrayList<>();
for (JsonElement roleEl : programRoles) {
JsonObject role = (JsonObject) roleEl;
userRoles.add(role.get("program").getAsJsonObject().get("name").getAsString());
}
Collections.sort(userRoles);
roleResults.add(userRoles);
}
return roleResults;
}
}