[Python] Python Unit Test Side Effect Returns Function Instead of Value

Discussão em 'Python' iniciado por Stack, Abril 30, 2025.

  1. Stack

    Stack Membro Participativo

    I am working through creating unit tests for a Python application that handles data via Pandas DataFrames. One section of this application formats data in various DataFrame columns. I am looking to mock the Series.apply function to format column values into strings.

    The line I am looking to mock is:

    source_table_df["col1"] = source_table_df["col1"].apply(self._format_col)


    I am mocking this with the following code:

    with patch("pandas.core.series.Series.apply") as mock_apply:
    mock_apply.side_effect = (lambda val: str(val))


    For my unit test, I have a table that looks like so:

    col1
    ===
    1
    1
    1


    And I am looking for this to be converted to:

    col1
    ===
    "1"
    "1"
    "1"


    However, I am recieving the following outcome:

    col1
    ===
    <function MyClass._format_col at 0x000001AA25FD0A40>
    <function MyClass._format_col at 0x000001AA25FD0A40>
    <function MyClass._format_col at 0x000001AA25FD0A40>


    How can I properly mock the conversion of the column values? Thank you for your time.

    Continue reading...

Compartilhe esta Página