【问题标题】:Passing multiple arguments through: `run bash -c ...`传递多个参数:`run bash -c ...`
【发布时间】:2021-12-29 16:11:50
【问题描述】:

在尝试在名为 some_function 的函数上使用 assert_failure 时,我在传递多个参数时遇到了一些困难。

load 'libs/bats-support/load'
load 'libs/bats-assert/load'
# https://github.com/bats-core/bats-file#Index-of-all-functions
load 'libs/bats-file/load'
# https://github.com/bats-core/bats-assert#usage
load 'assert_utils'

@test "Perform some test." {
  variable_one="one"
  variable_two="two"
  variable_three="three"
  variable_four="four"
  run bash -c 'source src/some_script.sh && some_function 
  "$variable_one" "$variable_two" "$variable_three"'
  assert_failure
  assert_output "$expected_error_message"
}

函数包含:

some_function() {
    local variable_one="$1"
    local variable_two="$2"
    local variable_three="$3"
    local variable_four="$4"
    echo "variable_one=$variable_one"
    echo "variable_two=$variable_two"
    echo "variable_three=$variable_three"
    echo "variable_four=$variable_four"
}

输出显示只有第一个变量传递成功,而第二个到第四个没有:

 ✗ Verify an error is thrown, if something.
   (from function `assert_failure' in file test/libs/bats-assert/src/assert.bash, line 140,
    in test file test/test_something.bats, line 89)
     `assert_failure' failed
   
   -- command succeeded, but it was expected to fail --
   output (3 lines):
     variable_one=one
     variable_two=
     variable_three=
     variable_four=
   --
   

如何在函数上运行assert_failure 的同时将多个/四个变量传递给函数?

根据评论进行编辑

虽然我很感谢 KamilCuk 在 cmets 中提供的实用解决方案,但它似乎可以提高特异性。例如,variable_one 可能是在多个函数中使用的变量,对于这些函数的不同调用具有不同的值。所以理想情况下,每次调用不同的函数时,我都不会覆盖“导出”的值。相反,我认为将特定参数传递给特定函数会更好。

【问题讨论】:

  • export variable_one variable_two ...While trying to assert_failure on a function assert_failure 是做什么的,它是如何工作的?这不是标准的 bash 命令。
  • 我想这是Bats?
  • @BenjaminW。是的,测试确实是蝙蝠测试。
  • export 你希望你的子进程看到的变量。

标签: bash parameter-passing assert bats-core


【解决方案1】:

正常传递参数,但跳过此上下文中保留的第一个参数:

bash -c 'source src/some_script.sh && some_function "$@"' _ 'argument a' 'argument B' 'This is c' 'Andy'

输出:

variable_one=argument a
variable_two=argument B
variable_three=This is c
variable_four=Andy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2015-06-27
    • 2021-11-04
    • 2012-08-13
    • 2017-08-28
    相关资源
    最近更新 更多