【问题标题】:Rust - Want to test case env::current_dir() return ErrRust - Want to test case env::current_dir() return Err
【发布时间】:2022-12-01 18:33:45
【问题描述】:

I am creating a function that will check at some point the current directory. In env::current_dir() can return an error, and I want to test the case it does... but I didn't find out how to do it. It's supposed to run on Linux.

Does any one have an idea?

Basic playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=b7d8ed377d2b89521e3fd2736dae383a

Code of the playground:

use std::env;
 
#[allow(unused)]
fn check_current_dir() -> Result<(), &'static str> {
    if let Ok(current_dir) = env::current_dir() {
        println!("Current dir is ok: {:?}", current_dir);
        return Ok(());
    } else {
        return Err("Currentdir failed");
    }
}



#[cfg(test)]
mod check_current_dir {
    use super::*;

    #[test]
   fn current_dir_fail() {
        assert!(check_current_dir().is_ok()) //want to make it fails       
    }
}

I tried creating a directory, moving current directory to it, removing the directory (but that fail), I tried using a symlink directory (but current_dir() return Ok() ).

【问题讨论】:

    标签: linux unit-testing testing rust directory


    【解决方案1】:

    From the manpage of getcwd which current_dir uses on Unix these are the possible failures on Unix:

    ERRORS
           EACCES Permission to read or search a component of the filename was denied.
    
           ENAMETOOLONG
                  getwd(): The size of the null-terminated absolute pathname string exceeds PATH_MAX bytes.
    
           ENOENT The current working directory has been unlinked.
    
           ENOMEM Out of memory.
    

    From wich I excluded EFAULT, EINVAL and ERANGE since Rusts std is handling buf and size for you. So for example this test which removes the current directory will fail:

    use std::fs;
    
    use super::*;
    
    #[test]
    fn current_dir_fail() {
        fs::create_dir("bogus").unwrap();
        std::env::set_current_dir("bogus").unwrap();
        fs::remove_dir("../bogus").unwrap();
        assert!(check_current_dir().is_ok()) //want to make it fail
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 2022-12-01
      • 2022-11-20
      • 2018-11-30
      • 2019-06-07
      • 2022-11-20
      • 1970-01-01
      相关资源
      最近更新 更多