Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I see log messages when unit testing in PyCharm?

Tags:

python

pycharm

I'm sure this is a simple fix, but I'd like to view log messages in the PyCharm console while running a unit test. The modules I'm testing have their own loggers, and normally I'd set a root logger to catch the debugging messages at a certain level, and pipe the other logs to a file. But I can't figure out how this works with unit tests.

I'm using the unittest2 module, and using PyCharm's automatic test discovery (which probably is based on nose, but I don't know).

I've tried fooling with the run configurations, but there doesn't seem to be a straightforward way to do this.

The PyCharm documentation isn't particularly helpful here either, if any of you work there.


In edit: It DOES appear that the console catches critical level log messages. I want to know if there is a way to configure this to catch debug level messages.


This post (Pycharm unit test interactive debug command line doesn't work) suggests adding the -s option to the build configuration, which does not produce the desired result.

like image 395
BenDundee Avatar asked Jun 28 '14 19:06

BenDundee


4 Answers

The only solution I've found is to do the normal logging setup at the top of the file with tests in it (assuming you're just running one test or test class): logging.basicConfig(level=logging.DEBUG). Make sure you put that before most import statements or the default logging for those modules will have already been set (that was a hard one to figure out!).

like image 55
Pat Avatar answered Oct 14 '22 15:10

Pat


I needed to add too the option --nologcapture to nosetests as param in pycharm 2016.3.2

Run>Edit COnfigurations > Defaults > Python Tests > Nosetests : activate the check for Prams option and add --nologcapture

like image 28
bott Avatar answered Oct 14 '22 15:10

bott


In Edit Configurations:

  • delete old configurations
  • go to Defaults / Python tests / NoseTests
  • add --nologcapture to "additional Arguments"

worked like a "charm" for me in pyCharm 2017.2.3

thanks bott

like image 2
gturbo Avatar answered Oct 14 '22 15:10

gturbo


My problem was similar, I only saw messages with level WARNING or higher while running tests in PyCharm. A colleague suggested to configure the logger in __init__.py which is in the directory of my tests.

# in tests/__init__.py
import logging
import sys

# Reconfiguring the logger here will also affect test running in the PyCharm IDE
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(message)s'
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format=log_format)

Then I can simply log in the test code like:

import logging
logging.info('whatever')
like image 1
Attila123 Avatar answered Oct 14 '22 15:10

Attila123