首页 > 解决方案 > 如何在空手道框架的 csv 文件中为特定列调用我的 JS 函数?

问题描述

我有一个读取包含多行的 csv 文件的功能文件,我需要验证如果其中两列满足特定条件,则第三列需要是强制性的。我曾尝试使用 js 函数,但我不确定如何为第三列调用此函数。所以根据下面的例子,如果名字是鸡,单位公斤,那么成本需要是强制性的。

#
noinspection CucumberTableInspection
Feature: Serverless

Scenario Outline: Per Row *
  def row =
  ""
" {
  name: '<Name>',
  unit: '<Unit>',
  cost: '<Cost>',
}
@FunctionComparison
  ""
" *
def name = '<Name>' *
  def unit = '<Unit>' *
  def cost = '<Cost>' *
  def checkMandatory =
  ""
"

function(arg1, arg2, arg3) {
  if (arg1 in ('Chicken')) {
    if (arg2 in ('kg')) {
      if (arg3.length < 0) {
      
        return false;
      }
      return true;
    }
    return true;
  }
  return true;
}


""
" *
match row ==
  ""
" {
  name: '#ignore',
  unit: '#regex ea|kg|ml',
  cost: 'checkMandatory(name, unit, cost) == true'

}
""
"
Examples:
  |
  read('input' + '.csv') |

input.csv 只是一个包含以下内容的 csv 文件:

行、名称、单位、成本(列)

1,Cheese,ea,34.50 2,Cake,ea,55.54 3,Chicken,kg, 4,Cement,ml,4.32

标签: karate

解决方案


您的验证功能可以简单得多,试试这个:

* def third = { name: 'foo', unit: 'bar', cost: '' }
* def isValid = function(x){ return (x.name && x.unit) ? x.cost.length != 0 : true }
* assert !isValid(third)

请注意,这Scenario Outlines将注入变量,因此不需要<and>占位符:https ://github.com/intuit/karate#scenario-outline-enhancements

您可以尝试这个独立的工作示例:

Feature:

Background:
* text data =
"""
name,unit,cost
Cheese,ea,34.50
Cake,ea,55.54
Chicken,kg,
Cement,ml,4.32
"""
* csv data = data
* def isValid = function(x){ return (x.name && x.unit) ? x.cost.length != 0 : true }

Scenario Outline:
* assert isValid(__row)

Examples:
| data |

推荐阅读