1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-23 15:49:44 -05:00

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.
This commit is contained in:
David Sherret 2023-06-10 11:09:45 -04:00 committed by GitHub
parent f3326eebd6
commit 7f15126f23
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
40 changed files with 778 additions and 719 deletions

View file

@ -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"));
}

View file

@ -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"),
]
)
}

View file

@ -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");

View file

@ -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(())
}

View file

@ -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")

View file

@ -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:");

2
cli/cache/emit.rs vendored
View file

@ -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",

View file

@ -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(

View file

@ -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(),

View file

@ -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()

View file

@ -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();
}

View file

@ -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]

View file

@ -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)

View file

@ -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(

View file

@ -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(())
}

View file

@ -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();

View file

@ -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

View file

@ -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();

View file

@ -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")

View file

@ -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");
}

View file

@ -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());

View file

@ -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");
}

View file

@ -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();

View file

@ -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();

View file

@ -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())

View file

@ -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()

View file

@ -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
);
}
}

View file

@ -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(

View file

@ -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());

View file

@ -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")

View file

@ -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")

View file

@ -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 {

View file

@ -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))
}
}

View file

@ -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();

View file

@ -2,6 +2,7 @@
use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::io::Read;
use std::io::Write;
use std::path::Path;
@ -13,9 +14,9 @@ use std::rc::Rc;
use os_pipe::pipe;
use pretty_assertions::assert_eq;
use crate::copy_dir_recursive;
use crate::deno_exe_path;
use crate::env_vars_for_npm_tests_no_sync_download;
use crate::fs::PathRef;
use crate::http_server;
use crate::lsp::LspClientBuilder;
use crate::new_deno_dir;
@ -38,7 +39,7 @@ pub struct TestContextBuilder {
copy_temp_dir: Option<String>,
cwd: Option<String>,
envs: HashMap<String, String>,
deno_exe: Option<PathBuf>,
deno_exe: Option<PathRef>,
}
impl TestContextBuilder {
@ -129,17 +130,17 @@ impl TestContextBuilder {
temp_dir
};
let testdata_dir = if let Some(temp_copy_dir) = &self.copy_temp_dir {
let test_data_path = testdata_path().join(temp_copy_dir);
let test_data_path = PathRef::new(testdata_path()).join(temp_copy_dir);
let temp_copy_dir = temp_dir.path().join(temp_copy_dir);
std::fs::create_dir_all(&temp_copy_dir).unwrap();
copy_dir_recursive(&test_data_path, &temp_copy_dir).unwrap();
temp_dir.path().to_owned()
temp_copy_dir.create_dir_all();
test_data_path.copy_to_recursive(&temp_copy_dir);
temp_dir.path().clone()
} else {
testdata_path()
PathRef::new(testdata_path())
};
let deno_exe = self.deno_exe.clone().unwrap_or_else(deno_exe_path);
println!("deno_exe path {}", deno_exe.display());
println!("deno_exe path {}", deno_exe);
let http_server_guard = if self.use_http_server {
Some(Rc::new(http_server()))
@ -162,14 +163,14 @@ impl TestContextBuilder {
#[derive(Clone)]
pub struct TestContext {
deno_exe: PathBuf,
deno_exe: PathRef,
envs: HashMap<String, String>,
use_temp_cwd: bool,
cwd: Option<String>,
_http_server_guard: Option<Rc<HttpServerGuard>>,
deno_dir: TempDir,
temp_dir: TempDir,
testdata_dir: PathBuf,
testdata_dir: PathRef,
}
impl Default for TestContext {
@ -183,7 +184,7 @@ impl TestContext {
TestContextBuilder::default().use_http_server().build()
}
pub fn testdata_path(&self) -> &PathBuf {
pub fn testdata_path(&self) -> &PathRef {
&self.testdata_dir
}
@ -197,7 +198,7 @@ impl TestContext {
pub fn new_command(&self) -> TestCommandBuilder {
TestCommandBuilder {
command_name: self.deno_exe.to_string_lossy().to_string(),
command_name: self.deno_exe.to_string(),
args: Default::default(),
args_vec: Default::default(),
stdin: Default::default(),
@ -229,8 +230,8 @@ pub struct TestCommandBuilder {
}
impl TestCommandBuilder {
pub fn command_name(mut self, name: impl AsRef<str>) -> Self {
self.command_name = name.as_ref().to_string();
pub fn command_name(mut self, name: impl AsRef<OsStr>) -> Self {
self.command_name = name.as_ref().to_string_lossy().to_string();
self
}
@ -261,10 +262,15 @@ impl TestCommandBuilder {
self
}
pub fn env(mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self {
self
.envs
.insert(key.as_ref().to_string(), value.as_ref().to_string());
pub fn env(
mut self,
key: impl AsRef<OsStr>,
value: impl AsRef<OsStr>,
) -> Self {
self.envs.insert(
key.as_ref().to_string_lossy().to_string(),
value.as_ref().to_string_lossy().to_string(),
);
self
}
@ -273,12 +279,12 @@ impl TestCommandBuilder {
self
}
pub fn cwd(mut self, cwd: impl AsRef<str>) -> Self {
self.cwd = Some(cwd.as_ref().to_string());
pub fn cwd(mut self, cwd: impl AsRef<OsStr>) -> Self {
self.cwd = Some(cwd.as_ref().to_string_lossy().to_string());
self
}
fn build_cwd(&self) -> PathBuf {
fn build_cwd(&self) -> PathRef {
let cwd = self.cwd.as_ref().or(self.context.cwd.as_ref());
if self.context.use_temp_cwd {
assert!(cwd.is_none());
@ -290,12 +296,12 @@ impl TestCommandBuilder {
}
}
fn build_command_path(&self) -> PathBuf {
fn build_command_path(&self) -> PathRef {
let command_name = &self.command_name;
if command_name == "deno" {
deno_exe_path()
} else {
PathBuf::from(command_name)
PathRef::new(PathBuf::from(command_name))
}
}
@ -317,7 +323,10 @@ impl TestCommandBuilder {
}
.iter()
.map(|arg| {
arg.replace("$TESTDATA", &self.context.testdata_dir.to_string_lossy())
arg.replace(
"$TESTDATA",
&self.context.testdata_dir.as_path().to_string_lossy(),
)
})
.collect::<Vec<_>>()
}
@ -352,9 +361,9 @@ impl TestCommandBuilder {
}
action(Pty::new(
&self.build_command_path(),
self.build_command_path().as_path(),
&args,
&self.build_cwd(),
self.build_cwd().as_path(),
Some(envs),
))
}
@ -383,7 +392,7 @@ impl TestCommandBuilder {
let mut command = Command::new(self.build_command_path());
println!("command {} {}", self.command_name, args.join(" "));
println!("command cwd {:?}", &cwd);
println!("command cwd {}", cwd);
command.args(args.iter());
if self.env_clear {
command.env_clear();
@ -464,7 +473,7 @@ pub struct TestCommandOutput {
std_out_err: Option<(String, String)>,
exit_code: Option<i32>,
signal: Option<i32>,
testdata_dir: PathBuf,
testdata_dir: PathRef,
asserted_stdout: RefCell<bool>,
asserted_stderr: RefCell<bool>,
asserted_combined: RefCell<bool>,
@ -514,7 +523,7 @@ impl Drop for TestCommandOutput {
}
impl TestCommandOutput {
pub fn testdata_dir(&self) -> &PathBuf {
pub fn testdata_dir(&self) -> &PathRef {
&self.testdata_dir
}
@ -669,10 +678,10 @@ impl TestCommandOutput {
file_path: impl AsRef<Path>,
) -> &Self {
let output_path = self.testdata_dir().join(file_path);
println!("output path {}", output_path.display());
println!("output path {}", output_path);
let expected_text =
std::fs::read_to_string(&output_path).unwrap_or_else(|err| {
panic!("failed loading {}\n\n{err:#}", output_path.display())
panic!("failed loading {}\n\n{err:#}", output_path)
});
self.inner_assert_matches_text(actual, expected_text)
}

394
test_util/src/fs.rs Normal file
View file

@ -0,0 +1,394 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use std::borrow::Cow;
use std::ffi::OsStr;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::sync::Arc;
use anyhow::Context;
use lsp_types::Url;
/// Represents a path on the file system, which can be used
/// to perform specific actions.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PathRef(PathBuf);
impl AsRef<Path> for PathRef {
fn as_ref(&self) -> &Path {
self.as_path()
}
}
impl AsRef<OsStr> for PathRef {
fn as_ref(&self) -> &OsStr {
self.as_path().as_ref()
}
}
impl std::fmt::Display for PathRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_path().display())
}
}
impl PathRef {
pub fn new(path: impl AsRef<Path>) -> Self {
Self(path.as_ref().to_path_buf())
}
pub fn parent(&self) -> PathRef {
PathRef(self.as_path().parent().unwrap().to_path_buf())
}
pub fn uri(&self) -> Url {
Url::from_directory_path(self.as_path()).unwrap()
}
pub fn as_path(&self) -> &Path {
self.0.as_path()
}
pub fn to_path_buf(&self) -> PathBuf {
self.0.to_path_buf()
}
pub fn to_string_lossy(&self) -> Cow<str> {
self.0.to_string_lossy()
}
pub fn exists(&self) -> bool {
self.0.exists()
}
pub fn try_exists(&self) -> std::io::Result<bool> {
self.0.try_exists()
}
pub fn is_dir(&self) -> bool {
self.0.is_dir()
}
pub fn is_file(&self) -> bool {
self.0.is_file()
}
pub fn join(&self, path: impl AsRef<Path>) -> PathRef {
PathRef(self.as_path().join(path))
}
pub fn with_extension(&self, ext: impl AsRef<OsStr>) -> PathRef {
PathRef(self.as_path().with_extension(ext))
}
pub fn canonicalize(&self) -> PathRef {
PathRef(strip_unc_prefix(self.as_path().canonicalize().unwrap()))
}
pub fn create_dir_all(&self) {
fs::create_dir_all(self).unwrap();
}
pub fn remove_file(&self) {
fs::remove_file(self).unwrap();
}
pub fn remove_dir_all(&self) {
fs::remove_dir_all(self).unwrap();
}
pub fn read_to_string(&self) -> String {
self.read_to_string_if_exists().unwrap()
}
pub fn read_to_string_if_exists(&self) -> Result<String, anyhow::Error> {
fs::read_to_string(self)
.with_context(|| format!("Could not find file: {}", self))
}
pub fn rename(&self, to: impl AsRef<Path>) {
fs::rename(self, self.join(to)).unwrap();
}
pub fn write(&self, text: impl AsRef<str>) {
fs::write(self, text.as_ref()).unwrap();
}
pub fn symlink_dir(
&self,
oldpath: impl AsRef<Path>,
newpath: impl AsRef<Path>,
) {
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
symlink(self.as_path().join(oldpath), self.as_path().join(newpath))
.unwrap();
}
#[cfg(not(unix))]
{
use std::os::windows::fs::symlink_dir;
symlink_dir(self.as_path().join(oldpath), self.as_path().join(newpath))
.unwrap();
}
}
pub fn symlink_file(
&self,
oldpath: impl AsRef<Path>,
newpath: impl AsRef<Path>,
) {
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
symlink(self.as_path().join(oldpath), self.as_path().join(newpath))
.unwrap();
}
#[cfg(not(unix))]
{
use std::os::windows::fs::symlink_file;
symlink_file(self.as_path().join(oldpath), self.as_path().join(newpath))
.unwrap();
}
}
pub fn read_dir(&self) -> fs::ReadDir {
fs::read_dir(self.as_path())
.with_context(|| format!("Reading {}", self.as_path().display()))
.unwrap()
}
pub fn copy(&self, to: &impl AsRef<Path>) {
std::fs::copy(self.as_path(), to)
.with_context(|| format!("Copying {} to {}", self, to.as_ref().display()))
.unwrap();
}
/// Copies this directory to another directory.
///
/// Note: Does not handle symlinks.
pub fn copy_to_recursive(&self, to: &PathRef) {
to.create_dir_all();
let read_dir = self.read_dir();
for entry in read_dir {
let entry = entry.unwrap();
let file_type = entry.file_type().unwrap();
let new_from = self.join(entry.file_name());
let new_to = to.join(entry.file_name());
if file_type.is_dir() {
new_from.copy_to_recursive(&new_to);
} else if file_type.is_file() {
new_from.copy(&new_to);
}
}
}
pub fn make_dir_readonly(&self) {
self.create_dir_all();
if cfg!(windows) {
Command::new("attrib").arg("+r").arg(self).output().unwrap();
} else if cfg!(unix) {
Command::new("chmod").arg("555").arg(self).output().unwrap();
}
}
}
#[cfg(not(windows))]
#[inline]
fn strip_unc_prefix(path: PathBuf) -> PathBuf {
path
}
/// Strips the unc prefix (ex. \\?\) from Windows paths.
///
/// Lifted from deno_core for use in the tests.
#[cfg(windows)]
fn strip_unc_prefix(path: PathBuf) -> PathBuf {
use std::path::Component;
use std::path::Prefix;
let mut components = path.components();
match components.next() {
Some(Component::Prefix(prefix)) => {
match prefix.kind() {
// \\?\device
Prefix::Verbatim(device) => {
let mut path = PathBuf::new();
path.push(format!(r"\\{}\", device.to_string_lossy()));
path.extend(components.filter(|c| !matches!(c, Component::RootDir)));
path
}
// \\?\c:\path
Prefix::VerbatimDisk(_) => {
let mut path = PathBuf::new();
path.push(prefix.as_os_str().to_string_lossy().replace(r"\\?\", ""));
path.extend(components);
path
}
// \\?\UNC\hostname\share_name\path
Prefix::VerbatimUNC(hostname, share_name) => {
let mut path = PathBuf::new();
path.push(format!(
r"\\{}\{}\",
hostname.to_string_lossy(),
share_name.to_string_lossy()
));
path.extend(components.filter(|c| !matches!(c, Component::RootDir)));
path
}
_ => path,
}
}
_ => path,
}
}
enum TempDirInner {
TempDir {
path_ref: PathRef,
// kept alive for the duration of the temp dir
_dir: tempfile::TempDir,
},
Path(PathRef),
Symlinked {
symlink: Arc<TempDirInner>,
target: Arc<TempDirInner>,
},
}
impl TempDirInner {
pub fn path(&self) -> &PathRef {
match self {
Self::Path(path_ref) => path_ref,
Self::TempDir { path_ref, .. } => path_ref,
Self::Symlinked { symlink, .. } => symlink.path(),
}
}
pub fn target_path(&self) -> &PathRef {
match self {
TempDirInner::Symlinked { target, .. } => target.target_path(),
_ => self.path(),
}
}
}
impl Drop for TempDirInner {
fn drop(&mut self) {
if let Self::Path(path) = self {
_ = fs::remove_dir_all(path);
}
}
}
/// For creating temporary directories in tests.
///
/// This was done because `tempfiles::TempDir` was very slow on Windows.
///
/// Note: Do not use this in actual code as this does not protect against
/// "insecure temporary file" security vulnerabilities.
#[derive(Clone)]
pub struct TempDir(Arc<TempDirInner>);
impl Default for TempDir {
fn default() -> Self {
Self::new()
}
}
impl TempDir {
pub fn new() -> Self {
Self::new_inner(&std::env::temp_dir(), None)
}
pub fn new_with_prefix(prefix: &str) -> Self {
Self::new_inner(&std::env::temp_dir(), Some(prefix))
}
pub fn new_with_path(path: &Path) -> Self {
Self(Arc::new(TempDirInner::Path(PathRef(path.to_path_buf()))))
}
pub fn new_symlinked(target: TempDir) -> Self {
let target_path = target.path();
let path = target_path.parent().join(format!(
"{}_symlinked",
target_path.as_path().file_name().unwrap().to_str().unwrap()
));
target.symlink_dir(target.path(), &path);
TempDir(Arc::new(TempDirInner::Symlinked {
target: target.0,
symlink: Self::new_with_path(path.as_path()).0,
}))
}
/// Create a new temporary directory with the given prefix as part of its name, if specified.
fn new_inner(parent_dir: &Path, prefix: Option<&str>) -> Self {
let mut builder = tempfile::Builder::new();
builder.prefix(prefix.unwrap_or("deno-cli-test"));
let dir = builder
.tempdir_in(parent_dir)
.expect("Failed to create a temporary directory");
Self(Arc::new(TempDirInner::TempDir {
path_ref: PathRef(dir.path().to_path_buf()),
_dir: dir,
}))
}
pub fn uri(&self) -> Url {
Url::from_directory_path(self.path()).unwrap()
}
pub fn path(&self) -> &PathRef {
self.0.path()
}
/// The resolved final target path if this is a symlink.
pub fn target_path(&self) -> &PathRef {
self.0.target_path()
}
pub fn create_dir_all(&self, path: impl AsRef<Path>) {
self.target_path().join(path).create_dir_all()
}
pub fn remove_file(&self, path: impl AsRef<Path>) {
self.target_path().join(path).remove_file()
}
pub fn remove_dir_all(&self, path: impl AsRef<Path>) {
self.target_path().join(path).remove_dir_all()
}
pub fn read_to_string(&self, path: impl AsRef<Path>) -> String {
self.target_path().join(path).read_to_string()
}
pub fn rename(&self, from: impl AsRef<Path>, to: impl AsRef<Path>) {
self.target_path().join(from).rename(to)
}
pub fn write(&self, path: impl AsRef<Path>, text: impl AsRef<str>) {
self.target_path().join(path).write(text)
}
pub fn symlink_dir(
&self,
oldpath: impl AsRef<Path>,
newpath: impl AsRef<Path>,
) {
self.target_path().symlink_dir(oldpath, newpath)
}
pub fn symlink_file(
&self,
oldpath: impl AsRef<Path>,
newpath: impl AsRef<Path>,
) {
self.target_path().symlink_file(oldpath, newpath)
}
}

View file

@ -56,16 +56,17 @@ use url::Url;
pub mod assertions;
mod builders;
pub mod factory;
mod fs;
pub mod lsp;
mod npm;
pub mod pty;
mod temp_dir;
pub use builders::TestCommandBuilder;
pub use builders::TestCommandOutput;
pub use builders::TestContext;
pub use builders::TestContextBuilder;
pub use temp_dir::TempDir;
pub use fs::PathRef;
pub use fs::TempDir;
const PORT: u16 = 4545;
const TEST_AUTH_TOKEN: &str = "abcdef123456789";
@ -115,30 +116,31 @@ pub fn env_vars_for_npm_tests() -> Vec<(String, String)> {
env_vars
}
pub fn root_path() -> PathBuf {
PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR")))
.parent()
.unwrap()
.to_path_buf()
pub fn root_path() -> PathRef {
PathRef::new(
PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR")))
.parent()
.unwrap(),
)
}
pub fn prebuilt_path() -> PathBuf {
pub fn prebuilt_path() -> PathRef {
third_party_path().join("prebuilt")
}
pub fn tests_path() -> PathBuf {
pub fn tests_path() -> PathRef {
root_path().join("cli").join("tests")
}
pub fn testdata_path() -> PathBuf {
pub fn testdata_path() -> PathRef {
tests_path().join("testdata")
}
pub fn third_party_path() -> PathBuf {
pub fn third_party_path() -> PathRef {
root_path().join("third_party")
}
pub fn napi_tests_path() -> PathBuf {
pub fn napi_tests_path() -> PathRef {
root_path().join("test_napi")
}
@ -147,7 +149,7 @@ pub fn npm_registry_url() -> String {
"http://localhost:4545/npm/registry/".to_string()
}
pub fn std_path() -> PathBuf {
pub fn std_path() -> PathRef {
root_path().join("test_util").join("std")
}
@ -155,22 +157,22 @@ pub fn std_file_url() -> String {
Url::from_directory_path(std_path()).unwrap().to_string()
}
pub fn target_dir() -> PathBuf {
pub fn target_dir() -> PathRef {
let current_exe = std::env::current_exe().unwrap();
let target_dir = current_exe.parent().unwrap().parent().unwrap();
target_dir.into()
PathRef::new(target_dir)
}
pub fn deno_exe_path() -> PathBuf {
pub fn deno_exe_path() -> PathRef {
// Something like /Users/rld/src/deno/target/debug/deps/deno
let mut p = target_dir().join("deno");
let mut p = target_dir().join("deno").to_path_buf();
if cfg!(windows) {
p.set_extension("exe");
}
p
PathRef::new(p)
}
pub fn prebuilt_tool_path(tool: &str) -> PathBuf {
pub fn prebuilt_tool_path(tool: &str) -> PathRef {
let mut exe = tool.to_string();
exe.push_str(if cfg!(windows) { ".exe" } else { "" });
prebuilt_path().join(platform_dir_name()).join(exe)
@ -189,7 +191,7 @@ pub fn platform_dir_name() -> &'static str {
}
pub fn test_server_path() -> PathBuf {
let mut p = target_dir().join("test_server");
let mut p = target_dir().join("test_server").to_path_buf();
if cfg!(windows) {
p.set_extension("exe");
}
@ -710,8 +712,7 @@ async fn absolute_redirect(
}
}
let mut file_path = testdata_path();
file_path.push(&req.uri().path()[1..]);
let file_path = testdata_path().join(&req.uri().path()[1..]);
if file_path.is_dir() || !file_path.exists() {
let mut not_found_resp = Response::new(Body::empty());
*not_found_resp.status_mut() = StatusCode::NOT_FOUND;
@ -1091,7 +1092,7 @@ async fn main_server(
Ok(res)
}
_ => {
let mut file_path = testdata_path();
let mut file_path = testdata_path().to_path_buf();
file_path.push(&req.uri().path()[1..]);
if let Ok(file) = tokio::fs::read(&file_path).await {
let file_resp = custom_headers(req.uri().path(), file);
@ -1138,8 +1139,7 @@ async fn main_server(
}
}
} else if let Some(suffix) = req.uri().path().strip_prefix("/deno_std/") {
let mut file_path = std_path();
file_path.push(suffix);
let file_path = std_path().join(suffix);
if let Ok(file) = tokio::fs::read(&file_path).await {
let file_resp = custom_headers(req.uri().path(), file);
return Ok(file_resp);
@ -2385,37 +2385,6 @@ pub fn parse_max_mem(output: &str) -> Option<u64> {
None
}
/// Copies a directory to another directory.
///
/// Note: Does not handle symlinks.
pub fn copy_dir_recursive(from: &Path, to: &Path) -> Result<(), anyhow::Error> {
use anyhow::Context;
std::fs::create_dir_all(to)
.with_context(|| format!("Creating {}", to.display()))?;
let read_dir = std::fs::read_dir(from)
.with_context(|| format!("Reading {}", from.display()))?;
for entry in read_dir {
let entry = entry?;
let file_type = entry.file_type()?;
let new_from = from.join(entry.file_name());
let new_to = to.join(entry.file_name());
if file_type.is_dir() {
copy_dir_recursive(&new_from, &new_to).with_context(|| {
format!("Dir {} to {}", new_from.display(), new_to.display())
})?;
} else if file_type.is_file() {
std::fs::copy(&new_from, &new_to).with_context(|| {
format!("Copying {} to {}", new_from.display(), new_to.display())
})?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;

View file

@ -2,6 +2,7 @@
use crate::deno_exe_path;
use crate::npm_registry_url;
use crate::PathRef;
use crate::TestContext;
use crate::TestContextBuilder;
@ -38,7 +39,6 @@ use std::collections::HashSet;
use std::io;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::process::Child;
use std::process::ChildStdin;
use std::process::ChildStdout;
@ -468,7 +468,7 @@ impl InitializeParamsBuilder {
pub struct LspClientBuilder {
print_stderr: bool,
deno_exe: PathBuf,
deno_exe: PathRef,
context: Option<TestContext>,
use_diagnostic_sync: bool,
}
@ -485,7 +485,7 @@ impl LspClientBuilder {
}
pub fn deno_exe(&mut self, exe_path: impl AsRef<Path>) -> &mut Self {
self.deno_exe = exe_path.as_ref().to_path_buf();
self.deno_exe = PathRef::new(exe_path);
self
}

View file

@ -93,10 +93,7 @@ fn get_npm_package(package_name: &str) -> Result<Option<CustomNpmPackage>> {
builder
.append_dir_all("package", &version_folder)
.with_context(|| {
format!(
"Error adding tarball for directory: {}",
version_folder.display()
)
format!("Error adding tarball for directory: {}", version_folder)
})?;
builder.finish()?;
}
@ -128,10 +125,7 @@ fn get_npm_package(package_name: &str) -> Result<Option<CustomNpmPackage>> {
let package_json_path = version_folder.join("package.json");
let package_json_text = fs::read_to_string(&package_json_path)
.with_context(|| {
format!(
"Error reading package.json at {}",
package_json_path.display()
)
format!("Error reading package.json at {}", package_json_path)
})?;
let mut version_info: serde_json::Map<String, serde_json::Value> =
serde_json::from_str(&package_json_text)?;

View file

@ -1,175 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::Context;
use lsp_types::Url;
enum TempDirInner {
TempDir(tempfile::TempDir),
Path(PathBuf),
Symlinked {
symlink: Arc<TempDirInner>,
target: Arc<TempDirInner>,
},
}
impl TempDirInner {
pub fn path(&self) -> &Path {
match self {
Self::Path(path) => path.as_path(),
Self::TempDir(dir) => dir.path(),
Self::Symlinked { symlink, .. } => symlink.path(),
}
}
pub fn target_path(&self) -> &Path {
match self {
TempDirInner::Symlinked { target, .. } => target.target_path(),
_ => self.path(),
}
}
}
impl Drop for TempDirInner {
fn drop(&mut self) {
if let Self::Path(path) = self {
_ = fs::remove_dir_all(path);
}
}
}
/// For creating temporary directories in tests.
///
/// This was done because `tempfiles::TempDir` was very slow on Windows.
///
/// Note: Do not use this in actual code as this does not protect against
/// "insecure temporary file" security vulnerabilities.
#[derive(Clone)]
pub struct TempDir(Arc<TempDirInner>);
impl Default for TempDir {
fn default() -> Self {
Self::new()
}
}
impl TempDir {
pub fn new() -> Self {
Self::new_inner(&std::env::temp_dir(), None)
}
pub fn new_in(path: &Path) -> Self {
Self::new_inner(path, None)
}
pub fn new_with_prefix(prefix: &str) -> Self {
Self::new_inner(&std::env::temp_dir(), Some(prefix))
}
pub fn new_with_path(path: &Path) -> Self {
Self(Arc::new(TempDirInner::Path(path.to_path_buf())))
}
pub fn new_symlinked(target: TempDir) -> Self {
let target_path = target.path();
let path = target_path.parent().unwrap().join(format!(
"{}_symlinked",
target_path.file_name().unwrap().to_str().unwrap()
));
target.symlink_dir(target.path(), &path);
TempDir(Arc::new(TempDirInner::Symlinked {
target: target.0,
symlink: Self::new_with_path(&path).0,
}))
}
/// Create a new temporary directory with the given prefix as part of its name, if specified.
fn new_inner(parent_dir: &Path, prefix: Option<&str>) -> Self {
let mut builder = tempfile::Builder::new();
builder.prefix(prefix.unwrap_or("deno-cli-test"));
let dir = builder
.tempdir_in(parent_dir)
.expect("Failed to create a temporary directory");
Self(Arc::new(TempDirInner::TempDir(dir)))
}
pub fn uri(&self) -> Url {
Url::from_directory_path(self.path()).unwrap()
}
pub fn path(&self) -> &Path {
self.0.path()
}
/// The resolved final target path if this is a symlink.
pub fn target_path(&self) -> &Path {
self.0.target_path()
}
pub fn create_dir_all(&self, path: impl AsRef<Path>) {
fs::create_dir_all(self.target_path().join(path)).unwrap();
}
pub fn remove_file(&self, path: impl AsRef<Path>) {
fs::remove_file(self.target_path().join(path)).unwrap();
}
pub fn remove_dir_all(&self, path: impl AsRef<Path>) {
fs::remove_dir_all(self.target_path().join(path)).unwrap();
}
pub fn read_to_string(&self, path: impl AsRef<Path>) -> String {
let file_path = self.target_path().join(path);
fs::read_to_string(&file_path)
.with_context(|| format!("Could not find file: {}", file_path.display()))
.unwrap()
}
pub fn rename(&self, from: impl AsRef<Path>, to: impl AsRef<Path>) {
fs::rename(self.target_path().join(from), self.path().join(to)).unwrap();
}
pub fn write(&self, path: impl AsRef<Path>, text: impl AsRef<str>) {
fs::write(self.target_path().join(path), text.as_ref()).unwrap();
}
pub fn symlink_dir(
&self,
oldpath: impl AsRef<Path>,
newpath: impl AsRef<Path>,
) {
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
symlink(self.path().join(oldpath), self.path().join(newpath)).unwrap();
}
#[cfg(not(unix))]
{
use std::os::windows::fs::symlink_dir;
symlink_dir(self.path().join(oldpath), self.path().join(newpath))
.unwrap();
}
}
pub fn symlink_file(
&self,
oldpath: impl AsRef<Path>,
newpath: impl AsRef<Path>,
) {
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
symlink(self.path().join(oldpath), self.path().join(newpath)).unwrap();
}
#[cfg(not(unix))]
{
use std::os::windows::fs::symlink_file;
symlink_file(self.path().join(oldpath), self.path().join(newpath))
.unwrap();
}
}
}