Reputation: 5061
I am using pytest for running my test methods. And i am trying to implement a log file for each test method.
consider the following test module with test methods.
#content of test_module.py
def test_1(log):
log.info('inside test_1')
util.abc(log)
def test_2(log):
log.info('inside test_2')
util.abc(log)
The content of my util module is:
#content of util.py module
def abc(log):
# perform some logic here and calculate result.
log.info('the value is: %s' % result)
And here is my conftest.py file.
#conftest.py
@pytest.fixture()
def log(request):
test_path = request.node.parent.name.strip(".py")
test_name = request.node.name
node_id = request.node.nodeid
logs_dir = pkg_resources.resource_filename("test_results", "logs")
log_file_path = '%s/%s' % (logs_dir, test_path)
if not os.path.exists(log_file_path):
os.makedirs(log_file_path)
logger_obj = logger.make_logger(test_name, log_file_path, node_id)
yield logger_obj
handlers = logger_obj.handlers
for handler in handlers:
handler.close()
logger_obj.removeHandler(handler)
The test module test_module.py is located under tests/ directory. So, when i run the tests using py.test tests/ it executes the test_1 and test_2 methods and logs the test specific info under test_results/ directory into a log file specific to each test. test_1.log and test_2.log.
This works for me. But, the problem is that i had to pass log object from the test methods to each method that i call from the test method.
In this example when i am calling the util.abc method i am passing the log object from the test method. So, the method abc inside the util module knows which log file to log to. But, i don't want to pass in the log object this way to all the methods that i call from test methods. I believe there should be a better way. I am thinking, if there is a way to find out which test method called the method abc then i don't have to pass in the log object this way. Anyone knows on how to figure this out? or any other ideas to achieve this? Thank you!
Upvotes: 0
Views: 1140
Reputation: 3092
Well, you can always create logger
module. In your test methods, you will assign log
to logger.log
#content of test_module.py
def test_1(log):
logger.log = log
log.info('inside test_1')
util.abc()
def test_2(log):
logger.log = log
log.info('inside test_2')
util.abc()
and in your normal methods just call it
def abc():
# perform some logic here and calculate result.
logger.log.info('the value is: %s' % result)
Upvotes: 1