Python OOP – Splitting a Single Class into Multiple Classes

classobject-orientedpythonselenium

I am writing automated test scripts with Selenium Webdriver (Python) and I try to follow the correct programming practices, specifically the Object Oriented methodologies, where possible.

At the moment, I represent every test scenario as a single Class. That class is basically has the following structure:

  1. Imports (Selenium modules as well as Python stuff)
  2. Logging configuration
  3. Class definition that includes the below:
    • Driver Instance initialization
    • Specific test scenario variables
    • Generic methods (some wrappers I created that are used in multiple testing scenarios)
    • Specific application methods

So that's something like that:

imports
logging

class AppName(object):
    def __init__(self):
        self.driver = webdriver.Chrome()

        self.localAppVar = "..."
        ...

    def genericFunction(self):
        #This is a generic function that is going to be used in many other test scenarios as well as in this one

    def specificAppFunction(self):
        #This is a specific application function. This function is only relevant withing this test. This function will use "genericFunction" internally.

app = AppName() #Initialize an AppName object
app.specificAppFunction()

...

What I would like to do is to separate the above Class into 2 new Classes and a launcher file:

  1. Generic functions Class. This one will define the driver object as well as all generic functions that are going to be used by multiple tests.

  2. Specific functions Class. This one will contain the application specific function that are irrelevant for other applications.

  3. Launcher file that will initialize\instantiate the above mentioned classes and will control the scenario on a higher level. (kind of main in C if you like).

The above idea makes sense to me but I am a bit confused about the practical approach. How should that be implemented properly?

I was thinking about following options:

  1. Creating a generic class instance withing a specific application class.
  2. Make the generic class a base class and then inherit it by specific application class.

I am not sure about pros and cons of both approaches and currently a bit stuck with the implementation. It will be great if someone could give me some insight on how such task should be implemented.

Hopefully my question is clear enough. If it's not, please comment and I will elaborate or/and edit.

Best Answer

Generic functions should not go into classes. Python is not Java, it does not require pure functions to live inside classes. Only use classes if you want to store state of some kind. Put the functions into a standalone utility module, and import that into the module that contains your test classes.