Home > Mobile >  Pytest: Get rid of redudant Code used in testfunctions introduced by decorators
Pytest: Get rid of redudant Code used in testfunctions introduced by decorators

Time:02-01

I have got the following very simple functions and tests:

from feedback import error_msg, info_msg, warn_msg
import pytest


def test_message_info(capsys):

    @info_msg
    def message():
        return "testmessage"
    message()

    assert capsys.readouterr().out == "INFO: testmessage\n"



def test_message_error(capsys):

    @error_msg
    def message():
        return "testmessage"
    message()

    assert capsys.readouterr().out == "ERROR: testmessage\n"


def test_message_warning(capsys):

    @warn_msg
    def message():
        return "testmessage"
    message()

    assert capsys.readouterr().out == "WARN: testmessage\n"

I know there are probably ways reduce these tests to a single test with a fixture or pytest.mark.parametrize, but I can not get my head around how to solve this. Does anyone know how to do this with a decorator?

CodePudding user response:

Apply the decorator to the function "by hand" rather than using the decorator syntactic sugar. Then you can do all three tests in one loop.

from feedback import error_msg, info_msg, warn_msg
import pytest

MESSAGE_BY_DECORATOR = [
(info_msg, "INFO"),
(error_msg, "ERROR"),
(warn_msg, "WARN")]


def test_message_all(capsys):

    def message():
        return "testmessage"

    for decorator, expected in MESSAGE_BY_DECORATOR:
        decorated_message = decorator(message)
        decorated_message()
        assert capsys.readouterr().out == f"{expected}: testmessage\n"
        # you'll need to reset your capsys object here
  •  Tags:  
  • Related