diff options
author | David Sherret <dsherret@users.noreply.github.com> | 2023-06-10 11:09:45 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-06-10 11:09:45 -0400 |
commit | 7f15126f23d97f20a4fb33e43136cd4d13825863 (patch) | |
tree | 85d77389969b31999680059e65954a9fa863758e /cli | |
parent | f3326eebd6af2aaca1543e8cb543a7b16762bc96 (diff) |
chore(tests): test_util - Add `PathRef` (#19450)
This adds a new `PathRef` struct to test_util for making it easier to
work with paths in test code. I'm going to expand on this more in the
future.
Diffstat (limited to 'cli')
34 files changed, 314 insertions, 446 deletions
diff --git a/cli/args/config_file.rs b/cli/args/config_file.rs index 328a6e574..9d1137b27 100644 --- a/cli/args/config_file.rs +++ b/cli/args/config_file.rs @@ -1258,14 +1258,14 @@ mod tests { #[test] fn read_config_file_absolute() { let path = test_util::testdata_path().join("module_graph/tsconfig.json"); - let config_file = ConfigFile::read(&path).unwrap(); + let config_file = ConfigFile::read(path.as_path()).unwrap(); assert!(config_file.json.compiler_options.is_some()); } #[test] fn include_config_path_on_error() { let path = test_util::testdata_path().join("404.json"); - let error = ConfigFile::read(&path).err().unwrap(); + let error = ConfigFile::read(path.as_path()).err().unwrap(); assert!(error.to_string().contains("404.json")); } @@ -1623,13 +1623,13 @@ mod tests { fn discover_from_success() { // testdata/fmt/deno.jsonc exists let testdata = test_util::testdata_path(); - let c_md = testdata.join("fmt/with_config/subdir/c.md"); + let c_md = testdata.join("fmt/with_config/subdir/c.md").to_path_buf(); let mut checked = HashSet::new(); let config_file = ConfigFile::discover_from(&c_md, &mut checked) .unwrap() .unwrap(); assert!(checked.contains(c_md.parent().unwrap())); - assert!(!checked.contains(&testdata)); + assert!(!checked.contains(testdata.as_path())); let fmt_config = config_file.to_fmt_config().unwrap().unwrap(); let expected_exclude = ModuleSpecifier::from_file_path( testdata.join("fmt/with_config/subdir/b.ts"), @@ -1640,12 +1640,12 @@ mod tests { assert_eq!(fmt_config.files.exclude, vec![expected_exclude]); // Now add all ancestors of testdata to checked. - for a in testdata.ancestors() { + for a in testdata.as_path().ancestors() { checked.insert(a.to_path_buf()); } // If we call discover_from again starting at testdata, we ought to get None. - assert!(ConfigFile::discover_from(&testdata, &mut checked) + assert!(ConfigFile::discover_from(testdata.as_path(), &mut checked) .unwrap() .is_none()); } @@ -1655,7 +1655,7 @@ mod tests { let testdata = test_util::testdata_path(); let d = testdata.join("malformed_config/"); let mut checked = HashSet::new(); - let err = ConfigFile::discover_from(&d, &mut checked).unwrap_err(); + let err = ConfigFile::discover_from(d.as_path(), &mut checked).unwrap_err(); assert!(err.to_string().contains("Unable to parse config file")); } diff --git a/cli/args/mod.rs b/cli/args/mod.rs index d740b9ab0..98e8f3564 100644 --- a/cli/args/mod.rs +++ b/cli/args/mod.rs @@ -1582,9 +1582,10 @@ mod test { temp_dir.write("pages/[id].ts", ""); + let temp_dir_path = temp_dir.path().as_path(); let error = resolve_files( Some(FilesConfig { - include: vec![temp_dir.path().join("data/**********.ts")], + include: vec![temp_dir_path.join("data/**********.ts")], exclude: vec![], }), None, @@ -1595,12 +1596,12 @@ mod test { let resolved_files = resolve_files( Some(FilesConfig { include: vec![ - temp_dir.path().join("data/test1.?s"), - temp_dir.path().join("nested/foo/*.ts"), - temp_dir.path().join("nested/fizz/*.ts"), - temp_dir.path().join("pages/[id].ts"), + temp_dir_path.join("data/test1.?s"), + temp_dir_path.join("nested/foo/*.ts"), + temp_dir_path.join("nested/fizz/*.ts"), + temp_dir_path.join("pages/[id].ts"), ], - exclude: vec![temp_dir.path().join("nested/**/*bazz.ts")], + exclude: vec![temp_dir_path.join("nested/**/*bazz.ts")], }), None, ) @@ -1609,24 +1610,24 @@ mod test { assert_eq!( resolved_files.include, vec![ - temp_dir.path().join("data/test1.js"), - temp_dir.path().join("data/test1.ts"), - temp_dir.path().join("nested/foo/bar.ts"), - temp_dir.path().join("nested/foo/bazz.ts"), - temp_dir.path().join("nested/foo/fizz.ts"), - temp_dir.path().join("nested/foo/foo.ts"), - temp_dir.path().join("nested/fizz/bar.ts"), - temp_dir.path().join("nested/fizz/bazz.ts"), - temp_dir.path().join("nested/fizz/fizz.ts"), - temp_dir.path().join("nested/fizz/foo.ts"), - temp_dir.path().join("pages/[id].ts"), + temp_dir_path.join("data/test1.js"), + temp_dir_path.join("data/test1.ts"), + temp_dir_path.join("nested/foo/bar.ts"), + temp_dir_path.join("nested/foo/bazz.ts"), + temp_dir_path.join("nested/foo/fizz.ts"), + temp_dir_path.join("nested/foo/foo.ts"), + temp_dir_path.join("nested/fizz/bar.ts"), + temp_dir_path.join("nested/fizz/bazz.ts"), + temp_dir_path.join("nested/fizz/fizz.ts"), + temp_dir_path.join("nested/fizz/foo.ts"), + temp_dir_path.join("pages/[id].ts"), ] ); assert_eq!( resolved_files.exclude, vec![ - temp_dir.path().join("nested/fizz/bazz.ts"), - temp_dir.path().join("nested/foo/bazz.ts"), + temp_dir_path.join("nested/fizz/bazz.ts"), + temp_dir_path.join("nested/foo/bazz.ts"), ] ) } diff --git a/cli/bench/http.rs b/cli/bench/http.rs index 031e9801c..909c4937c 100644 --- a/cli/bench/http.rs +++ b/cli/bench/http.rs @@ -23,7 +23,7 @@ pub fn benchmark( target_path: &Path, ) -> Result<HashMap<String, HttpBenchmarkResult>> { let deno_exe = test_util::deno_exe_path(); - let deno_exe = deno_exe.to_str().unwrap(); + let deno_exe = deno_exe.to_string(); let hyper_hello_exe = target_path.join("test_server"); let hyper_hello_exe = hyper_hello_exe.to_str().unwrap(); @@ -82,7 +82,7 @@ pub fn benchmark( res.insert( file_stem.to_string(), run( - &[bun_exe.to_str().unwrap(), path, &port.to_string()], + &[&bun_exe.to_string(), path, &port.to_string()], port, None, None, @@ -95,7 +95,7 @@ pub fn benchmark( file_stem.to_string(), run( &[ - deno_exe, + deno_exe.as_str(), "run", "--allow-all", "--unstable", @@ -160,8 +160,8 @@ fn run( assert!(wrk.is_file()); let addr = format!("http://127.0.0.1:{port}/"); - let mut wrk_cmd = - vec![wrk.to_str().unwrap(), "-d", DURATION, "--latency", &addr]; + let wrk = wrk.to_string(); + let mut wrk_cmd = vec![wrk.as_str(), "-d", DURATION, "--latency", &addr]; if let Some(lua_script) = lua_script { wrk_cmd.push("-s"); diff --git a/cli/bench/main.rs b/cli/bench/main.rs index 721cf06ab..fdeb588f4 100644 --- a/cli/bench/main.rs +++ b/cli/bench/main.rs @@ -12,6 +12,7 @@ use std::path::PathBuf; use std::process::Command; use std::process::Stdio; use std::time::SystemTime; +use test_util::PathRef; include!("../util/time.rs"); @@ -19,12 +20,12 @@ mod http; mod lsp; mod websocket; -fn read_json(filename: &str) -> Result<Value> { +fn read_json(filename: &Path) -> Result<Value> { let f = fs::File::open(filename)?; Ok(serde_json::from_reader(f)?) } -fn write_json(filename: &str, value: &Value) -> Result<()> { +fn write_json(filename: &Path, value: &Value) -> Result<()> { let f = fs::File::create(filename)?; serde_json::to_writer(f, value)?; Ok(()) @@ -170,17 +171,17 @@ const RESULT_KEYS: &[&str] = &["mean", "stddev", "user", "system", "min", "max"]; fn run_exec_time( deno_exe: &Path, - target_dir: &Path, + target_dir: &PathRef, ) -> Result<HashMap<String, HashMap<String, f64>>> { - let hyperfine_exe = test_util::prebuilt_tool_path("hyperfine"); + let hyperfine_exe = test_util::prebuilt_tool_path("hyperfine").to_string(); let benchmark_file = target_dir.join("hyperfine_results.json"); - let benchmark_file = benchmark_file.to_str().unwrap(); + let benchmark_file_str = benchmark_file.to_string(); let mut command = [ - hyperfine_exe.to_str().unwrap(), + hyperfine_exe.as_str(), "--export-json", - benchmark_file, + benchmark_file_str.as_str(), "--warmup", "3", ] @@ -213,7 +214,7 @@ fn run_exec_time( ); let mut results = HashMap::<String, HashMap<String, f64>>::new(); - let hyperfine_results = read_json(benchmark_file)?; + let hyperfine_results = read_json(benchmark_file.as_path())?; for ((name, _, _), data) in EXEC_TIME_BENCHMARKS.iter().zip( hyperfine_results .as_object() @@ -270,7 +271,7 @@ fn get_binary_sizes(target_dir: &Path) -> Result<HashMap<String, i64>> { sizes.insert( "deno".to_string(), - test_util::deno_exe_path().metadata()?.len() as i64, + test_util::deno_exe_path().as_path().metadata()?.len() as i64, ); // add up size for everything in target/release/deps/libswc* @@ -440,7 +441,7 @@ async fn main() -> Result<()> { println!("Starting Deno benchmark"); let target_dir = test_util::target_dir(); - let deno_exe = test_util::deno_exe_path(); + let deno_exe = test_util::deno_exe_path().to_path_buf(); env::set_current_dir(test_util::root_path())?; let mut new_data = BenchResult { @@ -474,7 +475,7 @@ async fn main() -> Result<()> { } if benchmarks.contains(&"binary_size") { - let binary_sizes = get_binary_sizes(&target_dir)?; + let binary_sizes = get_binary_sizes(target_dir.as_path())?; new_data.binary_size = binary_sizes; } @@ -489,7 +490,7 @@ async fn main() -> Result<()> { } if benchmarks.contains(&"http") && cfg!(not(target_os = "windows")) { - let stats = http::benchmark(&target_dir)?; + let stats = http::benchmark(target_dir.as_path())?; let req_per_sec = stats .iter() .map(|(name, result)| (name.clone(), result.requests as i64)) @@ -554,11 +555,10 @@ async fn main() -> Result<()> { new_data.max_memory = max_memory; } - if let Some(filename) = target_dir.join("bench.json").to_str() { - write_json(filename, &serde_json::to_value(&new_data)?)?; - } else { - eprintln!("Cannot write bench.json, path is invalid"); - } + write_json( + target_dir.join("bench.json").as_path(), + &serde_json::to_value(&new_data)?, + )?; Ok(()) } diff --git a/cli/bench/websocket.rs b/cli/bench/websocket.rs index 84a799660..0296d4ce8 100644 --- a/cli/bench/websocket.rs +++ b/cli/bench/websocket.rs @@ -10,7 +10,6 @@ use super::Result; pub fn benchmark() -> Result<HashMap<String, f64>> { let deno_exe = test_util::deno_exe_path(); - let deno_exe = deno_exe.to_str().unwrap(); let mut res = HashMap::new(); let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR")); @@ -22,7 +21,7 @@ pub fn benchmark() -> Result<HashMap<String, f64>> { let path = pathbuf.to_str().unwrap(); let file_stem = pathbuf.file_stem().unwrap().to_str().unwrap(); - let mut cmd = Command::new(deno_exe); + let mut cmd = Command::new(&deno_exe); let mut server = cmd .arg("run") .arg("-A") diff --git a/cli/cache/disk_cache.rs b/cli/cache/disk_cache.rs index 042064463..456b59912 100644 --- a/cli/cache/disk_cache.rs +++ b/cli/cache/disk_cache.rs @@ -166,9 +166,8 @@ mod tests { #[test] fn test_create_cache_if_dir_exits() { let cache_location = TempDir::new(); - let mut cache_path = cache_location.path().to_owned(); - cache_path.push("foo"); - let cache = DiskCache::new(&cache_path); + let cache_path = cache_location.path().join("foo"); + let cache = DiskCache::new(cache_path.as_path()); cache .ensure_dir_exists(&cache.location) .expect("Testing expect:"); @@ -178,11 +177,11 @@ mod tests { #[test] fn test_create_cache_if_dir_not_exits() { let temp_dir = TempDir::new(); - let mut cache_location = temp_dir.path().to_owned(); - assert!(fs::remove_dir(&cache_location).is_ok()); - cache_location.push("foo"); + let cache_location = temp_dir.path(); + cache_location.remove_dir_all(); + let cache_location = cache_location.join("foo"); assert!(!cache_location.is_dir()); - let cache = DiskCache::new(&cache_location); + let cache = DiskCache::new(cache_location.as_path()); cache .ensure_dir_exists(&cache.location) .expect("Testing expect:"); diff --git a/cli/cache/emit.rs b/cli/cache/emit.rs index dd7b9e662..f0e94d209 100644 --- a/cli/cache/emit.rs +++ b/cli/cache/emit.rs @@ -159,7 +159,7 @@ mod test { #[test] pub fn emit_cache_general_use() { let temp_dir = TempDir::new(); - let disk_cache = DiskCache::new(temp_dir.path()); + let disk_cache = DiskCache::new(temp_dir.path().as_path()); let cache = EmitCache { disk_cache: disk_cache.clone(), cli_version: "1.0.0", diff --git a/cli/cache/http_cache.rs b/cli/cache/http_cache.rs index b10c59756..e98f4bad7 100644 --- a/cli/cache/http_cache.rs +++ b/cli/cache/http_cache.rs @@ -111,11 +111,9 @@ impl HttpCache { /// Returns a new instance. /// /// `location` must be an absolute path. - pub fn new(location: &Path) -> Self { + pub fn new(location: PathBuf) -> Self { assert!(location.is_absolute()); - Self { - location: location.to_owned(), - } + Self { location } } /// Ensures the location of the cache. @@ -192,8 +190,7 @@ mod tests { #[test] fn test_create_cache() { let dir = TempDir::new(); - let mut cache_path = dir.path().to_owned(); - cache_path.push("foobar"); + let cache_path = dir.path().join("foobar"); // HttpCache should be created lazily on first use: // when zipping up a local project with no external dependencies // "$DENO_DIR/deps" is empty. When unzipping such project @@ -203,7 +200,7 @@ mod tests { // doesn't make sense to return error in such specific scenarios. // For more details check issue: // https://github.com/denoland/deno/issues/5688 - let cache = HttpCache::new(&cache_path); + let cache = HttpCache::new(cache_path.to_path_buf()); assert!(!cache.location.exists()); cache .set( @@ -219,7 +216,7 @@ mod tests { #[test] fn test_get_set() { let dir = TempDir::new(); - let cache = HttpCache::new(dir.path()); + let cache = HttpCache::new(dir.path().to_path_buf()); let url = Url::parse("https://deno.land/x/welcome.ts").unwrap(); let mut headers = HashMap::new(); headers.insert( diff --git a/cli/factory.rs b/cli/factory.rs index 30055da7d..a95f0facf 100644 --- a/cli/factory.rs +++ b/cli/factory.rs @@ -247,7 +247,7 @@ impl CliFactory { pub fn file_fetcher(&self) -> Result<&Arc<FileFetcher>, AnyError> { self.services.file_fetcher.get_or_try_init(|| { Ok(Arc::new(FileFetcher::new( - HttpCache::new(&self.deno_dir()?.deps_folder_path()), + HttpCache::new(self.deno_dir()?.deps_folder_path()), self.options.cache_setting(), !self.options.no_remote(), self.http_client().clone(), diff --git a/cli/file_fetcher.rs b/cli/file_fetcher.rs index 71d284ef6..17cc73bf2 100644 --- a/cli/file_fetcher.rs +++ b/cli/file_fetcher.rs @@ -764,10 +764,10 @@ mod tests { maybe_temp_dir: Option<TempDir>, ) -> (FileFetcher, TempDir, BlobStore) { let temp_dir = maybe_temp_dir.unwrap_or_default(); - let location = temp_dir.path().join("deps"); + let location = temp_dir.path().join("deps").to_path_buf(); let blob_store = BlobStore::default(); let file_fetcher = FileFetcher::new( - HttpCache::new(&location), + HttpCache::new(location), cache_setting, true, Arc::new(HttpClient::new(None, None)), @@ -827,8 +827,7 @@ mod tests { async fn test_fetch_local_encoded(charset: &str, expected: String) { let p = test_util::testdata_path().join(format!("encoding/{charset}.ts")); - let specifier = - ModuleSpecifier::from_file_path(p.to_str().unwrap()).unwrap(); + let specifier = ModuleSpecifier::from_file_path(p).unwrap(); let (file, _) = test_fetch(&specifier).await; assert_eq!(&*file.source, expected); } @@ -1034,11 +1033,9 @@ mod tests { async fn test_insert_cached() { let (file_fetcher, temp_dir) = setup(CacheSetting::Use, None); let local = temp_dir.path().join("a.ts"); - let specifier = - ModuleSpecifier::from_file_path(local.as_os_str().to_str().unwrap()) - .unwrap(); + let specifier = ModuleSpecifier::from_file_path(&local).unwrap(); let file = File { - local, + local: local.to_path_buf(), maybe_types: None, media_type: MediaType::TypeScript, source: "some source code".into(), @@ -1082,7 +1079,7 @@ mod tests { #[test] fn test_get_http_cache_location() { let (file_fetcher, temp_dir) = setup(CacheSetting::Use, None); - let expected = temp_dir.path().join("deps"); + let expected = temp_dir.path().join("deps").to_path_buf(); let actual = file_fetcher.get_http_cache_location(); assert_eq!(actual, expected); } @@ -1203,9 +1200,9 @@ mod tests { // This creates a totally new instance, simulating another Deno process // invocation and indicates to "cache bust". - let location = temp_dir.path().join("deps"); + let location = temp_dir.path().join("deps").to_path_buf(); let file_fetcher = FileFetcher::new( - HttpCache::new(&location), + HttpCache::new(location), CacheSetting::ReloadAll, true, Arc::new(HttpClient::new(None, None)), @@ -1228,9 +1225,9 @@ mod tests { async fn test_fetch_uses_cache() { let _http_server_guard = test_util::http_server(); let temp_dir = TempDir::new(); - let location = temp_dir.path().join("deps"); + let location = temp_dir.path().join("deps").to_path_buf(); let file_fetcher_01 = FileFetcher::new( - HttpCache::new(&location), + HttpCache::new(location.clone()), CacheSetting::Use, true, Arc::new(HttpClient::new(None, None)), @@ -1255,7 +1252,7 @@ mod tests { let metadata_file_modified_01 = metadata_file_metadata.modified().unwrap(); let file_fetcher_02 = FileFetcher::new( - HttpCache::new(&location), + HttpCache::new(location), CacheSetting::Use, true, Arc::new(HttpClient::new(None, None)), @@ -1394,9 +1391,9 @@ mod tests { async fn test_fetch_uses_cache_with_redirects() { let _http_server_guard = test_util::http_server(); let temp_dir = TempDir::new(); - let location = temp_dir.path().join("deps"); + let location = temp_dir.path().join("deps").to_path_buf(); let file_fetcher_01 = FileFetcher::new( - HttpCache::new(&location), + HttpCache::new(location.clone()), CacheSetting::Use, true, Arc::new(HttpClient::new(None, None)), @@ -1424,7 +1421,7 @@ mod tests { let metadata_file_modified_01 = metadata_file_metadata.modified().unwrap(); let file_fetcher_02 = FileFetcher::new( - HttpCache::new(&location), + HttpCache::new(location), CacheSetting::Use, true, Arc::new(HttpClient::new(None, None)), @@ -1521,9 +1518,9 @@ mod tests { async fn test_fetch_no_remote() { let _http_server_guard = test_util::http_server(); let temp_dir = TempDir::new(); - let location = temp_dir.path().join("deps"); + let location = temp_dir.path().join("deps").to_path_buf(); let file_fetcher = FileFetcher::new( - HttpCache::new(&location), + HttpCache::new(location), CacheSetting::Use, false, Arc::new(HttpClient::new(None, None)), @@ -1546,9 +1543,9 @@ mod tests { async fn test_fetch_cache_only() { let _http_server_guard = test_util::http_server(); let temp_dir = TempDir::new(); - let location = temp_dir.path().join("deps"); + let location = temp_dir.path().join("deps").to_path_buf(); let file_fetcher_01 = FileFetcher::new( - HttpCache::new(&location), + HttpCache::new(location.clone()), CacheSetting::Only, true, Arc::new(HttpClient::new(None, None)), @@ -1556,7 +1553,7 @@ mod tests { None, ); let file_fetcher_02 = FileFetcher::new( - HttpCache::new(&location), + HttpCache::new(location), CacheSetting::Use, true, Arc::new(HttpClient::new(None, None)), @@ -1946,10 +1943,7 @@ mod tests { version::get_user_agent(), CreateHttpClientOptions { ca_certs: vec![read( - test_util::testdata_path() - .join("tls/RootCA.pem") - .to_str() - .unwrap(), + test_util::testdata_path().join("tls/RootCA.pem"), ) .unwrap()], ..Default::default() @@ -2068,8 +2062,7 @@ mod tests { ca_certs: vec![read( test_util::testdata_path() .join("tls/RootCA.pem") - .to_str() - .unwrap(), + .to_string(), ) .unwrap()], ..Default::default() @@ -2112,8 +2105,7 @@ mod tests { ca_certs: vec![read( test_util::testdata_path() .join("tls/RootCA.pem") - .to_str() - .unwrap(), + .to_string(), ) .unwrap()], ..Default::default() @@ -2173,8 +2165,7 @@ mod tests { ca_certs: vec![read( test_util::testdata_path() .join("tls/RootCA.pem") - .to_str() - .unwrap(), + .to_string(), ) .unwrap()], ..Default::default() diff --git a/cli/lsp/cache.rs b/cli/lsp/cache.rs index f047e5fd4..df88254ee 100644 --- a/cli/lsp/cache.rs +++ b/cli/lsp/cache.rs @@ -8,6 +8,7 @@ use deno_core::ModuleSpecifier; use std::collections::HashMap; use std::fs; use std::path::Path; +use std::path::PathBuf; use std::sync::Arc; use std::time::SystemTime; @@ -97,7 +98,7 @@ impl CacheMetadata { Some(metadata) } - pub fn set_location(&mut self, location: &Path) { + pub fn set_location(&mut self, location: PathBuf) { self.cache = HttpCache::new(location); self.metadata.lock().clear(); } diff --git a/cli/lsp/completions.rs b/cli/lsp/completions.rs index 070e3168a..17a00010b 100644 --- a/cli/lsp/completions.rs +++ b/cli/lsp/completions.rs @@ -519,13 +519,13 @@ mod tests { source_fixtures: &[(&str, &str)], location: &Path, ) -> Documents { - let mut documents = Documents::new(location); + let mut documents = Documents::new(location.to_path_buf()); for (specifier, source, version, language_id) in fixtures { let specifier = resolve_url(specifier).expect("failed to create specifier"); documents.open(specifier, *version, *language_id, (*source).into()); } - let http_cache = HttpCache::new(location); + let http_cache = HttpCache::new(location.to_path_buf()); for (specifier, source) in source_fixtures { let specifier = resolve_url(specifier).expect("failed to create specifier"); @@ -546,7 +546,7 @@ mod tests { sources: &[(&str, &str)], ) -> Documents { let location = temp_dir.path().join("deps"); - mock_documents(documents, sources, &location) + mock_documents(documents, sources, location.as_path()) } #[test] diff --git a/cli/lsp/diagnostics.rs b/cli/lsp/diagnostics.rs index 6af6c92b3..9acb9cef5 100644 --- a/cli/lsp/diagnostics.rs +++ b/cli/lsp/diagnostics.rs @@ -1198,7 +1198,7 @@ mod tests { location: &Path, maybe_import_map: Option<(&str, &str)>, ) -> StateSnapshot { - let mut documents = Documents::new(location); + let mut documents = Documents::new(location.to_path_buf()); for (specifier, source, version, language_id) in fixtures { let specifier = resolve_url(specifier).expect("failed to create specifier"); @@ -1243,7 +1243,7 @@ mod tests { sources: &[(&str, &str, i32, LanguageId)], maybe_import_map: Option<(&str, &str)>, ) -> (StateSnapshot, PathBuf) { - let location = temp_dir.path().join("deps"); + let location = temp_dir.path().join("deps").to_path_buf(); let state_snapshot = mock_state_snapshot(sources, &location, maybe_import_map); (state_snapshot, location) diff --git a/cli/lsp/documents.rs b/cli/lsp/documents.rs index d088e01c0..1282f8a18 100644 --- a/cli/lsp/documents.rs +++ b/cli/lsp/documents.rs @@ -661,9 +661,9 @@ struct SpecifierResolver { } impl SpecifierResolver { - pub fn new(cache_path: &Path) -> Self { + pub fn new(cache: HttpCache) -> Self { Self { - cache: HttpCache::new(cache_path), + cache, redirects: Mutex::new(HashMap::new()), } } @@ -846,9 +846,10 @@ pub struct Documents { } impl Documents { - pub fn new(location: &Path) -> Self { + pub fn new(location: PathBuf) -> Self { + let cache = HttpCache::new(location); Self { - cache: HttpCache::new(location), + cache: cache.clone(), dirty: true, dependents_map: Default::default(), open_docs: HashMap::default(), @@ -858,7 +859,7 @@ impl Documents { resolver: Default::default(), npm_specifier_reqs: Default::default(), has_injected_types_node_package: false, - specifier_resolver: Arc::new(SpecifierResolver::new(location)), + specifier_resolver: Arc::new(SpecifierResolver::new(cache)), } } @@ -1136,10 +1137,11 @@ impl Documents { } /// Update the location of the on disk cache for the document store. - pub fn set_location(&mut self, location: &Path) { + pub fn set_location(&mut self, location: PathBuf) { // TODO update resolved dependencies? - self.cache = HttpCache::new(location); - self.specifier_resolver = Arc::new(SpecifierResolver::new(location)); + let cache = HttpCache::new(location); + self.cache = cache.clone(); + self.specifier_resolver = Arc::new(SpecifierResolver::new(cache)); self.dirty = true; } @@ -1785,11 +1787,12 @@ mod tests { use super::*; use import_map::ImportMap; use pretty_assertions::assert_eq; + use test_util::PathRef; use test_util::TempDir; - fn setup(temp_dir: &TempDir) -> (Documents, PathBuf) { + fn setup(temp_dir: &TempDir) -> (Documents, PathRef) { let location = temp_dir.path().join("deps"); - let documents = Documents::new(&location); + let documents = Documents::new(location.to_path_buf()); (documents, location) } @@ -1861,8 +1864,8 @@ console.log(b, "hello deno"); let (mut documents, documents_path) = setup(&temp_dir); let file_path = documents_path.join("file.ts"); let file_specifier = ModuleSpecifier::from_file_path(&file_path).unwrap(); - fs::create_dir_all(&documents_path).unwrap(); - fs::write(&file_path, "").unwrap(); + documents_path.create_dir_all(); + file_path.write(""); // open the document documents.open( diff --git a/cli/lsp/language_server.rs b/cli/lsp/language_server.rs index ecd91f459..cf7179670 100644 --- a/cli/lsp/language_server.rs +++ b/cli/lsp/language_server.rs @@ -605,11 +605,13 @@ impl Inner { let dir = DenoDir::new(None).expect("could not access DENO_DIR"); let module_registries_location = dir.registries_folder_path(); let http_client = Arc::new(HttpClient::new(None, None)); - let module_registries = - ModuleRegistry::new(&module_registries_location, http_client.clone()); + let module_registries = ModuleRegistry::new( + module_registries_location.clone(), + http_client.clone(), + ); let location = dir.deps_folder_path(); - let documents = Documents::new(&location); - let deps_http_cache = HttpCache::new(&location); + let documents = Documents::new(location.clone()); + let deps_http_cache = HttpCache::new(location); let cache_metadata = cache::CacheMetadata::new(deps_http_cache.clone()); let performance = Arc::new(Performance::default()); let ts_server = Arc::new(TsServer::new(performance.clone())); @@ -944,14 +946,14 @@ impl Inner { .clone(), )); self.module_registries = ModuleRegistry::new( - &module_registries_location, + module_registries_location.clone(), self.http_client.clone(), ); self.module_registries_location = module_registries_location; // update the cache path let location = dir.deps_folder_path(); - self.documents.set_location(&location); - self.cache_metadata.set_location(&location); + self.documents.set_location(location.clone()); + self.cache_metadata.set_location(location); self.maybe_cache_path = new_cache_path; Ok(()) } diff --git a/cli/lsp/registries.rs b/cli/lsp/registries.rs index b2f9bee2c..f683fa588 100644 --- a/cli/lsp/registries.rs +++ b/cli/lsp/registries.rs @@ -34,7 +34,7 @@ use deno_runtime::permissions::PermissionsContainer; use log::error; use once_cell::sync::Lazy; use std::collections::HashMap; -use std::path::Path; +use std::path::PathBuf; use std::sync::Arc; use tower_lsp::lsp_types as lsp; @@ -427,12 +427,12 @@ impl Default for ModuleRegistry { let dir = DenoDir::new(None).unwrap(); let location = dir.registries_folder_path(); let http_client = Arc::new(HttpClient::new(None, None)); - Self::new(&location, http_client) + Self::new(location, http_client) } } impl ModuleRegistry { - pub fn new(location: &Path, http_client: Arc<HttpClient>) -> Self { + pub fn new(location: PathBuf, http_client: Arc<HttpClient>) -> Self { let http_cache = HttpCache::new(location); let mut file_fetcher = FileFetcher::new( http_cache, @@ -1247,9 +1247,9 @@ mod tests { async fn test_registry_completions_origin_match() { let _g = test_util::http_server(); let temp_dir = TempDir::new(); - let location = temp_dir.path().join("registries"); + let location = temp_dir.path().join("registries").to_path_buf(); let mut module_registry = - ModuleRegistry::new(&location, Arc::new(HttpClient::new(None, None))); + ModuleRegistry::new(location, Arc::new(HttpClient::new(None, None))); module_registry .enable("http://localhost:4545/") .await @@ -1308,9 +1308,9 @@ mod tests { async fn test_registry_completions() { let _g = test_util::http_server(); let temp_dir = TempDir::new(); - let location = temp_dir.path().join("registries"); + let location = temp_dir.path().join("registries").to_path_buf(); let mut module_registry = - ModuleRegistry::new(&location, Arc::new(HttpClient::new(None, None))); + ModuleRegistry::new(location, Arc::new(HttpClient::new(None, None))); module_registry .enable("http://localhost:4545/") .await @@ -1531,9 +1531,9 @@ mod tests { async fn test_registry_completions_key_first() { let _g = test_util::http_server(); let temp_dir = TempDir::new(); - let location = temp_dir.path().join("registries"); + let location = temp_dir.path().join("registries").to_path_buf(); let mut module_registry = - ModuleRegistry::new(&location, Arc::new(HttpClient::new(None, None))); + ModuleRegistry::new(location, Arc::new(HttpClient::new(None, None))); module_registry .enable_custom("http://localhost:4545/lsp/registries/deno-import-intellisense-key-first.json") .await @@ -1601,9 +1601,9 @@ mod tests { async fn test_registry_completions_complex() { let _g = test_util::http_server(); let temp_dir = TempDir::new(); - let location = temp_dir.path().join("registries"); + let location = temp_dir.path().join("registries").to_path_buf(); let mut module_registry = - ModuleRegistry::new(&location, Arc::new(HttpClient::new(None, None))); + ModuleRegistry::new(location, Arc::new(HttpClient::new(None, None))); module_registry .enable_custom("http://localhost:4545/lsp/registries/deno-import-intellisense-complex.json") .await @@ -1652,9 +1652,9 @@ mod tests { async fn test_check_origin_supported() { let _g = test_util::http_server(); let temp_dir = TempDir::new(); - let location = temp_dir.path().join("registries"); + let location = temp_dir.path().join("registries").to_path_buf(); let module_registry = - ModuleRegistry::new(&location, Arc::new(HttpClient::new(None, None))); + ModuleRegistry::new(location, Arc::new(HttpClient::new(None, None))); let result = module_registry.check_origin("http://localhost:4545").await; assert!(result.is_ok()); } @@ -1663,9 +1663,9 @@ mod tests { async fn test_check_origin_not_supported() { let _g = test_util::http_server(); let temp_dir = TempDir::new(); - let location = temp_dir.path().join("registries"); + let location = temp_dir.path().join("registries").to_path_buf(); let module_registry = - ModuleRegistry::new(&location, Arc::new(HttpClient::new(None, None))); + ModuleRegistry::new(location, Arc::new(HttpClient::new(None, None))); let result = module_registry.check_origin("https://example.com").await; assert!(result.is_err()); let err = result.unwrap_err().to_string(); diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs index 0e52f8d87..66687789b 100644 --- a/cli/lsp/tsc.rs +++ b/cli/lsp/tsc.rs @@ -3903,7 +3903,7 @@ mod tests { fixtures: &[(&str, &str, i32, LanguageId)], location: &Path, ) -> StateSnapshot { - let mut documents = Documents::new(location); + let mut documents = Documents::new(location.to_path_buf()); for (specifier, source, version, language_id) in fixtures { let specifier = resolve_url(specifier).expect("failed to create specifier"); @@ -3926,7 +3926,7 @@ mod tests { config: Value, sources: &[(&str, &str, i32, LanguageId)], ) -> (JsRuntime, Arc<StateSnapshot>, PathBuf) { - let location = temp_dir.path().join("deps"); + let location = temp_dir.path().join("deps").to_path_buf(); let state_snapshot = Arc::new(mock_state_snapshot(sources, &location)); let mut runtime = js_runtime(Default::default()); start(&mut runtime, debug).unwrap(); @@ -4406,7 +4406,7 @@ mod tests { LanguageId::TypeScript, )], ); - let cache = HttpCache::new(&location); + let cache = HttpCache::new(location); let specifier_dep = resolve_url("https://deno.land/x/example/a.ts").unwrap(); cache diff --git a/cli/standalone/virtual_fs.rs b/cli/standalone/virtual_fs.rs index 44d3a1591..666683ddf 100644 --- a/cli/standalone/virtual_fs.rs +++ b/cli/standalone/virtual_fs.rs @@ -850,9 +850,9 @@ mod test { let temp_dir = TempDir::new(); // we canonicalize the temp directory because the vfs builder // will canonicalize the root path - let temp_dir_path = canonicalize_path(temp_dir.path()).unwrap(); - let src_path = temp_dir_path.join("src"); - temp_dir.create_dir_all(&src_path); + let src_path = temp_dir.path().canonicalize().join("src"); + src_path.create_dir_all(); + let src_path = src_path.to_path_buf(); let mut builder = VfsBuilder::new(src_path.clone()).unwrap(); builder .add_file(&src_path.join("a.txt"), "data".into()) @@ -922,19 +922,19 @@ mod test { #[test] fn test_include_dir_recursive() { let temp_dir = TempDir::new(); - let temp_dir_path = canonicalize_path(temp_dir.path()).unwrap(); + let temp_dir_path = temp_dir.path().canonicalize(); temp_dir.create_dir_all("src/nested/sub_dir"); temp_dir.write("src/a.txt", "data"); temp_dir.write("src/b.txt", "data"); util::fs::symlink_dir( - &temp_dir_path.join("src/nested/sub_dir"), - &temp_dir_path.join("src/sub_dir_link"), + temp_dir_path.join("src/nested/sub_dir").as_path(), + temp_dir_path.join("src/sub_dir_link").as_path(), ) .unwrap(); temp_dir.write("src/nested/sub_dir/c.txt", "c"); // build and create the virtual fs - let src_path = temp_dir_path.join("src"); + let src_path = temp_dir_path.join("src").to_path_buf(); let mut builder = VfsBuilder::new(src_path.clone()).unwrap(); builder.add_dir_recursive(&src_path).unwrap(); let (dest_path, virtual_fs) = into_virtual_fs(builder, &temp_dir); @@ -983,12 +983,12 @@ mod test { let file = std::fs::File::open(&virtual_fs_file).unwrap(); let dest_path = temp_dir.path().join("dest"); ( - dest_path.clone(), + dest_path.to_path_buf(), FileBackedVfs::new( file, VfsRoot { dir: root_dir, - root_path: dest_path, + root_path: dest_path.to_path_buf(), start_file_offset: 0, }, ), @@ -998,9 +998,9 @@ mod test { #[test] fn circular_symlink() { let temp_dir = TempDir::new(); - let temp_dir_path = canonicalize_path(temp_dir.path()).unwrap(); - let src_path = temp_dir_path.join("src"); - temp_dir.create_dir_all(&src_path); + let src_path = temp_dir.path().canonicalize().join("src"); + src_path.create_dir_all(); + let src_path = src_path.to_path_buf(); let mut builder = VfsBuilder::new(src_path.clone()).unwrap(); builder .add_symlink(&src_path.join("a.txt"), &src_path.join("b.txt")) @@ -1033,11 +1033,11 @@ mod test { #[tokio::test] async fn test_open_file() { let temp_dir = TempDir::new(); - let temp_path = canonicalize_path(temp_dir.path()).unwrap(); + let temp_path = temp_dir.path().canonicalize(); let mut builder = VfsBuilder::new(temp_path.to_path_buf()).unwrap(); builder .add_file( - &temp_path.join("a.txt"), + temp_path.join("a.txt").as_path(), "0123456789".to_string().into_bytes(), ) .unwrap(); diff --git a/cli/tests/integration/cache_tests.rs b/cli/tests/integration/cache_tests.rs index e8449ca05..3d387f15e 100644 --- a/cli/tests/integration/cache_tests.rs +++ b/cli/tests/integration/cache_tests.rs @@ -61,13 +61,11 @@ fn relative_home_dir() { use test_util as util; use test_util::TempDir; - let deno_dir = TempDir::new_in(&util::testdata_path()); - let path = deno_dir.path().strip_prefix(util::testdata_path()).unwrap(); - + let deno_dir = TempDir::new(); let mut deno_cmd = util::deno_cmd(); let output = deno_cmd .current_dir(util::testdata_path()) - .env("XDG_CACHE_HOME", path) + .env("XDG_CACHE_HOME", deno_dir.path()) .env_remove("HOME") .env_remove("DENO_DIR") .arg("cache") diff --git a/cli/tests/integration/cert_tests.rs b/cli/tests/integration/cert_tests.rs index b04f2d35e..ffd4b449d 100644 --- a/cli/tests/integration/cert_tests.rs +++ b/cli/tests/integration/cert_tests.rs @@ -82,7 +82,7 @@ fn cafile_env_fetch() { context .new_command() .args(format!("cache {module_url}")) - .env("DENO_CERT", cafile.to_string_lossy()) + .env("DENO_CERT", cafile) .run() .assert_exit_code(0) .skip_output_check(); @@ -96,11 +96,7 @@ fn cafile_fetch() { let cafile = context.testdata_path().join("tls/RootCA.pem"); context .new_command() - .args(format!( - "cache --quiet --cert {} {}", - cafile.to_string_lossy(), - module_url, - )) + .args(format!("cache --quiet --cert {} {}", cafile, module_url,)) .run() .assert_exit_code(0) .assert_matches_text(""); @@ -116,13 +112,13 @@ fn cafile_compile() { temp_dir.join("cert") }; let output = context.new_command() - .args(format!("compile --quiet --cert ./tls/RootCA.pem --allow-net --output {} ./cert/cafile_ts_fetch.ts", output_exe.to_string_lossy())) + .args(format!("compile --quiet --cert ./tls/RootCA.pem --allow-net --output {} ./cert/cafile_ts_fetch.ts", output_exe)) .run(); output.skip_output_check(); context .new_command() - .command_name(output_exe.to_string_lossy()) + .command_name(output_exe) .run() .assert_matches_text("[WILDCARD]\nHello\n"); } diff --git a/cli/tests/integration/check_tests.rs b/cli/tests/integration/check_tests.rs index 84ed92990..41c568ad3 100644 --- a/cli/tests/integration/check_tests.rs +++ b/cli/tests/integration/check_tests.rs @@ -204,10 +204,10 @@ fn typecheck_core() { format!( "import \"{}\";", deno_core::resolve_path( - util::root_path() - .join("core/lib.deno_core.d.ts") - .to_str() - .unwrap(), + &util::root_path() + .join("core") + .join("lib.deno_core.d.ts") + .to_string(), &std::env::current_dir().unwrap() ) .unwrap() @@ -215,7 +215,7 @@ fn typecheck_core() { ) .unwrap(); - let args = vec!["run".to_string(), test_file.to_string_lossy().into_owned()]; + let args = vec!["run".to_string(), test_file.to_string()]; let output = context.new_command().args_vec(args).split_output().run(); println!("stdout: {}", output.stdout()); diff --git a/cli/tests/integration/compile_tests.rs b/cli/tests/integration/compile_tests.rs index c3a5048a1..022148ce4 100644 --- a/cli/tests/integration/compile_tests.rs +++ b/cli/tests/integration/compile_tests.rs @@ -1,7 +1,6 @@ // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. use std::fs::File; -use std::path::Path; use std::process::Command; use test_util as util; use test_util::TempDir; @@ -30,37 +29,24 @@ fn compile_basic() { .run(); output.assert_exit_code(0); output.skip_output_check(); - let output = context - .new_command() - .command_name(exe.to_string_lossy()) - .run(); + let output = context.new_command().command_name(&exe).run(); output.assert_matches_text("Welcome to Deno!\n"); } // now ensure this works when the deno_dir is readonly let readonly_dir = dir.path().join("readonly"); - make_dir_readonly(&readonly_dir); + readonly_dir.make_dir_readonly(); let readonly_sub_dir = readonly_dir.join("sub"); let output = context .new_command() // it should fail creating this, but still work - .env("DENO_DIR", readonly_sub_dir.to_string_lossy()) - .command_name(exe.to_string_lossy()) + .env("DENO_DIR", readonly_sub_dir) + .command_name(exe) .run(); output.assert_matches_text("Welcome to Deno!\n"); } -fn make_dir_readonly(dir: &Path) { - std::fs::create_dir_all(dir).unwrap(); - eprintln!("DIR: {}", dir.display()); - if cfg!(windows) { - Command::new("attrib").arg("+r").arg(dir).output().unwrap(); - } else if cfg!(unix) { - Command::new("chmod").arg("555").arg(dir).output().unwrap(); - } -} - #[test] fn standalone_args() { let dir = TempDir::new(); @@ -272,7 +258,7 @@ fn compile_with_file_exists_error() { "is an existing file. You can use the `--output <file-path>` flag to ", "provide an alternative name.\n", ), - file_path.display(), + file_path, ); let stderr = String::from_utf8(output.stderr).unwrap(); assert_contains!(stderr, &expected_stderr); @@ -305,7 +291,7 @@ fn compile_with_directory_exists_error() { "the same name. You can use the `--output <file-path>` flag to ", "provide an alternative name." ), - exe.display() + exe ); let stderr = String::from_utf8(output.stderr).unwrap(); assert_contains!(stderr, &expected_stderr); @@ -338,7 +324,7 @@ fn compile_with_conflict_file_exists_error() { "and cannot be overwritten. Please delete the existing file or ", "use the `--output <file-path>` flag to provide an alternative name." ), - exe.display() + exe ); let stderr = String::from_utf8(output.stderr).unwrap(); assert_contains!(stderr, &expected_stderr); @@ -704,7 +690,7 @@ fn workers_not_in_module_map() { let output = context .new_command() - .command_name(exe.to_string_lossy()) + .command_name(exe) .env("NO_COLOR", "") .run(); output.assert_exit_code(1); @@ -842,10 +828,7 @@ fn compile_npm_specifiers() { output.assert_exit_code(0); output.skip_output_check(); - let output = context - .new_command() - .command_name(binary_path.to_string_lossy()) - .run(); + let output = context.new_command().command_name(&binary_path).run(); output.assert_matches_text( r#"Node esm importing node cjs =========================== @@ -901,10 +884,7 @@ testing[WILDCARD]this output.assert_exit_code(0); output.skip_output_check(); - let output = context - .new_command() - .command_name(binary_path.to_string_lossy()) - .run(); + let output = context.new_command().command_name(binary_path).run(); output.assert_matches_text("2\n"); } @@ -1042,10 +1022,7 @@ fn run_npm_bin_compile_test(opts: RunNpmBinCompileOptions) { let main_specifier = if opts.input_specifier.starts_with("npm:") { opts.input_specifier.to_string() } else { - testdata_path - .join(opts.input_specifier) - .to_string_lossy() - .to_string() + testdata_path.join(opts.input_specifier).to_string() }; let mut args = vec!["compile".to_string()]; @@ -1079,7 +1056,7 @@ fn run_npm_bin_compile_test(opts: RunNpmBinCompileOptions) { }; let output = context .new_command() - .command_name(binary_path.to_string_lossy()) + .command_name(binary_path) .args_vec(opts.run_args) .run(); output.assert_matches_file(opts.output_file); @@ -1144,9 +1121,6 @@ fn compile_node_modules_symlink_outside() { // run let binary_path = project_dir.join(if cfg!(windows) { "bin.exe" } else { "bin" }); - let output = context - .new_command() - .command_name(binary_path.to_string_lossy()) - .run(); + let output = context.new_command().command_name(binary_path).run(); output.assert_matches_file("compile/node_modules_symlink_outside/main.out"); } diff --git a/cli/tests/integration/coverage_tests.rs b/cli/tests/integration/coverage_tests.rs index 7443a8f37..0ac5974a6 100644 --- a/cli/tests/integration/coverage_tests.rs +++ b/cli/tests/integration/coverage_tests.rs @@ -68,7 +68,7 @@ fn error_if_invalid_cache() { .args_vec(vec![ "test".to_string(), "--quiet".to_string(), - format!("--coverage={}", tempdir.to_str().unwrap()), + format!("--coverage={}", tempdir), ]) .run(); @@ -80,10 +80,7 @@ fn error_if_invalid_cache() { let output = context .new_command() - .args_vec(vec![ - "coverage".to_string(), - format!("{}/", tempdir.to_str().unwrap()), - ]) + .args_vec(vec!["coverage".to_string(), format!("{}/", tempdir)]) .run(); output.assert_exit_code(1); @@ -106,7 +103,7 @@ fn run_coverage_text(test_name: &str, extension: &str) { "test".to_string(), "-A".to_string(), "--quiet".to_string(), - format!("--coverage={}", tempdir.to_str().unwrap()), + format!("--coverage={}", tempdir), format!("coverage/{test_name}_test.{extension}"), ]) .run(); @@ -116,10 +113,7 @@ fn run_coverage_text(test_name: &str, extension: &str) { let output = context .new_command() - .args_vec(vec![ - "coverage".to_string(), - format!("{}/", tempdir.to_str().unwrap()), - ]) + .args_vec(vec!["coverage".to_string(), format!("{}/", tempdir)]) .split_output() .run(); @@ -147,7 +141,7 @@ fn run_coverage_text(test_name: &str, extension: &str) { "coverage".to_string(), "--quiet".to_string(), "--lcov".to_string(), - format!("{}/", tempdir.to_str().unwrap()), + format!("{}/", tempdir), ]) .run(); @@ -178,7 +172,7 @@ fn multifile_coverage() { .args_vec(vec![ "test".to_string(), "--quiet".to_string(), - format!("--coverage={}", tempdir.to_str().unwrap()), + format!("--coverage={}", tempdir), format!("coverage/multifile/"), ]) .run(); @@ -188,10 +182,7 @@ fn multifile_coverage() { let output = context .new_command() - .args_vec(vec![ - "coverage".to_string(), - format!("{}/", tempdir.to_str().unwrap()), - ]) + .args_vec(vec!["coverage".to_string(), format!("{}/", tempdir)]) .split_output() .run(); @@ -218,7 +209,7 @@ fn multifile_coverage() { "coverage".to_string(), "--quiet".to_string(), "--lcov".to_string(), - format!("{}/", tempdir.to_str().unwrap()), + format!("{}/", tempdir), ]) .run(); @@ -249,7 +240,7 @@ fn no_snaps_included(test_name: &str, extension: &str) { "test".to_string(), "--quiet".to_string(), "--allow-read".to_string(), - format!("--coverage={}", tempdir.to_str().unwrap()), + format!("--coverage={}", tempdir), format!("coverage/no_snaps_included/{test_name}_test.{extension}"), ]) .run(); @@ -262,7 +253,7 @@ fn no_snaps_included(test_name: &str, extension: &str) { .args_vec(vec![ "coverage".to_string(), "--include=no_snaps_included.ts".to_string(), - format!("{}/", tempdir.to_str().unwrap()), + format!("{}/", tempdir), ]) .split_output() .run(); @@ -297,7 +288,7 @@ fn no_tests_included(test_name: &str, extension: &str) { "test".to_string(), "--quiet".to_string(), "--allow-read".to_string(), - format!("--coverage={}", tempdir.to_str().unwrap()), + format!("--coverage={}", tempdir), format!("coverage/no_tests_included/{test_name}.test.{extension}"), ]) .run(); @@ -309,11 +300,8 @@ fn no_tests_included(test_name: &str, extension: &str) { .new_command() .args_vec(vec![ "coverage".to_string(), - format!( - "--exclude={}", - util::std_path().canonicalize().unwrap().to_string_lossy() - ), - format!("{}/", tempdir.to_str().unwrap()), + format!("--exclude={}", util::std_path().canonicalize()), + format!("{}/", tempdir), ]) .split_output() .run(); @@ -349,7 +337,7 @@ fn no_npm_cache_coverage() { "test".to_string(), "--quiet".to_string(), "--allow-read".to_string(), - format!("--coverage={}", tempdir.to_str().unwrap()), + format!("--coverage={}", tempdir), format!("coverage/no_npm_coverage/no_npm_coverage_test.ts"), ]) .run(); @@ -359,10 +347,7 @@ fn no_npm_cache_coverage() { let output = context .new_command() - .args_vec(vec![ - "coverage".to_string(), - format!("{}/", tempdir.to_str().unwrap()), - ]) + .args_vec(vec!["coverage".to_string(), format!("{}/", tempdir)]) .split_output() .run(); @@ -396,7 +381,7 @@ fn no_transpiled_lines() { .args_vec(vec![ "test".to_string(), "--quiet".to_string(), - format!("--coverage={}", tempdir.to_str().unwrap()), + format!("--coverage={}", tempdir), "coverage/no_transpiled_lines/".to_string(), ]) .run(); @@ -409,7 +394,7 @@ fn no_transpiled_lines() { .args_vec(vec![ "coverage".to_string(), "--include=no_transpiled_lines/index.ts".to_string(), - format!("{}/", tempdir.to_str().unwrap()), + format!("{}/", tempdir), ]) .run(); @@ -434,7 +419,7 @@ fn no_transpiled_lines() { "coverage".to_string(), "--lcov".to_string(), "--include=no_transpiled_lines/index.ts".to_string(), - format!("{}/", tempdir.to_str().unwrap()), + format!("{}/", tempdir), ]) .run(); diff --git a/cli/tests/integration/fmt_tests.rs b/cli/tests/integration/fmt_tests.rs index e674f4a52..ef0ad3f3e 100644 --- a/cli/tests/integration/fmt_tests.rs +++ b/cli/tests/integration/fmt_tests.rs @@ -3,6 +3,7 @@ use test_util as util; use test_util::TempDir; use util::assert_contains; +use util::PathRef; use util::TestContext; use util::TestContextBuilder; @@ -15,34 +16,30 @@ fn fmt_test() { let badly_formatted_original_js = testdata_fmt_dir.join("badly_formatted.mjs"); let badly_formatted_js = t.path().join("badly_formatted.js"); - let badly_formatted_js_str = badly_formatted_js.to_str().unwrap(); - std::fs::copy(badly_formatted_original_js, &badly_formatted_js).unwrap(); + badly_formatted_original_js.copy(&badly_formatted_js); let fixed_md = testdata_fmt_dir.join("badly_formatted_fixed.md"); let badly_formatted_original_md = testdata_fmt_dir.join("badly_formatted.md"); let badly_formatted_md = t.path().join("badly_formatted.md"); - let badly_formatted_md_str = badly_formatted_md.to_str().unwrap(); - std::fs::copy(badly_formatted_original_md, &badly_formatted_md).unwrap(); + badly_formatted_original_md.copy(&badly_formatted_md); let fixed_json = testdata_fmt_dir.join("badly_formatted_fixed.json"); let badly_formatted_original_json = testdata_fmt_dir.join("badly_formatted.json"); let badly_formatted_json = t.path().join("badly_formatted.json"); - let badly_formatted_json_str = badly_formatted_json.to_str().unwrap(); - std::fs::copy(badly_formatted_original_json, &badly_formatted_json).unwrap(); + badly_formatted_original_json.copy(&badly_formatted_json); // First, check formatting by ignoring the badly formatted file. - let s = testdata_fmt_dir.as_os_str().to_str().unwrap(); let output = context .new_command() - .cwd(s) + .cwd(&testdata_fmt_dir) .args_vec(vec![ "fmt".to_string(), format!( - "--ignore={badly_formatted_js_str},{badly_formatted_md_str},{badly_formatted_json_str}", + "--ignore={badly_formatted_js},{badly_formatted_md},{badly_formatted_json}", ), format!( - "--check {badly_formatted_js_str} {badly_formatted_md_str} {badly_formatted_json_str}", + "--check {badly_formatted_js} {badly_formatted_md} {badly_formatted_json}", ), ]) .run(); @@ -54,13 +51,13 @@ fn fmt_test() { // Check without ignore. let output = context .new_command() - .cwd(s) + .cwd(&testdata_fmt_dir) .args_vec(vec![ "fmt".to_string(), "--check".to_string(), - badly_formatted_js_str.to_string(), - badly_formatted_md_str.to_string(), - badly_formatted_json_str.to_string(), + badly_formatted_js.to_string(), + badly_formatted_md.to_string(), + badly_formatted_json.to_string(), ]) .run(); @@ -70,24 +67,24 @@ fn fmt_test() { // Format the source file. let output = context .new_command() - .cwd(s) + .cwd(&testdata_fmt_dir) .args_vec(vec![ "fmt".to_string(), - badly_formatted_js_str.to_string(), - badly_formatted_md_str.to_string(), - badly_formatted_json_str.to_string(), + badly_formatted_js.to_string(), + badly_formatted_md.to_string(), + badly_formatted_json.to_string(), ]) .run(); output.assert_exit_code(0); output.skip_output_check(); - let expected_js = std::fs::read_to_string(fixed_js).unwrap(); - let expected_md = std::fs::read_to_string(fixed_md).unwrap(); - let expected_json = std::fs::read_to_string(fixed_json).unwrap(); - let actual_js = std::fs::read_to_string(badly_formatted_js).unwrap(); - let actual_md = std::fs::read_to_string(badly_formatted_md).unwrap(); - let actual_json = std::fs::read_to_string(badly_formatted_json).unwrap(); + let expected_js = fixed_js.read_to_string(); + let expected_md = fixed_md.read_to_string(); + let expected_json = fixed_json.read_to_string(); + let actual_js = badly_formatted_js.read_to_string(); + let actual_md = badly_formatted_md.read_to_string(); + let actual_json = badly_formatted_json.read_to_string(); assert_eq!(expected_js, actual_js); assert_eq!(expected_md, actual_md); assert_eq!(expected_json, actual_json); @@ -130,25 +127,21 @@ fn fmt_ignore_unexplicit_files() { #[test] fn fmt_auto_ignore_git_and_node_modules() { - use std::fs::create_dir_all; - use std::fs::File; - use std::io::Write; - use std::path::PathBuf; - fn create_bad_json(t: PathBuf) { + fn create_bad_json(t: PathRef) { let bad_json_path = t.join("bad.json"); - let mut bad_json_file = File::create(bad_json_path).unwrap(); - writeln!(bad_json_file, "bad json").unwrap(); + bad_json_path.write("bad json\n"); } + let temp_dir = TempDir::new(); let t = temp_dir.path().join("target"); let nest_git = t.join("nest").join(".git"); let git_dir = t.join(".git"); let nest_node_modules = t.join("nest").join("node_modules"); let node_modules_dir = t.join("node_modules"); - create_dir_all(&nest_git).unwrap(); - create_dir_all(&git_dir).unwrap(); - create_dir_all(&nest_node_modules).unwrap(); - create_dir_all(&node_modules_dir).unwrap(); + nest_git.create_dir_all(); + git_dir.create_dir_all(); + nest_node_modules.create_dir_all(); + node_modules_dir.create_dir_all(); create_bad_json(nest_git); create_bad_json(git_dir); create_bad_json(nest_node_modules); @@ -157,7 +150,7 @@ fn fmt_auto_ignore_git_and_node_modules() { let context = TestContext::default(); let output = context .new_command() - .cwd(t.as_os_str().to_str().unwrap()) + .cwd(t) .env("NO_COLOR", "1") .args("fmt") .run(); diff --git a/cli/tests/integration/install_tests.rs b/cli/tests/integration/install_tests.rs index af4edd2ee..0756d460c 100644 --- a/cli/tests/integration/install_tests.rs +++ b/cli/tests/integration/install_tests.rs @@ -11,7 +11,7 @@ use test_util::TempDir; fn install_basic() { let _guard = util::http_server(); let temp_dir = TempDir::new(); - let temp_dir_str = temp_dir.path().to_string_lossy().to_string(); + let temp_dir_str = temp_dir.path().to_string(); // ensure a lockfile doesn't get created or updated locally temp_dir.write("deno.json", "{}"); @@ -44,7 +44,7 @@ fn install_basic() { file_path = file_path.with_extension("cmd"); } - let content = fs::read_to_string(&file_path).unwrap(); + let content = file_path.read_to_string(); // ensure there's a trailing newline so the shell script can be // more versatile. assert_eq!(content.chars().last().unwrap(), '\n'); @@ -87,7 +87,7 @@ fn install_basic() { fn install_custom_dir_env_var() { let _guard = util::http_server(); let temp_dir = TempDir::new(); - let temp_dir_str = temp_dir.path().to_string_lossy().to_string(); + let temp_dir_str = temp_dir.path().to_string(); let status = util::deno_cmd() .current_dir(util::root_path()) // different cwd @@ -205,7 +205,7 @@ fn installer_test_remote_module_run() { fn check_local_by_default() { let _guard = util::http_server(); let temp_dir = TempDir::new(); - let temp_dir_str = temp_dir.path().to_string_lossy().to_string(); + let temp_dir_str = temp_dir.path().to_string(); let status = util::deno_cmd() .current_dir(temp_dir.path()) @@ -225,7 +225,7 @@ fn check_local_by_default() { fn check_local_by_default2() { let _guard = util::http_server(); let temp_dir = TempDir::new(); - let temp_dir_str = temp_dir.path().to_string_lossy().to_string(); + let temp_dir_str = temp_dir.path().to_string(); let status = util::deno_cmd() .current_dir(temp_dir.path()) diff --git a/cli/tests/integration/lsp_tests.rs b/cli/tests/integration/lsp_tests.rs index fa8cb6a3c..bd5bc409a 100644 --- a/cli/tests/integration/lsp_tests.rs +++ b/cli/tests/integration/lsp_tests.rs @@ -7670,7 +7670,7 @@ fn lsp_node_modules_dir() { .as_str() .unwrap(); // canonicalize for mac - let path = temp_dir.path().join("node_modules").canonicalize().unwrap(); + let path = temp_dir.path().join("node_modules").canonicalize(); assert_starts_with!( uri, ModuleSpecifier::from_file_path(&path).unwrap().as_str() diff --git a/cli/tests/integration/npm_tests.rs b/cli/tests/integration/npm_tests.rs index 3a18c13dc..c38e4f75f 100644 --- a/cli/tests/integration/npm_tests.rs +++ b/cli/tests/integration/npm_tests.rs @@ -880,7 +880,7 @@ fn ensure_registry_files_local() { if file_text.contains("https://registry.npmjs.org/") { panic!( "file {} contained a reference to the npm registry", - registry_json_path.display(), + registry_json_path ); } } diff --git a/cli/tests/integration/repl_tests.rs b/cli/tests/integration/repl_tests.rs index 77a534d2e..c25a151a1 100644 --- a/cli/tests/integration/repl_tests.rs +++ b/cli/tests/integration/repl_tests.rs @@ -316,7 +316,15 @@ fn repl_cwd() { .args_vec(["repl", "-A"]) .with_pty(|mut console| { console.write_line("Deno.cwd()"); - console.expect(temp_dir.path().file_name().unwrap().to_str().unwrap()); + console.expect( + temp_dir + .path() + .as_path() + .file_name() + .unwrap() + .to_str() + .unwrap(), + ); }); } @@ -535,10 +543,7 @@ fn missing_deno_dir() { "repl", Some(vec!["1"]), Some(vec![ - ( - "DENO_DIR".to_owned(), - deno_dir_path.to_str().unwrap().to_owned(), - ), + ("DENO_DIR".to_owned(), deno_dir_path.to_string()), ("NO_COLOR".to_owned(), "1".to_owned()), ]), false, @@ -558,10 +563,7 @@ fn custom_history_path() { "repl", Some(vec!["1"]), Some(vec![ - ( - "DENO_REPL_HISTORY".to_owned(), - history_path.to_str().unwrap().to_owned(), - ), + ("DENO_REPL_HISTORY".to_owned(), history_path.to_string()), ("NO_COLOR".to_owned(), "1".to_owned()), ]), false, @@ -580,10 +582,7 @@ fn disable_history_file() { "repl", Some(vec!["1"]), Some(vec![ - ( - "DENO_DIR".to_owned(), - deno_dir.path().to_str().unwrap().to_owned(), - ), + ("DENO_DIR".to_owned(), deno_dir.path().to_string()), ("DENO_REPL_HISTORY".to_owned(), "".to_owned()), ("NO_COLOR".to_owned(), "1".to_owned()), ]), @@ -877,10 +876,7 @@ fn npm_packages() { let mut env_vars = util::env_vars_for_npm_tests(); env_vars.push(("NO_COLOR".to_owned(), "1".to_owned())); let temp_dir = TempDir::new(); - env_vars.push(( - "DENO_DIR".to_string(), - temp_dir.path().to_string_lossy().to_string(), - )); + env_vars.push(("DENO_DIR".to_string(), temp_dir.path().to_string())); { let (out, err) = util::run_and_collect_output_with_args( diff --git a/cli/tests/integration/run_tests.rs b/cli/tests/integration/run_tests.rs index 3fa2f9896..476849b2a 100644 --- a/cli/tests/integration/run_tests.rs +++ b/cli/tests/integration/run_tests.rs @@ -14,6 +14,7 @@ use trust_dns_client::serialize::txt::Parser; use util::assert_contains; use util::assert_not_contains; use util::env_vars_for_npm_tests_no_sync_download; +use util::PathRef; use util::TestContext; use util::TestContextBuilder; @@ -520,8 +521,8 @@ fn _083_legacy_external_source_map() { .unwrap(); // Write a faulty old external source map. let faulty_map_path = deno_dir.path().join("gen/http/localhost_PORT4545/9576bd5febd0587c5c4d88d57cb3ac8ebf2600c529142abe3baa9a751d20c334.js.map"); - std::fs::create_dir_all(faulty_map_path.parent().unwrap()).unwrap(); - std::fs::write(faulty_map_path, "{\"version\":3,\"file\":\"\",\"sourceRoot\":\"\",\"sources\":[\"http://localhost:4545/083_legacy_external_source_map.ts\"],\"names\":[],\"mappings\":\";AAAA,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC\"}").unwrap(); + faulty_map_path.parent().create_dir_all(); + faulty_map_path.write(r#"{\"version\":3,\"file\":\"\",\"sourceRoot\":\"\",\"sources\":[\"http://localhost:4545/083_legacy_external_source_map.ts\"],\"names\":[],\"mappings\":\";AAAA,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC\"}"#); let output = Command::new(util::deno_exe_path()) .env("DENO_DIR", deno_dir.path()) .current_dir(util::testdata_path()) @@ -1925,8 +1926,8 @@ fn exec_path() { .unwrap(); assert!(output.status.success()); let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim(); - let actual = std::fs::canonicalize(std::path::Path::new(stdout_str)).unwrap(); - let expected = std::fs::canonicalize(util::deno_exe_path()).unwrap(); + let actual = PathRef::new(std::path::Path::new(stdout_str)).canonicalize(); + let expected = util::deno_exe_path().canonicalize(); assert_eq!(expected, actual); } @@ -1991,7 +1992,7 @@ enum WinProcConstraints { #[cfg(windows)] fn run_deno_script_constrained( - script_path: std::path::PathBuf, + script_path: test_util::PathRef, constraints: WinProcConstraints, ) -> Result<(), i64> { let file_path = "assets/DenoWinRunner.ps1"; @@ -2000,13 +2001,8 @@ fn run_deno_script_constrained( WinProcConstraints::NoStdOut => "2", WinProcConstraints::NoStdErr => "4", }; - let deno_exe_path = util::deno_exe_path() - .into_os_string() - .into_string() - .unwrap(); - - let deno_script_path = script_path.into_os_string().into_string().unwrap(); - + let deno_exe_path = util::deno_exe_path().to_string(); + let deno_script_path = script_path.to_string(); let args = vec![&deno_exe_path[..], &deno_script_path[..], constraints]; util::run_powershell_script_file(file_path, args) } @@ -2199,9 +2195,6 @@ mod permissions { "--allow-{0}={1}", permission, util::testdata_path() - .into_os_string() - .into_string() - .unwrap() )) .arg("run/complex_permissions_test.ts") .arg(permission) @@ -2223,15 +2216,8 @@ mod permissions { &format!( "run --allow-{0}={1} run/complex_permissions_test.ts {0} {2}", permission, - util::testdata_path() - .into_os_string() - .into_string() - .unwrap(), - util::root_path() - .join("Cargo.toml") - .into_os_string() - .into_string() - .unwrap(), + util::testdata_path(), + util::root_path().join("Cargo.toml"), ), None, None, @@ -2251,10 +2237,7 @@ mod permissions { .arg(format!( "--allow-{0}={1}", permission, - util::testdata_path() - .into_os_string() - .into_string() - .unwrap() + util::testdata_path(), )) .arg("run/complex_permissions_test.ts") .arg(permission) @@ -2270,15 +2253,8 @@ mod permissions { #[test] fn rw_outside_test_and_js_dir() { const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; - let test_dir = util::testdata_path() - .into_os_string() - .into_string() - .unwrap(); - let js_dir = util::root_path() - .join("js") - .into_os_string() - .into_string() - .unwrap(); + let test_dir = util::testdata_path(); + let js_dir = util::root_path().join("js"); for permission in &PERMISSION_VARIANTS { let (_, err) = util::run_and_collect_output( false, @@ -2287,11 +2263,7 @@ mod permissions { permission, test_dir, js_dir, - util::root_path() - .join("Cargo.toml") - .into_os_string() - .into_string() - .unwrap(), + util::root_path().join("Cargo.toml"), ), None, None, @@ -2304,15 +2276,8 @@ mod permissions { #[test] fn rw_inside_test_and_js_dir() { const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; - let test_dir = util::testdata_path() - .into_os_string() - .into_string() - .unwrap(); - let js_dir = util::root_path() - .join("js") - .into_os_string() - .into_string() - .unwrap(); + let test_dir = util::testdata_path(); + let js_dir = util::root_path().join("js"); for permission in &PERMISSION_VARIANTS { let status = util::deno_cmd() .current_dir(&util::testdata_path()) @@ -3551,35 +3516,23 @@ fn cache_test() { fn cache_invalidation_test() { let deno_dir = TempDir::new(); let fixture_path = deno_dir.path().join("fixture.ts"); - { - let mut file = std::fs::File::create(fixture_path.clone()) - .expect("could not create fixture"); - file - .write_all(b"console.log(\"42\");") - .expect("could not write fixture"); - } + fixture_path.write("console.log(\"42\");"); let output = Command::new(util::deno_exe_path()) .env("DENO_DIR", deno_dir.path()) .current_dir(util::testdata_path()) .arg("run") - .arg(fixture_path.to_str().unwrap()) + .arg(&fixture_path) .output() .expect("Failed to spawn script"); assert!(output.status.success()); let actual = std::str::from_utf8(&output.stdout).unwrap(); assert_eq!(actual, "42\n"); - { - let mut file = std::fs::File::create(fixture_path.clone()) - .expect("could not create fixture"); - file - .write_all(b"console.log(\"43\");") - .expect("could not write fixture"); - } + fixture_path.write("console.log(\"43\");"); let output = Command::new(util::deno_exe_path()) .env("DENO_DIR", deno_dir.path()) .current_dir(util::testdata_path()) .arg("run") - .arg(fixture_path.to_str().unwrap()) + .arg(fixture_path) .output() .expect("Failed to spawn script"); assert!(output.status.success()); @@ -3591,37 +3544,25 @@ fn cache_invalidation_test() { fn cache_invalidation_test_no_check() { let deno_dir = TempDir::new(); let fixture_path = deno_dir.path().join("fixture.ts"); - { - let mut file = std::fs::File::create(fixture_path.clone()) - .expect("could not create fixture"); - file - .write_all(b"console.log(\"42\");") - .expect("could not write fixture"); - } + fixture_path.write("console.log(\"42\");"); let output = Command::new(util::deno_exe_path()) .env("DENO_DIR", deno_dir.path()) .current_dir(util::testdata_path()) .arg("run") .arg("--no-check") - .arg(fixture_path.to_str().unwrap()) + .arg(&fixture_path) .output() .expect("Failed to spawn script"); assert!(output.status.success()); let actual = std::str::from_utf8(&output.stdout).unwrap(); assert_eq!(actual, "42\n"); - { - let mut file = std::fs::File::create(fixture_path.clone()) - .expect("could not create fixture"); - file - .write_all(b"console.log(\"43\");") - .expect("could not write fixture"); - } + fixture_path.write("console.log(\"43\");"); let output = Command::new(util::deno_exe_path()) .env("DENO_DIR", deno_dir.path()) .current_dir(util::testdata_path()) .arg("run") .arg("--no-check") - .arg(fixture_path.to_str().unwrap()) + .arg(fixture_path) .output() .expect("Failed to spawn script"); assert!(output.status.success()); diff --git a/cli/tests/integration/upgrade_tests.rs b/cli/tests/integration/upgrade_tests.rs index f4eaa03c9..6eed9e7a1 100644 --- a/cli/tests/integration/upgrade_tests.rs +++ b/cli/tests/integration/upgrade_tests.rs @@ -12,7 +12,7 @@ use test_util::TempDir; fn upgrade_in_tmpdir() { let temp_dir = TempDir::new(); let exe_path = temp_dir.path().join("deno"); - let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); + util::deno_exe_path().copy(&exe_path); assert!(exe_path.exists()); let _mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); let status = Command::new(&exe_path) @@ -34,7 +34,7 @@ fn upgrade_in_tmpdir() { fn upgrade_with_space_in_path() { let temp_dir = TempDir::new_with_prefix("directory with spaces"); let exe_path = temp_dir.path().join("deno"); - let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); + util::deno_exe_path().copy(&exe_path); assert!(exe_path.exists()); let status = Command::new(&exe_path) .arg("upgrade") @@ -54,7 +54,7 @@ fn upgrade_with_space_in_path() { fn upgrade_with_version_in_tmpdir() { let temp_dir = TempDir::new(); let exe_path = temp_dir.path().join("deno"); - let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); + util::deno_exe_path().copy(&exe_path); assert!(exe_path.exists()); let _mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); let status = Command::new(&exe_path) @@ -83,7 +83,7 @@ fn upgrade_with_version_in_tmpdir() { fn upgrade_with_canary_in_tmpdir() { let temp_dir = TempDir::new(); let exe_path = temp_dir.path().join("deno"); - let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); + util::deno_exe_path().copy(&exe_path); assert!(exe_path.exists()); let _mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); let status = Command::new(&exe_path) @@ -113,7 +113,7 @@ fn upgrade_with_out_in_tmpdir() { let temp_dir = TempDir::new(); let exe_path = temp_dir.path().join("deno"); let new_exe_path = temp_dir.path().join("foo"); - let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); + util::deno_exe_path().copy(&exe_path); assert!(exe_path.exists()); let mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); let status = Command::new(&exe_path) @@ -121,7 +121,7 @@ fn upgrade_with_out_in_tmpdir() { .arg("--version") .arg("1.11.5") .arg("--output") - .arg(new_exe_path.to_str().unwrap()) + .arg(&new_exe_path) .spawn() .unwrap() .wait() @@ -149,7 +149,7 @@ fn upgrade_with_out_in_tmpdir() { fn upgrade_invalid_stable_version() { let temp_dir = TempDir::new(); let exe_path = temp_dir.path().join("deno"); - let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); + util::deno_exe_path().copy(&exe_path); assert!(exe_path.exists()); let output = Command::new(&exe_path) .arg("upgrade") @@ -174,7 +174,7 @@ fn upgrade_invalid_stable_version() { fn upgrade_invalid_canary_version() { let temp_dir = TempDir::new(); let exe_path = temp_dir.path().join("deno"); - let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); + util::deno_exe_path().copy(&exe_path); assert!(exe_path.exists()); let output = Command::new(&exe_path) .arg("upgrade") diff --git a/cli/tests/integration/watcher_tests.rs b/cli/tests/integration/watcher_tests.rs index 2d41a74ed..ab3005f73 100644 --- a/cli/tests/integration/watcher_tests.rs +++ b/cli/tests/integration/watcher_tests.rs @@ -743,11 +743,7 @@ async fn run_watch_external_watch_files() { write(&external_file_to_watch, "Hello world").unwrap(); let mut watch_arg = "--watch=".to_owned(); - let external_file_to_watch_str = external_file_to_watch - .clone() - .into_os_string() - .into_string() - .unwrap(); + let external_file_to_watch_str = external_file_to_watch.to_string(); watch_arg.push_str(&external_file_to_watch_str); let mut child = util::deno_cmd() @@ -893,13 +889,15 @@ async fn run_watch_with_import_map_and_relative_paths() { let absolute_path = directory.path().join(filename); write(&absolute_path, filecontent).unwrap(); let relative_path = absolute_path - .strip_prefix(util::testdata_path()) + .as_path() + .strip_prefix(directory.path()) .unwrap() .to_owned(); assert!(relative_path.is_relative()); relative_path } - let temp_directory = TempDir::new_in(&util::testdata_path()); + + let temp_directory = TempDir::new(); let file_to_watch = create_relative_tmp_file( &temp_directory, "file_to_watch.js", @@ -912,7 +910,7 @@ async fn run_watch_with_import_map_and_relative_paths() { ); let mut child = util::deno_cmd() - .current_dir(util::testdata_path()) + .current_dir(temp_directory.path()) .arg("run") .arg("--unstable") .arg("--watch") diff --git a/cli/tools/installer.rs b/cli/tools/installer.rs index 07606d5f8..03c2ffdcf 100644 --- a/cli/tools/installer.rs +++ b/cli/tools/installer.rs @@ -1022,9 +1022,7 @@ mod tests { let result = create_install_shim( Flags { - config_flag: ConfigFlag::Path( - config_file_path.to_string_lossy().to_string(), - ), + config_flag: ConfigFlag::Path(config_file_path.to_string()), ..Flags::default() }, InstallFlags { @@ -1137,7 +1135,7 @@ mod tests { let result = create_install_shim( Flags { - import_map_path: Some(import_map_path.to_string_lossy().to_string()), + import_map_path: Some(import_map_path.to_string()), ..Flags::default() }, InstallFlags { diff --git a/cli/tsc/mod.rs b/cli/tsc/mod.rs index 83fd84f9d..a4d6640f7 100644 --- a/cli/tsc/mod.rs +++ b/cli/tsc/mod.rs @@ -841,11 +841,11 @@ mod tests { use deno_core::OpState; use deno_graph::GraphKind; use deno_graph::ModuleGraph; - use std::fs; + use test_util::PathRef; #[derive(Debug, Default)] pub struct MockLoader { - pub fixtures: PathBuf, + pub fixtures: PathRef, } impl deno_graph::source::Loader for MockLoader { @@ -860,15 +860,13 @@ mod tests { .replace("://", "_") .replace('/', "-"); let source_path = self.fixtures.join(specifier_text); - let response = fs::read_to_string(source_path) - .map(|c| { - Some(deno_graph::source::LoadResponse::Module { - specifier: specifier.clone(), - maybe_headers: None, - content: c.into(), - }) + let response = source_path.read_to_string_if_exists().map(|c| { + Some(deno_graph::source::LoadResponse::Module { + specifier: specifier.clone(), + maybe_headers: None, + content: c.into(), }) - .map_err(|err| err.into()); + }); Box::pin(future::ready(response)) } } diff --git a/cli/util/fs.rs b/cli/util/fs.rs index 658002e3b..b17e2d2d9 100644 --- a/cli/util/fs.rs +++ b/cli/util/fs.rs @@ -597,6 +597,7 @@ mod tests { use deno_core::futures; use deno_core::parking_lot::Mutex; use pretty_assertions::assert_eq; + use test_util::PathRef; use test_util::TempDir; use tokio::sync::Notify; @@ -645,11 +646,10 @@ mod tests { #[test] fn test_collect_files() { - fn create_files(dir_path: &Path, files: &[&str]) { - std::fs::create_dir(dir_path).expect("Failed to create directory"); + fn create_files(dir_path: &PathRef, files: &[&str]) { + dir_path.create_dir_all(); for f in files { - let path = dir_path.join(f); - std::fs::write(path, "").expect("Failed to create file"); + dir_path.join(f).write(""); } } @@ -698,10 +698,10 @@ mod tests { .map(|f| !f.starts_with('.')) .unwrap_or(false) }) - .add_ignore_paths(&[ignore_dir_path]); + .add_ignore_paths(&[ignore_dir_path.to_path_buf()]); let result = file_collector - .collect_files(&[root_dir_path.clone()]) + .collect_files(&[root_dir_path.to_path_buf()]) .unwrap(); let expected = [ "README.md", @@ -725,7 +725,7 @@ mod tests { let file_collector = file_collector.ignore_git_folder().ignore_node_modules(); let result = file_collector - .collect_files(&[root_dir_path.clone()]) + .collect_files(&[root_dir_path.to_path_buf()]) .unwrap(); let expected = [ "README.md", @@ -746,8 +746,8 @@ mod tests { // test opting out of ignoring by specifying the dir let result = file_collector .collect_files(&[ - root_dir_path.clone(), - root_dir_path.join("child/node_modules/"), + root_dir_path.to_path_buf(), + root_dir_path.to_path_buf().join("child/node_modules/"), ]) .unwrap(); let expected = [ @@ -770,11 +770,10 @@ mod tests { #[test] fn test_collect_specifiers() { - fn create_files(dir_path: &Path, files: &[&str]) { - std::fs::create_dir(dir_path).expect("Failed to create directory"); + fn create_files(dir_path: &PathRef, files: &[&str]) { + dir_path.create_dir_all(); for f in files { - let path = dir_path.join(f); - std::fs::write(path, "").expect("Failed to create file"); + dir_path.join(f).write(""); } } @@ -819,20 +818,19 @@ mod tests { &FilesConfig { include: vec![ PathBuf::from("http://localhost:8080"), - root_dir_path.clone(), + root_dir_path.to_path_buf(), PathBuf::from("https://localhost:8080".to_string()), ], - exclude: vec![ignore_dir_path], + exclude: vec![ignore_dir_path.to_path_buf()], }, predicate, ) .unwrap(); - let root_dir_url = ModuleSpecifier::from_file_path( - canonicalize_path(&root_dir_path).unwrap(), - ) - .unwrap() - .to_string(); + let root_dir_url = + ModuleSpecifier::from_file_path(root_dir_path.canonicalize()) + .unwrap() + .to_string(); let expected: Vec<ModuleSpecifier> = [ "http://localhost:8080", &format!("{root_dir_url}/a.ts"), @@ -860,11 +858,7 @@ mod tests { include: vec![PathBuf::from(format!( "{}{}", scheme, - root_dir_path - .join("child") - .to_str() - .unwrap() - .replace('\\', "/") + root_dir_path.join("child").to_string().replace('\\', "/") ))], exclude: vec![], }, @@ -901,7 +895,8 @@ mod tests { let temp_dir = temp_dir.clone(); async move { let flag = - LaxSingleProcessFsFlag::lock(lock_path.clone(), "waiting").await; + LaxSingleProcessFsFlag::lock(lock_path.to_path_buf(), "waiting") + .await; signal1.notify_one(); signal2.notified().await; tokio::time::sleep(Duration::from_millis(10)).await; // give the other thread time to acquire the lock @@ -918,7 +913,9 @@ mod tests { async move { signal1.notified().await; signal2.notify_one(); - let flag = LaxSingleProcessFsFlag::lock(lock_path, "waiting").await; + let flag = + LaxSingleProcessFsFlag::lock(lock_path.to_path_buf(), "waiting") + .await; temp_dir.write("file.txt", "update2"); signal5.notify_one(); drop(flag); @@ -949,7 +946,8 @@ mod tests { let expected_order = expected_order.clone(); tasks.push(tokio::spawn(async move { let flag = - LaxSingleProcessFsFlag::lock(lock_path.clone(), "waiting").await; + LaxSingleProcessFsFlag::lock(lock_path.to_path_buf(), "waiting") + .await; expected_order.lock().push(i.to_string()); // be extremely racy let mut output = std::fs::read_to_string(&output_path).unwrap(); |