Skip to content

Commit

Permalink
Merge branch 'master' into bugfix/create-request
Browse files Browse the repository at this point in the history
  • Loading branch information
GannaChernyshova committed Apr 3, 2018
2 parents ca7c04c + 15ca441 commit dfd6765
Show file tree
Hide file tree
Showing 7 changed files with 247 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ public void replaceCookie(String cookieName, String cookieValue){
public void switchToTheNextTab() {
String nextWindowHandle = nextWindowHandle();
getWebDriver().switchTo().window(nextWindowHandle);
akitascenario.write("Текущая вкладка " + nextWindowHandle);
}

/**
Expand Down
38 changes: 26 additions & 12 deletions src/main/java/ru/alfabank/steps/DefaultSteps.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,13 @@
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.codeborne.selenide.Condition.not;
import static com.codeborne.selenide.Selenide.*;
import static com.codeborne.selenide.WebDriverRunner.getWebDriver;
import static com.codeborne.selenide.WebDriverRunner.url;
import static java.util.Objects.isNull;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
Expand Down Expand Up @@ -71,6 +73,7 @@ public class DefaultSteps {
@И("^сохранено значение \"([^\"]*)\" из property файла в переменную \"([^\"]*)\"$")
public void saveValueToVar(String propertyVariableName, String variableName) {
akitaScenario.setVar(variableName, loadProperty(propertyVariableName));
akitaScenario.write("Знечение сохраненной переменной " + variableName);
}

/**
Expand Down Expand Up @@ -319,6 +322,7 @@ public void setWindowSize(String widthRaw, String heightRaw) {
int width = Integer.valueOf(widthRaw);
int height = Integer.valueOf(heightRaw);
WebDriverRunner.getWebDriver().manage().window().setSize(new Dimension(width, height));
akitaScenario.write("Установлены размеры окна браузера: ширина " + widthRaw + " высота" + heightRaw);
}

/**
Expand Down Expand Up @@ -415,6 +419,7 @@ public void checkListInnerTextCorrespondsToListFromVariable(String listName, Str
@Когда("^значение (?:элемента|поля) \"([^\"]*)\" сохранено в переменную \"([^\"]*)\"")
public void storeElementValueInVariable(String elementName, String variableName) {
akitaScenario.setVar(variableName, akitaScenario.getCurrentPage().getAnyElementText(elementName));
akitaScenario.write("Значение сохраненное в переменную: " + akitaScenario.getCurrentPage().getAnyElementText(elementName));
}

/**
Expand Down Expand Up @@ -652,6 +657,7 @@ public void currentDate(String fieldName, String dateFormat) {
SelenideElement valueInput = akitaScenario.getCurrentPage().getElement(fieldName);
valueInput.setValue("");
valueInput.setValue(currentStringDate);
akitaScenario.write("Текущая дата " + currentStringDate);
}

/**
Expand Down Expand Up @@ -701,6 +707,7 @@ public void selectRandomElementFromList(String listName) {
List<SelenideElement> listOfElementsFromPage = akitaScenario.getCurrentPage().getElementsList(listName);
listOfElementsFromPage.get(getRandom(listOfElementsFromPage.size()))
.shouldBe(Condition.visible).click();
akitaScenario.write("Выбран случайный элемент: " + listOfElementsFromPage);
}

/**
Expand Down Expand Up @@ -748,6 +755,7 @@ public void setRandomCharSequence(String elementName, int seqLength, String lang
else lang = "en";
String charSeq = getRandCharSequence(seqLength, lang);
valueInput.setValue(charSeq);
akitaScenario.write("Строка случайных символов равна :" + charSeq);
}

/**
Expand Down Expand Up @@ -776,17 +784,24 @@ public void checkFieldSymbolsCount(String element, int num) {
* @return
*/
public String getPropertyOrStringVariableOrValue(String propertyNameOrVariableNameOrValue) {
String returnValue = tryLoadProperty(propertyNameOrVariableNameOrValue);
if (returnValue == null) {
log.warn("Переменная " + propertyNameOrVariableNameOrValue + " в property файле не найдена");
returnValue = (String)akitaScenario.tryGetVar(propertyNameOrVariableNameOrValue);
if (returnValue == null) {
log.warn("Переменная сценария " + propertyNameOrVariableNameOrValue + " не найдена");
returnValue = propertyNameOrVariableNameOrValue;
}
}
String propertyValue = tryLoadProperty(propertyNameOrVariableNameOrValue);
String variableValue = (String) akitaScenario.tryGetVar(propertyNameOrVariableNameOrValue);

boolean propertyCheck = checkResult(propertyValue, "Переменная из property файла");
boolean variableCheck = checkResult(variableValue, "Переменная сценария");
checkResult(propertyNameOrVariableNameOrValue, "Переменная переданная на вход");

return propertyCheck ? propertyValue : (variableCheck ? variableValue : propertyNameOrVariableNameOrValue);
}

return returnValue;
private boolean checkResult(String result, String message) {
if (isNull(result)) {
log.warn(message + " не найдена");
return false;
}
log.info(message + result);
akitaScenario.write(message + result);
return true;
}

/**
Expand Down Expand Up @@ -841,8 +856,7 @@ private char charGenerator(String lang) {
Random random = new Random();
if (lang.equals("ru")) {
return (char) (1072 + random.nextInt(32));
}
else {
} else {
return (char) (97 + random.nextInt(26));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import lombok.extern.slf4j.Slf4j;
import net.lightbody.bmp.BrowserMobProxy;
import net.lightbody.bmp.BrowserMobProxyServer;
import net.lightbody.bmp.proxy.BlacklistEntry;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
Expand All @@ -28,10 +29,13 @@
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import ru.alfabank.tests.core.helpers.BlackList;

import java.net.MalformedURLException;
import java.net.URI;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import static com.codeborne.selenide.WebDriverRunner.*;
Expand Down Expand Up @@ -59,30 +63,32 @@ public class CustomDriverProvider implements WebDriverProvider {
public final static String REMOTE_URL = "remoteUrl";
public final static String WINDOW_WIDTH = "width";
public final static String WINDOW_HEIGHT = "height";
private BrowserMobProxy proxy = new BrowserMobProxyServer();

@Override
public WebDriver createDriver(DesiredCapabilities capabilities) {
String expectedBrowser = loadSystemPropertyOrDefault(BROWSER, CHROME);
String remoteUrl = loadSystemPropertyOrDefault(REMOTE_URL, "local");
BlackList blackList = new BlackList();

if (FIREFOX.equalsIgnoreCase(expectedBrowser)) {
capabilities = getFirefoxDriverCapabilities();
return "local".equalsIgnoreCase(remoteUrl) ? new FirefoxDriver() : getRemoteDriver(capabilities, remoteUrl);
return "local".equalsIgnoreCase(remoteUrl) ? new FirefoxDriver() : getRemoteDriver(capabilities, remoteUrl, blackList.getBlacklistEntries());
}

if (MOBILE_DRIVER.equalsIgnoreCase(expectedBrowser)) {
capabilities.setCapability(ChromeOptions.CAPABILITY, getMobileChromeOptions());
return "local".equalsIgnoreCase(remoteUrl) ? new ChromeDriver(getMobileChromeOptions()) : getRemoteDriver(capabilities, remoteUrl);
return "local".equalsIgnoreCase(remoteUrl) ? new ChromeDriver(getMobileChromeOptions()) : getRemoteDriver(capabilities, remoteUrl, blackList.getBlacklistEntries());
}

if (OPERA.equalsIgnoreCase(expectedBrowser)) {
capabilities = getOperaDriverCapabilities();
return "local".equalsIgnoreCase(remoteUrl) ? new OperaDriver() : getRemoteDriver(capabilities, remoteUrl);
return "local".equalsIgnoreCase(remoteUrl) ? new OperaDriver() : getRemoteDriver(capabilities, remoteUrl, blackList.getBlacklistEntries());
}

log.info("remoteUrl=" + remoteUrl + " expectedBrowser= " + expectedBrowser + " BROWSER_VERSION=" + System.getProperty(BROWSER_VERSION));
capabilities = getChromeDriverCapabilities();
return "local".equalsIgnoreCase(remoteUrl) ? new ChromeDriver() : getRemoteDriver(capabilities, remoteUrl);
return "local".equalsIgnoreCase(remoteUrl) ? new ChromeDriver() : getRemoteDriver(capabilities, remoteUrl, blackList.getBlacklistEntries());
}

/**
Expand All @@ -109,6 +115,19 @@ private WebDriver getRemoteDriver(DesiredCapabilities capabilities, String remot
}
}

/** Задает capabilities для запуска Remote драйвера для Selenoid
* со списком регулярных выражений соответствующих URL, которые добавляются в Blacklist
*
* @param capabilities
* @param remoteUrl
* @param blacklistEntries - список url для добавления в Blacklist
* @return
*/
private WebDriver getRemoteDriver(DesiredCapabilities capabilities, String remoteUrl, List<BlacklistEntry> blacklistEntries) {
proxy.setBlacklist(blacklistEntries);
return getRemoteDriver(capabilities, remoteUrl);
}

/**
* Устанавливает ChromeOptions для запуска google chrome эмулирующего работу мобильного устройства (по умолчанию nexus 5)
* Название мобильного устройства (device) может быть задано через системные переменные
Expand Down
69 changes: 69 additions & 0 deletions src/main/java/ru/alfabank/tests/core/helpers/BlackList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/**
* Copyright 2017 Alfa Laboratory
*
* 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 ru.alfabank.tests.core.helpers;

import net.lightbody.bmp.proxy.BlacklistEntry;

import java.util.ArrayList;
import java.util.List;

public class BlackList {
private List<BlacklistEntry> blacklistEntries = new ArrayList<>();

private BlackListManager blackListManager = new BlackListManager();

public BlackList() {
setDefaultBlacklistEntries();
}

public BlackList(List<BlacklistEntry> newEntries) {
setNewBlacklistEntries(newEntries);
}

/**
* Список регулярных выражений соответствующих URL, которые добавляются в Blacklist по умолчанию
*/
private void setDefaultBlacklistEntries() {
blackListManager.fillBlackList(blacklistEntries);
}

/**
* очищает дефолтный сисок URL из Blacklist и задает новый Blacklist
* @param newEntries - новый список URL для доавления в Blacklist
*/
private void setNewBlacklistEntries(List<BlacklistEntry> newEntries) {
blacklistEntries.clear();
blacklistEntries.addAll(newEntries);
}

/**
*
* @return - спискок URL, которые находятся в Blacklist
*/
public List<BlacklistEntry> getBlacklistEntries() {
return blacklistEntries;
}


/**
* добавляет новые URL к дефолтному Blacklist
*
* @param newEntries - новые URL, которые будут добавлены в Blacklist
*/
public void addToDefaultBlacklistEntries(List<BlacklistEntry> newEntries) {
blacklistEntries.addAll(newEntries);
}
}
59 changes: 59 additions & 0 deletions src/main/java/ru/alfabank/tests/core/helpers/BlackListManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* Copyright 2017 Alfa Laboratory
*
* 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 ru.alfabank.tests.core.helpers;

import net.lightbody.bmp.proxy.BlacklistEntry;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BlackListManager {
/**
* Производится парсинг строки из файла blacklist на наличие ссылок типа:
* .*ru.fp.kaspersky-labs.com.*
* http://google.com/ 200
* При необходимости можно указывать статус код, по умолчанию будет присвоен 404
* @param blacklistEntries - список ссылок и статус кодов
*/
public void fillBlackList(List<BlacklistEntry> blacklistEntries) {
String file = getResource();
Pattern pattern = Pattern.compile("((https?:\\/\\/)?([\\da-z\\.\\*-]+)\\.([a-z\\.]{2,6})([\\/\\w\\.\\*-]*)*\\/?)\\s?(\\d{3})*");
Matcher matcher = pattern.matcher(file);
while (matcher.find()) {
if (matcher.group(6) == null)
blacklistEntries.add(new BlacklistEntry(matcher.group(1), 404));
else blacklistEntries.add(new BlacklistEntry(matcher.group(1), Integer.parseInt(matcher.group(6))));
}
}

private String getResource() {
ClassLoader classLoader = getClass().getClassLoader();
byte[] file = new byte[0];
try {
file = Files.readAllBytes(new File(classLoader.getResource("blacklist").getFile()).toPath());
return new String(file, "UTF-8");
} catch (IOException e) {
System.out.println("Файла 'blacklist' - не существует\n");
e.printStackTrace();
}
return new String(file);
}

}
65 changes: 65 additions & 0 deletions src/test/java/ru/alfabank/core/BlackListTests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* Copyright 2017 Alfa Laboratory
*
* 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 ru.alfabank.core;


import net.lightbody.bmp.proxy.BlacklistEntry;
import org.junit.Before;
import org.junit.Test;
import ru.alfabank.tests.core.helpers.BlackList;
import ru.alfabank.tests.core.helpers.BlackListManager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs;

public class BlackListTests {
private static List<BlacklistEntry> defaultBlacklistEntries = new ArrayList<>();

@Test
public void testGetDefaultBlacklistEntries() {
BlackList blackList = new BlackList();
assertThat(defaultBlacklistEntries, samePropertyValuesAs(blackList.getBlacklistEntries()));
}

@Test
public void testAddToDefaultBlacklistEntries() {
List<BlacklistEntry> expectedEntries = new ArrayList<>();
expectedEntries.addAll(defaultBlacklistEntries);

List<BlacklistEntry> newEntries = new ArrayList<>(Arrays.asList(new BlacklistEntry("new.entry", 404)));
expectedEntries.addAll(newEntries);

BlackList blackList = new BlackList();
blackList.addToDefaultBlacklistEntries(newEntries);
assertThat(expectedEntries, samePropertyValuesAs(blackList.getBlacklistEntries()));
}

@Test
public void testNewBlacklistEntries() {
List<BlacklistEntry> newEntries = new ArrayList<>(Arrays.asList(new BlacklistEntry("new.entry", 404)));
BlackList blackList = new BlackList(newEntries);
assertThat(newEntries, samePropertyValuesAs(blackList.getBlacklistEntries()));
}

@Before
public void initBlackList() {
new BlackListManager().fillBlackList(defaultBlacklistEntries);
}
}
4 changes: 4 additions & 0 deletions src/test/resources/blacklist
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.*ru.fp.kaspersky-labs.com.*
.*google-analytics.com.*
.*yastatic.net.*
.*googletagmanager.com.* 200

0 comments on commit dfd6765

Please sign in to comment.