Skip to content

Instantly share code, notes, and snippets.

@jettero
Last active June 29, 2018 14:56
Show Gist options
  • Save jettero/3bd163418ca328e53b7825e4f6be72d8 to your computer and use it in GitHub Desktop.
Save jettero/3bd163418ca328e53b7825e4f6be72d8 to your computer and use it in GitHub Desktop.
pytest cli (aka livelog) filtered output
import pytest, logging, os
class OnlyMe(logging.Filter):
_only_one = None
my_path = os.path.dirname(
os.path.dirname(
os.path.abspath(__file__)))
@classmethod
def scramble_every_zig(cls):
if cls._only_one is None:
cls._only_one = cls()
# logging.root.addFilter can be skipped, it doesn't seem to actually do anything
# the first handler in logging.root.handlers will be the
# _pytest.logging._LiveLoggingStreamHandler (the output to terminal)
# the second handler will be the
# _pytest.logging.LogCaptureHandler (the output to the caplog fixture)
for i in [logging.root] + logging.root.handlers:
i.addFilter(cls._only_one)
@classmethod
def return_zig(cls):
if cls._only_one is not None:
for i in [logging.root] + logging.root.handlers:
i.removeFilter(cls._only_one)
def filter(self,r):
return r.pathname.startswith(self.my_path)
# this fixture needs to be used once after the caplog/LiveLog handlers are set up
# trying to simply do this in conftest won't work, it has to be somewhat later
# (livelog/caplog are themselves provided through the fixture interfaces,
# later than conftest is loaded)
@pytest.fixture
def stfu():
OnlyMe.scramble_every_zig() # all your base are belong to us!
yield OnlyMe.my_path # deliever nonsense message to player
OnlyMe.return_zig() # get us back to our own base
import docker, logging
log = logging.getLogger('something')
def test_something(stfu):
log.debug("something") # this will emit in the in pytest --log-cli-level debug
dc = docker.DockerClient()
try:
l = dc.containers.get('something') # docker.auth spams debugs, as does urllib3.connectionpool
assert l == None # but they won't show up here thanks to the stfu fixture
except docker.errors.NotFound:
assert True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment