PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 21, 2022

[FIXED] How can I test Rust methods that depend on environment variables?

 August 21, 2022     environment-variables, rust, unit-testing     No comments   

Issue

I am building a library that interrogates its running environment to return values to the asking program. Sometimes as simple as

pub fn func_name() -> Option<String> {
    match env::var("ENVIRONMENT_VARIABLE") {
        Ok(s) => Some(s),
        Err(e) => None
    }
}

but sometimes a good bit more complicated, or even having a result composed of various environment variables. How can I test that these methods are functioning as expected?


Solution

"How do I test X" is almost always answered with "by controlling X". In this case, you need to control the environment variables:

use std::env;

fn env_is_set() -> bool {
    match env::var("ENVIRONMENT_VARIABLE") {
        Ok(s) => s == "yes",
        _ => false
    }
}

#[test]
fn when_set_yes() {
    env::set_var("ENVIRONMENT_VARIABLE", "yes");
    assert!(env_is_set());
}

#[test]
fn when_set_no() {
    env::set_var("ENVIRONMENT_VARIABLE", "no");
    assert!(!env_is_set());
}

#[test]
fn when_unset() {
    env::remove_var("ENVIRONMENT_VARIABLE");
    assert!(!env_is_set());
}

However, you need to be aware that environment variables are a shared resource. From the docs for set_var, emphasis mine:

Sets the environment variable k to the value v for the currently running process.

You may also need to be aware that the Rust test runner runs tests in parallel by default, so it's possible to have one test clobber another.

Additionally, you may wish to "reset" your environment variables to a known good state after the test.



Answered By - Shepmaster
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing