- 以下是使用Python的unittest模块对代码进行单元测试的示例:
import unittest
from unittest.mock import patch
from app import app, validate_date
class TestApp(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
def test_validate_date_valid(self):
self.assertTrue(validate_date('2024-11-10'))
def test_validate_date_invalid_format(self):
with self.assertRaises(ValueError) as context:
validate_date('2024/11/10')
self.assertEqual(str(context.exception), "日期格式不正确,请使用YYYY-MM-DD格式。")
def test_validate_date_invalid_value(self):
with self.assertRaises(ValueError) as context:
validate_date('2024-13-32')
self.assertEqual(str(context.exception), "日期格式不正确,请使用YYYY-MM-DD格式。")
@patch('app.hive.connect')
def test_get_orders_success(self, mock_connect):
mock_cursor = mock_connect.return_value.cursor.return_value
mock_cursor.fetchall.return_value = [(1, '2024-11-10', 100.0)]
response = self.app.get('/api/orders?start_date=2024-11-10&end_date=2024-11-10')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get_json(), [{"order_id": 1, "order_date": "2024-11-10", "order_amount": 100.0}])
def test_get_orders_missing_parameters(self):
response = self.app.get('/api/orders')
self.assertEqual(response.status_code, 400)
self.assertEqual(response.get_json()['description'], "日期格式不正确,请使用YYYY-MM-DD格式。")
@patch('app.hive.connect')
def test_get_orders_database_error(self, mock_connect):
mock_connect.side_effect = hive.DatabaseError("模拟数据库错误")
response = self.app.get('/api/orders?start_date=2024-11-10&end_date=2024-11-10')
self.assertEqual(response.status_code, 500)
self.assertEqual(response.get_json()['description'], "Hive数据库错误: 模拟数据库错误")
@patch('app.hive.connect')
def test_get_orders_general_error(self, mock_connect):
mock_connect.side_effect = Exception("模拟一般错误")
response = self.app.get('/api/orders?start_date=2024-11-10&end_date=2024-11-10')
self.assertEqual(response.status_code, 500)
self.assertEqual(response.get_json()['description'], "其他错误: 模拟一般错误")
if __name__ == '__main__':
unittest.main()