-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
AdministrationServiceTest.java
879 lines (691 loc) · 35.3 KB
/
AdministrationServiceTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
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
/**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs.api;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.openmrs.GlobalProperty;
import org.openmrs.ImplementationId;
import org.openmrs.User;
import org.openmrs.api.context.Context;
import org.openmrs.customdatatype.datatype.BooleanDatatype;
import org.openmrs.customdatatype.datatype.DateDatatype;
import org.openmrs.messagesource.MutableMessageSource;
import org.openmrs.messagesource.impl.MutableResourceBundleMessageSource;
import org.openmrs.test.jupiter.BaseContextSensitiveTest;
import org.openmrs.util.HttpClient;
import org.openmrs.util.LocaleUtility;
import org.openmrs.util.OpenmrsConstants;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.validation.BindException;
/**
* Tests the {@link AdministrationService} using a database.
* Unit tests are {@link AdministrationServiceUnitTest}.
*/
public class AdministrationServiceTest extends BaseContextSensitiveTest {
private AdministrationService adminService;
protected static final String ADMIN_INITIAL_DATA_XML = "org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml";
private HttpClient implementationHttpClient;
private CacheManager cacheManager;
@BeforeEach
public void runBeforeEachTest() {
adminService = Context.getAdministrationService();
implementationHttpClient = mock(HttpClient.class);
adminService.setImplementationIdHttpClient(implementationHttpClient);
cacheManager = Context.getRegisteredComponent("apiCacheManager", CacheManager.class);
}
@Test
public void executeSQL_shouldExecuteSqlContainingGroupBy() {
String sql = "select encounter1_.location_id, encounter1_.creator, encounter1_.encounter_type, encounter1_.form_id, location2_.location_id, count(obs0_.obs_id) from obs obs0_ right outer join encounter encounter1_ on obs0_.encounter_id=encounter1_.encounter_id inner join location location2_ on encounter1_.location_id=location2_.location_id inner join users user3_ on encounter1_.creator=user3_.user_id inner join person user3_1_ on user3_.user_id=user3_1_.person_id inner join encounter_type encountert4_ on encounter1_.encounter_type=encountert4_.encounter_type_id inner join form form5_ on encounter1_.form_id=form5_.form_id where encounter1_.date_created>='2007-05-05' and encounter1_.date_created<= '2008-05-05' group by encounter1_.location_id, encounter1_.creator , encounter1_.encounter_type , encounter1_.form_id, location2_.location_id";
adminService.executeSQL(sql, true);
String sql2 = "select encounter_id, count(*) from encounter encounter_id group by encounter_id";
adminService.executeSQL(sql2, true);
}
@Test
public void setImplementationId_shouldNotFailIfGivenImplementationIdIsNull() {
// save a null impl id. no exception thrown
adminService.setImplementationId(null);
ImplementationId afterNull = adminService.getImplementationId();
assertNull(afterNull, "There shouldn't be an impl id defined after setting a null impl id");
}
/**
* This uses a try/catch so that we can make sure no blank id is saved to the database.
*
* @see AdministrationService#setImplementationId(ImplementationId)
*/
@Test()
public void setImplementationId_shouldThrowAPIExceptionIfGivenEmptyImplementationIdObject() {
// save a blank impl id. exception thrown
assertThrows(APIException.class, () -> adminService.setImplementationId(new ImplementationId()));
ImplementationId afterBlank = adminService.getImplementationId();
assertNull(afterBlank, "There shouldn't be an impl id defined after setting a blank impl id");
}
/**
* This uses a try/catch so that we can make sure no blank id is saved to the database.
*/
@Test
public void setImplementationId_shouldThrowAPIExceptionIfGivenACaretInTheImplementationIdCode() {
// save an impl id with an invalid hl7 code
ImplementationId invalidId = new ImplementationId();
invalidId.setImplementationId("caret^caret");
invalidId.setName("an invalid impl id for a unit test");
invalidId.setPassphrase("some valid passphrase");
invalidId.setDescription("Some valid description");
assertThrows(APIException.class, () -> adminService.setImplementationId(invalidId));
ImplementationId afterInvalid = adminService.getImplementationId();
assertNull(afterInvalid, "There shouldn't be an impl id defined after setting an invalid impl id");
}
@Test
public void setImplementationId_shouldThrowAPIExceptionIfGivenAPipeInTheImplementationIdCode() {
// save an impl id with an invalid hl7 code
ImplementationId invalidId2 = new ImplementationId();
invalidId2.setImplementationId("pipe|pipe");
invalidId2.setName("an invalid impl id for a unit test");
invalidId2.setPassphrase("some valid passphrase");
invalidId2.setDescription("Some valid description");
assertThrows(APIException.class, () -> adminService.setImplementationId(invalidId2));
ImplementationId afterInvalid2 = adminService.getImplementationId();
assertNull(afterInvalid2, "There shouldn't be an impl id defined after setting an invalid impl id");
}
@Test
@Disabled
public void setImplementationId_shouldCreateImplementationIdInDatabase() {
// save a valid impl id
ImplementationId validId = new ImplementationId();
validId.setImplementationId("JUNIT-TEST");
validId.setName("JUNIT-TEST implementation id");
validId.setPassphrase("This is the junit test passphrase");
validId.setDescription("This is the junit impl id used for testing of the openmrs API only.");
adminService.setImplementationId(validId);
assertEquals(validId, adminService.getImplementationId());
}
@Test
@Disabled
public void setImplementationId_shouldOverwriteImplementationIdInDatabaseIfExists() {
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-general.xml");
// sanity check to make sure we have an implementation id
assertNotNull(adminService.getImplementationId());
Context.clearSession(); // so a NonUniqueObjectException doesn't occur on the global property later
// save a second valid id
ImplementationId validId2 = new ImplementationId();
validId2.setImplementationId("JUNIT-TEST 2");
validId2.setName("JUNIT-TEST (#2) implementation id");
validId2.setPassphrase("This is the junit test passphrase 2");
validId2.setDescription("This is the junit impl id (2) used for testing of the openmrs API only.");
adminService.setImplementationId(validId2);
assertEquals(validId2, adminService.getImplementationId());
}
@Test
@Disabled
public void setImplementationId_shouldSetUuidOnImplementationIdGlobalProperty() {
ImplementationId validId = new ImplementationId();
validId.setImplementationId("JUNIT-TEST");
validId.setName("JUNIT-TEST implementation id");
validId.setPassphrase("This is the junit test passphrase");
validId.setDescription("This is the junit impl id used for testing of the openmrs API only.");
adminService.setImplementationId(validId);
GlobalProperty gp = adminService.getGlobalPropertyObject(OpenmrsConstants.GLOBAL_PROPERTY_IMPLEMENTATION_ID);
assertNotNull(gp.getUuid());
}
@Test
public void getGlobalProperty_shouldNotFailWithNullPropertyName() {
adminService.getGlobalProperty(null);
}
@Test
public void getGlobalProperty_shouldGetPropertyValueGivenValidPropertyName() {
// put the global property into the database
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
String propertyValue = adminService.getGlobalProperty("a_valid_gp_key");
assertEquals("correct-value", propertyValue);
}
@Test
public void getGlobalProperty_shouldNotFailWithNullDefaultValue() {
adminService.getGlobalProperty("asdfsadfsafd", null);
}
@Test
public void updateGlobalProperty_shouldUpdateGlobalPropertyInDatabase() {
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
String propertyValue = adminService.getGlobalProperty("a_valid_gp_key");
assertEquals("correct-value", propertyValue);
adminService.updateGlobalProperty("a_valid_gp_key", "new-value");
String newValue = adminService.getGlobalProperty("a_valid_gp_key");
assertEquals("new-value", newValue);
}
@Test
public void updateGlobalProperty_shouldFailIfGlobalPropertyBeingUpdatedDoesNotAlreadyExist() {
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
assertThrows(IllegalStateException.class, () -> adminService.updateGlobalProperty("a_invalid_gp_key", "asdfsadfsafd"));
}
@Test
public void updateGlobalProperty_shouldUpdateAGlobalPropertyWhoseTypedvalueIsHandledByACustomDatatype() {
GlobalProperty gp = new GlobalProperty();
gp.setProperty("Flag");
gp.setDatatypeClassname(BooleanDatatype.class.getName());
gp.setValue(Boolean.FALSE);
adminService.saveGlobalProperty(gp);
assertEquals(adminService.getGlobalProperty("Flag"), "false");
adminService.updateGlobalProperty("Flag", Boolean.TRUE.toString());
assertEquals(adminService.getGlobalProperty("Flag"), "true");
}
@Test
public void setGlobalProperty_shouldCreateGlobalPropertyInDatabase() {
String newKey = "new_gp_key";
String initialValue = adminService.getGlobalProperty(newKey);
assertNull(initialValue); // ensure gp doesn't exist before test
adminService.setGlobalProperty(newKey, "new_key");
String newValue = adminService.getGlobalProperty(newKey);
assertNotNull(newValue);
}
@Test
public void setGlobalProperty_shouldOverwriteGlobalPropertyIfExists() {
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
String propertyValue = adminService.getGlobalProperty("a_valid_gp_key");
assertEquals("correct-value", propertyValue);
adminService.setGlobalProperty("a_valid_gp_key", "new-value");
String newValue = adminService.getGlobalProperty("a_valid_gp_key");
assertEquals("new-value", newValue);
}
@Test
public void setGlobalProperty_shouldSaveAGlobalPropertyWhoseTypedValueIsHandledByACustomDatatype() {
String newKey = "Flag";
String initialValue = adminService.getGlobalProperty(newKey);
assertNull(initialValue);
adminService.setGlobalProperty(newKey, Boolean.FALSE.toString());
assertEquals(adminService.getGlobalProperty("Flag"), "false");
}
@Test
public void getGlobalProperty_shouldReturnDefaultValueIfPropertyNameDoesNotExist() {
String invalidKey = "asdfasdf";
String propertyValue = adminService.getGlobalProperty(invalidKey);
assertNull(propertyValue); // make sure there isn't a gp
String value = adminService.getGlobalProperty(invalidKey, "default");
assertEquals("default", value);
}
@Test
public void getGlobalPropertiesByPrefix_shouldReturnAllRelevantGlobalPropertiesInTheDatabase() {
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
List<GlobalProperty> properties = adminService.getGlobalPropertiesByPrefix("fake.module.");
for (GlobalProperty property : properties) {
assertTrue(property.getProperty().startsWith("fake.module."));
assertTrue(property.getPropertyValue().startsWith("correct-value"));
}
}
@Test
public void getGlobalPropertiesByInvalidPrefix_shouldReturnEmptyList() {
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
String invalidPrefix = "non.existing.prefix.";
List<GlobalProperty> properties = adminService.getGlobalPropertiesByPrefix(invalidPrefix);
assertTrue(properties.isEmpty());
}
@Test
public void getGlobalPropertiesByPrefix_shouldReturnEmptyWhenPrefixIsNull() {
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
List<GlobalProperty> properties = adminService.getGlobalPropertiesByPrefix(null);
assertNotNull(properties);
assertTrue(properties.isEmpty());
}
@Test
public void getGlobalPropertiesBySuffix_shouldReturnAllRelevantGlobalPropertiesInTheDatabase() {
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
List<GlobalProperty> properties = adminService.getGlobalPropertiesBySuffix(".abcd");
assertNotNull(properties);
assertTrue(properties.size() > 0);
for (GlobalProperty property : properties) {
assertTrue(property.getProperty().endsWith(".abcd"));
}
}
@Test
public void getGlobalPropertiesByInvalidSuffix_shouldReturnEmptyList() {
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
String invalidSuffix = "non.existing.suffix.";
List<GlobalProperty> properties = adminService.getGlobalPropertiesBySuffix(invalidSuffix);
assertTrue(properties.isEmpty());
}
@Test
public void getGlobalPropertiesBySuffix_shouldReturnEmptyWhenSuffixIsNull() {
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
List<GlobalProperty> properties = adminService.getGlobalPropertiesBySuffix(null);
assertNotNull(properties);
assertTrue(properties.isEmpty());
}
@Test
public void getAllowedLocales_shouldNotFailIfNotGlobalPropertyForLocalesAllowedDefinedYet() {
adminService.purgeGlobalProperty(
new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST));
adminService.getAllowedLocales();
}
@Test
public void getGlobalPropertyByUuid_shouldFindObjectGivenValidUuid() {
String uuid = "4f55827e-26fe-102b-80cb-0017a47871b3";
GlobalProperty prop = adminService.getGlobalPropertyByUuid(uuid);
assertEquals("locale.allowed.list", prop.getProperty());
}
@Test
public void getGlobalPropertyByUuid_shouldReturnNullIfNoObjectFoundWithGivenUuid() {
assertNull(adminService.getGlobalPropertyByUuid("some invalid uuid"));
}
@Test
public void saveGlobalProperties_shouldNotFailWithEmptyList() {
adminService.saveGlobalProperties(new ArrayList<>());
}
@Test
public void saveGlobalProperties_shouldSaveAllGlobalPropertiesToTheDatabase() {
// get the current global properties
List<GlobalProperty> globalProperties = adminService.getAllGlobalProperties();
// and now add some new ones to it
globalProperties.add(new GlobalProperty("new prop1", "new prop value1", "desc"));
globalProperties.add(new GlobalProperty("new prop2", "new prop value2", "desc"));
adminService.saveGlobalProperties(globalProperties);
assertEquals("new prop value1", adminService.getGlobalProperty("new prop1"));
assertEquals("new prop value2", adminService.getGlobalProperty("new prop2"));
}
@Test
public void saveGlobalProperties_shouldAssignUuidToAllNewProperties() {
// get the current global properties
List<GlobalProperty> globalProperties = adminService.getAllGlobalProperties();
// and now add a new one to it and save it
globalProperties.add(new GlobalProperty("new prop", "new prop value", "desc"));
adminService.saveGlobalProperties(globalProperties);
assertNotNull(adminService.getGlobalPropertyObject("new prop").getUuid());
}
@Test
public void getAllGlobalProperties_shouldReturnAllGlobalPropertiesInTheDatabase() {
int allGlobalPropertiesSize = adminService.getAllGlobalProperties().size();
executeDataSet(ADMIN_INITIAL_DATA_XML);
assertEquals(allGlobalPropertiesSize + 9, adminService.getAllGlobalProperties().size());
}
@Test
public void getAllGlobalProperties_shouldReturnPropertiesInAscendingOrder() {
executeDataSet(ADMIN_INITIAL_DATA_XML);
List<GlobalProperty> properties = adminService.getAllGlobalProperties();
assertFalse(properties.isEmpty(), "The list of global properties should not be empty");
// Verify the properties are in ascending order
for (int i = 0; i < properties.size() - 1; i++) {
String currentProperty = properties.get(i).getProperty();
String nextProperty = properties.get(i + 1).getProperty();
assertTrue(currentProperty.compareTo(nextProperty) <= 0,
"The global properties should be in ascending order by the property name");
}
}
@Test
public void getAllowedLocales_shouldReturnAtLeastOneLocaleIfNoLocalesDefinedInDatabaseYet() {
assertTrue(adminService.getAllowedLocales().size() > 0);
}
@Test
public void getGlobalPropertyObject_shouldReturnNullWhenNoGlobalPropertyMatchGivenPropertyName() {
executeDataSet(ADMIN_INITIAL_DATA_XML);
assertNull(adminService.getGlobalPropertyObject("magicResistSkill"));
}
@Test
public void getImplementationId_shouldReturnNullIfNoImplementationIdIsDefinedYet() {
executeDataSet(ADMIN_INITIAL_DATA_XML);
assertNull(adminService.getImplementationId());
}
@Test
@Disabled
//TODO: This test fails for some reason
public void getPresentationLocales_shouldReturnAtLeastOneLocaleIfNoLocalesDefinedInDatabaseYet() {
assertTrue(adminService.getPresentationLocales().size() > 0);
}
@Test
public void getPresentationLocales_shouldNotReturnMoreLocalesThanMessageSourceServiceLocales() {
assertFalse(adminService.getPresentationLocales().size() > Context
.getMessageSourceService().getLocales().size());
}
@Test
public void getSystemVariables_shouldReturnAllRegisteredSystemVariables() {
// The method implementation adds 11 system variables
assertEquals(11, adminService.getSystemVariables().size());
}
@Test
public void purgeGlobalProperty_shouldDeleteGlobalPropertyFromDatabase() {
executeDataSet(ADMIN_INITIAL_DATA_XML);
int allGlobalPropertiesSize = adminService.getAllGlobalProperties().size();
adminService.purgeGlobalProperty(adminService.getGlobalPropertyObject("a_valid_gp_key"));
assertEquals(allGlobalPropertiesSize -1, adminService.getAllGlobalProperties().size());
}
@Test
public void saveGlobalProperty_shouldCreateGlobalPropertyInDatabase() {
executeDataSet(ADMIN_INITIAL_DATA_XML);
adminService.saveGlobalProperty(new GlobalProperty("detectHiddenSkill", "100"));
assertNotNull(adminService.getGlobalProperty("detectHiddenSkill"));
}
@Test
public void saveGlobalProperty_shouldOverwriteGlobalPropertyIfExists() {
executeDataSet(ADMIN_INITIAL_DATA_XML);
GlobalProperty gp = adminService.getGlobalPropertyObject("a_valid_gp_key");
assertEquals("correct-value", gp.getPropertyValue());
gp.setPropertyValue("new-even-more-correct-value");
adminService.saveGlobalProperty(gp);
assertEquals("new-even-more-correct-value", adminService.getGlobalProperty("a_valid_gp_key"));
}
@Test
public void saveGlobalProperty_shouldFailIfGivenAllowedLocaleListDoesNotContainDefaultLocale() {
String localeList = "fr,es";
assertThat("localeList contains default locale but should not for this test case", localeList,
not(containsString(LocaleUtility.getDefaultLocale().toString())));
APIException exception = assertThrows(APIException.class, () -> adminService.saveGlobalProperty(new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, localeList)));
assertThat(exception.getMessage(), containsString("can not be removed from allowed locales list because it is the default locale"));
}
@Test
public void saveGlobalProperty_shouldFailIfDefaultLocaleNotInAllowedLocaleList() {
Locale defaultLocale = new Locale("fr");
APIException exception = assertThrows(APIException.class, () -> adminService.saveGlobalProperty(new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE, defaultLocale.toString())));
assertThat(exception.getMessage(), containsString("is not in allowed locales list"));
}
@Test
public void getAllowedLocales_shouldNotReturnDuplicatesEvenIfTheGlobalPropertyHasThem() {
adminService.saveGlobalProperty(
new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en_GB,fr,es,en_GB"));
assertEquals(3, adminService.getAllowedLocales().size());
}
@Test
public void getGlobalPropertyValue_shouldReturnValueInTheSpecifiedIntegerType() {
// put the global property into the database
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
Object value = adminService.getGlobalPropertyValue("valid.integer", 4);
assertTrue(value instanceof Integer);
assertEquals(1234, value);
}
@Test
public void getGlobalPropertyValue_shouldReturnDefaultValueForMissingProperty() {
// put the global property into the database
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
Object value = adminService.getGlobalPropertyValue("does.not.exist", 1234);
assertEquals(1234, value);
}
@Test
public void getGlobalPropertyValue_shouldReturnValueInTheSpecifiedDoubleType() {
// put the global property into the database
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
Object retValue = adminService.getGlobalPropertyValue("valid.double", 4.34);
assertTrue(retValue instanceof Double);
assertEquals(1234.54, retValue);
}
@Test
public void getGlobalProperty_shouldGetPropertyInCaseInsensitiveWay() {
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
// sanity check
String orig = adminService.getGlobalProperty("another-global-property");
assertEquals("anothervalue", orig);
// try to get a global property with invalid case
String noprop = adminService.getGlobalProperty("ANOTher-global-property");
assertEquals(orig, noprop);
}
@Test
public void saveGlobalProperty_shouldNotAllowDifferentPropertiesToHaveTheSameStringWithDifferentCase() {
executeDataSet("org/openmrs/api/include/AdministrationServiceTest-globalproperties.xml");
// sanity check
String orig = adminService.getGlobalProperty("another-global-property");
assertEquals("anothervalue", orig);
// should match current gp and update
GlobalProperty gp = new GlobalProperty("ANOTher-global-property", "somethingelse");
adminService.saveGlobalProperty(gp);
String prop = adminService.getGlobalProperty("ANOTher-global-property", "boo");
assertEquals("somethingelse", prop);
orig = adminService.getGlobalProperty("another-global-property");
assertEquals("somethingelse", orig);
}
@Test
public void saveGlobalProperties_shouldSavePropertiesWithCaseDifferenceOnly() {
int originalSize = adminService.getAllGlobalProperties().size();
List<GlobalProperty> props = new ArrayList<>();
props.add(new GlobalProperty("a.property.key", "something"));
props.add(new GlobalProperty("a.property.KEY", "somethingelse"));
adminService.saveGlobalProperties(props);
// make sure that we now have two properties
props = adminService.getAllGlobalProperties();
assertEquals(originalSize + 1, props.size());
assertTrue(props.contains(adminService.getGlobalPropertyObject("a.property.KEY")));
}
@Test
public void purgeGlobalProperties_shouldDeleteGlobalPropertiesFromDatabase() {
int originalSize = adminService.getAllGlobalProperties().size();
List<GlobalProperty> props = new ArrayList<>();
props.add(new GlobalProperty("a.property.key", "something"));
adminService.saveGlobalProperties(props);
int afterSaveSize = adminService.getAllGlobalProperties().size();
assertEquals(originalSize + 1, afterSaveSize);
adminService.purgeGlobalProperties(props);
int afterPurgeSize = adminService.getAllGlobalProperties().size();
assertEquals(originalSize, afterPurgeSize);
}
@Test
public void saveGlobalProperty_shouldSaveAGlobalPropertyWhoseTypedValueIsHandledByACustomDatatype() {
GlobalProperty gp = new GlobalProperty();
gp.setProperty("What time is it?");
gp.setDatatypeClassname(DateDatatype.class.getName());
gp.setValue(new Date());
adminService.saveGlobalProperty(gp);
assertNotNull(gp.getValueReference());
}
@Test
public void getSearchLocales_shouldExcludeNotAllowedLocales() {
//given
adminService.saveGlobalProperty(
new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en_US, en_GB, pl, es"));
User user = Context.getAuthenticatedUser();
user.setUserProperty(OpenmrsConstants.USER_PROPERTY_PROFICIENT_LOCALES, "es_CL, en_US, pl");
Context.getUserService().saveUser(user);
//when
List<Locale> searchLocales = adminService.getSearchLocales();
//then
assertTrue(searchLocales.contains(new Locale("en", "US")), "en_US");
assertTrue(searchLocales.contains(new Locale("pl")), "pl");
assertTrue(searchLocales.contains(new Locale("es")), "es");
assertFalse(searchLocales.contains(new Locale("es", "CL")), "es_CL");
}
@Test
public void getSearchLocales_shouldIncludeCurrentlySelectedFullLocaleAndLangugage() {
//given
adminService.saveGlobalProperty(
new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en_GB"));
User user = Context.getAuthenticatedUser();
user.setUserProperty(OpenmrsConstants.USER_PROPERTY_PROFICIENT_LOCALES, "");
Context.getUserService().saveUser(user);
Context.setLocale(new Locale("en", "GB"));
//when
List<Locale> searchLocales = adminService.getSearchLocales();
//then
assertEquals(Context.getLocale(), searchLocales.get(0));
assertEquals(new Locale(Context.getLocale().getLanguage()), searchLocales.get(1));
}
@Test
public void getSearchLocales_shouldIncludeUsersProficientLocales() {
//given
adminService.saveGlobalProperty(
new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en_GB, en_US, pl"));
User user = Context.getAuthenticatedUser();
user.setUserProperty(OpenmrsConstants.USER_PROPERTY_PROFICIENT_LOCALES, "en_GB, en_US");
Context.getUserService().saveUser(user);
//when
List<Locale> searchLocales = adminService.getSearchLocales();
//then
assertTrue(searchLocales.contains(new Locale("en", "GB")), "en_GB");
assertTrue(searchLocales.contains(new Locale("en", "US")), "en_US");
assertFalse(searchLocales.contains(new Locale("pl")), "pl");
}
@Test
public void validate_shouldThrowThrowAPIExceptionIfTheInputIsNull() {
BindException errors = new BindException(new Object(), "");
assertThrows(APIException.class, () -> adminService.validate(null, errors));
}
@Test
public void getPresentationLocales_shouldReturnOnlyCountryLocaleIfBothCountryLocaleAndLanguageLocaleAreSpecifiedInAllowedList()
{
adminService.saveGlobalProperty(
new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en_GB, es, es_CL"));
List<Locale> locales = new ArrayList<>();
locales.add(new Locale("pl", "PL"));
locales.add(new Locale("en"));
locales.add(new Locale("es"));
locales.add(new Locale("es", "CL"));
MutableResourceBundleMessageSource mutableResourceBundleMessageSource = Mockito
.mock(MutableResourceBundleMessageSource.class);
Mockito.when(mutableResourceBundleMessageSource.getLocales()).thenReturn(locales);
MutableMessageSource mutableMessageSource = Context.getMessageSourceService().getActiveMessageSource();
Context.getMessageSourceService().setActiveMessageSource(mutableResourceBundleMessageSource);
Set<Locale> presentationLocales = adminService.getPresentationLocales();
Context.getMessageSourceService().setActiveMessageSource(mutableMessageSource);
assertEquals(2, presentationLocales.size());
assertTrue(presentationLocales.contains(new Locale("en")), "en");
assertTrue(presentationLocales.contains(new Locale("es", "CL")), "es_CL");
}
@Test
public void getPresentationLocales_shouldReturnAllCountryLocalesIfLanguageLocaleAndNoCountryLocalesAreSpecifiedInAllowedList()
{
adminService.saveGlobalProperty(
new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en_GB, es"));
List<Locale> locales = new ArrayList<>();
locales.add(new Locale("pl", "PL"));
locales.add(new Locale("en"));
locales.add(new Locale("es"));
locales.add(new Locale("es", "CL"));
locales.add(new Locale("es", "SN"));
MutableResourceBundleMessageSource mutableResourceBundleMessageSource = Mockito
.mock(MutableResourceBundleMessageSource.class);
Mockito.when(mutableResourceBundleMessageSource.getLocales()).thenReturn(locales);
MutableMessageSource mutableMessageSource = Context.getMessageSourceService().getActiveMessageSource();
Context.getMessageSourceService().setActiveMessageSource(mutableResourceBundleMessageSource);
Set<Locale> presentationLocales = adminService.getPresentationLocales();
Context.getMessageSourceService().setActiveMessageSource(mutableMessageSource);
assertEquals(3, presentationLocales.size());
assertTrue(presentationLocales.contains(new Locale("es", "CL")), "es_CL");
assertTrue(presentationLocales.contains(new Locale("es", "SN")), "es_SN");
assertTrue(presentationLocales.contains(new Locale("en")), "en");
}
@Test
public void getPresentationLocales_shouldReturnLanguageLocaleIfCountryLocaleIsSpecifiedInAllowedListButCountryLocaleMessageFileIsMissing()
{
adminService.saveGlobalProperty(
new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en_GB, es_CL"));
List<Locale> locales = new ArrayList<>();
locales.add(new Locale("pl", "PL"));
locales.add(new Locale("en"));
locales.add(new Locale("es"));
MutableResourceBundleMessageSource mutableResourceBundleMessageSource = Mockito
.mock(MutableResourceBundleMessageSource.class);
Mockito.when(mutableResourceBundleMessageSource.getLocales()).thenReturn(locales);
MutableMessageSource mutableMessageSource = Context.getMessageSourceService().getActiveMessageSource();
Context.getMessageSourceService().setActiveMessageSource(mutableResourceBundleMessageSource);
Set<Locale> presentationLocales = adminService.getPresentationLocales();
Context.getMessageSourceService().setActiveMessageSource(mutableMessageSource);
assertEquals(2, presentationLocales.size());
assertTrue(presentationLocales.contains(new Locale("en")), "en");
assertTrue(presentationLocales.contains(new Locale("es")), "es");
}
@Test
public void getPresentationLocales_shouldReturnLanguageLocaleIfItIsSpecifiedInAllowedListAndThereAreNoCountryLocaleMessageFilesAvailable()
{
adminService.saveGlobalProperty(
new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en_GB, es"));
List<Locale> locales = new ArrayList<>();
locales.add(new Locale("pl", "PL"));
locales.add(new Locale("en"));
locales.add(new Locale("es"));
MutableResourceBundleMessageSource mutableResourceBundleMessageSource = Mockito
.mock(MutableResourceBundleMessageSource.class);
Mockito.when(mutableResourceBundleMessageSource.getLocales()).thenReturn(locales);
MutableMessageSource mutableMessageSource = Context.getMessageSourceService().getActiveMessageSource();
Context.getMessageSourceService().setActiveMessageSource(mutableResourceBundleMessageSource);
Set<Locale> presentationLocales = adminService.getPresentationLocales();
Context.getMessageSourceService().setActiveMessageSource(mutableMessageSource);
assertEquals(2, presentationLocales.size());
assertTrue(presentationLocales.contains(new Locale("en")), "en");
assertTrue(presentationLocales.contains(new Locale("es")), "es");
}
@Test
public void getPresentationLocales_shouldPreserveInsertionOrderInSetReturnedByMethod()
{
String globalPropertyLocaleListAllowedData = "en_GB, es, ja_JP, it_IT, pl_PL";
//The order of languages and locales is described above and should be followed bt `presentationLocales` Set
adminService.saveGlobalProperty(
new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, globalPropertyLocaleListAllowedData));
List<Locale> locales = new ArrayList<>();
//Add data in random order and verify that order is maintained in the end by checking against order in global property
locales.add(new Locale("pl", "PL"));
locales.add(new Locale("es"));
locales.add(new Locale("en"));
locales.add(new Locale("it", "IT"));
MutableResourceBundleMessageSource mutableResourceBundleMessageSource = Mockito
.mock(MutableResourceBundleMessageSource.class);
Mockito.when(mutableResourceBundleMessageSource.getLocales()).thenReturn(locales);
MutableMessageSource mutableMessageSource = Context.getMessageSourceService().getActiveMessageSource();
Context.getMessageSourceService().setActiveMessageSource(mutableResourceBundleMessageSource);
List<Locale> presentationLocales = new ArrayList<>(adminService.getPresentationLocales());
Context.getMessageSourceService().setActiveMessageSource(mutableMessageSource);
//Assert Locales in expected order as set by global property
assertEquals(new Locale("en"), presentationLocales.get(0));
assertEquals(new Locale("es"), presentationLocales.get(1));
assertEquals(new Locale("it", "IT"), presentationLocales.get(2));
assertEquals(new Locale("pl", "PL"), presentationLocales.get(3));
}
@Test
public void getSearchLocales_shouldCacheResultsForAnUser() {
//given
adminService.saveGlobalProperty(
new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en_GB, en_US, pl"));
User user = Context.getAuthenticatedUser();
user.setUserProperty(OpenmrsConstants.USER_PROPERTY_PROFICIENT_LOCALES, "en_GB, en_US");
Context.getUserService().saveUser(user);
//when
adminService.getSearchLocales();
List<Locale> cachedSearchLocales = getCachedSearchLocalesForCurrentUser();
//then
assertThat(cachedSearchLocales, hasItem(Locale.ENGLISH));
assertThat(cachedSearchLocales, hasItem(new Locale("en", "US")));
assertThat(cachedSearchLocales, not(hasItem(new Locale("pl"))));
}
@Test
public void saveGlobalProperty_shouldEvictCachedResults() {
//given
adminService.saveGlobalProperty(
new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en_GB, en_US, pl"));
User user = Context.getAuthenticatedUser();
user.setUserProperty(OpenmrsConstants.USER_PROPERTY_PROFICIENT_LOCALES, "en_GB, en_US");
Context.getUserService().saveUser(user);
//sanity check that cache has been populated
adminService.getSearchLocales();
List<Locale> cachedSearchLocales = getCachedSearchLocalesForCurrentUser();
assertThat(cachedSearchLocales, hasItem(new Locale("en", "US")));
//evict cache
adminService.saveGlobalProperty(new GlobalProperty("test", "TEST"));
assertThat(getCacheForCurrentUser(), nullValue());
}
private Cache.ValueWrapper getCacheForCurrentUser(){
Object[] params = { Context.getLocale(), Context.getAuthenticatedUser() };
Object key = (new SimpleKeyGenerator()).generate(null, null, params);
return cacheManager.getCache("userSearchLocales").get(key);
}
private List<Locale> getCachedSearchLocalesForCurrentUser() {
return (List<Locale>) getCacheForCurrentUser().get();
}
}