Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,83 @@ browser.devTools().emulation().setGeolocationOverride(latitude, longitude, accur
```
See more DevTools use cases [here](./src/test/java/tests/usecases/devtools)

It is also possible to set mobile emulation capabilities (for chromium-based browsers) in resources/settings.json file, as well as to configure other arguments and options there:
```json
{
"browserName": "chrome",
"isRemote": false,
"remoteConnectionUrl": "http://qa-auto-nexus:4444/wd/hub",
"isElementHighlightEnabled": true,

"driverSettings": {
"chrome": {
"capabilities": {
"selenoid:options":
{
"enableVNC": true
},
"mobileEmulation": {
"userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19",
"deviceMetrics": {
"width": 660,
"height": 1040,
"pixelRatio": 3.0
},
"clientHints": {
"platform": "Android",
"mobile": true
}
},
"unhandledPromptBehavior": "ignore"
},
"options": {
"download.prompt_for_download": "false",
"download.default_directory": "./downloads"
},
"loggingPreferences": {
"Performance": "All"
},
"excludedArguments": [ "enable-automation" ],
"startArguments": [ "--disable-search-engine-choice-screen" ],
"pageLoadStrategy": "normal"
},
"safari": {
"options": {
"safari.options.dataDir": "/Users/username/Downloads"
}
}
},
"timeouts": {
"timeoutImplicit": 0,
"timeoutCondition": 30,
"timeoutScript": 10,
"timeoutPageLoad": 60,
"timeoutPollingInterval": 300,
"timeoutCommand": 60
},
"retry": {
"number": 2,
"pollingInterval": 300
},
"logger": {
"language": "en",
"logPageSource": true
},
"elementCache": {
"isEnabled": false
},
"visualization": {
"imageExtension": "png",
"maxFullFileNameLength": 255,
"defaultThreshold": 0.012,
"comparisonWidth": 16,
"comparisonHeight": 16,
"pathToDumps": "./src/test/resources/visualDumps/"
}
}
```


8. Quit browser at the end
```java
browser.quit();
Expand Down
18 changes: 18 additions & 0 deletions azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,21 @@ jobs:
mavenAuthenticateFeed: false
effectivePomSkip: false
sonarQubeRunAnalysis: false

- task: CopyFiles@2
displayName: 'Copy failure screenshots and test logs'
inputs:
SourceFolder: '$(Build.SourcesDirectory)/target'
Contents: |
surefire-reports/failure_screenshots/*.png
log/*.log
TargetFolder: '$(Build.ArtifactStagingDirectory)'
condition: succeededOrFailed()

- task: PublishBuildArtifacts@1
displayName: 'Publish copied artifacts'
inputs:
PathtoPublish: '$(Build.ArtifactStagingDirectory)'
ArtifactName: 'drop'
publishLocation: 'Container'
condition: succeededOrFailed()
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.AbstractDriverOptions;

import java.util.HashMap;
import java.util.Map;

public class ChromeSettings extends DriverSettings {
public class ChromeSettings extends ChromiumSettings {

public ChromeSettings(ISettingsFile settingsFile){
super(settingsFile);
Expand All @@ -17,39 +14,11 @@ public ChromeSettings(ISettingsFile settingsFile){
@Override
public AbstractDriverOptions<?> getDriverOptions() {
ChromeOptions chromeOptions = new ChromeOptions();
setChromePrefs(chromeOptions);
setCapabilities(chromeOptions);
setChromeArgs(chromeOptions);
setExcludedArguments(chromeOptions);
chromeOptions.setPageLoadStrategy(getPageLoadStrategy());
setupDriverOptions(chromeOptions);
setLoggingPreferences(chromeOptions, ChromeOptions.LOGGING_PREFS);
return chromeOptions;
}

private void setChromePrefs(ChromeOptions options){
HashMap<String, Object> chromePrefs = new HashMap<>();
Map<String, Object> configOptions = getBrowserOptions();
configOptions.forEach((key, value) -> {
if (key.equals(getDownloadDirCapabilityKey())) {
chromePrefs.put(key, getDownloadDir());
} else {
chromePrefs.put(key, value);
}
});
options.setExperimentalOption("prefs", chromePrefs);
}

private void setChromeArgs(ChromeOptions options) {
for (String arg : getBrowserStartArguments()) {
options.addArguments(arg);
}
}

@Override
public String getDownloadDirCapabilityKey() {
return "download.default_directory";
}

@Override
public BrowserName getBrowserName() {
return BrowserName.CHROME;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package aquality.selenium.configuration.driversettings;

import aquality.selenium.core.utilities.ISettingsFile;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.chromium.ChromiumOptions;
import org.openqa.selenium.logging.LoggingPreferences;

import java.util.HashMap;
import java.util.Map;

public abstract class ChromiumSettings extends DriverSettings {

private static final String MOBILE_EMULATION_CAPABILITY_KEY = "mobileEmulation";
private static final String DEVICE_METRICS_CAPABILITY_KEY = "deviceMetrics";
private static final String CLIENT_HINTS_CAPABILITY_KEY = "clientHints";

protected ChromiumSettings(ISettingsFile settingsFile){
super(settingsFile);
}

protected <T extends ChromiumOptions<T>> void setupDriverOptions(T options) {
setPrefs(options);
setCapabilities(options);
getBrowserStartArguments().forEach(options::addArguments);
setExcludedArguments(options);
options.setPageLoadStrategy(getPageLoadStrategy());
}

void setLoggingPreferences(MutableCapabilities options, String capabilityKey) {
if (!getLoggingPreferences().isEmpty()) {
LoggingPreferences logs = new LoggingPreferences();
getLoggingPreferences().forEach(logs::enable);
options.setCapability(capabilityKey, logs);
}
}

@Override
void setCapabilities(MutableCapabilities options) {
getBrowserCapabilities().forEach((key, value) -> {
if (key.equals(MOBILE_EMULATION_CAPABILITY_KEY)) {
Map<String, Object> mobileOptions = getMapOrEmpty(getDriverSettingsPath(CapabilityType.CAPABILITIES.getKey(), MOBILE_EMULATION_CAPABILITY_KEY));
if (mobileOptions.containsKey(DEVICE_METRICS_CAPABILITY_KEY)) {
Map<String, Object> deviceMetrics = getMapOrEmpty(getDriverSettingsPath(CapabilityType.CAPABILITIES.getKey(), MOBILE_EMULATION_CAPABILITY_KEY, DEVICE_METRICS_CAPABILITY_KEY));
mobileOptions.put(DEVICE_METRICS_CAPABILITY_KEY, deviceMetrics);
}
if (mobileOptions.containsKey(CLIENT_HINTS_CAPABILITY_KEY)) {
Map<String, Object> clientHints = getMapOrEmpty(getDriverSettingsPath(CapabilityType.CAPABILITIES.getKey(), MOBILE_EMULATION_CAPABILITY_KEY, CLIENT_HINTS_CAPABILITY_KEY));
mobileOptions.put(CLIENT_HINTS_CAPABILITY_KEY, clientHints);
}
((ChromiumOptions<?>)options).setExperimentalOption(key, mobileOptions);
} else {
options.setCapability(key, value);
}
});
}

protected <T extends ChromiumOptions<T>> void setPrefs(T options){
HashMap<String, Object> prefs = new HashMap<>();
Map<String, Object> configOptions = getBrowserOptions();
configOptions.forEach((key, value) -> {
if (key.equals(getDownloadDirCapabilityKey())) {
prefs.put(key, getDownloadDir());
} else {
prefs.put(key, value);
}
});
options.setExperimentalOption("prefs", prefs);
}


protected <T extends ChromiumOptions<T>> void setExcludedArguments(T chromiumOptions) {
chromiumOptions.setExperimentalOption("excludeSwitches", getExcludedArguments());
}

@Override
public String getDownloadDirCapabilityKey() {
return "download.default_directory";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.chromium.ChromiumOptions;
import org.openqa.selenium.logging.LoggingPreferences;

import java.io.File;
import java.io.IOException;
Expand Down Expand Up @@ -59,9 +57,13 @@ protected Map<String, Level> getLoggingPreferences() {
return loggingPreferences;
}

protected Map<String, Object> getMapOrEmpty(String path) {
return getSettingsFile().isValuePresent(path) ? getSettingsFile().getMap(path) : Collections.emptyMap();
}

private Map<String, Object> getMapOrEmpty(CapabilityType capabilityType) {
String path = getDriverSettingsPath(capabilityType);
Map<String, Object> map = getSettingsFile().isValuePresent(path) ? getSettingsFile().getMap(path) : Collections.emptyMap();
Map<String, Object> map = getMapOrEmpty(path);
logCollection("loc.browser.".concat(capabilityType.getKey()), map);
return map;
}
Expand Down Expand Up @@ -138,18 +140,6 @@ void setCapabilities(MutableCapabilities options) {
getBrowserCapabilities().forEach(options::setCapability);
}

<T extends ChromiumOptions<T>> void setExcludedArguments(T chromiumOptions) {
chromiumOptions.setExperimentalOption("excludeSwitches", getExcludedArguments());
}

void setLoggingPreferences(MutableCapabilities options, String capabilityKey) {
if (!getLoggingPreferences().isEmpty()) {
LoggingPreferences logs = new LoggingPreferences();
getLoggingPreferences().forEach(logs::enable);
options.setCapability(capabilityKey, logs);
}
}

@Override
public String getDownloadDir() {
Map<String, Object> browserOptions = getBrowserOptions();
Expand All @@ -162,7 +152,7 @@ public String getDownloadDir() {
throw new IllegalArgumentException(String.format("failed to find %s profiles option for %s", key, getBrowserName()));
}

private enum CapabilityType {
protected enum CapabilityType {
CAPABILITIES("capabilities"),
OPTIONS("options"),
START_ARGS("startArguments"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.remote.AbstractDriverOptions;

import java.util.HashMap;
import java.util.Map;

public class EdgeSettings extends DriverSettings {
public class EdgeSettings extends ChromiumSettings {

public EdgeSettings(ISettingsFile settingsFile){
super(settingsFile);
Expand All @@ -17,33 +14,11 @@ public EdgeSettings(ISettingsFile settingsFile){
@Override
public AbstractDriverOptions<?> getDriverOptions() {
EdgeOptions edgeOptions = new EdgeOptions();
setCapabilities(edgeOptions);
setPrefs(edgeOptions);
getBrowserStartArguments().forEach(edgeOptions::addArguments);
setExcludedArguments(edgeOptions);
edgeOptions.setPageLoadStrategy(getPageLoadStrategy());
setupDriverOptions(edgeOptions);
setLoggingPreferences(edgeOptions, EdgeOptions.LOGGING_PREFS);
return edgeOptions;
}

@Override
public String getDownloadDirCapabilityKey() {
return "download.default_directory";
}

private void setPrefs(EdgeOptions options){
HashMap<String, Object> prefs = new HashMap<>();
Map<String, Object> configOptions = getBrowserOptions();
configOptions.forEach((key, value) -> {
if (key.equals(getDownloadDirCapabilityKey())) {
prefs.put(key, getDownloadDir());
} else {
prefs.put(key, value);
}
});
options.setExperimentalOption("prefs", prefs);
}

@Override
public BrowserName getBrowserName() {
return BrowserName.EDGE;
Expand Down
3 changes: 2 additions & 1 deletion src/test/java/forms/MyLocationForm.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ public MyLocationForm() {
}

public double getLatitude() {
if (!lblLatitude.state().isDisplayed() && btnConsent.state().isDisplayed()) {
if (!lblLatitude.state().isDisplayed() && btnConsent.state().waitForDisplayed()) {
clickConsent();
}
lblLatitude.state().waitForDisplayed();
return Double.parseDouble(lblLatitude.getText());
}

Expand Down
34 changes: 34 additions & 0 deletions src/test/java/testreport/ScreenshotListener.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package testreport;

import aquality.selenium.browser.AqualityServices;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ScreenshotListener extends TestListenerAdapter {
@Override
public void onTestFailure(ITestResult result) {
String dateString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd_MM_yyyy_HH_mm_ss"));
String methodName = result.getName();
if (AqualityServices.isBrowserStarted()) {
try {
File scrFile = ((TakesScreenshot) AqualityServices.getBrowser().getDriver()).getScreenshotAs(OutputType.FILE);
String reportDirectory = String.format("%s/target/surefire-reports", new File(System.getProperty("user.dir")).getAbsolutePath());
File destFile = new File(String.format("%s/failure_screenshots/%s_%s.png", reportDirectory, methodName, dateString));
Files.createDirectories(destFile.getParentFile().toPath());
Files.copy(scrFile.toPath(), destFile.toPath());
Reporter.log(String.format("<a href='%s'> <img src='%s' height='100' width='100'/> </a>", destFile.getAbsolutePath(), destFile.getAbsolutePath()));
} catch (IOException e) {
AqualityServices.getLogger().fatal("An IO exception occurred while tried to save a screenshot", e);
}
}
}
}
Loading
Loading