You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
92 lines
2.6 KiB
92 lines
2.6 KiB
import os
|
|
import pytest
|
|
import django
|
|
import json
|
|
from asgiref.sync import sync_to_async
|
|
from channels.testing import WebsocketCommunicator
|
|
from channels.layers import get_channel_layer
|
|
from channels.db import database_sync_to_async # 确保导入
|
|
from .consumers import ClassroomConsumer
|
|
from .models import Students
|
|
|
|
# 设置 Django 设置模块
|
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Rollcall_applet.settings')
|
|
django.setup()
|
|
|
|
@database_sync_to_async
|
|
def create_student(sid, name, score):
|
|
return Students.objects.create(sid=sid, name=name, score=score)
|
|
|
|
@database_sync_to_async
|
|
def get_student(sid):
|
|
return Students.objects.get(sid=sid)
|
|
|
|
@database_sync_to_async
|
|
def update_student_score(sid, new_score):
|
|
student = Students.objects.get(sid=sid)
|
|
student.score = new_score
|
|
student.save()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pick_student():
|
|
# 创建一些学生
|
|
await create_student("1", "Student 1", 10)
|
|
await create_student("2", "Student 2", 0)
|
|
await create_student("3", "Student 3", -5)
|
|
|
|
consumer = ClassroomConsumer()
|
|
await consumer.connect()
|
|
|
|
chosen_student = await consumer.pick_student()
|
|
|
|
assert chosen_student is not None
|
|
assert chosen_student.sid in ["1", "2", "3"]
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_exemption_card_used():
|
|
# 创建一个学生
|
|
student = await create_student("1", "Student 1", 10)
|
|
|
|
consumer = ClassroomConsumer()
|
|
await consumer.connect()
|
|
|
|
# 模拟接收豁免卡使用信息
|
|
await consumer.receive(text_data=json.dumps({
|
|
'action': 'use_exemption_card',
|
|
'studentId': student.sid,
|
|
'newScore': 20,
|
|
'studentName': student.name,
|
|
}))
|
|
|
|
updated_student = await get_student(student.sid)
|
|
assert updated_student.score == 20
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_student_message():
|
|
student = await create_student("1", "Student 1", 10)
|
|
|
|
consumer = ClassroomConsumer()
|
|
await consumer.connect()
|
|
|
|
# 发送学生消息
|
|
await consumer.send_student_message(student)
|
|
|
|
# 验证消息发送到学生组
|
|
channel_layer = get_channel_layer()
|
|
message = await channel_layer.receive(consumer.student_group)
|
|
assert message['type'] == 'student_message'
|
|
assert message['message']['name'] == student.name
|
|
assert message['message']['student_id'] == student.sid
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_update_student_score():
|
|
student = await create_student("1", "Student 1", 10)
|
|
|
|
consumer = ClassroomConsumer()
|
|
await consumer.connect()
|
|
|
|
await update_student_score(student.sid, 30)
|
|
|
|
updated_student = await get_student(student.sid)
|
|
assert updated_student.score == 30
|