Skip to content

Commit

Permalink
Improved failsafe ness of WebDriver properties
Browse files Browse the repository at this point in the history
  • Loading branch information
Mike Reiche committed Oct 19, 2021
1 parent 552756c commit 089203b
Show file tree
Hide file tree
Showing 9 changed files with 169 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@
import eu.tsystems.mms.tic.testframework.testing.DefaultTestController;
import eu.tsystems.mms.tic.testframework.testing.DefaultTestControllerOverrides;
import eu.tsystems.mms.tic.testframework.testing.TestController;
import eu.tsystems.mms.tic.testframework.utils.DefaultExecutionUtils;
import eu.tsystems.mms.tic.testframework.utils.DefaultFormatter;
import eu.tsystems.mms.tic.testframework.utils.ExecutionUtils;
import eu.tsystems.mms.tic.testframework.utils.Formatter;
import org.testng.annotations.Test;

Expand All @@ -76,6 +78,7 @@ protected void configure() {
bind(TestNGContextNameGenerator.class).to(DefaultTestNGContextGenerator.class).in(Scopes.SINGLETON);
bind(IdGenerator.class).to(SequenceIdGenerator.class).in(Scopes.SINGLETON);
bind(IExecutionContextController.class).to(DefaultExecutionContextController.class).in(Scopes.SINGLETON);
bind(ExecutionUtils.class).to(DefaultExecutionUtils.class).in(Scopes.SINGLETON);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Testerra
*
* (C) 2021, Mike Reiche, T-Systems MMS GmbH, Deutsche Telekom AG
*
* Deutsche Telekom AG and all other contributors /
* copyright owners license this file to you 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 eu.tsystems.mms.tic.testframework.utils;

public class DefaultExecutionUtils implements ExecutionUtils {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Testerra
*
* (C) 2021, Mike Reiche, T-Systems MMS GmbH, Deutsche Telekom AG
*
* Deutsche Telekom AG and all other contributors /
* copyright owners license this file to you 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 eu.tsystems.mms.tic.testframework.utils;

import eu.tsystems.mms.tic.testframework.logging.Loggable;
import java.util.Optional;
import java.util.function.Supplier;

public interface ExecutionUtils extends Loggable {
default <T> Optional<T> getFailsafe(Supplier<T> supplier) {
try {
T returnVal = supplier.get();
return Optional.ofNullable(returnVal);
} catch (Throwable e) {
log().warn("Unable to supply property", e);
return Optional.empty();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,20 @@
*/
package eu.tsystems.mms.tic.testframework.exceptions;

import eu.tsystems.mms.tic.testframework.common.Testerra;
import eu.tsystems.mms.tic.testframework.pageobjects.PageObject;
import eu.tsystems.mms.tic.testframework.utils.ExecutionUtils;
import org.openqa.selenium.WebDriver;

public class PageFactoryException extends RuntimeException {

private static final ExecutionUtils executionUtils = Testerra.getInjector().getInstance(ExecutionUtils.class);

public PageFactoryException(Class<? extends PageObject> pageClass, WebDriver webDriver, Throwable cause) {
super(String.format("Could not create instance of %s on \"%s\" (%s)",
pageClass.getSimpleName(),
(webDriver!=null)?webDriver.getTitle():"null",
(webDriver!=null)?webDriver.getCurrentUrl():"null"
executionUtils.getFailsafe(webDriver::getTitle).orElse("(na)"),
executionUtils.getFailsafe(webDriver::getCurrentUrl).orElse("(na)")
), cause);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ public class UITestUtils implements WebDriverManagerProvider {
* The logger for this class.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(UITestUtils.class);
private static final ExecutionUtils executionUtils = Testerra.getInjector().getInstance(ExecutionUtils.class);

/**
* A date format for files like screenshots.
Expand Down Expand Up @@ -108,46 +109,33 @@ public static void takeScreenshot(WebDriver webDriver, Screenshot screenshot) {
takeWebDriverScreenshotToFile(webDriver, screenshotFile);

// get page source (webdriver)
String pageSource = webDriver.getPageSource();

if (pageSource == null) {
LOGGER.error("getPageSource() returned nothing, skipping to add page source");
} else {
// save page source to file
executionUtils.getFailsafe(webDriver::getPageSource).ifPresent(pageSource -> {
savePageSource(pageSource, screenshot.createPageSourceFile());
}
});

Map<String, String> metaData = screenshot.getMetaData();
sessionContext.map(SessionContext::getSessionKey).ifPresent(s -> metaData.put(Screenshot.MetaData.SESSION_KEY, s));
sessionContext.map(SessionContext::getId).ifPresent(s -> metaData.put(Screenshot.MetaData.SESSION_CONTEXT_ID, s));
executionUtils.getFailsafe(webDriver::getTitle).ifPresent(s -> metaData.put(Screenshot.MetaData.TITLE, s));
executionUtils.getFailsafe(webDriver::getCurrentUrl).ifPresent(s -> metaData.put(Screenshot.MetaData.URL, s));

/*
get infos
window and focus infos
*/
try {
Map<String, String> metaData = screenshot.getMetaData();
metaData.put(Screenshot.MetaData.SESSION_KEY, sessionContext.map(SessionContext::getSessionKey).orElse(null));
metaData.put(Screenshot.MetaData.SESSION_CONTEXT_ID, sessionContext.map(SessionContext::getId).orElse(null));
metaData.put(Screenshot.MetaData.TITLE, webDriver.getTitle());

/*
window and focus infos
*/
String window = "";
String windowHandle = webDriver.getWindowHandle();
Set<String> windowHandles = webDriver.getWindowHandles();
if (windowHandles.size() < 2) {
window = "#1/1";
} else {
String[] handleStrings = windowHandles.toArray(new String[0]);
for (int i = 0; i < handleStrings.length; i++) {
if (handleStrings[i].equals(windowHandle)) {
window = "#" + (i + 1) + "/" + handleStrings.length;
}
String window = "";
String windowHandle = executionUtils.getFailsafe(webDriver::getWindowHandle).orElse("");
Set<String> windowHandles = webDriver.getWindowHandles();
if (windowHandles.size() < 2) {
window = "#1/1";
} else {
String[] handleStrings = windowHandles.toArray(new String[0]);
for (int i = 0; i < handleStrings.length; i++) {
if (handleStrings[i].equals(windowHandle)) {
window = "#" + (i + 1) + "/" + handleStrings.length;
}
}

metaData.put(Screenshot.MetaData.WINDOW, window);
metaData.put(Screenshot.MetaData.URL, webDriver.getCurrentUrl());
} catch (Exception e) {
LOGGER.warn("Unable to fulfill screenshot meta data: " + e.getMessage());
}
metaData.put(Screenshot.MetaData.WINDOW, window);
}

private static Screenshot takeScreenshot(WebDriver eventFiringWebDriver, String originalWindowHandle) {
Expand Down Expand Up @@ -267,12 +255,7 @@ private static void switchToWindow(WebDriver webDriver, String windowHandle) {
private static List<Screenshot> pTakeAllScreenshotsForSession(WebDriver webDriver) {
final List<Screenshot> screenshots = new LinkedList<>();
Set<String> windowHandles = webDriver.getWindowHandles();
String originalWindowHandle;
try {
originalWindowHandle = webDriver.getWindowHandle();
} catch (Exception e) {
originalWindowHandle = windowHandles.stream().findFirst().orElse("");
}
String originalWindowHandle = executionUtils.getFailsafe(webDriver::getWindowHandle).orElseGet(() -> windowHandles.stream().findFirst().orElse(""));

if (windowHandles.size() > 1) {
for (String windowHandle : windowHandles) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
package eu.tsystems.mms.tic.testframework.utils;

import eu.tsystems.mms.tic.testframework.common.PropertyManager;
import eu.tsystems.mms.tic.testframework.common.Testerra;
import eu.tsystems.mms.tic.testframework.constants.TesterraProperties;
import eu.tsystems.mms.tic.testframework.exceptions.SystemException;
import eu.tsystems.mms.tic.testframework.transfer.ThrowablePackedResponse;
Expand Down Expand Up @@ -56,6 +57,7 @@ public final class WebDriverUtils {
* Logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(WebDriverUtils.class);
private static final ExecutionUtils executionUtils = Testerra.getInjector().getInstance(ExecutionUtils.class);

/**
* Timeout / maximum duration for Window Switching
Expand All @@ -73,13 +75,7 @@ public static boolean switchToWindow(Predicate<WebDriver> predicate) {
}

public static boolean switchToWindow(WebDriver mainWebDriver, Predicate<WebDriver> predicate) {
String mainWindowHandle;
try {
mainWindowHandle = mainWebDriver.getWindowHandle();
} catch (Exception e) {
mainWindowHandle = "";
}
String finalMainWindowHandle = mainWindowHandle;
String finalMainWindowHandle = executionUtils.getFailsafe(mainWebDriver::getWindowHandle).orElse("");

return mainWebDriver.getWindowHandles().stream()
.filter(windowHandle -> !windowHandle.equals(finalMainWindowHandle))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
*/
package eu.tsystems.mms.tic.testframework.webdrivermanager;

import eu.tsystems.mms.tic.testframework.common.Testerra;
import eu.tsystems.mms.tic.testframework.logging.Loggable;
import eu.tsystems.mms.tic.testframework.utils.ExecutionUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
Expand All @@ -30,6 +32,8 @@

public class EventLoggingEventDriverListener implements WebDriverEventListener, Loggable {

private static final ExecutionUtils executionUtils = Testerra.getInjector().getInstance(ExecutionUtils.class);

@Override
public void beforeAlertAccept(WebDriver webDriver) {

Expand Down Expand Up @@ -131,7 +135,7 @@ public void beforeSwitchToWindow(String s, WebDriver webDriver) {

@Override
public void afterSwitchToWindow(String s, WebDriver webDriver) {
log().info(String.format("Switched to window \"%s\" (%s)", webDriver.getTitle(), webDriver.getCurrentUrl()));
log().info(String.format("Switched to window \"%s\" (%s)", executionUtils.getFailsafe(webDriver::getTitle).orElse("(na)"), executionUtils.getFailsafe(webDriver::getCurrentUrl).orElse("(na)")));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Testerra
*
* (C) 2021, Mike Reiche, T-Systems MMS GmbH, Deutsche Telekom AG
*
* Deutsche Telekom AG and all other contributors /
* copyright owners license this file to you 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 eu.tsystems.mms.tic.testframework.test.utils;

import eu.tsystems.mms.tic.testframework.common.Testerra;
import eu.tsystems.mms.tic.testframework.internal.utils.ExceptionUtils;
import eu.tsystems.mms.tic.testframework.testing.TesterraTest;
import eu.tsystems.mms.tic.testframework.utils.ExecutionUtils;
import java.util.Optional;
import org.testng.Assert;
import org.testng.annotations.Test;

public class ExecutionUtilsTest extends TesterraTest {

@Test
public void test_getFailsafe() {
String expected = "katze";
ExecutionUtils executionUtils = Testerra.getInjector().getInstance(ExecutionUtils.class);
Optional<Object> failsafe = executionUtils.getFailsafe(() -> {
return expected;
});

Assert.assertEquals(failsafe.get(), expected);
}

@Test
public void test_getFailsafe_null() {
ExecutionUtils executionUtils = Testerra.getInjector().getInstance(ExecutionUtils.class);
Optional<Object> failsafe = executionUtils.getFailsafe(() -> {
return null;
});

Assert.assertFalse(failsafe.isPresent());
}

@Test
public void test_getFailsafe_NPE() {
ExecutionUtils executionUtils = Testerra.getInjector().getInstance(ExecutionUtils.class);
Optional<Object> failsafe = executionUtils.getFailsafe(() -> {
String expected = null;
return expected.trim();
});

Assert.assertFalse(failsafe.isPresent());
}
}

0 comments on commit 089203b

Please sign in to comment.