首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Python Behave中将CSV作为表导入?

如何在Python Behave中将CSV作为表导入?
EN

Stack Overflow用户
提问于 2017-10-18 15:55:31
回答 2查看 550关注 0票数 0

我有一个像blow的特征文件。如何导入.csv文件来替换示例中的表?

代码语言:javascript
复制
Scenario Outline: Blenders
   Given I put <thing> in a blender,
    when I switch the blender on
    then it should transform into <other thing>

 Examples: Amphibians
   | thing         | other thing |
   | Red Tree Frog | mush        |

 Examples: Consumer Electronics
   | thing         | other thing |
   | iPhone        | toxic waste |
   | Galaxy Nexus  | toxic waste |
EN

回答 2

Stack Overflow用户

发布于 2018-06-15 21:22:02

here所述,尚不支持表导入。

但根据jenisys在同一篇文章中的回应,它很快就会推出。

票数 0
EN

Stack Overflow用户

发布于 2021-11-22 05:58:10

暂不支持表导入,但可以创建helper方法。

x.feature文件:

代码语言:javascript
复制
Feature: csv file

@dynamic
Scenario Outline: Load data from csv
  Then just print <username> <email> <password>
    Examples: Dynamic
      | username | email |  password |
      |    .     |   .   |      .    |

Step文件(steps/step_file.py):

代码语言:javascript
复制
from behave import step


@step('just print {username} {email} {password}')
def step_impl(context, username, email, password):
    print(username, email, password)

environment.py文件:

代码语言:javascript
复制
from behave.model import ScenarioOutline
import copy
import csv


def before_feature(context, feature):
    features = (scenario for scenario in feature.scenarios if type(scenario) == ScenarioOutline and 'dynamic' in scenario.tags)
    for scenario in features:
        for example in scenario.examples: 
            orig = copy.deepcopy(example.table.rows[0])
            example.table.rows = []
            with open('test.json') as csv_file:
                csv_reader = csv.reader(csv_file, delimiter=',')
                for row in csv_reader:
                    n = copy.deepcopy(orig)
                    n.cells = ['{}'.format(row[0]), '{}'.format(row[1]), '{}'.format(row[2])]
                    example.table.rows.append(n)

test.json文件:

代码语言:javascript
复制
andrew,testemail1@example.com,1235aaa
mike,testemail1@example.com,1234bbb

结果是:

代码语言:javascript
复制
behave -i tutorial.feature
Feature: csv file # features/tutorial.feature:1

  @dynamic
  Scenario Outline: Load data from csv -- @1.1 Dynamic     # features/tutorial.feature:8
    Then just print andrew  testemail1@example.com 1235aaa # features/steps/step_test.py:4 0.000s

  @dynamic
  Scenario Outline: Load data from csv -- @1.2 Dynamic    # features/tutorial.feature:8
    Then just print marina testemail1@example.com 1234bbb # features/steps/step_test.py:4 0.000s

1 feature passed, 0 failed, 0 skipped
2 scenarios passed, 0 failed, 0 skipped
2 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.000s
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46805304

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档