【问题标题】:Python mock assert called fails even if mock called即使调用了模拟,调用的 Python 模拟断言也会失败
【发布时间】:2020-09-17 09:04:31
【问题描述】:

我正在使用 mock 和 pytest 对我的项目运行多个单元测试,但我遇到了一个非常奇怪的错误。

在模拟的特定测试中,我正在测试的函数中调用了一个函数,我想检查该函数是否使用特定参数调用。但是 mock_function.assert_called() 失败了。

为了调试它,我添加了以下几行:

    print(f"called: {str( mock_send_ano.called )}")
    print(f"call args: {str( mock_send_ano.call_args )}")
    assert mock_send_ano.assert_called()
    assert mock_send_ano.assert_called_with(expected_parameter)

在我得到的输出控制台中:

called: True
call args: call({'msn': 'F8231', 'flight': 'V0001'})

expected_parameter= {'msn': 'F8231', 'flight': 'V0001'}

我仍然收到此错误

AssertionError: assert None
   +  where None = <bound method NonCallableMock.assert_called of <MagicMock name='send_anomaly' id='2120318385680'>>()

这是我要测试的功能:

def retrieve_anomalies(file):
try:
    if file.split(".")[-1] == "csv" and "anomalies" in file.split("/")[3]:

        print(file)
        s3 = boto3.client("s3")
        csvfile = s3.get_object(Bucket=file.split("/")[2],Key=file.split("/")3])

        csvcontent = csvfile["Body"].read().decode("utf-8").splitlines()
        csv_data = csv.DictReader(csvcontent)

        for row in csv_data:

            anomaly = {
                "msn": row["flight_id"][:5],
                "flight": row["flight_id"][5:]
            }

            send_anomaly(anomaly)

和测试功能:

@mock.patch("boto3.client", new=mock.MagicMock())
@mock.patch("lambda_out.lambda-out.send_anomaly")
@mock.patch("csv.DictReader")
def test_ok(mock_csv_reader, mock_send_ano):
    csv_data = [
        {
            "flight_id": "F8231V0001"
        }
    ]
    mock_csv_reader.return_value = csv_data
    file = "s3://bucket/anomalies.csv"

    lambda_out.retrieve_anomalies(file)

    anomaly = {
        "msn": "F8231",
        "flight": "V0001"
    }
    print(f"called: {str( mock_send_ano.called )}")
    print(f"call args: {str( mock_send_ano.call_args )}")
    assert mock_send_ano.assert_called()
    assert mock_send_ano.assert_called_with(anomaly)

【问题讨论】:

  • 你能展示更多的测试和它正在测试的功能吗
  • 确定我正在更新帖子

标签: python unit-testing mocking pytest


【解决方案1】:

当使用unittest.mock 中的assert_called 方法时,您需要省略assert 调用。你的代码就变成了:

@mock.patch("lambda_out.lambda-out.send_anomaly")
@mock.patch("csv.DictReader")
def test_ok(mock_csv_reader, mock_send_ano):
    csv_data = [
        {
            "flight_id": "F8231V0001"
        }
    ]
    mock_csv_reader.return_value = csv_data
    file = "s3://bucket/anomalies.csv"

    lambda_out.retrieve_anomalies(file)

    anomaly = {
        "msn": "F8231",
        "flight": "V0001"
    }
    print(f"called: {str( mock_send_ano.called )}")
    print(f"call args: {str( mock_send_ano.call_args )}")
    mock_send_ano.assert_called()
    mock_send_ano.assert_called_with(anomaly)

【讨论】:

  • 非常感谢您为我节省了这么多时间!我混淆了 unitest 和 pytest
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
相关资源
最近更新 更多