Config.yaml
Config.yaml file has all the configurations defined in it like environment variables, locators, paths, etc.
These variables and locators will be fetched/accessed by the test scripts. You just need to supply the location/path of the config.yaml file to the method/function which reads this file and gets the data.

# config.yaml file# ********************Environment variables************************
Environment_variables :
  OS: 'macOS Catalina'  OS_version: 'Version 10.15.3'
  project_path: '/Users/pravin.a/my-project/venv/MyFramework'  Driver_pth: '/usr/local/bin'
browsers:
  - Chrome
  - Firefox
  - Ie
  - Safari

urls: {
  practice_url: 'https://learn.letskodeit.com/p/practice',
  login_url: 'https://letskodeit.teachable.com/'}

credentials: {
  username: pravin.alhat7@gmail.com,
  password: Prayag@77,
  invalid_username: test@email.com,
  invalid_password: abcabc
}
#*****************************************Login Page/ Login Test Class Locators*************************
locators: {
  login_link: Login,
  email_field: "//input[@id='user_email']",
  password_field: "//input[@id='user_password']",
  login_button: "commit"}

#*****************************************Login Page/ Login Test Class Locators*************************


There is a method created to read the data from this config.yaml file and it will return a required data.
class HandyUtilities():
CONFIG_PATH
= '<path where config.yaml file is located>'
def read_yaml(self, key, data):
    list_items = []
    with open(self.CONFIG_PATH) as file:
        list_items = yaml.load(file, Loader=yaml.Loader)
        try:
            for k, v in list_items.items():
                if k == key:
                    valt = list_items[key]
                    if type(valt) is dict:
                        for k, v in valt.items():
                            if k == data:
                                val = valt[data]
                                return val
                    elif type(valt) is list:
                        if data in valt:
                            print("data '{}' is found in config file".format(data))
                            return data
                        else:
                            raise Exception("data '{}' is not available in config file".format(data))
                else:
                    print("<Incorrect key>")
                    sys.exit()
        except:
            print(
                "Something is invalid in key/value pair '{}: {}' as this type of data is not supported by config  file".format(
                    key, data))
            return ('<Incorrect data found>')
Logs
In a framework it is required to capture the logs of all the activities which will be referred while troubleshooting any issue.
Custime logger method shown below is derived with the help of logging module which is in-built in pyhton.
import logging
import logging.config
import inspect
from datetime import datetime

def customlogger(loglevel=logging.DEBUG):
    # To get the name of the class/method from where this method is called.    now = datetime.now()
    loggerName = inspect.stack()[1][3]
    logger = logging.getLogger(loggerName)

    # Print all log message    logger.setLevel(logging.DEBUG)

    fileHandler = logging.FileHandler('{0}'.format(loggerName)+'_'+str(now.strftime("%Y%m%d%H%M%S %p")) +
                       '.log', mode='w')
    fileHandler.setLevel(loglevel)

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s',
                    datefmt='%m/%d/%Y %I:%M:%S %p')

    fileHandler.setFormatter(formatter)

    logger.addHandler(fileHandler)

    return logger

This customer logger method returns a logger which is used to print a log. Object will be created of this method and logs will be printed as shown below



log = customlogger(loglevel=logging.DEBUG)
log.info("Message")
log.error("Message")
log.warn("Message")

Running tests
'pytest' and 'unittest' frameworks are used to make framework more efficient and effective. Run the test scripts using pytest and generate html report. 
(venv) pravin-a:SampleProject pravin.a$ pytest --html=Result.html
pytest run
pytest will look for all the scripts that start with 'test' keyword and execute it. As shown above, it will give you the details like what all tests are run and their status.
The HTML report is generated at the current directory location.
Log files
logs will be generated by the framework and it will be stored in the files created by custom logger method.

Running tests in TestSuite
'Unittest' framework of Python provides great features and methods to collect multiple test methods/cases from different-different test classes and bundle them together in a test suite.

import unittest
from tests.login.test_login import LoginTests

# Pull the test cases/methods from the test class

Login_TCs = unittest.TestLoader().loadTestsFromTestCase(LoginTests)

# Create a test suite and add the pulled test cases to it

smoke_suite = unittest.TestSuite(Login_TCs)

#Run the test suite

unittest.TextTestRunner(verbosity=2).run(smoke_suite)

Comments

Popular Posts

Image