我有一个简单的应用程序,可以使用javascript和python / flask将分数读写到MySQL数据库。我想知道如何最好地隔离应用程序的不同单元进行测试。
JavaScript:
我将如何对此进行模拟,还需要在仅JavaScript的测试套件中进行特定的测试?
$scope.create_score = function () {
console.log("logged");
var scoreData = new scoreObj($scope.match_ID,$scope.Home_Score, $scope.Away_Score);
if ($scope.Home_Score >= 0 && $scope.Away_Score >= 0) {
$http(
{
method: 'POST',
url: "/api/v1/scores",
data: scoreData
}
).then(function successCallback(response) {
alert("Success");
}, function errorCallback(response) {
alert("Sorry, there was a problem!");
}
)
} else {
alert("Sorry, score can not be negative!");
}
};
Python:
这些是我需要测试的主要功能。
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)
return "ok"
测试:
我将如何整合要在不同测试中使用的不同模拟方法(上下文管理器/修饰器)?
不同的模拟方法的用例是什么,或者它们可以互换?
我将如何创建用于不同模拟对象的假json /预期分数数据?
from unittest.mock import patch, MagicMock
from unittest.mock import Mock
import unittest
from source.src import scores
from source.src.scores import add_score
import source
@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))}
json = {columns[i]:values[i] for i in range(len(columns)-1)}
with patch('source.src.scores.mysql.connector') as patch_connector:
self.assertIs(scores.mysql.connector, 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
new_score = 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, new_score)
if __name__ == '__main__':
test_add_scores()
非常感谢你们,真的让我感到困惑。