I am running tests using python, selenium and pytest framework with page object models.
As of now, I have created a logger function in my BaseClass, and every test class inherits this function.,
So, in a test case, if I want to log something, I have to create a log object using below code in each test case, and then call methods on log. I am trying to abstract away this object creation step from each and every test case.
Reproducible Test case as follows:
from baseclass import BaseClass class test_module(BaseClass): def test_case1(self): log = self.logger() log.info('testing log!')
I tried to abstract the logger function into my conftest.py in setup function, calling the method and creating an object, and then returning this logger object using request.cls, but when I run the logs, I get the file name as setup instead of the test case name.
2021-01-27 05:42:42,377 : INFO : setup : testing log!
My conftest.py is setup as follows:
import pytest from selenium import webdriver import inspect import logging def logger(): name = inspect.stack()[1][3] log_item = logging.getLogger(name) with open('LogFile.log', 'w+') as logFile: logFile.seek(0) logFile.truncate() file_handler = logging.FileHandler("LogFile.log") log_format = logging.Formatter("%(asctime)s : %(levelname)s : %(name)s : %(message)s") file_handler.setFormatter(log_format) log_item.addHandler(file_handler) log_item.setLevel(logging.DEBUG) return log_item @pytest.fixture(scope='class') def setup(request): driver = webdriver.Chrome(executable_path=TestData.CHROME) log = logger() request.cls.driver = driver request.cls.log = log yield driver.close()
I actually want to get the name of the test being performed. Like below:
2021-01-27 01:57:02,594 : INFO : test_case1 : testing log!
How can I get the logger method to print the name of the test case without moving the method back to BaseClass? Or, how can I best abstract away the object creation step from each test case? I am about to write a lot of test cases, and trying to find a better way as it's repetitive to create a logger object in each test case.
My BaseClass is as below:
import pytest @pytest.mark.usefixtures('setup') class BaseClass: """ Base class for all Test classes This class creates the necessary variables that a Test objects needs to work, and so, it must be inherited by all of them. """ pass
https://stackoverflow.com/questions/65911522/how-to-get-name-of-test-case-instead-of-conftest-py-method-in-each-log January 27, 2021 at 09:07AM
没有评论:
发表评论