Python 2.7 Unittest check if warning is logged [duplicate]Python 2.7 Unit test: Assert logger warning thrownHow do I check if a list is empty?How do I check whether a file exists without exceptions?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?Check if a given key already exists in a dictionaryDoes Python have a string 'contains' substring method?
What can we do about our 9-month-old putting fingers down his throat?
If every star in the universe except the Sun were destroyed, would we die?
Get a MPS file using NEOS/GAMS web interface
"syntax error near unexpected token" after editing .bashrc
Python reimplementation of Lost In Space by Tim Hartnell
How to best explain that you are taking pictures in a space for practice reasons?
Are fast interviews red flags?
How do draw effects during the discard phase work?
Dissuading my girlfriend from a scam
Let A,B,C be sets. If A△B=A△C, does this imply that B=C?
Infinitely many primes
At what point does a land become controlled?
What is the "Brake to Exit" feature on the Boeing 777X?
Filling attribute tables with values from the same attribute table
Does the word voltage exist in academic engineering?
Do aarakocra have arms as well as wings?
Contractor cut joist hangers to make them fit
Why do the Brexit opposition parties not want a new election?
Compiler optimization of bitwise not operation
Examples where "thin + thin = nice and thick"
What makes an ending "happy"?
Short story: Interstellar inspector senses "off" nature of planet hiding aggressive culture
Why did Tony's Arc Reactor do this?
What is the purpose of the rotating plate in front of the lock?
Python 2.7 Unittest check if warning is logged [duplicate]
Python 2.7 Unit test: Assert logger warning thrownHow do I check if a list is empty?How do I check whether a file exists without exceptions?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?Check if a given key already exists in a dictionaryDoes Python have a string 'contains' substring method?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
This question already has an answer here:
Python 2.7 Unit test: Assert logger warning thrown
2 answers
I am trying to write a unit-test for my module that is written in Python 2.7, I can't migrate to 3.x right now. What i want is for this test do is to check if my module generates an warning logs, if it does then capture it. I couldn't find an answer for Python 2.7 from my searching the web and stack-overflow. i have included a simple testable code that you could use to try things out or understand my question better.
UPDATE:
Just to clarify i am willing to change my test case i.e test_warning_2
to be able to catch log.warn
current implementation of that method is just a place holder.
import logging
import warnings
from unittest import TestCase
def generate_warning_2():
logging.warn("this is a warning")
def generate_warning_1():
warnings.warn("this is a warning")
class TestWarning(TestCase):
def test_warning_1(self):
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_1()
self.assertEquals(len(w), 1)
def test_warning_2(self):
# Below code is just a place holder, i need some code to replace this so that i can catch `log.warn`
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_2()
self.assertEquals(len(w), 1)
Here if you see function generate_warning_2
you will notice i am using conventional python logging warning that is not captured by my test case. I know the reason is because it doesn't use warnings
module. I just wanted to show what i want it to do.
The other function generate_warning_1
i use warnings
module to capture warning log, this is my current implementation that works fine.
I would like to be able to catch log.warn
instead of having to use warning
to achieve this. Is this possible in Python 2.7? Please don't provide answers for Python 3.x, as i already know its possible there.
Hope my question is clear, please feel free to ask me questions or edit where appropriate. Any help here is appreciated.
python python-2.7 python-unittest python-logging
marked as duplicate by Martijn Pieters♦
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Apr 3 at 11:51
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
|
show 1 more comment
This question already has an answer here:
Python 2.7 Unit test: Assert logger warning thrown
2 answers
I am trying to write a unit-test for my module that is written in Python 2.7, I can't migrate to 3.x right now. What i want is for this test do is to check if my module generates an warning logs, if it does then capture it. I couldn't find an answer for Python 2.7 from my searching the web and stack-overflow. i have included a simple testable code that you could use to try things out or understand my question better.
UPDATE:
Just to clarify i am willing to change my test case i.e test_warning_2
to be able to catch log.warn
current implementation of that method is just a place holder.
import logging
import warnings
from unittest import TestCase
def generate_warning_2():
logging.warn("this is a warning")
def generate_warning_1():
warnings.warn("this is a warning")
class TestWarning(TestCase):
def test_warning_1(self):
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_1()
self.assertEquals(len(w), 1)
def test_warning_2(self):
# Below code is just a place holder, i need some code to replace this so that i can catch `log.warn`
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_2()
self.assertEquals(len(w), 1)
Here if you see function generate_warning_2
you will notice i am using conventional python logging warning that is not captured by my test case. I know the reason is because it doesn't use warnings
module. I just wanted to show what i want it to do.
The other function generate_warning_1
i use warnings
module to capture warning log, this is my current implementation that works fine.
I would like to be able to catch log.warn
instead of having to use warning
to achieve this. Is this possible in Python 2.7? Please don't provide answers for Python 3.x, as i already know its possible there.
Hope my question is clear, please feel free to ask me questions or edit where appropriate. Any help here is appreciated.
python python-2.7 python-unittest python-logging
marked as duplicate by Martijn Pieters♦
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Apr 3 at 11:51
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
"I can't migrate to 3.x right now." Better find time soon. 2.7 is reaching end of life next year.
– jpmc26
Mar 28 at 7:56
Also, don't unit testing logging operations. It is not a valuable use of time.
– jpmc26
Mar 28 at 7:57
i know 2.7 is reaching its end, the decision to not migrate is not mine.
– AJS
Mar 28 at 8:42
You are confusing warnings with logging at loglevel WARN. These are two very different types of things. You are simply looking for testing if your logging code works, andwarnings.catch_warnings()
can't help with that.
– Martijn Pieters♦
Apr 2 at 22:14
1
Right, then see the duplicate post, which covers exactly that scenario.
– Martijn Pieters♦
Apr 3 at 11:51
|
show 1 more comment
This question already has an answer here:
Python 2.7 Unit test: Assert logger warning thrown
2 answers
I am trying to write a unit-test for my module that is written in Python 2.7, I can't migrate to 3.x right now. What i want is for this test do is to check if my module generates an warning logs, if it does then capture it. I couldn't find an answer for Python 2.7 from my searching the web and stack-overflow. i have included a simple testable code that you could use to try things out or understand my question better.
UPDATE:
Just to clarify i am willing to change my test case i.e test_warning_2
to be able to catch log.warn
current implementation of that method is just a place holder.
import logging
import warnings
from unittest import TestCase
def generate_warning_2():
logging.warn("this is a warning")
def generate_warning_1():
warnings.warn("this is a warning")
class TestWarning(TestCase):
def test_warning_1(self):
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_1()
self.assertEquals(len(w), 1)
def test_warning_2(self):
# Below code is just a place holder, i need some code to replace this so that i can catch `log.warn`
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_2()
self.assertEquals(len(w), 1)
Here if you see function generate_warning_2
you will notice i am using conventional python logging warning that is not captured by my test case. I know the reason is because it doesn't use warnings
module. I just wanted to show what i want it to do.
The other function generate_warning_1
i use warnings
module to capture warning log, this is my current implementation that works fine.
I would like to be able to catch log.warn
instead of having to use warning
to achieve this. Is this possible in Python 2.7? Please don't provide answers for Python 3.x, as i already know its possible there.
Hope my question is clear, please feel free to ask me questions or edit where appropriate. Any help here is appreciated.
python python-2.7 python-unittest python-logging
This question already has an answer here:
Python 2.7 Unit test: Assert logger warning thrown
2 answers
I am trying to write a unit-test for my module that is written in Python 2.7, I can't migrate to 3.x right now. What i want is for this test do is to check if my module generates an warning logs, if it does then capture it. I couldn't find an answer for Python 2.7 from my searching the web and stack-overflow. i have included a simple testable code that you could use to try things out or understand my question better.
UPDATE:
Just to clarify i am willing to change my test case i.e test_warning_2
to be able to catch log.warn
current implementation of that method is just a place holder.
import logging
import warnings
from unittest import TestCase
def generate_warning_2():
logging.warn("this is a warning")
def generate_warning_1():
warnings.warn("this is a warning")
class TestWarning(TestCase):
def test_warning_1(self):
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_1()
self.assertEquals(len(w), 1)
def test_warning_2(self):
# Below code is just a place holder, i need some code to replace this so that i can catch `log.warn`
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_2()
self.assertEquals(len(w), 1)
Here if you see function generate_warning_2
you will notice i am using conventional python logging warning that is not captured by my test case. I know the reason is because it doesn't use warnings
module. I just wanted to show what i want it to do.
The other function generate_warning_1
i use warnings
module to capture warning log, this is my current implementation that works fine.
I would like to be able to catch log.warn
instead of having to use warning
to achieve this. Is this possible in Python 2.7? Please don't provide answers for Python 3.x, as i already know its possible there.
Hope my question is clear, please feel free to ask me questions or edit where appropriate. Any help here is appreciated.
This question already has an answer here:
Python 2.7 Unit test: Assert logger warning thrown
2 answers
python python-2.7 python-unittest python-logging
python python-2.7 python-unittest python-logging
edited Apr 3 at 6:10
AJS
asked Mar 28 at 6:13
AJSAJS
1,43110 silver badges20 bronze badges
1,43110 silver badges20 bronze badges
marked as duplicate by Martijn Pieters♦
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Apr 3 at 11:51
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by Martijn Pieters♦
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Apr 3 at 11:51
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by Martijn Pieters♦
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Apr 3 at 11:51
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
"I can't migrate to 3.x right now." Better find time soon. 2.7 is reaching end of life next year.
– jpmc26
Mar 28 at 7:56
Also, don't unit testing logging operations. It is not a valuable use of time.
– jpmc26
Mar 28 at 7:57
i know 2.7 is reaching its end, the decision to not migrate is not mine.
– AJS
Mar 28 at 8:42
You are confusing warnings with logging at loglevel WARN. These are two very different types of things. You are simply looking for testing if your logging code works, andwarnings.catch_warnings()
can't help with that.
– Martijn Pieters♦
Apr 2 at 22:14
1
Right, then see the duplicate post, which covers exactly that scenario.
– Martijn Pieters♦
Apr 3 at 11:51
|
show 1 more comment
"I can't migrate to 3.x right now." Better find time soon. 2.7 is reaching end of life next year.
– jpmc26
Mar 28 at 7:56
Also, don't unit testing logging operations. It is not a valuable use of time.
– jpmc26
Mar 28 at 7:57
i know 2.7 is reaching its end, the decision to not migrate is not mine.
– AJS
Mar 28 at 8:42
You are confusing warnings with logging at loglevel WARN. These are two very different types of things. You are simply looking for testing if your logging code works, andwarnings.catch_warnings()
can't help with that.
– Martijn Pieters♦
Apr 2 at 22:14
1
Right, then see the duplicate post, which covers exactly that scenario.
– Martijn Pieters♦
Apr 3 at 11:51
"I can't migrate to 3.x right now." Better find time soon. 2.7 is reaching end of life next year.
– jpmc26
Mar 28 at 7:56
"I can't migrate to 3.x right now." Better find time soon. 2.7 is reaching end of life next year.
– jpmc26
Mar 28 at 7:56
Also, don't unit testing logging operations. It is not a valuable use of time.
– jpmc26
Mar 28 at 7:57
Also, don't unit testing logging operations. It is not a valuable use of time.
– jpmc26
Mar 28 at 7:57
i know 2.7 is reaching its end, the decision to not migrate is not mine.
– AJS
Mar 28 at 8:42
i know 2.7 is reaching its end, the decision to not migrate is not mine.
– AJS
Mar 28 at 8:42
You are confusing warnings with logging at loglevel WARN. These are two very different types of things. You are simply looking for testing if your logging code works, and
warnings.catch_warnings()
can't help with that.– Martijn Pieters♦
Apr 2 at 22:14
You are confusing warnings with logging at loglevel WARN. These are two very different types of things. You are simply looking for testing if your logging code works, and
warnings.catch_warnings()
can't help with that.– Martijn Pieters♦
Apr 2 at 22:14
1
1
Right, then see the duplicate post, which covers exactly that scenario.
– Martijn Pieters♦
Apr 3 at 11:51
Right, then see the duplicate post, which covers exactly that scenario.
– Martijn Pieters♦
Apr 3 at 11:51
|
show 1 more comment
1 Answer
1
active
oldest
votes
This can be solved using a logger handler. Unfortunately there seems to be no way of setting the handler on the root logger, but only on instances returned by getLogger
. If you can live with that, this should work:
import logging
import warnings
import unittest
class WarningsHandler(logging.Handler):
def handle(self, record):
if record.levelno == logging.WARN:
warnings.warn(record.getMessage())
return record
log = logging.getLogger()
log.addHandler(WarningsHandler())
def generate_warning_2():
log.warn("this is a warning")
def generate_warning_1():
warnings.warn("this is a warning")
class TestWarning(unittest.TestCase):
def test_warning_1(self):
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_1()
self.assertEquals(len(w), 1)
def test_warning_2(self):
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_2()
self.assertEquals(len(w), 1)
if __name__ == "__main__":
unittest.main()
$ python2 so.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
In order to prevent eventual double printing, you might want to make the handler return the LogRecord only conditionally.
Thanks for your answer, had thought about something like this. I want to avoid touching the logging module for now if i can,
– AJS
Apr 1 at 6:29
Then I probably misunderstood the question. You don't want to use thewarnings
module everywhere, but you also do not want to do anything with thelogging
module?
– Hubert Grzeskowiak
Apr 1 at 6:40
Also just to clarify i am willing to change functiontest_warning_2
if there is any other way to capturelog.warn
logging
– AJS
Apr 1 at 6:40
i don't want to change the logging module so that i can catch warning in my test case. I am primary want to catch log.warn in my test case any way possible. even if that mean to change thetest_warning_2
test case that is just a place holder as i don't know any other implementation.
– AJS
Apr 1 at 6:43
1
@AJS just modify the code such that theWarningsHandler
stores the information (e.g. store the message in awarnings
instance variable), and gets instantiated, added and removed by the test case. That way you set up the handler at the start of the test case, run the code, remove the handler, then check the handler's content. Alternatively, switch everything to pytest: it has support for warnings assertions and logging assertions built in.
– Masklinn
Apr 1 at 7:46
|
show 2 more comments
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
This can be solved using a logger handler. Unfortunately there seems to be no way of setting the handler on the root logger, but only on instances returned by getLogger
. If you can live with that, this should work:
import logging
import warnings
import unittest
class WarningsHandler(logging.Handler):
def handle(self, record):
if record.levelno == logging.WARN:
warnings.warn(record.getMessage())
return record
log = logging.getLogger()
log.addHandler(WarningsHandler())
def generate_warning_2():
log.warn("this is a warning")
def generate_warning_1():
warnings.warn("this is a warning")
class TestWarning(unittest.TestCase):
def test_warning_1(self):
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_1()
self.assertEquals(len(w), 1)
def test_warning_2(self):
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_2()
self.assertEquals(len(w), 1)
if __name__ == "__main__":
unittest.main()
$ python2 so.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
In order to prevent eventual double printing, you might want to make the handler return the LogRecord only conditionally.
Thanks for your answer, had thought about something like this. I want to avoid touching the logging module for now if i can,
– AJS
Apr 1 at 6:29
Then I probably misunderstood the question. You don't want to use thewarnings
module everywhere, but you also do not want to do anything with thelogging
module?
– Hubert Grzeskowiak
Apr 1 at 6:40
Also just to clarify i am willing to change functiontest_warning_2
if there is any other way to capturelog.warn
logging
– AJS
Apr 1 at 6:40
i don't want to change the logging module so that i can catch warning in my test case. I am primary want to catch log.warn in my test case any way possible. even if that mean to change thetest_warning_2
test case that is just a place holder as i don't know any other implementation.
– AJS
Apr 1 at 6:43
1
@AJS just modify the code such that theWarningsHandler
stores the information (e.g. store the message in awarnings
instance variable), and gets instantiated, added and removed by the test case. That way you set up the handler at the start of the test case, run the code, remove the handler, then check the handler's content. Alternatively, switch everything to pytest: it has support for warnings assertions and logging assertions built in.
– Masklinn
Apr 1 at 7:46
|
show 2 more comments
This can be solved using a logger handler. Unfortunately there seems to be no way of setting the handler on the root logger, but only on instances returned by getLogger
. If you can live with that, this should work:
import logging
import warnings
import unittest
class WarningsHandler(logging.Handler):
def handle(self, record):
if record.levelno == logging.WARN:
warnings.warn(record.getMessage())
return record
log = logging.getLogger()
log.addHandler(WarningsHandler())
def generate_warning_2():
log.warn("this is a warning")
def generate_warning_1():
warnings.warn("this is a warning")
class TestWarning(unittest.TestCase):
def test_warning_1(self):
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_1()
self.assertEquals(len(w), 1)
def test_warning_2(self):
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_2()
self.assertEquals(len(w), 1)
if __name__ == "__main__":
unittest.main()
$ python2 so.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
In order to prevent eventual double printing, you might want to make the handler return the LogRecord only conditionally.
Thanks for your answer, had thought about something like this. I want to avoid touching the logging module for now if i can,
– AJS
Apr 1 at 6:29
Then I probably misunderstood the question. You don't want to use thewarnings
module everywhere, but you also do not want to do anything with thelogging
module?
– Hubert Grzeskowiak
Apr 1 at 6:40
Also just to clarify i am willing to change functiontest_warning_2
if there is any other way to capturelog.warn
logging
– AJS
Apr 1 at 6:40
i don't want to change the logging module so that i can catch warning in my test case. I am primary want to catch log.warn in my test case any way possible. even if that mean to change thetest_warning_2
test case that is just a place holder as i don't know any other implementation.
– AJS
Apr 1 at 6:43
1
@AJS just modify the code such that theWarningsHandler
stores the information (e.g. store the message in awarnings
instance variable), and gets instantiated, added and removed by the test case. That way you set up the handler at the start of the test case, run the code, remove the handler, then check the handler's content. Alternatively, switch everything to pytest: it has support for warnings assertions and logging assertions built in.
– Masklinn
Apr 1 at 7:46
|
show 2 more comments
This can be solved using a logger handler. Unfortunately there seems to be no way of setting the handler on the root logger, but only on instances returned by getLogger
. If you can live with that, this should work:
import logging
import warnings
import unittest
class WarningsHandler(logging.Handler):
def handle(self, record):
if record.levelno == logging.WARN:
warnings.warn(record.getMessage())
return record
log = logging.getLogger()
log.addHandler(WarningsHandler())
def generate_warning_2():
log.warn("this is a warning")
def generate_warning_1():
warnings.warn("this is a warning")
class TestWarning(unittest.TestCase):
def test_warning_1(self):
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_1()
self.assertEquals(len(w), 1)
def test_warning_2(self):
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_2()
self.assertEquals(len(w), 1)
if __name__ == "__main__":
unittest.main()
$ python2 so.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
In order to prevent eventual double printing, you might want to make the handler return the LogRecord only conditionally.
This can be solved using a logger handler. Unfortunately there seems to be no way of setting the handler on the root logger, but only on instances returned by getLogger
. If you can live with that, this should work:
import logging
import warnings
import unittest
class WarningsHandler(logging.Handler):
def handle(self, record):
if record.levelno == logging.WARN:
warnings.warn(record.getMessage())
return record
log = logging.getLogger()
log.addHandler(WarningsHandler())
def generate_warning_2():
log.warn("this is a warning")
def generate_warning_1():
warnings.warn("this is a warning")
class TestWarning(unittest.TestCase):
def test_warning_1(self):
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_1()
self.assertEquals(len(w), 1)
def test_warning_2(self):
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
generate_warning_2()
self.assertEquals(len(w), 1)
if __name__ == "__main__":
unittest.main()
$ python2 so.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
In order to prevent eventual double printing, you might want to make the handler return the LogRecord only conditionally.
answered Apr 1 at 6:07
Hubert GrzeskowiakHubert Grzeskowiak
6,7433 gold badges33 silver badges47 bronze badges
6,7433 gold badges33 silver badges47 bronze badges
Thanks for your answer, had thought about something like this. I want to avoid touching the logging module for now if i can,
– AJS
Apr 1 at 6:29
Then I probably misunderstood the question. You don't want to use thewarnings
module everywhere, but you also do not want to do anything with thelogging
module?
– Hubert Grzeskowiak
Apr 1 at 6:40
Also just to clarify i am willing to change functiontest_warning_2
if there is any other way to capturelog.warn
logging
– AJS
Apr 1 at 6:40
i don't want to change the logging module so that i can catch warning in my test case. I am primary want to catch log.warn in my test case any way possible. even if that mean to change thetest_warning_2
test case that is just a place holder as i don't know any other implementation.
– AJS
Apr 1 at 6:43
1
@AJS just modify the code such that theWarningsHandler
stores the information (e.g. store the message in awarnings
instance variable), and gets instantiated, added and removed by the test case. That way you set up the handler at the start of the test case, run the code, remove the handler, then check the handler's content. Alternatively, switch everything to pytest: it has support for warnings assertions and logging assertions built in.
– Masklinn
Apr 1 at 7:46
|
show 2 more comments
Thanks for your answer, had thought about something like this. I want to avoid touching the logging module for now if i can,
– AJS
Apr 1 at 6:29
Then I probably misunderstood the question. You don't want to use thewarnings
module everywhere, but you also do not want to do anything with thelogging
module?
– Hubert Grzeskowiak
Apr 1 at 6:40
Also just to clarify i am willing to change functiontest_warning_2
if there is any other way to capturelog.warn
logging
– AJS
Apr 1 at 6:40
i don't want to change the logging module so that i can catch warning in my test case. I am primary want to catch log.warn in my test case any way possible. even if that mean to change thetest_warning_2
test case that is just a place holder as i don't know any other implementation.
– AJS
Apr 1 at 6:43
1
@AJS just modify the code such that theWarningsHandler
stores the information (e.g. store the message in awarnings
instance variable), and gets instantiated, added and removed by the test case. That way you set up the handler at the start of the test case, run the code, remove the handler, then check the handler's content. Alternatively, switch everything to pytest: it has support for warnings assertions and logging assertions built in.
– Masklinn
Apr 1 at 7:46
Thanks for your answer, had thought about something like this. I want to avoid touching the logging module for now if i can,
– AJS
Apr 1 at 6:29
Thanks for your answer, had thought about something like this. I want to avoid touching the logging module for now if i can,
– AJS
Apr 1 at 6:29
Then I probably misunderstood the question. You don't want to use the
warnings
module everywhere, but you also do not want to do anything with the logging
module?– Hubert Grzeskowiak
Apr 1 at 6:40
Then I probably misunderstood the question. You don't want to use the
warnings
module everywhere, but you also do not want to do anything with the logging
module?– Hubert Grzeskowiak
Apr 1 at 6:40
Also just to clarify i am willing to change function
test_warning_2
if there is any other way to capture log.warn
logging– AJS
Apr 1 at 6:40
Also just to clarify i am willing to change function
test_warning_2
if there is any other way to capture log.warn
logging– AJS
Apr 1 at 6:40
i don't want to change the logging module so that i can catch warning in my test case. I am primary want to catch log.warn in my test case any way possible. even if that mean to change the
test_warning_2
test case that is just a place holder as i don't know any other implementation.– AJS
Apr 1 at 6:43
i don't want to change the logging module so that i can catch warning in my test case. I am primary want to catch log.warn in my test case any way possible. even if that mean to change the
test_warning_2
test case that is just a place holder as i don't know any other implementation.– AJS
Apr 1 at 6:43
1
1
@AJS just modify the code such that the
WarningsHandler
stores the information (e.g. store the message in a warnings
instance variable), and gets instantiated, added and removed by the test case. That way you set up the handler at the start of the test case, run the code, remove the handler, then check the handler's content. Alternatively, switch everything to pytest: it has support for warnings assertions and logging assertions built in.– Masklinn
Apr 1 at 7:46
@AJS just modify the code such that the
WarningsHandler
stores the information (e.g. store the message in a warnings
instance variable), and gets instantiated, added and removed by the test case. That way you set up the handler at the start of the test case, run the code, remove the handler, then check the handler's content. Alternatively, switch everything to pytest: it has support for warnings assertions and logging assertions built in.– Masklinn
Apr 1 at 7:46
|
show 2 more comments
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
"I can't migrate to 3.x right now." Better find time soon. 2.7 is reaching end of life next year.
– jpmc26
Mar 28 at 7:56
Also, don't unit testing logging operations. It is not a valuable use of time.
– jpmc26
Mar 28 at 7:57
i know 2.7 is reaching its end, the decision to not migrate is not mine.
– AJS
Mar 28 at 8:42
You are confusing warnings with logging at loglevel WARN. These are two very different types of things. You are simply looking for testing if your logging code works, and
warnings.catch_warnings()
can't help with that.– Martijn Pieters♦
Apr 2 at 22:14
1
Right, then see the duplicate post, which covers exactly that scenario.
– Martijn Pieters♦
Apr 3 at 11:51