Update to gracefully handle nonexistent relative paths (#691)

* Update Input::new to gracefully handle nonexistent relative paths
* Add test checking Input::new can handle real relative paths
* Add better pre-conditions to Input::new tests
* Add integration tests for handling relative paths in lychee-bin
* Update lychee-lib/src/types/input.rs
This commit is contained in:
Walter Beller-Morales 2022-07-22 11:15:55 -04:00 committed by GitHub
parent 31566419a0
commit 6d40a2ab7b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 78 additions and 0 deletions

View file

@ -874,4 +874,43 @@ mod cli {
Ok(())
}
#[test]
fn test_handle_relative_paths_as_input() -> Result<()> {
let test_path = fixtures_path();
let mut cmd = main_command();
cmd.current_dir(&test_path)
.arg("--verbose")
.arg("--exclude")
.arg("example.*")
.arg("--")
.arg("./TEST_DUMP_EXCLUDE.txt")
.assert()
.success()
.stdout(contains("3 Total"))
.stdout(contains("3 Excluded"));
Ok(())
}
#[test]
fn test_handle_nonexistent_relative_paths_as_input() -> Result<()> {
let test_path = fixtures_path();
let mut cmd = main_command();
cmd.current_dir(&test_path)
.arg("--verbose")
.arg("--exclude")
.arg("example.*")
.arg("--")
.arg("./NOT-A-REAL-TEST-FIXTURE.md")
.assert()
.failure()
.stderr(contains(
"Cannot find local file ./NOT-A-REAL-TEST-FIXTURE.md",
));
Ok(())
}
}

View file

@ -147,6 +147,9 @@ impl Input {
let path = PathBuf::from(value);
if path.exists() {
InputSource::FsPath(path)
} else if path.is_relative() {
// If the file does not exist and it is a relative path, exit immediately
return Err(ErrorKind::FileNotFound(path));
} else {
// Invalid path; check if a valid URL can be constructed from the input
// by prefixing it with a `http://` scheme.
@ -374,6 +377,42 @@ fn is_excluded_path(excluded_paths: &[PathBuf], path: &PathBuf) -> bool {
mod tests {
use super::*;
#[test]
fn test_input_handles_real_relative_paths() {
let test_file = "./Cargo.toml";
let path = Path::new(test_file);
assert!(path.exists());
assert!(path.is_relative());
let input = Input::new(test_file, None, false, None);
assert!(input.is_ok());
assert!(matches!(
input,
Ok(Input {
source: InputSource::FsPath(PathBuf { .. }),
file_type_hint: None,
excluded_paths: None
})
));
}
#[test]
fn test_input_handles_nonexistent_relative_paths() {
let test_file = "./nonexistent/relative/path";
let path = Path::new(test_file);
assert!(!path.exists());
assert!(path.is_relative());
let input = Input::new(test_file, None, false, None);
assert!(input.is_err());
assert!(matches!(
input,
Err(ErrorKind::FileNotFound(PathBuf { .. }))
));
}
#[test]
fn test_valid_extension() {
assert!(valid_extension(Path::new("file.md")));