1

我正在尝试使用 Python 的行为库在一堆分隔的文本文件上编写一些 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
4

2 回答 2

0

Dirk,您可以考虑编写一个脚本来生成场景大纲(给定 csv 文件)。这样您就可以依赖标准的行为/小黄瓜功能。让它尽可能简单,因为它引入了另一个可能出错的地方。然而,它简化了您的步骤文件,因此您可以专注于实际的功能测试,而不是读取 csv 文件的机制。根据您的数据集有多大,您可能还会遇到内存限制,因为我认为该表仅保存在内存中。不是一个很好的解决方案,而是“替代方案”。

于 2016-09-02T19:15:26.123 回答
-2

为了实现我的场景的一般循环 - 我已经完成了如下所示。当然,您必须编写步骤定义,这可能就像拥有一个日志条目一样简单。

@test
Scenario Outline: Repeat Step in Loop
 Given we repeat the same test X times
 When we do something
 Then we analyze results
 Examples: Iteration
  | X |
  | 1 |
  | 2 |
  | 3 |

欢迎提出更好的方法。迭代不是程序化的,必须硬编码(生成示例表的小脚本)

于 2017-04-07T16:11:26.930 回答