Monday, December 21, 2015

Xpath

Note:
- xpath("") --- location paths should be in double quotes
- xpath("//node[@attribute='xcvv']") --- every attribute declaration should be inside [] and value of attribute should be in single quote.

Regular Expression in Xpath??


  • We can join two conditions using and
          xpath = //<tag name>[@<attribute name>='<value>'  and @value='1']

  • Use Higlight, adjacent to Xpath section in inspect by Firepath window, when you click Highlight it will show the web element that xpath is refering too. That way you can validate the xpath, whether its pointing out to the proper web element. Dont forget to enter xpath in the field.
  • Regular Expression in xpath:
           xpath = //<tag name>[starts-with(@<attribute name>,'<value>')]

           Following could be used:
           ends-with
           contains


12/21/2015

Source: http://www.w3.org/TR/xpath/

Here are some examples of location paths using abbreviated syntax:
  • para selects the para element children of the context node
  • * selects all element children of the context node
  • text() selects all text node children of the context node
  • @name selects the name attribute of the context node
  • @* selects all the attributes of the context node
  • para[1] selects the first para child of the context node
  • para[last()] selects the last para child of the context node
  • */para selects all para grandchildren of the context node
  • /doc/chapter[5]/section[2] selects the second section of the fifth chapter of the doc
  • chapter//para selects the para element descendants of the chapter element children of the context node
  • //para selects all the para descendants of the document root and thus selects all para elements in the same document as the context node
  • //olist/item selects all the item elements in the same document as the context node that have an olist parent
  • . selects the context node
  • .//para selects the para element descendants of the context node
  • .. selects the parent of the context node
  • ../@lang selects the lang attribute of the parent of the context node
  • para[@type="warning"] selects all para children of the context node that have a type attribute with value warning
  • para[@type="warning"][5] selects the fifth para child of the context node that has a type attribute with value warning
  • para[5][@type="warning"] selects the fifth para child of the context node if that child has a type attribute with value warning
  • chapter[title="Introduction"] selects the chapter children of the context node that have one or more title children with string-value equal to Introduction
  • chapter[title] selects the chapter children of the context node that have one or more title children
  • employee[@secretary and @assistant] selects all the employee children of the context node that have both a secretary attribute and an assistant attribute
The most important abbreviation is that child:: can be omitted from a location step. In effect, child is the default axis. For example, a location path div/para is short for child::div/child::para.
There is also an abbreviation for attributes: attribute:: can be abbreviated to @. For example, a location path para[@type="warning"] is short for child::para[attribute::type="warning"] and so selects para children with a type attribute with value equal towarning.
// is short for /descendant-or-self::node()/. For example, //para is short for /descendant-or-self::node()/child::para and so will select any para element in the document (even a para element that is a document element will be selected by //para since the document element node is a child of the root node); div//para is short for div/descendant-or-self::node()/child::para and so will select all para descendants of div children.
NOTE: The location path //para[1] does not mean the same as the location path /descendant::para[1]. The latter selects the first descendant para element; the former selects all descendant para elements that are the first para children of their parents.
A location step of . is short for self::node(). This is particularly useful in conjunction with //. For example, the location path .//para is short for
self::node()/descendant-or-self::node()/child::para
and so will select all para descendant elements of the context node.
Similarly, a location step of .. is short for parent::node(). For example, ../title is short for parent::node()/child::title and so will select the title children of the parent of the context node.


More examples are covered in the following website

http://hedleyproctor.com/2011/05/tutorial-writing-xpath-selectors-for-selenium-tests/
There are a number of ways to write and test an XPath expression:
  1. Using the Selenium IDE itself – it has a “test” option.
  2. Using Firebug and a separate XPath tester.
  3. Using Firebug and the FirePath tester, which is a separate add-on but integrates with Firebug.

Other websites:

http://zvon.org/comp/r/ref-XPath_1.html


3/2/2016:

Ways of Validating Xpath:

xpath could be validated or written on own to find web objects in web pages. And process of writing and finding xpath is possible in many ways, for an example in

My Experience:

Chrome 
- One could write the xpath by following below process

F12->ctrl+F-> Enter xpath in the field opened.

- To generate xpath, you could go to element, right click on it -> Inspect -> Go to the inspect code and Right click -> Copy the xpath.

You could use this process, when ever you are working on finding element in a web page.

FireFox:

Firebug and Firepath  are the two addins that would help you to validate your xpath.

Source:
http://stackoverflow.com/questions/22571267/how-to-verify-an-xpath-expression-in-chrome-developers-tool-or-firefoxs-firebug


1. Chrome

This can be achieved by three different approaches (see my blog article here for more details):
  • Search in Elements panel
  • Execute $x() and $$() in Console panel, as shown in Lawrence's answer
  • Third party extensions (not necessary)
Here is how you search XPath in Elements panel:
  1. Press F12 to open Chrome Developer Tool
  2. In "Elements" panel, press Ctrl+F
  3. In the search box, type in XPath or CSS Selector, if elements are found, they will be highlighted in yellow.
enter image description here

2. Firefox

  1. Install Firebug
  2. Install Firepath
  3. Press F12 to open Firebug
  4. Switch to FirePath panel
  5. In dropdown, select XPathor CSS
  6. Type in to locate
enter image description here

3. Chrome and Firefox

You can open a Console in Chrome, and check the XPath by typing $x("your_xpath_here"). This will return an array of matched values. If it is empty, you know there is no match on the page.

enter image description here

Monday, September 21, 2015

Unknown questions in Selenium


Source: http://www.brainmeasures.com/e_notes_and_certification.aspx

- Finding an element ending with specific letter, how do you write the xpath or regular exp in selenium??

Try: Use of Contains method: 
xpath("//<nearest tag name>@contains(<attribute>,"text"))



- What is Selenium 2

- Selenium has an ____________ that allows us to fire the event that is attached to elements on a page.

- The Default Selenium object takes _________parameters in its constructor.

- The command runs the snippet within the Selenium object.
http://www.seleniumwiki.com/selenium-rc/example-of-store-storeeval-and-geteval-in-selenium/

- To initialize the Selenium object how many parameters it will take

- What is the annotation we put above our setUp() to make sure we pass in the browser?


- If you wanted to validate that a button, which has appeared, is on a page, what two commands would be the best to use?

a) Verify Text Present/assert Text Present
b) Verify Element Present/assert Element Present
c) Verify Alert Present/assert Alert Present
d) Verify Alert/assert Alert

- What is the node inside the node that allows us to specify the browser?

a) Limit
b) Bound
c) Constraint
d) Parameter

- ________Finds the item ending with the value passed in. This is the equivalent to the X Path ends-with.

a) &=
b) *=
c) ^=
d) $=

-
Are you still required to use Browserbot in your JavaScript?

- Selenium cannot always type into --------------------------------- areas.
a) Content Editable
b) Content Erasable
c) Content Writable
d) None of the above

- When we wanted to find if there was text with Cap on the page, we put a _______ at the start and end of the pattern.

a) #
b) /
c) *
d) &


- Selenium and are being merged to create the new Selenium 2 code framework.

a) remoteWebDriver
b) webtesting
c) webDrives
d) webDriver


- What is the desktop viewing application Castro relies on?

a) VCG
b) VRC
c) VNC
d) VNG

- _______________ are used extensively throughout Selenium as the default pattern matching technique.

a) Globbing
b) Expressions
c) Globs
d) Characters

- What is the name of the library we used to record video?

a) Citrine
b) Castro
c) Castrate
d) None of the above


- To find an element by ID in a CSS selector, we need to place a _____________ in front of the ID of the element in the CSS selector.

a) !
b) #
c) $
d) *


- __________________is a way to wrap up the Window object within Selenium that Firefox adds and only allows access to very basic DOM calls.

a) XPC Native Wrapped
b) XPC Native Wrapper
c) XPM Nate Wrap
d) XPN Nate Wrap


- What class do we need to extend when writing JUnit 3 style tests?

a) Selenium Test Case
b) Selenese Test Case
c) Seleneum Test Care
d) Selenium IDE tests


- Which command is used to get the string?

a) StoreVariable command
b) StoreData command
c) StoreText command
d) StoreRecord command


- Selenium and are being merged to create the new Selenium 2 code framework.

a) remoteWebDriver
b) webtesting
c) webDrives
d) webDriver


- How do you start the browser?

a) Call the execute() function
b) Call the run() function
c) Call the proceed() function
d) Call the start() function


- The_________ node in the TestNG configuration file also stores which test classes these parameters are going to be used in.

a) <test>
b) <check>
c) <analysis>
d) <trial>


- From which method we can stop the browser?

a) exit () method
b) stop() method
c) pause() method
d) end() method


- How would you get all the cookies that are on the page?

a) acquireCookie()
b) obtainCookie()
c) getCookie()
d) catchCookie()


- The one window will hold the_____________ with the Test Suite on the left-hand side.

a) Selenium Code Framework
b) Selenium Core Framework
c) Selenium Framework
d) Selenium Core


- ____________ file that contains all the configurations that Selenium grid has.

a) YACL
b) YANL
c) YAML
d) YAPL


- How many Mechanisms are for validating elements that are available on the application under test?

a) 3
b) 4
c) 2
d) 5


-
If we want to access the DOM in your test without using a specific Selenium command, you will need to access it through this special object. This object is called __________?

a) DOM access
b) browser access
c) browserboat
d) browserbot


- How do you store variables to be used later in the test?

a) Use the storedVars dictionary
b) Create a new variable that has global scope
c) You cannot store variables using user extensions
d) You can store variables using user extensions

- How do you specify the port the Remote Control is running on?

a) Dport=portSeries
b) Dport=portNumber
c) Dport=port
d) Dport=portCount

- What is the command required to start the Hub?

a) ant launch-network
b) ant launch –hub
c) ant launch-caption
d) None of the above

Handling Cookies

Selenium 1 vs Selenium 2


Friday, August 21, 2015

TestNG - Notes and Support

Detailed info:

http://testng.org/doc/documentation-main.html



Presention that makes you understand TestNG better and differentiates from Junit:

source: http://kaczanowscy.pl/tomek/sites/default/files/testng_vs_junit.txt.slidy_.html#(24)

 Why TestNG?
My (biased) observations
People are moving from JUnit to TestNG once they start to write integration and end-to-end tests (e.g. with Selenium). Apparently, on unit tests level you can put up with JUnit deficiencies, but once you go outside the unit tests realm, JUnit stands in your way.
From what I have noticed, people who work with JUnit usually test their code with only one set of parameters. I suspect this is because parametrized tests are unusable with JUnit. And this is bad, because such tests are really useful.
If you really, really have to use JUnit (do you?) then at least us JUnit Params!
Parametrized tests
Parametrized tests
@DataProvider
private static final Object[][] getMoney(){
    return new Object[][] {
        {new Money(4, "USD"), new Money(3, "USD"), 7},
        {new Money(1, "EUR"), new Money(4, "EUR"), 5},
        {new Money(1234, "CHF"), new Money(234, "CHF"), 1468}};
}

@Test(dataProvider = "getMoney")
public void shouldAddSameCurrencies(Money a, Money b,
        int expectedResult) {
    Money result = a.add(b);
    assertEquals(result.getAmount(), expectedResult);
}
Parametrized tests
@DataProvider
private static final Object[][] getMoney(){
    return new Object[][] {
        {new Money(4, "USD"), new Money(3, "USD"), 7},
        {new Money(1, "EUR"), new Money(4, "EUR"), 5},
        {new Money(1234, "CHF"), new Money(234, "CHF"), 1468}};
}

@Test(dataProvider = "getMoney")
public void shouldAddSameCurrencies(Money a, Money b,
        int expectedResult) {
    Money result = a.add(b);
    assertEquals(result.getAmount(), expectedResult);
}

@DataProvider
private static final Object[][] getInvalidAmount(){
    return new Integer[][] {{-12387}, {-5}, {-1}};
}

@Test(dataProvider = "getInvalidAmount", expectedExceptions = IllegalArgumentException.class)
public void shouldThrowIAEForInvalidAmount(int invalidAmount) {
    Money money = new Money(invalidAmount, VALID_CURRENCY);
}

@DataProvider
private static final Object[][] getInvalidCurrency(){
    return new String[][] {{null}, {""}};
}

@Test(dataProvider = "getInvalidCurrency", expectedExceptions = IllegalArgumentException.class)
public void shouldThrowIAEForInvalidCurrency(String invalidCurrency) {
    Money money = new Money(VALID_AMOUNT, invalidCurrency);
}
Test Fixture Setting
@Test
public class TestFixtureTest {

    private Server server;
    private Client client;

    @BeforeSuite(timeOut = 1000)
    public void setUpServer() {
        server = new Server();
        server.start();
    }

    @BeforeMethod
    public void setUpClient() { client = new Client(); }

    // some test methods here

    @AfterSuite
    public void shutDownServer() { server.stop(); }
}
Logical dependencies gives you a much more realistic error information - you learn that 1 tests has failed and 99 has been skipped, which is much easier to fix than the information about 100 failed tests (OMG! what’s going on!? All tests failed…. aaarrhghg!).
Dependencies between tests
@Test
public void serverStartedOk() {}

@Test(dependsOnMethods = { "serverStartedOk" })
public void method1() {}
Dependencies between tests
@Test(groups = { "init" })
public void serverStartedOk() {}

@Test(groups = { "init" })
public void initEnvironment() {}

@Test(dependsOnGroups = { "init.* })
public void method1() {}
Listeners, Reporters
OK       FirstTest           fifthTestMethod            1944
OK       FirstTest           firstTestMethod            3799
OK       FirstTest           fourthTestMethod           1920
OK       FirstTest           secondTestMethod           4891
OK       FirstTest           thirdTestMethod            2963
OK       SecondTest          methodA                    3525
OK       SecondTest          methodB                    1390
FAILED   SecondTest          methodC                     117
SKIPPED  SecondTest          methodD                      23
OK       SecondTest          methodE                    4552
There is more of this
Who is the boss?
JUnit
TestNG
releases since 2009 (not counting betas)
3 - from 4.8.2 to 4.10 (see JUnit announcements)
13 - from 5.12 to 6.4 (see TestNG Changelog)
mailing list
JUnit mailing list,
members: 8511
emails since January 2012: ~25
TestNG mailing list,
members: 2858,
emails since January 2012: ~560, threads: 115
While better support for integration and end-to-end tests is definitely true, not many people know that TestNG offers more than JUnit also in case of unit tests.

Concurrency
No need to create own Thread objects! Use annotations and that is it!
An example of running same test method simultaneously (20 times, by 3 threads):
@Test(threadPoolSize = 3, invocationCount = 20)
public void concurrencyTest() {
    System.out.print(" " + Thread.currentThread().getId());
}
Result:
13 12 13 11 12 13 11 12 13 12 11 13 12 11 11 13 12 11 12 13


Parametrized tests
In general, it is a good practice, to test your code with different sets of parameters:
§  expected values: sqrt(4), sqrt(9),
§  boundary values: sqrt(0),
§  strange/unexpected values: sqrt(-1), sqrt(3)
A good testing framework should make it simple, and avoid copy&paste coding.
Alas, the default JUnit implementation of the parametrized tests is rather unusable… In short, JUnit expects all test methods to be parameter-less. Because of this constraint, parametrized tests with JUnit looks awkward, because parameters are passed by constructor and kept as fields!
You can see some examples here, here or here.



Parametrized tests are very simple with TestNG (no constructor awkwardness).
You can have as many data providers in one class as you wish. You can reuse them (call them from other classes), and you can make them "lazy", so each set of parameters is created when required.
Once you migrate to TestNG you will notice that you start writing a lot of parametrized tests. Because they are so very useful!


Ok, so this is how it looks with TestNG. There is a test method (shouldAddSameCurrencies()) which has some "testing logic" and a data provider method (getMoney()) which provides data. That is all.





Parametrized tests
You also get a very detailed information about the test results (in this case thanks to reasonable implementation of Money class toString() method), e.g.:

BTW. not sure if you noticed, but parametrized tests are perfect for verifying if all your "utils" methods work - you know, all this date/strings/numbers handling/transforming methods.


TestNG does not care how many parametrized tests you have in one class. See below for an example ofMoneyTest which verifies both the constructor and add() method using data providers.


TestNG offers well-thought @Before… and @After… annotations (on suite, class, group and method level).
An example below shows that a server (something heavy) is created only once before a test suite, and client (something small and cheap to create) is created before each test method.


Parameters passing
Want to:
§  configure your tests so they e.g. invoke GUI methods on different servers/ports?
§  run tests using mysql database instead of h2?
§  run GUI tests with Opera, Firefox, Chrome (or even IE 6)?
It is pretty simple to pass parameters to test methods (example copied directly from TestNG documentation):
@Parameters({ "datasource", "jdbcDriver" })
@BeforeMethod
public void beforeTest(String ds, String driver) {
    m_dataSource = ...;
    m_jdbcDriver = driver;
}
Parameters can come for example from configured Maven Surefire Plugin


Groups of tests
§  each test class (and method) can belong to multiple groups,
§  it is pretty easy to run only selected group:
·         e.g. you can run only tests from groups "smoke", or only "gui" tests,
·         it is possible to define dependencies between methods/groups (see next slide).
§  all done with annotations (e.g. @Test(groups = "smoke"))
This is also supported by tools - e.g. it is pretty simple to instruct Maven to do it (see here).


Dependencies between tests
Rather bad practice with unit tests,
but very important for integration and end-to-end tests, e.g.:
§  fail fast:
·         run Selenium tests only if application was deployed properly,
·         run full system tests only if smoke tests passed,
§  logical dependencies between tests:
·         execute shouldDeleteUserFromDatabase test only if shouldAddUserToDatabaseworked
Fail fast means that the feedback will be much quicker in case of failed tests.


Example copied from TestNG documentation.
Method method1 will be skipped (will not run) if serverStartedOk fails.


Example copied from TestNG documentation.
Method method1 will be skipped (will not run) if any method of group init fails.



It is pretty easy to write your own listeners (which act in runtime) and reporters (which are invoked after the execution).
Example output of listener which prints test result, class and method name, and execution time of each test method:
This feature is not very useful with unit-tests but can be very handy to report progress/results of integration and end-to-end tests.



There are few more interesting features of TestNG (e.g. factories) but lets skip it.




(chart from Google trends)
Well, as you can see TestNG is not really closing the gap. It rather seems to find its niche and sit there. Well, it is time to change it! :)



But who is the boss now?
All data gathered on 4th April 2012.
One could say, this all means only that JUnit development has been finished, all documentation has been written, all questions answered and easy to find by googling, all issues solved, … well, actually no. It rather looks, hm… a little bit abandonned.


Documentation
§  TestNG offers much better documentation
·         even though there are numerous articles about different versions and features of JUnit you will find it hard to find a comprehensive resource on the net which explains it thoroughly.
·         TestNG documentation is in very good shape, and always up-to date (seriously, it is!)


Have no fear
Yes, with TestNG you still can:
§  run tests with Maven, Ant, Gradle, …
§  execute tests with your IDE: Eclipse, IntelliJ IDEA, …
§  enjoy Spring support for testing,
§  etc., etc.



How to migrate from JUnit to TestNG?
§  There is Eclipse converter which does a decent job of changing imports etc. so you do not have to do it by hand
§  TestNG plugin for IntelliJ IDEA also provides a "Convert JUnit test to TestNG" feature
§  There might be an issue with objects creation, because TestNG does not create test classes before every test
·         This means you need to enclose creation of objects within some method.
§  Another - minor - issue is with assertions, because TestNG uses different order of arguments (first actual, then expected) than JUnit (first expected, then actual)
·         If you use matcher libraries, you do not have to change anything



The End
Great things are done by a series of small things brought together.
— Vincent Van Gogh
It is many small things which sum up and give you a much better experience.
TestNG offers support for all kind of tests. It is great, and still getting better with each new release.
…is TestNG a silver bullet? No, but close to it. :)
P.S. Want to know more about TestNG? Read the book.




List of Annotations:

@Beforesuite
You can set driver paths (System.setProperty(...)) in@BeforeSuite method. 
@BeforeMethod
Instantiate browser in @BeforeMethod.