跳转至

Python基础测试用例

测试目标: 验证Python基础语法和功能的正确性 测试类型: 单元测试、集成测试 涉及组件: 数据类型、控制流、函数、类、异常处理


📋 测试概述

测试目标

  1. 语法测试: 验证Python语法正确性
  2. 功能测试: 验证Python内置功能
  3. 性能测试: 评估代码执行效率
  4. 边界测试: 测试边界条件

测试环境

  • Python版本: 3.8+
  • 测试框架: pytest
  • 类型检查: mypy(可选)

🧪 测试用例列表

1. 数据类型测试

测试用例1.1: 数字类型

测试目标: 验证数字类型操作

测试代码:

Python
import pytest

def test_integer_operations():
    """测试整数操作"""
    # 基本运算
    assert 2 + 3 == 5  # assert断言条件为真,否则抛出AssertionError
    assert 10 - 4 == 6
    assert 3 * 4 == 12
    assert 15 // 4 == 3
    assert 15 / 4 == 3.75
    assert 15 % 4 == 3

    # 幂运算
    assert 2 ** 3 == 8

    # 比较运算
    assert 5 > 3
    assert 5 >= 5
    assert 3 < 5
    assert 3 <= 3
    assert 5 == 5
    assert 5 != 3

    print("✓ 整数操作测试通过")

def test_float_operations():
    """测试浮点数操作"""
    # 基本运算
    assert abs(2.5 + 3.7 - 6.2) < 1e-10
    assert abs(10.5 - 4.2 - 6.3) < 1e-10
    assert abs(2.5 * 4.0 - 10.0) < 1e-10

    # 浮点数比较
    assert abs(0.1 + 0.2 - 0.3) < 1e-10

    print("✓ 浮点数操作测试通过")

def test_number_conversions():
    """测试数字类型转换"""
    # 整数转浮点数
    assert float(5) == 5.0

    # 浮点数转整数
    assert int(5.7) == 5
    assert int(5.3) == 5

    # 字符串转数字
    assert int("42") == 42
    assert float("3.14") == 3.14

    # 数字转字符串
    assert str(42) == "42"
    assert str(3.14) == "3.14"

    print("✓ 数字类型转换测试通过")

预期结果: 所有断言通过


测试用例1.2: 字符串操作

测试目标: 验证字符串操作

测试代码:

Python
def test_string_operations():
    """测试字符串操作"""
    # 字符串拼接
    assert "Hello" + " " + "World" == "Hello World"
    assert "Hello " * 3 == "Hello Hello Hello "

    # 字符串长度
    assert len("Hello") == 5

    # 字符串索引
    assert "Hello"[0] == "H"
    assert "Hello"[-1] == "o"  # 负索引[-1]表示访问序列的最后一个元素
    assert "Hello"[1:4] == "ell"

    # 字符串查找
    assert "Hello World".find("World") == 6
    assert "Hello World".find("Python") == -1

    # 字符串替换
    assert "Hello World".replace("World", "Python") == "Hello Python"

    # 字符串分割
    assert "a,b,c".split(",") == ["a", "b", "c"]

    # 字符串大小写
    assert "hello".upper() == "HELLO"
    assert "HELLO".lower() == "hello"
    assert "hello world".title() == "Hello World"

    # 字符串去除空格
    assert "  hello  ".strip() == "hello"

    print("✓ 字符串操作测试通过")

def test_string_formatting():
    """测试字符串格式化"""
    name = "Alice"
    age = 25

    # f-string
    assert f"My name is {name} and I'm {age} years old" == \
           "My name is Alice and I'm 25 years old"

    # format方法
    assert "My name is {} and I'm {} years old".format(name, age) == \
           "My name is Alice and I'm 25 years old"

    # %格式化
    assert "My name is %s and I'm %d years old" % (name, age) == \
           "My name is Alice and I'm 25 years old"

    print("✓ 字符串格式化测试通过")

预期结果: 所有断言通过


测试用例1.3: 列表操作

测试目标: 验证列表操作

测试代码:

Python
def test_list_operations():
    """测试列表操作"""
    # 创建列表
    lst = [1, 2, 3, 4, 5]

    # 列表长度
    assert len(lst) == 5

    # 列表索引
    assert lst[0] == 1
    assert lst[-1] == 5
    assert lst[1:4] == [2, 3, 4]

    # 列表追加
    lst.append(6)
    assert lst == [1, 2, 3, 4, 5, 6]

    # 列表插入
    lst.insert(0, 0)
    assert lst == [0, 1, 2, 3, 4, 5, 6]

    # 列表删除
    lst.remove(0)
    assert lst == [1, 2, 3, 4, 5, 6]

    # 列表弹出
    lst.pop()
    assert lst == [1, 2, 3, 4, 5]

    # 列表排序
    lst2 = [3, 1, 4, 2, 5]
    lst2.sort()
    assert lst2 == [1, 2, 3, 4, 5]

    # 列表反转
    lst3 = [1, 2, 3, 4, 5]
    lst3.reverse()
    assert lst3 == [5, 4, 3, 2, 1]

    # 列表推导
    squares = [x**2 for x in range(5)]  # 列表推导式,简洁地从可迭代对象创建新列表
    assert squares == [0, 1, 4, 9, 16]

    print("✓ 列表操作测试通过")

def test_list_methods():
    """测试列表方法"""
    # 列表连接
    assert [1, 2] + [3, 4] == [1, 2, 3, 4]

    # 列表重复
    assert [1, 2] * 2 == [1, 2, 1, 2]

    # 列表包含
    assert 3 in [1, 2, 3, 4]
    assert 5 not in [1, 2, 3, 4]

    # 列表计数
    assert [1, 2, 2, 3].count(2) == 2

    # 列表索引
    assert [1, 2, 3, 4].index(3) == 2

    # 列表清空
    lst = [1, 2, 3]
    lst.clear()
    assert lst == []

    print("✓ 列表方法测试通过")

预期结果: 所有断言通过


测试用例1.4: 字典操作

测试目标: 验证字典操作

测试代码:

Python
def test_dict_operations():
    """测试字典操作"""
    # 创建字典
    d = {"name": "Alice", "age": 25}

    # 字典长度
    assert len(d) == 2

    # 字典访问
    assert d["name"] == "Alice"
    assert d.get("age") == 25
    assert d.get("city", "Unknown") == "Unknown"

    # 字典添加
    d["city"] = "Beijing"
    assert d["city"] == "Beijing"

    # 字典更新
    d.update({"age": 26, "country": "China"})
    assert d["age"] == 26
    assert d["country"] == "China"

    # 字典删除
    del d["country"]
    assert "country" not in d

    # 字典键
    assert "name" in d
    assert "country" not in d

    # 字典键值
    assert set(d.keys()) == {"name", "age", "city"}
    assert set(d.values()) >= {"Alice", 26, "Beijing"}

    # 字典项
    assert ("name", "Alice") in d.items()

    print("✓ 字典操作测试通过")

def test_dict_comprehension():
    """测试字典推导"""
    # 创建字典
    squares = {x: x**2 for x in range(5)}
    assert squares == {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

    # 字典过滤
    d = {"a": 1, "b": 2, "c": 3, "d": 4}
    filtered = {k: v for k, v in d.items() if v % 2 == 0}
    assert filtered == {"b": 2, "d": 4}

    print("✓ 字典推导测试通过")

预期结果: 所有断言通过


2. 控制流测试

测试用例2.1: 条件语句

测试目标: 验证条件语句

测试代码:

Python
def test_if_statement():
    """测试if语句"""
    x = 10

    # if语句
    if x > 5:
        result = "greater"
    else:
        result = "less or equal"

    assert result == "greater"

    # if-elif-else
    if x > 15:
        result = "greater than 15"
    elif x > 10:
        result = "greater than 10"
    elif x > 5:
        result = "greater than 5"
    else:
        result = "less or equal to 5"

    assert result == "greater than 5"

    # 三元运算符
    result = "even" if x % 2 == 0 else "odd"
    assert result == "even"

    print("✓ if语句测试通过")

预期结果: 所有断言通过


测试用例2.2: 循环语句

测试目标: 验证循环语句

测试代码:

Python
def test_for_loop():
    """测试for循环"""
    # 基本for循环
    result = []
    for i in range(5):
        result.append(i)
    assert result == [0, 1, 2, 3, 4]

    # for循环遍历列表
    result = []
    for item in [1, 2, 3, 4, 5]:
        result.append(item * 2)
    assert result == [2, 4, 6, 8, 10]

    # for循环遍历字典
    d = {"a": 1, "b": 2, "c": 3}
    keys = []
    values = []
    for key, value in d.items():
        keys.append(key)
        values.append(value)

    assert set(keys) == {"a", "b", "c"}
    assert set(values) == {1, 2, 3}

    # enumerate
    result = []
    for index, value in enumerate([10, 20, 30]):  # enumerate()同时获取索引和值,避免手动计数
        result.append((index, value))
    assert result == [(0, 10), (1, 20), (2, 30)]

    print("✓ for循环测试通过")

def test_while_loop():
    """测试while循环"""
    # 基本while循环
    count = 0
    result = []
    while count < 5:
        result.append(count)
        count += 1

    assert result == [0, 1, 2, 3, 4]

    # while循环with break
    count = 0
    result = []
    while True:
        result.append(count)
        count += 1
        if count >= 3:
            break

    assert result == [0, 1, 2]

    # while循环with continue
    count = 0
    result = []
    while count < 5:
        count += 1
        if count % 2 == 0:
            continue
        result.append(count)

    assert result == [1, 3, 5]

    print("✓ while循环测试通过")

预期结果: 所有断言通过


3. 函数测试

测试用例3.1: 函数定义和调用

测试目标: 验证函数定义和调用

测试代码:

Python
def test_function_definition():
    """测试函数定义"""
    # 无参数函数
    def greet():
        return "Hello, World!"

    assert greet() == "Hello, World!"

    # 有参数函数
    def greet_name(name):
        return f"Hello, {name}!"

    assert greet_name("Alice") == "Hello, Alice!"

    # 默认参数
    def greet_default(name="World"):
        return f"Hello, {name}!"

    assert greet_default() == "Hello, World!"
    assert greet_default("Bob") == "Hello, Bob!"

    # 可变参数
    def sum_all(*args):  # *args接收任意数量的位置参数
        return sum(args)

    assert sum_all(1, 2, 3, 4, 5) == 15

    # 关键字参数
    def print_info(**kwargs):  # **kwargs接收任意数量的关键字参数
        return kwargs

    info = print_info(name="Alice", age=25)
    assert info == {"name": "Alice", "age": 25}

    print("✓ 函数定义测试通过")

def test_lambda_function():
    """测试lambda函数"""
    # lambda函数
    square = lambda x: x ** 2  # lambda定义匿名函数,适用于简单的单行表达式
    assert square(5) == 25

    # lambda函数with多个参数
    add = lambda x, y: x + y
    assert add(3, 4) == 7

    # lambda函数with条件
    is_even = lambda x: x % 2 == 0
    assert is_even(4) == True
    assert is_even(5) == False

    print("✓ lambda函数测试通过")

预期结果: 所有断言通过


测试用例3.2: 高阶函数

测试目标: 验证高阶函数

测试代码:

Python
def test_map_function():
    """测试map函数"""
    # map函数
    numbers = [1, 2, 3, 4, 5]
    squared = list(map(lambda x: x**2, numbers))  # map()对每个元素应用函数,返回迭代器
    assert squared == [1, 4, 9, 16, 25]

    # mapwith多个可迭代对象
    numbers1 = [1, 2, 3]
    numbers2 = [4, 5, 6]
    summed = list(map(lambda x, y: x + y, numbers1, numbers2))
    assert summed == [5, 7, 9]

    print("✓ map函数测试通过")

def test_filter_function():
    """测试filter函数"""
    # filter函数
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    even = list(filter(lambda x: x % 2 == 0, numbers))  # filter()按条件筛选元素,返回迭代器
    assert even == [2, 4, 6, 8, 10]

    odd = list(filter(lambda x: x % 2 != 0, numbers))
    assert odd == [1, 3, 5, 7, 9]

    print("✓ filter函数测试通过")

def test_reduce_function():
    """测试reduce函数"""
    from functools import reduce

    # reduce函数
    numbers = [1, 2, 3, 4, 5]
    total = reduce(lambda x, y: x + y, numbers)
    assert total == 15

    # reducewith初始值
    total = reduce(lambda x, y: x * y, numbers, 1)
    assert total == 120

    print("✓ reduce函数测试通过")

预期结果: 所有断言通过


4. 类和对象测试

测试用例4.1: 类定义

测试目标: 验证类定义和对象创建

测试代码:

Python
def test_class_definition():
    """测试类定义"""
    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age

        def greet(self):
            return f"Hello, my name is {self.name}"

        def __str__(self):  # __str__定义对象的可读字符串表示
            return f"Person(name={self.name}, age={self.age})"

    # 创建对象
    person = Person("Alice", 25)

    # 访问属性
    assert person.name == "Alice"
    assert person.age == 25

    # 调用方法
    assert person.greet() == "Hello, my name is Alice"

    # __str__方法
    assert str(person) == "Person(name=Alice, age=25)"

    print("✓ 类定义测试通过")

def test_inheritance():
    """测试继承"""
    class Animal:
        def __init__(self, name):
            self.name = name

        def speak(self):
            return "Some sound"

    class Dog(Animal):
        def speak(self):
            return "Woof!"

    class Cat(Animal):
        def speak(self):
            return "Meow!"

    # 创建对象
    dog = Dog("Buddy")
    cat = Cat("Whiskers")

    # 继承属性
    assert dog.name == "Buddy"
    assert cat.name == "Whiskers"

    # 重写方法
    assert dog.speak() == "Woof!"
    assert cat.speak() == "Meow!"

    print("✓ 继承测试通过")

预期结果: 所有断言通过


5. 异常处理测试

测试用例5.1: 异常捕获

测试目标: 验证异常处理

测试代码:

Python
def test_exception_handling():
    """测试异常处理"""
    # try-except
    try:
        result = 10 / 0
    except ZeroDivisionError:
        result = "Division by zero"

    assert result == "Division by zero"

    # 多个except
    try:
        result = int("abc")
    except ValueError:
        result = "Invalid value"
    except TypeError:
        result = "Type error"

    assert result == "Invalid value"

    # else和finally
    try:
        result = 10 / 2
    except ZeroDivisionError:
        result = "Division by zero"
    else:
        result = "Success"
    finally:
        final = "Finally executed"

    assert result == "Success"
    assert final == "Finally executed"

    print("✓ 异常处理测试通过")

def test_raise_exception():
    """测试抛出异常"""
    # 自定义异常
    class CustomError(Exception):
        pass

    # 抛出异常
    def check_value(value):
        if value < 0:
            raise ValueError("Value must be non-negative")
        if value > 100:
            raise CustomError("Value too large")
        return True

    # 测试正常情况
    assert check_value(50) == True

    # 测试ValueError
    try:
        check_value(-1)
        assert False, "Should raise ValueError"
    except ValueError as e:
        assert str(e) == "Value must be non-negative"

    # 测试CustomError
    try:
        check_value(101)
        assert False, "Should raise CustomError"
    except CustomError as e:
        assert str(e) == "Value too large"

    print("✓ 抛出异常测试通过")

预期结果: 所有断言通过


📊 测试执行

运行所有测试

Bash
# 运行所有测试
pytest tests/test_python_basics.py -v

# 运行特定测试
pytest tests/test_python_basics.py::test_integer_operations -v

# 生成覆盖率报告
pytest tests/test_python_basics.py --cov=python_basics --cov-report=html

✅ 验证方法

1. 自动化验证

  • 运行所有测试用例
  • 检查断言是否通过
  • 记录测试结果

2. 类型检查

  • 使用mypy进行类型检查
  • 确保类型注解正确
  • 修复类型错误

3. 代码质量

  • 使用pylint检查代码质量
  • 使用black格式化代码
  • 使用flake8检查代码风格

📝 测试报告

测试报告应包含:

  1. 测试概览
  2. 测试用例数量
  3. 通过/失败统计
  4. 代码覆盖率

  5. 详细结果

  6. 每个测试用例的结果
  7. 失败测试的错误信息
  8. 性能指标

  9. 问题分析

  10. 失败原因分析
  11. 改进建议
  12. 后续计划

测试完成标准: 所有测试用例通过 推荐测试频率: 每次代码更新 测试维护周期: 每周