pytest实战演练
pycharm常见操作
创建项目使用虚拟环境
创建文件夹的时候建议使用的创建方式
- 这样创建是因为python3.0版本之后导包无区别,之前版本导包会报错的
_init_.py文件中建议为空不写内容
_all_=[]的含义
- 是将列表中的方法或变量或类暴漏出去便于使用的
- 生效方法,当调用模块中使用 import * 时才生效
联动git使用
pytes实战2
#####测试代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
class Calc:
def add(self, a, b):
return a + b
def div(self, a, b):
return a / b
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import unittest
from pytest_exercise.python.calc import Calc
class TestCal(unittest.TestCase):
def test_add_1(self):
self.calc = Calc()
result = self.calc.add(1, 2)
self.assertEqual(3, result)
if __name__ == '__main__':
unittest.main()
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import unittest
import pytest
from pytest_exercise.python.calc import Calc
class TestCal():
def setup(self):
self.calc = Calc()
def test_add_1(self):
result = self.calc.add(1, 2)
print(result)
assert 3 == result
def test_div(self):
self.calc = Calc()
result = self.calc.div(2, 2)
assert 1 == result
if __name__ == '__main__':
pytest.main(["-vs", "test_pytest.py::TestCal::test_div"])
新特性,自定义变量后的数据类型提示格式
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# type:类星体是
class Calc:
def add(self, a: int, b: int) -> int:
return a + b
def div(self, a, b):
return a / b
pytest常用参数
#####pytest --collect-only
pytest按顺序执行
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import unittest
import pytest
from pytest_exercise.python.calc import Calc
class TestCal():
def setup(self):
self.calc = Calc()
@pytest.mark.run(order=2)
def test_add_1(self):
result = self.calc.add(1, 2)
print(result)
assert 3 == result
@pytest.mark.run(order=1)
def test_div(self):
self.calc = Calc()
result = self.calc.div(2, 2)
assert 1 == result
if __name__ == '__main__':
pytest.main(["-vs", "test_pytest.py::TestCal"])
pytest.ini文件的应用(修改匹配对应的测试用例的方法)
导出依赖包
反射代码片段
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Person:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating")
p = Person('jerry')
print(hasattr(p, 'name'))
f = getattr(p, "eat")
f()
init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating")
p = Person(‘jerry’)
print(hasattr(p, ‘name’))
f = getattr(p, “eat”)
f()