pax_global_header00006660000000000000000000000064137453726020014523gustar00rootroot0000000000000052 comment=e4e8be3534ca3d0c7f2dc8712534c2630694d602 logassert-6/000077500000000000000000000000001374537260200132355ustar00rootroot00000000000000logassert-6/.github/000077500000000000000000000000001374537260200145755ustar00rootroot00000000000000logassert-6/.github/workflows/000077500000000000000000000000001374537260200166325ustar00rootroot00000000000000logassert-6/.github/workflows/python-package.yml000066400000000000000000000024221374537260200222670ustar00rootroot00000000000000# This workflow will install Python dependencies, run tests and lint with a variety of Python versions # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions name: Python package on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest strategy: matrix: python-version: [3.5, 3.6, 3.7, 3.8] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install flake8 pytest if [ -f requirements.txt ]; then pip install -r requirements.txt; fi - name: Lint with flake8 run: | # stop the build if there are Python syntax errors or undefined names flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide flake8 . --count --exit-zero --max-complexity=10 --max-line-length=99 --statistics - name: Test with pytest run: | python3 -m pytest -p pytester logassert-6/.gitignore000066400000000000000000000013471374537260200152320ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ # Own stuff MANIFEST # PyCharm .idea/ logassert-6/AUTHORS000066400000000000000000000000771374537260200143110ustar00rootroot00000000000000Copyright 2015 Facundo Batista logassert-6/LICENSE000066400000000000000000000167441374537260200142560ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. logassert-6/MANIFEST.in000066400000000000000000000000631374537260200147720ustar00rootroot00000000000000include README.rst include LICENSE include AUTHORS logassert-6/README.md000066400000000000000000000167401374537260200145240ustar00rootroot00000000000000# Log Assertion ![Python package](https://github.com/facundobatista/logassert/workflows/Python%20package/badge.svg) ## What? A simple log assertion mechanism for Python unittests. ## Why? As is vox populi, you must also test the logging calls in your programs. With `logassert` this is now very easy. # Awesome! How do I use it? The same functionality is exposed in two very different ways, one that fits better the *pytest semantics*, the other one more suitable for classic unit tests. ## For pytest All you need to do is to declare `logs` in your test arguments, it works just like any other fixture. Then you just check (using `assert`, as usual with *pytest*) if a specific line is in the logs for a specific level. Example: ```python def test_bleh(logs) (...) assert "The meaning of life is 42" in logs.debug ``` Actually, 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): ```python assert "The meaning of life is \d+" in logs.debug ``` The 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: ```python assert "^The meaning of life is \d+$" in logs.debug ``` In 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: ```python assert "The meaning of life is 42" in logs.any_level ``` To verify that some text was NOT logged, just juse the Python's syntax! For example: ```python assert "A problem happened" not in logs.error ``` ### But I don't like regexes, I want the exact string Then you just import `Exact` from `logassert` and wrap the string with that. For example, in this case the `..` means exactly two dots, no regex semantics at all: ```python assert Exact("The meaning of life is ..") in logs.any_level ``` ### Anyway, I liked old behaviour of searching multiple strings Then you may want to import `Multiple` from `logassert` and wrap the different strings you had in each call for the classic behaviour. For example: ```python assert Multiple("life", "meaning", "42") in logs.any_level ``` ### What if I want to check that nothing was logged? The simplest way to do it is to use the `NOTHING` verifier that you can import from `logassert`: ```python assert NOTHING in logs.debug ``` Note 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 verify *what* was 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 the `Sequence` helper, that receives all the lines to verify (regexes by default, but you can use the other helpers there): ```python assert Sequence( "Got 2 errors and \d+ warnings:", Exact(" error 1: foo"), Exact(" error 2: bar"), ) in logs.debug ``` ### Examples After logging... ```python person = "madam" item = "wallet" logger.debug("Excuse me %s, you dropped your %s", person, item) ``` ...the following test will just pass: ```python assert "Excuse me .*?, you dropped your wallet" in logs.debug ``` However, the following will fail (different text!)... ```python assert "Excuse me .*?, you lost your wallet" in logs.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!)... ```python assert "Excuse me .*?, you dropped your wallet" in logs.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: ```python 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" in logs.debug ``` See 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 the `reset` method. See the following test sequence: ```python def test_welcoming message(logs): logger.info("foo") # first log! it should trigger the welcoming message assert "Welcome" in logs.info logs.reset() logger.info("foo") # second log! it should NOT trigger the welcoming message assert "Welcome" not in logs.info ``` ## For classic TestCases All you need to do is to call this module's `setup()` passing the test case instance, and the logger you want to supervise. Like ```python class MyTestCase(unittest.TestCase): """Example.""" def setUp(self): logassert.setup(self, 'mylogger') ``` In the example, `mylogger` is 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 the `assertLogged` method and it's family, passing all the strings you want to find. This is the default behaviour for backwards compatibility. Example: ```python def test_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: ```python 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):: ```python 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 level - `self.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 level - `self.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 ticket [here](https://github.com/facundobatista/logassert/issues/new). Thanks in advance for your time. logassert-6/logassert/000077500000000000000000000000001374537260200152405ustar00rootroot00000000000000logassert-6/logassert/__init__.py000066400000000000000000000015041374537260200173510ustar00rootroot00000000000000# Copyright 2015-2020 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License version 3, as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . # # For further info, check https://github.com/facundobatista/logassert from .logassert import setup, Exact, Regex, Multiple, Sequence, NOTHING # NOQA (imported but not used) logassert-6/logassert/logassert.py000066400000000000000000000263351374537260200176260ustar00rootroot00000000000000# Copyright 2015-2020 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License version 3, as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . # # For further info, check https://github.com/facundobatista/logassert """Main module.""" import collections import functools import logging.handlers import re Record = collections.namedtuple("Record", "levelname levelno message") class _StoringHandler(logging.handlers.MemoryHandler): """A fake handler to store the records.""" def __init__(self, log_path): # init memory handler to never flush super().__init__(capacity=100000, flushLevel=1000) # hook in the logger logger = logging.getLogger(log_path) # ensure there are not other _StoringHandlers logger.handlers[:] = [h for h in logger.handlers if not isinstance(h, _StoringHandler)] logger.addHandler(self) logger.setLevel(logging.DEBUG) self.setLevel(logging.DEBUG) # hold a kind of record with the message already composed self.records = [] def emit(self, record): """Store the message, not only the record. Here is where we get in the middle of the logging machinery to capture messages. """ r = Record(levelno=record.levelno, levelname=record.levelname, message=self.format(record)) self.records.append(r) return super().emit(record) class SetupLogChecker: """A version of the LogChecker to use in classic TestCases.""" def __init__(self, test_instance, log_path): self._log_checker = _StoringHandler(log_path) # fix TestCase instance with all classic-looking helpers self.test_instance = test_instance test_instance.assertLogged = self._check_generic_pos test_instance.assertLoggedError = functools.partial(self._check_pos, logging.ERROR) test_instance.assertLoggedWarning = functools.partial(self._check_pos, logging.WARNING) test_instance.assertLoggedInfo = functools.partial(self._check_pos, logging.INFO) test_instance.assertLoggedDebug = functools.partial(self._check_pos, logging.DEBUG) test_instance.assertNotLogged = functools.partial(self._check_neg, None) test_instance.assertNotLoggedError = functools.partial(self._check_neg, logging.ERROR) test_instance.assertNotLoggedWarning = functools.partial(self._check_neg, logging.WARNING) test_instance.assertNotLoggedInfo = functools.partial(self._check_neg, logging.INFO) test_instance.assertNotLoggedDebug = functools.partial(self._check_neg, logging.DEBUG) def _check_generic_pos(self, *tokens): """Check if the different tokens were logged in one record, any level.""" for record in self._log_checker.records: if all(token in record.message for token in tokens): return # didn't exit, all tokens are not present in the same record msgs = ["Tokens {} not found, all was logged is...".format(tokens)] for record in self._log_checker.records: msgs.append(" {:9s} {!r}".format(record.levelname, record.message)) self.test_instance.fail("\n".join(msgs)) def _check_pos(self, level, *tokens): """Check if the different tokens were logged in one record, assert by level.""" for record in self._log_checker.records: if all(record.levelno == level and token in record.message for token in tokens): return # didn't exit, all tokens are not present in the same record level_name = logging.getLevelName(level) msgs = ["Tokens {} not found in {}, all was logged is...".format(tokens, level_name)] for record in self._log_checker.records: msgs.append(" {:9s} {!r}".format(record.levelname, record.message)) self.test_instance.fail("\n".join(msgs)) def _check_neg(self, level, *tokens): """Check that the different tokens were NOT logged in one record, assert by level.""" for record in self._log_checker.records: if level is not None and record.levelno != level: continue if all(token in record.message for token in tokens): break else: return # didn't exit, all tokens found in the same record msg = "Tokens {} found in the following record: {} {!r}".format( tokens, record.levelname, record.message) self.test_instance.fail(msg) class Matcher: """A generic matcher.""" default_response = None def __init__(self, token): self.token = token def search(self, message): """Search the token in the message, return if it's present.""" raise NotImplementedError() def __str__(self): return "{} {!r} check".format(self.__class__.__name__.lower(), self.token) class Regex(Matcher): """A matcher that uses the token string as a regex.""" def __init__(self, token): super().__init__(token) self.regex = re.compile(token) def search(self, message): """Search the token in the message, return if it's present.""" return bool(self.regex.search(message)) class Exact(Matcher): """A matcher that matches exactly the token string.""" def search(self, message): """Search the token in the message, return if it's present.""" return self.token == message class Multiple(Matcher): """A matcher that matches multiple tokens (legacy support).""" def __init__(self, *tokens): super().__init__(tokens) def search(self, message): """Search the token in the message, return if it's present.""" return all(t in message for t in self.token) class Sequence(Matcher): """A matcher that just holds its inners so each one can be verified separatedly. Note it doesn't define a `search` method, as it should never be called. """ def __init__(self, *tokens): super().__init__(tokens) class _Nothing(Matcher): """A matcher that is succesful only if nothing was logged.""" default_response = True def search(self, message): """If a message was given, it implies "something was logged".""" # as a message happened, change the final default response self.default_response = None return False def __str__(self): return 'nothing' NOTHING = _Nothing(None) class PyTestComparer: def __init__(self, handler, level=None): self.handler = handler self.level = level self._matcher_description = "" def _get_matcher(self, item): """Produce a real matcher from a specific item.""" if isinstance(item, str): # item is not specific, so default to Regex return Regex(item) if isinstance(item, Matcher): return item raise ValueError("Unknown item type: {!r}".format(item)) def __contains__(self, item): if isinstance(item, Sequence): self._matcher_description = str(item) # sequence! all needs to succeed, in order results = [] for subitem in item.token: matcher = self._get_matcher(subitem) result = self._check(matcher) if result is None: # didn't succeed, calling it off break else: results.append(result) else: # all went fine... now check if it was in the proper order expected_sequence = list(range(results[0], len(item.token) + 1)) if expected_sequence == results: return True else: # simple matcher, check if it just succeeds matcher = self._get_matcher(item) self._matcher_description = str(matcher) if self._check(matcher) is not None: return True return False @property def messages(self): """Get all the messages in this log, to show when an assert fails.""" if self.level is None: level_name = "any level" else: level_name = logging.getLevelName(self.level) records = self._get_records() if records: title = "for {} in {} failed; logged lines:".format( self._matcher_description, level_name) else: title = "for {} in {} failed; no logged lines at all!".format( self._matcher_description, level_name) messages = [title] for _, logged_levelname, logged_message in records: messages.append(" {:9s} {!r}".format(logged_levelname, logged_message)) return messages def _get_records(self): """Get the level number, level name and message from the logged records.""" return [(r.levelno, r.levelname, r.message.split('\n')[0]) for r in self.handler.records] def _check(self, matcher): """Check if the matcher is ok with any of the logged levels/messages.""" for idx, (logged_level, _, logged_message) in enumerate(self._get_records()): if logged_level == self.level or self.level is None: if matcher.search(logged_message): return idx return matcher.default_response class FixtureLogChecker: """A version of the LogChecker to use as a pytest fixture.""" # translation between the attributes and logging levels _levels = { 'any_level': None, 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, } def __init__(self): self.handler = _StoringHandler('') def __getattribute__(self, name): handler = object.__getattribute__(self, 'handler') if name == 'reset': return handler.records.clear # this is handled dinamically so we don't need to create a bunch of PyTestComparares # for every test, specially because most of them won't be used in that test _levels = object.__getattribute__(self, '_levels') try: level = _levels[name] except KeyError: raise AttributeError("'FixtureLogChecker' object has no attribute {!r}".format(name)) return PyTestComparer(handler, level) def setup(test_instance, logger_name): """Set up the log monitoring. The test instance is the one where this will be used. The logger name is the one of the logger to supervise. Example of use for classic tests (for "pytest" just install it and will be a fixture 'logged'): class MyTestCase(unittest.TestCase): def setUp(self): logassert.setup(self, 'mylogger') def test_blah(self): (...) self.assertLogged(...) """ return SetupLogChecker(test_instance, logger_name) logassert-6/logassert/pytest_plugin.py000066400000000000000000000024131374537260200205200ustar00rootroot00000000000000# Copyright 2020 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License version 3, as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . # # For further info, check https://github.com/facundobatista/logassert """Integration to be a fixture of pytest.""" from logassert import logassert import pytest @pytest.fixture() def logs(request): """Provide the logassert functionality through a fixture. Its scope is "session" so it hooks the log handler only once. """ return logassert.FixtureLogChecker() @pytest.hookimpl() def pytest_assertrepr_compare(op, left, right): """Hook called by pytest to return the messages to show to the user.""" if op in ("in", "not in") and isinstance(right, logassert.PyTestComparer): return right.messages logassert-6/setup.py000077500000000000000000000052421374537260200147550ustar00rootroot00000000000000#!/usr/bin/env python3 # Copyright 2015-2020 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License version 3, as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . # # For further info, check https://github.com/facundobatista/logassert """Build tar.gz for logassert.""" from setuptools import setup setup( name='logassert', version='6', license='LGPL-3', author='Facundo Batista', author_email='facundo@taniquetil.com.ar', description='Simple but powerful assertion and verification of logged lines.', long_description=open('README.md').read(), long_description_content_type="text/markdown", url='https://github.com/facundobatista/logassert', # the following makes a plugin available to pytest entry_points={"pytest11": ["logassert = logassert.pytest_plugin"]}, packages=["logassert"], install_requires=['setuptools'], python_requires='>=3.5', # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'Framework :: Pytest', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: GNU General Public License (GPL)', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Natural Language :: English', 'Natural Language :: Spanish', 'Operating System :: MacOS', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Topic :: Software Development', 'Topic :: Utilities', ], ) logassert-6/test000077500000000000000000000000661374537260200141440ustar00rootroot00000000000000#!/bin/sh fades -d pytest -m pytest -p pytester "$@" logassert-6/tests/000077500000000000000000000000001374537260200143775ustar00rootroot00000000000000logassert-6/tests/conftest.py000077700000000000000000000000001374537260200242672../logassert/pytest_plugin.pyustar00rootroot00000000000000logassert-6/tests/test_asfixture.py000066400000000000000000000264351374537260200200340ustar00rootroot00000000000000# Copyright 2020 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License version 3, as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . # # For further info, check https://github.com/facundobatista/logassert """Tests for the main module when used as a pytest fixture.""" import logging import pytest from logassert import Exact, Multiple, Sequence, NOTHING logger = logging.getLogger() # -- Basic usage def test_basic_simple_assert_ok_simple(logs): logger.debug("test") assert "test" in logs.any_level def test_basic_simple_assert_ok_with_replaces(logs): logger.debug("test %d %r", 65, 'foobar') assert "test 65 'foobar'" in logs.any_level def test_basic_simple_negated_assert_(logs): logger.debug("aaa") assert "aaa" not in logs.warning # different than logged assert "bbb" not in logs.any_level # checking other text in any level assert "bbb" not in logs.debug # checking other text in same level def test_reset(logs): logger.debug("foobar") assert "foobar" in logs.debug logs.reset() assert "foobar" not in logs.debug # -- messages def test_failure_message_simple(logs): logger.debug("aaa") with pytest.raises(AssertionError) as err: assert "bbb" in logs.debug assert str(err.value) == ( "assert for regex 'bbb' check in DEBUG failed; logged lines:\n" " DEBUG 'aaa'" ) def test_failure_message_no_logs(logs): with pytest.raises(AssertionError) as err: assert "bbb" in logs.debug assert str(err.value) == ( "assert for regex 'bbb' check in DEBUG failed; no logged lines at all!" ) def test_failure_message_any_level(logs): logger.debug("aaa") with pytest.raises(AssertionError) as err: assert "bbb" in logs.any_level assert str(err.value) == ( "assert for regex 'bbb' check in any level failed; logged lines:\n" " DEBUG 'aaa'" ) def test_failure_message_multiple(logs): logger.debug("aaa") logger.warning("bbb") with pytest.raises(AssertionError) as err: assert "bbb" in logs.debug assert str(err.value) == ( "assert for regex 'bbb' check in DEBUG failed; logged lines:\n" " DEBUG 'aaa'\n" " WARNING 'bbb'" ) def test_failure_message_exception(logs): try: raise ValueError("test error") except ValueError: logger.exception("test message") with pytest.raises(AssertionError) as err: assert "will make it fail" in logs.error assert str(err.value) == ( "assert for regex 'will make it fail' check in ERROR failed; logged lines:\n" " ERROR 'test message'" ) # -- different forms of comparison def test_regex_matching_exact(logs): logger.debug("foo 42") assert r"foo 42" in logs.debug assert r"foo \d\d" in logs.debug def test_regex_matching_inside(logs): logger.debug("foo bar 42") assert r"bar \d\d" in logs.debug assert r"ba." in logs.debug assert r"f.. bar" in logs.debug with pytest.raises(AssertionError): assert r"foo 42" in logs.debug def test_regex_matching_forcing_complete(logs): logger.debug("foo x bar") assert r"^foo . bar$" in logs.debug with pytest.raises(AssertionError): assert r"^foo .$" in logs.debug def test_exact_cases(logs): logger.debug("foo 42") assert Exact("foo 42") in logs.debug assert Exact("foo ..") not in logs.debug assert Exact("foo") not in logs.debug def test_exact_failure(logs): logger.debug("aaa") comparer = logs.debug check_ok = comparer.__contains__(Exact("bbb")) assert not check_ok assert comparer.messages == [ "for exact 'bbb' check in DEBUG failed; logged lines:", " DEBUG 'aaa'", ] def test_multiple_cases(logs): logger.debug("foo bar 42") assert Multiple("foo bar 42") in logs.debug assert Multiple("foo bar 42", "extra") not in logs.debug assert Multiple("foo", "bar") in logs.debug assert Multiple("42", "bar") in logs.debug assert Multiple("foo 42") not in logs.debug assert Multiple("foo.*") not in logs.debug def test_multiple_failure(logs): logger.debug("aaa") comparer = logs.debug check_ok = comparer.__contains__(Multiple("bbb", 'ccc')) assert not check_ok assert comparer.messages == [ "for multiple ('bbb', 'ccc') check in DEBUG failed; logged lines:", " DEBUG 'aaa'", ] def test_sequence_simple(logs): logger.debug("foo") logger.debug("a1") logger.debug("a2") logger.debug("bar") assert Sequence("a1", "a2") in logs.debug def test_sequence_rotated(logs): logger.debug("a2") logger.debug("a1") comparer = logs.debug check_ok = comparer.__contains__(Sequence("a1", "a2")) assert not check_ok assert comparer.messages == [ "for sequence ('a1', 'a2') check in DEBUG failed; logged lines:", " DEBUG 'a2'", " DEBUG 'a1'", ] def test_sequence_partial(logs): logger.debug("a1") comparer = logs.debug check_ok = comparer.__contains__(Sequence("a1", "a2")) assert not check_ok assert comparer.messages == [ "for sequence ('a1', 'a2') check in DEBUG failed; logged lines:", " DEBUG 'a1'", ] def test_sequence_interrupted(logs): logger.debug("a1") logger.debug("--") logger.debug("a2") comparer = logs.debug check_ok = comparer.__contains__(Sequence("a1", "a2")) assert not check_ok assert comparer.messages == [ "for sequence ('a1', 'a2') check in DEBUG failed; logged lines:", " DEBUG 'a1'", " DEBUG '--'", " DEBUG 'a2'", ] def test_sequence_inners(logs): logger.debug("foo") logger.debug("xxx a1") logger.debug("xxx a2") logger.debug("xxx a3") logger.debug("bar") assert Sequence( ".* a.", Exact("xxx a2"), Multiple("a3", "xxx"), ) in logs.debug def test_basic_avoid_delayed_messaging(logs): class Exploding: """Explode on delayed str.""" should_explode = False def __str__(self): if self.should_explode: raise ValueError("str exploded") return "didn't explode" # log something using the Exploding class exploding = Exploding() logger = logging.getLogger() logger.debug("feeling lucky? %s", exploding) # now flag the class to explode and check exploding.should_explode = True assert r"feeling lucky\? didn't explode" in logs.debug def test_nothing_ok(logs): logger.debug("aaa") assert NOTHING in logs.warning def test_nothing_fail_level(logs): logger.debug("aaa") with pytest.raises(AssertionError) as err: assert NOTHING in logs.debug assert str(err.value) == ( "assert for nothing in DEBUG failed; logged lines:\n" " DEBUG 'aaa'" ) def test_nothing_fail_any(logs): logger.debug("aaa") with pytest.raises(AssertionError) as err: assert NOTHING in logs.any_level assert str(err.value) == ( "assert for nothing in any level failed; logged lines:\n" " DEBUG 'aaa'" ) # -- Levels def test_levels_assert_ok_debug(logs): logger.debug("test") assert "test" in logs.debug def test_levels_assert_ok_info(logs): logger.info("test") assert "test" in logs.info def test_levels_assert_ok_warning(logs): logger.warning("test") assert "test" in logs.warning def test_levels_assert_ok_error(logs): logger.error("test") assert "test" in logs.error def test_levels_assert_ok_exception(logs): try: raise ValueError("test error") except ValueError: logger.exception("test message") assert "^test message$" in logs.error def test_levels_assert_different_level_fail_debug_warning(logs): logger.warning("test") with pytest.raises(AssertionError): assert "test" in logs.debug def test_levels_assert_different_level_fail_warning_debug(logs): logger.debug("test") with pytest.raises(AssertionError): assert "test" in logs.warning # -- Usage as a fixture! def test_as_fixture_basic(testdir, pytestconfig): """Make sure that our plugin works.""" # create a temporary conftest.py file plugin_fpath = pytestconfig.rootdir / 'logassert' / 'pytest_plugin.py' with plugin_fpath.open('rt', encoding='utf8') as fh: testdir.makeconftest(fh.read()) # create a temporary pytest test file testdir.makepyfile( """ def test_hello_default(logs): assert "anything" not in logs.any_level """ ) # run the test with pytest result = testdir.runpytest() # check that the test passed result.assert_outcomes(passed=1) def test_as_fixture_double_handler(testdir, pytestconfig): """Check that we don't hook many handlers.""" # create a temporary conftest.py file plugin_fpath = pytestconfig.rootdir / 'logassert' / 'pytest_plugin.py' with plugin_fpath.open('rt', encoding='utf8') as fh: testdir.makeconftest(fh.read()) # create a temporary pytest test file testdir.makepyfile( """ from logassert import logassert import logging logger = logging.getLogger() def test_1(logs): logger.debug('test') assert "test" in logs.any_level def test_2(logs): logger.debug('test') assert "test" in logs.debug assert len( [h for h in logger.handlers if isinstance(h, logassert._StoringHandler)]) == 1 """ ) # run the test with pytest result = testdir.runpytest() print('\n'.join(result.stdout.lines)) # check that the test passed result.assert_outcomes(passed=2) def test_as_fixture_no_record_leaking(testdir, pytestconfig): """Nothing is leaked between tests.""" # create a temporary conftest.py file plugin_fpath = pytestconfig.rootdir / 'logassert' / 'pytest_plugin.py' with plugin_fpath.open('rt', encoding='utf8') as fh: testdir.makeconftest(fh.read()) # create a temporary pytest test file testdir.makepyfile( """ import logging logger = logging.getLogger() def test_1(logs): logger.debug('test') assert "test" in logs.any_level def test_2(logs): assert "test" not in logs.any_level """ ) # run the test with pytest result = testdir.runpytest() # check that the test passed result.assert_outcomes(passed=2) def test_logged_lines_are_shown_when_using_not_in(logs): logger.error("foo") with pytest.raises(AssertionError) as err: assert "foo" not in logs.error expected_log = ("assert for regex 'foo' check in ERROR failed; logged lines:\n" " ERROR 'foo'") assert expected_log == str(err.value) logassert-6/tests/test_classic.py000066400000000000000000000163371374537260200174430ustar00rootroot00000000000000# Copyright 2015 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License version 3, as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . # # For further info, check https://github.com/facundobatista/logassert """Tests for the main module.""" import logging import unittest import logassert class FakeTestCase: """A fake to record if stuff failed.""" def __init__(self): self.failed = None def fail(self, text): self.failed = text class BasicUsageTestCase(unittest.TestCase): """Basic usage.""" def setUp(self): self.logger = logging.getLogger() self.logger.handlers = [] def test_simple_assert_ok(self): ftc = FakeTestCase() logassert.setup(ftc, '') self.logger.debug("test") ftc.assertLogged("test") self.assertEqual(ftc.failed, None) def test_simple_assert_ok_with_replaces(self): ftc = FakeTestCase() logassert.setup(ftc, '') self.logger.debug("test %d %r", 65, 'foobar') ftc.assertLogged("test", "65", "foobar") self.assertEqual(ftc.failed, None) def test_simple_assert_fail(self): ftc = FakeTestCase() logassert.setup(ftc, '') self.logger.debug("test") ftc.assertLogged("test2") self.assertEqual(ftc.failed, "Tokens ('test2',) not found, all was logged is...\n" " DEBUG 'test'") def test_simple_assert_fail_with_replaces(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') logger.debug("test %d %r", 65, 'foobar') ftc.assertLogged("test", "pumba") self.assertEqual(ftc.failed, "Tokens ('test', 'pumba') not found, all was logged is...\n" " DEBUG \"test 65 'foobar'\"") def test_avoid_delayed_messaging(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') class Exploding: """Explode on delayed str.""" should_explode = False def __str__(self): if self.should_explode: raise ValueError("str exploded") return "didn't explode" # log something using the Exploding class exploding = Exploding() logger.debug("feeling lucky? %s", exploding) # now flag the class to explode and check exploding.should_explode = True ftc.assertLogged("feeling lucky", "didn't explode") class LevelsTestCase(unittest.TestCase): """Work aware of logging levels.""" def test_assert_different_level_ok_debug(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') logger.debug("test") ftc.assertLoggedDebug("test") self.assertEqual(ftc.failed, None) def test_assert_different_level_ok_info(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') logger.info("test") ftc.assertLoggedInfo("test") self.assertEqual(ftc.failed, None) def test_assert_different_level_ok_error(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') logger.error("test") ftc.assertLoggedError("test") self.assertEqual(ftc.failed, None) def test_assert_different_level_ok_exception(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') try: raise ValueError("test error") except Exception: logger.exception("test message") ftc.assertLoggedError("test error") ftc.assertLoggedError("test message") ftc.assertLoggedError("ValueError") self.assertEqual(ftc.failed, None) def test_assert_different_level_ok_warning(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') logger.warning("test") ftc.assertLoggedWarning("test") self.assertEqual(ftc.failed, None) def test_assert_different_level_fail_oneway(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') logger.warning("test") ftc.assertLoggedDebug("test") self.assertEqual(ftc.failed, "Tokens ('test',) not found in DEBUG, all was logged is...\n" " WARNING 'test'") def test_assert_different_level_fail_inverse(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') logger.debug("test") ftc.assertLoggedWarning("test") self.assertEqual( ftc.failed, "Tokens ('test',) not found in WARNING, all was logged is...\n" " DEBUG 'test'") class NotLoggedTestCase(unittest.TestCase): """Also check that it wasn't logged.""" def test_simple_ok(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') logger.debug("test") ftc.assertNotLogged("other") self.assertEqual(ftc.failed, None) def test_simple_fail(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') logger.info("test") ftc.assertNotLogged("test") self.assertEqual(ftc.failed, "Tokens ('test',) found in the following record: INFO 'test'") def test_level_debug_ok(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') logger.info("test") ftc.assertNotLoggedDebug("test") self.assertEqual(ftc.failed, None) def test_level_debug_fail(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') logger.debug("test") ftc.assertNotLoggedDebug("test") self.assertEqual(ftc.failed, "Tokens ('test',) found in the following record: DEBUG 'test'") def test_level_info(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') logger.debug("test") ftc.assertNotLoggedInfo("test") self.assertEqual(ftc.failed, None) def test_level_warning(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') logger.info("test") ftc.assertNotLoggedWarning("test") self.assertEqual(ftc.failed, None) def test_level_error(self): ftc = FakeTestCase() logger = logging.getLogger() logassert.setup(ftc, '') logger.info("test") ftc.assertNotLoggedError("test") self.assertEqual(ftc.failed, None)