1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-22 15:24:46 -05:00

chore: split up integration_tests.rs into separate files (#11131)

This commit is contained in:
David Sherret 2021-06-27 13:27:36 -04:00 committed by GitHub
parent 5bf7da91f1
commit 098a7c8886
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 5784 additions and 5964 deletions

View file

@ -0,0 +1,377 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use crate::itest;
use tempfile::TempDir;
use test_util as util;
#[test]
fn bundle_exports() {
// First we have to generate a bundle of some module that has exports.
let mod1 = util::root_path().join("cli/tests/subdir/mod1.ts");
assert!(mod1.is_file());
let t = TempDir::new().expect("tempdir fail");
let bundle = t.path().join("mod1.bundle.js");
let mut deno = util::deno_cmd()
.current_dir(util::root_path())
.arg("bundle")
.arg(mod1)
.arg(&bundle)
.spawn()
.expect("failed to spawn script");
let status = deno.wait().expect("failed to wait for the child process");
assert!(status.success());
assert!(bundle.is_file());
// Now we try to use that bundle from another module.
let test = t.path().join("test.js");
std::fs::write(
&test,
"
import { printHello3 } from \"./mod1.bundle.js\";
printHello3(); ",
)
.expect("error writing file");
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("run")
.arg(&test)
.output()
.expect("failed to spawn script");
// check the output of the test.ts program.
assert!(std::str::from_utf8(&output.stdout)
.unwrap()
.trim()
.ends_with("Hello"));
assert_eq!(output.stderr, b"");
}
#[test]
fn bundle_exports_no_check() {
// First we have to generate a bundle of some module that has exports.
let mod1 = util::root_path().join("cli/tests/subdir/mod1.ts");
assert!(mod1.is_file());
let t = TempDir::new().expect("tempdir fail");
let bundle = t.path().join("mod1.bundle.js");
let mut deno = util::deno_cmd()
.current_dir(util::root_path())
.arg("bundle")
.arg("--no-check")
.arg(mod1)
.arg(&bundle)
.spawn()
.expect("failed to spawn script");
let status = deno.wait().expect("failed to wait for the child process");
assert!(status.success());
assert!(bundle.is_file());
// Now we try to use that bundle from another module.
let test = t.path().join("test.js");
std::fs::write(
&test,
"
import { printHello3 } from \"./mod1.bundle.js\";
printHello3(); ",
)
.expect("error writing file");
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("run")
.arg(&test)
.output()
.expect("failed to spawn script");
// check the output of the test.ts program.
assert!(std::str::from_utf8(&output.stdout)
.unwrap()
.trim()
.ends_with("Hello"));
assert_eq!(output.stderr, b"");
}
#[test]
fn bundle_circular() {
// First we have to generate a bundle of some module that has exports.
let circular1 = util::root_path().join("cli/tests/subdir/circular1.ts");
assert!(circular1.is_file());
let t = TempDir::new().expect("tempdir fail");
let bundle = t.path().join("circular1.bundle.js");
let mut deno = util::deno_cmd()
.current_dir(util::root_path())
.arg("bundle")
.arg(circular1)
.arg(&bundle)
.spawn()
.expect("failed to spawn script");
let status = deno.wait().expect("failed to wait for the child process");
assert!(status.success());
assert!(bundle.is_file());
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("run")
.arg(&bundle)
.output()
.expect("failed to spawn script");
// check the output of the the bundle program.
assert!(std::str::from_utf8(&output.stdout)
.unwrap()
.trim()
.ends_with("f2\nf1"));
assert_eq!(output.stderr, b"");
}
#[test]
fn bundle_single_module() {
// First we have to generate a bundle of some module that has exports.
let single_module =
util::root_path().join("cli/tests/subdir/single_module.ts");
assert!(single_module.is_file());
let t = TempDir::new().expect("tempdir fail");
let bundle = t.path().join("single_module.bundle.js");
let mut deno = util::deno_cmd()
.current_dir(util::root_path())
.arg("bundle")
.arg(single_module)
.arg(&bundle)
.spawn()
.expect("failed to spawn script");
let status = deno.wait().expect("failed to wait for the child process");
assert!(status.success());
assert!(bundle.is_file());
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("run")
.arg(&bundle)
.output()
.expect("failed to spawn script");
// check the output of the the bundle program.
assert!(std::str::from_utf8(&output.stdout)
.unwrap()
.trim()
.ends_with("Hello world!"));
assert_eq!(output.stderr, b"");
}
#[test]
fn bundle_tla() {
// First we have to generate a bundle of some module that has exports.
let tla_import = util::root_path().join("cli/tests/subdir/tla.ts");
assert!(tla_import.is_file());
let t = tempfile::TempDir::new().expect("tempdir fail");
let bundle = t.path().join("tla.bundle.js");
let mut deno = util::deno_cmd()
.current_dir(util::root_path())
.arg("bundle")
.arg(tla_import)
.arg(&bundle)
.spawn()
.expect("failed to spawn script");
let status = deno.wait().expect("failed to wait for the child process");
assert!(status.success());
assert!(bundle.is_file());
// Now we try to use that bundle from another module.
let test = t.path().join("test.js");
std::fs::write(
&test,
"
import { foo } from \"./tla.bundle.js\";
console.log(foo); ",
)
.expect("error writing file");
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("run")
.arg(&test)
.output()
.expect("failed to spawn script");
// check the output of the test.ts program.
assert!(std::str::from_utf8(&output.stdout)
.unwrap()
.trim()
.ends_with("Hello"));
assert_eq!(output.stderr, b"");
}
#[test]
fn bundle_js() {
// First we have to generate a bundle of some module that has exports.
let mod6 = util::root_path().join("cli/tests/subdir/mod6.js");
assert!(mod6.is_file());
let t = TempDir::new().expect("tempdir fail");
let bundle = t.path().join("mod6.bundle.js");
let mut deno = util::deno_cmd()
.current_dir(util::root_path())
.arg("bundle")
.arg(mod6)
.arg(&bundle)
.spawn()
.expect("failed to spawn script");
let status = deno.wait().expect("failed to wait for the child process");
assert!(status.success());
assert!(bundle.is_file());
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("run")
.arg(&bundle)
.output()
.expect("failed to spawn script");
// check that nothing went to stderr
assert_eq!(output.stderr, b"");
}
#[test]
fn bundle_dynamic_import() {
let _g = util::http_server();
let dynamic_import =
util::root_path().join("cli/tests/bundle_dynamic_import.ts");
assert!(dynamic_import.is_file());
let t = TempDir::new().expect("tempdir fail");
let bundle = t.path().join("bundle_dynamic_import.bundle.js");
let mut deno = util::deno_cmd()
.current_dir(util::root_path())
.arg("bundle")
.arg(dynamic_import)
.arg(&bundle)
.spawn()
.expect("failed to spawn script");
let status = deno.wait().expect("failed to wait for the child process");
assert!(status.success());
assert!(bundle.is_file());
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("run")
.arg("--allow-net")
.arg("--quiet")
.arg(&bundle)
.output()
.expect("failed to spawn script");
// check the output of the test.ts program.
assert!(std::str::from_utf8(&output.stdout)
.unwrap()
.trim()
.ends_with("Hello"));
assert_eq!(output.stderr, b"");
}
#[test]
fn bundle_import_map() {
let import = util::root_path().join("cli/tests/bundle_im.ts");
let import_map_path = util::root_path().join("cli/tests/bundle_im.json");
assert!(import.is_file());
let t = TempDir::new().expect("tempdir fail");
let bundle = t.path().join("import_map.bundle.js");
let mut deno = util::deno_cmd()
.current_dir(util::root_path())
.arg("bundle")
.arg("--import-map")
.arg(import_map_path)
.arg(import)
.arg(&bundle)
.spawn()
.expect("failed to spawn script");
let status = deno.wait().expect("failed to wait for the child process");
assert!(status.success());
assert!(bundle.is_file());
// Now we try to use that bundle from another module.
let test = t.path().join("test.js");
std::fs::write(
&test,
"
import { printHello3 } from \"./import_map.bundle.js\";
printHello3(); ",
)
.expect("error writing file");
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("run")
.arg(&test)
.output()
.expect("failed to spawn script");
// check the output of the test.ts program.
assert!(std::str::from_utf8(&output.stdout)
.unwrap()
.trim()
.ends_with("Hello"));
assert_eq!(output.stderr, b"");
}
#[test]
fn bundle_import_map_no_check() {
let import = util::root_path().join("cli/tests/bundle_im.ts");
let import_map_path = util::root_path().join("cli/tests/bundle_im.json");
assert!(import.is_file());
let t = TempDir::new().expect("tempdir fail");
let bundle = t.path().join("import_map.bundle.js");
let mut deno = util::deno_cmd()
.current_dir(util::root_path())
.arg("bundle")
.arg("--no-check")
.arg("--import-map")
.arg(import_map_path)
.arg(import)
.arg(&bundle)
.spawn()
.expect("failed to spawn script");
let status = deno.wait().expect("failed to wait for the child process");
assert!(status.success());
assert!(bundle.is_file());
// Now we try to use that bundle from another module.
let test = t.path().join("test.js");
std::fs::write(
&test,
"
import { printHello3 } from \"./import_map.bundle.js\";
printHello3(); ",
)
.expect("error writing file");
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("run")
.arg(&test)
.output()
.expect("failed to spawn script");
// check the output of the test.ts program.
assert!(std::str::from_utf8(&output.stdout)
.unwrap()
.trim()
.ends_with("Hello"));
assert_eq!(output.stderr, b"");
}
itest!(lock_check_err_with_bundle {
args: "bundle --lock=lock_check_err_with_bundle.json http://127.0.0.1:4545/cli/tests/subdir/mod1.ts",
output: "lock_check_err_with_bundle.out",
exit_code: 10,
http_server: true,
});
itest!(bundle {
args: "bundle subdir/mod1.ts",
output: "bundle.test.out",
});
itest!(bundle_jsx {
args: "bundle jsx_import_from_ts.ts",
output: "bundle_jsx.out",
});
itest!(error_027_bundle_with_bare_import {
args: "bundle error_027_bundle_with_bare_import.ts",
output: "error_027_bundle_with_bare_import.ts.out",
exit_code: 1,
});
itest!(ts_decorators_bundle {
args: "bundle ts_decorators_bundle.ts",
output: "ts_decorators_bundle.out",
});

View file

@ -0,0 +1,50 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use crate::itest;
itest!(_036_import_map_fetch {
args:
"cache --quiet --reload --import-map=import_maps/import_map.json import_maps/test.ts",
output: "036_import_map_fetch.out",
});
itest!(_037_fetch_multiple {
args: "cache --reload fetch/test.ts fetch/other.ts",
http_server: true,
output: "037_fetch_multiple.out",
});
itest!(_095_cache_with_bare_import {
args: "cache 095_cache_with_bare_import.ts",
output: "095_cache_with_bare_import.ts.out",
exit_code: 1,
});
itest!(cache_extensionless {
args: "cache --reload http://localhost:4545/cli/tests/subdir/no_js_ext",
output: "cache_extensionless.out",
http_server: true,
});
itest!(cache_random_extension {
args: "cache --reload http://localhost:4545/cli/tests/subdir/no_js_ext@1.0.0",
output: "cache_random_extension.out",
http_server: true,
});
itest!(performance_stats {
args: "cache --reload --log-level debug 002_hello.ts",
output: "performance_stats.out",
});
itest!(redirect_cache {
http_server: true,
args: "cache --reload http://localhost:4548/cli/tests/subdir/redirects/a.ts",
output: "redirect_cache.out",
});
itest!(ignore_require {
args: "cache --reload --no-check ignore_require.js",
output_str: Some(""),
exit_code: 0,
});

View file

@ -0,0 +1,372 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use std::process::Command;
use tempfile::TempDir;
use test_util as util;
#[test]
fn compile() {
let dir = TempDir::new().expect("tempdir fail");
let exe = if cfg!(windows) {
dir.path().join("welcome.exe")
} else {
dir.path().join("welcome")
};
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("compile")
.arg("--unstable")
.arg("--output")
.arg(&exe)
.arg("./test_util/std/examples/welcome.ts")
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
let output = Command::new(exe)
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
assert_eq!(output.stdout, "Welcome to Deno!\n".as_bytes());
}
#[ignore]
#[test]
#[cfg(windows)]
// https://github.com/denoland/deno/issues/9667
fn compile_windows_ext() {
let dir = TempDir::new().expect("tempdir fail");
let exe = dir.path().join("welcome_9667");
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("compile")
.arg("--unstable")
.arg("--output")
.arg(&exe)
.arg("--target")
.arg("x86_64-unknown-linux-gnu")
.arg("./test_util/std/examples/welcome.ts")
// TODO(kt3k): Prints command output to the test log for debugging purpose.
// Uncomment this line when this test become stable.
//.stdout(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
assert!(std::path::Path::new(&exe).exists());
}
#[test]
fn standalone_args() {
let dir = TempDir::new().expect("tempdir fail");
let exe = if cfg!(windows) {
dir.path().join("args.exe")
} else {
dir.path().join("args")
};
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("compile")
.arg("--unstable")
.arg("--output")
.arg(&exe)
.arg("./cli/tests/028_args.ts")
.arg("a")
.arg("b")
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
let output = Command::new(exe)
.arg("foo")
.arg("--bar")
.arg("--unstable")
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
assert_eq!(output.stdout, b"a\nb\nfoo\n--bar\n--unstable\n");
}
#[test]
fn standalone_error() {
let dir = TempDir::new().expect("tempdir fail");
let exe = if cfg!(windows) {
dir.path().join("error.exe")
} else {
dir.path().join("error")
};
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("compile")
.arg("--unstable")
.arg("--output")
.arg(&exe)
.arg("./cli/tests/standalone_error.ts")
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
let output = Command::new(exe)
.env("NO_COLOR", "1")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(!output.status.success());
assert_eq!(output.stdout, b"");
let expected_stderr = "error: Error: boom!\n at boom (file://$deno$/bundle.js:2:11)\n at foo (file://$deno$/bundle.js:5:5)\n at file://$deno$/bundle.js:7:1\n";
let stderr = String::from_utf8(output.stderr).unwrap();
assert_eq!(stderr, expected_stderr);
}
#[test]
fn standalone_no_module_load() {
let dir = TempDir::new().expect("tempdir fail");
let exe = if cfg!(windows) {
dir.path().join("hello.exe")
} else {
dir.path().join("hello")
};
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("compile")
.arg("--unstable")
.arg("--output")
.arg(&exe)
.arg("./cli/tests/standalone_import.ts")
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
let output = Command::new(exe)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(!output.status.success());
assert_eq!(output.stdout, b"start\n");
let stderr_str = String::from_utf8(output.stderr).unwrap();
assert!(util::strip_ansi_codes(&stderr_str)
.contains("Self-contained binaries don't support module loading"));
}
#[test]
fn standalone_load_datauri() {
let dir = TempDir::new().expect("tempdir fail");
let exe = if cfg!(windows) {
dir.path().join("load_datauri.exe")
} else {
dir.path().join("load_datauri")
};
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("compile")
.arg("--unstable")
.arg("--output")
.arg(&exe)
.arg("./cli/tests/standalone_import_datauri.ts")
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
let output = Command::new(exe)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
assert_eq!(output.stdout, b"Hello Deno!\n");
}
#[test]
fn standalone_compiler_ops() {
let dir = TempDir::new().expect("tempdir fail");
let exe = if cfg!(windows) {
dir.path().join("standalone_compiler_ops.exe")
} else {
dir.path().join("standalone_compiler_ops")
};
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("compile")
.arg("--unstable")
.arg("--output")
.arg(&exe)
.arg("./cli/tests/standalone_compiler_ops.ts")
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
let output = Command::new(exe)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
assert_eq!(output.stdout, b"Hello, Compiler API!\n");
}
#[test]
fn compile_with_directory_exists_error() {
let dir = TempDir::new().expect("tempdir fail");
let exe = if cfg!(windows) {
dir.path().join("args.exe")
} else {
dir.path().join("args")
};
std::fs::create_dir(&exe).expect("cannot create directory");
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("compile")
.arg("--unstable")
.arg("--output")
.arg(&exe)
.arg("./cli/tests/028_args.ts")
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(!output.status.success());
let expected_stderr =
format!("Could not compile: {:?} is a directory.\n", &exe);
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(stderr.contains(&expected_stderr));
}
#[test]
fn compile_with_conflict_file_exists_error() {
let dir = TempDir::new().expect("tempdir fail");
let exe = if cfg!(windows) {
dir.path().join("args.exe")
} else {
dir.path().join("args")
};
std::fs::write(&exe, b"SHOULD NOT BE OVERWRITTEN")
.expect("cannot create file");
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("compile")
.arg("--unstable")
.arg("--output")
.arg(&exe)
.arg("./cli/tests/028_args.ts")
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(!output.status.success());
let expected_stderr =
format!("Could not compile: cannot overwrite {:?}.\n", &exe);
let stderr = String::from_utf8(output.stderr).unwrap();
dbg!(&stderr);
assert!(stderr.contains(&expected_stderr));
assert!(std::fs::read(&exe)
.expect("cannot read file")
.eq(b"SHOULD NOT BE OVERWRITTEN"));
}
#[test]
fn compile_and_overwrite_file() {
let dir = TempDir::new().expect("tempdir fail");
let exe = if cfg!(windows) {
dir.path().join("args.exe")
} else {
dir.path().join("args")
};
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("compile")
.arg("--unstable")
.arg("--output")
.arg(&exe)
.arg("./cli/tests/028_args.ts")
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
assert!(&exe.exists());
let recompile_output = util::deno_cmd()
.current_dir(util::root_path())
.arg("compile")
.arg("--unstable")
.arg("--output")
.arg(&exe)
.arg("./cli/tests/028_args.ts")
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(recompile_output.status.success());
}
#[test]
fn standalone_runtime_flags() {
let dir = TempDir::new().expect("tempdir fail");
let exe = if cfg!(windows) {
dir.path().join("flags.exe")
} else {
dir.path().join("flags")
};
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("compile")
.arg("--unstable")
.arg("--allow-read")
.arg("--seed")
.arg("1")
.arg("--output")
.arg(&exe)
.arg("./cli/tests/standalone_runtime_flags.ts")
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
let output = Command::new(exe)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(!output.status.success());
let stdout_str = String::from_utf8(output.stdout).unwrap();
assert_eq!(util::strip_ansi_codes(&stdout_str), "0.147205063401058\n");
let stderr_str = String::from_utf8(output.stderr).unwrap();
assert!(util::strip_ansi_codes(&stderr_str)
.contains("PermissionDenied: Requires write access"));
}

View file

@ -0,0 +1,156 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use std::fs;
use tempfile::TempDir;
use test_util as util;
#[test]
fn branch() {
let tempdir = TempDir::new().expect("tempdir fail");
let tempdir = tempdir.path().join("cov");
let status = util::deno_cmd()
.current_dir(util::root_path())
.arg("test")
.arg("--quiet")
.arg("--unstable")
.arg(format!("--coverage={}", tempdir.to_str().unwrap()))
.arg("cli/tests/coverage/branch_test.ts")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit())
.status()
.expect("failed to spawn test runner");
assert!(status.success());
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("coverage")
.arg("--quiet")
.arg("--unstable")
.arg(format!("{}/", tempdir.to_str().unwrap()))
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit())
.output()
.expect("failed to spawn coverage reporter");
let actual =
util::strip_ansi_codes(std::str::from_utf8(&output.stdout).unwrap())
.to_string();
let expected = fs::read_to_string(
util::root_path().join("cli/tests/coverage/expected_branch.out"),
)
.unwrap();
if !util::wildcard_match(&expected, &actual) {
println!("OUTPUT\n{}\nOUTPUT", actual);
println!("EXPECTED\n{}\nEXPECTED", expected);
panic!("pattern match failed");
}
assert!(output.status.success());
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("coverage")
.arg("--quiet")
.arg("--unstable")
.arg("--lcov")
.arg(format!("{}/", tempdir.to_str().unwrap()))
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit())
.output()
.expect("failed to spawn coverage reporter");
let actual =
util::strip_ansi_codes(std::str::from_utf8(&output.stdout).unwrap())
.to_string();
let expected = fs::read_to_string(
util::root_path().join("cli/tests/coverage/expected_branch.lcov"),
)
.unwrap();
if !util::wildcard_match(&expected, &actual) {
println!("OUTPUT\n{}\nOUTPUT", actual);
println!("EXPECTED\n{}\nEXPECTED", expected);
panic!("pattern match failed");
}
assert!(output.status.success());
}
#[test]
fn complex() {
let tempdir = TempDir::new().expect("tempdir fail");
let status = util::deno_cmd()
.current_dir(util::root_path())
.arg("test")
.arg("--quiet")
.arg("--unstable")
.arg(format!("--coverage={}", tempdir.path().to_str().unwrap()))
.arg("cli/tests/coverage/complex_test.ts")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit())
.status()
.expect("failed to spawn test runner");
assert!(status.success());
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("coverage")
.arg("--quiet")
.arg("--unstable")
.arg(format!("{}/", tempdir.path().to_str().unwrap()))
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit())
.output()
.expect("failed to spawn coverage reporter");
let actual =
util::strip_ansi_codes(std::str::from_utf8(&output.stdout).unwrap())
.to_string();
let expected = fs::read_to_string(
util::root_path().join("cli/tests/coverage/expected_complex.out"),
)
.unwrap();
if !util::wildcard_match(&expected, &actual) {
println!("OUTPUT\n{}\nOUTPUT", actual);
println!("EXPECTED\n{}\nEXPECTED", expected);
panic!("pattern match failed");
}
assert!(output.status.success());
let output = util::deno_cmd()
.current_dir(util::root_path())
.arg("coverage")
.arg("--quiet")
.arg("--unstable")
.arg("--lcov")
.arg(format!("{}/", tempdir.path().to_str().unwrap()))
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit())
.output()
.expect("failed to spawn coverage reporter");
let actual =
util::strip_ansi_codes(std::str::from_utf8(&output.stdout).unwrap())
.to_string();
let expected = fs::read_to_string(
util::root_path().join("cli/tests/coverage/expected_complex.lcov"),
)
.unwrap();
if !util::wildcard_match(&expected, &actual) {
println!("OUTPUT\n{}\nOUTPUT", actual);
println!("EXPECTED\n{}\nEXPECTED", expected);
panic!("pattern match failed");
}
assert!(output.status.success());
}

View file

@ -0,0 +1,45 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use crate::itest;
itest!(deno_doc_builtin {
args: "doc",
output: "deno_doc_builtin.out",
});
itest!(deno_doc {
args: "doc deno_doc.ts",
output: "deno_doc.out",
});
itest!(deno_doc_import_map {
args: "doc --unstable --import-map=doc/import_map.json doc/use_import_map.js",
output: "doc/use_import_map.out",
});
itest!(deno_doc_types_hint {
args: "doc doc/types_hint.ts",
output: "doc/types_hint.out",
});
itest!(deno_doc_types_ref {
args: "doc doc/types_ref.js",
output: "doc/types_ref.out",
});
itest!(deno_doc_types_header {
args: "doc --reload doc/types_header.ts",
output: "doc/types_header.out",
http_server: true,
});
itest!(_060_deno_doc_displays_all_overloads_in_details_view {
args: "doc 060_deno_doc_displays_all_overloads_in_details_view.ts NS.test",
output: "060_deno_doc_displays_all_overloads_in_details_view.ts.out",
});
itest!(deno_doc_types_header_direct {
args: "doc --reload http://127.0.0.1:4545/xTypeScriptTypes.js",
output: "doc/types_header.out",
http_server: true,
});

View file

@ -0,0 +1,44 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use crate::itest;
use test_util as util;
#[test]
fn eval_p() {
let output = util::deno_cmd()
.arg("eval")
.arg("-p")
.arg("1+2")
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(output.status.success());
let stdout_str =
util::strip_ansi_codes(std::str::from_utf8(&output.stdout).unwrap().trim());
assert_eq!("3", stdout_str);
}
itest!(_029_eval {
args: "eval console.log(\"hello\")",
output: "029_eval.out",
});
// Ugly parentheses due to whitespace delimiting problem.
itest!(_030_eval_ts {
args: "eval --quiet --ext=ts console.log((123)as(number))", // 'as' is a TS keyword only
output: "030_eval_ts.out",
});
itest!(_041_dyn_import_eval {
args: "eval import('./subdir/mod4.js').then(console.log)",
output: "041_dyn_import_eval.out",
});
// Cannot write the expression to evaluate as "console.log(typeof gc)"
// because itest! splits args on whitespace.
itest!(v8_flags_eval {
args: "eval --v8-flags=--expose-gc console.log(typeof(gc))",
output: "v8_flags.js.out",
});

View file

@ -0,0 +1,184 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use crate::itest;
use tempfile::TempDir;
use test_util as util;
#[test]
fn fmt_test() {
let t = TempDir::new().expect("tempdir fail");
let fixed_js = util::root_path().join("cli/tests/badly_formatted_fixed.js");
let badly_formatted_original_js =
util::root_path().join("cli/tests/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)
.expect("Failed to copy file");
let fixed_md = util::root_path().join("cli/tests/badly_formatted_fixed.md");
let badly_formatted_original_md =
util::root_path().join("cli/tests/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)
.expect("Failed to copy file");
let fixed_json =
util::root_path().join("cli/tests/badly_formatted_fixed.json");
let badly_formatted_original_json =
util::root_path().join("cli/tests/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)
.expect("Failed to copy file");
// First, check formatting by ignoring the badly formatted file.
let status = util::deno_cmd()
.current_dir(util::root_path())
.arg("fmt")
.arg(format!(
"--ignore={},{},{}",
badly_formatted_js_str, badly_formatted_md_str, badly_formatted_json_str
))
.arg("--check")
.arg(badly_formatted_js_str)
.arg(badly_formatted_md_str)
.arg(badly_formatted_json_str)
.spawn()
.expect("Failed to spawn script")
.wait()
.expect("Failed to wait for child process");
// No target files found
assert!(!status.success());
// Check without ignore.
let status = util::deno_cmd()
.current_dir(util::root_path())
.arg("fmt")
.arg("--check")
.arg(badly_formatted_js_str)
.arg(badly_formatted_md_str)
.arg(badly_formatted_json_str)
.spawn()
.expect("Failed to spawn script")
.wait()
.expect("Failed to wait for child process");
assert!(!status.success());
// Format the source file.
let status = util::deno_cmd()
.current_dir(util::root_path())
.arg("fmt")
.arg(badly_formatted_js_str)
.arg(badly_formatted_md_str)
.arg(badly_formatted_json_str)
.spawn()
.expect("Failed to spawn script")
.wait()
.expect("Failed to wait for child process");
assert!(status.success());
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();
assert_eq!(expected_js, actual_js);
assert_eq!(expected_md, actual_md);
assert_eq!(expected_json, actual_json);
}
#[test]
fn fmt_stdin_error() {
use std::io::Write;
let mut deno = util::deno_cmd()
.current_dir(util::root_path())
.arg("fmt")
.arg("-")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let stdin = deno.stdin.as_mut().unwrap();
let invalid_js = b"import { example }";
stdin.write_all(invalid_js).unwrap();
let output = deno.wait_with_output().unwrap();
// Error message might change. Just check stdout empty, stderr not.
assert!(output.stdout.is_empty());
assert!(!output.stderr.is_empty());
assert!(!output.status.success());
}
#[test]
fn fmt_ignore_unexplicit_files() {
let output = util::deno_cmd()
.current_dir(util::root_path())
.env("NO_COLOR", "1")
.arg("fmt")
.arg("--check")
.arg("--ignore=./")
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(!output.status.success());
assert_eq!(
String::from_utf8_lossy(&output.stderr),
"error: No target files found.\n"
);
}
itest!(fmt_check_tests_dir {
args: "fmt --check ./ --ignore=.test_coverage",
output: "fmt/expected_fmt_check_tests_dir.out",
exit_code: 1,
});
itest!(fmt_quiet_check_fmt_dir {
args: "fmt --check --quiet fmt/",
output_str: Some(""),
exit_code: 0,
});
itest!(fmt_check_formatted_files {
args: "fmt --check fmt/formatted1.js fmt/formatted2.ts fmt/formatted3.md fmt/formatted4.jsonc",
output: "fmt/expected_fmt_check_formatted_files.out",
exit_code: 0,
});
itest!(fmt_check_ignore {
args: "fmt --check --ignore=fmt/formatted1.js fmt/",
output: "fmt/expected_fmt_check_ignore.out",
exit_code: 0,
});
itest!(fmt_stdin {
args: "fmt -",
input: Some("const a = 1\n"),
output_str: Some("const a = 1;\n"),
});
itest!(fmt_stdin_markdown {
args: "fmt --ext=md -",
input: Some("# Hello Markdown\n```ts\nconsole.log( \"text\")\n```\n"),
output_str: Some("# Hello Markdown\n\n```ts\nconsole.log(\"text\");\n```\n"),
});
itest!(fmt_stdin_json {
args: "fmt --ext=json -",
input: Some("{ \"key\": \"value\"}"),
output_str: Some("{ \"key\": \"value\" }\n"),
});
itest!(fmt_stdin_check_formatted {
args: "fmt --check -",
input: Some("const a = 1;\n"),
output_str: Some(""),
});
itest!(fmt_stdin_check_not_formatted {
args: "fmt --check -",
input: Some("const a = 1\n"),
output_str: Some("Not formatted stdin\n"),
});

View file

@ -0,0 +1,113 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use crate::itest;
use tempfile::TempDir;
use test_util as util;
#[test]
fn info_with_compiled_source() {
let _g = util::http_server();
let module_path = "http://127.0.0.1:4545/cli/tests/048_media_types_jsx.ts";
let t = TempDir::new().expect("tempdir fail");
let mut deno = util::deno_cmd()
.env("DENO_DIR", t.path())
.current_dir(util::root_path())
.arg("cache")
.arg(&module_path)
.spawn()
.expect("failed to spawn script");
let status = deno.wait().expect("failed to wait for the child process");
assert!(status.success());
let output = util::deno_cmd()
.env("DENO_DIR", t.path())
.env("NO_COLOR", "1")
.current_dir(util::root_path())
.arg("info")
.arg(&module_path)
.output()
.expect("failed to spawn script");
let str_output = std::str::from_utf8(&output.stdout).unwrap().trim();
eprintln!("{}", str_output);
// check the output of the test.ts program.
assert!(str_output.contains("emit: "));
assert_eq!(output.stderr, b"");
}
itest!(_022_info_flag_script {
args: "info http://127.0.0.1:4545/cli/tests/019_media_types.ts",
output: "022_info_flag_script.out",
http_server: true,
});
itest!(_031_info_ts_error {
args: "info 031_info_ts_error.ts",
output: "031_info_ts_error.out",
});
itest!(_041_info_flag {
args: "info",
output: "041_info_flag.out",
});
itest!(_042_info_flag_location {
args: "info --location https://deno.land",
output: "041_info_flag_location.out",
});
itest!(info_json {
args: "info --json --unstable",
output: "info_json.out",
});
itest!(info_json_location {
args: "info --json --unstable --location https://deno.land",
output: "info_json_location.out",
});
itest!(_049_info_flag_script_jsx {
args: "info http://127.0.0.1:4545/cli/tests/048_media_types_jsx.ts",
output: "049_info_flag_script_jsx.out",
http_server: true,
});
itest!(_055_info_file_json {
args: "info --quiet --json --unstable 005_more_imports.ts",
output: "055_info_file_json.out",
exit_code: 0,
});
itest!(_065_import_map_info {
args:
"info --quiet --import-map=import_maps/import_map.json import_maps/test.ts",
output: "065_import_map_info.out",
});
itest!(_076_info_json_deps_order {
args: "info --unstable --json 076_info_json_deps_order.ts",
output: "076_info_json_deps_order.out",
});
itest!(info_missing_module {
args: "info error_009_missing_js_module.js",
output: "info_missing_module.out",
});
itest!(info_recursive_modules {
args: "info --quiet info_recursive_imports_test.ts",
output: "info_recursive_imports_test.out",
exit_code: 0,
});
itest!(info_type_import {
args: "info info_type_import.ts",
output: "info_type_import.out",
});
itest!(_054_info_local_imports {
args: "info --quiet 005_more_imports.ts",
output: "054_info_local_imports.out",
exit_code: 0,
});

View file

@ -0,0 +1,495 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use deno_core::futures;
use deno_core::futures::prelude::*;
use deno_core::serde_json;
use deno_core::url;
use deno_runtime::deno_fetch::reqwest;
use deno_runtime::deno_websocket::tokio_tungstenite;
use std::io::BufRead;
use test_util as util;
fn inspect_flag_with_unique_port(flag_prefix: &str) -> String {
use std::sync::atomic::{AtomicU16, Ordering};
static PORT: AtomicU16 = AtomicU16::new(9229);
let port = PORT.fetch_add(1, Ordering::Relaxed);
format!("{}=127.0.0.1:{}", flag_prefix, port)
}
fn extract_ws_url_from_stderr(
stderr_lines: &mut impl std::iter::Iterator<Item = String>,
) -> url::Url {
let stderr_first_line = stderr_lines.next().unwrap();
assert!(stderr_first_line.starts_with("Debugger listening on "));
let v: Vec<_> = stderr_first_line.match_indices("ws:").collect();
assert_eq!(v.len(), 1);
let ws_url_index = v[0].0;
let ws_url = &stderr_first_line[ws_url_index..];
url::Url::parse(ws_url).unwrap()
}
#[tokio::test]
async fn inspector_connect() {
let script = util::tests_path().join("inspector1.js");
let mut child = util::deno_cmd()
.arg("run")
.arg(inspect_flag_with_unique_port("--inspect"))
.arg(script)
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let stderr = child.stderr.as_mut().unwrap();
let mut stderr_lines =
std::io::BufReader::new(stderr).lines().map(|r| r.unwrap());
let ws_url = extract_ws_url_from_stderr(&mut stderr_lines);
// We use tokio_tungstenite as a websocket client because warp (which is
// a dependency of Deno) uses it.
let (_socket, response) = tokio_tungstenite::connect_async(ws_url)
.await
.expect("Can't connect");
assert_eq!("101 Switching Protocols", response.status().to_string());
child.kill().unwrap();
child.wait().unwrap();
}
#[derive(Debug)]
enum TestStep {
StdOut(&'static str),
StdErr(&'static str),
WsRecv(&'static str),
WsSend(&'static str),
}
#[tokio::test]
async fn inspector_break_on_first_line() {
let script = util::tests_path().join("inspector2.js");
let mut child = util::deno_cmd()
.arg("run")
.arg(inspect_flag_with_unique_port("--inspect-brk"))
.arg(script)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let stderr = child.stderr.as_mut().unwrap();
let mut stderr_lines =
std::io::BufReader::new(stderr).lines().map(|r| r.unwrap());
let ws_url = extract_ws_url_from_stderr(&mut stderr_lines);
let (socket, response) = tokio_tungstenite::connect_async(ws_url)
.await
.expect("Can't connect");
assert_eq!(response.status(), 101); // Switching protocols.
let (mut socket_tx, socket_rx) = socket.split();
let mut socket_rx =
socket_rx.map(|msg| msg.unwrap().to_string()).filter(|msg| {
let pass = !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#);
futures::future::ready(pass)
});
let stdout = child.stdout.as_mut().unwrap();
let mut stdout_lines =
std::io::BufReader::new(stdout).lines().map(|r| r.unwrap());
use TestStep::*;
let test_steps = vec![
WsSend(r#"{"id":1,"method":"Runtime.enable"}"#),
WsSend(r#"{"id":2,"method":"Debugger.enable"}"#),
WsRecv(
r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#,
),
WsRecv(r#"{"id":1,"result":{}}"#),
WsRecv(r#"{"id":2,"result":{"debuggerId":"#),
WsSend(r#"{"id":3,"method":"Runtime.runIfWaitingForDebugger"}"#),
WsRecv(r#"{"id":3,"result":{}}"#),
WsRecv(r#"{"method":"Debugger.paused","#),
WsSend(
r#"{"id":4,"method":"Runtime.evaluate","params":{"expression":"Deno.core.print(\"hello from the inspector\\n\")","contextId":1,"includeCommandLineAPI":true,"silent":false,"returnByValue":true}}"#,
),
WsRecv(r#"{"id":4,"result":{"result":{"type":"undefined"}}}"#),
StdOut("hello from the inspector"),
WsSend(r#"{"id":5,"method":"Debugger.resume"}"#),
WsRecv(r#"{"id":5,"result":{}}"#),
StdOut("hello from the script"),
];
for step in test_steps {
match step {
StdOut(s) => assert_eq!(&stdout_lines.next().unwrap(), s),
WsRecv(s) => assert!(socket_rx.next().await.unwrap().starts_with(s)),
WsSend(s) => socket_tx.send(s.into()).await.unwrap(),
_ => unreachable!(),
}
}
child.kill().unwrap();
child.wait().unwrap();
}
#[tokio::test]
async fn inspector_pause() {
let script = util::tests_path().join("inspector1.js");
let mut child = util::deno_cmd()
.arg("run")
.arg(inspect_flag_with_unique_port("--inspect"))
.arg(script)
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let stderr = child.stderr.as_mut().unwrap();
let mut stderr_lines =
std::io::BufReader::new(stderr).lines().map(|r| r.unwrap());
let ws_url = extract_ws_url_from_stderr(&mut stderr_lines);
// We use tokio_tungstenite as a websocket client because warp (which is
// a dependency of Deno) uses it.
let (mut socket, _) = tokio_tungstenite::connect_async(ws_url)
.await
.expect("Can't connect");
/// Returns the next websocket message as a string ignoring
/// Debugger.scriptParsed messages.
async fn ws_read_msg(
socket: &mut tokio_tungstenite::WebSocketStream<
tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
>,
) -> String {
use deno_core::futures::stream::StreamExt;
while let Some(msg) = socket.next().await {
let msg = msg.unwrap().to_string();
// FIXME(bartlomieju): fails because there's a file loaded
// called 150_errors.js
// assert!(!msg.contains("error"));
if !msg.contains("Debugger.scriptParsed") {
return msg;
}
}
unreachable!()
}
socket
.send(r#"{"id":6,"method":"Debugger.enable"}"#.into())
.await
.unwrap();
let msg = ws_read_msg(&mut socket).await;
println!("response msg 1 {}", msg);
assert!(msg.starts_with(r#"{"id":6,"result":{"debuggerId":"#));
socket
.send(r#"{"id":31,"method":"Debugger.pause"}"#.into())
.await
.unwrap();
let msg = ws_read_msg(&mut socket).await;
println!("response msg 2 {}", msg);
assert_eq!(msg, r#"{"id":31,"result":{}}"#);
child.kill().unwrap();
}
#[tokio::test]
async fn inspector_port_collision() {
// Skip this test on WSL, which allows multiple processes to listen on the
// same port, rather than making `bind()` fail with `EADDRINUSE`.
if cfg!(target_os = "linux") && std::env::var_os("WSL_DISTRO_NAME").is_some()
{
return;
}
let script = util::tests_path().join("inspector1.js");
let inspect_flag = inspect_flag_with_unique_port("--inspect");
let mut child1 = util::deno_cmd()
.arg("run")
.arg(&inspect_flag)
.arg(script.clone())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let stderr_1 = child1.stderr.as_mut().unwrap();
let mut stderr_1_lines = std::io::BufReader::new(stderr_1)
.lines()
.map(|r| r.unwrap());
let _ = extract_ws_url_from_stderr(&mut stderr_1_lines);
let mut child2 = util::deno_cmd()
.arg("run")
.arg(&inspect_flag)
.arg(script)
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let stderr_2 = child2.stderr.as_mut().unwrap();
let stderr_2_error_message = std::io::BufReader::new(stderr_2)
.lines()
.map(|r| r.unwrap())
.inspect(|line| assert!(!line.contains("Debugger listening")))
.find(|line| line.contains("Cannot start inspector server"));
assert!(stderr_2_error_message.is_some());
child1.kill().unwrap();
child1.wait().unwrap();
child2.wait().unwrap();
}
#[tokio::test]
async fn inspector_does_not_hang() {
let script = util::tests_path().join("inspector3.js");
let mut child = util::deno_cmd()
.arg("run")
.arg(inspect_flag_with_unique_port("--inspect-brk"))
.env("NO_COLOR", "1")
.arg(script)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let stderr = child.stderr.as_mut().unwrap();
let mut stderr_lines =
std::io::BufReader::new(stderr).lines().map(|r| r.unwrap());
let ws_url = extract_ws_url_from_stderr(&mut stderr_lines);
let (socket, response) = tokio_tungstenite::connect_async(ws_url)
.await
.expect("Can't connect");
assert_eq!(response.status(), 101); // Switching protocols.
let (mut socket_tx, socket_rx) = socket.split();
let mut socket_rx =
socket_rx.map(|msg| msg.unwrap().to_string()).filter(|msg| {
let pass = !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#);
futures::future::ready(pass)
});
let stdout = child.stdout.as_mut().unwrap();
let mut stdout_lines =
std::io::BufReader::new(stdout).lines().map(|r| r.unwrap());
use TestStep::*;
let test_steps = vec![
WsSend(r#"{"id":1,"method":"Runtime.enable"}"#),
WsSend(r#"{"id":2,"method":"Debugger.enable"}"#),
WsRecv(
r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#,
),
WsRecv(r#"{"id":1,"result":{}}"#),
WsRecv(r#"{"id":2,"result":{"debuggerId":"#),
WsSend(r#"{"id":3,"method":"Runtime.runIfWaitingForDebugger"}"#),
WsRecv(r#"{"id":3,"result":{}}"#),
WsRecv(r#"{"method":"Debugger.paused","#),
WsSend(r#"{"id":4,"method":"Debugger.resume"}"#),
WsRecv(r#"{"id":4,"result":{}}"#),
WsRecv(r#"{"method":"Debugger.resumed","params":{}}"#),
];
for step in test_steps {
match step {
WsRecv(s) => assert!(socket_rx.next().await.unwrap().starts_with(s)),
WsSend(s) => socket_tx.send(s.into()).await.unwrap(),
_ => unreachable!(),
}
}
for i in 0..128u32 {
let request_id = i + 10;
// Expect the number {i} on stdout.
let s = i.to_string();
assert_eq!(stdout_lines.next().unwrap(), s);
// Expect console.log
let s = r#"{"method":"Runtime.consoleAPICalled","#;
assert!(socket_rx.next().await.unwrap().starts_with(s));
// Expect hitting the `debugger` statement.
let s = r#"{"method":"Debugger.paused","#;
assert!(socket_rx.next().await.unwrap().starts_with(s));
// Send the 'Debugger.resume' request.
let s = format!(r#"{{"id":{},"method":"Debugger.resume"}}"#, request_id);
socket_tx.send(s.into()).await.unwrap();
// Expect confirmation of the 'Debugger.resume' request.
let s = format!(r#"{{"id":{},"result":{{}}}}"#, request_id);
assert_eq!(socket_rx.next().await.unwrap(), s);
let s = r#"{"method":"Debugger.resumed","params":{}}"#;
assert_eq!(socket_rx.next().await.unwrap(), s);
}
// Check that we can gracefully close the websocket connection.
socket_tx.close().await.unwrap();
socket_rx.for_each(|_| async {}).await;
assert_eq!(&stdout_lines.next().unwrap(), "done");
assert!(child.wait().unwrap().success());
}
#[tokio::test]
async fn inspector_without_brk_runs_code() {
let script = util::tests_path().join("inspector4.js");
let mut child = util::deno_cmd()
.arg("run")
.arg(inspect_flag_with_unique_port("--inspect"))
.arg(script)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let stderr = child.stderr.as_mut().unwrap();
let mut stderr_lines =
std::io::BufReader::new(stderr).lines().map(|r| r.unwrap());
let _ = extract_ws_url_from_stderr(&mut stderr_lines);
// Check that inspector actually runs code without waiting for inspector
// connection.
let stdout = child.stdout.as_mut().unwrap();
let mut stdout_lines =
std::io::BufReader::new(stdout).lines().map(|r| r.unwrap());
let stdout_first_line = stdout_lines.next().unwrap();
assert_eq!(stdout_first_line, "hello");
child.kill().unwrap();
child.wait().unwrap();
}
#[tokio::test]
async fn inspector_runtime_evaluate_does_not_crash() {
let mut child = util::deno_cmd()
.arg("repl")
.arg(inspect_flag_with_unique_port("--inspect"))
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let stderr = child.stderr.as_mut().unwrap();
let mut stderr_lines = std::io::BufReader::new(stderr)
.lines()
.map(|r| r.unwrap())
.filter(|s| s.as_str() != "Debugger session started.");
let ws_url = extract_ws_url_from_stderr(&mut stderr_lines);
let (socket, response) = tokio_tungstenite::connect_async(ws_url)
.await
.expect("Can't connect");
assert_eq!(response.status(), 101); // Switching protocols.
let (mut socket_tx, socket_rx) = socket.split();
let mut socket_rx =
socket_rx.map(|msg| msg.unwrap().to_string()).filter(|msg| {
let pass = !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#);
futures::future::ready(pass)
});
let stdin = child.stdin.take().unwrap();
let stdout = child.stdout.as_mut().unwrap();
let mut stdout_lines = std::io::BufReader::new(stdout)
.lines()
.map(|r| r.unwrap())
.filter(|s| !s.starts_with("Deno "));
use TestStep::*;
let test_steps = vec![
WsSend(r#"{"id":1,"method":"Runtime.enable"}"#),
WsSend(r#"{"id":2,"method":"Debugger.enable"}"#),
WsRecv(
r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#,
),
WsRecv(r#"{"id":1,"result":{}}"#),
WsRecv(r#"{"id":2,"result":{"debuggerId":"#),
WsSend(r#"{"id":3,"method":"Runtime.runIfWaitingForDebugger"}"#),
WsRecv(r#"{"id":3,"result":{}}"#),
StdOut("exit using ctrl+d or close()"),
WsSend(
r#"{"id":4,"method":"Runtime.compileScript","params":{"expression":"Deno.cwd()","sourceURL":"","persistScript":false,"executionContextId":1}}"#,
),
WsRecv(r#"{"id":4,"result":{}}"#),
WsSend(
r#"{"id":5,"method":"Runtime.evaluate","params":{"expression":"Deno.cwd()","objectGroup":"console","includeCommandLineAPI":true,"silent":false,"contextId":1,"returnByValue":true,"generatePreview":true,"userGesture":true,"awaitPromise":false,"replMode":true}}"#,
),
WsRecv(r#"{"id":5,"result":{"result":{"type":"string","value":""#),
WsSend(
r#"{"id":6,"method":"Runtime.evaluate","params":{"expression":"console.error('done');","objectGroup":"console","includeCommandLineAPI":true,"silent":false,"contextId":1,"returnByValue":true,"generatePreview":true,"userGesture":true,"awaitPromise":false,"replMode":true}}"#,
),
WsRecv(r#"{"method":"Runtime.consoleAPICalled"#),
WsRecv(r#"{"id":6,"result":{"result":{"type":"undefined"}}}"#),
StdErr("done"),
];
for step in test_steps {
match step {
StdOut(s) => assert_eq!(&stdout_lines.next().unwrap(), s),
StdErr(s) => assert_eq!(&stderr_lines.next().unwrap(), s),
WsRecv(s) => assert!(socket_rx.next().await.unwrap().starts_with(s)),
WsSend(s) => socket_tx.send(s.into()).await.unwrap(),
}
}
drop(stdin);
child.wait().unwrap();
}
#[tokio::test]
async fn inspector_json() {
let script = util::tests_path().join("inspector1.js");
let mut child = util::deno_cmd()
.arg("run")
.arg(inspect_flag_with_unique_port("--inspect"))
.arg(script)
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let stderr = child.stderr.as_mut().unwrap();
let mut stderr_lines =
std::io::BufReader::new(stderr).lines().map(|r| r.unwrap());
let ws_url = extract_ws_url_from_stderr(&mut stderr_lines);
let mut url = ws_url.clone();
let _ = url.set_scheme("http");
url.set_path("/json");
let resp = reqwest::get(url).await.unwrap();
assert_eq!(resp.status(), reqwest::StatusCode::OK);
let endpoint_list: Vec<deno_core::serde_json::Value> =
serde_json::from_str(&resp.text().await.unwrap()).unwrap();
let matching_endpoint = endpoint_list
.iter()
.find(|e| e["webSocketDebuggerUrl"] == ws_url.as_str());
assert!(matching_endpoint.is_some());
child.kill().unwrap();
}
#[tokio::test]
async fn inspector_json_list() {
let script = util::tests_path().join("inspector1.js");
let mut child = util::deno_cmd()
.arg("run")
.arg(inspect_flag_with_unique_port("--inspect"))
.arg(script)
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let stderr = child.stderr.as_mut().unwrap();
let mut stderr_lines =
std::io::BufReader::new(stderr).lines().map(|r| r.unwrap());
let ws_url = extract_ws_url_from_stderr(&mut stderr_lines);
let mut url = ws_url.clone();
let _ = url.set_scheme("http");
url.set_path("/json/list");
let resp = reqwest::get(url).await.unwrap();
assert_eq!(resp.status(), reqwest::StatusCode::OK);
let endpoint_list: Vec<deno_core::serde_json::Value> =
serde_json::from_str(&resp.text().await.unwrap()).unwrap();
let matching_endpoint = endpoint_list
.iter()
.find(|e| e["webSocketDebuggerUrl"] == ws_url.as_str());
assert!(matching_endpoint.is_some());
child.kill().unwrap();
}

View file

@ -0,0 +1,78 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use std::process::Command;
use tempfile::TempDir;
use test_util as util;
#[test]
fn installer_test_local_module_run() {
let temp_dir = TempDir::new().expect("tempdir fail");
let bin_dir = temp_dir.path().join("bin");
std::fs::create_dir(&bin_dir).unwrap();
let status = util::deno_cmd()
.current_dir(util::root_path())
.arg("install")
.arg("--name")
.arg("echo_test")
.arg("--root")
.arg(temp_dir.path())
.arg(util::tests_path().join("echo.ts"))
.arg("hello")
.spawn()
.unwrap()
.wait()
.unwrap();
assert!(status.success());
let mut file_path = bin_dir.join("echo_test");
if cfg!(windows) {
file_path = file_path.with_extension("cmd");
}
assert!(file_path.exists());
// NOTE: using file_path here instead of exec_name, because tests
// shouldn't mess with user's PATH env variable
let output = Command::new(file_path)
.current_dir(temp_dir.path())
.arg("foo")
.env("PATH", util::target_dir())
.output()
.expect("failed to spawn script");
let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim();
assert!(stdout_str.ends_with("hello, foo"));
}
#[test]
fn installer_test_remote_module_run() {
let _g = util::http_server();
let temp_dir = TempDir::new().expect("tempdir fail");
let bin_dir = temp_dir.path().join("bin");
std::fs::create_dir(&bin_dir).unwrap();
let status = util::deno_cmd()
.current_dir(util::root_path())
.arg("install")
.arg("--name")
.arg("echo_test")
.arg("--root")
.arg(temp_dir.path())
.arg("http://localhost:4545/cli/tests/echo.ts")
.arg("hello")
.spawn()
.unwrap()
.wait()
.unwrap();
assert!(status.success());
let mut file_path = bin_dir.join("echo_test");
if cfg!(windows) {
file_path = file_path.with_extension("cmd");
}
assert!(file_path.exists());
let output = Command::new(file_path)
.current_dir(temp_dir.path())
.arg("foo")
.env("PATH", util::target_dir())
.output()
.expect("failed to spawn script");
assert!(std::str::from_utf8(&output.stdout)
.unwrap()
.trim()
.ends_with("hello, foo"));
}

View file

@ -0,0 +1,82 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use crate::itest;
use test_util as util;
#[test]
fn ignore_unexplicit_files() {
let output = util::deno_cmd()
.current_dir(util::root_path())
.env("NO_COLOR", "1")
.arg("lint")
.arg("--unstable")
.arg("--ignore=./")
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()
.unwrap();
assert!(!output.status.success());
assert_eq!(
String::from_utf8_lossy(&output.stderr),
"error: No target files found.\n"
);
}
itest!(all {
args: "lint --unstable lint/file1.js lint/file2.ts lint/ignored_file.ts",
output: "lint/expected.out",
exit_code: 1,
});
itest!(quiet {
args: "lint --unstable --quiet lint/file1.js",
output: "lint/expected_quiet.out",
exit_code: 1,
});
itest!(json {
args:
"lint --unstable --json lint/file1.js lint/file2.ts lint/ignored_file.ts lint/malformed.js",
output: "lint/expected_json.out",
exit_code: 1,
});
itest!(ignore {
args: "lint --unstable --ignore=lint/file1.js,lint/malformed.js lint/",
output: "lint/expected_ignore.out",
exit_code: 1,
});
itest!(glob {
args: "lint --unstable --ignore=lint/malformed.js lint/",
output: "lint/expected_glob.out",
exit_code: 1,
});
itest!(stdin {
args: "lint --unstable -",
input: Some("let _a: any;"),
output: "lint/expected_from_stdin.out",
exit_code: 1,
});
itest!(stdin_json {
args: "lint --unstable --json -",
input: Some("let _a: any;"),
output: "lint/expected_from_stdin_json.out",
exit_code: 1,
});
itest!(rules {
args: "lint --unstable --rules",
output: "lint/expected_rules.out",
exit_code: 0,
});
// Make sure that the rules are printed if quiet option is enabled.
itest!(rules_quiet {
args: "lint --unstable --rules -q",
output: "lint/expected_rules.out",
exit_code: 0,
});

1092
cli/tests/integration/mod.rs Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,98 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use crate::itest;
use test_util as util;
#[test]
fn no_color() {
let (out, _) = util::run_and_collect_output(
false,
"test test/deno_test_no_color.ts",
None,
Some(vec![("NO_COLOR".to_owned(), "true".to_owned())]),
false,
);
// ANSI escape codes should be stripped.
assert!(out.contains("test success ... ok"));
assert!(out.contains("test fail ... FAILED"));
assert!(out.contains("test ignored ... ignored"));
assert!(out.contains("test result: FAILED. 1 passed; 1 failed; 1 ignored; 0 measured; 0 filtered out"));
}
itest!(all {
args: "test test/test_runner_test.ts",
exit_code: 1,
output: "test/deno_test.out",
});
itest!(doc {
args: "test --doc --allow-all test/doc.ts",
exit_code: 1,
output: "test/doc.out",
});
itest!(allow_all {
args: "test --unstable --allow-all test/allow_all.ts",
exit_code: 0,
output: "test/allow_all.out",
});
itest!(allow_none {
args: "test --unstable test/allow_none.ts",
exit_code: 1,
output: "test/allow_none.out",
});
itest!(fail_fast {
args: "test --fail-fast test/test_runner_test.ts",
exit_code: 1,
output: "test/deno_test_fail_fast.out",
});
itest!(only {
args: "test test/deno_test_only.ts",
exit_code: 1,
output: "test/deno_test_only.ts.out",
});
itest!(no_check {
args: "test --no-check test/test_runner_test.ts",
exit_code: 1,
output: "test/deno_test.out",
});
itest!(finally_cleartimeout {
args: "test test/test_finally_cleartimeout.ts",
exit_code: 1,
output: "test/test_finally_cleartimeout.out",
});
itest!(unresolved_promise {
args: "test test/test_unresolved_promise.js",
exit_code: 1,
output: "test/deno_test_unresolved_promise.out",
});
itest!(unhandled_rejection {
args: "test test/unhandled_rejection.ts",
exit_code: 1,
output: "test/unhandled_rejection.out",
});
itest!(exit_sanitizer {
args: "test test/exit_sanitizer_test.ts",
output: "test/exit_sanitizer_test.out",
exit_code: 1,
});
itest!(quiet {
args: "test --quiet test/quiet_test.ts",
exit_code: 0,
output: "test/quiet_test.out",
});
itest!(_067_test_no_run_type_error {
args: "test --unstable --no-run test_type_error",
output: "067_test_no_run_type_error.out",
exit_code: 1,
});

View file

@ -0,0 +1,145 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use std::process::Command;
use tempfile::TempDir;
use test_util as util;
// Warning: this test requires internet access.
// TODO(#7412): reenable. test is flaky
#[test]
#[ignore]
fn upgrade_in_tmpdir() {
let temp_dir = TempDir::new().unwrap();
let exe_path = temp_dir.path().join("deno");
let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap();
assert!(exe_path.exists());
let _mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap();
let status = Command::new(&exe_path)
.arg("upgrade")
.arg("--force")
.spawn()
.unwrap()
.wait()
.unwrap();
assert!(status.success());
let _mtime2 = std::fs::metadata(&exe_path).unwrap().modified().unwrap();
// TODO(ry) assert!(mtime1 < mtime2);
}
// Warning: this test requires internet access.
// TODO(#7412): reenable. test is flaky
#[test]
#[ignore]
fn upgrade_with_space_in_path() {
let temp_dir = tempfile::Builder::new()
.prefix("directory with spaces")
.tempdir()
.unwrap();
let exe_path = temp_dir.path().join("deno");
let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap();
assert!(exe_path.exists());
let status = Command::new(&exe_path)
.arg("upgrade")
.arg("--force")
.env("TMP", temp_dir.path())
.spawn()
.unwrap()
.wait()
.unwrap();
assert!(status.success());
}
// Warning: this test requires internet access.
// TODO(#7412): reenable. test is flaky
#[test]
#[ignore]
fn upgrade_with_version_in_tmpdir() {
let temp_dir = TempDir::new().unwrap();
let exe_path = temp_dir.path().join("deno");
let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap();
assert!(exe_path.exists());
let _mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap();
let status = Command::new(&exe_path)
.arg("upgrade")
.arg("--force")
.arg("--version")
.arg("0.42.0")
.spawn()
.unwrap()
.wait()
.unwrap();
assert!(status.success());
let upgraded_deno_version = String::from_utf8(
Command::new(&exe_path).arg("-V").output().unwrap().stdout,
)
.unwrap();
assert!(upgraded_deno_version.contains("0.42.0"));
let _mtime2 = std::fs::metadata(&exe_path).unwrap().modified().unwrap();
// TODO(ry) assert!(mtime1 < mtime2);
}
// Warning: this test requires internet access.
// TODO(#7412): reenable. test is flaky
#[test]
#[ignore]
fn upgrade_with_canary_in_tmpdir() {
let temp_dir = TempDir::new().unwrap();
let exe_path = temp_dir.path().join("deno");
let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap();
assert!(exe_path.exists());
let _mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap();
let status = Command::new(&exe_path)
.arg("upgrade")
.arg("--canary")
.arg("--version")
.arg("e6685f0f01b8a11a5eaff020f5babcfde76b3038")
.spawn()
.unwrap()
.wait()
.unwrap();
assert!(status.success());
let upgraded_deno_version = String::from_utf8(
Command::new(&exe_path).arg("-V").output().unwrap().stdout,
)
.unwrap();
assert!(upgraded_deno_version.contains("e6685f0"));
let _mtime2 = std::fs::metadata(&exe_path).unwrap().modified().unwrap();
// TODO(ry) assert!(mtime1 < mtime2);
}
// Warning: this test requires internet access.
// TODO(#7412): reenable. test is flaky
#[test]
#[ignore]
fn upgrade_with_out_in_tmpdir() {
let temp_dir = TempDir::new().unwrap();
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();
assert!(exe_path.exists());
let mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap();
let status = Command::new(&exe_path)
.arg("upgrade")
.arg("--version")
.arg("1.0.2")
.arg("--output")
.arg(&new_exe_path.to_str().unwrap())
.spawn()
.unwrap()
.wait()
.unwrap();
assert!(status.success());
assert!(new_exe_path.exists());
let mtime2 = std::fs::metadata(&exe_path).unwrap().modified().unwrap();
assert_eq!(mtime1, mtime2); // Original exe_path was not changed.
let v = String::from_utf8(
Command::new(&new_exe_path)
.arg("-V")
.output()
.unwrap()
.stdout,
)
.unwrap();
assert!(v.contains("1.0.2"));
}

View file

@ -0,0 +1,597 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use std::io::BufRead;
use tempfile::TempDir;
use test_util as util;
// Helper function to skip watcher output that contains "Restarting"
// phrase.
fn skip_restarting_line(
mut stderr_lines: impl Iterator<Item = String>,
) -> String {
loop {
let msg = stderr_lines.next().unwrap();
if !msg.contains("Restarting") {
return msg;
}
}
}
/// Helper function to skip watcher output that doesn't contain
/// "{job_name} finished" phrase.
fn wait_for_process_finished(
job_name: &str,
stderr_lines: &mut impl Iterator<Item = String>,
) {
let phrase = format!("{} finished", job_name);
loop {
let msg = stderr_lines.next().unwrap();
if msg.contains(&phrase) {
break;
}
}
}
/// Helper function to skip watcher output that doesn't contain
/// "{job_name} failed" phrase.
fn wait_for_process_failed(
job_name: &str,
stderr_lines: &mut impl Iterator<Item = String>,
) {
let phrase = format!("{} failed", job_name);
loop {
let msg = stderr_lines.next().unwrap();
if msg.contains(&phrase) {
break;
}
}
}
#[test]
fn fmt_watch_test() {
let t = TempDir::new().expect("tempdir fail");
let fixed = util::root_path().join("cli/tests/badly_formatted_fixed.js");
let badly_formatted_original =
util::root_path().join("cli/tests/badly_formatted.mjs");
let badly_formatted = t.path().join("badly_formatted.js");
std::fs::copy(&badly_formatted_original, &badly_formatted)
.expect("Failed to copy file");
let mut child = util::deno_cmd()
.current_dir(util::root_path())
.arg("fmt")
.arg(&badly_formatted)
.arg("--watch")
.arg("--unstable")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("Failed to spawn script");
let stderr = child.stderr.as_mut().unwrap();
let stderr_lines =
std::io::BufReader::new(stderr).lines().map(|r| r.unwrap());
// TODO(lucacasonato): remove this timeout. It seems to be needed on Linux.
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(skip_restarting_line(stderr_lines).contains("badly_formatted.js"));
let expected = std::fs::read_to_string(fixed.clone()).unwrap();
let actual = std::fs::read_to_string(badly_formatted.clone()).unwrap();
assert_eq!(expected, actual);
// Change content of the file again to be badly formatted
std::fs::copy(&badly_formatted_original, &badly_formatted)
.expect("Failed to copy file");
std::thread::sleep(std::time::Duration::from_secs(1));
// Check if file has been automatically formatted by watcher
let expected = std::fs::read_to_string(fixed).unwrap();
let actual = std::fs::read_to_string(badly_formatted).unwrap();
assert_eq!(expected, actual);
// the watcher process is still alive
assert!(child.try_wait().unwrap().is_none());
child.kill().unwrap();
drop(t);
}
#[test]
fn bundle_js_watch() {
use std::path::PathBuf;
// Test strategy extends this of test bundle_js by adding watcher
let t = TempDir::new().expect("tempdir fail");
let file_to_watch = t.path().join("file_to_watch.js");
std::fs::write(&file_to_watch, "console.log('Hello world');")
.expect("error writing file");
assert!(file_to_watch.is_file());
let t = TempDir::new().expect("tempdir fail");
let bundle = t.path().join("mod6.bundle.js");
let mut deno = util::deno_cmd()
.current_dir(util::root_path())
.arg("bundle")
.arg(&file_to_watch)
.arg(&bundle)
.arg("--watch")
.arg("--unstable")
.env("NO_COLOR", "1")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("failed to spawn script");
let stderr = deno.stderr.as_mut().unwrap();
let mut stderr_lines =
std::io::BufReader::new(stderr).lines().map(|r| r.unwrap());
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(stderr_lines.next().unwrap().contains("file_to_watch.js"));
assert!(stderr_lines.next().unwrap().contains("mod6.bundle.js"));
let file = PathBuf::from(&bundle);
assert!(file.is_file());
wait_for_process_finished("Bundle", &mut stderr_lines);
std::fs::write(&file_to_watch, "console.log('Hello world2');")
.expect("error writing file");
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(stderr_lines
.next()
.unwrap()
.contains("File change detected!"));
assert!(stderr_lines.next().unwrap().contains("file_to_watch.js"));
assert!(stderr_lines.next().unwrap().contains("mod6.bundle.js"));
let file = PathBuf::from(&bundle);
assert!(file.is_file());
wait_for_process_finished("Bundle", &mut stderr_lines);
// Confirm that the watcher keeps on working even if the file is updated and has invalid syntax
std::fs::write(&file_to_watch, "syntax error ^^")
.expect("error writing file");
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(stderr_lines
.next()
.unwrap()
.contains("File change detected!"));
assert!(stderr_lines.next().unwrap().contains("error: "));
wait_for_process_failed("Bundle", &mut stderr_lines);
// the watcher process is still alive
assert!(deno.try_wait().unwrap().is_none());
deno.kill().unwrap();
drop(t);
}
/// Confirm that the watcher continues to work even if module resolution fails at the *first* attempt
#[test]
fn bundle_watch_not_exit() {
let t = TempDir::new().expect("tempdir fail");
let file_to_watch = t.path().join("file_to_watch.js");
std::fs::write(&file_to_watch, "syntax error ^^")
.expect("error writing file");
let target_file = t.path().join("target.js");
let mut deno = util::deno_cmd()
.current_dir(util::root_path())
.arg("bundle")
.arg(&file_to_watch)
.arg(&target_file)
.arg("--watch")
.arg("--unstable")
.env("NO_COLOR", "1")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("failed to spawn script");
let stderr = deno.stderr.as_mut().unwrap();
let mut stderr_lines =
std::io::BufReader::new(stderr).lines().map(|r| r.unwrap());
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(stderr_lines.next().unwrap().contains("error:"));
assert!(stderr_lines.next().unwrap().contains("Bundle failed"));
// the target file hasn't been created yet
assert!(!target_file.is_file());
// Make sure the watcher actually restarts and works fine with the proper syntax
std::fs::write(&file_to_watch, "console.log(42);")
.expect("error writing file");
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(stderr_lines
.next()
.unwrap()
.contains("File change detected!"));
assert!(stderr_lines.next().unwrap().contains("file_to_watch.js"));
assert!(stderr_lines.next().unwrap().contains("target.js"));
wait_for_process_finished("Bundle", &mut stderr_lines);
// bundled file is created
assert!(target_file.is_file());
// the watcher process is still alive
assert!(deno.try_wait().unwrap().is_none());
deno.kill().unwrap();
drop(t);
}
#[test]
fn run_watch() {
let t = TempDir::new().expect("tempdir fail");
let file_to_watch = t.path().join("file_to_watch.js");
std::fs::write(&file_to_watch, "console.log('Hello world');")
.expect("error writing file");
let mut child = util::deno_cmd()
.current_dir(util::root_path())
.arg("run")
.arg("--watch")
.arg("--unstable")
.arg(&file_to_watch)
.env("NO_COLOR", "1")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("failed to spawn script");
let stdout = child.stdout.as_mut().unwrap();
let mut stdout_lines =
std::io::BufReader::new(stdout).lines().map(|r| r.unwrap());
let stderr = child.stderr.as_mut().unwrap();
let mut stderr_lines =
std::io::BufReader::new(stderr).lines().map(|r| r.unwrap());
assert!(stdout_lines.next().unwrap().contains("Hello world"));
wait_for_process_finished("Process", &mut stderr_lines);
// TODO(lucacasonato): remove this timeout. It seems to be needed on Linux.
std::thread::sleep(std::time::Duration::from_secs(1));
// Change content of the file
std::fs::write(&file_to_watch, "console.log('Hello world2');")
.expect("error writing file");
// Events from the file watcher is "debounced", so we need to wait for the next execution to start
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(stderr_lines.next().unwrap().contains("Restarting"));
assert!(stdout_lines.next().unwrap().contains("Hello world2"));
wait_for_process_finished("Process", &mut stderr_lines);
// Add dependency
let another_file = t.path().join("another_file.js");
std::fs::write(&another_file, "export const foo = 0;")
.expect("error writing file");
std::fs::write(
&file_to_watch,
"import { foo } from './another_file.js'; console.log(foo);",
)
.expect("error writing file");
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(stderr_lines.next().unwrap().contains("Restarting"));
assert!(stdout_lines.next().unwrap().contains('0'));
wait_for_process_finished("Process", &mut stderr_lines);
// Confirm that restarting occurs when a new file is updated
std::fs::write(&another_file, "export const foo = 42;")
.expect("error writing file");
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(stderr_lines.next().unwrap().contains("Restarting"));
assert!(stdout_lines.next().unwrap().contains("42"));
wait_for_process_finished("Process", &mut stderr_lines);
// Confirm that the watcher keeps on working even if the file is updated and has invalid syntax
std::fs::write(&file_to_watch, "syntax error ^^")
.expect("error writing file");
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(stderr_lines.next().unwrap().contains("Restarting"));
assert!(stderr_lines.next().unwrap().contains("error:"));
wait_for_process_failed("Process", &mut stderr_lines);
// Then restore the file
std::fs::write(
&file_to_watch,
"import { foo } from './another_file.js'; console.log(foo);",
)
.expect("error writing file");
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(stderr_lines.next().unwrap().contains("Restarting"));
assert!(stdout_lines.next().unwrap().contains("42"));
wait_for_process_finished("Process", &mut stderr_lines);
// Update the content of the imported file with invalid syntax
std::fs::write(&another_file, "syntax error ^^").expect("error writing file");
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(stderr_lines.next().unwrap().contains("Restarting"));
assert!(stderr_lines.next().unwrap().contains("error:"));
wait_for_process_failed("Process", &mut stderr_lines);
// Modify the imported file and make sure that restarting occurs
std::fs::write(&another_file, "export const foo = 'modified!';")
.expect("error writing file");
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(stderr_lines.next().unwrap().contains("Restarting"));
assert!(stdout_lines.next().unwrap().contains("modified!"));
wait_for_process_finished("Process", &mut stderr_lines);
// the watcher process is still alive
assert!(child.try_wait().unwrap().is_none());
child.kill().unwrap();
drop(t);
}
/// Confirm that the watcher continues to work even if module resolution fails at the *first* attempt
#[test]
fn run_watch_not_exit() {
let t = TempDir::new().expect("tempdir fail");
let file_to_watch = t.path().join("file_to_watch.js");
std::fs::write(&file_to_watch, "syntax error ^^")
.expect("error writing file");
let mut child = util::deno_cmd()
.current_dir(util::root_path())
.arg("run")
.arg("--watch")
.arg("--unstable")
.arg(&file_to_watch)
.env("NO_COLOR", "1")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("failed to spawn script");
let stdout = child.stdout.as_mut().unwrap();
let mut stdout_lines =
std::io::BufReader::new(stdout).lines().map(|r| r.unwrap());
let stderr = child.stderr.as_mut().unwrap();
let mut stderr_lines =
std::io::BufReader::new(stderr).lines().map(|r| r.unwrap());
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(stderr_lines.next().unwrap().contains("error:"));
assert!(stderr_lines.next().unwrap().contains("Process failed"));
// Make sure the watcher actually restarts and works fine with the proper syntax
std::fs::write(&file_to_watch, "console.log(42);")
.expect("error writing file");
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(stderr_lines.next().unwrap().contains("Restarting"));
assert!(stdout_lines.next().unwrap().contains("42"));
wait_for_process_finished("Process", &mut stderr_lines);
// the watcher process is still alive
assert!(child.try_wait().unwrap().is_none());
child.kill().unwrap();
drop(t);
}
#[test]
fn run_watch_with_import_map_and_relative_paths() {
fn create_relative_tmp_file(
directory: &TempDir,
filename: &'static str,
filecontent: &'static str,
) -> std::path::PathBuf {
let absolute_path = directory.path().join(filename);
std::fs::write(&absolute_path, filecontent).expect("error writing file");
let relative_path = absolute_path
.strip_prefix(util::root_path())
.expect("unable to create relative temporary file")
.to_owned();
assert!(relative_path.is_relative());
relative_path
}
let temp_directory =
TempDir::new_in(util::root_path()).expect("tempdir fail");
let file_to_watch = create_relative_tmp_file(
&temp_directory,
"file_to_watch.js",
"console.log('Hello world');",
);
let import_map_path = create_relative_tmp_file(
&temp_directory,
"import_map.json",
"{\"imports\": {}}",
);
let mut child = util::deno_cmd()
.current_dir(util::root_path())
.arg("run")
.arg("--unstable")
.arg("--watch")
.arg("--import-map")
.arg(&import_map_path)
.arg(&file_to_watch)
.env("NO_COLOR", "1")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("failed to spawn script");
let stdout = child.stdout.as_mut().unwrap();
let mut stdout_lines =
std::io::BufReader::new(stdout).lines().map(|r| r.unwrap());
let stderr = child.stderr.as_mut().unwrap();
let mut stderr_lines =
std::io::BufReader::new(stderr).lines().map(|r| r.unwrap());
assert!(stderr_lines.next().unwrap().contains("Process finished"));
assert!(stdout_lines.next().unwrap().contains("Hello world"));
child.kill().unwrap();
drop(file_to_watch);
drop(import_map_path);
temp_directory.close().unwrap();
}
// TODO(bartlomieju): flaky (https://github.com/denoland/deno/issues/10552)
#[ignore]
#[test]
fn test_watch() {
macro_rules! assert_contains {
($string:expr, $($test:expr),+) => {
let string = $string; // This might be a function call or something
if !($(string.contains($test))||+) {
panic!("{:?} does not contain any of {:?}", string, [$($test),+]);
}
}
}
let t = TempDir::new().expect("tempdir fail");
let mut child = util::deno_cmd()
.current_dir(util::root_path())
.arg("test")
.arg("--watch")
.arg("--unstable")
.arg("--no-check")
.arg(&t.path())
.env("NO_COLOR", "1")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("failed to spawn script");
let stdout = child.stdout.as_mut().unwrap();
let mut stdout_lines =
std::io::BufReader::new(stdout).lines().map(|r| r.unwrap());
let stderr = child.stderr.as_mut().unwrap();
let mut stderr_lines =
std::io::BufReader::new(stderr).lines().map(|r| r.unwrap());
assert_contains!(
stdout_lines.next().unwrap(),
"No matching test modules found"
);
wait_for_process_finished("Test", &mut stderr_lines);
let foo_file = t.path().join("foo.js");
let bar_file = t.path().join("bar.js");
let foo_test = t.path().join("foo_test.js");
let bar_test = t.path().join("bar_test.js");
std::fs::write(&foo_file, "export default function foo() { 1 + 1 }")
.expect("error writing file");
std::fs::write(&bar_file, "export default function bar() { 2 + 2 }")
.expect("error writing file");
std::fs::write(
&foo_test,
"import foo from './foo.js'; Deno.test('foo', foo);",
)
.expect("error writing file");
std::fs::write(
&bar_test,
"import bar from './bar.js'; Deno.test('bar', bar);",
)
.expect("error writing file");
assert_contains!(stdout_lines.next().unwrap(), "running 1 test");
assert_contains!(stdout_lines.next().unwrap(), "foo", "bar");
assert_contains!(stdout_lines.next().unwrap(), "running 1 test");
assert_contains!(stdout_lines.next().unwrap(), "foo", "bar");
stdout_lines.next();
stdout_lines.next();
stdout_lines.next();
wait_for_process_finished("Test", &mut stderr_lines);
// Change content of the file
std::fs::write(
&foo_test,
"import foo from './foo.js'; Deno.test('foobar', foo);",
)
.expect("error writing file");
assert_contains!(stderr_lines.next().unwrap(), "Restarting");
assert_contains!(stdout_lines.next().unwrap(), "running 1 test");
assert_contains!(stdout_lines.next().unwrap(), "foobar");
stdout_lines.next();
stdout_lines.next();
stdout_lines.next();
wait_for_process_finished("Test", &mut stderr_lines);
// Add test
let another_test = t.path().join("new_test.js");
std::fs::write(&another_test, "Deno.test('another one', () => 3 + 3)")
.expect("error writing file");
assert_contains!(stderr_lines.next().unwrap(), "Restarting");
assert_contains!(stdout_lines.next().unwrap(), "running 1 test");
assert_contains!(stdout_lines.next().unwrap(), "another one");
stdout_lines.next();
stdout_lines.next();
stdout_lines.next();
wait_for_process_finished("Test", &mut stderr_lines);
// Confirm that restarting occurs when a new file is updated
std::fs::write(&another_test, "Deno.test('another one', () => 3 + 3); Deno.test('another another one', () => 4 + 4)")
.expect("error writing file");
assert_contains!(stderr_lines.next().unwrap(), "Restarting");
assert_contains!(stdout_lines.next().unwrap(), "running 2 tests");
assert_contains!(stdout_lines.next().unwrap(), "another one");
assert_contains!(stdout_lines.next().unwrap(), "another another one");
stdout_lines.next();
stdout_lines.next();
stdout_lines.next();
wait_for_process_finished("Test", &mut stderr_lines);
// Confirm that the watcher keeps on working even if the file is updated and has invalid syntax
std::fs::write(&another_test, "syntax error ^^").expect("error writing file");
assert_contains!(stderr_lines.next().unwrap(), "Restarting");
assert_contains!(stderr_lines.next().unwrap(), "error:");
assert_contains!(stderr_lines.next().unwrap(), "Test failed");
// Then restore the file
std::fs::write(&another_test, "Deno.test('another one', () => 3 + 3)")
.expect("error writing file");
assert_contains!(stderr_lines.next().unwrap(), "Restarting");
assert_contains!(stdout_lines.next().unwrap(), "running 1 test");
assert_contains!(stdout_lines.next().unwrap(), "another one");
stdout_lines.next();
stdout_lines.next();
stdout_lines.next();
wait_for_process_finished("Test", &mut stderr_lines);
// Confirm that the watcher keeps on working even if the file is updated and the test fails
// This also confirms that it restarts when dependencies change
std::fs::write(
&foo_file,
"export default function foo() { throw new Error('Whoops!'); }",
)
.expect("error writing file");
assert_contains!(stderr_lines.next().unwrap(), "Restarting");
assert_contains!(stdout_lines.next().unwrap(), "running 1 test");
assert_contains!(stdout_lines.next().unwrap(), "FAILED");
while !stdout_lines.next().unwrap().contains("test result") {}
stdout_lines.next();
wait_for_process_finished("Test", &mut stderr_lines);
// Then restore the file
std::fs::write(&foo_file, "export default function foo() { 1 + 1 }")
.expect("error writing file");
assert_contains!(stderr_lines.next().unwrap(), "Restarting");
assert_contains!(stdout_lines.next().unwrap(), "running 1 test");
assert_contains!(stdout_lines.next().unwrap(), "foo");
stdout_lines.next();
stdout_lines.next();
stdout_lines.next();
wait_for_process_finished("Test", &mut stderr_lines);
// Test that circular dependencies work fine
std::fs::write(
&foo_file,
"import './bar.js'; export default function foo() { 1 + 1 }",
)
.expect("error writing file");
std::fs::write(
&bar_file,
"import './foo.js'; export default function bar() { 2 + 2 }",
)
.expect("error writing file");
// the watcher process is still alive
assert!(child.try_wait().unwrap().is_none());
child.kill().unwrap();
drop(t);
}

View file

@ -0,0 +1,102 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use crate::itest;
use test_util as util;
#[test]
fn workers() {
let _g = util::http_server();
let status = util::deno_cmd()
.current_dir(util::tests_path())
.arg("test")
.arg("--reload")
.arg("--location")
.arg("http://127.0.0.1:4545/cli/tests/")
.arg("--allow-net")
.arg("--allow-read")
.arg("--unstable")
.arg("workers/test.ts")
.spawn()
.unwrap()
.wait()
.unwrap();
assert!(status.success());
}
itest!(worker_error {
args: "run -A workers/worker_error.ts",
output: "workers/worker_error.ts.out",
exit_code: 1,
});
itest!(worker_nested_error {
args: "run -A workers/worker_nested_error.ts",
output: "workers/worker_nested_error.ts.out",
exit_code: 1,
});
itest!(nonexistent_worker {
args: "run --allow-read workers/nonexistent_worker.ts",
output: "workers/nonexistent_worker.out",
exit_code: 1,
});
itest!(_084_worker_custom_inspect {
args: "run --allow-read 084_worker_custom_inspect.ts",
output: "084_worker_custom_inspect.ts.out",
});
itest!(error_worker_permissions_local {
args: "run --reload error_worker_permissions_local.ts",
output: "error_worker_permissions_local.ts.out",
exit_code: 1,
});
itest!(error_worker_permissions_remote {
args: "run --reload error_worker_permissions_remote.ts",
http_server: true,
output: "error_worker_permissions_remote.ts.out",
exit_code: 1,
});
itest!(worker_permissions_remote_remote {
args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_remote_remote.ts",
output: "workers/permissions_remote_remote.ts.out",
http_server: true,
exit_code: 1,
});
itest!(worker_permissions_dynamic_remote {
args: "run --quiet --reload --allow-net --unstable workers/permissions_dynamic_remote.ts",
output: "workers/permissions_dynamic_remote.ts.out",
http_server: true,
exit_code: 1,
});
itest!(worker_permissions_data_remote {
args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_data_remote.ts",
output: "workers/permissions_data_remote.ts.out",
http_server: true,
exit_code: 1,
});
itest!(worker_permissions_blob_remote {
args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_blob_remote.ts",
output: "workers/permissions_blob_remote.ts.out",
http_server: true,
exit_code: 1,
});
itest!(worker_permissions_data_local {
args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_data_local.ts",
output: "workers/permissions_data_local.ts.out",
http_server: true,
exit_code: 1,
});
itest!(worker_permissions_blob_local {
args: "run --quiet --reload --allow-net=localhost:4545 workers/permissions_blob_local.ts",
output: "workers/permissions_blob_local.ts.out",
http_server: true,
exit_code: 1,
});

File diff suppressed because it is too large Load diff