python单元测试框架

202041413221 叶磊
student

class Student:
    def __init__(self,name,score):
        self.name = name
        self.score = score

    def __str__(self):
        return f"Student(name={self.name}, score={self.score})"

student_manager

from student import Student


class StudentManager:

    def __init__(self):
        self.students = []

    def add(self, student):
        """
        添加学员
        :param student:
        :return:
        """
        self.students.append(student)

    def remove(self, name: str):
        """
        删除学员
        :param name:
        :return:
        """
        for student in self.students:
            if student.name == name:
                self.students.remove(student)
                break

    def show_students(self):
        """
        显式所有的学员信息
        :return:
        """
        for student in self.students:
            print(student)

    def average_score(self):
        """
        计算学员的平均成绩
        :return:
        """
        total_score = 0
        for student in self.students:
            total_score += student.score

        if len(self.students) > 0:
            average_score = total_score / len(self.students)
            return average_score
        else:
            return 0

test_student_manager

import pytest
from student import Student
from student_manager import StudentManager


@pytest.fixture
def student_manager():
    return StudentManager()


def test_add_student(student_manager):
    student = Student("Alice", 90)
    student_manager.add(student)
    assert len(student_manager.students) == 1

def test_show(student_manager):
    student_manager.show_students()

def test_remove_student(student_manager):
    student = Student("Bob", 85)
    student_manager.add(student)
    student_manager.remove("Bob")
    assert len(student_manager.students) == 0

def test_average_score(student_manager):
    student1 = Student("Charlie", 70)
    student2 = Student("David", 80)
    student_manager.add(student1)
    student_manager.add(student2)
    assert student_manager.average_score() == 75

image

201941412218 魏峰
1697725023993

1697725111956