【发布时间】:2016-08-19 12:59:25
【问题描述】:
我正在尝试使用 Python 的 behave library 在一堆分隔的文本文件上编写一些 BDD/Gherkin 样式测试。
一个典型的场景是这样的:
Scenario: Check delivery files for illegal values
Given a file system path to the delivery folder
When I open each file and read its values
Then all values in the "foo" column are smaller than 1
And all values in the "fizz" column are larger than 2
由于文件很多,每个文件都包含很多行,因此不可能将所有文件硬编码到场景大纲中。此外,我想避免一次将整个文件读入内存,而是使用生成器逐行迭代。
我尝试了以下方法。但是,这在大型数据集和大量条件下效率非常低,因为对于每个then 步骤,都会一次又一次地读取每一行。是否有可能在多个 then 步骤之间传递单行并从第一个 then 步骤重新开始下一行?
或者 BDD/Gherkin 不适合这种测试?有什么替代方案?
import csv
import itertools
import os
@given('a file system path to the delivery folder')
def step(context):
context.path = '/path/to/delivery/files'
@when('I open each file and read its values')
def step(context):
file_list = os.listdir(context.path)
def row_generator():
for path in file_list:
with open(path, 'rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
yield row
context.row_generator = row_generator
# itertools.tee forks off the row generator so it can be used multiple times instead of being exhausted after the first 'then' step
@then('all values in the "foo" column are smaller than 1')
def step(context):
for row in itertools.tee(context.row_generator(), 1)[0]:
assert row['foo'] < 1
@then('all values in the "bar" column are larger than 2')
def step(context):
for row in itertools.tee(context.row_generator(), 1)[0]:
assert row['bar'] > 2
【问题讨论】:
标签: python loops iteration gherkin python-behave