简体   繁体   English

即使调用了模拟,Python 模拟断言也会失败

[英]Python mock assert called fails even if mock called

I'm using mock and pytest to run several unit test on my project but I'm facing a very strange error.我正在使用 mock 和 pytest 在我的项目上运行多个单元测试,但我面临一个非常奇怪的错误。

In a specific test in mock a function called in the function I'm testing and I want to check that this function is called with specific parameters.在模拟中的特定测试中,我正在测试的函数中调用了一个函数,我想检查是否使用特定参数调用了该函数。 But the mock_function.assert_called() fails.但是 mock_function.assert_called() 失败了。

To debug it, I add the following lines :为了调试它,我添加了以下几行:

    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)

In the output console I got :在输出控制台中,我得到了:

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

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

And I still get this error我仍然收到此错误

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

Here is the function I want to test :这是我要测试的功能:

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)

and the test function :和测试功能:

@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)

When using the assert_called methods from unittest.mock you need to omit the assert calls.使用unittest.mockassert_called方法时,您需要省略assert调用。 Your code simply becomes:您的代码简单地变为:

@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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM