[Python] How can I attach Python decorator @pytest.mark.paramerize to an imported function?

Discussão em 'Python' iniciado por Stack, Agosto 25, 2025.

  1. Stack

    Stack Membro Participativo

    In my test suite, I have a lot of code like this:

    # file test/test_procedural.py
    from test.helper import check_evaluation

    @pytest.mark.parametrize(
    ("str_expr", "msgs", "assert_fail_msg"),
    [
    (
    "Abort[a, b]",
    ["Abort called with 2 arguments; 0 arguments are expected."],
    "Abort argument error call",
    ),
    (
    "Catch[a, b, c, d, e]",
    ["Catch called with 5 arguments; between 1 and 3 arguments are expected."],
    "Catch argument error call",
    ),
    # ...
    ],
    )
    def test_wrong_number_of_arguments(str_expr, msgs, assert_fail_msg):
    """
    check_evaluation(
    str_expr,
    str_expr,
    to_string_expr=True,
    to_string_expected=True,
    hold_expected=True,
    failure_message=assert_fail_msg,
    expected_messages=msgs,
    )



    # file test/test_strings.py
    from test.helper import check_evaluation
    @pytest.mark.parametrize(
    ("str_expr", "msgs", "assert_fail_msg"),
    [
    (
    "ToExpression[]",
    (
    "ToExpression called with 0 arguments; between 1 and 3 arguments are expected.",
    ),
    "ToExpression argument error call",
    ),
    ],
    )

    def test_wrong_number_of_arguments(str_expr, msgs, assert_fail_msg):
    """ """
    check_evaluation(
    str_expr,
    str_expr,
    to_string_expr=True,
    to_string_expected=True,
    hold_expected=True,
    failure_message=assert_fail_msg,
    expected_messages=msgs,
    )



    Instead of definining test_wrong_number_of_arguments many times, I would like to define this once in helper and decorate that in each file with the pytest.mark.paramaterize.

    How do I accomplish this?

    I have looked at How can I apply a decorator to an imported function?, but the challenge here is pytest's introspection. When I try:

    from test.helper import wrong_number_of_arguments
    test_wrong_number_of_arguments = pytest.mark.parametrize(wrong_number_of_arguments,
    ("str_expr", "msgs", "assert_fail_msg"),
    [
    (
    "ToExpression[]",
    (
    "ToExpression called with 0 arguments; between 1 and 3 arguments are expected.",
    ),
    "ToExpression argument error call",
    ),
    ],
    )


    and run pytest, I get:

    /tmp/3.13.7/lib/python3.13/site-packages/_pytest/mark/structures.py:391: PytestCollectionWarning: cannot collect 'test_wrong_number_of_arguments' because it is not a function.
    def __call__(self, *args: object, **kwargs: object):

    Continue reading...

Compartilhe esta Página