-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathLabKeySiteWrapper.java
More file actions
1563 lines (1371 loc) · 59.8 KB
/
LabKeySiteWrapper.java
File metadata and controls
1563 lines (1371 loc) · 59.8 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
/*
* Copyright (c) 2015-2019 LabKey Corporation
*
* 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.labkey.test;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.jetbrains.annotations.Nullable;
import org.json.simple.JSONObject;
import org.junit.Assert;
import org.junit.Assume;
import org.labkey.remoteapi.Command;
import org.labkey.remoteapi.CommandException;
import org.labkey.remoteapi.CommandResponse;
import org.labkey.remoteapi.Connection;
import org.labkey.remoteapi.PostCommand;
import org.labkey.remoteapi.query.ContainerFilter;
import org.labkey.remoteapi.query.Filter;
import org.labkey.remoteapi.query.SelectRowsCommand;
import org.labkey.remoteapi.query.SelectRowsResponse;
import org.labkey.test.components.api.ProjectMenu;
import org.labkey.test.components.dumbster.EmailRecordTable;
import org.labkey.test.components.html.SiteNavBar;
import org.labkey.test.pages.core.admin.ShowAdminPage;
import org.labkey.test.pages.user.UserDetailsPage;
import org.labkey.test.util.APIUserHelper;
import org.labkey.test.util.AbstractUserHelper;
import org.labkey.test.util.DataRegionTable;
import org.labkey.test.util.ExperimentalFeaturesHelper;
import org.labkey.test.util.LabKeyExpectedConditions;
import org.labkey.test.util.LogMethod;
import org.labkey.test.util.LoggedParam;
import org.labkey.test.util.Maps;
import org.labkey.test.util.PasswordUtil;
import org.labkey.test.util.PipelineStatusTable;
import org.labkey.test.util.PortalHelper;
import org.labkey.test.util.SimpleHttpRequest;
import org.labkey.test.util.SimpleHttpResponse;
import org.labkey.test.util.TestLogger;
import org.labkey.test.util.TextSearcher;
import org.labkey.test.util.Timer;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.labkey.test.TestProperties.isDevModeEnabled;
import static org.labkey.test.WebTestHelper.buildURL;
import static org.labkey.test.WebTestHelper.getBaseURL;
import static org.labkey.test.WebTestHelper.getHttpClientBuilder;
import static org.labkey.test.WebTestHelper.getHttpResponse;
import static org.labkey.test.WebTestHelper.logToServer;
/**
* TODO: Move non-JUnit related methods from BWDT.
* Many existing helpers, components, and page classes will need refactor as well
*/
public abstract class LabKeySiteWrapper extends WebDriverWrapper
{
private static final int MAX_SERVER_STARTUP_WAIT_SECONDS = 60;
private static final String CLIENT_SIDE_ERROR = "Client exception detected";
public AbstractUserHelper _userHelper = new APIUserHelper(this);
public boolean isGuestModeTest()
{
return false;
}
protected void assumeTestModules()
{
Assume.assumeFalse("Test modules are needed but not installed. Skipping test.",
TestProperties.isWithoutTestModules());
}
// Just sign in & verify -- don't check for startup, upgrade, admin mode, etc.
public void simpleSignIn()
{
if ( isGuestModeTest() )
{
goToHome();
return;
}
if (!getDriver().getTitle().startsWith("Sign In"))
{
executeScript("window.onbeforeunload = null;"); // Just get logged in, ignore 'unload' alerts
beginAt(WebTestHelper.buildURL("login", "login"));
waitForAnyElement("Should be on login or Home portal", Locator.id("email"), SiteNavBar.Locators.userMenu);
}
if (PasswordUtil.getUsername().equals(getCurrentUser()))
{
log("Already logged in as " + PasswordUtil.getUsername());
goToHome();
}
else
{
log("Signing in as " + PasswordUtil.getUsername());
assertElementPresent(Locator.tagWithName("form", "login"));
setFormElement(Locator.name("email"), PasswordUtil.getUsername());
setFormElement(Locator.name("password"), PasswordUtil.getPassword());
acceptTermsOfUse(null, false);
clickButton("Sign In", 0);
// verify we're signed in now
if (!waitFor(() ->
{
if (isElementPresent(SiteNavBar.Locators.userMenu))
return true;
bypassSecondaryAuthentication();
return false;
}, defaultWaitForPage))
{
bypassSecondaryAuthentication();
String errors = StringUtils.join(getTexts(Locator.css(".labkey-error").findElements(getDriver())), "\n");
// If we get redirected here the message is not indicated as an error
if (errors.length() == 0 && null != getUrlParam("message", true))
errors = getUrlParam("message", true);
if (errors.contains("The email address and password you entered did not match any accounts on file."))
throw new IllegalStateException("Could not log in with the saved credentials. Please verify that the test user exists on this installation or reset the credentials using 'gradlew :server:test:setPassword'");
else if (errors.contains("Your password does not meet the complexity requirements; please choose a new password."))
throw new IllegalStateException("Password complexity requirement was left on by a previous test");
else if (errors.contains("log in and approve the terms of use."))
throw new IllegalStateException("Terms of use not accepted at login");
else
throw new IllegalStateException("Unexpected error(s) during login." + errors);
}
}
assertSignedInNotImpersonating();
_userHelper.saveCurrentDisplayName();
WebTestHelper.saveSession(PasswordUtil.getUsername(), getDriver());
}
/**
* Call the LogoutApi to sign out
*/
public void simpleSignOut()
{
signOutHTTP();
goToHome();
}
@LogMethod
public void signOut(@Nullable String termsText)
{
log("Signing out");
simpleSignOut();
acceptTermsOfUse(termsText, true);
waitForElement(Locators.signInLink);
}
@LogMethod
public void signOut()
{
signOut(null);
}
public void signOutHTTP()
{
String logOutUrl = WebTestHelper.buildURL("login", "logout");
SimpleHttpRequest logOutRequest = new SimpleHttpRequest(logOutUrl, "POST");
logOutRequest.copySession(getDriver());
try
{
SimpleHttpResponse response = logOutRequest.getResponse();
assertEquals(HttpStatus.SC_OK, response.getResponseCode());
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
public void stopImpersonatingHTTP()
{
String stopImpersonatingUrl = WebTestHelper.buildURL("login", "stopImpersonating.api");
SimpleHttpRequest logOutRequest = new SimpleHttpRequest(stopImpersonatingUrl, "POST");
logOutRequest.copySession(getDriver());
try
{
SimpleHttpResponse response = logOutRequest.getResponse();
if (HttpStatus.SC_OK != response.getResponseCode() && HttpStatus.SC_UNAUTHORIZED != response.getResponseCode())
{
fail("Failed to stop impersonating. " + response.getResponseCode());
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
@LogMethod
public void ensureSignedInAsPrimaryTestUser()
{
boolean wasImpersonating = isImpersonating(); // To make sure browser isn't in an apparent impersonation state
stopImpersonatingHTTP();
if (!isSignedInAsPrimaryTestUser())
{
if (isSignedIn())
signOutHTTP();
simpleSignIn();
}
else if (wasImpersonating || !onLabKeyPage() || isOnServerErrorPage())
{
goToHome();
}
WebTestHelper.saveSession(getCurrentUser(), getDriver()); // In case a test signed in without using a helper
}
@LogMethod
public void deleteSiteWideTermsOfUsePage()
{
getHttpResponse(WebTestHelper.buildURL("wiki", "delete", Maps.of("name", "_termsOfUse")), "POST").getResponseCode();
}
protected void bypassSecondaryAuthentication()
{
try
{
String configId = getUrlParameters().get("configuration");
//Select radio Yes
checkRadioButton(Locator.radioButtonByNameAndValue("valid", "1"));
//Click on button 'TestSecondary'
clickAndWait(Locator.input("TestSecondary"));
// delete the current secondaryAuth configuration
deleteAuthenticationConfiguration(configId, createDefaultConnection());
}
catch (NoSuchElementException ignored)
{
}
}
protected void acceptTermsOfUse(String termsText, boolean clickAgree)
{
Optional<WebElement> optionalCheckbox = Locators.termsOfUseCheckbox().findOptionalElement(getDriver());
optionalCheckbox.ifPresent(termsCheckbox ->
{
if (termsCheckbox.isDisplayed())
{
checkCheckbox(termsCheckbox);
if (null != termsText)
{
assertTextPresent(termsText);
}
if (clickAgree)
clickButton("Agree");
}
});
}
@LogMethod
public void signIn()
{
if (isGuestModeTest())
{
waitForStartup();
log("Skipping sign in. Test runs as guest.");
simpleSignOut();
return;
}
try
{
PasswordUtil.ensureCredentials();
}
catch (IOException e)
{
throw new RuntimeException("Unable to ensure credentials", e);
}
waitForStartup();
log("Signing in");
simpleSignOut();
checkForUpgrade();
simpleSignIn();
assertEquals("Signed in as wrong user.", PasswordUtil.getUsername(), getCurrentUser());
}
// Just sign in & verify -- don't check for startup, upgrade, admin mode, etc.
public void signIn(String email, String password)
{
attemptSignIn(email, password);
Assert.assertEquals("Logged in as wrong user", email, getCurrentUser());
WebTestHelper.saveSession(email, getDriver());
}
public void attemptSignIn(String email, String password)
{
if (isSignedIn())
throw new IllegalStateException("You need to be logged out to log in. Please log out to log in.");
if (!getDriver().getTitle().contains("Sign In"))
{
try
{
// attempt to navigate to login page
clickAndWait(Locator.linkWithText("Sign In"));
}
catch (NoSuchElementException error)
{
throw new IllegalStateException("Unable to find \"Sign In\" link on current page.", error);
}
}
assertTitleContains("Sign In");
assertElementPresent(Locator.tagWithName("form", "login"));
setFormElement(Locator.id("email"), email);
setFormElement(Locator.id("password"), password);
WebElement signInButton = Locator.lkButton("Sign In").findElement(getDriver());
signInButton.click();
shortWait().until(ExpectedConditions.invisibilityOfElementLocated(Locator.byClass("signing-in-msg")));
shortWait().until(ExpectedConditions.or(
ExpectedConditions.stalenessOf(signInButton), // Successful login
ExpectedConditions.presenceOfElementLocated(Locators.labkeyError.withText()))); // Error during sign-in
}
public void signInShouldFail(String email, String password, String... expectedMessages)
{
attemptSignIn(email, password);
String errorText = waitForElement(Locator.id("errors").withText()).getText();
assertElementPresent(Locator.tagWithName("form", "login"));
List<String> missingErrors = getMissingTexts(new TextSearcher(errorText), expectedMessages);
assertTrue(String.format("Wrong errors.\nExpected: ['%s']\nActual: '%s'", String.join("',\n'", expectedMessages), errorText), missingErrors.isEmpty());
}
protected void setInitialPassword(String user, String password)
{
beginAt(WebTestHelper.buildURL("security", "showRegistrationEmail", Map.of("email", user)));
// Get setPassword URL from notification email.
WebElement resetLink = Locator.linkWithHref("setPassword.view").findElement(getDriver());
clickAndWait(resetLink, WAIT_FOR_PAGE);
setFormElement(Locator.id("password"), password);
setFormElement(Locator.id("password2"), password);
clickButton("Set Password");
}
protected String getPasswordResetUrl(String username)
{
beginAt(WebTestHelper.buildURL("security", "showResetEmail", Map.of("email", username)));
WebElement resetLink = Locator.xpath("//a[contains(@href, 'setPassword.view')]").findElement(getDriver());
shortWait().until(ExpectedConditions.elementToBeClickable(resetLink));
return resetLink.getText();
}
protected void resetPassword(String resetUrl, String username, String newPassword)
{
if (PasswordUtil.getUsername().equals(username))
throw new IllegalArgumentException("Don't change the primary site admin user's password");
if (resetUrl != null)
beginAt(resetUrl);
assertTextPresent(username,
"has been verified! Create an account password below.",
"Your password must be at least six characters and cannot contain spaces or match your email address."
);
setFormElement(Locator.id("password"), newPassword);
setFormElement(Locator.id("password2"), newPassword);
clickButton("Set Password");
}
@LogMethod protected void changePassword(String oldPassword, @LoggedParam String password)
{
if (PasswordUtil.getUsername().equals(getCurrentUser()))
throw new IllegalArgumentException("Don't change the primary site admin user's password");
goToMyAccount();
clickButton("Change Password");
setFormElement(Locator.id("oldPassword"), oldPassword);
setFormElement(Locator.id("password"), password);
setFormElement(Locator.id("password2"), password);
clickButton("Set Password");
}
/**
* change user's email from userEmail to newUserEmail from admin console
*/
protected void changeUserEmail(String userEmail, String newUserEmail)
{
log("Attempting to change user email from " + userEmail + " to " + newUserEmail);
goToSiteUsers();
clickAndWait(Locator.linkContainingText(_userHelper.getDisplayNameForEmail(userEmail)));
clickButton("Change Email");
setFormElement(Locator.name("requestedEmail"), newUserEmail);
setFormElement(Locator.name("requestedEmailConfirmation"), newUserEmail);
clickButton("Submit");
}
protected void setSystemMaintenance(boolean enable)
{
// Not available in production mode
if (isDevModeEnabled())
{
goToAdminConsole().clickSystemMaintenance();
setCheckbox(waitForElement(Locator.name("enableSystemMaintenance")), enable);
clickButton("Save");
}
}
/**
* @deprecated This method is mostly unnecessary and the end state is
* inconsistent. It may or may not navigate and may or may not stop
* impersonating.
*/
@Deprecated
public void ensureAdminMode()
{
if (!onLabKeyPage())
{
TestLogger.warn("ensureAdminMode called from non-standard page");
goToHome();
}
if (!isSignedIn())
{
TestLogger.warn("ensureAdminMode called while not logged in");
simpleSignIn();
}
else if (!isUserSystemAdmin() && isImpersonating())
{
TestLogger.warn("ensureAdminMode called while impersonating non-admin");
stopImpersonating(false);
}
Locator projectMenu = ProjectMenu.Locators.menuProjectNav;
if (!isElementPresent(projectMenu))
{
TestLogger.warn("project menu not present after ensureAdminMode");
goToHome();
waitForElement(projectMenu, WAIT_FOR_PAGE);
}
assertTrue("Test user '" + getCurrentUser() + "' is not an admin", isUserAdmin());
}
public ShowAdminPage goToAdminConsole()
{
return ShowAdminPage.beginAt(this);
}
protected void createDefaultStudy()
{
clickButton("Create Study");
clickButton("Create Study");
}
private void waitForStartup()
{
Boolean hitFirstPage = null;
log("Verifying that server has started...");
Timer startupTimer = new Timer(Duration.ofSeconds(MAX_SERVER_STARTUP_WAIT_SECONDS));
Throwable lastError = null;
do
{
if (hitFirstPage == null)
{
hitFirstPage = false;
}
else
{
// retrying
log("Server is not ready. Waiting " + startupTimer.timeRemaining().getSeconds() + " more seconds...");
sleep(1000);
}
try
{
String startPage = buildURL("project", "home", "start");
SimpleHttpResponse httpResponse = WebTestHelper.getHttpResponse(startPage);
if (httpResponse.getResponseCode() >= 400)
{
log("Waiting for server: " + httpResponse.getResponseCode());
// Don't try to interact with the WebDriver while the site is unresponsive. It can cause tests to hang
continue;
}
else
{
log("Response: " + httpResponse.getResponseCode());
}
getDriver().manage().timeouts().pageLoadTimeout(WAIT_FOR_PAGE, TimeUnit.MILLISECONDS);
getDriver().get(startPage);
try
{
waitForElement(Locator.CssLocator.union(Locator.css("table.labkey-main"), Locator.css("#permalink"), Locator.css("#headerpanel")));
hitFirstPage = true;
}
catch (NoSuchElementException e)
{
lastError = e;
}
}
catch (WebDriverException e)
{
// ignore timeouts that occur during startup; a poorly timed request
// as the webapp is loading may hang forever, causing a timeout.
log("Waiting for server: " + e.getMessage());
lastError = e;
}
catch (RuntimeException e)
{
if (e.getCause() != null && e.getCause() instanceof IOException)
{
log("Waiting for server: " + e.getCause().getMessage());
lastError = e;
}
else
throw e;
}
} while (!hitFirstPage && !startupTimer.isTimedOut());
if (!hitFirstPage)
{
throw new RuntimeException("Webapp failed to start up after " + MAX_SERVER_STARTUP_WAIT_SECONDS + " seconds.", lastError);
}
log("Server is running.");
WebTestHelper.setUseContainerRelativeUrl((Boolean)executeScript("return LABKEY.experimental.containerRelativeURL;"));
}
@LogMethod
private void checkForUpgrade()
{
final String upgradeText = "Please wait, this page will automatically update with progress information.";
boolean bootstrapped = false;
boolean performingUpgrade = false;
// check to see if we're the first user:
if (isTextPresent("Welcome! We see that this is your first time logging in."))
{
bootstrapped = true;
assertTitleEquals("Account Setup");
log("Need to bootstrap");
verifyInitialUserRedirects();
log("Testing bad email addresses");
verifyInitialUserError(null, null, null, "Invalid email address");
verifyInitialUserError("bogus@bogus@bogus", null, null, "Invalid email address: bogus@bogus@bogus");
log("Testing bad passwords");
String email = PasswordUtil.getUsername();
verifyInitialUserError(email, null, null, "You must enter a password.");
verifyInitialUserError(email, "LongEnough", null, "You must enter a password.");
verifyInitialUserError(email, null, "LongEnough", "You must enter a password.");
verifyInitialUserError(email, "short", "short", "Your password must be at least six characters and cannot contain spaces.");
verifyInitialUserError(email, email, email, "Your password must not match your email address.");
verifyInitialUserError(email, "LongEnough", "ButDontMatch", "Your password entries didn't match.");
log("Register the first user");
pushLocation();
assertTextPresent("Confirm Password");
verifyInitialUserError(email, PasswordUtil.getPassword(), PasswordUtil.getPassword(), null);
// Runner was unable to log the test start prior to initial user creation
logToServer("=== Starting " + getClass().getSimpleName() + " ===");
log("Attempting to register another initial user");
popLocation();
// Make sure we got redirected to the module status page, since we already have a user
assertTextNotPresent("Confirm Password");
assertTextPresent("Please wait, this page will automatically update with progress information");
WebTestHelper.saveSession(email, getDriver());
}
else if (getDriver().getTitle().startsWith("Sign In"))
{
// if the logout page takes us to the sign-in page, then we may have a schema update to do:
if (getDriver().getTitle().startsWith("Sign In"))
simpleSignIn();
performingUpgrade = isTextPresent(upgradeText);
}
if (bootstrapped || performingUpgrade)
{
RuntimeException redirectCheckError = null;
try
{
verifyRedirectBehavior(upgradeText);
}
catch (IOException | AssertionError fail)
{
// Delay throwing failure so that upgrade can finish
redirectCheckError = new RuntimeException(fail);
}
int waitMs = 10 * 60 * 1000; // we'll wait at most ten minutes
long startTime = System.currentTimeMillis();
long elapsed = 0;
while (elapsed < waitMs && (!isElementPresent(Locator.lkButton("Next"))))
{
try
{
// Pound the server aggressively with requests for the home page to test synchronization
// in the sql script runner.
for (int i = 0; i < 5; i++)
{
int responseCode = WebTestHelper.getHttpResponse(buildURL("project", "Home", "begin")).getResponseCode();
TestLogger.log("Home: " + responseCode);
sleep(200);
}
sleep(2000);
if (isTextPresent("error occurred") || isTextPresent("failure occurred"))
throw new RuntimeException("A startup failure occurred.");
Optional<WebElement> progressBar = Locator.id("status-progress-bar").findOptionalElement(getDriver());
log(bootstrapped ? "Bootstrapping" : "Upgrading" + (progressBar.map(webElement -> (": \"" + webElement.getText() + "\"")).orElse("")));
}
catch (WebDriverException ignore)
{
// Do nothing -- this page will sometimes auto-navigate out from under selenium
}
finally
{
elapsed = System.currentTimeMillis() - startTime;
}
}
if (elapsed > waitMs)
throw new TestTimeoutException("Script runner took more than 10 minutes to complete.");
if (bootstrapped)
{
// admin-moduleStatus
assertEquals("Progress bar text", "Module startup complete", getText(Locator.id("status-progress-bar")));
clickAndWait(Locator.lkButton("Next"));
// admin-newInstallSiteSettings
assertElementPresent(Locator.id("rootPath"));
uncheckCheckbox(Locator.name("allowReporting"));
clickAndWait(Locator.lkButton("Next"));
// admin-installComplete
clickAndWait(Locator.linkContainingText("Go to the server's Home page"));
assertEquals("Landed on wrong project after bootstrapping", "home", getCurrentProject().toLowerCase());
// Tests hit Home portal a lot. Make it load as fast as possible
new PortalHelper(this).removeAllWebParts();
String displayName = AbstractUserHelper.getDefaultDisplayName(PasswordUtil.getUsername())
+ (WebTestHelper.RANDOM.nextBoolean() ? BaseWebDriverTest.INJECT_CHARS_1 : BaseWebDriverTest.INJECT_CHARS_2);
_userHelper.setDisplayName(PasswordUtil.getUsername(), displayName);
}
else // Just upgrading
{
Optional<WebElement> header = Locator.css(".labkey-nav-page-header").findOptionalElement(getDriver());
if (header.isPresent() && Arrays.asList("Start Modules", "Upgrade Modules").contains(header.get().getText().trim()))
{
waitForElement(Locator.id("status-progress-bar").withText("Module startup complete"), WAIT_FOR_PAGE);
clickAndWait(Locator.lkButton("Next"));
Locator.lkButton("Next")
.findOptionalElement(getDriver())
.ifPresent(button ->
doAndWaitForPageToLoad(() ->
shortWait().until(LabKeyExpectedConditions.clickUntilStale(button))));
}
else
{
goToHome();
}
}
PipelineStatusTable.goToAllJobsPage(this);
log("Wait for any upgrade/bootstrap pipeline jobs");
waitForRunningPipelineJobs(false, 120000);
checkErrors(); // Check for errors from bootstrap/upgrade
if (redirectCheckError != null)
throw redirectCheckError;
}
}
private void verifyInitialUserError(@Nullable String email, @Nullable String password1, @Nullable String password2, @Nullable String expectedError)
{
if (null != email)
setFormElement(Locator.id("email"), email);
if (null != password1)
setFormElement(Locator.id("password"), password1);
if (null != password2)
setFormElement(Locator.id("password2"), password2);
clickAndWait(Locator.linkWithText("Next"), 90000); // Initial user creation blocks during upgrade script execution
if (null != expectedError)
assertEquals("Wrong error message.", expectedError, Locator.css(".labkey-error").findElement(getDriver()).getText());
}
private void verifyInitialUserRedirects()
{
String initialText = "Welcome! We see that this is your first time logging in.";
// These requests should redirect to the initial user page
beginAt("/login/resetPassword.view");
assertTextPresent(initialText);
beginAt("/admin/maintenance.view");
assertTextPresent(initialText);
}
@LogMethod
private void verifyRedirectBehavior(String upgradeText) throws IOException
{
// Do these checks via direct http requests the primary upgrade window seems to interfere with this test, #15853
HttpResponse response = null;
HttpUriRequest method;
int status;
try (CloseableHttpClient client = (CloseableHttpClient)WebTestHelper.getHttpClient())
{
// These requests should NOT redirect to the upgrade page
method = new HttpGet(getBaseURL() + "/login/resetPassword.view");
response = client.execute(method, WebTestHelper.getBasicHttpContext());
status = response.getStatusLine().getStatusCode();
assertEquals("Unexpected response", HttpStatus.SC_OK, status);
assertFalse("Upgrade text found", WebTestHelper.getHttpResponseBody(response).contains(upgradeText));
EntityUtils.consume(response.getEntity());
method = new HttpGet(getBaseURL() + "/admin/maintenance.view");
response = client.execute(method, WebTestHelper.getBasicHttpContext());
status = response.getStatusLine().getStatusCode();
assertEquals("Unexpected response", HttpStatus.SC_OK, status);
assertFalse("Upgrade text found", WebTestHelper.getHttpResponseBody(response).contains(upgradeText));
EntityUtils.consume(response.getEntity());
// Check that sign out and sign in work properly during upgrade/install (once initial user is configured)
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy()
{
@Override
public boolean isRedirected(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException
{
boolean isRedirect = false;
try
{
isRedirect = super.isRedirected(httpRequest, httpResponse, httpContext);
}
catch (ProtocolException ignore)
{
}
if (!isRedirect)
{
int responseCode = httpResponse.getStatusLine().getStatusCode();
if (responseCode == 301 || responseCode == 302)
return true;
// if (WebTestHelper.getHttpResponseBody(httpResponse).contains("http-equiv=\"Refresh\""))
// return true;
}
return isRedirect;
}
//TODO: Generate HttpRequest for 'http-equiv' redirect
// @Override
// public HttpUriRequest getRedirect(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException
// {
// HttpUriRequest redirectRequest = null;
// ProtocolException ex = null;
// try
// {
// return super.getRedirect(httpRequest, httpResponse, httpContext);
// }
// catch (ProtocolException e){ex = e;}
// redirectRequest = httpRequest.;
//
// if (redirectRequest == null)
// throw ex;
// else
// return redirectRequest;
// }
};
try (CloseableHttpClient redirectClient = getHttpClientBuilder()
.setRedirectStrategy(redirectStrategy) /* Clear cookies so that we don't actually log out */
.setDefaultCookieStore(null).build())
{
List<NameValuePair> loginParams = new ArrayList<>();
loginParams.add(new BasicNameValuePair("email", PasswordUtil.getUsername()));
loginParams.add(new BasicNameValuePair("password", PasswordUtil.getPassword()));
// Login to get CSRF token
HttpPost loginMethod = new HttpPost(getBaseURL() + "/login/loginApi.api");
loginMethod.setEntity(new UrlEncodedFormEntity(loginParams));
HttpClientContext httpContext = WebTestHelper.getBasicHttpContext();
response = redirectClient.execute(loginMethod, httpContext);
status = response.getStatusLine().getStatusCode();
assertEquals("Unexpected response to login: \n" + TestFileUtils.getStreamContentsAsString(response.getEntity().getContent()), HttpStatus.SC_OK, status);
EntityUtils.consume(response.getEntity());
List<NameValuePair> logoutParams = new ArrayList<>();
Optional<Cookie> csrfToken = httpContext.getCookieStore().getCookies().stream().filter(c -> c.getName().equals(Connection.X_LABKEY_CSRF)).findAny();
csrfToken.ifPresent(cookie -> logoutParams.add(new BasicNameValuePair(Connection.X_LABKEY_CSRF, cookie.getValue())));
// Logout to verify redirect
HttpPost logoutMethod = new HttpPost(getBaseURL() + "/login/logout.view");
logoutMethod.setEntity(new UrlEncodedFormEntity(logoutParams));
response = redirectClient.execute(logoutMethod, httpContext);
status = response.getStatusLine().getStatusCode();
assertEquals("Unexpected response to logout: \n" + TestFileUtils.getStreamContentsAsString(response.getEntity().getContent()), HttpStatus.SC_OK, status);
// TODO: check login, once http-equiv redirect is sorted out
assertFalse("Upgrade text found", WebTestHelper.getHttpResponseBody(response).contains(upgradeText));
EntityUtils.consume(response.getEntity());
}
}
finally
{
if (null != response)
EntityUtils.consumeQuietly(response.getEntity());
}
}
public void checkErrors()
{
if (isGuestModeTest())
return;
ensureSignedInAsPrimaryTestUser();
String serverErrors = getServerErrors();
if (!serverErrors.isEmpty())
{
beginAt(buildURL("admin", "showErrorsSinceMark"));
resetErrors();
if (serverErrors.toLowerCase().contains(CLIENT_SIDE_ERROR.toLowerCase()))
fail("There were client-side errors during the test run. Check labkey.log and/or labkey-errors.log for details.");
else
fail("There were server-side errors during the test run. Check labkey.log and/or labkey-errors.log for details.");
}
log("No new errors found.");
}
public String getServerErrors()
{
SimpleHttpResponse httpResponse = WebTestHelper.getHttpResponse(buildURL("admin", "showErrorsSinceMark"), PasswordUtil.getUsername(), PasswordUtil.getPassword());
assertEquals("Failed to fetch server errors: " + httpResponse.getResponseMessage(), HttpStatus.SC_OK, httpResponse.getResponseCode());
return httpResponse.getResponseBody();
}
@LogMethod
public void checkExpectedErrors(@LoggedParam int expectedErrors)
{
int count = getServerErrorCount();
if (expectedErrors != count)
{
beginAt(buildURL("admin", "showErrorsSinceMark"));
resetErrors();
assertEquals("Expected error count does not match actual count for this run.", expectedErrors, count);
}
// Clear expected errors to prevent the test from failing.
resetErrors();
}
protected int getServerErrorCount()
{
String text = getServerErrors();
Pattern errorPattern = Pattern.compile("^ERROR", Pattern.MULTILINE);
Matcher errorMatcher = errorPattern.matcher(text);
int count = 0;
while (errorMatcher.find())
{
count++;
}
return count;
}
public void resetErrors()
{
if (isGuestModeTest())
return;
invokeApiAction(null, "admin", "resetErrorMark", "Failed to reset server errors");
}
@LogMethod
public void disableMaintenance()
{
if ( isGuestModeTest() )
return;
beginAt("/admin/customizeSite.view");
click(Locator.radioButtonByNameAndValue("systemMaintenanceInterval", "never"));
clickButton("Save");
}
private static long smStart = 0;
private static String smUrl = null;
public void startSystemMaintenance()
{
startSystemMaintenance("");
}
public void startSystemMaintenance(String taskName)
{
Map<String, String> urlParams = new HashMap<>();
urlParams.put("test", "true");
if (!taskName.isEmpty())
urlParams.put("taskName", taskName);
String maintenanceTriggerUrl = WebTestHelper.buildURL("admin", "systemMaintenance", urlParams);
smStart = System.currentTimeMillis();
SimpleHttpRequest request = new SimpleHttpRequest(maintenanceTriggerUrl);
request.setRequestMethod("POST");
request.copySession(getDriver());
try
{
SimpleHttpResponse response = request.getResponse();
assertEquals("Failed to start system maintenance", HttpStatus.SC_OK, response.getResponseCode());
smUrl = response.getResponseBody();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
public void waitForSystemMaintenanceCompletion()
{
assertTrue("Must call startSystemMaintenance() before waiting for completion", smStart > 0);
long elapsed = System.currentTimeMillis() - smStart;
// Navigate to pipeline details page, then refresh page and check for system maintenance complete, up to 10 minutes from the start of the test
beginAt(smUrl);
int timeLeft = 10 * 60 * 1000 - ((Long)elapsed).intValue();
waitForTextWithRefresh(timeLeft > 0 ? timeLeft : 0, "System maintenance complete");
}
public void goToProjectHome(String projectName)
{
beginAt(buildURL("project", projectName, "begin"));
}
/**
* go to the project settings page of a project
* @param project project name