snakeyaml -> jackson-dataformat-yaml
2023년 2월 3일 금요일
unix timestamp 13 digit compare
Intstant instant = Instant.ofEpochMilli(Long.parseLong(String timestamp));
Instant current = Instant.now();
instant.compareTo(current);
1 : t1 > t2
0 : t1 == t2
-1 : t1 < t2
2023년 1월 7일 토요일
2020년 11월 16일 월요일
.gitignore 파일 규칙
.gitignore 파일이란?
사용자가 원하지 않는 파일들을 자동으로 git commit 대상에서 제외하도록 규칙을 작성
원하지 않는 파일은?
- IDE tool과 관련된 설정파일
- 언어의 빌드 결과물, 로그 패키지 관련 파일
- 사용자가 제외하기 원하는 파일 등
- gitignore 참고 url : https://github.com/github/gitignore
.gitignore 파일 위치는?
프로젝트 최상단 폴더에 위치시키면 된다.
.gitignore 파일 규칙
- #은 주석 역할
- 표준 glob 패턴 사용
- / 를 사용하면 규칙이 프로젝트 전체에 적용되지 않음
- / 로 끝나는 것은 폴더로 인식
- ! 를 사용하면 무시되지 않음
.gitignore sample
#*#
.#*
*~
_site/
*/src/META-INF/
*/src/main/java/META-INF/
bin/
target/
.classpath
.project
.DS_Store
.settings/
.springBeans
*.iml
*.iws
*.ipr
.idea/
code/
cargo-installs/
atlassian-ide-plugin.xml
deploy/
# 모든 확장자 .txt 파일을 무시
*.txt
# 무시하는 모든 확장자 .txt 파일들 중에서 test.txt 파일은 무시하지 않음
!test.txt
# Project/
# ㄴ.gitignore
# ㄴsrc/
# ㄴabc.txt
# ㄴTODO/
# ㄴtest1.txt
# ㄴTODO/
# ㄴtest2.txt
#
# 현재 폴더 중에서 TODO 폴더에 있는 모든 파일을 무시
# (즉, test1.txt 파일만 무시되고 test2.txt 파일은 무시되지 않음)
/TODO
# 프로젝트 전체 폴더 중 TODO라는 폴더명을 사용하는 TODO 폴더의 하위 파일은 모두 무시
# (즉, test1.txt 파일과 test2.txt 파일 모두 무시됨)
TODO/
# Project/
# ㄴ.gitignore
# ㄴdoc/
# ㄴa.txt
# ㄴb.pdf
# ㄴserver/
# ㄴaa.txt
# ㄴbb.pdf
#
# 현재 폴더 중에서 doc 폴더 바로 밑에 있는 .txt 확장자 파일만 모두 무시
# 단, doc/server/aa.txt 와 같은 형식에서는 .txt 확장자 파일이 무시되지 않음
doc/*.txt
# 현재 폴더 중에서 doc 폴더 하위에 있는 .pdf 확장자 파일은
# doc 폴더 하위 어떤 폴더에 들어 있더라도 모두 무시
# (즉, b.pdf 파일과 bb.pdf 파일 모두 무시됨)
doc/**/*.pdf
Git 원격 및 로컬 디렉토리 연동방법
1. git init //저장소 초기화
2. git add 파일명(폴더) //파일 및 폴더 추가
3. git commit -m "first commit" //commit
4. git remote add origin URL //원격 저장소 연동
5. git push -u origin master <리모트 저장소 이름> <push할 브랜치 이름> //파일 및 폴더 push
2020년 11월 9일 월요일
element.click으로 브라우져의 새 탭이 열렸을 때 driver 제어 방법
element.click 으로 같은 화면에서 UI가 갱신되는 게 아니라 새 탭이 열렸을 경우,
selenium driver에 알려줘야 한다.
그렇지 않으면 기존에 오픈 된 브라우져의 화면에서 element를 찾게 되어 no such element 에러 메시지를 보게 된다.
[How to]
//driver 제어를 위한 현재 열려있는 브라우져 확인
String parentWindow = driver.getWindowHandle();
element.click();
String childWindow = null;
for(String childs: driver.getWindowHandles()){
if(!childs.equals(parentWindow)){
childWindow = childs;
break;
}
}
driver.switchTo().window(childWindow);
2020년 11월 6일 금요일
Hamcrest Test Framework
Hamcrest란?
test framework을 이용하여 단위 테스트 진행 시 assert를 유연하게 하기 위해 matcher를 이용하여 좀 더 쉽고 확장성 있는 assert를 하기 위해 만들어진 framework이다.
Hamcrest는 처음부터 test framework과 통합되도록 설계되어 JUnit, TestNG와 함께 사용할 수 있다.
maven dependency
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
Hamcrest code
assertThat(actual, is(equalTo(expedted);
assertThat(result, instanceof String);
assertThat(result, is(hasItem(anyOf(equalTo("x", equalTo("y"), equalTo("z"))))));Hamcrest Matcher
2020년 1월 22일 수요일
Python Test Code 예제
import unittest class ArithTest(unittest.TestCase): def runTest(self): """ Test addition and succeed. """ self.failUnless(1 + 1 == 2, ‘one plus one fails!’) self.failIf(1 + 1 != 2, ‘one plus one fails again!’) self.failUnlessEqual(1 + 1, 2, ‘more trouble with one plus one!’) def suite(): suite = unittest.TestSuite() suite.addTest(ArithTest()) return suite if __name__ == ‘__main__’: runner = unittest.TextTestRunner() test_suite = suite() runner.run(test_suite)
Selenium WebDriver setting
public class LaunchWebDriver { private static final Logger logger = LoggerFactory.getLogger(UserPageTest.class); WebDriver driver; public LaunchWebDriver(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } public WebDriver launchWebDriverMode(String headlessOnOff) { Path path = Paths.get(""); String pathStr = path.toAbsolutePath().toString(); logger.debug("pathStr={}", pathStr); /* MAC 과 WINDOWS chromedriver 분기 */ if (isWindows()) { System.setProperty("webdriver.chrome.driver", pathStr + "//driver//chromedriver.exe"); } else if (isMac()) { System.setProperty("webdriver.chrome.driver", pathStr + "//driver//chromedriver"); } else { logger.error("지원하지 않는 OS 입니다."); return null; } ChromeOptions co = new ChromeOptions(); logger.debug("computername={}", System.getenv("computername")); /* 공통 ChromeOptions 값. */ co.addArguments("start-maximized"); co.addArguments("enable-automation"); co.addArguments("--disable-gpu"); if (isWindows() && "NG-BF".equals(System.getenv("computername"))) { /* Jenkins 서버(windows)는 항상 headless 모드이다 (java.awt.headless = true) */ logger.debug("headless Mode : NG-BF is Always headlessMode"); /* jenkins 에만 추가되는 ChromeOptions 값. */ co.addArguments("--no-sandbox"); } else { if ("On".equals(headlessOnOff)) { // On / Off /* headless chrome */ co.addArguments("--headless"); } } driver = new ChromeDriver(co); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // 기본 대기 시간 driver.manage().window().maximize(); return driver; } public static boolean isWindows() { return (OS.isFamilyWindows()); } public static boolean isMac() { return (OS.isFamilyMac()); } }
public abstract class BaseTest { public WebDriver driver; public LaunchWebDriver launchWebDriver; @BeforeClass public void setUp(){ System.out.println("*** before class ****"); String headlessOnOff ="On"; // headless = On or Off launchWebDriver = new LaunchWebDriver(driver); driver = launchWebDriver.launchWebDriverMode(headlessOnOff); if(driver == null){ Assert.assertTrue(false); } } @AfterClass public void tearDown(){ System.out.println("*** after class ****"); if( driver != null) driver.quit(); } @AfterTest public void afterTest() throws IOException { System.out.println("*** after test ****"); if( LaunchWebDriver.isWindows() ){ Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe /T"); } } }
2020년 1월 17일 금요일
test 메소드 이름 알아오기
@Test public void test(){ StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); String methodName = stackTraceElements[1].getMethodName(); }
Spec by Exam
| TC No | Test Level | Assertion | Precondition | Input | Output | Comment |
Test Level
Positive
P-Mandatory : 필수 파라메타로 기본 기능 검증
P-ALL : 모든 파라메타로 기본 기능 검증
P-InRange : 필수 파라메타에 대한 범위 검증, 조건부 필수 파라메타에 대한 범위 내 검증, 옵션 파라메타에 대한 범위 내 검증
Negative
N-isMandatory : 파라메타 존재에 대한 예외 처리 검증
N-OutRange : 유효하지 않은 값에 대한 예외 처리 검증
N-Restriction : 파라메타 별 제약 사항 검증
TestNG의 ReportNG 설정법
<dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>${selenium.java.version}</version> </dependency> <dependency> <groupId>org.uncommons</groupId> <artifactId>reportng</artifactId> <version>${reportng.version}</version> </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> <version>${guice.version}</version> </dependency> ...... </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>${maven.surefire.version}</version> <configuration> <encoding>UTF-8</encoding> <argLine>-Dfile.encoding=UTF-8</argLine> <properties> <!-- Setting ReportNG listeners --> <property> <name>usedefaultlisteners</name> <value>false</value> </property> <property> <name>listener</name> <value>org.uncommons.reportng.HTMLReporter, org.uncommons.reportng.JUnitXMLReporter</value> </property> </properties> <suiteXmlFiles> <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile> </suiteXmlFiles> </configuration> </plugin> ...... </plugins> </build>
testng.xml(test-suite)
<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" > <suite name="TestNG Suite Name"> <listeners> <listener class-name="org.uncommons.reportng.HTMLReporter" /> <listener class-name="org.uncommons.reportng.JUnitXMLReporter" /> </listeners> <test name="tmon_monthly_maintenance"> <classes> <class name="com.tmoncorp.test.maintenance.TmonHomeTest" /> <class name="com.tmoncorp.test.maintenance.UserPageTest" /> ..... </classes> </test> </suite>
Response Data 추출 시 NullPointerException으로 테스트가 종료되지 않게 하려면
리포트에서도 NullPointerException으로 fail이 발생했다고만 나와서 왜 NullPointerException이 났는지 코드를 봐야 하는 문제점이 있다.
해결책으로는 MapUtils(org.apache.commons.collections)를 사용하면 된다.
MapUtils의 get Method들은 내부적으로 null 체크를 한다.
{
"data": { "dealSrl": [ 1111111111 ], "total": 1 }, "httpStatus": "OK", "httpCode": 200 } |
Map<Object, Object> resMap = jsonPath.get("data"); List<Long> dealSrlList = (List) MapUtils.getObject(resMap, "dealSrl"); softAssertions.assertThat(dealSrlList.size()).as(methodName).isEqualTo(total); Long dealSrl = dealSrlList.get(0); logger.debug("dealSrl : " + dealSrl); softAssertions.assertThat(dealSrl).as(methodName).isNotNull();
2020년 1월 16일 목요일
.gitignore 내용
#*# .#* *~ _site/ */src/META-INF/ */src/main/java/META-INF/ bin/ target/ .classpath .project .DS_Store .settings/ .springBeans *.iml *.iws *.ipr .idea/ code/ cargo-installs/ atlassian-ide-plugin.xml deploy/
Selenium implicitly wait & explicitly wait
해당 페이지에 속한 element가 모두 로딩될 때 까지 기다리는 방식
syntax
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
example
driver = new ChromeDriver(co); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); return driver;
[explicitly wait]
특정 element가 나타날 때 까지 기다려주는 방식
syntax
WebDriverWait wait = new WebDriverWait(WebDriverReference, TimeOut);
exmaple
driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, 20); .... WebElement element; element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(",,,"))); element.click();
2020년 1월 14일 화요일
HttpStatusCode 체크
import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(new HttpGet(URL)); int statusCode = response.getStatusLine().getStatusCode(); logger.debug("StatusCode: {}", statusCode);
2019년 12월 5일 목요일
Selenium implicitly-wait and explicitly-wait
explicitly-wait : 특정 요소가 로드될 때 까지 기다린다.
implicitly wait
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 | import java.util.concurrent.TimeUnit; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class WaitTest { private WebDriver driver; private String baseUrl; private WebElement element; @BeforeMethod public void setUp() throws Exception { driver = new FirefoxDriver(); baseUrl = "http://www.google.com"; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @Test public void testUntitled() throws Exception { driver.get(baseUrl); element = driver.findElement(By.id("lst-ib")); element.sendKeys("Selenium WebDriver Interview questions"); element.sendKeys(Keys.RETURN); List<WebElement> list = driver.findElements(By.className("_Rm")); System.out.println(list.size()); } @AfterMethod public void tearDown() throws Exception { driver.quit(); } } |
Explicitly wate
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 | import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ExpectedConditionExample { // created reference variable for WebDriver WebDriver driver; @BeforeMethod public void setup() throws InterruptedException { // initializing driver variable using FirefoxDriver driver=new FirefoxDriver(); // launching gmail.com on the browser driver.get("https://gmail.com"); // maximized the browser window driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @Test public void test() throws InterruptedException { // saving the GUI element reference into a "element" variable of WebElement type WebElement element = driver.findElement(By.id("Email")); // entering username element.sendKeys("dummy@gmail.com"); element.sendKeys(Keys.RETURN); // entering password driver.findElement(By.id("Passwd")).sendKeys("password"); // clicking signin button driver.findElement(By.id("signIn")).click(); // explicit wait - to wait for the compose button to be click-able WebDriverWait wait = new WebDriverWait(driver,30); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'COMPOSE')]"))); // click on the compose button as soon as the "compose" button is visible driver.findElement(By.xpath("//div[contains(text(),'COMPOSE')]")).click(); } @AfterMethod public void teardown() { // closes all the browser windows opened by web driver driver.quit(); } } |
Fluent wait
1 2 3 4 5 6 7 8 9 | Wait wait = new FluentWait(WebDriver reference) .withTimeout(timeout, SECONDS) .pollingEvery(timeout, SECONDS) .ignoring(Exception.class); WebElement foo = wait.until(new Function<WebDriver, WebElement>() { public WebElement applyy(WebDriver driver) { return driver.findElement(By.id("foo")); }}); |


