-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgramControllerIntegrationTest.java
More file actions
2529 lines (2046 loc) · 109 KB
/
ProgramControllerIntegrationTest.java
File metadata and controls
2529 lines (2046 loc) · 109 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
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
/*
* 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 ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.*;
import io.kowalski.fannypack.FannyPack;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MediaType;
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.BrAPITest;
import org.breedinginsight.TestUtils;
import org.breedinginsight.api.auth.AuthenticatedUser;
import org.breedinginsight.api.model.v1.request.*;
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.ProgramDao;
import org.breedinginsight.dao.db.tables.pojos.ProgramEntity;
import org.breedinginsight.daos.ProgramUserDAO;
import org.breedinginsight.daos.UserDAO;
import org.breedinginsight.model.*;
import org.breedinginsight.services.*;
import org.breedinginsight.utilities.email.EmailUtil;
import org.geojson.Feature;
import org.geojson.Point;
import org.jooq.DSLContext;
import org.junit.jupiter.api.*;
import javax.inject.Inject;
import javax.inject.Named;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.stream.Collectors;
import static io.micronaut.http.HttpRequest.*;
import static org.breedinginsight.TestUtils.getProgramById;
import static org.breedinginsight.TestUtils.insertAndFetchTestProgram;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
@MicronautTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class ProgramControllerIntegrationTest extends BrAPITest {
private FannyPack fp;
private FannyPack brapiFp;
private FannyPack securityFp;
private ProgramEntity validProgram;
private ProgramEntity validProgramB;
private Program otherProgram;
private User validUser;
private Species validSpecies;
private Role validRole;
private ProgramLocation validLocation;
private Country validCountry;
private EnvironmentType validEnvironment;
private Accessibility validAccessibility;
private Topography validTopography;
private User testUser;
private User otherUser;
private AuthenticatedUser actingUser;
private String invalidUUID = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
private String invalidProgram = invalidUUID;
private String invalidUser = invalidUUID;
private String invalidRole = invalidUUID;
private String invalidSpecies = invalidUUID;
private String invalidLocation= invalidUUID;
private String invalidCountry = invalidUUID;
private String invalidEnvironment = invalidUUID;
private String invalidAccessibility = invalidUUID;
private String invalidTopography = invalidUUID;
private Gson gson = new GsonBuilder().registerTypeAdapter(OffsetDateTime.class, (JsonDeserializer<OffsetDateTime>)
(json, type, context) -> OffsetDateTime.parse(json.getAsString()))
.create();
private ObjectMapper objMapper = new ObjectMapper();
private ListAppender<ILoggingEvent> loggingEventListAppender;
@Inject
private UserService userService;
@Inject
private ProgramService programService;
@Inject
private SpeciesService speciesService;
@Inject
private RoleService roleService;
@Inject
private ProgramUserService programUserService;
@Inject
private ProgramLocationService programLocationService;
@Inject
private CountryService countryService;
@Inject
private AccessibilityService accessibilityService;
@Inject
private EnvironmentTypeService environmentTypeService;
@Inject
private TopographyService topographyService;
@Inject
private DSLContext dsl;
@Inject
private ProgramDao programDao;
@Inject
private ProgramUserDAO programUserDAO;
@Inject
private UserDAO userDAO;
@Inject
@Client("/${micronaut.bi.api.version}")
private RxHttpClient client;
// Micronaut is naming this mock under 'orcid' for some reason.
@Named("")
@MockBean(bean = EmailUtil.class)
EmailUtil emailUtil() { return mock(EmailUtil.class); }
@BeforeAll
void setup() throws Exception {
// Skip our emails
doNothing().when(emailUtil()).sendEmail(any(String.class), any(String.class), any(String.class));
brapiFp = FannyPack.fill("src/test/resources/sql/brapi/species.sql");
fp = FannyPack.fill("src/test/resources/sql/ProgramControllerIntegrationTest.sql");
securityFp = FannyPack.fill("src/test/resources/sql/ProgramSecuredAnnotationRuleIntegrationTest.sql");
// Insert system roles
testUser = userDAO.getUserByOAuthId(TestTokenValidator.TEST_USER_ORCID).get();
otherUser = userDAO.getUserByOAuthId(TestTokenValidator.OTHER_TEST_USER_ORCID).get();
dsl.execute(securityFp.get("InsertSystemRoleAdmin"), testUser.getId().toString());
super.getBrapiDsl().execute(brapiFp.get("InsertSpecies"));
Optional<User> optionalUser = userService.getByOAuthId(TestTokenValidator.TEST_USER_ORCID);
testUser = optionalUser.get();
// Get species for tests
Species species = getTestSpecies();
validSpecies = species;
// Get role for tests
validRole = getTestRole();
validCountry = getTestCountry();
validAccessibility = getTestAccessibility();
validEnvironment = getTestEnvironment();
validTopography = getTestTopography();
// Insert and get user for tests
try {
validUser = fetchTestUser();
} catch (Exception e){
throw new Exception(e.toString());
}
actingUser = getActingUser();
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.commonName(validSpecies.getCommonName())
.id(validSpecies.getId())
.build();
ProgramRequest programRequest = ProgramRequest.builder()
.name("Other Test Program")
.abbreviation("test")
.documentationUrl("localhost:8080")
.objective("To test things")
.species(speciesRequest)
.key("OT")
.build();
otherProgram = insertAndFetchTestProgram(gson, client, programRequest);
dsl.execute(fp.get("InsertOtherProgramObservationLevel"));
dsl.execute(securityFp.get("InsertProgramRolesBreeder"), testUser.getId().toString(), otherProgram.getId().toString());
// Insert and get location for tests
validLocation = insertAndFetchTestLocation();
}
public ProgramLocation insertAndFetchTestLocation() throws Exception {
CountryRequest countryRequest = CountryRequest.builder()
.id(validCountry.getId())
.build();
NameIdRequest accessibilityRequest = NameIdRequest.builder()
.id(validAccessibility.getId())
.build();
NameIdRequest environmentRequest = NameIdRequest.builder()
.id(validEnvironment.getId())
.build();
NameIdRequest topographyRequest = NameIdRequest.builder()
.id(validTopography.getId())
.build();
Feature coordinates = new Feature();
Point point = new Point(-76.506042, 42.417373, 123);
coordinates.setGeometry(point);
ProgramLocationRequest locationRequest = ProgramLocationRequest.builder()
.country(countryRequest)
.accessibility(accessibilityRequest)
.environmentType(environmentRequest)
.topography(topographyRequest)
.name("Test Location")
.abbreviation("TL")
.coordinates(coordinates)
.coordinateDescription("Test Point")
.coordinateUncertainty(BigDecimal.ZERO)
.documentationUrl("http://www.test.com")
.exposure("Test")
.slope(BigDecimal.ZERO)
.build();
String json;
try {
json = objMapper.writeValueAsString(locationRequest);
} catch (JsonProcessingException e) {
throw new Exception("Problem parsing geojson coordinates");
}
Flowable<HttpResponse<String>> call = client.exchange(
POST("/programs/"+otherProgram.getId().toString()+"/locations", json)
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> response = call.blockingFirst();
JsonObject result = JsonParser.parseString(response.body()).getAsJsonObject().getAsJsonObject("result");
String locationId = result.get("id").getAsString();
Optional<ProgramLocation> location = programLocationService.getById(otherProgram.getId(), UUID.fromString(locationId));
return location.orElseThrow(() -> new Exception("Unable to get test location"));
}
public User fetchTestUser() throws Exception{
Optional<User> user = userService.getByOAuthId(TestTokenValidator.TEST_USER_ORCID);
if (!user.isPresent()){
throw new Exception("Failed to insert test user");
}
return user.get();
}
public Species getTestSpecies() {
List<Species> species = speciesService.getAll();
return species.get(0);
}
public Role getTestRole() {
List<Role> roles = roleService.getAll();
return roles.stream().filter(role -> role.getDomain().equals("Program Administrator")).collect(Collectors.toList()).get(0);
}
public Country getTestCountry() {
List<Country> countries = countryService.getAll();
return countries.get(0);
}
public EnvironmentType getTestEnvironment() {
List<EnvironmentType> environments = environmentTypeService.getAll();
return environments.get(0);
}
public Accessibility getTestAccessibility() {
List<Accessibility> accessibilities = accessibilityService.getAll();
return accessibilities.get(0);
}
public Topography getTestTopography() {
List<Topography> topographies = topographyService.getAll();
return topographies.get(0);
}
public AuthenticatedUser getActingUser() {
UUID id = validUser.getId();
List<String> systemRoles = new ArrayList<>();
systemRoles.add(validRole.getDomain());
return new AuthenticatedUser("test_user", systemRoles, id, new ArrayList<>());
}
//region Program Tests
public void checkValidProgram(ProgramEntity program, JsonObject programJson){
assertEquals(program.getName(), programJson.get("name").getAsString(), "Wrong name");
assertEquals(program.getAbbreviation(), programJson.get("abbreviation").getAsString(), "Wrong abbreviation");
assertEquals(program.getDocumentationUrl(), programJson.get("documentationUrl").getAsString(), "Wrong documentation url");
assertEquals(program.getObjective(), programJson.get("objective").getAsString(), "Wrong objective");
JsonObject species = programJson.getAsJsonObject("species");
assertEquals(program.getSpeciesId().toString(), species.get("id").getAsString(), "Wrong species");
JsonObject createdByUser = programJson.getAsJsonObject("createdByUser");
assertEquals(program.getCreatedBy().toString(), createdByUser.get("id").getAsString(), "Wrong created by user");
JsonObject updatedByUser = programJson.getAsJsonObject("updatedByUser");
assertEquals(program.getUpdatedBy().toString(), updatedByUser.get("id").getAsString(), "Wrong updated by user");
assertEquals(program.getKey(), programJson.get("key").getAsString(), "Wrong key");
}
public void checkValidProgram(Program program, JsonObject programJson){
assertEquals(program.getName(), programJson.get("name").getAsString(), "Wrong name");
assertEquals(program.getAbbreviation(), programJson.get("abbreviation").getAsString(), "Wrong abbreviation");
assertEquals(program.getDocumentationUrl(), programJson.get("documentationUrl").getAsString(), "Wrong documentation url");
assertEquals(program.getObjective(), programJson.get("objective").getAsString(), "Wrong objective");
JsonObject species = programJson.getAsJsonObject("species");
assertEquals(program.getSpecies().getId().toString(), species.get("id").getAsString(), "Wrong species");
JsonObject createdByUser = programJson.getAsJsonObject("createdByUser");
assertEquals(program.getCreatedByUser().getId().toString(), createdByUser.get("id").getAsString(), "Wrong created by user");
JsonObject updatedByUser = programJson.getAsJsonObject("updatedByUser");
assertEquals(program.getUpdatedByUser().getId().toString(), updatedByUser.get("id").getAsString(), "Wrong updated by user");
assertEquals(program.getKey(), programJson.get("key").getAsString(), "Wrong key");
}
public void checkMinimalValidProgram(ProgramEntity program, JsonObject programJson){
assertEquals(program.getName(), programJson.get("name").getAsString(), "Wrong name");
JsonObject species = programJson.getAsJsonObject("species");
assertEquals(program.getSpeciesId().toString(), species.get("id").getAsString(), "Wrong species");
JsonObject createdByUser = programJson.getAsJsonObject("createdByUser");
assertEquals(program.getCreatedBy().toString(), createdByUser.get("id").getAsString(), "Wrong created by user");
JsonObject updatedByUser = programJson.getAsJsonObject("updatedByUser");
assertEquals(program.getUpdatedBy().toString(), updatedByUser.get("id").getAsString(), "Wrong updated by user");
assertEquals(program.getKey(), programJson.get("key").getAsString(), "Wrong key");
}
@Test
@Order(1)
public void getProgramsSuccess() {
Flowable<HttpResponse<String>> call = client.exchange(
GET("/programs").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");
assertTrue(result.size() >= 1, "Wrong number of programs");
JsonArray data = result.getAsJsonArray("data");
JsonObject programResult = data.get(0).getAsJsonObject();
checkValidProgram(otherProgram, programResult);
}
@Test
@SneakyThrows
@Order(2)
public void postProgramsFullBodySuccess() throws Exception {
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.id(validSpecies.getId())
.commonName(validSpecies.getCommonName())
.build();
Program program = Program.builder()
.name("Test Program")
.abbreviation("Test")
.documentationUrl("localhost")
.objective("Testing things")
.brapiUrl(getProperties().get("brapi.server.core-url"))
.species(validSpecies)
.speciesId(validSpecies.getId())
.key("TESPR")
.build();
ProgramRequest validRequest = ProgramRequest.builder()
.name("Test Program")
.abbreviation("Test")
.documentationUrl("localhost")
.objective("Testing things")
.species(speciesRequest)
.key("TESPR")
.build();
Flowable<HttpResponse<String>> call = client.exchange(
POST("/programs", gson.toJson(validRequest))
.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.body()).getAsJsonObject().getAsJsonObject("result");
validProgram = programDao.fetchById(UUID.fromString(result.get("id").getAsString())).get(0);
checkMinimalValidProgram(validProgram, result);
dsl.execute(securityFp.get("InsertProgramRolesBreeder"), testUser.getId().toString(), validProgram.getId().toString());
}
@Test
public void getProgramsSpecificInvalidId() {
Flowable<HttpResponse<String>> call = client.exchange(
GET(String.format("/programs/%s", invalidProgram)).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
public void getProgramsSpecificSuccess(){
Flowable<HttpResponse<String>> call = client.exchange(
GET(String.format("/programs/%s", validProgram.getId().toString()))
.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");
checkValidProgram(validProgram, result);
}
@Test
public void postProgramsInvalidSpecies() {
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.id(UUID.fromString(invalidSpecies))
.build();
ProgramRequest invalidProgramRequest = ProgramRequest.builder()
.name("Invalid Species Test program")
.species(speciesRequest)
.key("INVSP")
.build();
Flowable<HttpResponse<String>> call = client.exchange(
POST("/programs", gson.toJson(invalidProgramRequest))
.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
@Order(3)
public void postProgramsNameAlreadyExists() {
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.id(validSpecies.getId())
.build();
ProgramRequest validRequest = ProgramRequest.builder()
.name(validProgram.getName())
.species(speciesRequest)
.key("EXISP")
.build();
Flowable<HttpResponse<String>> call = client.exchange(
POST("/programs", gson.toJson(validRequest))
.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 postProgramsKeyAlreadyExists() {
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.id(validSpecies.getId())
.build();
ProgramRequest validRequest = ProgramRequest.builder()
.name("KeyExists")
.species(speciesRequest)
.key(validProgram.getKey())
.build();
Flowable<HttpResponse<String>> call = client.exchange(
POST("/programs", gson.toJson(validRequest))
.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
public void postProgramsUnsupportedBrapiUrl() {
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.id(validSpecies.getId())
.build();
ProgramRequest validRequest = ProgramRequest.builder()
.name("invalidBrAPITestProgram")
.species(speciesRequest)
.brapiUrl("http://www.notabrapiserver.com")
.key("INVBR")
.build();
Flowable<HttpResponse<String>> call = client.exchange(
POST("/programs", gson.toJson(validRequest))
.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 postProgramsMissingBody() {
Flowable<HttpResponse<String>> call = client.exchange(
POST("/programs", "")
.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 postProgramsMissingSpecies() {
ProgramRequest invalidProgramRequest = ProgramRequest.builder()
.name("Test program")
.key("NOSP")
.build();
Flowable<HttpResponse<String>> call = client.exchange(
POST("/programs", gson.toJson(invalidProgramRequest))
.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
public void postProgramsMinimalBodySuccess() throws Exception{
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.id(validSpecies.getId())
.build();
ProgramRequest validRequest = ProgramRequest.builder()
.name("MinimalBodySuccess Program")
.species(speciesRequest)
.key("MIN")
.build();
Flowable<HttpResponse<String>> call = client.exchange(
POST("/programs", gson.toJson(validRequest))
.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.body()).getAsJsonObject().getAsJsonObject("result");
String newProgramId = result.getAsJsonPrimitive("id").getAsString();
Program program = getProgramById(gson, client, UUID.fromString(newProgramId));
validProgramB = programDao.fetchById(UUID.fromString(result.get("id").getAsString())).get(0);
checkMinimalValidProgram(validProgramB, result);
dsl.execute(fp.get("DeleteProgram"), program.getId().toString(), program.getId().toString(), program.getId().toString(), program.getId().toString(), program.getId().toString());
}
@Test
public void putProgramsInvalidSpecies() {
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.id(UUID.fromString(invalidSpecies))
.build();
ProgramRequest invalidProgramRequest = ProgramRequest.builder()
.name("Test program")
.species(speciesRequest)
.key("BADSP")
.build();
Flowable<HttpResponse<String>> call = client.exchange(
PUT(String.format("/programs/%s", validProgram.getId()), gson.toJson(invalidProgramRequest))
.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 putProgramsMissingSpecies() {
ProgramRequest invalidProgramRequest = ProgramRequest.builder()
.name("Test program")
.key("MISSSP")
.build();
Flowable<HttpResponse<String>> call = client.exchange(
PUT(String.format("/programs/%s", validProgram.getId()), gson.toJson(invalidProgramRequest))
.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 putProgramsInvalidId() {
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.id(UUID.fromString(invalidSpecies))
.build();
ProgramRequest invalidProgramRequest = ProgramRequest.builder()
.name("Test program")
.species(speciesRequest)
.key("INV")
.build();
Flowable<HttpResponse<String>> call = client.exchange(
PUT(String.format("/programs/%s", invalidProgram), gson.toJson(invalidProgramRequest))
.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
public void putProgramsMissingName() {
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.id(UUID.fromString(invalidSpecies))
.build();
ProgramRequest invalidProgramRequest = ProgramRequest.builder()
.species(speciesRequest)
.key("NONAME")
.build();
Flowable<HttpResponse<String>> call = client.exchange(
PUT(String.format("/programs/%s", validProgram.getId()), gson.toJson(invalidProgramRequest))
.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 putProgramsMissingKey() {
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.id(UUID.fromString(invalidSpecies))
.build();
ProgramRequest invalidProgramRequest = ProgramRequest.builder()
.name("MissingKeyTest")
.species(speciesRequest)
.build();
Flowable<HttpResponse<String>> call = client.exchange(
PUT(String.format("/programs/%s", validProgram.getId()), gson.toJson(invalidProgramRequest))
.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 putProgramsInvalidKey() {
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.id(UUID.fromString(invalidSpecies))
.build();
ProgramRequest invalidProgramRequest = ProgramRequest.builder()
.name("InvalidKeyTest")
.species(speciesRequest)
.key("THISISTOOLONGANDWR0NG-CHAR")
.build();
Flowable<HttpResponse<String>> call = client.exchange(
PUT(String.format("/programs/%s", validProgram.getId()), gson.toJson(invalidProgramRequest))
.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
@Order(3)
public void putProgramsMinimalBodySuccess() {
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.id(validSpecies.getId())
.build();
validProgram.setName("changed");
ProgramRequest validRequest = ProgramRequest.builder()
.name(validProgram.getName())
.species(speciesRequest)
.build();
Flowable<HttpResponse<String>> call = client.exchange(
PUT(String.format("/programs/%s", validProgram.getId()) , gson.toJson(validRequest))
.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.body()).getAsJsonObject().getAsJsonObject("result");
checkMinimalValidProgram(validProgram, result);
}
@Test
@Order(4)
public void putProgramsFullBodySuccess() {
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.id(validSpecies.getId())
.commonName(validSpecies.getCommonName())
.build();
validProgram.setName("changed");
validProgram.setAbbreviation("changed abbreviation");
validProgram.setObjective("changed objective");
validProgram.setDocumentationUrl("changed doc url");
ProgramRequest validRequest = ProgramRequest.builder()
.name(validProgram.getName())
.abbreviation(validProgram.getAbbreviation())
.documentationUrl(validProgram.getDocumentationUrl())
.objective(validProgram.getObjective())
.species(speciesRequest)
.build();
Flowable<HttpResponse<String>> call = client.exchange(
PUT(String.format("/programs/%s", validProgram.getId()), gson.toJson(validRequest))
.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.body()).getAsJsonObject().getAsJsonObject("result");
checkMinimalValidProgram(validProgram, result);
}
@Test
public void archiveProgramsInvalidId() {
Flowable<HttpResponse<String>> call = client.exchange(
DELETE(String.format("/programs/archive/%s", invalidProgram))
.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());
Program program = getProgramById(gson, client, validProgram.getId());
assertEquals(true, program.getActive(), "Inactive flag not set in database");
}
@Test
@SneakyThrows
public void archiveProgramsSuccess() {
SpeciesRequest speciesRequest = SpeciesRequest.builder()
.id(validSpecies.getId())
.build();
ProgramRequest validRequest = ProgramRequest.builder()
.name("ArchiveProgram Test")
.species(speciesRequest)
.key("APT")
.build();
Flowable<HttpResponse<String>> createCall = client.exchange(
POST("/programs", gson.toJson(validRequest))
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> response = createCall.blockingFirst();
assertEquals(HttpStatus.OK, response.getStatus());
JsonObject result = JsonParser.parseString(response.body()).getAsJsonObject().getAsJsonObject("result");
String newProgramId = result.getAsJsonPrimitive("id").getAsString();
Flowable<HttpResponse<String>> archiveCall = client.exchange(
DELETE(String.format("/programs/archive/%s", newProgramId))
.contentType(MediaType.APPLICATION_JSON)
.cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class
);
HttpResponse<String> archiveResponse = archiveCall.blockingFirst();
assertEquals(HttpStatus.OK, archiveResponse.getStatus());
Program program = getProgramById(gson, client, UUID.fromString(newProgramId));
assertEquals(false, program.getActive(), "Inactive flag not set in database");
dsl.execute(fp.get("DeleteProgram"), newProgramId, newProgramId, newProgramId, newProgramId, newProgramId);
}
@Test
@Order(5)
public void getProgramQuery() {
dsl.execute(fp.get("InsertManyPrograms"));
List<ProgramEntity> allPrograms = programDao.findAll();
Flowable<HttpResponse<String>> call = client.exchange(
GET("/programs?page=2&pageSize=10&sortField=name&sortOrder=DESC").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(10, data.size(), "Wrong page size");
TestUtils.checkStringSorting(data, "name", SortOrder.DESC);
JsonObject pagination = JsonParser.parseString(response.body()).getAsJsonObject().getAsJsonObject("metadata").getAsJsonObject("pagination");
assertEquals((int) Math.ceil(allPrograms.size()/10.0), pagination.get("totalPages").getAsInt(), "Wrong number of pages");
assertEquals(allPrograms.size(), pagination.get("totalCount").getAsInt(), "Wrong total count");
assertEquals(2, pagination.get("currentPage").getAsInt(), "Wrong current page");
}
@Test
@Order(6)
public void searchPrograms() {
List<ProgramEntity> allPrograms = programDao.findAll();
SearchRequest searchRequest = new SearchRequest();
searchRequest.setFilters(new ArrayList<>());
searchRequest.getFilters().add(new FilterRequest("name", "program1"));
Flowable<HttpResponse<String>> call = client.exchange(
POST("/programs/search?page=1&pageSize=20&sortField=name&sortOrder=ASC", 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 11, program1, program10->program19
assertEquals(11, data.size(), "Wrong page size");
TestUtils.checkStringSorting(data, "name", SortOrder.ASC);
JsonObject pagination = JsonParser.parseString(response.body()).getAsJsonObject().getAsJsonObject("metadata").getAsJsonObject("pagination");
assertEquals(1, pagination.get("totalPages").getAsInt(), "Wrong number of pages");
assertEquals(11, pagination.get("totalCount").getAsInt(), "Wrong total count");
assertEquals(1, pagination.get("currentPage").getAsInt(), "Wrong current page");
}
//endregion
//region Program Location Tests
@Test
@Order(4)
public void postProgramsLocationsInvalidProgram() {
JsonObject requestBody = validProgramLocationRequest();
Flowable<HttpResponse<String>> call = client.exchange(
POST("/programs/"+invalidProgram+"/locations", 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
@Order(4)
public void postProgramsLocationsInvalidCountry() {
JsonObject requestBody = new JsonObject();
requestBody.addProperty("name", "Field 1");
JsonObject country = new JsonObject();
country.addProperty("id", invalidCountry);
requestBody.add("country", country);