Skip to content

Commit

Permalink
chore(tests): test_util - Add PathRef (denoland#19450)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
dsherret committed Jun 10, 2023
1 parent f3326ee commit 7f15126
Show file tree
Hide file tree
Showing 40 changed files with 778 additions and 719 deletions.
14 changes: 7 additions & 7 deletions cli/args/config_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
}

Expand Down Expand Up @@ -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"),
Expand All @@ -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());
}
Expand All @@ -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"));
}

Expand Down
39 changes: 20 additions & 19 deletions cli/args/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
)
Expand All @@ -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"),
]
)
}
Expand Down
10 changes: 5 additions & 5 deletions cli/bench/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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,
Expand All @@ -95,7 +95,7 @@ pub fn benchmark(
file_stem.to_string(),
run(
&[
deno_exe,
deno_exe.as_str(),
"run",
"--allow-all",
"--unstable",
Expand Down Expand Up @@ -160,8 +160,8 @@ fn run(
assert!(wrk.is_file());

let addr = format!("http:https://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");
Expand Down
34 changes: 17 additions & 17 deletions cli/bench/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,20 @@ use std::path::PathBuf;
use std::process::Command;
use std::process::Stdio;
use std::time::SystemTime;
use test_util::PathRef;

include!("../util/time.rs");

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(())
Expand Down Expand Up @@ -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",
]
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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*
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
}

Expand All @@ -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))
Expand Down Expand Up @@ -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(())
}
Expand Down
3 changes: 1 addition & 2 deletions cli/bench/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
Expand All @@ -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")
Expand Down
13 changes: 6 additions & 7 deletions cli/cache/disk_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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:");
Expand All @@ -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:");
Expand Down
2 changes: 1 addition & 1 deletion cli/cache/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
13 changes: 5 additions & 8 deletions cli/cache/http_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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(
Expand All @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion cli/factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
Loading

0 comments on commit 7f15126

Please sign in to comment.