How to pass arguments from github actions to unit tests in rust

441 views Asked by At

I would like to use github secrets to inject a secret API key into my unit testing functions to prevent having ay API key within the source:

My (simplfied) test is defining the APIKEY as string constant.

const APIKEY: &str = "ddbe2befdeadbeefa2d20f09b4a694";

#[test]
fn test_apikey() {
    assert!( usekey(APIKEY).is_ok() );
}

Now I would like to get the API-key from the arguments which the test executable gets when I run:

> cargo test -- ddbe2befdeadbeefa2d20f09b4a694";

But while I tried to use the following code to get the first argument with:

let args: Vec<String> = env::args().collect();
let apikey = &args[1];

I realized that my tests won't be processed any more whenever I give an argument to cargo test --.

Here is the call without giving arguments:

▶ 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

But no test will be processed when I try to give the apikey in an argument to the tests:

▶ 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

One can see that the test was correctly called with the apikey attached.

I do not understand why this happens and diving into rust tests documentation did not lead me to something useful.

Do you have any tips?

1

There are 1 answers

0
pat On

Seems that giving secrets through program arguments is not how it's been made.

Instead use a method like this:

fn apikey() -> String {
    match std::env::var("APIKEY") {
        Ok(key) => key,
        Err(_r) => {
            eprintln!("error: set API-key with environment valiable APIKEY");
            "".to_string()
        }
    }
}

...I can inject the API key into my tests in github actions with:

env:
  APIKEY: ${{ secrets.APIKEY }}

jobs:
  build:
    steps:
 
    - name: Run tests
      run: cargo test --verbose

Thanks for the help!