[Python Test] Use pytest fixtures to reduce duplicated code across unit tests
2018-02-22 22:04
627 查看
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.
test:
""" 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] Use Python to generate Java Unit Test codes automatically
- Unable to use IEC module under PortablePython_1.1_py2.5.4
- python unittest源码解析三----loader.py之_get_name_from_path(self, path)
- python错误:SyntaxError: Non-UTF-8 code starting with '\xcb' in file E:/Python/test.py on line 2
- Python之使用unittest框架和HTMLTestRunner.py文件实现多个测试用例执行与测试报告生成
- Use Python to run REST API Automation Test
- Usefunctional programming in Perl to make test automation code more structural
- [Python + Unit Testing] Write Your First Python Unit Test with pytest
- Use python for C++ unit/function test
- Effective Objective-C 2.0: Item 39: Use Handler Blocks to Reduce Code Separation
- Python单元测试框架之pytest -- fixtures
- VS 2005, How to use Assert to perform UnitTest?
- python unittest/pyunit
- Python单元测试框架之pytest -- fixtures
- python:解决pycharm运行py文件时只有unittest选项的方法
- Introduction to unittest using python
- python unit test to assert a method calls sys.exit()
- Unable to use IEC module under PortablePython_1.1_py2.5.4
- Introduction to unittest using python
- [zz]How to produce html unit test output in Python?