-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathBaseWebDriverTest.java
More file actions
2882 lines (2532 loc) · 107 KB
/
Copy pathBaseWebDriverTest.java
File metadata and controls
2882 lines (2532 loc) · 107 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) 2012-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.io.FileUtils;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.mutable.MutableInt;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.awaitility.Awaitility;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;
import org.junit.Assume;
import org.junit.AssumptionViolatedException;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.internal.runners.statements.FailOnTimeout;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.junit.runner.Description;
import org.junit.runners.model.MultipleFailureException;
import org.junit.runners.model.Statement;
import org.junit.runners.model.TestTimedOutException;
import org.labkey.junit.rules.TestWatcher;
import org.labkey.remoteapi.CommandException;
import org.labkey.remoteapi.CommandResponse;
import org.labkey.remoteapi.Connection;
import org.labkey.remoteapi.SimpleGetCommand;
import org.labkey.remoteapi.SimplePostCommand;
import org.labkey.remoteapi.collections.CaseInsensitiveHashMap;
import org.labkey.remoteapi.query.ContainerFilter;
import org.labkey.remoteapi.query.Filter;
import org.labkey.remoteapi.query.SelectRowsResponse;
import org.labkey.remoteapi.security.CreateUserResponse;
import org.labkey.serverapi.reader.TabLoader;
import org.labkey.serverapi.writer.PrintWriters;
import org.labkey.test.components.CustomizeView;
import org.labkey.test.components.ext4.Checkbox;
import org.labkey.test.components.ext4.Window;
import org.labkey.test.components.html.RadioButton;
import org.labkey.test.components.labkey.PortalTab;
import org.labkey.test.components.search.SearchBodyWebPart;
import org.labkey.test.pages.admin.ExportFolderPage;
import org.labkey.test.pages.core.admin.logger.ManagerPage;
import org.labkey.test.pages.query.NewQueryPage;
import org.labkey.test.pages.query.SourceQueryPage;
import org.labkey.test.pages.search.SearchResultsPage;
import org.labkey.test.params.FieldDefinition;
import org.labkey.test.params.FieldKey;
import org.labkey.test.teamcity.TeamCityUtils;
import org.labkey.test.util.APIAssayHelper;
import org.labkey.test.util.APIContainerHelper;
import org.labkey.test.util.AbstractAssayHelper;
import org.labkey.test.util.AbstractContainerHelper;
import org.labkey.test.util.ApiPermissionsHelper;
import org.labkey.test.util.ArtifactCollector;
import org.labkey.test.util.ComponentQuery;
import org.labkey.test.util.Crawler;
import org.labkey.test.util.CspLogUtil;
import org.labkey.test.util.DataRegionTable;
import org.labkey.test.util.DebugUtils;
import org.labkey.test.util.DeferredErrorCollector;
import org.labkey.test.util.Ext4Helper;
import org.labkey.test.util.FileBrowserHelper;
import org.labkey.test.util.ListHelper;
import org.labkey.test.util.Log4jUtils;
import org.labkey.test.util.LogMethod;
import org.labkey.test.util.LoggedParam;
import org.labkey.test.util.PermissionsHelper;
import org.labkey.test.util.PipelineToolsHelper;
import org.labkey.test.util.ReadOnlyTest;
import org.labkey.test.util.SimpleHttpResponse;
import org.labkey.test.util.StudyHelper;
import org.labkey.test.util.TestLogger;
import org.labkey.test.util.UIPermissionsHelper;
import org.labkey.test.util.core.webdav.WebDavUploadHelper;
import org.labkey.test.util.ext4cmp.Ext4FieldRef;
import org.labkey.test.util.query.QueryUtils;
import org.labkey.test.util.search.SearchAdminAPIHelper;
import org.labkey.test.util.selenium.WebDriverUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.ElementClickInterceptedException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.UnhandledAlertException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.html5.WebStorage;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.UnreachableBrowserException;
import org.openqa.selenium.remote.service.DriverService;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.labkey.test.TestProperties.isHeapDumpCollectionEnabled;
import static org.labkey.test.TestProperties.isInjectionCheckEnabled;
import static org.labkey.test.TestProperties.isLeakCheckSkipped;
import static org.labkey.test.TestProperties.isLinkCheckEnabled;
import static org.labkey.test.TestProperties.isQueryCheckSkipped;
import static org.labkey.test.TestProperties.isRunWebDriverHeadless;
import static org.labkey.test.TestProperties.isSystemMaintenanceDisabled;
import static org.labkey.test.TestProperties.isTestCleanupSkipped;
import static org.labkey.test.TestProperties.isTestRunningOnTeamCity;
import static org.labkey.test.TestProperties.isViewCheckSkipped;
import static org.labkey.test.WebTestHelper.GC_ATTEMPT_LIMIT;
import static org.labkey.test.WebTestHelper.MAX_LEAK_LIMIT;
import static org.labkey.test.WebTestHelper.buildURL;
import static org.labkey.test.WebTestHelper.isLocalServer;
import static org.labkey.test.WebTestHelper.logToServer;
import static org.labkey.test.components.ext4.Window.Window;
import static org.labkey.test.components.html.RadioButton.RadioButton;
import static org.labkey.test.teamcity.TeamCityUtils.publishArtifact;
/**
* This class should be used as the base for all functional test classes
* Test cases should be non-destructive and should not depend on a particular execution order
*
* Shared setup steps should be in a public static void method annotated with org.junit.BeforeClass
* The name of the method is not important. The JUnit runner finds the method solely based on the BeforeClass annotation
*
* <pre>
* &BeforeClass
* public static void setupProject() throws Exception
* {
* MyTestClass initTest = (MyTestClass)getCurrentTest();
* initTest.doSetup(); // Perform shared setup steps here
* }
*</pre>
*
* {@link org.junit.AfterClass} is also supported, but should not be used to perform any destructive cleanup or
* navigation as it is executed before the base test class can perform its final checks -- link check, leak check, etc.
* The doCleanup method should be overridden for initial and final project cleanup
*/
@BaseWebDriverTest.ClassTimeout()
public abstract class BaseWebDriverTest extends LabKeySiteWrapper implements Cleanable, WebTest
{
private static BaseWebDriverTest currentTest;
private final BrowserType BROWSER_TYPE;
private String _lastPageTitle = null;
private URL _lastPageURL = null;
private String _lastPageText = null;
protected static boolean _testFailed = false;
protected static boolean _anyTestFailed = false;
private static boolean _dumpedHeap = false;
private final ArtifactCollector _artifactCollector;
private final DeferredErrorCollector _errorCollector;
private final CspCheckPageLoadListener _cspCheckPageLoadListener; // Need a strong reference to this
public AbstractContainerHelper _containerHelper = new APIContainerHelper(this);
public final CustomizeView _customizeViewsHelper;
public StudyHelper _studyHelper = new StudyHelper(this);
public final ListHelper _listHelper;
public AbstractAssayHelper _assayHelper = new APIAssayHelper(this);
public FileBrowserHelper _fileBrowserHelper = new FileBrowserHelper(this);
@Deprecated // Use ApiPermissionsHelper unless UI testing is necessary
public UIPermissionsHelper _permissionsHelper = new UIPermissionsHelper(this);
public static final int MAX_WAIT_SECONDS = 10 * 60;
public static final double DELTA = 10E-10;
public static final String ALL_ILLEGAL_QUERY_KEY_CHARACTERS = StringUtils.join(FieldKey.getIllegalChars(), "");
// See TSVWriter.shouldQuote. Generally we are not able to use the tab and new line characters when creating field names in the UI, but including here for completeness
public static final String[] TRICKY_IMPORT_FIELD_CHARACTERS = {"\\", "\"", "\\t", ",", "\\n", "\\r"};
public static final String TRICKY_CHARACTERS = "><&/%\\' \"1\u00E4\u00F6\u00FC\u00C5";
public static final String TRICKY_CHARACTERS_NO_QUOTES = "></% 1\u00E4\u00F6\u00FC\u00C5";
public static final String TRICKY_CHARACTERS_FOR_PROJECT_NAMES = "\u2603~!@$&()_+{}-=[],.#\u00E4\u00F6\u00FC\u00C5"; // No slash or space
public static final String LONG_NON_ASCII_STRING = StringUtils.repeat(FieldDefinition.SNOWMAN, 22); // "☃" See Issue 52714
public static final String INJECT_CHARS_1 = Crawler.injectScriptBlock;
public static final String INJECT_CHARS_2 = Crawler.injectAttributeScript;
/** Have we already done a memory leak and error check in this test harness VM instance? */
protected static boolean _checkedLeaksAndErrors = false;
private static final String ACTION_SUMMARY_TABLE_NAME = "actions";
public static final String DISMISSED_STORAGE_PREFIX = "__release_notes_dismissed__";
static final Set<String> urlsSeen = new HashSet<>();
static
{
TestProperties.load();
}
public BaseWebDriverTest()
{
Awaitility.pollInSameThread(); // We don't do cross thread selenium testing.
_artifactCollector = new ArtifactCollector(this);
_errorCollector = new DeferredErrorCollector(_artifactCollector);
_listHelper = new ListHelper(this);
_customizeViewsHelper = new CustomizeView(this);
_cspCheckPageLoadListener = new CspCheckPageLoadListener(this);
String seleniumBrowser = System.getProperty("selenium.browser");
if (seleniumBrowser == null || seleniumBrowser.isEmpty())
{
if (isTestRunningOnTeamCity())
BROWSER_TYPE = BrowserType.FIREFOX;
else
BROWSER_TYPE = bestBrowser();
}
else if (seleniumBrowser.toLowerCase().contains("best"))
{
BROWSER_TYPE = bestBrowser();
}
else
{
for (BrowserType bt : BrowserType.values())
{
if (seleniumBrowser.toLowerCase().contains(bt.name().toLowerCase()))
{
BROWSER_TYPE = bt;
return;
}
}
BROWSER_TYPE = bestBrowser();
log("Unknown browser [" + seleniumBrowser + "]; Using best compatible browser [" + BROWSER_TYPE + "]");
}
}
public Set<String> getUrlsSeen()
{
return urlsSeen;
}
public static <T extends BaseWebDriverTest> T getCurrentTest()
{
return (T)currentTest;
}
private static Class<? extends BaseWebDriverTest> getCurrentTestClass()
{
return getCurrentTest() != null ? getCurrentTest().getClass() : null;
}
@Override
public WebDriver getWrappedDriver()
{
return SingletonWebDriver.getInstance().getWebDriver();
}
protected abstract String getProjectName();
public final @Nullable String getPrimaryTestProject()
{
return getProjectName();
}
@LogMethod
public void setUp()
{
if (_testFailed)
{
// In case the previous test failed so catastrophically that it couldn't clean up after itself
doTearDown();
}
SingletonWebDriver.getInstance().setUpWebDriver(this);
initWebDriverTimeouts();
closeExtraWindows();
if (!TestProperties.isCspCheckSkipped() && cspFailFast())
{
addPageLoadListener(_cspCheckPageLoadListener);
}
}
@LogMethod
private void initWebDriverTimeouts()
{
TestLogger.debug("set script timeout");
getDriver().manage().timeouts().scriptTimeout(Duration.ofMillis(WAIT_FOR_PAGE));
TestLogger.debug("page load timeout set");
getDriver().manage().timeouts().pageLoadTimeout(Duration.ofMillis(defaultWaitForPage));
}
/**
* Specifies whether the CSP log should be checked before each page load.
* Tests that only want the CSP log to be checked at the end should override this method.
* @return true to check for CSP violations before each navigation
*/
protected boolean cspFailFast()
{
return true;
}
public ArtifactCollector getArtifactCollector()
{
return _artifactCollector;
}
public final DeferredErrorCollector checker()
{
return TestProperties.isCheckerFatal() ? _errorCollector.fatal() : _errorCollector;
}
/**
* The browser that can run the test fastest.
* Firefox by default unless a faster browser (probably Chrome) has been verified.
*/
protected BrowserType bestBrowser()
{
return BrowserType.FIREFOX;
}
public BrowserType getBrowserType()
{
return BROWSER_TYPE;
}
@LogMethod
private static void doTearDown()
{
boolean closeWindow = !_testFailed || isRunWebDriverHeadless() || Boolean.parseBoolean(System.getProperty("close.on.fail", "true"));
SingletonWebDriver.getInstance().tearDown(closeWindow || isTestRunningOnTeamCity());
}
private void clearLastPageInfo()
{
_lastPageTitle = null;
_lastPageURL = null;
_lastPageText = null;
}
private void populateLastPageInfo()
{
clearLastPageInfo();
_lastPageTitle = getLastPageTitle();
_lastPageURL = getLastPageURL();
_lastPageText = getLastPageText();
}
public String getLastPageTitle()
{
if (_lastPageTitle == null)
{
if (null != getDriver().getTitle())
return getDriver().getTitle();
else
return "[no title: content type is not html]";
}
return _lastPageTitle;
}
public String getLastPageText()
{
return _lastPageText != null ? _lastPageText : getHtmlSource();
}
public URL getLastPageURL()
{
try
{
return _lastPageURL != null ? _lastPageURL : new URL(getDriver().getCurrentUrl());
}
catch (MalformedURLException x)
{
return null;
}
}
private static final String BEFORE_CLASS = "BeforeClass";
private static final String AFTER_CLASS = "AfterClass";
private static boolean beforeClassSucceeded = false;
private static boolean reenableMiniProfiler = false;
private static long previousLeakCheck = 0;
private static long testCount;
private static int currentTestNumber;
@ClassRule
public static RuleChain testClassWatcher()
{
TestWatcher innerClassWatcher = new TestWatcher()
{
@Override
public void starting(Description description)
{
SingletonWebDriver.getInstance().clear();
testCount = description.getChildren().stream().filter(child -> child.getAnnotation(Ignore.class) == null).count();
currentTestNumber = 0;
beforeClassSucceeded = false;
_anyTestFailed = false;
ArtifactCollector.init();
try
{
currentTest = (BaseWebDriverTest) description.getTestClass().getConstructor().newInstance();
}
catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e)
{
currentTest = null; // Make sure previous instance is cleared
throw new RuntimeException(e);
}
currentTest.setUp();
if (getDownloadDir().exists())
{
try{
FileUtils.deleteDirectory(getDownloadDir());
}
catch (IOException ignore) { }
}
currentTest.getContainerHelper().clearCreatedProjects();
currentTest.doPreamble();
}
@Override
protected void skipped(AssumptionViolatedException e, Description description)
{
getCurrentTest().checker().reportResults();
}
@Override
protected void succeeded(Description description)
{
getCurrentTest().checker().reportResults();
if (!_anyTestFailed)
getCurrentTest().doPostamble();
else
TestLogger.log("Skipping post-test checks because a test case failed.");
}
};
TestWatcher classFailWatcher = new TestWatcher()
{
@Override
protected void failed(Throwable e, Description description)
{
String pseudoTestName = beforeClassSucceeded ? AFTER_CLASS : BEFORE_CLASS;
if (getCurrentTest() != null && description.getTestClass().equals(getCurrentTestClass()))
{
getCurrentTest().handleFailure(e, pseudoTestName);
}
}
@Override
protected void finished(Description description)
{
// Skip teardown if another test has already started
if (description.getTestClass().equals(getCurrentTestClass()))
{
doTearDown();
if (!isTestCleanupSkipped())
{
try (TestScrubber scrubber = new TestScrubber(TestProperties.isTestRunningOnTeamCity() ? BrowserType.FIREFOX : getCurrentTest().getBrowserType(), getDownloadDir()))
{
scrubber.cleanSiteSettings();
}
}
}
}
};
/*
* Using Timeout at the class level isn't actually supported by JUnit.
* We do some extra magic to make sure subsequent test methods don't keep running
* when the class times out
*/
TestRule classTimeout = new TestWatcher()
{
Statement createFailOnTimeoutStatement(Statement statement, Class<?> testClass)
{
double timeoutMultiplier = TestProperties.getTimeoutMultiplier();
// No class timeout when running through IntelliJ or when multiplier is zero
if ("true".equals(System.getProperty("intellij.debug.agent")) || timeoutMultiplier == 0)
return statement;
long minutes;
ClassTimeout timeout = testClass.getAnnotation(ClassTimeout.class);
if (timeout != null)
minutes = timeout.minutes();
else
minutes = ClassTimeout.DEFAULT;
minutes *= timeoutMultiplier;
if (minutes == 0)
minutes = 1;
if (isLinkCheckEnabled())
{
// Increase timeout to account for crawler
minutes += TestProperties.getCrawlerTimeout().toMinutes();
minutes++;
}
if (!canConnectWithPrimaryUser())
{
// Increase timeout to allow initial user creation and testing
minutes += 3;
}
return FailOnTimeout.builder()
.withTimeout(minutes, TimeUnit.MINUTES)
.build(statement);
}
@Override
public Statement apply(Statement base, Description description)
{
try
{
return createFailOnTimeoutStatement(base, description.getTestClass());
}
catch (final Exception e)
{
return new Statement()
{
@Override public void evaluate()
{
throw new RuntimeException("Invalid parameters for Timeout", e);
}
};
}
}
@Override
protected void failed(Throwable e, Description description)
{
if (e instanceof TestTimedOutException || e instanceof InterruptedException)
{
SingletonWebDriver.getInstance().clear();
currentTest = null;
}
}
};
TestWatcher loggingClassWatcher = new TestWatcher()
{
@Override
public void starting(Description description)
{
TestLogger.resetLogger();
TestLogger.setTestLogContext("Before " + description.getTestClass().getSimpleName());
TestLogger.log("// BeforeClass - " + description.getTestClass().getSimpleName() + " \\\\");
TestLogger.increaseIndent();
}
@Override
protected void finished(Description description)
{
TestLogger.resetLogger();
TestLogger.log("\\\\ AfterClass Complete - " + description.getTestClass().getSimpleName() + " //");
TestLogger.setTestLogContext("");
}
};
TestWatcher lock = new TestWatcher()
{
@Override
public @NotNull Statement apply(Statement base, Description description)
{
final Statement statement = super.apply(base, description);
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
synchronized (BaseWebDriverTest.class)
{
statement.evaluate();
}
}
};
}
};
return RuleChain.outerRule(lock).around(loggingClassWatcher).around(classTimeout).around(classFailWatcher).around(innerClassWatcher);
}
private static boolean canConnectWithPrimaryUser()
{
try
{
String startPage = buildURL("project", "home", "start");
SimpleHttpResponse httpResponse = WebTestHelper.getHttpResponse(startPage);
return httpResponse.getResponseCode() < 400;
}
catch (RuntimeException re)
{
return false; // Probably a connection timeout
}
}
private void doPreamble()
{
signIn();
// Only do this as part of test startup if we haven't already checked. Since we do this as the last
// step in the test, there's no reason to bother doing it again at the beginning of the next test
if (!_checkedLeaksAndErrors && !"DRT".equals(System.getProperty("suite")))
{
if (!TestProperties.isTestRunningOnTeamCity())
{
// Running locally, pre-test errors are unlikely to be interesting. Clear them out.
resetErrors();
CspLogUtil.resetCspLogMark();
}
checker().addRecordableErrorType(WebDriverException.class);
checker().withScreenshot("startupErrors").wrapAssertion(this::checkErrors);
checker().withScreenshot("startupLeaks").wrapAssertion(this::checkLeaks);
checker().wrapAssertion(() -> CspLogUtil.checkNewCspWarnings(getArtifactCollector()));
checker().setErrorMark(); // Nothing to screenshot from CSP check
checker().resetErrorTypes();
_checkedLeaksAndErrors = true;
}
if (TestProperties.isTroubleshootingStacktracesEnabled())
{
enableTroubleshootingStacktraces();
}
setServerDebugLogging();
setOptionalFlags();
// Start logging JS errors.
resumeJsErrorChecker();
assertModulesAvailable(getAssociatedModules());
deleteSiteWideTermsOfUsePage();
try
{
enableEmailRecorder();
}
catch (AssumptionViolatedException | AssertionError ignore) { } // Tests should, generally, enable dumbster if they need it
reenableMiniProfiler = disableMiniProfiler();
if (isSystemMaintenanceDisabled())
{
// Disable scheduled system maintenance to prevent timeouts during nightly tests.
disableMaintenance();
}
cleanup(false);
new PipelineToolsHelper(this).resetPipelineToolsDirectory();
}
private void enableTroubleshootingStacktraces()
{
if (TestProperties.isPrimaryUserAppAdmin())
{
return; // app admin can't enable stack traces
}
Connection cn = createDefaultConnection();
SimplePostCommand command = new SimplePostCommand("mini-profiler", "enableTroubleshootingStacktraces");
JSONObject jsonObject = new JSONObject();
jsonObject.put("enabled", true);
command.setJsonObject(jsonObject);
try
{
CommandResponse r = command.execute(cn, null);
Map<String, Object> response = r.getParsedData();
log("Troubleshooting stacktraces state updated: " + response.get("data"));
}
catch (IOException | CommandException e)
{
throw new RuntimeException("Failed to enable troubleshooting stacktraces", e);
}
}
private void setServerDebugLogging()
{
Log4jUtils.resetAllLogLevels();
for (String pkg : TestProperties.getDebugLoggingPackages())
{
Log4jUtils.setLogLevel(pkg, ManagerPage.LoggingLevel.DEBUG);
}
}
private void assertModulesAvailable(List<String> modules)
{
if (modules != null && !modules.isEmpty())
{
Set<String> allModules = _containerHelper.getAllModules();
Set<String> missing = Collections.newSetFromMap(new CaseInsensitiveHashMap<>());
missing.addAll(modules);
missing.removeAll(allModules);
if (!missing.isEmpty()) // TODO: Make this a fail state so that tests fail quickly if required modules are missing
log(String.format("WARNING: Missing associated module%s [%s]. Ensure that you have these modules and that they are actually module, not controllers.", missing.size() > 1 ? "s" : "", String.join(", ", missing)));
}
}
public Timeout testTimeout()
{
return new Timeout(30, TimeUnit.MINUTES);
}
@Rule
public final RuleChain testRules()
{
TestWatcher _watcher = new TestWatcher()
{
@Override
public @NotNull Statement apply(Statement base, Description description)
{
final Statement statement = super.apply(base, description);
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
Assume.assumeTrue("Class timed out, skipping remaining tests", description.getTestClass().equals(getCurrentTestClass()));
statement.evaluate();
}
};
}
private void clearLocalStorage()
{
// Clears browser localStorage. Needed in order to reset some state such as grid filters/sorts/etc.
// which are sticky, but can interfere with what tests expect.
WebDriver driver = getDriver();
if (driver instanceof WebStorage webStorage)
{
webStorage.getLocalStorage().clear();
}
}
@Override
protected void starting(Description description)
{
// We know that @BeforeClass methods are done now that we are in a non-static context
beforeClassSucceeded = true;
if (TestProperties.isNewWebDriverForEachTest())
doTearDown();
setUp(); // Instantiate new WebDriver if needed
ensureSignedInAsPrimaryTestUser();
clearLocalStorage();
if (_testFailed)
resetErrors(); // Clear errors from a previously failed test
_testFailed = false;
}
@Override
protected void skipped(AssumptionViolatedException e, Description description)
{
succeeded(description);
}
@Override
protected void succeeded(Description description)
{
closeExtraWindows();
dismissAllAlerts();
checker().withScreenshot(description.getMethodName() + "_serverErrors").wrapAssertion(() -> checkErrors());
checker().reportResults();
}
};
// Separate TestWatcher to handle failures that happen in the nested succeeded method
TestWatcher _failWatcher = new TestWatcher()
{
@Override
protected void failed(Throwable e, Description description)
{
handleFailure(e, description.getMethodName());
}
@Override
protected void finished(Description description)
{
if (description.getTestClass().equals(getCurrentTestClass()))
{
Ext4Helper.resetCssPrefix();
}
}
};
TestWatcher _logger = new TestWatcher()
{
private long testStartTimeStamp;
@Override
protected void starting(Description description)
{
if (currentTestNumber == 0)
{
TestLogger.resetLogger();
TestLogger.log("\\\\ BeforeClass - " + description.getTestClass().getSimpleName() + " Complete //");
}
currentTestNumber++;
testStartTimeStamp = System.currentTimeMillis();
TestLogger.resetLogger();
TestLogger.setTestLogContext(description.getMethodName());
TestLogger.log("// Begin Test Case [" + currentTestNumber + "/" + testCount + "] - " + description.getMethodName() + " \\\\");
logToServer("=== Begin Test Case - " + description.getTestClass().getSimpleName() + "[" + currentTestNumber + "/" + testCount + "]." + description.getMethodName());
TestLogger.increaseIndent();
}
@Override
protected void skipped(AssumptionViolatedException e, Description description)
{
TestLogger.log(e.getMessage());
TestLogger.resetLogger();
TestLogger.log("\\\\ Test Case Skipped - " + description.getMethodName() + " //");
}
@Override
protected void succeeded(Description description)
{
long elapsed = System.currentTimeMillis() - testStartTimeStamp;
TestLogger.resetLogger();
TestLogger.log("\\\\ Test Case Complete - " + description.getMethodName() + TestLogger.formatElapsedTime(elapsed) + " //");
}
@Override
protected void failed(Throwable e, Description description)
{
long elapsed = System.currentTimeMillis() - testStartTimeStamp;
TestLogger.resetLogger();
TestLogger.log("\\\\ Failed Test Case - " + description.getMethodName() + TestLogger.formatElapsedTime(elapsed) + " //");
}
@Override
protected void finished(Description description)
{
if (currentTestNumber == testCount)
{
TestLogger.resetLogger();
TestLogger.setTestLogContext("After " + description.getTestClass().getSimpleName());
TestLogger.log("// AfterClass - " + description.getTestClass().getSimpleName() + " \\\\");
TestLogger.increaseIndent();
}
}
};
TestWatcher _lock = new TestWatcher()
{
@Override
public @NotNull Statement apply(Statement base, Description description)
{
final Statement statement = super.apply(base, description);
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
synchronized (description.getTestClass())
{
statement.evaluate();
}
}
};
}
};
Timeout timeoutRule = "true".equals(System.getProperty("intellij.debug.agent")) ? Timeout.millis(0) : testTimeout();
return RuleChain.outerRule(_lock).around(_logger).around(timeoutRule).around(_failWatcher).around(_watcher);
// return RuleChain.outerRule(_logger).around(timeoutRule).around(_failWatcher).around(_watcher);
}
/**
* Collect additional information about test failures and publish build artifacts for TeamCity
*/
@LogMethod
private void handleFailure(Throwable error, @LoggedParam String testName)
{
_testFailed = true;
_anyTestFailed = true;
if (error instanceof MultipleFailureException mfe)
{
// Only "handle" primary test failure. Just log failures thrown during @After or @AfterClass methods.
error = mfe.getFailures().get(0);
for (int i = 1; i < mfe.getFailures().size(); i++)
{
TestLogger.error("Secondary error after test:", mfe.getFailures().get(i));
}
}
TestLogger.error("Primary test failure:", error);
if (Thread.interrupted() || wasCausedBy(error, Arrays.asList(TestTimedOutException.class, InterruptedException.class)))
{
log("Test interrupted. Skipping failure handling");
return;
}
try
{
try
{
if (TestProperties.isDumpBrowserConsole())
{
dumpBrowserConsole();
}
}
catch (WebDriverException e)
{
log("Unable to dump console log");
TestLogger.error(e.getMessage(), e);
}
try
{
if (isTestRunningOnTeamCity())
{
getArtifactCollector().addArtifactLocation(TestFileUtils.getBaseFileRoot());
getArtifactCollector().dumpPipelineFiles();
}
}
catch (RuntimeException | Error e)
{
log("Unable to dump pipeline files");
TestLogger.error(e.getMessage(), e);
}
try
{
if (wasCausedBy(error, Arrays.asList(TestTimeoutException.class, SocketTimeoutException.class)))
ArtifactCollector.dumpThreads();
}
catch (RuntimeException | Error e)
{
log("Unable to dump threads");
TestLogger.error(e.getMessage(), e);
}
if (error instanceof UnreachableBrowserException || getWrappedDriver() == null)
{
log("Browser is unavailable. Skipping browser-dependant failure handling.");
return;
}
if (error instanceof UnhandledAlertException)
{
dismissAllAlerts();
}