目录
Install and Set Up Pytest
Write Your First Test
Use Fixtures for Reusable Setup
Test Exceptions and Edge Cases
Run Specific Tests and Use Options
首页 后端开发 Python教程 如何用Pytest测试Python代码

如何用Pytest测试Python代码

Sep 20, 2025 am 12:35 AM
python 测试

Pytest是Python中简单强大的测试工具,安装后按命名规则自动发现测试文件。编写以test_开头的函数进行断言测试,使用@pytest.fixture创建可复用的测试数据,通过pytest.raises验证异常,支持运行指定测试和多种命令行选项,提升测试效率。

How to test Python code with pytest

Testing Python code with pytest is simple, powerful, and widely used in the Python community. It helps you write clean, maintainable tests with minimal boilerplate. Here’s how to get started and use it effectively.

Install and Set Up Pytest

First, install pytest using pip:

pip install pytest

Once installed, you can run tests from your project root. Pytest automatically discovers test files and functions following naming conventions.

By default, it looks for files named:

  • test_*.py
  • *_test.py

Inside these files, it runs functions starting with test_.

Write Your First Test

Create a file called test_sample.py with a simple function and test:

def add(a, b):
    return a b

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

Run the test in your terminal:

pytest

You’ll see output showing how many tests passed or failed.

Use Fixtures for Reusable Setup

Pytest fixtures let you define reusable setup logic. For example, if you need a database connection or test data:

import pytest

@pytest.fixture
def sample_data():
    return [1, 2, 3, 4, 5]

def test_sum(sample_data):
    assert sum(sample_data) == 15

The sample_data fixture is injected into any test that requests it by parameter name.

Test Exceptions and Edge Cases

To check that code raises expected exceptions, use pytest.raises:

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

def test_divide_by_zero():
    with pytest.raises(ValueError, match="Cannot divide by zero"):
        divide(10, 0)

Run Specific Tests and Use Options

You can run specific tests using patterns:

  • pytest test_sample.py – run all tests in a file
  • pytest test_sample.py::test_add – run one test function
  • pytest -v – show verbose output
  • pytest -x – stop after first failure
  • pytest --tb=short – shorten traceback

Basically, pytest makes testing easy once you follow the naming rules and learn to use assertions and fixtures. It handles most of the plumbing so you can focus on writing meaningful tests.

以上是如何用Pytest测试Python代码的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Stock Market GPT

Stock Market GPT

人工智能驱动投资研究,做出更明智的决策

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

如何从python中的unignts.txt文件安装包装 如何从python中的unignts.txt文件安装包装 Sep 18, 2025 am 04:24 AM

运行pipinstall-rrequirements.txt可安装依赖包,建议先创建并激活虚拟环境以避免冲突,确保文件路径正确且pip已更新,必要时使用--no-deps或--user等选项调整安装行为。

如何用Pytest测试Python代码 如何用Pytest测试Python代码 Sep 20, 2025 am 12:35 AM

Pytest是Python中简单强大的测试工具,安装后按命名规则自动发现测试文件。编写以test_开头的函数进行断言测试,使用@pytest.fixture创建可复用的测试数据,通过pytest.raises验证异常,支持运行指定测试和多种命令行选项,提升测试效率。

如何处理python中的命令行参数 如何处理python中的命令行参数 Sep 21, 2025 am 03:49 AM

theargparsemodulestherecommondedwaywaytohandlecommand-lineargumentsInpython,提供式刺激,typeValidation,helpmessages anderrornhandling; useSudys.argvforsimplecasesRequeRequeRingminimalSetup。

从新手到专家:10个必备的免费公共数据集网站 从新手到专家:10个必备的免费公共数据集网站 Sep 15, 2025 pm 03:51 PM

对于数据科学的初学者而言,从“毫无经验”到“行业专家”的跃迁之路,其核心就是不断地实践。而实践的基础,正是丰富多样的数据集。幸运的是,网络上有大量提供免费公共数据集的网站,它们是提升技能、磨练技术的宝贵资源。

电脑怎么选才适合大数据分析?高性能计算的配置指南 电脑怎么选才适合大数据分析?高性能计算的配置指南 Sep 15, 2025 pm 01:54 PM

大数据分析需侧重多核CPU、大容量内存及分层存储。首选多核处理器如AMDEPYC或RyzenThreadripper,兼顾核心数量与单核性能;内存建议64GB起步,优先选用ECC内存保障数据完整性;存储采用NVMeSSD(系统与热数据)、SATASSD(常用数据)和HDD(冷数据)组合,提升整体处理效率。

什么是BIP?为什么它们对比特币的未来如此重要? 什么是BIP?为什么它们对比特币的未来如此重要? Sep 24, 2025 pm 01:51 PM

目录什么是比特币改进提案(BIP)?为什么BIP如此重要?比特币改进提案(BIP)的历史BIP流程如何运作?BIP类型什么是信号以及矿工如何发出信号?Taproot快速试用BIP的利与弊结语‍自2011年以来,对比特币的任何改进都通过称为比特币改进提案或​​“BIP”的系统进行。比特币改进提案(BIP)为比特币如何发展提供了指导方针一般来说,BIP有三种可能的类型,其中两种与比特币的技术变革有关每个BIP都是从比特币开发者之间的非正式讨论开始的,他们可以在任何地方聚集,包括Twi

如何使用Python中的@ContextManager Decorator创建上下文管理器? 如何使用Python中的@ContextManager Decorator创建上下文管理器? Sep 20, 2025 am 04:50 AM

Import@contextmanagerfromcontextlibanddefineageneratorfunctionthatyieldsexactlyonce,wherecodebeforeyieldactsasenterandcodeafteryield(preferablyinfinally)actsas__exit__.2.Usethefunctioninawithstatement,wheretheyieldedvalueisaccessibleviaas,andthesetup

如何编写Python中日常任务的自动化脚本 如何编写Python中日常任务的自动化脚本 Sep 21, 2025 am 04:45 AM

Identifyrepetitivetasksworthautomating,suchasorganizingfilesorsendingemails,focusingonthosethatoccurfrequentlyandtakesignificanttime.2.UseappropriatePythonlibrarieslikeos,shutil,glob,smtplib,requests,BeautifulSoup,andseleniumforfileoperations,email,w

See all articles