Search code examples
pythonseleniumselenium-webdriverpytestpytest-html

Python Selenium run multiple test classes in one selenium webdriver using with pytest


I am new in python and I started to create an automation test suite about a GUI(multiple test cases in different file). I want to execute all my test cases in one selenium webdriver, so I created a singleton webdriver class and I want to use this class all my test cases. Here is my singleton webdriver class:

from selenium import webdriver


class Webdriver(object):
    """
    Singleton class based on overriding the __new__ method
    """

    def __new__(cls):
        """
        Override __new__ method to control the obj. creation
        :return: Singleton obj.
        """
        if not hasattr(cls, 'instance'):
            cls.instance = super(Webdriver, cls).__new__(cls)

        return cls.instance

    @staticmethod
    def get_driver():
        """
        :return: Selenium driver
        """
        dir = "C:\\Python36\\Lib\\site-packages\\selenium\\webdriver\\ie"
        ie_driver_path = dir + "\\IEDriverServer.exe"
        return webdriver.Ie(ie_driver_path)

and my setUp example:

from Core.Webdriver import Webdriver

class LoginExternal(unittest.TestCase):

    def setUp(self):
        # Create Instances
        self.web = Webdriver.get_driver()
        self.matcher = TemplateMatcher()
        self.gif = GifCapture("C:\\wifi\\Videos\\" + self._testMethodName + ".gif")
        self.gif.start()
        time.sleep(3)

     def test_LoginExternal(self):
         # Open External Login Page
         self.web.maximize_window()

Here is my problem, when I execute my test suite, my code create a new selenium instance but I want only one selenium instance to be used in all test cases.

I use pytest as a test runner with following cmd command:

pytest --pyargs --html=Report/External_04052018.html ExternalTestSuite/

I think the problem is pytest use a new proccess in every test case execution. Is there any way to prevent or use like this way?


Solution

  • Pytest greatest feature and advantage over traditional XUnit family test runners is that it has fixtures. I invite you to use it. In your scenario, I would get rid of extending unittest.TestCase and setUp method in favor of pytest fixture as follows:

    import pytest
    
    from Core.Webdriver import Webdriver
    
    
    class TestLoginExternal:
    
        @pytest.fixture(scope='class')
        def driver(self):
            print('Setup runs once before all tests in class')
            driver = Webdriver.get_driver()
            yield driver
            driver.quit()
            print('Teardown runs once after all tests in class')
    
        def test_LoginExternal(self, driver):
            # Open External Login Page
            print('test_LoginExternal')
    
        def test_LoginInternal(self, driver):
            # Open External Login Page
            print('test_LoginInternal')