ADD file via upload

main
piw4f8lbj 2 months ago
parent d73f2fde1e
commit fcc7687aed

@ -0,0 +1,66 @@
import unittest
from unittest.mock import patch, MagicMock
import web # 假设你的Flask app文件命名为web.py
class StartCallTestCase(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
self.app.testing = True
@patch('web.pymysql.connect') # 模拟数据库连接
def test_start_call_rendering(self, mock_connect):
# 模拟数据库返回的数据
mock_cursor = MagicMock()
mock_cursor.fetchall.return_value = [
{'id': 1, 'name': 'Alice', 'points': 10.0},
{'id': 2, 'name': 'Bob', 'points': 5.0},
{'id': 3, 'name': 'Charlie', 'points': 2.0}
]
mock_connect.return_value.cursor.return_value = mock_cursor
# 发送GET请求到/start_call
response = self.app.get('/start_call')
# 验证响应状态
self.assertEqual(response.status_code, 200)
# 验证是否渲染了正确的内容
response_text = response.get_data(as_text=True)
self.assertIn('pstuents', response_text) # 检查渲染内容
@patch('web.pymysql.connect') # 模拟数据库连接
def test_weighted_random_selection(self, mock_connect):
# 模拟数据库返回的数据
mock_cursor = MagicMock()
mock_cursor.fetchall.return_value = [
{'id': 1, 'name': 'Alice', 'points': 10.0}, # Alice的权重最低
{'id': 2, 'name': 'Bob', 'points': 5.0}, # Bob的权重次之
{'id': 3, 'name': 'Charlie', 'points': 2.0} # Charlie的权重最高
]
mock_connect.return_value.cursor.return_value = mock_cursor
# 存储选择结果的字典
selection_count = {'Alice': 0, 'Bob': 0, 'Charlie': 0}
# 进行多次调用来验证随机性
for _ in range(100):
response = self.app.get('/start_call')
response_text = response.get_data(as_text=True)
# 统计每个学生的选择次数
if 'Alice' in response_text:
selection_count['Alice'] += 1
elif 'Bob' in response_text:
selection_count['Bob'] += 1
elif 'Charlie' in response_text:
selection_count['Charlie'] += 1
# 验证选择的相对概率
self.assertTrue(selection_count['Charlie'] > selection_count['Bob'])
self.assertTrue(selection_count['Bob'] > selection_count['Alice'])
if __name__ == '__main__':
unittest.main()
Loading…
Cancel
Save