簡體   English   中英

即使調用了模擬,Python 模擬斷言也會失敗

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

我正在使用 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)

使用unittest.mockassert_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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM