我目前正在尝试对我的简单应用程序进行单元测试,该应用程序将数据发布到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()
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
任何帮助都非常感激。
{k:v for k, v in zip(columns, values)}
(甚至是dict(zip(columns, vertices))
)来替代索引迭代。 - chepner