我想使用github secrets将秘密 API 密钥注入到我的单元测试函数中,以防止在源代码中有任何 API 密钥:
我的(简化的)测试将 APIKEY 定义为字符串常量。
const APIKEY: &str = "ddbe2befdeadbeefa2d20f09b4a694";
#[test]
fn test_apikey() {
assert!( usekey(APIKEY).is_ok() );
}
现在我想从测试可执行文件在运行时获取的参数中获取 API 密钥:
> cargo test -- ddbe2befdeadbeefa2d20f09b4a694";
但是,当我尝试使用以下代码来获取第一个参数时:
let args: Vec<String> = env::args().collect();
let apikey = &args[1];
我意识到每当我向cargo test --
.
这是没有给出参数的调用:
▶ cargo test -v --
[..]
Finished test [unoptimized + debuginfo] target(s) in 0.05s
Running `/home/pat/git/myprg/target/debug/deps/myrg-7e0bdeadbeef95ff`
running 7 tests
test tests::test_cityid ... ok
test tests::test_coordinate ... ok
test tests::test_apikey ... ok
test tests::test_city ... ok
test tests::test_language ... ok
test tests::test_units ... ok
test tests::test_cities ... ok
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
但是,当我尝试在测试的参数中提供 apikey 时,不会处理任何测试:
▶ cargo test -v -- ddbe2befdeadbeefa2d20f09b4a694
[..]
Finished test [unoptimized + debuginfo] target(s) in 0.05s
Running `/home/pat/git/myprg/target/debug/deps/myprg-7e0bdeadbeef95ff ddbe2befdeadbeefa2d20f09b4a694";`
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 7 filtered out
可以看到,在附加 apikey 的情况下正确调用了测试。
我不明白为什么会发生这种情况,并且深入研究 rust 测试文档并没有让我找到有用的东西。
你有什么建议吗?