BATS:在所有测试中使变量持久化(BATS: Make variable persistent across all tests)

编程入门 行业动态 更新时间:2024-10-27 17:24:47
BATS:在所有测试中使变量持久化(BATS: Make variable persistent across all tests)

我正在编写一个BATS (Bash自动化测试系统)脚本,我想要的是一个变量,可以在所有测试中保持不变。 例如:

#!/usr/bin/env bats # Generate random port number port_num=$(shuf -i 2000-65000 -n 1) @test "Test number one" { a = $port_num } @test "Test number two" { b = $port_num }

评估时,a和b应该相等。 但这不起作用,因为(根据文档)在每次测试运行后评估整个文件。 这意味着$ port_num在测试之间重新生成。 我是否有办法存储将在所有测试中保留的变量?

I'm writing a BATS (Bash Automated Testing System) script and what I'd like is a variable to be persisted across all the tests. For example:

#!/usr/bin/env bats # Generate random port number port_num=$(shuf -i 2000-65000 -n 1) @test "Test number one" { a = $port_num } @test "Test number two" { b = $port_num }

When evaluated, a and b should equal each other. This doesn't work, though, because (according to the docs) the entire file is evaluated after each test run. Which means $port_num gets regenerated between tests. Is there a way/place for me to store variables that will be persisted for across all tests?

最满意答案

将其导出为环境变量。

# If ENV Var $port_num doesn't exist, set it. if [ -z "$port_num" ]; then export port_num=$(shuf -i 2000-65000 -n 1) fi

在BATS您必须调用load来获取文件。

将上面的代码放在正在执行的目录中名为port.bash的文件中。

然后在您的功能之前,调用load port 。 这将设置一次$port_num ,而不是更改它。

load port @test "Test number one" { a = $port_num } @test "Test number two" { b = $port_num }

Export it as an environmental variable.

# If ENV Var $port_num doesn't exist, set it. if [ -z "$port_num" ]; then export port_num=$(shuf -i 2000-65000 -n 1) fi

In BATS you must call load to source a file.

Put the above code in a file named port.bash in the directory you are executing from.

Then before your functions, call load port. This will set up your $port_num once, and not change it.

load port @test "Test number one" { a = $port_num } @test "Test number two" { b = $port_num }

更多推荐

本文发布于:2023-08-04 15:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1417612.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   持久   测试中   BATS   persistent

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!