[Python Test] Use pytest fixtures to reduce duplicated code across unit tests

In this lesson, you will learn how to implement pytest fixtures. Many unit tests have the same resource requirements. For example, an instantiated object from a class. You will learn how to create the instance of the class one time as a fixture and reuse that object across all your tests. This results in faster tests, eliminates duplicate code, and uses less resources when running your tests.

 

复制代码
"""
Python class for a self-driving car.
Suitable for disrupting automotive industry
"""

class Car(object):

    def __init__(self, speed, state):
        self.speed = speed
        self.state = state

    def start(self):
        self.state = "running"
        return self.state

    def turn_off(self):
        self.state = "off"
        return self.state

    def accelerate(self):
        self.speed += 10
        return self.speed

    def stop(self):
        self.speed = 0
        return self.speed
复制代码

 

test:

复制代码
"""
Tests for Car class
"""

import pytest
from car import Car

class TestCar(object):

    """
    default scope is "function" which means
    foreach test, it will have its own scope
    "module" ref to class itself, so it sharing
    the same instance
    """

    @pytest.fixture(scope="module")
    def my_car(self):
        return Car(0, "off")

    def test_start(self, my_car):
        my_car.start()
        assert my_car.state == "running"

    def test_turn_off(self, my_car):
        my_car.turn_off()
        assert my_car.state == "off"

    def test_accelerate(self, my_car):
        my_car.accelerate()
        assert my_car.speed == 10

    """
    This one will failed because we are using fixture
    scope as "module", my_car.speed == 20
    """
    def test_accelerate1(self, my_car):
        my_car.accelerate()
        assert my_car.speed == 10

    def test_stop(self, my_car):
        my_car.stop()
        assert my_car.speed == 0
复制代码

 

posted @   Zhentiw  阅读(351)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-02-22 [Redux] Important things in Redux
2016-02-22 [Immutable.js] Exploring Sequences and Range() in Immutable.js
2016-02-22 [Immutable.js] Converting Immutable.js Structures to Javascript and other Immutable Types
2016-02-22 [Immutable.js] Transforming Immutable Data with Reduce
点击右上角即可分享
微信分享提示