tag:blogger.com,1999:blog-12821468807419781152024-03-17T00:22:02.643+05:30Gaurang Shah about AutomationContains the tutorial for various automation tools: QTP, Selenium, JUnit, TestNG, ReportNG, ANT, AutoIt, WatirAnonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.comBlogger83125tag:blogger.com,1999:blog-1282146880741978115.post-40493992382246691662017-09-01T16:00:00.002+05:302017-09-12T20:55:45.770+05:30Selenium Python Object Repository - Using Lambda<div dir="ltr" style="text-align: left;" trbidi="on">
in the last post I discussed how to create object repository using decorator. if you haven't read the post, please read it <a href="http://www.automationtesting.co.in/2017/08/selenium-python-object-repository-using.html" target="_blank">here</a><br />
<br />
I am going to take the same example to demonstrate how to use lambda (anonymous function).<br />
<br />
<!--INFOLINKS_OFF-->
<pre class="brush:python;highlight: [7, 12]">from selenium import webdriver
from selenium.webdriver.common.by import By
class TestGoogle(object):
search_input = lambda self: self.find_element(By.NAME, "q")
def test_search(self):
self.driver = webdriver.Firefox()
self.driver.get("https://google.com")
self.search_input().send_keys("selenium python")
</pre>
<span style="font-size: large;">Pros of Using</span>
<br />
<ul style="text-align: left;">
<li>all the elements are in one place in the file (class), so if any element change it's easy and fast</li>
<li>it's a function, so every time a object would be created, you should never get
<b>StaleElementRefereceException</b></li>
</ul>
<span style="font-size: large;">Cons of Using</span>
<br />
<ul style="text-align: left;">
<li>You will have to keep in mind it's a function not a variable </li>
<li>Every time a new object would be created, so it could be a overhead. </li>
</ul>
</div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com0tag:blogger.com,1999:blog-1282146880741978115.post-14748094952213162602017-08-24T16:36:00.000+05:302017-08-24T16:38:23.430+05:30Selenium Python Object Repository - Using decorator<div dir="ltr" style="text-align: left;" trbidi="on">
In the series of posts I will try to explain how to create the object repository when you are writing selenium tests using python. There are different ways, few more simple than others but finally it's upto you which to use and how to use it.<br />
<br />
Java has <a href="https://github.com/SeleniumHQ/selenium/wiki/PageFactory">PageFactory</a> which allows a nicer, cleaner way to create WebElement object repository. It doesn't actually creates the object it's just do the lazy initialization. which means the first time you do some action on this object and it's actually created.<br />
<br />
I wanted to something like this Python, I searched it but didn't find any satisfactory answer. and So I write my own code. It look similar to how you initialize the object in Java, however, it's different in few aspects. For one it doesn't actually do the lazy initialization, however it creates the new object every time you do some action on it. However, it has advantages as well.<br />
<br />
Remember, <b>StaleElemementReferenceException</b>, it's very less likely you will get this as it creates new object every time.<br />
<br />
For this I am using Decorator, if don't know what is decorator, it's simply a function which takes a function as a input and returns you a brand new function. However, I would advice you to read more about this.<br />
<br />
Now let's just to code.<br />
<br />
<!--INFOLINKS_OFF--><br />
<b>Without Object Repository
</b><br />
<b><br /></b>
<br />
<pre class="brush:python">class TestGoogle(object):
def test_search(self):
self.driver = webdriver.Firefox()
self.driver.get("https://google.com")
self.driver.find_element_by_name("q").send_keys("selenium")
</pre>
<br />
<b>And now, with Object Repository
</b><br />
<pre class="brush:python;highlight: [3, 4, 9]">class TestGoogle(object):
@FindBy(By.NAME, "q")
def search_input(self): pass
def test_search(self):
self.driver = webdriver.Firefox()
self.driver.get("https://google.com")
self.search_input().send_keys("selenium python")
</pre>
<pre class="brush:python;highlight: [3, 4, 9]">
</pre>
If you have noticed, search_input is a function and not a variable. The reason for this is, Python don't have a decorator for variable, at least yet. And so you need to call the function which will give you a WebElement object on which you can do multiple actions.
</div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com0tag:blogger.com,1999:blog-1282146880741978115.post-86898346154095260002017-02-21T16:47:00.000+05:302017-02-21T16:48:17.036+05:30PyTest with Selenium - HTML report with Screenshot <div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
recently I was working with Py.Test with selenium. It's really powerful tool with awesome fixtures. It generates JUnit XML report as well which is good to be consumed by Jenkins. However, I needed an HTML report as well with embedded screenshot for the ease of identifying the issue. And this is how I did it finally after doing some googling.<br />
<br />
<h3 style="text-align: left;">
Generate HTML Report of PyTest </h3>
<div>
<a href="https://pypi.python.org/pypi/pytest-html">Pytest-html </a>plugin is available which you can use to generate the beautiful Report. The all you have to do is install the plugin and run your test case with this plugin. </div>
<div>
<br /></div>
<div>
Embede ScreenShot When Test Case Fails</div>
<div>
<br /></div>
<div>
PyTest-html plugin allows you to extend the plugin and that's the best thing about this plugin. </div>
</div>
<b>conftest.py</b><br />
<!--INFOLINKS_OFF--><br />
<pre class="brush:python">from selenium import webdriver
import pytest
driver = None
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
"""
Extends the PyTest Plugin to take and embed screenshot in html report, whenever test fails.
:param item:
"""
pytest_html = item.config.pluginmanager.getplugin('html')
outcome = yield
report = outcome.get_result()
extra = getattr(report, 'extra', [])
if report.when == 'call' or report.when == "setup":
xfail = hasattr(report, 'wasxfail')
if (report.skipped and xfail) or (report.failed and not xfail):
file_name = report.nodeid.replace("::", "_")+".png"
_capture_screenshot(file_name)
if file_name:
html = '<div><img src="%s" alt="screenshot" style="width:304px;height:228px;" ' \
'onclick="window.open(this.src)" align="right"/></div>' % file_name
extra.append(pytest_html.extras.html(html))
report.extra = extra
def _capture_screenshot(name):
driver.get_screenshot_as_file(name)
@pytest.fixture(scope='session', autouse=True)
def browser():
global driver
if driver is None:
driver = webdriver.Firefox()
return driver
</pre>
<b>test_screenshot.py</b><br />
<!--INFOLINKS_OFF-->
<pre class="brush:python">def test_screenshot_on_test_failure(browser):
# driver = webdriver.Firefox()
browser.get("https://google.com")
assert False</pre>
</div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com6tag:blogger.com,1999:blog-1282146880741978115.post-76424810393152554522016-03-29T10:14:00.000+05:302016-03-29T10:16:50.915+05:30linux java shows older version after upgrade<div dir="ltr" style="text-align: left;" trbidi="on">
While working with Linux today I stumbled upon a weird problem, even after upgrading java to 1.8 it was showing 1.7 only.<br />
<br />
And when I tried to install it again, it showed me following message.<br />
<!--INFOLINKS_OFF-->
<pre class="brush:text">sudo yum install java-1.8.0-openjdk.x86_64
Package 1:java-1.8.0-openjdk-1.8.0.71-2.b15.8.amzn1.x86_64 already installed and latest version
Nothing to do
</pre><!--INFOLINKS_ON-->
<div>
Following command help me to figure out what's going wrong. </div>
<div>
<br /></div>
<div>
Following command will show you all the java versions currently installed on your system, it will also show you which one is currently active. If you need to change just provide the number and that would be activated. </div>
<br />
<!--INFOLINKS_OFF-->
<b>Command:</b><br />
<pre class="brush:text">sudo update-alternatives --config java
</pre>
<br />
<b>Output:</b><br />
<pre class="brush:text">There are 2 programs which provide 'java'.
Selection Command
-----------------------------------------------
+ 1 /usr/lib/jvm/jre-1.8.0-openjdk.x86_64/bin/java
* 2 /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
Enter to keep the current selection[+], or type selection number:
</pre>
</div>Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com0tag:blogger.com,1999:blog-1282146880741978115.post-41046522613762883092015-12-18T21:56:00.001+05:302015-12-18T21:58:59.011+05:30JVM Cucumber Hooks Part 1 <div dir="ltr" style="text-align: left;" trbidi="on">
As the name itself suggests hooks are used to hook any feature or scenario. In a simpler terms you can create a function and then hook that into any feature or scenario.<br />
<br />
There are two types of hooks you can create. Please not there ain't such categories, I have just divided them into following categories for better understanding.<br />
<ul>
<li><b>Generic Hooks</b>: Hooks that executes before or after each and every scenario.</li>
<li><b>Specific Hooks</b>: Hooks that executes before or after every specific(mentioned) scenario or feature. </li>
</ul>
<h3 style="text-align: left;">
<div style="text-align: left;">
<span style="font-weight: normal;"><span style="font-size: small;">Now let's see how to implement this, for this I am going to use the same example I used in the last blog post. if you haven't read that yet, please visit it here. </span></span></div>
</h3>
<h3 style="text-align: left;">
<b>Generic Hooks</b></h3>
if you will check the code of the previous post, we were creating the driver object, in the class file as we had only one test case(scenario). if we have multiple scenarios and we want to open new browser before each and every scenario and want to close after each and every scenario we can utilize the hooks.<br />
<br />
In the following example, I am going to create a hook (setUp method) that will be called before each and every scenario. this method will open a firefox browser and will navigate to site home page. I will also create an another hook (tearDown method) which will be called after each and every scenario. This method will close the browser after each and every scenario.<br />
<br />
<b>Hooks.java</b> <!--INFOLINKS_OFF--><br />
<pre class="brush:java">public class Hooks extends WebDriverManager{
@Before
public void setUp(){
driver = new FirefoxDriver();
wait = new WebDriverWait(driver, 30);
driver.get("https://en.wikipedia.org");
driver.manage().window().maximize();
}
@After
public void tearDown(){
driver.quit();
}
}
</pre>
</br>
<b>WebDriverManager.java</b>
<br />
<pre class="brush:java">public class WebDriverManager {
public static WebDriver driver;
public static WebDriverWait wait;
}</pre>
<b><br /></b> <b>HomePage.java</b>
<br />
<pre class="brush:java">public class HomePage extends WebDriverManager{
@When("^I search \"(.*?)\"$")
public void i_search(String arg1) throws Throwable {
WebElement search_box = driver.findElement(By.id("searchInput"));
search_box.sendKeys(arg1);
search_box.submit();
}
@Then("^I should get \"(.*?)\" on page$")
public void i_should_get_on_page(String arg1) throws Throwable {
Assert.assertTrue(driver.findElement(By.xpath("//body")).getText().contains(arg1));
}
}</pre>
<br />
<b>wkipedia_search.feature</b><br />
<pre class="brush:text">@Search
Feature: Verify WikiPedia Search
@Regression @Functional
Scenario: Verify Wikipdia for indirect posts-BDD
When I search "BDD"
Then I should get "Behavior-driven development" on page
@Regression
Scenario: Verify Wikipdia for indirect posts-TDD
When I search "TDD"
Then I should get "Test-driven development" on page
</pre>
</div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com0tag:blogger.com,1999:blog-1282146880741978115.post-44803150759635279802015-05-05T13:43:00.000+05:302015-09-03T08:17:33.571+05:30BDD (Cucumber) with Selenium Webdriver<div dir="ltr" style="text-align: left;" trbidi="on">
In the following post I am going to explain how to setup cucumber on Java with selenium to use for Behavior Driven Development.<br />
<br />
I am going to use IntelliJ for writing this test cases, however you can choose eclipse or any other IDE as well.<br />
<br />
<h2 style="text-align: left;">
How to create project.</h2>
<div>
I have also hosted the demo project on GitHub you can access that using following link </div>
<div>
<a href="https://github.com/Gaurang033/CucumberDemo">https://github.com/Gaurang033/CucumberDemo</a></div>
<div>
<br /></div>
<br />
<li>Go to File >> New >> Project and select Maven as shown in the screenshot<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-_n2nfxJeq4A/VUh55Qe7TLI/AAAAAAAACPA/ZZz1PEJnino/s1600/New_Project.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="303" src="http://2.bp.blogspot.com/-_n2nfxJeq4A/VUh55Qe7TLI/AAAAAAAACPA/ZZz1PEJnino/s400/New_Project.jpg" width="400" /></a></div>
</li>
<li>Provide GroupId and ArtifactID<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-rPDJRO0leUo/VUh55YUXw1I/AAAAAAAACPc/o-LuYDhlFbE/s1600/New_Project_1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="91" src="http://4.bp.blogspot.com/-rPDJRO0leUo/VUh55YUXw1I/AAAAAAAACPc/o-LuYDhlFbE/s320/New_Project_1.jpg" width="320" /></a></div>
<ol style="text-align: left;">
</ol>
</li>
<li>Provide the Project Name, After this step, IntelliJ will create new project for you.
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-3rW9UviirsM/VUh56GsYkpI/AAAAAAAACPM/KOzNMa_c1h0/s1600/new_project_2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="128" src="http://2.bp.blogspot.com/-3rW9UviirsM/VUh56GsYkpI/AAAAAAAACPM/KOzNMa_c1h0/s320/new_project_2.jpg" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
</li>
<br />
<h2 style="text-align: left;">
Add Maven Dependencies.</h2>
We need to add Cucumber, Selenium and JUnit dependencies to pom.xml. Open pom.xml and add the following code to it. <br />
<br />
<!--INFOLINKS_OFF--><pre class="brush:xml"><dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.40.0</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
</pre><!--INFOLINKS_ON-->
<br />
<h2 style="text-align: left;">
Automating Your First Test case</h2>
<br />
I am going to automate following test case for this BDD (Cucumber) demo<br />
<ol style="text-align: left;">
<li>Open wikipedia.com website </li>
<li>Search for BDD </li>
<li>Result page should contain Behavior-driven development text. </li>
</ol>
<div>
Now before we begin writing test cases, let's create proper packages. I have created the packages in following, however you can create the way you like. </div>
<div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-pJtG2dPKwcU/VUh55e1P0MI/AAAAAAAACO8/AckObYsp_WU/s1600/cucumber_demo.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="257" src="http://4.bp.blogspot.com/-pJtG2dPKwcU/VUh55e1P0MI/AAAAAAAACO8/AckObYsp_WU/s320/cucumber_demo.jpg" width="320" /></a></div>
<br /></div>
<div>
Just make sure that all your code (directly or indirectly) is under test package. </div>
<div>
<br /></div>
<div>
The first thing we need to do, to write cucumber tests, is to convert existing test case into Gherkin Syntax. In the resources folder create one package and inside this package create one feature file, mine is called wikipedia_search.feature however you can give the name you want. </div>
<div>
<br />
<!--INFOLINKS_OFF--><pre class="brush:text">Feature: Verify WikiPedia Search
Scenario: Verify Wikipdia for indirect posts
When I search "BDD"
Then I should get "Behavior-driven development" on page
</pre><!--INFOLINKS_ON-->
<br />
Feature:, is a keyword through which you can specify which feature you are testing<br />
Scenario:, is a keyword though which you can specify of which scenario following test cases belong to<br />
Your test cases start after the scenario line.
When specifies the step we need to perform and Then specifies the part we need to verify.
<br />
<br />
Now the next thing we need to do is, implement this test cases and write selenium code for it. however before that you need to write a Java class which runs your test cases. Create a java class under test\java\com.gaurang package and paste the following code. <br />
<br />
Please create one file with following code<br />
<!--INFOLINKS_OFF--><pre class="brush:java">@RunWith(Cucumber.class)
@CucumberOptions(plugin={"pretty", "html:target/cucumber-html-report"})
public class RunAllTests {
}
</pre><!--INFOLINKS_ON-->
<br />
Now everything is in place, let's write the selenium code for Gherkin statement we wrote above. There are actually two way to do it.
<br />
<br />
<ol style="text-align: left;">
<li>Run the file created in above step, and on the console you will be able to see something like below. copy this code and paste into the class file. </li>
<li>You can open the feature file and press ALT+Enter key combination, this will ask you to choose the file name and then it will create the empty implementation of all the steps in that file. </li>
</ol>
<div>
Once this is done, the only thing remain is to write corresponding selenium code. </div>
<div>
<br /></div>
<div>
<h2 style="text-align: left;">
Report: </h2>
</div>
<div>
Cucmber generates it's own HTML report, which look like this. </div>
<div>
<br /></div>
<table cellpadding="0" cellspacing="0" class="tr-caption-container" style="float: left; margin-right: 1em; text-align: left;"><tbody>
<tr><td style="text-align: center;"><a href="http://3.bp.blogspot.com/-9z080KCZnk0/VUh5eaysjCI/AAAAAAAACO0/Ef-uz_6GhUc/s1600/cucumber_report.jpg" imageanchor="1" style="clear: left; margin-bottom: 1em; margin-left: auto; margin-right: auto;"><img border="0" height="153" src="http://3.bp.blogspot.com/-9z080KCZnk0/VUh5eaysjCI/AAAAAAAACO0/Ef-uz_6GhUc/s640/cucumber_report.jpg" width="640" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Cucumber HTML Report</td></tr>
</tbody></table>
<div>
<br /></div>
</div>
</div>Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com0tag:blogger.com,1999:blog-1282146880741978115.post-53606906843468169992015-03-17T18:15:00.000+05:302015-03-17T22:24:27.331+05:30Selenium WebDriver with Python<div dir="ltr" style="text-align: left;" trbidi="on">
In the following blog I will show you how to setup and write your first test case using Webdriver in Python Language.
<br />
<h4 style="text-align: left;">
Install Python:</h4>
If you are using Linux or Mac you need not do this as Python comes pre-installed on these OS. however if you are using windows (most of us do), Please follow the steps mentioned blow to install python on windows platform.<br />
<ul style="text-align: left;">
<li>Download the Python from following location for your windows OS and install it.<br />https://www.python.org/downloads/windows/</li>
<li>Once installed you need to set the following paths in your system PATH variable. (Python folder name may be depends on the version of the Python you have installed)</li>
<ul>
<li>C:\Python27</li>
<li>C:\Python27\Scripts</li>
</ul>
<li>Now, let's test if Python has installed or not. Open command prompt (CMD) and enter following command, if it shows you version number then python has successfully installed.<br />python --version</li>
</ul>
<div>
<h4 style="text-align: left;">
Now let's Install WebDriver for Python</h4>
</div>
<div>
Installing WebDriver in python is different than installing in Java, actually Installing webdriver for Python is pretty simple. To install WebDriver, Just open command prompt (CMD) and enter following command. </div>
<div>
<ul style="text-align: left;">
<li>pip install selenium</li>
</ul>
<div>
<h4 style="text-align: left;">
First WebDriver Test in Python.</h4>
test_google.py
<br />
<pre class="brush:python">from selenium import webdriver
import unittest
class TestGoogle(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.get("https://google.com")
def tearDown(self):
self.driver.quit()
def test_search(self):
search_edit_box = self.driver.find_element_by_name("q")
search_edit_box.send_keys("webdriver with python")
search_edit_box.submit()
if __name__ == '__main__':
unittest.main()</pre>
</div>
<h4 style="text-align: left;">
Now let's see How to run Above Webdrive Test</h4>
<ul style="text-align: left;">
<li>First of all copy above file and paste it in any file and save as <b>test_google.py</b></li>
<li>Open command prompt (CMD) and navigate to folder where you have stored this file. </li>
<li>Now run the following command<br /><b>python test_google.py</b></li>
</ul>
<br />
<br /></div>
</div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com0tag:blogger.com,1999:blog-1282146880741978115.post-72705546784886378232014-10-03T16:14:00.000+05:302015-03-11T12:14:11.637+05:30Alternative to Setup and TearDown - Python Decorators<div dir="ltr" style="text-align: left;" trbidi="on">
I recently designed a Automation Framework using Selenium Webdriver and Python. Everything was working fine until few days back when we realized that we have some test cases which verifies back-end and doesn't require browser to be opened. I never knew this while I was designing the framework, and so I wrote one common Setup and Teardown, now problem is it opens the browser and does so many other stuffs even for the test cases which doesn't require it.<br />
<br />
So, I came up with solution, I wrote down two decorators, one for UI test cases and one for backend test cases. <br />
<br />
Following is the code.<br />
<br />
<pre class="brush:python">import traceback
import unittest
from selenium import webdriver
class AppManager(unittest.TestCase):
def setup_func(self, url):
self.driver = webdriver.Firefox()
self.driver.maximize_window()
if url is not None:
self.driver.get("http://google.com")
def teardown_func(self):
self.driver.close()
@staticmethod
def gui_test(url=None):
def wrapper(func):
def deco_func(self):
#Setup
self.setup_func(url)
#Your Test case
try:
func(self)
except Exception as e:
print traceback.print_exc()
self.teardown_func()
self.teardown_func()
#TearDown
return deco_func
return wrapper
@staticmethod
def backend_test(func):
def deco_func(self):
#Setup
#TODO add setup stpes
#Your Test case
func(self)
#TearDown
#TODO Add teardown steps
return deco_func</pre>
<br />
<h4 style="text-align: left;">
How to use this decorator
</h4>
<br />
<pre class="brush:python">
class Demo(AppManager):
@AppManager.gui_test(url="http://www.google.com")
def test_setup(self):
#self.driver.get("http://google.com")
search_editbox =self.driver.find_element_by_name("q").submit()
search_editbox.send_keys("gaurang")
search_editbox.submit()</pre>
</div>Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com0tag:blogger.com,1999:blog-1282146880741978115.post-15034175561678025632014-07-27T15:08:00.000+05:302015-03-12T17:11:27.224+05:30WebDriver with Python using Splinter and Nose<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
Till now I have been writing all my post in java, However after spending almost an year in python, Why not I write post in python. So here is my first post about how to use WebDriver in Python. If you are reading this please don't forget to put the comment.<br />
<br />
I have used two frameworks for writing Webdriver tests in Python<br />
<br />
Splinter:<br />
Splinter is basically a wrapper around the Webdriver API, which ease you to write code as compared to webdriver.<br />
<br />
For example if you have to fill a form with web driver, your code might look<br />
elem = browser.find_element.by_name('username')<br />
elem.send_keys('janedoe')
<br />
<br />
However, if you use splinter, it will look like this<br />
browser.fill('username', 'janedoe')
<br />
<br />
Better, Aint't it ?<br />
<br />
Nose:<br />
Nose is an unit testing framework extended from python unittest. As I told you it's extended from unittest which mean it provides all the features provided by unittest plus few more<br />
<br />
Enough of theory, let's see the code.<br />
<br />
<br /></div>
<pre class="brush:python">from nose.tools import assert_true
__author__ = 'Gaurang_Shah1'
import unittest
import splinter
class GoogleTest(unittest.TestCase):
def setUp(self):
self.browser = splinter.Browser()
def tearDown(self):
self.browser.quit()
def test_google_search(self):
google = GooglePage(self.browser)
google.search('splinter - python acceptance testing for web applications').verify_text_on_page(''splinter.cobrateam.info')
class GooglePage(object):
def __init__(self, browser):
self.browser = browser
self.browser.visit("http://google.co.in")
def search(self, keyword):
self.browser.fill('q', keyword)
self.browser.find_by_name('btnG').click()
return self
def verify_text_on_page(self, text):
assert_true(self.browser.is_text_present('splinter.cobrateam.info'))
</pre>
</div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com0tag:blogger.com,1999:blog-1282146880741978115.post-29569174889371605362014-06-26T15:01:00.001+05:302015-03-11T12:15:33.144+05:30REST API Testing using REST-assured<div dir="ltr" style="text-align: left;" trbidi="on">
This is my second post about doing Automation of REST API Testing, few days back I write the post to do REST API Testing using Frisby.js ( a Javascript tool), today i will post about how to do this in JAVA using REST-assured API.<br />
<div>
<br /></div>
<div>
Installation</div>
<div>
Please down and put following JAR files in your build path. </div>
<div>
rest-assured</div>
<div>
json-schema-validator</div>
<div>
<br /></div>
<div>
Test Case. </div>
<div>
For this demo purpose, I am going to use freegeoip.net site which return simple JSON response. </div>
<div>
steps: </div>
<div>
1. visit http://freegeoip.net:80/json/yahoo.com site </div>
<div>
<br /></div>
<div>
verification:</div>
<div>
1. verify that it returns 200 OK </div>
<div>
2. verify it return correct JSON </div>
<div>
<br /></div>
<div>
Test Script. </div>
<pre class="brush:java">/**
* @author Gaurang_Shah
*
*/
//import com.jayway.restassured.RestAssured;
import static com.jayway.restassured.RestAssured.baseURI;
import static com.jayway.restassured.RestAssured.given;
import static com.jayway.restassured.RestAssured.useRelaxedHTTPSValidation;
import static com.jayway.restassured.RestAssured.when;
import static org.hamcrest.Matchers.equalTo;
import org.junit.Test;
import com.jayway.restassured.authentication.FormAuthConfig;
public class TestATP {
@Test
public void testDemo(){
baseURI="http://freegeoip.net:80/";
when().
get("/json/yahoo.com").
then().
assertThat().statusCode(200).
log().all().
body("country_code",equalTo("US"),
"country_name",equalTo("United States"),
"region_code",equalTo("CA"),
"region_name",equalTo("California"),
"city",equalTo("Sunnyvale")
);
}
}
</pre>
</div>Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com0United States36.5978891330702 -101.601562511.075854633070197 -142.9101565 62.1199236330702 -60.2929685tag:blogger.com,1999:blog-1282146880741978115.post-22529875160175572782014-05-30T10:44:00.003+05:302015-03-05T16:44:20.996+05:30REST API Testing using Frisby.js<div dir="ltr" style="text-align: left;" trbidi="on">
Couple of days back I was searching ways to Automate REST API, I was searching for tool which is open source, free and has good support. The first thing which I came across is Frisby.js<br />
<br />
Frisby.Js is a framework for testing REST API built on node.js. (Yes, that means you will have use javascript)<br />
<br />
<b><u>Pros:</u></b><br />
<ul style="text-align: left;">
<li>It's fast and easy to use. </li>
<li>It generated JUnit XML report. </li>
</ul>
<ul style="text-align: left;">
</ul>
<div>
<b><u>Cons</u></b></div>
<div>
<ul style="text-align: left;">
<li>Doesn't have much facilities</li>
<li>very limited support group. </li>
</ul>
<div>
However't that's what I feel, you can explore this and can comment if feels other wise. Now let me show you how to install it. </div>
</div>
<div>
<br /></div>
<h3 style="text-align: left;">
Installation </h3>
<div>
<ul style="text-align: left;">
<li>First install the node.js from following location<br />http://nodejs.org/download/</li>
<li>Now go the command line and install the frisby.js using npm (node package manager)<br />npm install -g frisby</li>
<li>You will also require to install jasmine as it is being used by frisby.js, Goto the command line and install jasmine using following command.<br />npm install -g jasmine-node</li>
<li>Now all is set, you can go ahead and create the test case. </li>
</ul>
<h3 style="text-align: left;">
Write Test Cases</h3>
</div>
<div>
<ul style="text-align: left;">
<li>Now firsby.js is using jasmine, name of the test case file must end with spec.js.</li>
<li>You also need to create the folder named spec and then folder names api inside that. </li>
<li>Now copy the following file in spec/api.</li>
<li>Please not that, the first line is the location of the code may change depends where frisby module is located on your local machine. </li>
</ul>
<div>
getHostDetails_specs.js.</div>
</div>
<div>
<br /></div>
<div>
In following test cases, we will get the details for yahoo.com site using freegeoip.com and then verify the JSON reponse. </div>
<pre class="brush:javascript">var frisby = require('C:/Users/gaurang_shah/AppData/Roaming/npm/node_modules/frisby');
frisby.create('Get IP From Host Name')
.get('http://freegeoip.net/json/yahoo.com')
.expectStatus(200)
.expectHeaderContains('content-type', 'application/json')
.inspectJSON()
.expectJSON({
country_code:"US",
country_name:"United States",
region_code: 'CA',
region_name: 'Californ',
city: 'Sunnyvale',
zipcode: '94089',
latitude: 37.4249,
longitude: -122.0074,
metro_code: '807',
area_code: '408'
})
.toss();
</pre>
<h3 style="text-align: left;">
Run the Test Cases</h3>
<div>
<ul style="text-align: left;">
<li>open the command prompt and make sure you are in the parent directory of spec/api folder. </li>
<li>Enter the following command<br />jasmine-node spec\api\getHostDetails_spec.js</li>
<li>If you have multiple spec file and if you want to run all, then you can run using following command<br />jasmine-node spec/api</li>
</ul>
<h3 style="text-align: left;">
Results & Reports </h3>
<ul style="text-align: left;">
<li>Above test case will fail, as we are expecting region_name to be Californ and actual is California.</li>
<li>To Generate the Junit report, you just need to run the test cases using following command<span class="comment" style="box-sizing: border-box;"><br />jasmine</span><span class="literal" style="box-sizing: border-box;">-</span><span class="comment" style="box-sizing: border-box;">node</span> <span class="comment" style="box-sizing: border-box;">spec/api/</span> <span class="literal" style="box-sizing: border-box;">-</span><span class="literal" style="box-sizing: border-box;">-</span><span class="comment" style="box-sizing: border-box;">junitreport</span>
</li>
</ul>
<ul style="text-align: left;">
</ul>
</div>
</div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com2tag:blogger.com,1999:blog-1282146880741978115.post-47420137449286137712014-01-20T12:23:00.001+05:302015-03-11T12:16:22.306+05:30WebDriver: Verify If JavaScript Alert is Present or Not<div dir="ltr" style="text-align: left;" trbidi="on">
WebDriver has provided decent API to handle JavaScript Alert, however there isn't any API present which lets you know if JavaScript Alert is present on page or not. And sometime we are not sure if Alert is present or not, if it is present then we need to cancel it.<br />
<br />
Implementation of isAlertPresent is very simple, Following code shows how to check if alert is present or not and if present cancel it.<br />
<br />
<br />
<pre class="brush:java">/**
* If Javascript Alert is present on the page cancels it.
*/
public void handleAlert(){
if(isAlertPresent()){
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
}
}
/**
*
* @return True if JavaScript Alert is present on the page otherwise false
*/
public boolean isAlertPresent(){
try{
driver.switchTo().alert();
return true;
}catch(NoAlertPresentException ex){
return false;
}
}</pre>
</div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com0tag:blogger.com,1999:blog-1282146880741978115.post-60858222707454514382013-10-17T16:16:00.000+05:302015-03-11T12:17:13.530+05:30Speedup Your Selenium Test with PhantomJS<div dir="ltr" style="text-align: left;" trbidi="on">
I was searching some way to speedup my WebDriver tests and this is what I came across, PhantomJS. It took awhile to understand how it works but it's worth spending time as I can say it's <b>more than 50% faster</b> when your run your test with <b>PhantomJS</b>. So,<br />
<h4 style="text-align: left;">
What is PhantomJS?</h4>
PhantomJS is a headless <b>WebKit </b>scriptable with a JavaScript API. It's okay if you didn't understand it by this single line. Let me explain it to you.<br />
Webkit is a browser engine which allows web browser to render pages, and it is used by many streamline browser (I guess Firefox and Google chrome both uses this). Now what is this headless then? Headless mean you won't be able to see any GUI component of the browser.<br />
<h4 style="text-align: left;">
So Why PhantomJS is faster ?</h4>
This is the second question you might come up with. That if it is the same engine that many browser uses then how my test cases will execute faster if I will run them on PhantomJS.<br />
The reason is, it just process data (request and response) it doesn't draw canvas.<br />
<br />
We have had enough talk, now let's compare the result.<br />
<br />
<pre class="brush:java">import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.testng.annotations.Test;
public class TestPhantoJS {
/**
* @author Gaurang_Shah
* Following test will search the keyword on google
* and will print all websites on first page.
*/
@Test
public void GoogleSearch(){
WebDriver driver = new PhantomJSDriver();
// WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
driver.findElement(By.name("q")).sendKeys("phantomjs");
driver.findElement(By.name("q")).submit();
List<WebElement> sites = driver.findElements(By.xpath("//cite"));
System.out.println(driver.getTitle());
int index=1;
for(WebElement site: sites){
String siteName=site.getText();
if(!siteName.equalsIgnoreCase(""))
System.out.println(index+++":--"+site.getText());
}
driver.close();
}
}</pre>
On my machine when I am running above test with PhantomJSdriver and FirefoxDriver following is the result. <br />
<b>FirefoxDriver </b>- ~28 seconds<br />
<b>PhantomJSDriver </b>- ~13 seconds<br />
<b>Pretty Fast. Right ??</b><br />
<h4 style="text-align: left;">
Let Me Move My all Tests to PhantomJSDriver </h4>
this is the first thought that my come up in your mind after this result. Right ???, however I wouldn't advice you to do that. And there are reason to this as well as mention below.<br />
PhantomJS is just a headless WebKit which uses JavaScript, however it uses GhostDriver to run your test cases used webdriver. And it's in intermediate stage and you might feel bit trouble with someone the WebDriver API.<br />
<br />
<h4 style="text-align: left;">
What is GhostDriver?? </h4>
I am sure you must have this question in mind. Let me try to explain it to you. It's a Webdriver wire protocol in simple javascript for PhantomJS. (what the hell ??? ) ohh. let me make it more simple. GhostDriver is not but some kind of communicator between your Webdriver Bidning and PhantomJS.
PhantomJS comes with the GhostDriver inbuilt, however it's available separately as well.
</div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com2tag:blogger.com,1999:blog-1282146880741978115.post-69306575025931672312013-10-08T13:57:00.000+05:302015-03-11T12:18:26.542+05:30Webdriver: RobotFramework with Java - Part 1<div dir="ltr" style="text-align: left;" trbidi="on">
There are so many posts available which states how to install/setup and configure robotframwork in python, however i didn't find any good posts which states how to configure robotframework in Java. So decided to write a blog.<br />
<div>
<br /></div>
<h3 style="text-align: left;">
Install/Setup Robot Framework </h3>
<div>
To run webdriver test with RoboFramework in java you require following two jar files. </div>
<div>
<a href="https://code.google.com/p/robotframework/downloads/detail?name=robotframework-2.8.1.jar">robotframework-2.8.1.jar</a></div>
<div>
<a href="http://search.maven.org/remotecontent?filepath=com/github/markusbernhardt/robotframework-selenium2library-java/1.2.0.13/robotframework-selenium2library-java-1.2.0.13-jar-with-dependencies.jar">robotframework-selenium2library-java-1.2.0.13-jar-with-dependencies.jar</a></div>
<div>
<br /></div>
<div>
Download the above two files and put that into some directory. </div>
<div>
<br /></div>
<h3 style="text-align: left;">
Sample Test Case</h3>
<div>
Create the <b>testcase.txt</b> as mention below into the same directory in which you downloaded JARs</div>
<div>
</div>
<pre class="brush:text">***Setting***
Library Selenium2Library
*** Test Cases ***
Get Current Browser Test
Open Browser http://google.com</pre>
<h3 style="text-align: left;">
Run Test Case</h3>
<div>
To run the RobotFramework test case you need to set the <b>CLASSPATH</b>. Please add above jar files into your classapth and run the following command </div>
<div>
</div>
<div>
<pre class="brush:text">java org.robotframework.RobotFramework run testcase.txt</pre></div>
<div>
</div>
<h3 style="text-align: left;">
Verify Results</h3>
<div>
Results will be located into same directory in which you have created test case. </div>
<div>
<br /></div>
</div>Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com11tag:blogger.com,1999:blog-1282146880741978115.post-82008280028147284522013-10-01T10:17:00.000+05:302015-03-12T17:44:15.317+05:30WebDriver: TestNG with ANT<div dir="ltr" style="text-align: left;" trbidi="on">
Few posts back I explained how to use Maven with Webdriver and TestNG. Now let's see how to use ANT with WebDriver and TestNG.
<br />
<pre class="brush:xml"><project name="WebDriverAntTestNG" default="run" basedir=".">
<path id="libs">
<!-- Include all the external Jar files -->
<fileset dir="${basedir}\src\jars">
<include name="*.jar"/>
</fileset>
<!-- Include all the compile classes -->
<fileset dir="bin">
<include name = "**/*.class"/>
</fileset>
<pathelement path="${basedir}\bin"/>
</path>
<target name="run">
<antcall target="init"/>
<antcall target="compile"/>
<antcall target="runTests"/>
</target>
<!-- Delete old data and create new directories -->
<target name="init" >
<echo>Initlizing...</echo>
<delete dir="bin" />
<mkdir dir="bin"/>
<delete dir="report" />
<mkdir dir="report"/>
</target>
<!-- Complies the java files -->
<target name="compile">
<echo>Compiling...</echo>
<javac includeantruntime="false" debug="true" srcdir="src" destdir="bin" classpathref="libs" />
</target>
<!-- Runs the file and generates Reportng report -->
<target name="runTests" description="Running tests" >
<echo>Running Tests...</echo>
<taskdef resource="testngtasks" classpathref="libs"/>
<testng outputDir="report"
haltonfailure="true"
classpathref="libs"
>
<classfileset dir="bin" includes="**/*.class" />
</testng>
</target>
</project></pre>
<h4>
Targets Explained:
</h4>
<br />
<div>
<b>Run: </b>This is main target, which will call all the below target in order.</div>
<div>
<b>Init:</b> This target will delete the Bin an Report directory and will crate again in order to clean. </div>
<div>
<b>Compile:</b> This target will compile all the java classes. </div>
<div>
<b>runTests:</b> This target contain the TestNGTask which will all the testng tests. </div>
<div>
</div>
<br />
<br /></div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com1tag:blogger.com,1999:blog-1282146880741978115.post-8993231378620526312013-09-03T15:00:00.001+05:302015-03-05T16:45:09.604+05:30Jenkins: Static Analysis with CheckStyle<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
In the last post I mention how to configure your Maven Webdriver project on Jenkins, today let's see how to configure <b>checkStyle </b>plugin for static analysis with jenkins.<br />
<br />
<h3 style="text-align: left;">
Configure Check Style with Maven</h3>
Mention the following plugin in pom.xml, make sure you mention it inside build block
<br />
<b>pom.xml
<br />
</b><br />
<pre class="brush:xml"><b><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>2.10</version>
<configuration>
<sourceDirectory>src</sourceDirectory>
</configuration>
</plugin></b></pre>
<b><br /></b>
<b>Configure Check Style with Jenkins</b><b>
</b><br />
follow the steps mention below to configure and generate checkStyle Report in jenkins
<br />
Install checkStyle plugin
Navigate to Manage Jenkins->Manage Plugin and install checkStyle plugin and then restart the jenkins
<br />
<br />
<b>Configure checkStyle for project</b>
<br />
Following is how to configure checkStyle for Maven project, it might vary if you are using ANT.
</div>
<ul style="text-align: left;">
<li>Append checkstyle:checkstyle to your build goal<div class="separator" style="clear: both; text-align: center;">
</div>
</li>
<li>check Publish Checkstyle analysis results<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="font-weight: bold; margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://4.bp.blogspot.com/-DWjQyafHWzM/UiWosCtjn6I/AAAAAAAACB4/pZKtnXYmvhE/s1600/Jenkins_Config_CheckStyle.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="Configure Checkstyle for project" border="0" height="143" src="http://4.bp.blogspot.com/-DWjQyafHWzM/UiWosCtjn6I/AAAAAAAACB4/pZKtnXYmvhE/s400/Jenkins_Config_CheckStyle.jpg" title="Configure Checkstyle for project" width="400" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;"><span style="font-weight: normal;">Configure checkStyle for Project</span></td></tr>
</tbody></table>
<div class="separator" style="clear: both; font-weight: bold; text-align: center;">
</div>
</li>
</ul>
<b>Configure checkStyle Reports</b>
<br />
Now you need to configure which reports you want to see for this project, follow the steps to configure reports
</div>
<ul style="text-align: left;">
<li>Navigate to Jenkins home page and create new view<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="font-weight: bold; margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://4.bp.blogspot.com/-Y7SivhclCQg/UiWor6qdSEI/AAAAAAAACBw/etKslC0iI0k/s1600/Jenkins_Config_CheckStyle_1.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="Add New Dashboard for checkStyle" border="0" height="81" src="http://4.bp.blogspot.com/-Y7SivhclCQg/UiWor6qdSEI/AAAAAAAACBw/etKslC0iI0k/s400/Jenkins_Config_CheckStyle_1.jpg" title="Add New Dashboard for checkStyle" width="400" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;"><span style="font-weight: normal;">Add new dashboard for checkstyle</span></td></tr>
</tbody></table>
<div class="separator" style="clear: both; font-weight: bold; text-align: center;">
</div>
</li>
<li>Select the project you want to include for checkStyle Report<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="font-weight: bold; margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://3.bp.blogspot.com/-V6wskXdSWRQ/UiWorxXf-VI/AAAAAAAACBs/tjiq7gGNVx0/s1600/Jenkins_Config_CheckStyle_2.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="Add Projects for checkStyle Report" border="0" height="63" src="http://3.bp.blogspot.com/-V6wskXdSWRQ/UiWorxXf-VI/AAAAAAAACBs/tjiq7gGNVx0/s400/Jenkins_Config_CheckStyle_2.jpg" title="Add project for checkstyle report" width="400" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;"><span style="font-weight: normal;">choose jenkins jobs for checkstyle</span></td></tr>
</tbody></table>
<div class="separator" style="clear: both; text-align: center;">
</div>
</li>
<li>Include the graphs/reports you want<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="font-weight: bold; margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://4.bp.blogspot.com/-X2AHs7vO_T8/UiWovXXoPBI/AAAAAAAACCA/ToFd4JAEieM/s1600/Jenkins_Config_CheckStyle_3.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="Select Graphs for checkStyle report" border="0" height="193" src="http://4.bp.blogspot.com/-X2AHs7vO_T8/UiWovXXoPBI/AAAAAAAACCA/ToFd4JAEieM/s400/Jenkins_Config_CheckStyle_3.jpg" title="Select Graphs for checkStyle report" width="400" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;"><span style="font-weight: normal;">configure checkstyle report in jenkins</span></td></tr>
</tbody></table>
<div class="separator" style="clear: both; font-weight: bold; text-align: center;">
</div>
</li>
</ul>
<b>
</b>
</div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com2Pune, Maharashtra, India18.5204303 73.85674369999992518.2782328 73.532647199999928 18.7626278 74.180840199999921tag:blogger.com,1999:blog-1282146880741978115.post-19947741929628942862013-09-02T14:39:00.004+05:302013-09-05T19:54:20.043+05:30WebDriver with Jenkins<div dir="ltr" style="text-align: left;" trbidi="on">
In the last post we see how to create Maven Project for WebDriver from eclipse. Now let's configure same Webdriver Maven Project on Jenkins.<br />
<br />
<h3 style="text-align: left;">
Setup Jenkins on Windows </h3>
download the jenkins from following location<br />
http://jenkins-ci.org/<br />
<b>Running Jenkins as War file </b><br />
You can run jenkins using war file, if you are doing it you don't need any slave to start on machine.
<b>Running Jenkins as Windows Service </b><br />
If you have installed Jenkins as Windows Services then you need to Start Slave and Bind you project to that slave.<br />
<br />
<h3 style="text-align: left;">
Create/Run Slave Node </h3>
If Jenkins is installed as Windows Services you need to start the JNLP slave node on machine where you need to execute your test cases. Follow the process to create node.<br />
<ul style="text-align: left;">
<li>Go to Manage Jenkins->Manage Nodes and Click on New Node</li>
<li>Enter the Node Name and choose Dumb Slave<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://1.bp.blogspot.com/-uaWimFNI2U8/UiRRr6TBnqI/AAAAAAAACAs/mA8AHQApbbQ/s1600/Jenkins_Create_Node_1.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="Create Jenkins Slave node for WebDriver Execution" border="0" height="58" src="http://1.bp.blogspot.com/-uaWimFNI2U8/UiRRr6TBnqI/AAAAAAAACAs/mA8AHQApbbQ/s200/Jenkins_Create_Node_1.png" title="Create Jenkins Slave node for WebDriver Execution" width="200" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Create Jenkins Slave node for WebDriver Execution</td></tr>
</tbody></table>
<br /><br /><div class="separator" style="clear: both; text-align: center;">
</div>
</li>
<li>Enter the information as mention in the screenshot<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://4.bp.blogspot.com/-Dms_JbZEgaA/UiRRsVk0I1I/AAAAAAAACAw/-I2SekZdOuM/s1600/Jenkins_Create_Node_2.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="Configure Node for WebDriver" border="0" height="124" src="http://4.bp.blogspot.com/-Dms_JbZEgaA/UiRRsVk0I1I/AAAAAAAACAw/-I2SekZdOuM/s320/Jenkins_Create_Node_2.jpg" title="Configure Node for WebDriver" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Configure Node for WebDriver</td></tr>
</tbody></table>
</li>
<li>After saving node will be listed under Nodes <table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://4.bp.blogspot.com/-3By-qhsX2TM/UiRRtO_25xI/AAAAAAAACA8/wnIkAKi3lcU/s1600/Jenkins_Create_Node_3.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="All Available Nodes in Jenkins" border="0" height="97" src="http://4.bp.blogspot.com/-3By-qhsX2TM/UiRRtO_25xI/AAAAAAAACA8/wnIkAKi3lcU/s320/Jenkins_Create_Node_3.jpg" title="All Available Nodes in Jenkins" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">All Available Nodes in Jenkins</td></tr>
</tbody></table>
</li>
<li>Start the node by Running displayed command in CMD<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://4.bp.blogspot.com/-V_xl1malmQk/UiRRtMmcTxI/AAAAAAAACBA/_5z6ZKZ21i4/s1600/Jenkins_Create_Node_4.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="Start JNLP node in Jenkins" border="0" height="96" src="http://4.bp.blogspot.com/-V_xl1malmQk/UiRRtMmcTxI/AAAAAAAACBA/_5z6ZKZ21i4/s320/Jenkins_Create_Node_4.jpg" title="Start JNLP node in Jenkins" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Starting JNLP Node in Jenkins</td></tr>
</tbody></table>
<div class="separator" style="clear: both; text-align: center;">
</div>
</li>
<li>if everything has been done correctly if you will able to see small java program running<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://3.bp.blogspot.com/-kRbRIrT8VJg/UiRRtvsw63I/AAAAAAAACBM/5NStHgOlpoI/s1600/Jenkins_Create_Node_6.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="Connected JNLP Node" border="0" src="http://3.bp.blogspot.com/-kRbRIrT8VJg/UiRRtvsw63I/AAAAAAAACBM/5NStHgOlpoI/s1600/Jenkins_Create_Node_6.jpg" title="Connected JNLP Node" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Connected JNLP Node</td></tr>
</tbody></table>
</li>
</ul>
<br />
<br />
<h3 style="text-align: left;">
Configure Maven in Jenkins</h3>
<div>
Before you create a new Job for Maven WebDriver Project, let's configure Maven in jenkins<br />
Go to Manage Jenkins->Configure System and Provide Installation directory for JDK and Maven as mention in screenshot below<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://4.bp.blogspot.com/-Dms_JbZEgaA/UiRRsVk0I1I/AAAAAAAACAw/-I2SekZdOuM/s1600/Jenkins_Create_Node_2.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="Configure JDK and Maven in Jenkins" border="0" height="124" src="http://4.bp.blogspot.com/-Dms_JbZEgaA/UiRRsVk0I1I/AAAAAAAACAw/-I2SekZdOuM/s320/Jenkins_Create_Node_2.jpg" title="Configure JDK and Maven in Jenkins" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Configure JDK and Maven in Jenkins</td></tr>
</tbody></table>
</div>
<br />
<h3 style="text-align: left;">
Create New Job on Jenkins
</h3>
Now let's create the new Job for Project
<br />
<ul style="text-align: left;">
<li>Go to Home page and click on New Job<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://4.bp.blogspot.com/-DjKPoqWygE0/UiRRqwuZXGI/AAAAAAAACAU/HhnK-sLKIC4/s1600/Create_Job_1.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="Create Jenkins Job for Maven WebDriver Project" border="0" height="127" src="http://4.bp.blogspot.com/-DjKPoqWygE0/UiRRqwuZXGI/AAAAAAAACAU/HhnK-sLKIC4/s320/Create_Job_1.jpg" title="Create Jenkins Job for Maven WebDriver Project" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Create Jenkins Job for Maven WebDriver Project</td></tr>
</tbody></table>
</li>
<li>Restrict the job to run on the Slave Node we created<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://2.bp.blogspot.com/-yRldPfw1xWU/UiRRqz572cI/AAAAAAAACAM/EE4a2ZUF9B8/s1600/Create_Job_2.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="Configure WebDriver Project to run on Specific Node" border="0" height="91" src="http://2.bp.blogspot.com/-yRldPfw1xWU/UiRRqz572cI/AAAAAAAACAM/EE4a2ZUF9B8/s320/Create_Job_2.jpg" title="Configure WebDriver Project to run on Specific Node" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Configure WebDriver Project to run on Specific Node</td></tr>
</tbody></table>
</li>
<li>Click on Use custom workspace and Mention your workspace location und Directory</li>
<li>Provide the path of pom.xml in Root POM and provide Test in Goals and Options<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://4.bp.blogspot.com/-oRkZEcKmzag/UiRRq3ToqOI/AAAAAAAACAY/cNqS5KMg-NE/s1600/Create_Job_3.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="Provide Maven in Goal in Jenkins" border="0" height="156" src="http://4.bp.blogspot.com/-oRkZEcKmzag/UiRRq3ToqOI/AAAAAAAACAY/cNqS5KMg-NE/s320/Create_Job_3.jpg" title="Provide Maven in Goal in Jenkins" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Provide Maven Goal in Jenkins</td></tr>
</tbody></table>
</li>
</ul>
</div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com2tag:blogger.com,1999:blog-1282146880741978115.post-16903963483845209602013-09-01T17:52:00.000+05:302015-05-12T21:13:10.705+05:30WebDriver with Maven<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
Maven is a build Automation Tool somewhat like ANT. Having use ANT for the previous project wanted to try Maven this time. I thought it would be easy as I know ANT, however it took a while for me to figure out as i didn't find any proper tutorial on net. And this is the reason I am writing new Blogpost.<br />
<br />
I have just started, So if someone knows the better way to do few things mention here please let me know in comment.<br />
<br />
Now let's try setting up new Maven Project for Webdriver using Eclipse. However before you do, you need to download and setup Maven on you local machine. <br />
<br />
<span style="font-size: large;">Setup up Maven</span><br />
<ul style="text-align: left;">
<li>download the appropriate maven from the following site. <br />http://maven.apache.org/download.cgi
Extract it to some location and setup the PATH variable. </li>
<li>If you have done everything correctly, Following command on CMD will let you know the Maven Version. <br />mvn --version </li>
</ul>
<br />
<br />
<span style="font-size: large;">Install Maven Plug-in in Eclipse </span><br />
Install the <b>m2Eclipse </b>plugin in you eclipse<br />
<br />
<span style="font-size: large;">Setup Maven Project for WebDriver. </span><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<ul style="text-align: left;">
<li>In Eclipse choose New Maven Project and check the "Create Simple Project" <div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-GeQ3mTulFHE/UiMw1CzW-8I/AAAAAAAAB_w/om-2Z4zApRc/s1600/NewMavenProject.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="288" src="http://1.bp.blogspot.com/-GeQ3mTulFHE/UiMw1CzW-8I/AAAAAAAAB_w/om-2Z4zApRc/s320/NewMavenProject.jpg" width="320" /></a></div>
</li>
<li>Fill the <b>Group id</b> and <b>Artifact id</b> <div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-QYky3hPSyCA/UiMw1_RwkpI/AAAAAAAAB_4/enMWB6_KAhs/s1600/NewMavenProject_1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="288" src="http://1.bp.blogspot.com/-QYky3hPSyCA/UiMw1_RwkpI/AAAAAAAAB_4/enMWB6_KAhs/s320/NewMavenProject_1.jpg" width="320" /></a></div>
</li>
<li>Create New Class named <b>"GoogleTest"</b> under <b>"src/test/java"</b>
Copy Following code in it.</li>
<b>
GoogleTest.java <div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-ufrB0E41xe4/UiMw1JKh1XI/AAAAAAAAB_s/O3hD1R_RCTg/s1600/MavenPackageExploere.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="257" src="http://2.bp.blogspot.com/-ufrB0E41xe4/UiMw1JKh1XI/AAAAAAAAB_s/O3hD1R_RCTg/s320/MavenPackageExploere.jpg" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div><!--INFOLINKS_OFF-->
</b><pre class="brush:java">import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
/**
* @author Gaurang_Shah
*/
public class GoogleTest {
private WebDriver driver;
@Test
public void verifySearch() {
driver = new FirefoxDriver();
driver.get("http://www.google.com/");
driver.quit();
}
}</pre>
</ul>
</div>
<br />
<br /><!--INFOLINKS_ON-->
<li>It will show you some compile time error as we haven't added the dependencies yet. </li>
<li>Maven mention all the dependencies in pom.xml file. Please copy and replace the following pom.xml with your project <b>pom.xml</b> file.
<!--INFOLINKS_OFF-->
<pre class="brush:xml"><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>MavenWebDriverDemo</groupId>
<artifactId>MavenWebDriverDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.33.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>2.33.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.5</version>
</dependency>
</dependencies>
</project></pre>
</li>
<span style="font-size: large;">
<!--INFOLINKS_ON-->
Running Project
</span><br />
<ul style="text-align: left;">
<li>To run from Eclipse, Right click on<b> pom.xml</b> and choose <b>Run as --> Maven Test</b> </li>
<li>To run from command line, Go to project directory and enter following command <br /><b> mvn test</b></li>
</ul>
<div>
</div>
</div>Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com7tag:blogger.com,1999:blog-1282146880741978115.post-60805804154131572562013-07-22T11:14:00.002+05:302013-07-22T11:15:20.504+05:30webdriver - handle untrusted ssl certificate<div dir="ltr" style="text-align: left;" trbidi="on">
While doing automation of https site there are chances when you get the following error.<br />
<b>This Connection is Untrusted. </b><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-WZlYTQ0QXUA/UezForHHJ-I/AAAAAAAAB9Q/-jZ_wFvlhOQ/s1600/Connection_Untrustred.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-WZlYTQ0QXUA/UezForHHJ-I/AAAAAAAAB9Q/-jZ_wFvlhOQ/s1600/Connection_Untrustred.png" /></a></div>
<b><br /></b>
<b>Reason:</b> This certificate is not issued by some valid authority, it's a self signed certificate.<br />
<br />
<b>Solution:</b><br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<ul style="text-align: left;">
<li>Create a new profile and add this certificate in that profile by using following steps.</li>
<li>Make sure you are accessing site though the domain for which certificate has issued.</li>
<li> If you get the above screen after accessible the site, You need to add certificate in Exception so next time it doesn't give you error.</li>
<li>However while adding certificate make sure "Permanently store this exception" check box is selected. </li>
<li>If "Permanently store this exception" is enable the history.<br /><br /><div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-p99IbocI2DQ/UezGIDzrvmI/AAAAAAAAB9Y/-hQWqvPJ8_0/s1600/Add_Exception.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-p99IbocI2DQ/UezGIDzrvmI/AAAAAAAAB9Y/-hQWqvPJ8_0/s1600/Add_Exception.png" /></a></div>
</li>
<li>Now you need to give path of this newly created profile while creating the object of WebDriver.</li>
</ul>
</div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com0tag:blogger.com,1999:blog-1282146880741978115.post-49080200141460095512013-07-17T17:14:00.002+05:302013-07-17T17:16:28.420+05:30PyTest - Quick Reference<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-size: large;">What is PyTest?</span><br />
PyTest is just like any other unit test framework for Python. It generates JUnit XML report as well which makes easy to integrate it's report with Jenkins<br />
<br />
<span style="font-size: large;">How to Install PyTest: </span><br />
pip install -U pytest
or<br />
easy_install pytest<br />
<br />
<span style="font-size: large;">How it Identifies: </span><br />
Every unit testing framework has some pattern though which identifies which is Test Class, which is Test Method, Which is Setup and TearDown method and so do PyTest.<br />
Test Class - Any Class name which starts with Test is indentified as Test Class (i.e. TestMathFunc)
Test- Any function which starts with test_ is identified as test method (i.e. test_devision)<br />
Apart from this there are few setup and teardown methods as well, as mention below<br />
<b>setup_module:-</b> Called before the first test of the module<br />
<b>teardown_module:-</b> Called after the last test of the module<br />
<b>setup_class:-</b> Called before the first test of the class<br />
<b>teardown_class:-</b> Called after the last test of the class
<br />
<b>setup_method:-</b> Called before each and every test inside class<br />
<b>teardown_method:-</b> Called after each and every test inside class<br />
<b>setup_function:- </b>Called before each and every test outside class<b> </b><br />
<b>teardown_function:- </b>Called after each and every test outside class<b> </b><br />
<br />
<span style="font-size: large;">Sample Code:
</span><br />
PyTestDemo.py
<br />
<pre class="brush:py">class TestPyTestDemo():
"""
This class demonstrates who to write simple test using pytest framework
@author: Gaurang Shah
@contact: gaurangnshah@gmail.com
"""
def add(self,arg1,arg2):
return arg1+arg2
def test_pass(self):
print "test_pass"
assert self.add(2, 3) == 5
def test_fail(self):
print "test_fail"
assert self.add(0, 2) == 1
def setup_method(self,method):
"This method will be called before each and every method inside class"
print "setup_method"
def teardown_method(self,method):
"This method will be called after each and every method inside class"
print "teardown_method"
@classmethod
def setup_class(cls):
"This method will be called before first method of classe"
print "setup_class"
@classmethod
def teardown_class(cls):
"This method will be called after last method of class"
print "teardown_class"
def setup_module(module):
"This method will be called before first method of module"
print "setup_module"
def teardown_module(module):
"This method will be called after last method of module"
print "teardown_module"
def setup_function(function):
"This method will be called before each and every function outside class"
print "setup function"
def teardown_function(function):
"This method will be called before each and every function outside class"
print "teardown function"
def test_function():
print "test_function"</pre>
<span style="font-size: large;">How to Execute :</span><br />
py.test PyTestDemo.py
</div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com0tag:blogger.com,1999:blog-1282146880741978115.post-91870992245626125142013-01-28T20:01:00.001+05:302013-01-29T16:36:01.695+05:30WebDriver: isTextPresent<div dir="ltr" style="text-align: left;" trbidi="on">
WebDriver is way far better in many ways than selenium RC, However if you have migrated from Selenium RC, you will miss few functions. And two on the top lists are isTextPresent and isElementPresent.
Though it's not available in webdriver, it's not complicated to implement, there are various ways to the same thing. I will discuss few ways in following post.<br />
<br />
<ol style="text-align: left;">
<li><b>Using in in-build PageSource API</b></li>
<pre class="brush:java">public boolean isTextPresent(String text){
if (driver.getPageSource().contains(text)) {
return true;
}
else
return false;
}</pre>
<b>
Disadvantages: </b>
<ul style="text-align: left;">
<li>It is too slow as compared other two options as it checks in whole page source.</li>
<li>Result might be wrong as it doesn't verify only visible text on webpage but whole source code (script + html tags)<br /></li>
</ul>
<li><b>Using XPath</b></li>
<pre class="brush:java">public boolean isTextPresent(String text){
try {
driver.findElement(By.xpath("//*[contains(.,'"+text+"')]"));
return true;
}catch(NoSuchElementException e){
return false;
}
}</pre>
<b>
Disadvantages:
</b><br />As it is using XPath, it might be slow on IE than on Firefox and Chrome Browsers.</ol>
<ol style="text-align: left;">
<li><b>Using Selenium RC Function.</b></li>
<pre class="brush:java">public boolean isTextPresent(String text){
try{
WebDriverBackedSelenium selenium = new WebDriverBackedSelenium(driver, "");
if(selenium.isTextPresent(text)){
return true;
}else{
return false;
}
}catch(Exception e){
return false;
}
}</pre>
<b>
Disadvantages:
</b><br />It is using Selenium RC code.
</ol>
<br /></div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com0tag:blogger.com,1999:blog-1282146880741978115.post-89523195286100370772012-10-18T18:03:00.000+05:302015-03-11T12:47:08.037+05:30WebDriver - Take Screenshots on Test Case Fail.<div dir="ltr" style="text-align: left;" trbidi="on">
There are two way you can achieve this if you are using <b>TestNG</b> as you unit testing framework.
Refer the following blog post to see how to do this using TestNG.<br />
<a href="http://qtp-help.blogspot.in/2010/07/testng-take-screenshot-of-failed-test.html">http://qtp-help.blogspot.in/2010/07/testng-take-screenshot-of-failed-test.html</a><br />
<br />
Below we will discuss how to do the same thing using WebDriver listeners.
Webdriver has a <b>WebDriverEventListener </b>interface which you can implement and override the particular listener you want.
WebDriverEventListener interface has <b>onException </b>method which is being called whenever a WebDriver exception occurs, So we will override this method and will write down the code to take screenshot in it.<br />
<br />
<b>WebDriverEventListenerDemo.java
</b><br />
you need to implement all the methods of the WebDriverEventListener class, here I haven't show that to make code looks small.<br />
<pre class="brush:java">import java.io.*;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.support.events.WebDriverEventListener;
/***
* Implements WebDriverEventListener and overrides onException method
* @author Gaurang
*
*/
public class WebDriverEventListenerDemo implements WebDriverEventListener {
@Override
public void onException(Throwable exception, WebDriver driver) {
File screenShot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenShot, new File("c:\\tmp\\exception.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
</pre>
<b>TestWithEvenRegistered.java
</b><br />
<pre class="brush:java">import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/***
* Class registers the Event listern class we created
* @author gshah
*
*/
public class TestWithEvenRegistered {
WebDriver driver = new FirefoxDriver();
EventFiringWebDriver eventFiringWebDriver;
@BeforeClass
public void setup() {
eventFiringWebDriver = new EventFiringWebDriver(driver);
eventFiringWebDriver.register(new WebDriverEventListenerDemo());
eventFiringWebDriver.get("http://google.com");
}
/**
* "qq" is wrong element id and so NoElementFound Exception will
* be generated, which will call our overridden method of WebDriverEventListenerDemo
* class and will take the screenshot.
*/
@Test
public void test(){
eventFiringWebDriver.navigate().to("http://google.com");
eventFiringWebDriver.findElement(By.name("qq"));
}
}
</pre>
</div>
<!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_sharing_toolbox"></div>Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com2tag:blogger.com,1999:blog-1282146880741978115.post-24258891454605648192012-10-08T17:54:00.002+05:302012-10-09T12:22:30.630+05:30WebDriver - Selecting from CSS dropdown<div dir="ltr" style="text-align: left;" trbidi="on">
In last few years the web designing has advanced too much. And for better look and feel people sometimes uses CSS to overwrite basic HTML component like editbox, dropdown, checkbox.
It doesn't create any problem until you try to Automate it, but the moment you think to automate it started giving problem.<br />
The biggest problem is, tools specifically selenium doesn't identify them as a proper element.
For example, "All Categories" dropdown on flipcart.com.<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-H4FCLy9hNC4/UHLLmB-uHLI/AAAAAAAAA6Q/6BdInZ_-BDE/s1600/flipcart_CSS_Dropdown.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="259" src="http://1.bp.blogspot.com/-H4FCLy9hNC4/UHLLmB-uHLI/AAAAAAAAA6Q/6BdInZ_-BDE/s640/flipcart_CSS_Dropdown.jpg" width="640" /></a></div>
<br />
If you will see it's code it is not standard HTML dropdown box, you wouldn't be able to find any select tag. And so the following code would fail.
<br />
<pre class="brush:java">@Test
public void selectCSSDropDown(){
driver.get("http://flipcart.com");
Select catagoryDropDown = new Select(driver.findElement(By.className("fk-menu-selector")));
catagoryDropDown.selectByVisibleText("Cameras");
}</pre>
It will give you error somewhat like blow: <br />
<span style="color: red;">org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "a"</span><br />
There are two workarounds to this.<br />
<ol style="text-align: left;">
<li><b>Click on the Dropdown and then click on the item you want to select </b>
<br /> However using this you will be able to select by index only and not by visible text
<pre class="brush:java">@Test
public void selectCssDropDownUsingCSS() {
driver.get("http://flipcart.com");
driver.findElement(By.className("fk-menu-selector")).click();
driver.findElement(By.cssSelector("div#fk-mI li:nth-child(5)")).click();
}</pre>
</li>
<li><b>Through JavaScript</b>
<br />You are lucky if your website if using JavaScript function to select an item, that way we can directly call those JavaScript functions as mention below
<pre class="brush:java">@Test
public void selectCssDropDownUsingJavaScript(){
driver.get("http://flipcart.com");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("selectMItem('Cameras', 'cameras')");
}</pre>
</li>
</ol>
</div>
Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com1tag:blogger.com,1999:blog-1282146880741978115.post-1460454017872724292012-10-07T22:26:00.000+05:302015-03-01T15:19:43.398+05:30Webdriver - Page Object Pattern<div dir="ltr" style="text-align: left;" trbidi="on">
What I am going to discuss here is Page Object Pattern with Page Factory for Webdriver.
Let's not talk much about theory and let's see how to implement it. let's take one scenario and see how we can automate it without and with Page Object Pattern
Scenario:<br />
<ol style="text-align: left;">
<li>Open http://newtours.demoaut.com/ site </li>
<li>Login to the site. </li>
<li>Log out.
Now if we are not using any design patten the testcase will look like below
</li>
</ol>
<pre class="brush:java">@Test
public void testLogin() {
driver.findElement(By.id("userName")).clear();
driver.findElement(By.id("userName")).sendKeys("testuser33");
driver.findElement(By.id("password")).clear();
driver.findElement(By.id("password")).sendKeys("password123");
driver.findElement(By.id("login")).click();
driver.findElement(By.linkText("SIGN-OFF")).click();
}
</pre>
Now let's see how the code will look like if we will have to use the Page Object Pattern with Page Factory.
<b>LoginPage.java - </b>contains Login page web elements and functions<b><br /></b><br />
<pre class="brush:java">package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
public class LoginPage {
final WebDriver driver;
@FindBy(how = How.NAME, using = "userName")
private WebElement usernameEditbox;
@FindBy(how = How.NAME, using = "password")
private WebElement passwordEditbox;
@FindBy(how = How.NAME, using = "login")
private WebElement singinButton;
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void enterUsername(String login) {
usernameEditbox.clear();
usernameEditbox.sendKeys(login);
}
public void enterPassword(String password) {
passwordEditbox.clear();
passwordEditbox.sendKeys(password);
}
public void clickSigninButton() {
singinButton.click();
}
public FindFlightPage login(String login, String password) {
enterUsername(login);
enterPassword(password);
clickSigninButton();
return PageFactory.initElements(driver, FindFlightPage.class);
}
}
</pre>
<b>FindFlightPage.java - </b>contains Find Flight page web elements and functions
<br />
<pre class="brush:java">package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
public class FindFlightPage {
final WebDriver driver;
public FindFlightPage(WebDriver driver) {
this.driver = driver;
}
@FindBy(how = How.LINK_TEXT, using="SIGN-OFF")
private WebElement signOff;
public LoginPage singOff(){
signOff.click();
return PageFactory.initElements(driver, LoginPage.class);
}
}
</pre>
<b>LoginTest.java - </b>Actual class which contains tests for login page
<br />
<pre class="brush:java">package Tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import Pages.FindFlightPage;
import Pages.LoginPage;
public class LoginTest {
WebDriver driver;
private static String login = "testuser33";
private static String pass = "password123";
@BeforeClass
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.get("http://newtours.demoaut.com/mercuryreservation.php");
}
@Test
public void testLogin() {
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
FindFlightPage findPage = loginPage.login(login, pass);
loginPage = findPage.singOff();
}
@AfterClass
public void tearDown() throws Exception {
driver.quit();
}
}
</pre>
</div>Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com4tag:blogger.com,1999:blog-1282146880741978115.post-90865183398223912042012-03-07T11:49:00.000+05:302012-03-09T10:20:50.742+05:30WebDriver - Dynamic Table<div dir="ltr" style="text-align: left;" trbidi="on">
<b>Scenario:</b> Sometimes we have a dynamic table, in which neither the number of rows, or the order is constant. And in such case if you have to verify and particular values from the table you can use the following technique. <br />
<br />
<b>Assumption:</b> Following table is dynamic table, which can have any number of rows and order or the records may also change every time you load. <br />
<br />
<div dir="ltr" style="text-align: left;" trbidi="on">
<table border="1" name="salaryTable"><tbody>
<tr> <td><b>Names</b></td> <td><b>Designation</b></td><td><b>salary</b></td> </tr>
<tr> <td>Gaurang</td><td>Confused</td><td>45000</td> </tr>
<tr> <td>Ajay</td><td>Team Lead</td><td>50000</td> </tr>
<tr> <td>Binoy</td><td>QA</td><td>40000</td> </tr>
<tr> <td>Santosh</td><td>Project Manager</td><td>100000</td> </tr>
</tbody></table>
</div>
<br />
<b>TestCase:</b> Verify the Salary of Gaurang from the above table. <br />
<br />
<pre class="brush:java">/**
* @author Gaurang Shah
* Purpose: To demonstrate how to verify Dynamic Table in Selenium
*/
import static org.junit.Assert.*;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WebDriverTable {
public static WebDriver driver;
@BeforeClass
public static void setup() {
// Create a new instance of the Firefox driver
driver = new FirefoxDriver();
driver.get("http://qtp-help.blogspot.in/2012/02/selenium-verify-table.html");
}
@AfterClass
public static void tearDown() {
// Close the browser
driver.quit();
}
@Test
public void testDynamicTable() throws InterruptedException {
String salary = "0";
List<WebElement> totalRows = driver.findElements(By
.xpath("//table[@name='salaryTable']/tbody/tr"));
for (int row = 1; row <= totalRows.size(); row++) {
// Fetch the text of first column (name)
String name = driver.findElement(By.xpath("//table[@name='salaryTable']/tbody/tr["+row+"]/td[1]")).getText();
// If name matches gaurang fetch the text of third column (salary)
if (name.equalsIgnoreCase("gaurang")) {
salary = driver.findElement(By.xpath("//table[@name='salaryTable']/tbody/tr["+row+"]/td[3]")).getText();
}
}
System.out.println(salary);
assertEquals("Verify Salary", "45000", salary);
}
}
</pre>
<br /></div>Anonymoushttp://www.blogger.com/profile/08771276997741729373noreply@blogger.com2