zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    POJ-1004-Finanical Management
    POJ-1003-hangover
    第一次写博客,想了很久要给自己留一个什么样的开始
    从exchange2010上面删除特定主题或特定时间的邮件
    STM32 一个定时器产生4路 独立调频率,占中比可调,脉冲个数可以统计。
    光电耦合
    STM32 定时器级联
    Eclipse 创建新的workspace
    一次提交,多文件上传
    Grid标签计算结果集中的合计行
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8460290.html
Copyright © 2011-2022 走看看