Package: logassert
Log AssertionWhat?A simple log assertion mechanism for Python unittests.Why?As is vox populi, you must also test the logging calls in your programs.Withlogassertthis is now very easy.Awesome! How do I use it?The same functionality is exposed in two very different ways, one that fits better thepytest semantics, the other one more suitable for classic unit tests.For pytestAll you need to do is to declarelogsin your test arguments, it works
just like any other fixture.Then you just check (usingassert, as usual withpytest) if a specific
line is in the logs for a specific level.Example:deftest_bleh(logs)(...)assert"The meaning of life is 42"inlogs.debugActually, the line you write is a regular expression, so you can totally
do (in case you're not exactly sure which the meaning of life is):assert"The meaning of life is \d+"inlogs.debugThe indicated string is searched to be inside the log lines, it doesn't
need to be exact whole line. If you want that, just indicate it as with
any regular expression:assert"^The meaning of life is \d+$"inlogs.debugIn a similar way you can also express the desire to check if it's at the
beginning or at the end of the log lines.NOTE: the message checked is the final one, after the logging system
replaced all the indicated parameters in the indicated string.If you want to verify that a text was logged, no matter at which level,
just do:assert"The meaning of life is 42"inlogs.any_levelTo verify that some text was NOT logged, just juse the Python's syntax!
For example:assert"A problem happened"notinlogs.errorBut I don't like regexes, I want the exact stringThen you just importExactfromlogassertand wrap the string
with that.For example, in this case the..means exactly two dots, no regex
semantics at all:assertExact("The meaning of life is ..")inlogs.any_levelAnyway, I liked old behaviour of searching multiple stringsThen you may want to importMultiplefromlogassertand wrap the
different strings you had in each call for the classic behaviour.For example:assertMultiple("life","meaning","42")inlogs.any_levelWhat if I want to check that nothing was logged?The simplest way to do it is to use theNOTHINGverifier that you can
import fromlogassert:assertNOTHINGinlogs.debugNote that it doesn't make sense to use it by the negative (...NOTHING not in logs...):
is no really useful at testing level to know that "something was logged", you should
improve the test to specifically verifywhatwas logged.Breaking the "per line barrier"Sometimes it's useful to verify that several lines were logged, and that
those lines are logged one after the other, as they build a "composite
message".To achieve that control on the logged lines you can use theSequencehelper, that receives all the lines to verify (regexes by default, but
you can use the other helpers there):assertSequence("Got 2 errors and \d+ warnings:",Exact("  error 1: foo"),Exact("  error 2: bar"),)inlogs.debugExamplesAfter logging...person="madam"item="wallet"logger.debug("Excuse me%s, you dropped your%s",person,item)...the following test will just pass:assert"Excuse me .*?, you dropped your wallet"inlogs.debugHowever, the following will fail (different text!)...assert"Excuse me .*?, you lost your wallet"inlogs.debug...producing this message in your tests:assert for regex 'Excuse me .*?, you lost your wallet' check in DEBUG, failed; logged lines:
      DEBUG     'Excuse me madam, you dropped your wallet'This one will also fail (different level!)...assert"Excuse me .*?, you dropped your wallet"inlogs.info...producing this message in your tests:assert for regex 'Excuse me .*?, you dropped your wallet' check in INFO, failed; logged lines:
       DEBUG     'Excuse me madam, you dropped your wallet'A more complex example, with several log lines, and a specific assertion:logger.info("Starting system")places=['/tmp/','~/temp']logger.debug("Checking for config XYZ in all these places%s",places)logger.warning("bad config XYZ")assert"bad config XYZ"inlogs.debugSee how the test failure message is super helpful:assert for regex 'bad config XYZ' check in DEBUG, failed; logged lines:
       INFO      'Starting system'
       DEBUG     "Checking for config XYZ in all these places ['/tmp/', '~/temp']"
       WARNING   'bad config XYZ'What about repeated verifications?Sometimes it's needed to verify that something if logged only once (e.g.
welcoming messages). In this cases it's super useful to use theresetmethod.See the following test sequence:deftest_welcomingmessage(logs):logger.info("foo")# first log! it should trigger the welcoming messageassert"Welcome"inlogs.infologs.reset()logger.info("foo")# second log! it should NOT trigger the welcoming messageassert"Welcome"notinlogs.infoFor classic TestCasesAll you need to do is to call this module'ssetup()passing the test case
instance, and the logger you want to supervise.LikeclassMyTestCase(unittest.TestCase):"""Example."""defsetUp(self):logassert.setup(self,'mylogger')In the example,myloggeris the name of the logging to supervise. If
different subsystems of your code log in other loggers, this tester
won't notice.Then, to use it, just call theassertLoggedmethod and it's family,
passing all the strings you want to find. This is the default behaviour for
backwards compatibility.Example:deftest_blah(self):(...)self.assertLoggedDebug('secret','life','42')That line will check that "secret", "life" and "42" are all logged in the
same logging call, in DEBUG level.So, if you logged this, the test will pass:logger.debug("The secret of life, the universe and everything is%d",42)Note that the message checked is the one with all parameters replaced.But if you logged any of the following, the test will fail (the first because
it misses one of the string, the second because it has the wrong log level)::logger.debug("The secret of life, the universe and everything is lost")logger.info("The secret of life, the universe and everything is 42")What can I test?You'll have at disposition several assertion methods:self.assertLogged: will check that the strings
were logged, no matter at which levelself.assertLoggedLEVEL(being LEVEL one of Error,
Warning, Info, or Debug): will check that the strings were logged at
that specific level.self.assertNotLogged: will check that the
strings were NOT logged, no matter at which levelself.assertNotLoggedLEVEL(being LEVEL one of
Error, Warning, Info, or Debug): will check that the strings were NOT
logged at that specific level.Nice! But...If you need help, or have any question, or found any issue, please open a
tickethere.Thanks in advance for your time.