上周看了元类的实现方式后,对「代码块」的理解好像有了不一样的认知。
根据现在的工作中使用的pytest写一个demo
demo:
import pytest
import requests
@pytest.fixture(scope='module')
def get_request():
request_list = []
def _get_request(data, flag=True):
if flag:
x = requests.post('http://httpbin.org/post', data=data)
request_list.append(x.json().get('data'))
return request_list
yield _get_request
@pytest.mark.parametrize("i", [1, 2, 3])
def test_customer_records(i, get_request):
print('\n')
print(f'第{i}次测试')
customer = get_request(f'{{"a{i}", "b{i}"}}')
print(customer)
结果:
第1次测试
['{"a1", "b1"}']
.
第2次测试
['{"a1", "b1"}', '{"a2", "b2"}']
.
第3次测试
['{"a1", "b1"}', '{"a2", "b2"}', '{"a3", "b3"}']
解释:
request_list
yield
将它返回以供调用参数化构建
case会执行三次写的时候感觉好像很神奇,后来想想其实和以下方式实现一样:
request_list = []
def _get_request2(request_list, data, flag=True):
if flag:
x = requests.post('http://httpbin.org/post', data=data)
request_list.append(x.json().get('data'))
return request_list
@pytest.fixture(scope='module')
def get_request2():
yield _get_request2
@pytest.mark.parametrize("i", [1, 2, 3])
def test_customer_records(i, get_request2):
print('\n')
print(f'第{i}次测试')
customer = get_request2(request_list, f'{{"a{i}", "b{i}"}}')
print(customer)
也不就是:
request_list = []
def _get_request2(request_list, data, flag=True):
if flag:
x = requests.post('http://httpbin.org/post', data=data)
request_list.append(x.json().get('data'))
return request_list
@pytest.mark.parametrize("i", [1, 2, 3])
def test_customer_records(i):
print('\n')
print(f'第{i}次测试')
customer = _get_request2(request_list, f'{{"a{i}", "b{i}"}}')
print(customer)
额,好Low
不过其实也不是毫无用处,当scope
等级改变之后
global
turndown
机制