Friday, October 3, 2014

Alternative to Setup and TearDown - Python Decorators

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.

So, I came up with solution, I wrote down two decorators, one for UI test cases and one for backend test cases.

Following is the code.

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

How to use this decorator


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()