Python自动化测试入门:拒绝枯燥的点点点

什么是自动化测试?

想象一下,你有一位不知疲倦的助手,可以24小时不间断地帮你检查软件功能是否正常。这位助手就是自动化测试

自动化测试是通过编写代码来模拟用户操作,验证软件功能是否正确,从而替代繁琐的手动测试过程。

python自动化测试工具

Python拥有丰富的测试工具生态系统,以下是最常用的几种:

1. unittest – Python自带的测试框架

unittest是Python标准库中的测试框架,无需安装即可使用。

import unittest

def add(a, b):
    return a + b

class TestMathFunctions(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)  # 验证2+3是否等于5
        self.assertEqual(add(-1, 1), 0)  # 验证-1+1是否等于0

if __name__ == '__main__':
    unittest.main()

运行上面的代码,如果所有测试通过,你会看到:

..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

2. pytest – 更简单强大的测试框架

pytest是当前最流行的Python测试框架,以其简洁的语法和强大的功能著称。

首先安装pytest:

pip install pytest

然后编写测试:

# test_math.py
def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

运行测试:

pytest test_math.py -v

3. Selenium – Web自动化测试利器

Selenium可以模拟用户在浏览器中的操作,实现Web应用的自动化测试。

安装Selenium:

pip install selenium

还需要下载浏览器驱动(如ChromeDriver)并添加到系统路径中。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

# 创建浏览器实例
driver = webdriver.Chrome()

try:
    # 打开网页
    driver.get("https://www.google.com")
    
    # 查找搜索框并输入关键词
    search_box = driver.find_element_by_name("q")
    search_box.send_keys("Python自动化测试")
    search_box.send_keys(Keys.RETURN)
    
    # 等待结果加载
    time.sleep(2)
    
    # 验证页面标题
    assert "Python自动化测试" in driver.title
    print("测试通过!")
    
finally:
    # 关闭浏览器
    driver.quit()

4. Requests – API测试轻松搞定

对于API接口测试,Requests库是绝佳选择。

import requests

# 测试GET请求
def test_get_request():
    response = requests.get('https://api.github.com/users/octocat')
    assert response.status_code == 200
    assert response.json()['login'] == 'octocat'
    print("API测试通过!")

# 测试POST请求
def test_post_request():
    data = {'key': 'value'}
    response = requests.post('https://httpbin.org/post', data=data)
    assert response.status_code == 200
    assert response.json()['form']['key'] == 'value'
    print("POST测试通过!")

实战:为一个简单应用编写测试

让我们为一个简单的计算器应用编写完整的测试套件。

计算器代码 (calculator.py):

class Calculator:
    def add(self, a, b):
        return a + b
    
    def subtract(self, a, b):
        return a - b
    
    def multiply(self, a, b):
        return a * b
    
    def divide(self, a, b):
        if b == 0:
            raise ValueError("除数不能为零")
        return a / b

测试代码 (test_calculator.py):

import pytest
from calculator import Calculator

class TestCalculator:
    @classmethod
    def setup_class(cls):
        """在所有测试前执行一次"""
        cls.calc = Calculator()
    
    def test_add(self):
        assert self.calc.add(2, 3) == 5
        assert self.calc.add(-1, -1) == -2
        assert self.calc.add(0, 0) == 0
    
    def test_subtract(self):
        assert self.calc.subtract(5, 3) == 2
        assert self.calc.subtract(0, 5) == -5
    
    def test_multiply(self):
        assert self.calc.multiply(3, 4) == 12
        assert self.calc.multiply(0, 5) == 0
    
    def test_divide(self):
        assert self.calc.divide(10, 2) == 5
        assert self.calc.divide(5, 2) == 2.5
    
    def test_divide_by_zero(self):
        """测试除以零的异常处理"""
        with pytest.raises(ValueError) as excinfo:
            self.calc.divide(5, 0)
        assert "除数不能为零" in str(excinfo.value)

运行测试:

pytest test_calculator.py -v

自动化测试最佳实践

  1. 命名清晰:测试方法和文件名应清晰表达测试目的

  2. 保持独立:每个测试应该独立运行,不依赖其他测试

  3. 测试边界情况:特别关注边界值和异常情况

  4. 定期运行:将自动化测试集成到开发流程中

  5. 持续维护:随着功能变化更新测试用例

THE END
喜欢就支持一下吧
赞赏 分享