Monday, February 23, 2015

While writing functional test cases using selenium tearDown() method is one of the greatest functionality/place to do all cleanup actions. This method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state. Any exception raised by this method will be considered an error rather than a test failure. This method will only be called if the setUp() succeeds, regardless of the outcome of the test method. The default implementation does nothing. 

So instead of adding screenshots functionality in each test cases, we can add this functionality in tearDown method as follows:

def tearDown(self):
        if sys.exc_info()[0]:
            test_method_name = self._testMethodName
            now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
            self.driver.save_screenshot(os.getcwd() +'/screenshots/' + test_method_name + "-" + now + ".png")
--

Make sure to import following packages for above code.

from selenium import webdriver
from datetime import datetime
import os 



When we click on a link which open a new window, getting focus at currently opened windows is not straightforward in selenium. The main issue with it is that the new window may or may not have a WINDOWNAME that can be used by the webdriver function switch_to_window(WINDOWNAME).

 If the new window has been opened by a code snippet such as,

<a href="http://www.qanepal.com/" target="_blank">Subscribe</a>

then the name is randomly assigned, and you’ll need to use code as shown below to find it’s name.

current_windows = self.driver.window_handles

# This is the code which open new windows.
self.driver.find_element_by_link_text("Subscribe").click()

new_windows = self.driver.window_handles
new_window = list(set(new_windows) - set(current_windows))[0]
self.driver.switch_to_window(new_window)


If you can modify the source html or influence the developers to do so, it would be nice to have a proper name assigned to the new window. This can be done by using a named target; eg:

<a href="http://some-link/" target="mytarget">some link</a>

Now, when the new window is opened, you can use it’s name explicitly in code, such as

driver.switch_to_window('mytarget')

Categories

.
Powered by Blogger.

Popular Posts

Like Us