반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리

Selenium WebDriver Tutorial 01

2013. 10. 17. 17:25 | Posted by 솔웅


반응형

Selenium WebDriver

NOTE: We’re currently working on documenting these sections. We believe the information here is accurate, however be aware we are also still working on this chapter. Additional information will be provided as we go which should make this chapter more solid.



Introducing WebDriver



Selenium 2.0 의 새 기능중 중요한 부분은 WebDriver API 를 통합했다는 겁니다. WebDriver는 Selenium-RC API 의 한계를 극복하기 위한 기능들이 추가 된 것으로 프로그래밍을 좀 더 간단하고 간결하게 할 수 있도록 도와 줍니다. Selenium-WebDriver는 페이지가 reload 되지 않고도 페이지의 element들이 바뀌는 dynamic web page를 좀 더 제대로 지원하기 위해 만들었습니다. WebDriver의 목표는 현재 Web-App의 문제점들을 제대로 해결하기 위해 만들어진 잘 디자인된 객체 지향 API 입니다.



How Does WebDriver ‘Drive’ the Browser Compared to Selenium-RC?



Selenium-WebDriver는 자동화를 위해 각 브라우저 고유의 기능들을 지원함으로서 브라우저에 직접 호출하는 기능을 지원합니다. 어떻게 이렇게 직접 호출을 할 수 있고 어떤 기능들을 지원하느냐는 여러분이 사용하는 브라우저에 따라 다릅니다. 각 browser driver에 대한 정보는 나중에 살펴 보겠습니다.



Selenium-RC에 익숙하신 분들에게는 이 부분이 여러분이 사용하시던 부분과 좀 다를 겁니다. Selenium-RC는 각 브라우저에 대해 같은 방법으로 작독했습니다. 브라우저가 로드 되면 그 브라우저에 자바스크립트를 inject 하고 그 브라우저 안에서 AUT를 drive 하기 위해 그 자바스크립트를 사용합니다. WebDriver는 이와 같이 작동하지 않습니다. WebDriver는 automation을 위해 지원하는 브라우저의 고유 기능을 direct 하게 사용합니다.


WebDriver and the Selenium-Server



이 Selenium-WebDriver를 어떻게 사용할 것인가에 따라 Selenium Server가 필요할 수도 있고 그렇지 않을 수도 있습니다. 만약 WebDriver API 만을 사용할 거라면 Selenium-Server는 필요하지 않습니다. 만약 여러분의 브라우저와 테스트들이 같은 machine 에서 작동하고 여러분의 테스트가 WebDriver API만을 사용한다면 Selenium-Server가 필요하지 않습니다. WebDriver가 곧바로 그 브라우저를 실행시킬 겁니다.



Selenium-WebDriver와 함께 Selenium-Server를 사용하는데는 몇가지 이유가 있습니다.

       

- 여러분의 tests를 여러 machine들이나 virtual machines(VMs)에서 사용하기 위해 Selenium-Grid를 사용하는 경우.
      

- 여러분의 machine에 있지 않는 브라우저 버전을 갖고 있는 다른 machine에 remote로 접근해야 할 경우.
       

- Java bindings (Python,C#,Ruby 같은) 을 사용하지 않고 HtmlUnit Driver를 사용 할 경우.



Setting Up a Selenium-WebDriver Project



Selenium 을 인스톨한다는 의미는 development에 project를 셋업한다는 얘기입니다. 그렇게 되면 Selenium을 사용해서 프로그래밍 할 수 있게 되는거죠. 이것을 프로그래밍 언오와 개발환경에 따라 어떻게 할까요.





JAVA



Selenium 2.0 Java 프로젝트를 셋업하는 가장 쉬운 방법은 Maven을 이용하는 겁니다. Maven 은 java binding들 (Selenium 2.0 java client library)와 모든 dependency들을 다운로드 하고 프로젝트를 생성할 겁니다. 메이븐의 pom.xml (project configuration) 파일을 사용해서 이러한 일을 하시면 됩니다. 이 작업이 완료 되면 여러분은 maven 프로젝트를 여러분이 사용하시는 IDE (IntelliJ IDEA 나 이클립스)에 import 하실 수 있습니다.



첫번째로 Selenium project 파일들이 들어갈 폴더를 생성합니다. Maven을 사용하려면 pom.xml 파일이 필요합니다. 이 파일은 텍스트 에디터로 만들 수 있습니다. 이 pom.xml 파일이나 메이븐에 대한 자세한 부분은 다루지 않겠습니다. 아마 pom.xml은 아래와 같을 겁니다. 여러분 프로젝트를 위해 만든 폴더에 이 파일을 생성해 넣으세요.



<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>MySel20Proj</groupId>
        <artifactId>MySel20Proj</artifactId>
        <version>1.0</version>
        <dependencies>
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-java</artifactId>
                <version>2.35.0</version>
            </dependency>
            <dependency>
                <groupId>com.opera</groupId>
                <artifactId>operadriver</artifactId>
            </dependency>
        </dependencies>
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>com.opera</groupId>
                    <artifactId>operadriver</artifactId>
                    <version>1.5</version>
                    <exclusions>
                        <exclusion>
                            <groupId>org.seleniumhq.selenium</groupId>
                            <artifactId>selenium-remote-driver</artifactId>
                        </exclusion>
                    </exclusions>
                </dependency>
            </dependencies>
        </dependencyManagement>
</project>



이 때 최신 버전을 사용하세요. 위 코드 내의 버전들은이 글을 쓸 당시의 최종 버전들입니다. Maven download page를 체크하셔서 위의 코드 중 버전이 바뀐 경우 바꿔주세요.



이제 command-line에서 cd 로 해당 프로젝트 디렉토리로 가셔서 아래처럼 maven을 run 해 주세요.



mvn clean install



이렇게 하면 Selenium과 다른 dependency들을 다운받아 프로젝트에 추가할 겁니다.



마지막으로 이 프로젝트를 개발환경에 import 하시면 됩니다. 이 방법을 자세히 아시려면 아래 링크를 따라 가서 참고하시면 도움이 될 겁니다.



Importing a maven project into IntelliJ IDEA. Importing a maven project into Eclipse.



C#



As of Selenium 2.2.0, the C# bindings are distributed as a set of signed dlls along with other dependency dlls. Prior to 2.2.0, all Selenium dll’s were unsigned. To include Selenium in your project, simply download the latest selenium-dotnet zip file from https://code.google.com/p/selenium/downloads/list. If you are using Windows Vista or above, you should unblock the zip file before unzipping it: Right click on the zip file, click “Properties”, click “Unblock” and click “OK”.



Unzip the contents of the zip file, and add a reference to each of the unzipped dlls to your project in Visual Studio (or your IDE of choice).



Official NuGet Packages: RC WebDriver WebDriverBackedSelenium Support


Python



If you are using Python for test automation then you probably are already familiar with developing in Python. To add Selenium to your Python environment run the following command from a command-line.



pip install selenium



Pip requires pip to be installed, pip also has a dependency on setuptools.



Teaching Python development itself is beyond the scope of this document, however there are many resources on Python and likely developers in your organization can help you get up to speed.
Ruby



If you are using Ruby for test automation then you probably are already familiar with developing in Ruby. To add Selenium to your Ruby environment run the following command from a command-line.



gem install selenium-webdriver



Teaching Ruby development itself is beyond the scope of this document, however there are many resources on Ruby and likely developers in your organization can help you get up to speed.



Perl



Perl bindings are provided by a third party, please refer to any of their documentation on how to install / get started. There is one known Perl binding as of this writing.



PHP



PHP bindings are provided by a third party, please refer to any of their documentation on how to install / get started. There are three known bindings at this time: By Chibimagic By Lukasz Kolczynski and By the Facebook

반응형


반응형

오늘은 Selenium WebDriver를 이용한 예제를 하나 공부했습니다.


클래스를 실행 시키면 Firefox 브라우저를 켜서 gmail로 가고 아이디 입력과 비밀번호 입력 그리고 Log in 버튼을 누르는 것까지 실행하는 예제입니다.


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class WebDriver_Ex {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://gmail.com");
//        WebElement username = driver.findElement(By.id("Email"));
        WebElement username = driver.findElement(By.xpath("//*[@id=\"Email\"]"));
        username.sendKeys("아이디");
        WebElement password  = driver.findElement(By.id("Passwd"));
        password.sendKeys("비밀번호");
       
        WebElement signInBtn = driver.findElement(By.id("signIn"));
        signInBtn.click();
    }
}



이 소스를 실행시키면 Firefox를 실행시키고 사용자 이름과 비밀번호를 주어진 값으로 채워 넣습니다.

그리고 로그인 버튼을 클릭하는 이벤트를 발생시켜서 gmail로 로그인을 합니다.


소스를 보면요.

먼저 WebDriver 인터페이스에 있는 FirefoxDriver()의 객체를 만듭니다.

다음에 get() 메소드를 사용해서 gmail 로 접속을 합니다.

여기까지 하면 파이어폭스 브라우저에 gmail.com 페이지가 뜹니다.


그 다음에는 gmail 페이지의 태그를 알아야 하는데요. 사용자 이름을 넣는 텍스트필드에 값을 넣어야 하는데 이때 사용할 수 있는 방법이 id로 하는 방법과 xpath 로 하는 방법이 있습니다.


이 페이지의 소스를 보려면 firebug 플러그인을 firefox 브라우저에 인스톨해서 사용하시면 편합니다.

xpath를 아시려면 firepath 를 인스톨 하시면 되구요.


자세한 방법은 검색하셔서 관련 글을 보시면 됩니다. 관련된 글이 많이 있을 겁니다.


이 Firebug를 통해서 보면 gmail 의 로그인 페이지에서 아이디를 넣는 텍스트 필드의 id 가 Email 인 것을 알 수 있습니다.

여기까지 알면 WebElement 를 사용해서 해당 텍스트 필드의 객체를 생성합니다.


WebElement username = driver.findElement(By.id("Email"));


혹은 Firepath 를 사용해서 xpath 를 알 수도 있습니다.

xpath 에는 절대경로(Absolute xpath,complete xpath)와 상대경로(partial xpath) 가 있는데요.

여기서는 상대경로를 사용합니다.

WebElement username = driver.findElement(By.xpath("//*[@id=\"Email\"]"));


이렇게 하면 아이디를 넣는 텍스트 필드의 WebElement 객체를 만들었습니다.


이러면 이 엘리먼트를 마음대로 다룰 수가 있게 됩니다.


아이디를 넣어야 하니까 이럴때눈 sendKeys() 메소드를 사용하시면 됩니다.

비밀번호두 마찬가지로 진행합니다.

그리고 로그인 버튼도 WebElement 객체를 만들어서 click() 메소드를 사용해서 클릭하도록 합니다.


이제 이 소스를 실행하면 gmail로 가서 아이디와 비밀번호를 입력하고 로그인 버튼을 눌러서 접속하는것까지 실행합니다.


Selenium 은 테스팅 툴입니다.


여기서는 그 다음페이지의 title을 받아서 원래 설계된 페이지로 제대로 왔는지 안 왔는지 여부를 테스트 할 수 있겠네요.


일단 오늘은 Selenium 을 사용해서 웹페이지에 있는 WebElement들을 control 하는 방법을 정리했습니다.


반응형


반응형

Maven Information


Maven을 사용하신다면 아래에 central Maven repository에서 Maven artifacts를 보실 수 있습니다.

 http://repo1.maven.org/maven2/org/seleniumhq/selenium/

DefaultSelenium이나 Maven 프로젝트의 WebDrever 중 하나를 사용하시려면 pom.xml에 아래 dependency를 추가하세요.

   

<dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.35.0</version>
    </dependency> 



Note: 2.0,rc3 이전 버전은 이 artifact 이름이 selenium-remote-control입니다.

다른 Maven artifacts를 보시려면 diagram을 보세요. Selenium Maven artifacts와 그 artifacts의 주요한 클래스들과 인터페이스들을 보실 수 있습니다.






특정 WebDriver implementation만을 사용하시려면 (예를 들어 FirefoxDriver 만 사용한다든지), selenium-java artifact 를 사용하지 않으셔도 됩니다. 여기에는 많은 transitive dependency들이 있습니다. 이것을 사용하는 대신 간단히 아래와 같은 dependency를 추가하시면 됩니다.

   

<dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-firefox-driver</artifactId>
        <version>2.35.0</version>
    </dependency> 


DefaultSelenium이나 RemoteWebDriver implementation 을 사용한다면 Selenium server를 사용해야 합니다. Selenium Downloads page  에서 selenium-server-standalone.jar를 다운 받으세요. 그리고 여러분 프로젝트에 이 Selenium 서버를 embed 하시면 됩니다. pom.xml 파일에 아래 dependency를 추가해 주세요.
 
   

<dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-server</artifactId>
        <version>2.35.0</version>
    </dependency> 



이제 SeleniumServer 인스턴스를 생성하실 수 있습니다.

selenium-server artifact는 servlet-api-2.5 artifact에 대한 dependency를 가지고 있다는 것을 명심하세요. 여러분 프로젝트가 웹 어플리케이션 컨테이너 안에서 실행된다면 여러분은 이것을 exclude 하셔야 합니다.


Third Party Browser Drivers NOT SUPPORTED/DEVELOPED by seleniumhq


Opera Driver

   

<dependency>
        <groupId>com.opera</groupId>
        <artifactId>operadriver</artifactId>
        <version>1.5</version>
    </dependency> 




PhantomJSDriver (GhostDriver)

  

<dependency>
        <groupId>com.github.detro.ghostdriver</groupId>
        <artifactId>phantomjsdriver</artifactId>
        <version>1.0.4</version>
    </dependency> 
 



반응형