python单元测试框架

ppt

pytest

allure

pytest的安装

pip install -U pytest
pip install -U pytest -i https://pypi.tuna.tsinghua.edu.cn/simple/
pytest -V

pytest的命名规则

  • 测试文件 test_ 开头或者 _test 结尾
  • 测试类 Test 开头
  • 测试方法/函数 test_ 开头
  • 注意:测试类中不能包含 __init__() 方法

pytest 命令行参数

pytest --help 帮助文档,查看所有命令行参数
pytest 文件名.py                执行单独一个pytest模块
pytest 文件名.py::类名           运行某个模块里面某个类
pytest 文件名.py::类名::方法名    运行某个模块里面某个类里面的方法
pytest -v 打印运行详细信息
pytest -s 打印输出信息
pytest -x 遇到失败的用例就停止执行
pytest --maxfail 遇到失败数为maxfail时,停止执行

pytest 的装置

  • 模块级: setup_module/teardown_module 模块始末,全局的(优先最高)
  • 函数级: setup_function/teardown_function 只对函数用例生效(不在类中)
  • 类级: setup_class/teardown_class 只在类中前后运行一次(在类中)
  • 方法级: setup_method/teardown_method 开始于方法始末(在类中)
  • 方法级: setup/teardown 运行在调用方法的前后

allure 安装

确认自己电脑上的java 环境

java -version

下载allure的程序包

https://repo1.maven.org/maven2/io/qameta/allure/allure-commandline/2.19.0/


image

安装allure-pytest 包

pip install allure-pytest -i https://pypi.tuna.tsinghua.edu.cn/simple/

生成报告数据

查看报告

  1. allure serve result

allure generate result -o report --clean
allure open -h 127.0.0.1 -p 8883 report


### 课后作业

1.实现一个学生管理系统
   a. 定义个学生的对象student.py,包含学生的姓名和分数两个属性
   b. 定义一个学生管理的student_manager.py ,实现学员的增加、删除、查询,计算学员的平均分数功能
2.  对这个学生管理系统进行单元测试,并且生成allure测试报告

student.py
```python

class Student:

    def __init__(self,name,score):
        pass

    def __str__(self):
        return

student_manager.py

class StudentManager:

    def __init__(self):
        pass

    def add(self, student: Student):
        """
        添加学员
        :param student:
        :return:
        """
        pass

    def remove(self, name: str):
        """
        删除学员
        :param name:
        :return:
        """
        pass

    def show_students(self):
        """
        显式所有的学员信息
        :return:
        """
        pass

    def average_score(self):
        """
        计算学员的平均成绩
        :return:
        """
        pass

课程源码

dgsut.zip (2.4 MB)

202041404121 阮达



姓名:倪灿烽 学号:202041412218





202041412221 阮凯林

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})"

StudentManager

class StudentManager:

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

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

    def remove(self, name):
        """
        删除学员
        :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
        num_students = len(self.students)

        for student in self.students:
            total_score += student.score

        if num_students > 0:
            average = total_score / num_students
            return average
        else:
            return 0.0

TestStudentManager

import pytest
from student import Student
from student_manager import StudentManager


class TestStudentManager:

    def setup_class(self):
        self.student_manager = StudentManager()

    def setup(self):
        print("开始计算")

    def teardown(self):
        print("结束计算")

    def teardown_class(self):
        print("结束测试")

    @pytest.mark.add
    @pytest.mark.run(order=1)
    @pytest.mark.parametrize("student, expect", [
        (Student("张三", 60), 1),
        (Student("李四", 70), 2),
        (Student("王五", 80), 3),
        (Student("赵六", 90), 4),
        (Student("孙七", 100), 5)
    ])
    def test_add_student(self, student, expect):
        self.student_manager.add(student)
        assert len(self.student_manager.students) == expect

    @pytest.mark.add
    @pytest.mark.run(order=2)
    @pytest.mark.parametrize("name, expect", [("周八", 5), ("孙七", 4), ("赵六", 3)])
    def test_remove_student(self, name, expect):
        self.student_manager.remove(name)
        assert len(self.student_manager.students) == expect

    @pytest.mark.add
    @pytest.mark.run(order=3)
    @pytest.mark.parametrize("expect", ["Student(name=张三, score=60)\nStudent(name=李四, score=70)\nStudent(name=王五, score=80)\n"])
    def test_show_students(self, capsys, expect):
        self.student_manager.show_students()
        captured = capsys.readouterr().out
        assert captured == expect

    @pytest.mark.add
    @pytest.mark.run(order=3)
    @pytest.mark.parametrize("expect", [70])
    def test_average_score(self, expect):
        average = self.student_manager.average_score()
        assert average == expect

202041413209 何宇明


image

image


image

202041412213 林梓豪
1696949161101




曾深 202041404224



202041412208蒋冠岳
image
student_manage.py

import pytest

from student import Student


class StudentManager:

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

    # @pytest.mark.parametrize("student", [(Student("alice", 90)), (Student("Bob", 85)), (Student("Charlie", 80))])
    def add(self, student: Student):
        """
        添加学员
        :param student:
        :return:
        """
        self.students.append(student)

    def remove(self, name: str):
        """
        删除学员
        :param name:
        :return:
        """
        self.students = list(filter(lambda student: student.name != name, self.students))

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

    # @pytest.mark.P0
    def average_score(self):
        """
        计算学员的平均成绩
        :return:
        """
        avg = 0
        cnt = 0
        for student in self.students:
            avg += student.score
            cnt += 1
        avg /= cnt
        print("平均成绩为:%ld" % avg)

test_student_manage.py

import pytest

from student_manage import StudentManager
from student import Student


class TestStudentManage:
    def setup_method(self):
        print("初始化")
        self.student_manage = StudentManager()

    @pytest.mark.add
    def test_add_student(self):
        student1 = Student("Alice", 90)
        student2 = Student("Bob", 100)
        student3 = Student("Charlie", 90)
        self.student_manage.add(student1)
        self.student_manage.add(student2)
        self.student_manage.add(student3)
        # self.student_manage.remove("Alice")
        self.student_manage.show_students()

    @pytest.mark.show
    def test_show_student(self):
        student1 = Student("Alice", 90)
        student2 = Student("Bob", 100)
        student3 = Student("Charlie", 90)
        self.student_manage.add(student1)
        self.student_manage.add(student2)
        self.student_manage.add(student3)
        self.student_manage.show_students()

    @pytest.mark.remove
    def test_remove_student(self):
        student1 = Student("Alice", 90)
        student2 = Student("Bob", 100)
        student3 = Student("Charlie", 90)
        self.student_manage.add(student1)
        self.student_manage.add(student2)
        self.student_manage.add(student3)
        self.student_manage.remove("Alice")
        self.student_manage.show_students()

    @pytest.mark.average
    def test_average_score(self):
        student1 = Student("Alice", 90)
        student2 = Student("Bob", 100)
        student3 = Student("Charlie", 90)
        self.student_manage.add(student1)
        self.student_manage.add(student2)
        self.student_manage.add(student3)
        self.student_manage.average_score()

202044101107黄亦斌
屏幕截图 2023-10-10 224330
屏幕截图 2023-10-10 224658

202041404124王沛维

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})"

class StudentManager:

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

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

    def remove(self, name):
        """
        删除学员
        :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
        num_students = len(self.students)

        for student in self.students:
            total_score += student.score

        if num_students > 0:
            average = total_score / num_students
            return average
        else:
            return 0.0
import pytest
from student import Student
from student import StudentManager


class TestStudentManager:

    def setup_class(self):
        self.student_manager = StudentManager()

    def setup(self):
        print("开始计算")

    def teardown(self):
        print("结束计算")

    def teardown_class(self):
        print("结束测试")

    @pytest.mark.add
    @pytest.mark.run(order=1)
    @pytest.mark.parametrize("student, expect", [
        (Student("张三", 60), 1),
        (Student("李四", 70), 2),
        (Student("王五", 80), 3),
        (Student("赵六", 90), 4),
        (Student("孙七", 100), 5)
    ])
    def test_add_student(self, student, expect):
        self.student_manager.add(student)
        assert len(self.student_manager.students) == expect

    @pytest.mark.add
    @pytest.mark.run(order=2)
    @pytest.mark.parametrize("name, expect", [("周八", 5), ("孙七", 4), ("赵六", 3)])
    def test_remove_student(self, name, expect):
        self.student_manager.remove(name)
        assert len(self.student_manager.students) == expect

    @pytest.mark.add
    @pytest.mark.run(order=3)
    @pytest.mark.parametrize("expect", ["Student(name=张三, score=60)\nStudent(name=李四, score=70)\nStudent(name=王五, score=80)\n"])
    def test_show_students(self, capsys, expect):
        self.student_manager.show_students()
        captured = capsys.readouterr().out
        assert captured == expect

    @pytest.mark.add
    @pytest.mark.run(order=3)
    @pytest.mark.parametrize("expect", [70])
    def test_average_score(self, expect):
        average = self.student_manager.average_score()
        assert average == expect




202041404129 詹佳润

python

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

    def __str__(self):
        return f"Name: {self.name}, Score: {self.score}"

# student_manager.py
class StudentManager:
    def __init__(self):
        self.students = []

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

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

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

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

# test_student_manager.py
import pytest
from pytest_study.student import Student
from pytest_study.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_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_empty(student_manager):
    assert student_manager.average_score() == 0


def test_average_score(student_manager):
    student1 = Student("Charlie", 75)
    student2 = Student("David", 88)
    student_manager.add(student1)
    student_manager.add(student2)
    assert student_manager.average_score() == pytest.approx(81.5, 0.01)

刘尚杰 202041412216

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})"
class ManageStudent:

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

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

    def remove(self, name):
        """
        删除学员
        :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 = total_score + student.score
        length = len(self.students)
        return total_score / length
import pytest
from student import Student
from manage_student import ManageStudent


class TestStudentManager:

    def setup_class(self):
        self.manage_student = ManageStudent()

    def setup(self):
        print("开始计算")

    def teardown(self):
        print("结束计算")

    def teardown_class(self):
        print("结束测试")

    @pytest.mark.add
    @pytest.mark.run(order=1)
    @pytest.mark.parametrize("student, expect", [
        (Student("张一", 60), 1),
        (Student("张二", 70), 2),
        (Student("张三", 80), 3),
        (Student("张四", 90), 4),
        (Student("张五", 100), 5)
    ])
    def test_add_student(self, student, expect):
        self.manage_student.add(student)
        assert len(self.manage_student.students) == expect

    @pytest.mark.add
    @pytest.mark.run(order=2)
    @pytest.mark.parametrize("name, expect", [("张五", 4), ("张四", 3), ("张三", 2)])
    def test_remove_student(self, name, expect):
        self.manage_student.remove(name)
        assert len(self.manage_student.students) == expect

    @pytest.mark.add
    @pytest.mark.run(order=3)
    @pytest.mark.parametrize("expect", ["Student(name=张一, score=60)\nStudent(name=张二, score=70)\n"])
    def test_show_students(self, capsys, expect):
        self.manage_student.show_students()
        captured = capsys.readouterr().out
        assert captured == expect

    @pytest.mark.add
    @pytest.mark.run(order=3)
    @pytest.mark.parametrize("expect", [65])
    def test_average_score(self, expect):
        average = self.manage_student.average_score()
        assert average == expect

202041412126 于智康
student.py
image
student_manager.py
image
image
test_student_manager.py


202041404213 刘建升


2

image




姓名:聂振枫 学号:202041404216

姓名:翁开锋, 学号:202041412223
image


import allure
import pytest

from Student import Student
from StudentManager import StudentManager


@allure.epic("学生管理系统")
@allure.feature("学生管理")
class TestStudent:
    @classmethod
    def setup_class(cls) -> None:
        cls.manager = StudentManager()

    def setup(self):
        student = Student("小明", 100)
        self.manager.students.append(student)
        student = Student("小红", 50)
        self.manager.students.append(student)
        student = Student("小李", 88)
        self.manager.students.append(student)
        student = Student("小花", 40)
        self.manager.students.append(student)

    def teardown(self):
        self.manager.students.clear()

    @allure.story("添加学生")
    def test_add_student(self):
        alice = Student("Alice", 90)
        len1 = len(self.manager.students)
        self.manager.add(alice)
        assert len1+1 == len(self.manager.students)

    @allure.story("删除学生")
    def test_remove_student(self):
        alice = Student("Alice1", 90)
        self.manager.add(alice)
        len1 = len(self.manager.students)
        self.manager.remove(alice.name)
        assert len1-1 == len(self.manager.students)

    @allure.story("显示学生")
    def test_show_student(self, capfd):
        self.manager.show_students()
        out, _ = capfd.readouterr()
        a = "学生的名字是小明,成绩是100\n学生的名字是小红,成绩是50\n学生的名字是小李,成绩是88\n学生的名字是小花,成绩是40\n"
        assert a == out

    @allure.story("计算平均分数")
    # @pytest.mark.parametrize("b" , 69.5)
    def test_calculate_average_score(self):

        average_score = self.manager.average_score()
        assert average_score == 69.5

    @classmethod
    def teardown_class(cls) -> None:
        cls.manager = None

姓名:胡福生 学号:202041404204
Student.py

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

    def __str__(self):
        return f'姓名:{self.name},分数:{self.score}'

student_manager.py

from pytest_study.student import Student

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

    #添加学员
    def add(self, student:Student):
        self.students.append(student)

    #删除学员
    def remove(self, name:str):
        for student in self.students:
            if student.name == name:
                self.students.remove(student)
                return True
        return False

    #查询学员
    def select(self, name:str):
        for student in self.students:
            if student.name == name:
                return student
        return None

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

    #计算学员的平均成绩
    def average_score(self):
        total_score = 0
        for student in self.students:
            total_score += student.score
        if len(self.students)>0:
            return total_score / len(self.students)
        else:
            return 0

test_student_manager.py

import allure
import pytest
from pytest_study.student import Student
from pytest_study.student_manager import StudentManager

@allure.feature("学生管理系统")
class TestStudentManager:
    @allure.story("添加学生")
    @pytest.mark.parametrize("name, score", [("张三", 66), ])
    def test_add(self, name, score):
        manager = StudentManager()
        student = Student(name, score)
        manager.add(student)
        assert len(manager.students) == 1

    @allure.story("删除学生")
    @pytest.mark.parametrize("name, score", [("张三", 66), ])
    def test_remove(self, name, score):
        manager = StudentManager()
        student = Student(name, score)
        manager.add(student)
        manager.remove("张三")
        assert len(manager.students) == 0

    @allure.story("查询学生")
    @pytest.mark.parametrize("name, score", [("张三", 66), ])
    def test_select(self, name, score):
        manager = StudentManager()
        student = Student(name, score)
        manager.add(student)
        student = manager.select("张三")
        assert student.name == "张三"
        assert student.score == 66

    @allure.story("显示所有的学员信息")
    def test_show_students(self):
        manager = StudentManager()
        student1 = Student("张三", 66)
        student2 = Student("李四", 88)
        manager.add(student1)
        manager.add(student2)
        shows = manager.show_students()
        assert shows == [student1, student2]

    @allure.story("计算学员的平均成绩")
    def test_average_score(self):
        manager = StudentManager()
        student1 = Student("张三", 66)
        student2 = Student("李四", 88)
        manager.add(student1)
        manager.add(student2)
        average = manager.average_score()
        assert average == 77

学号 202041404110 名字 胡鑫

student.py:
image

student_manager.py:

class StudentManager:

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

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

    def remove(self, name):
        """
        删除学员
        :param name: 学员姓名
        :return: 删除是否成功的布尔值
        """
        for student in self.students:
            if student.name == name:
                self.students.remove(student)
                return True  # 返回True表示成功删除
        return False  # 返回False表示未找到要删除的学员



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

    def calculate_average_score(self):
        """
        计算学员的平均分数
        :return: 平均分数
        """
        total_score = sum([student.score for student in self.students])
        average_score = total_score / len(self.students)
        return average_score

test_student_manager.py:

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_remove_student(student_manager):
    student = Student("Bob", 85)
    student_manager.add(student)
    assert student_manager.remove("Bob") == True
    assert len(student_manager.students) == 0

def test_show_students(capsys, student_manager):
    student1 = Student("Charlie", 75)
    student2 = Student("David", 88)
    student_manager.add(student1)
    student_manager.add(student2)
    student_manager.show_students()
    captured = capsys.readouterr()
    assert "Name: Charlie, Score: 75" in captured.out
    assert "Name: David, Score: 88" in captured.out

结果