Skip to content

Commit

Permalink
Rename envfile to env_file
Browse files Browse the repository at this point in the history
To match env_var
  • Loading branch information
sonro committed Jul 31, 2024
1 parent 1efcba9 commit aa9f907
Show file tree
Hide file tree
Showing 10 changed files with 150 additions and 150 deletions.
22 changes: 11 additions & 11 deletions test_util/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ By setting up a `TestEnv`, and running a closure via `test_in_env`.
- Lock the environment from other tests
- Store the existing environment variables
- Add any custom env_vars to the environment
- Create any custom envfiles in the temporary directory
- Create any custom env files in the temporary directory

**In the closure** you can use the assertion functions to test the environment.

Expand Down Expand Up @@ -48,10 +48,10 @@ fn dotenv_override_existing_key() {
// with an existing environment variable
testenv.add_env_var(EXISTING_KEY, EXISTING_VAL);

// with an envfile that overrides it
testenv.add_envfile(
// with an env file that overrides it
testenv.add_env_file(
".env",
create_custom_envfile(&[(EXISTING_KEY, OVERRIDING_VAL)]),
create_custom_env_file(&[(EXISTING_KEY, OVERRIDING_VAL)]),
);

// execute a closure in the testing environment
Expand Down Expand Up @@ -84,27 +84,27 @@ The default `TestEnv` has 1 existing environment variable:

- `DEFAULT_EXISTING_KEY` set to `DEFAULT_EXISTING_VAL`

It has an envfile `.env` that sets:
It has an env file `.env` that sets:

- `DEFAULT_TEST_KEY` to `DEFAULT_TEST_VAL`
- `DEFAULT_EXISTING_KEY` to `DEFAULT_OVERRIDING_VAL`

### Customised Envfile

Use the `EnvFileBuilder` to manipulate the content of an envfile. Useful
Use the `EnvFileBuilder` to manipulate the content of an env file. Useful
for byte-order-mark(BOM) testing, and other edge cases.

```rust
use dotenvy_test_util::*;
use dotenvy::dotenv;

#[test]
fn comments_ignored_in_utf8bom_envfile() {
fn comments_ignored_in_utf8bom_env_file() {
let mut efb = EnvFileBuilder::new();
efb.insert_utf8_bom();
efb.add_strln("# TEST_KEY=TEST_VAL");

let testenv = TestEnv::init_with_envfile(efb);
let testenv = TestEnv::init_with_env_file(efb);

test_in_env(&testenv, || {
dotenv().expect(".env should be loaded");
Expand All @@ -113,7 +113,7 @@ fn comments_ignored_in_utf8bom_envfile() {
}
```

Or use anything that can be converted to a `Vec<u8>` if your envfile is
Or use anything that can be converted to a `Vec<u8>` if your env_file is
simple.

```rust
Expand All @@ -122,9 +122,9 @@ use dotenvy::dotenv;

#[test]
fn comments_ignored() {
let envfile = "# TEST_KEY=TEST_VAL\n";
let env_file = "# TEST_KEY=TEST_VAL\n";

let testenv = TestEnv::init_with_envfile(envfile);
let testenv = TestEnv::init_with_env_file(env_file);

test_in_env(&testenv, || {
dotenv().expect(".env should be loaded");
Expand Down
2 changes: 1 addition & 1 deletion test_util/src/assertions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ pub fn assert_default_keys_unset() {
}

/// Assert default testing environment variables are set.
/// Assuming the default envfile is loaded.
/// Assuming the default env file is loaded.
pub fn assert_default_keys() {
assert_env_var(DEFAULT_TEST_KEY, DEFAULT_TEST_VALUE);
assert_default_existing_var();
Expand Down
16 changes: 8 additions & 8 deletions test_util/src/envfile.rs → test_util/src/env_file.rs
Original file line number Diff line number Diff line change
@@ -1,42 +1,42 @@
use super::*;

/// Create the default envfile contents.
/// Create the default env file contents.
///
/// [`DEFAULT_TEST_KEY`] set as [`DEFAULT_TEST_VALUE`]
///
/// [`DEFAULT_EXISTING_KEY`] set as [`DEFAULT_OVERRIDING_VALUE`]
pub fn create_default_envfile() -> String {
pub fn create_default_env_file() -> String {
format!(
"{DEFAULT_TEST_KEY}={DEFAULT_TEST_VALUE}\n{DEFAULT_EXISTING_KEY}={DEFAULT_OVERRIDING_VALUE}",
)
}

/// Invalid due to missing `=` between key and value.
pub fn create_invalid_envfile() -> String {
pub fn create_invalid_env_file() -> String {
format!(
"{DEFAULT_TEST_KEY}{DEFAULT_TEST_VALUE}\n{DEFAULT_EXISTING_KEY}{DEFAULT_OVERRIDING_VALUE}",
)
}

/// Create an envfile with custom key-value pairs.
/// Create an env file with custom key-value pairs.
///
/// ## Example
///
/// ```no_run
/// # use dotenvy_test_util::create_custom_envfile;
/// let contents = create_custom_envfile(&[
/// # use dotenvy_test_util::create_custom_env_file;
/// let contents = create_custom_env_file(&[
/// ("CUSTOM_KEY", "test_val"),
/// ("ANOTHER_KEY", "another_val"),
/// ]);
/// assert_eq!(contents, "CUSTOM_KEY=test_val\nANOTHER_KEY=another_val\n");
/// ```
pub fn create_custom_envfile(env_vars: &[(&str, &str)]) -> String {
pub fn create_custom_env_file(env_vars: &[(&str, &str)]) -> String {
let mut efb = EnvFileBuilder::new();
efb.add_vars(env_vars);
efb.into_owned_string()
}

/// Advanced test-envfile constructor.
/// Advanced test-env file constructor.
///
/// Represented as bytes to allow for advanced manipulation and BOM testing.
#[derive(Debug, Default)]
Expand Down
22 changes: 11 additions & 11 deletions test_util/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@
//! - different directory layouts,
//! - custom `.env` file contents,
//! - multiple `.env` files,
//! - custom envfile name/path.
//! - custom env file name/path.
//!
//! Use the `create_` helper functions, such as [`create_custom_envfile`], to
//! Use the `create_` helper functions, such as [`create_custom_env_file`], to
//! generate the `.env` file contents. If you need more control of the
//! envfile's bytes, use the [`EnvFileBuilder`].
//! env file's bytes, use the [`EnvFileBuilder`].
//!
//! In your tests, call the [`dotenvy`] API, then make use of the `assert_`
//! helpers, such as [`assert_env_var`] and [`assert_env_var_unset`], to check
Expand All @@ -44,10 +44,10 @@
//! // with an existing environment variable
//! testenv.add_env_var(EXISTING_KEY, EXISTING_VAL);
//!
//! // with an envfile that overrides it
//! testenv.add_envfile(
//! // with an env file that overrides it
//! testenv.add_env_file(
//! ".env",
//! create_custom_envfile(&[(EXISTING_KEY, OVERRIDING_VAL)]),
//! create_custom_env_file(&[(EXISTING_KEY, OVERRIDING_VAL)]),
//! );
//!
//! // execute a closure in the testing environment
Expand All @@ -62,24 +62,24 @@
//! [`dotenvy`]: https://docs.rs/dotenvy

mod assertions;
mod envfile;
mod env_file;
mod testenv;

#[cfg(test)]
mod tests;

pub use assertions::*;
pub use envfile::*;
pub use env_file::*;
pub use testenv::*;

/// Default key used in envfile
/// Default key used in env file
pub const DEFAULT_TEST_KEY: &str = "DEFAULT_TEST_KEY";
/// Default value used in envfile
/// Default value used in env file
pub const DEFAULT_TEST_VALUE: &str = "default_test_val";

/// Default existing key set before test is run
pub const DEFAULT_EXISTING_KEY: &str = "DEFAULT_EXISTING_KEY";
/// Default existing value set before test is run
pub const DEFAULT_EXISTING_VALUE: &str = "loaded_from_env";
/// Default overriding value in envfile
/// Default overriding value in env file
pub const DEFAULT_OVERRIDING_VALUE: &str = "loaded_from_file";
68 changes: 34 additions & 34 deletions test_util/src/testenv.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::{create_default_envfile, DEFAULT_EXISTING_KEY, DEFAULT_EXISTING_VALUE};
use super::{create_default_env_file, DEFAULT_EXISTING_KEY, DEFAULT_EXISTING_VALUE};
use once_cell::sync::OnceCell;
use std::{
collections::HashMap,
Expand All @@ -18,12 +18,12 @@ static ENV_LOCKER: OnceCell<Arc<Mutex<EnvMap>>> = OnceCell::new();
/// A test environment.
///
/// Will create a new temporary directory. Use its builder methods to configure
/// the directory structure, preset variables, envfile name and contents, and
/// the directory structure, preset variables, env file name and contents, and
/// the working directory to run the test from.
///
/// Creation methods:
/// - [`TestEnv::init`]: blank environment (no envfile)
/// - [`TestEnv::init_with_envfile`]: blank environment with a custom `.env`
/// - [`TestEnv::init`]: blank environment (no env file)
/// - [`TestEnv::init_with_env_file`]: blank environment with a custom `.env`
/// - [`TestEnv::default`]: default testing environment (1 existing var and 2
/// set in a `.env` file)
#[derive(Debug)]
Expand All @@ -33,7 +33,7 @@ pub struct TestEnv {
dir_path: PathBuf,
work_dir: PathBuf,
env_vars: EnvMap,
envfiles: Vec<EnvFile>,
env_files: Vec<EnvFile>,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -87,7 +87,7 @@ where
test_in_env(&testenv, test);
}

/// Create a [`TestEnv`] without an envfile, but with the
/// Create a [`TestEnv`] without an env file, but with the
/// default existing environment variable.
pub fn create_testenv_with_default_var() -> TestEnv {
let mut testenv = TestEnv::init();
Expand All @@ -98,7 +98,7 @@ pub fn create_testenv_with_default_var() -> TestEnv {
impl TestEnv {
/// Blank testing environment in a new temporary directory.
///
/// No envfile or pre-existing variables set. The working directory is the
/// No env file or pre-existing variables set. The working directory is the
/// created temporary directory.
pub fn init() -> Self {
let tempdir = tempdir().expect("create tempdir");
Expand All @@ -111,21 +111,21 @@ impl TestEnv {
work_dir: dir_path.clone(),
dir_path,
env_vars: HashMap::default(),
envfiles: vec![],
env_files: vec![],
}
}

/// Testing environment with custom envfile contents.
/// Testing environment with custom env file contents.
///
/// No pre-existing env vars set. The envfile path is set to `.env`. The
/// No pre-existing env vars set. The env file path is set to `.env`. The
/// working directory is the created temporary directory.
pub fn init_with_envfile(contents: impl Into<Vec<u8>>) -> Self {
pub fn init_with_env_file(contents: impl Into<Vec<u8>>) -> Self {
let mut testenv = Self::init();
testenv.add_envfile(".env", contents);
testenv.add_env_file(".env", contents);
testenv
}

/// Add an individual envfile.
/// Add an individual env file.
///
/// ## Arguments
///
Expand All @@ -135,15 +135,15 @@ impl TestEnv {
/// ## Panics
///
/// - if the path is empty or the same as the temporary directory
/// - if the envfile already exists
pub fn add_envfile<P, C>(&mut self, path: P, contents: C) -> &mut Self
/// - if the env file already exists
pub fn add_env_file<P, C>(&mut self, path: P, contents: C) -> &mut Self
where
P: AsRef<Path>,
C: Into<Vec<u8>>,
{
let path = self.dir_path.join(path);
self.assert_envfile_path_is_valid(&path);
self.add_envfile_assume_valid(path, contents.into())
self.assert_env_file_path_is_valid(&path);
self.add_env_file_assume_valid(path, contents.into())
}

/// Add an individual environment variable.
Expand Down Expand Up @@ -212,7 +212,7 @@ impl TestEnv {
/// Create a child folder within the temporary directory.
///
/// This will not change the working directory the test is run in, or where
/// the envfile is created.
/// the env file is created.
///
/// Will create parent directories if they are missing.
pub fn add_child_dir(&mut self, path: impl AsRef<Path>) -> &mut Self {
Expand Down Expand Up @@ -244,24 +244,24 @@ impl TestEnv {
}

/// Get a reference to the environment files that will created
pub fn envfiles(&self) -> &[EnvFile] {
&self.envfiles
pub fn env_files(&self) -> &[EnvFile] {
&self.env_files
}

fn add_envfile_assume_valid(&mut self, path: PathBuf, contents: Vec<u8>) -> &mut Self {
let envfile = EnvFile { path, contents };
self.envfiles.push(envfile);
fn add_env_file_assume_valid(&mut self, path: PathBuf, contents: Vec<u8>) -> &mut Self {
let env_file = EnvFile { path, contents };
self.env_files.push(env_file);
self
}

fn assert_envfile_path_is_valid(&self, path: &Path) {
fn assert_env_file_path_is_valid(&self, path: &Path) {
assert!(
path != self.temp_path(),
"path cannot be empty or the same as the temporary directory"
);
assert!(
!self.envfiles.iter().any(|f| f.path == path),
"envfile already in testenv: {}",
!self.env_files.iter().any(|f| f.path == path),
"env_file already in testenv: {}",
path.display()
);
}
Expand All @@ -279,7 +279,7 @@ impl Default for TestEnv {
fn default() -> Self {
let mut testenv = Self::init();
testenv.add_env_var(DEFAULT_EXISTING_KEY, DEFAULT_EXISTING_VALUE);
testenv.add_envfile(".env", create_default_envfile());
testenv.add_env_file(".env", create_default_env_file());
testenv
}
}
Expand All @@ -306,21 +306,21 @@ fn reset_env(original_env: &EnvMap) {

/// Create an environment to run tests in.
///
/// Writes the envfiles, sets the working directory, and sets environment vars.
/// Writes the env files, sets the working directory, and sets environment vars.
fn create_env(testenv: &TestEnv) {
env::set_current_dir(&testenv.work_dir).expect("setting working directory");

for EnvFile { path, contents } in &testenv.envfiles {
create_envfile(path, contents);
for EnvFile { path, contents } in &testenv.env_files {
create_env_file(path, contents);
}

for (key, value) in &testenv.env_vars {
env::set_var(key, value);
}
}

/// Create an envfile for use in tests.
fn create_envfile(path: &Path, contents: &[u8]) {
/// Create an env file for use in tests.
fn create_env_file(path: &Path, contents: &[u8]) {
fn create_env_file_inner(path: &Path, contents: &[u8]) -> io::Result<()> {
let mut file = fs::File::create(path)?;
file.write_all(contents)?;
Expand All @@ -329,14 +329,14 @@ fn create_envfile(path: &Path, contents: &[u8]) {

assert!(
!path.exists(),
"envfile `{}` already exists",
"env_file `{}` already exists",
path.display()
);
// inner function to group together io::Results

// call inner function
if let Err(err) = create_env_file_inner(path, contents) {
// handle any io::Result::Err
panic!("error creating envfile `{}`: {err}", path.display());
panic!("error creating env_file `{}`: {err}", path.display());
}
}
Loading

0 comments on commit aa9f907

Please sign in to comment.