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

本文介绍如何使用 pytest 的 fixtures 功能来提高单元测试效率。通过创建一次性实例并在多个测试中重复使用该实例,可以减少资源消耗并加快测试速度。示例展示了如何为 Car 类设置 fixture 并在不同测试用例中应用。

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值