【发布时间】: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