Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions system-map/tests/binary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ use std::process::{Command, Output};

use serde_json::Value;

use crate::common::{FILES, base, project};
use crate::common::{FILES, base, git_repo, project};

/// `check` with `args` run by the binary on the folder at `root`, made a real repository first.
fn run(root: &str, args: &[&str]) -> Output {
git_repo(root);
Command::new(env!("CARGO_BIN_EXE_system-map"))
.arg("check")
.args(args)
Expand Down Expand Up @@ -45,7 +47,6 @@ fn the_pass_line_counts_in_the_plural_links_by_kind_and_laws_by_backing() {
&["alpha/a.rs", "alpha/b.rs", "beta/b.rs", "docs/d.md"],
);
crate::common::write(dir.path(), "beta/b.rs", &format!("// @{}: held\n", "law"));
studio_test_support::git(dir.path(), &["commit", "-qam", "Tag"]);
let out = run(&root, &[]);
assert!(out.status.success(), "{out:?}");
assert_eq!(
Expand Down Expand Up @@ -96,8 +97,6 @@ fn json_lists_each_law_with_its_backing_and_its_tags_by_file_and_line() {
let (dir, root) = project(&map, &FILES);
let tag = format!("// @{}: stay-true\n", "law");
crate::common::write(dir.path(), "alpha/a.rs", &format!("fn a() {{}}\n{tag}"));
studio_test_support::git(dir.path(), &["add", "-A"]);
studio_test_support::git(dir.path(), &["commit", "-q", "-m", "Tag"]);
let out = run(&root, &["--json"]);
let value: Value = serde_json::from_slice(&out.stdout).unwrap();
assert_eq!(value["problems"].as_array().unwrap().len(), 0);
Expand Down
4 changes: 3 additions & 1 deletion system-map/tests/c.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
use serde_json::{Value, json};

use crate::common::{
assert_only_candidate_links_relaxed, extractor_map, pairs, repo, report, run, sites, write,
assert_only_candidate_links_relaxed, commit, extractor_map, pairs, repo, report, run, sites,
write,
};

/// A map naming `c-includes` that gives every tracked file but `ignored` ones its own part, so that a file pair is a
Expand Down Expand Up @@ -377,6 +378,7 @@ fn commit_mode_gives_the_pairs_of_the_working_tree() {
),
&files,
);
commit(&root);
let tree = run(&root, "check", &["--json"]);
let commit = run(&root, "check", &["--json", "--commit", "HEAD"]);
assert_eq!(
Expand Down
171 changes: 145 additions & 26 deletions system-map/tests/common.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,104 @@
//! Temporary git repositories with a map in them.
//! Temporary folders with a map in them. A folder is plain, with no git: the files a test tracks are listed here and
//! handed to `check_files`, and a file written but not tracked is one the list leaves out. A folder becomes a real git
//! repository, tracking the listed files, only where git or the binary reads it: `run`, `imports_json` and `commit`.

use std::{fs, path::Path, process::Command};
use std::{
collections::{BTreeMap, BTreeSet},
fs,
path::{Path, PathBuf},
process::Command,
sync::Mutex,
};

use serde_json::{Value, json};
use studio_test_support::git;

/// The files each folder tracks, by its real path.
static TRACKED: Mutex<BTreeMap<PathBuf, BTreeSet<String>>> = Mutex::new(BTreeMap::new());

/// The registry's key for the folder at `root`: its real path, however the test spells it.
fn key(root: &Path) -> PathBuf {
root.canonicalize().unwrap()
}

/// A new plain folder, and its real path.
pub(crate) fn folder() -> (tempfile::TempDir, String) {
let dir = tempfile::tempdir().unwrap();
let root = key(dir.path());
TRACKED
.lock()
.unwrap()
.insert(root.clone(), BTreeSet::new());
(dir, root.display().to_string())
}

/// Tracks `files` in the folder at `root`, as `git add` would.
pub(crate) fn track(root: &Path, files: &[&str]) {
TRACKED
.lock()
.unwrap()
.entry(key(root))
.or_default()
.extend(files.iter().map(ToString::to_string));
if root.join(".git").exists() && !files.is_empty() {
git(root, &[&["add", "--"], files].concat());
}
}

/// Tracks every file on disk in the folder at `root`, as `git add -A` would.
pub(crate) fn track_all(root: &Path) {
fn walk(dir: &Path, prefix: &str, found: &mut BTreeSet<String>) {
for entry in fs::read_dir(dir).unwrap() {
let entry = entry.unwrap();
let name = entry.file_name().to_string_lossy().into_owned();
let path = format!("{prefix}{name}");
if entry.file_type().unwrap().is_dir() {
if name != ".git" {
walk(&entry.path(), &format!("{path}/"), found);
}
} else {
found.insert(path);
}
}
}
let mut found = BTreeSet::new();
walk(root, "", &mut found);
TRACKED.lock().unwrap().insert(key(root), found);
if root.join(".git").exists() {
git(root, &["add", "-A"]);
}
}

/// The files the folder at `root` tracks.
fn tracked(root: &Path) -> Vec<String> {
let tracked = TRACKED.lock().unwrap();
tracked[&key(root)].iter().cloned().collect()
}

/// Makes the folder at `root` a git repository whose index holds its tracked files, with no commit: `git ls-files` reads
/// the index.
pub(crate) fn git_repo(root: &str) {
let root = Path::new(root);
if root.join(".git").exists() {
return;
}
git(root, &["init", "-q", "-b", "main"]);
let files = tracked(root);
if !files.is_empty() {
let files: Vec<&str> = files.iter().map(String::as_str).collect();
git(root, &[&["add", "--"], &files[..]].concat());
}
}

/// Commits the tracked files of the folder at `root`, making it a repository first: for a case that reads a commit.
pub(crate) fn commit(root: &str) {
git_repo(root);
git(
Path::new(root),
&["commit", "-q", "--allow-empty", "-m", "Files"],
);
}

/// A valid map: two parts, an actor, an import link (unproven, since the map names no extractor), an ignored folder and
/// a law.
pub(crate) fn base() -> Value {
Expand Down Expand Up @@ -43,19 +137,18 @@ pub(crate) fn base_v1() -> Value {
/// The files `base` places: one per part and one ignored.
pub(crate) const FILES: [&str; 3] = ["alpha/a.rs", "beta/b.rs", "docs/d.md"];

/// A repository that tracks `files` and `system-map.json` holding `map`, and its root.
/// A folder that tracks `files` and `system-map.json` holding `map`, and its root.
pub(crate) fn project(map: &Value, files: &[&str]) -> (tempfile::TempDir, String) {
project_text(&map.to_string(), files)
}

pub(crate) fn project_text(map: &str, files: &[&str]) -> (tempfile::TempDir, String) {
let (dir, root) = studio_test_support::repo();
let (dir, root) = folder();
write(dir.path(), "system-map.json", map);
for file in files {
write(dir.path(), file, "x\n");
}
git(dir.path(), &["add", "-A"]);
git(dir.path(), &["commit", "-q", "-m", "Files"]);
track(dir.path(), &[&["system-map.json"], files].concat());
(dir, root)
}

Expand All @@ -65,9 +158,9 @@ pub(crate) fn write(root: &Path, file: &str, text: &str) {
fs::write(path, text).unwrap();
}

/// The problems `check` reports for a repository.
/// The problems `check` reports for a folder.
pub(crate) fn problems(root: &str) -> Vec<String> {
system_map::check(Path::new(root)).problems
report(root).problems
}

/// Whether some problem mentions every one of `needles`.
Expand Down Expand Up @@ -102,20 +195,21 @@ pub(crate) fn extractor_map(
})
}

/// A repository holding `map` and `files` with their texts, committed.
/// A folder tracking `map` and `files` with their texts.
pub(crate) fn repo(map: &Value, files: &[(&str, &str)]) -> (tempfile::TempDir, String) {
let (dir, root) = project_text(&map.to_string(), &[]);
for (file, text) in files {
write(dir.path(), file, text);
}
git(dir.path(), &["add", "-A"]);
git(dir.path(), &["commit", "-q", "-m", "Code"]);
let names: Vec<&str> = files.iter().map(|(file, _)| *file).collect();
track(dir.path(), &names);
(dir, root)
}

/// What `check` reports for a repository.
/// What `check` reports for a folder, against its tracked files.
pub(crate) fn report(root: &str) -> system_map::Report {
system_map::check(Path::new(root))
let root = Path::new(root);
system_map::check_files(root, tracked(root))
}

/// Every file pair of the computed edges, as `from>to`.
Expand All @@ -127,8 +221,9 @@ pub(crate) fn pairs(report: &system_map::Report) -> Vec<String> {
.collect()
}

/// The `system-map` binary run as `command` with `args` on the repository at `root`.
/// The `system-map` binary run as `command` with `args` on the folder at `root`, made a repository first.
pub(crate) fn run(root: &str, command: &str, args: &[&str]) -> std::process::Output {
git_repo(root);
Command::new(env!("CARGO_BIN_EXE_system-map"))
.arg(command)
.args(args)
Expand All @@ -143,10 +238,15 @@ pub(crate) fn imports_json(root: &str) -> Value {
serde_json::from_slice(&out.stdout).unwrap()
}

/// Each file pair's import sites in `check --json` with `args`, as `from>to file:line`, sorted.
/// Each file pair's import sites in `check --json` with `args`, as `from>to file:line`, sorted: from the report itself
/// when there are no `args`, which is what `check --json` prints.
pub(crate) fn sites(root: &str, args: &[&str]) -> Vec<String> {
let out = run(root, "check", &[&["--json"], args].concat());
let value: Value = serde_json::from_slice(&out.stdout).unwrap();
let value: Value = if args.is_empty() {
serde_json::to_value(report(root)).unwrap()
} else {
let out = run(root, "check", &[&["--json"], args].concat());
serde_json::from_slice(&out.stdout).unwrap()
};
let mut found = Vec::new();
for edge in value["edges"].as_array().into_iter().flatten() {
for pair in edge["pairs"].as_array().unwrap() {
Expand All @@ -169,9 +269,9 @@ pub(crate) fn sites(root: &str, args: &[&str]) -> Vec<String> {
/// `to` with no dependency behind it: the links to the candidates of an unsure import pass as unproven, any other
/// link of the part still fails.
pub(crate) fn assert_only_candidate_links_relaxed(root: &str, note: &str, from: &str, to: &str) {
let out = run(root, "check", &[]);
assert_eq!(String::from_utf8_lossy(&out.stderr), note);
let problems = String::from_utf8_lossy(&out.stdout);
let (stdout, stderr) = printed(&report(root));
assert_eq!(stderr, note);
let problems = stdout;
assert_eq!(problems.lines().count(), 1, "{problems}");
let link = format!(
"import link \"{from}-{to}\" runs from \"{from}\" to \"{to}\", but the code shows no dependency"
Expand All @@ -185,11 +285,30 @@ pub(crate) fn assert_unsure_file_listed_and_link_unproven(root: &str, file: &str
let value = imports_json(root);
assert_eq!(value["unsure"][0]["file"], file);
assert_eq!(value["unsure"][0]["reason"], "declared twice");
let out = run(root, "check", &[]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "{stdout}");
assert!(
stdout.contains("1 import (0 proven, 1 unproven)"),
"{stdout}"
let report = report(root);
assert_eq!(report.problems, Vec::<String>::new());
let links = &report.counts.links;
assert_eq!(
(links.import, links.proven, links.unproven),
(1, 0, 1),
"{links:?}"
);
}

/// What `check` without `--json` prints of `report` on standard output, its problems, and on standard error, its notes.
fn printed(report: &system_map::Report) -> (String, String) {
let stdout = report.problems.iter().map(|p| format!("{p}\n")).collect();
let stderr = report
.suggested
.iter()
.map(|name| format!("note: {name} could read this repository; add it to extractors\n"))
.chain(
report
.unsure_notes()
.iter()
.chain(&report.notes)
.map(|note| format!("note: {note}\n")),
)
.collect();
(stdout, stderr)
}
3 changes: 2 additions & 1 deletion system-map/tests/dart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use serde_json::{Value, json};

use crate::common::{
assert_only_candidate_links_relaxed, assert_unsure_file_listed_and_link_unproven,
assert_only_candidate_links_relaxed, assert_unsure_file_listed_and_link_unproven, commit,
extractor_map, has, imports_json, pairs, repo, report, run, sites, write,
};

Expand Down Expand Up @@ -950,6 +950,7 @@ fn commit_mode_gives_the_edges_of_the_working_tree() {
("lib/z.dart", ""),
],
);
commit(&root);
let tree = run(&root, "check", &["--json"]);
let commit = run(&root, "check", &["--json", "--commit", "HEAD"]);
assert_eq!(
Expand Down
4 changes: 3 additions & 1 deletion system-map/tests/dotnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
use serde_json::{Value, json};

use crate::common::{
assert_only_candidate_links_relaxed, extractor_map, has, pairs, repo, report, run, sites, write,
assert_only_candidate_links_relaxed, commit, extractor_map, has, pairs, repo, report, run,
sites, write,
};

/// A map naming `dotnet-projects` whose parts are `parts`, each an id with its paths, and whose import links are `links`.
Expand Down Expand Up @@ -756,6 +757,7 @@ fn commit_mode_gives_the_edges_of_the_working_tree() {
("core/Core.csproj", EMPTY),
],
);
commit(&root);
let tree = run(&root, "check", &["--json"]);
let commit = run(&root, "check", &["--json", "--commit", "HEAD"]);
assert_eq!(
Expand Down
Loading
Loading