3

I have a several click command on my project on app.py . I use Click 7.0, Pytest 4.6.4 . I have a ui.py which i use for interface to write a logs and encapsulate Logging functionality. I don't know why i can't catch a log message on test.

this is my project structure

project/
    core/
        __init__.py
        app.py
        ui.py

    tests/
        __init__.py
        test_main.py

app.py

import click
from ui import info


@click.group()
def cli():
    pass

@cli.command()
def main():
    info("hello world")

ui.py

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

logger.addHandler(ch)


#interface which i use on my project
def info(msg=""):
    logger.info(msg)

def error(msg=""):
    logger.error(msg)

def warning(msg=""):
    logger.warning(msg)

def debug(msg=""):
    logger.debug(msg)

test_main.py

from click.testing import CliRunner
from core.app import cli


def test_main():
    runner = CliRunner()
    result = runner.invoke(cli, ['main'])
    assert "hello world" in result.output

I got assert error and the reason is that because result.output is empty string ""

def test_main():
        runner = CliRunner()
        result = runner.invoke(cli, ['main'])
>       assert "hello world" in result.output
E       AssertionError: assert 'hello world' in ''
E        +  where '' = <Result okay>.output

What i do wrong? Also i notice that when i move handler to interface function the test will passed. I don't understand this behavior.

something like this

ui.py

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

#interface which i use on my project
def info(msg=""):
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    logger.addHandler(ch)
    logger.info(msg)

Please help.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Romillion
  • 101
  • 1
  • 3
  • 5
    `pytest` will capture output streams, so you won't see the usual output in the test run. Use the `caplog` fixture to access captured log records. Check out [Logging](http://doc.pytest.org/en/latest/logging.html) for details and examples. – hoefling Jul 26 '19 at 09:20
  • 2
    [Here](https://docs.pytest.org/en/latest/logging.html#caplog-fixture) is more documentation on how to use `caplog` to set log level and access log output inside a test for your assertions. – kontur Apr 07 '20 at 13:24

0 Answers0