[Python Test] Use pytest fixtures to reduce duplicated code across unit tests
2023-09-14 09:00:50 时间
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
相关文章
- 【Python成长之路】Python爬虫 --requests库爬取网站乱码(xe4xb8xb0xe5xa)的解决方法
- 全功能Python测试框架:pytest
- 全功能Python测试框架:pytest
- Python 利用pexpect和paramiko模块进行远程服务器的监控
- Python简单计算数组元素平均值的方法示例
- 全面了解python中的类,对象,方法,属性
- python 配置pip镜像地址
- Python 刷Leetcode题库,顺带学英语单词(21)
- Python语言学习:Python语言学习之程序打包发布(exe/msi等)&如何将自己的Python项目(自定义程序代码库)发布到PyPI全流程的简介、案例应用之详细攻略
- Python编程语言学习:利用open函数将文本内容追加写入到txt文件中(两种方法实现)
- Py之pytest-shutil:Python库之pytest-shutil简介、安装、使用方法之详细攻略
- stylecloud:一款可以制作个性化词云图的 Python 神器
- 【Pytest】python单元测试框架pytest简介
- 【LeetCode Python实现】求水仙花数
- python爬虫入门requests模块
- pytest接口自动化测试框架 | 修改Python traceback输出
- python+requests+pytest接口自动化介绍
- python+appium自动化测试-pytest+allure测试报告(一)
- 全功能Python测试框架:pytest
- 老司机教你如何学习Python数据分析