96 lines
3.0 KiB
Java
96 lines
3.0 KiB
Java
package ru.kovbasa.driver;
|
|
|
|
import com.google.inject.Inject;
|
|
import org.openqa.selenium.WebDriver;
|
|
import org.openqa.selenium.support.events.EventFiringDecorator;
|
|
|
|
import io.github.bonigarcia.wdm.WebDriverManager;
|
|
import ru.kovbasa.config.TestConfig;
|
|
import ru.kovbasa.listeners.HighlightElementListener;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.InputStreamReader;
|
|
import java.util.Optional;
|
|
import java.util.regex.Matcher;
|
|
import java.util.regex.Pattern;
|
|
|
|
public final class WebDriverProvider {
|
|
|
|
private WebDriver driver;
|
|
private final DriverFactory driverFactory;
|
|
|
|
@Inject
|
|
public WebDriverProvider(DriverFactory driverFactory) {
|
|
this.driverFactory = driverFactory;
|
|
}
|
|
|
|
public WebDriver getDriver() {
|
|
if (driver == null) {
|
|
driver = createDecoratedDriver();
|
|
}
|
|
return driver;
|
|
}
|
|
|
|
private WebDriver createDecoratedDriver() {
|
|
if (!TestConfig.isSelenoidMode()) {
|
|
final String chromeVersion = detectChromeMajorVersion().orElse(null);
|
|
if (chromeVersion != null) {
|
|
WebDriverManager.chromedriver().browserVersion(chromeVersion).setup();
|
|
} else {
|
|
WebDriverManager.chromedriver().setup();
|
|
}
|
|
}
|
|
final WebDriver raw = driverFactory.createDriver();
|
|
return new EventFiringDecorator(new HighlightElementListener())
|
|
.decorate(raw);
|
|
}
|
|
|
|
public void quit() {
|
|
if (driver != null) {
|
|
driver.quit();
|
|
driver = null;
|
|
}
|
|
}
|
|
|
|
private Optional<String> detectChromeMajorVersion() {
|
|
final String os = System.getProperty("os.name", "").toLowerCase();
|
|
if (!os.contains("linux")) {
|
|
return Optional.empty();
|
|
}
|
|
|
|
final String[] commands = new String[] {
|
|
"chromium --version",
|
|
"chromium-browser --version",
|
|
"google-chrome --version"
|
|
};
|
|
for (String cmd : commands) {
|
|
final Optional<String> version = runVersionCommand(cmd);
|
|
if (version.isPresent()) {
|
|
return version;
|
|
}
|
|
}
|
|
return Optional.empty();
|
|
}
|
|
|
|
private Optional<String> runVersionCommand(String command) {
|
|
try {
|
|
final Process process = new ProcessBuilder("sh", "-c", command)
|
|
.redirectErrorStream(true)
|
|
.start();
|
|
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
|
|
final String output = reader.readLine();
|
|
if (output == null) {
|
|
return Optional.empty();
|
|
}
|
|
final Matcher matcher = Pattern.compile("(\\d+)\\.").matcher(output);
|
|
if (matcher.find()) {
|
|
return Optional.of(matcher.group(1));
|
|
}
|
|
}
|
|
} catch (Exception ignored) {
|
|
// Best-effort detection only.
|
|
}
|
|
return Optional.empty();
|
|
}
|
|
}
|