gpt4 book ai didi

python - 模拟对象不可迭代

转载 作者:行者123 更新时间:2023-12-01 01:21:40 27 4
gpt4 key购买 nike

我目前正在尝试(但失败了)在我的简单应用程序上执行单元测试,该应用程序将数据发布到 MySQL 数据库。下面是我尝试运行的单元测试,不确定这是否能成功测试我的代码,但会出现 TypeError: 'Mock' object is not iterable

Unit_Test.py

from unittest import mock
from unittest.mock import patch, MagicMock
from unittest.mock import Mock


from source.src.scores import *


@mock.patch('source.src.scores.request')
def test_add_scores(self):
columns = ["Match_ID", "Home_Score", "Away_Score"]
values = [1, 1, 1]

expected_score = {columns[i]: values[i] for i in range(len(columns))}

with patch('source.src.scores.mysql.connector') as patch_connector:

cursor = Mock()
cursor.fetchone.return_value = values
cursor.column_names = columns
connect = Mock()
connect.cursor.return_value = cursor

patch_connector.connect.return_value = connect

with patch('source.src.scores.jsonify') as json:
json.return_value = expected_score

json_return, http_code = add_score()

assert patch_connector.connect.called
assert connect.cursor.called
assert connect.commit.called
assert cursor.fetchone.called
self.assertEqual(cursor.execute.call_count, 2)
self.assertDictEqual(expected_score, json_return)


if __name__ == '__main__':
test_add_scores()

分数.py

 def execute_query(cursor, qry):
print("Executing query...")
cursor.execute(qry)


def execute_query_json(cursor, qry, cnx):
print("Executing JSON query...")
cursor.execute(qry, (request.json['Match_ID'],
request.json['Home_Score'],
request.json['Away_Score'],
)
)
cnx.commit()


def add_score():
cnx = conn_db()
cursor = cnx.cursor()
print("Updating score")

execute_query_json(cursor, "INSERT INTO scores (Match_ID, Home_Score, Away_Score) VALUES (%s,%s,%s)", cnx)
execute_query(cursor, "SELECT * FROM scores WHERE Score_ID=" + str(cursor.lastrowid))
recs = extract_records(cursor)

return jsonify({'discipline':recs}), 201

非常感谢任何帮助

最佳答案

当您创建模拟时,有时必须让它知道如何响应一些预期的调用。举个例子:

class A(object):
def __init__(self):
self.items = []

如果您要创建一个模拟来代替 A 的实例,则当您尝试请求 .items 时,模拟将不会自动知道如何响应>。您可以通过将特定属性作为关键字传递给构造函数来告诉 Mock 返回什么来克服这个问题,如下所示:

mocked_a = Mock(items = [])

现在,当您调用 mock_a.items 时,您将得到一个空列表,因此迭代不会出错。

关于python - 模拟对象不可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53768225/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com