from __future__ import annotations
import contextlib
import io
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import check_doc_ownership as gate
def run(cwd, *args, check=True):
subprocess.run(
args, cwd=cwd, check=check, capture_output=True, text=True
)
class Repo:
def __init__(self, tmp: Path):
self.path = tmp
run(tmp, "git", "init", "-q", "-b", "main")
run(tmp, "git", "config", "user.email", "t@example.com")
run(tmp, "git", "config", "user.name", "t")
def commit(self, name: str, text: str, message: str = "c"):
(self.path / name).write_text(text)
run(self.path, "git", "add", "-A")
run(self.path, "git", "commit", "-q", "-m", message)
def branch(self, name: str):
run(self.path, "git", "checkout", "-q", "-b", name)
def checkout(self, name: str):
run(self.path, "git", "checkout", "-q", name)
def merge(self, name: str):
run(self.path, "git", "merge", "-q", "--no-edit", name)
def exit_code(self, base="main", head="HEAD"):
import os
cwd = os.getcwd()
argv = sys.argv
os.chdir(self.path)
sys.argv = ["check_doc_ownership.py", base, head]
try:
return gate.main()
finally:
sys.argv = argv
os.chdir(cwd)
def run_gate(self, base="main", head="HEAD"):
out = io.StringIO()
cwd, argv = os.getcwd(), sys.argv
os.chdir(self.path)
sys.argv = ["check_doc_ownership.py", base, head]
try:
with contextlib.redirect_stdout(out):
return gate.main(), out.getvalue()
finally:
sys.argv = argv
os.chdir(cwd)
DOCUMENTED_CONST = '''/// The scopes each role uses.
const SYNTAX_SCOPES: &[&str] = &["a"];
'''
CAPTURED_CONST = '''/// The scopes each role uses.
const SYNTAX_SEMANTIC: &[&str] = &["b"];
const SYNTAX_SCOPES: &[&str] = &["a"];
'''
class ItemKinds(unittest.TestCase):
def test_every_item_kind_is_recognised(self):
for decl, name in [
("fn a() {}", "a"),
("pub fn a() {}", "a"),
("const A: u8 = 1;", "A"),
("pub const A: &str = \"x\";", "A"),
("static A: u8 = 1;", "A"),
("pub static mut A: u8 = 1;", "A"),
("struct A;", "A"),
("pub enum A { B }", "A"),
("union A { b: u8 }", "A"),
("pub trait A {}", "A"),
("type A = u8;", "A"),
("macro_rules! a {}", "a"),
]:
state = gate.documented(f"/// doc\n{decl}\n")
self.assertEqual(
state.get(name),
True,
f"{decl!r} should be seen as documented item {name!r}",
)
def test_declaration_shapes_the_regex_must_not_miss(self):
for label, text in [
("attribute on its own line", "/// doc\n#[cfg(test)]\nconst A: u8 = 1;\n"),
("attribute on the same line", "/// doc\n#[cfg(test)] const A: u8 = 1;\n"),
("generic type alias", "/// doc\npub type A<T> = Vec<T>;\n"),
("const fn", "/// doc\npub const fn a() -> u8 { 1 }\n"),
("indented impl method", "impl X {\n /// doc\n pub fn a(&self) {}\n}\n"),
("const unsafe fn", "/// doc\npub const unsafe fn a() {}\n"),
("const extern fn", '/// doc\nconst unsafe extern "C" fn a() {}\n'),
("every qualifier", "/// doc\npub default const async unsafe fn a() {}\n"),
]:
state = gate.documented(text)
self.assertTrue(
any(state.values()),
f"{label}: nothing was recognised, so the item is invisible "
f"to the gate rather than merely undocumented",
)
def test_multi_line_attributes_and_block_docs_are_read_correctly(self):
documented_shapes = [
("multi-line attribute", "/// doc\n#[cfg(all(\n feature = \"x\",\n unix\n))]\nconst A: u8 = 1;\n"),
("one-line block doc", "/** doc */\nconst A: u8 = 1;\n"),
("multi-line block doc", "/**\n * doc\n */\nconst A: u8 = 1;\n"),
("block doc then attribute", "/** doc */\n#[cfg(test)]\nconst A: u8 = 1;\n"),
]
for label, text in documented_shapes:
self.assertEqual(
gate.documented(text).get("A"), True, f"{label} documents A"
)
undocumented_shapes = [
("inner block doc documents the MODULE", "/*! module */\nconst A: u8 = 1;\n"),
("ordinary block comment", "/* a note */\nconst A: u8 = 1;\n"),
("triple-star rule", "/*** rule ***/\nconst A: u8 = 1;\n"),
("four slashes is a rule", "//// rule\nconst A: u8 = 1;\n"),
]
for label, text in undocumented_shapes:
self.assertEqual(
gate.documented(text).get("A"),
False,
f"{label} must not count as documentation",
)
def test_a_declaration_inside_a_string_is_not_an_item(self):
state = gate.documented('/// doc\nconst A: &str = "const B: u8 = 1;";\n')
self.assertEqual(state, {"A": True}, "B is inside a string, not an item")
def test_methods_are_keyed_by_their_enclosing_impl(self):
both_documented = (
"impl A {\n /// a\n fn new() {}\n}\n\n"
"impl B {\n /// b\n fn new() {}\n}\n"
)
one_captured = (
"impl A {\n /// a\n fn other() {}\n fn new() {}\n}\n\n"
"impl B {\n /// b\n fn new() {}\n}\n"
)
self.assertEqual(
gate.documented(both_documented), {"A::new": True, "B::new": True}
)
self.assertEqual(
gate.documented(one_captured),
{"A::other": True, "A::new": False, "B::new": True},
"the capture on A::new is visible even though B::new kept its doc",
)
def test_trait_impls_for_the_same_type_are_distinct_blocks(self):
text = (
"impl fmt::Display for X {\n /// d\n fn fmt(&self) {}\n}\n"
"impl fmt::Debug for X {\n fn fmt(&self) {}\n}\n"
)
self.assertEqual(
gate.documented(text),
{"fmt::Display for X::fmt": True, "fmt::Debug for X::fmt": False},
)
def test_impl_header_shapes(self):
for label, header in [
("plain", "impl Foo {"),
("generic", "impl<'a, T: Clone> Foo<'a, T> {"),
("where clause, brace on the next line", "impl<T> Foo<T>\nwhere\n T: Clone,\n{"),
("unsafe impl", "unsafe impl Foo {"),
]:
state = gate.documented(f"{header}\n /// doc\n fn new() {{}}\n}}\n")
self.assertEqual(state, {"Foo::new": True}, label)
state = gate.documented(
"impl<T> Iterator for Foo<T> {\n /// doc\n fn next(&mut self) {}\n}\n"
)
self.assertEqual(state, {"Iterator for Foo::next": True})
def test_braces_in_strings_and_chars_do_not_break_block_tracking(self):
text = (
"impl Foo {\n"
" /// doc\n"
' fn new() { let _ = format!("{{ {x} }}"); let c = \'{\'; }\n'
"}\n"
"/// top\n"
"fn top() {}\n"
)
self.assertEqual(gate.documented(text), {"Foo::new": True, "top": True})
def test_items_outside_any_impl_keep_the_bare_name(self):
text = (
"/// a\nfn a() {}\n"
"mod m {\n /// b\n pub fn b() {}\n}\n"
"impl X {\n /// c\n fn c() {}\n}\n"
"/// d\nfn d() {}\n"
)
self.assertEqual(
gate.documented(text), {"a": True, "b": True, "X::c": True, "d": True}
)
def test_a_bodyless_impl_does_not_qualify_the_next_block(self):
text = "impl Eq for X {}\nmod util {\n /// doc\n pub fn go() {}\n}\n"
self.assertEqual(gate.documented(text), {"go": True})
captured = (
"impl Eq for X {}\nmod util {\n /// doc\n pub fn newcomer() {}\n"
" pub fn go() {}\n}\n"
)
after = gate.documented(captured)
self.assertEqual(after.get("go"), False, f"go lost its doc: {after}")
def test_raw_strings_do_not_break_block_tracking(self):
single = (
'impl Foo {\n /// doc\n fn m() {\n'
' let j = r#"[{"key": "click"}]"#;\n }\n}\n'
"/// top\nfn top() {}\n"
)
self.assertEqual(gate.documented(single), {"Foo::m": True, "top": True})
multi = (
'impl Foo {\n /// doc\n fn m() {\n'
' let j = r#"{ "tasks": [\n'
' { "label": "x" }\n'
' ] }"#;\n }\n}\n'
"/// top\nfn top() {}\n"
)
self.assertEqual(gate.documented(multi), {"Foo::m": True, "top": True})
plain_multi = (
'impl Foo {\n /// doc\n fn m() {\n'
' let s = "{ opens here\n'
' and closes here }";\n }\n}\n'
"/// top\nfn top() {}\n"
)
self.assertEqual(gate.documented(plain_multi), {"Foo::m": True, "top": True})
def test_a_header_wrapped_by_rustfmt_keeps_its_key(self):
text = "impl<T>\n Trait for X<T>\n{\n /// doc\n fn m() {}\n}\n"
self.assertEqual(gate.documented(text), {"Trait for X::m": True})
def test_trait_methods_are_keyed_by_their_trait(self):
text = (
"trait A {\n /// a\n fn id(&self);\n}\n"
"trait B: Clone {\n /// b\n fn id(&self);\n}\n"
)
self.assertEqual(
gate.documented(text),
{"A": False, "trait A::id": True, "B": False, "trait B::id": True},
"the traits are items in their own scope; their methods are in theirs",
)
def test_the_block_tracker_is_balanced_at_eof_on_every_real_file(self):
src = Path(__file__).resolve().parents[2] / "src"
files = sorted(src.rglob("*.rs"))
self.assertGreater(len(files), 50, "the control corpus is missing")
unbalanced = []
for f in files:
lines = f.read_text().splitlines()
kinds = gate.classify(lines)
t = gate.BlockTracker()
for line, kind in zip(lines, kinds):
if kind == gate.CODE:
t.feed(line)
if t.depth != 0 or t.blocks or t.open_string is not None:
unbalanced.append((str(f.relative_to(src)), t.depth, t.blocks, t.open_string))
self.assertEqual(unbalanced, [], "the tracker lost count in these files")
def test_same_named_items_in_the_same_scope_are_still_merged(self):
text = "/// a\nfn new() {}\n\n/// b\nfn new() {}\n"
one_captured = "/// a\nfn other() {}\nfn new() {}\n\n/// b\nfn new() {}\n"
self.assertEqual(gate.documented(text), {"new": True})
self.assertEqual(gate.documented(one_captured), {"other": True, "new": True})
def test_a_capture_on_one_impl_of_a_shared_method_name_is_reported(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit(
"a.rs",
"impl A {\n /// a\n fn new() {}\n}\n"
"impl B {\n /// b\n fn new() {}\n}\n",
)
repo.branch("work")
repo.commit(
"a.rs",
"impl A {\n /// a\n fn other() {}\n fn new() {}\n}\n"
"impl B {\n /// b\n fn new() {}\n}\n",
)
self.assertEqual(repo.exit_code(), 1, "A::new lost its doc")
repo.commit("a.rs", "// nudge\n" + (repo.path / "a.rs").read_text(), "ok\n\ndoc-removal: a.rs::A::new")
self.assertEqual(repo.exit_code(), 0, "a declared A::new removal is exempt")
def test_the_error_names_the_revision_the_doc_was_last_seen_at(self):
import contextlib
import io
import os
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("seed.rs", "fn seed() {}\n")
repo.branch("work")
repo.commit("new.rs", DOCUMENTED_CONST)
documented_at = subprocess.run(
["git", "rev-parse", "HEAD"],
cwd=repo.path,
capture_output=True,
text=True,
check=True,
).stdout.strip()
repo.commit("new.rs", CAPTURED_CONST)
code, text = repo.run_gate()
self.assertEqual(code, 1)
printed = text
self.assertIn(
documented_at[:12],
printed,
f"the error must name the commit the doc was last seen at, said: {printed}",
)
def test_a_rename_is_not_a_lost_doc(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "/// doc\nfn a() {}\n")
repo.branch("work")
repo.commit("a.rs", "/// doc\nfn b() {}\n")
self.assertEqual(
repo.exit_code(), 0, "a rename is not a captured doc comment"
)
def test_a_const_that_loses_its_doc_is_reported(self):
before = gate.documented(DOCUMENTED_CONST)
after = gate.documented(CAPTURED_CONST)
self.assertTrue(before["SYNTAX_SCOPES"])
self.assertFalse(after["SYNTAX_SCOPES"], "its doc now sits on the newcomer")
self.assertTrue(after["SYNTAX_SEMANTIC"], "which is how the capture hides")
class GitShapes(unittest.TestCase):
def test_a_capture_in_an_existing_file_is_reported(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", DOCUMENTED_CONST)
repo.branch("work")
repo.commit("a.rs", CAPTURED_CONST)
self.assertEqual(
repo.exit_code(), 1, "the gate must fail on a captured doc"
)
def test_a_file_present_at_the_base_is_not_treated_as_added(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", DOCUMENTED_CONST)
repo.branch("work")
repo.commit("a.rs", CAPTURED_CONST)
repo.commit("new.rs", "/// n\nfn n() {}\n")
cwd = os.getcwd()
os.chdir(repo.path)
try:
self.assertTrue(gate.exists_at("main", "a.rs"))
self.assertFalse(gate.exists_at("main", "new.rs"))
self.assertEqual(gate.added_files("main", ["a.rs", "new.rs"]), ["new.rs"])
finally:
os.chdir(cwd)
def test_a_capture_in_an_existing_file_is_reported_exactly_once(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", DOCUMENTED_CONST)
repo.branch("work")
repo.commit("a.rs", DOCUMENTED_CONST + "\n/// Extra.\nconst EXTRA: u8 = 1;\n")
repo.commit("a.rs", CAPTURED_CONST + "\n/// Extra.\nconst EXTRA: u8 = 1;\n")
code, text = repo.run_gate()
self.assertEqual(code, 1)
self.assertEqual(
text.count("::error"),
1,
f"one loss, one annotation: {text}",
)
def test_a_capture_inside_a_file_the_branch_added_is_reported(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("seed.rs", "fn seed() {}\n")
repo.branch("work")
repo.commit("new.rs", DOCUMENTED_CONST)
repo.commit("new.rs", CAPTURED_CONST)
self.assertEqual(
repo.exit_code(), 1, "the gate must fail on a captured doc"
)
def test_a_doc_captured_and_then_restored_within_a_branch_passes(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("seed.rs", "fn seed() {}\n")
repo.branch("work")
repo.commit("new.rs", DOCUMENTED_CONST)
repo.commit("new.rs", CAPTURED_CONST)
repo.commit(
"new.rs",
"/// Its own doc.\nconst SYNTAX_SEMANTIC: &[&str] = &[\"b\"];\n\n"
+ DOCUMENTED_CONST,
)
self.assertEqual(
repo.exit_code(),
0,
"a doc restored before the branch tip is not a loss",
)
def test_a_branch_that_captures_nothing_passes(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", DOCUMENTED_CONST)
repo.branch("work")
repo.commit("a.rs", DOCUMENTED_CONST + "\n/// Another.\nconst B: u8 = 2;\n")
self.assertEqual(repo.exit_code(), 0, "an honest addition must pass")
def test_a_declared_removal_is_exempt(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", DOCUMENTED_CONST)
repo.branch("work")
repo.commit(
"a.rs",
"const SYNTAX_SCOPES: &[&str] = &[\"a\"];\n",
"drop it\n\ndoc-removal: a.rs::SYNTAX_SCOPES",
)
self.assertEqual(
repo.exit_code(),
0,
"a declared removal is the documented escape hatch",
)
if __name__ == "__main__":
unittest.main()
class HeadOnlyOrphanTests(unittest.TestCase):
def test_a_use_between_a_doc_and_its_fn_is_caught(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "fn existing() {}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"fn existing() {}\n\n/// Documents beta.\nuse std::fmt;\n\nfn beta() {}\n",
)
self.assertEqual(repo.exit_code(), 1)
def test_a_capture_whose_victim_is_new_on_the_branch_is_caught(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "fn existing() {}\n")
repo.branch("feat")
repo.commit("a.rs", "fn existing() {}\n\n/// Documents beta.\nfn beta() {}\n")
repo.commit(
"a.rs",
"fn existing() {}\n\n/// Documents beta.\n\n"
"/// Documents gamma.\nfn gamma() {}\n\nfn beta() {}\n",
)
self.assertEqual(repo.exit_code(), 1)
def test_a_capture_both_older_passes_see_is_reported_once(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "/// Documents beta.\nfn beta() {}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"/// Documents beta.\n\n/// Documents gamma.\nfn gamma() {}\n\nfn beta() {}\n",
)
code, text = repo.run_gate()
self.assertEqual(code, 1)
self.assertIn(
"`beta` had a doc comment",
text,
f"the loss pass keeps the report: {text}",
)
self.assertEqual(
text.count("::error"),
1,
f"one insertion, one annotation: {text}",
)
def test_a_stranded_block_unrelated_to_a_loss_is_still_reported(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "/// Documents beta.\nfn beta() {}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"/// Documents beta.\n\n/// Documents gamma.\nfn gamma() {}\n\nfn beta() {}\n"
"\n/// Lonely.\n\n/// Documents delta.\nfn delta() {}\n",
)
code, text = repo.run_gate()
self.assertEqual(code, 1)
self.assertIn("`beta` had a doc comment", text)
self.assertIn("'/// Lonely.'", text, f"the unrelated block is still stranded: {text}")
self.assertNotIn("'/// Documents beta.'", text, f"the block the loss explains stands down: {text}")
self.assertEqual(text.count("::error"), 2, f"two defects, two annotations: {text}")
def test_duplicated_prose_does_not_silence_a_second_stranded_block(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "impl A {\n /// Creates a new instance.\n pub fn new() {}\n}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"impl A {\n /// Creates a new instance.\n\n /// Helper.\n"
" pub fn helper() {}\n\n pub fn new() {}\n}\n"
"impl C {\n /// Creates a new instance.\n\n /// Other.\n"
" pub fn other() {}\n\n pub fn new() {}\n}\n",
)
code, text = repo.run_gate()
self.assertEqual(code, 1)
self.assertIn("`A::new` had a doc comment", text)
self.assertIn("line=10::", text, f"the copy in impl C is its own defect: {text}")
self.assertNotIn("line=2::", text, f"the copy above A::new is the loss's: {text}")
self.assertEqual(text.count("::error"), 2, f"two captures, two annotations: {text}")
def test_a_rewritten_victim_block_does_not_lend_its_loss_to_a_farther_block(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "impl A {\n /// Creates a new instance.\n pub fn new() {}\n}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"impl C {\n /// Creates a new instance.\n\n /// Other.\n"
" pub fn other() {}\n\n pub fn new() {}\n}\n"
"impl A {\n /// Creates a new instance, better.\n\n /// Helper.\n"
" pub fn helper() {}\n\n pub fn new() {}\n}\n",
)
code, text = repo.run_gate()
self.assertEqual(code, 1)
self.assertIn("`A::new` had a doc comment", text)
self.assertIn("line=2::", text, f"impl C's stranded copy is its own defect: {text}")
self.assertIn("line=10::", text, f"the rewritten block is stranded too: {text}")
self.assertEqual(text.count("::error"), 3, f"three defects, three annotations: {text}")
def test_a_victim_moved_above_its_old_block_leaves_the_block_reported(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "/// Documents beta.\nfn beta() {}\n")
repo.branch("feat")
repo.commit("a.rs", "fn beta() {}\n/// Documents beta.\n")
code, text = repo.run_gate()
self.assertEqual(code, 1)
self.assertIn("`beta` had a doc comment", text)
self.assertIn("line=2::", text, f"the block at end of file is reported: {text}")
self.assertEqual(text.count("::error"), 2, f"loss and stranded block both print: {text}")
def test_two_identical_blocks_above_one_victim_are_both_reported(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "impl A {\n /// Creates a new instance.\n pub fn new() {}\n}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"impl A {\n /// Creates a new instance.\n\n /// Helper.\n"
" pub fn helper() {}\n\n /// Creates a new instance.\n\n /// Other.\n"
" pub fn other() {}\n\n pub fn new() {}\n}\n",
)
code, text = repo.run_gate()
self.assertEqual(code, 1)
self.assertIn("`A::new` had a doc comment", text)
self.assertIn("line=2::", text, f"the farther copy is reported: {text}")
self.assertIn("line=7::", text, f"and so is the nearer one: {text}")
self.assertEqual(text.count("::error"), 3, f"an ambiguous pairing stands nothing down: {text}")
def test_cfg_twins_each_captured_stand_both_blocks_down(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit(
"a.rs",
"/// Creates a new instance.\n#[cfg(unix)]\nfn new() {}\n\n"
"/// Creates a new instance.\n#[cfg(windows)]\nfn new() {}\n",
)
repo.branch("feat")
repo.commit(
"a.rs",
"/// Creates a new instance.\n\n/// Helper.\nfn helper_a() {}\n\n"
"#[cfg(unix)]\nfn new() {}\n\n"
"/// Creates a new instance.\n\n/// Helper.\nfn helper_b() {}\n\n"
"#[cfg(windows)]\nfn new() {}\n",
)
code, text = repo.run_gate()
self.assertEqual(code, 1)
self.assertIn("`new` had a doc comment", text)
self.assertNotIn("line=", text, f"both stranded copies are explained: {text}")
self.assertEqual(text.count("::error"), 1, f"one loss, one annotation: {text}")
def test_ordinary_docs_are_not_reported(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "fn existing() {}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"fn existing() {}\n\n"
"/// Documented, with an attribute under the doc.\n"
"#[derive(Clone, Debug)]\n"
"struct A;\n\n"
"/// Documented, with an implementation note.\n"
"// not a doc comment\n"
"fn b() {}\n\n"
"/// Documented, above an impl.\n"
"impl A {}\n\n"
"/// Documented, above a mod.\n"
"mod inner {}\n",
)
self.assertEqual(repo.exit_code(), 0)
def test_a_doc_block_at_end_of_file_is_reported(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "fn existing() {}\n")
repo.branch("feat")
repo.commit("a.rs", "fn existing() {}\n\n/// Documents nothing at all.\n")
self.assertEqual(repo.exit_code(), 1)
def test_a_capture_by_a_documented_newcomer_is_caught(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "fn existing() {}\n")
repo.branch("feat")
repo.commit("a.rs", "fn existing() {}\n\n/// Documents alpha.\nfn alpha() {}\n")
repo.commit(
"a.rs",
"fn existing() {}\n\n/// Documents alpha.\n"
"/// ...but now sits above the newcomer.\n"
"struct Inserted;\n\nfn alpha() {}\n",
)
self.assertEqual(repo.exit_code(), 1)
def test_a_documented_re_export_is_not_reported(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "fn existing() {}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"fn existing() {}\n\n"
"/// Re-exported for convenience.\n"
"pub use crate::x::Y;\n\n"
"/// Also re-exported.\n"
"pub(crate) use crate::x::Z;\n",
)
self.assertEqual(repo.exit_code(), 0)
def test_a_use_that_documents_nothing_untouched_is_not_reported(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "/// Stranded.\nuse std::fmt;\n\nfn a() {}\n")
repo.commit("b.rs", "fn b() {}\n")
repo.branch("feat")
repo.commit("b.rs", "fn b() {}\n\nfn c() {}\n")
self.assertEqual(repo.exit_code(), 0)
class ReassignedDocTests(unittest.TestCase):
def test_a_contiguous_capture_of_a_variants_doc_is_caught(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit(
"a.rs",
"enum E {\n"
" /// Doc for A, an existing item.\n"
" A,\n"
"}\n",
)
repo.branch("feat")
repo.commit(
"a.rs",
"enum E {\n"
" /// Doc for A, an existing item.\n"
" /// Doc for B, inserted above it.\n"
" B,\n"
" A,\n"
"}\n",
)
self.assertEqual(repo.exit_code(), 1)
def test_the_error_names_the_line_and_both_items(self):
before = "enum E {\n /// Doc for A.\n A,\n}\n"
after = "enum E {\n /// Doc for A.\n /// Doc for B.\n B,\n A,\n}\n"
found = gate.reassigned_docs(before, after)
self.assertEqual(len(found), 1, found)
_line, doc, old, new = found[0]
self.assertEqual(doc, "/// Doc for A.")
self.assertEqual(old, "A,")
self.assertEqual(new, "B,")
def test_moving_a_doc_back_onto_its_own_item_is_not_a_capture(self):
before = "enum E {\n /// Doc for A.\n B,\n A,\n}\n"
after = "enum E {\n B,\n /// Doc for A.\n A,\n}\n"
self.assertEqual(gate.reassigned_docs(before, after), [])
def test_reordering_documented_items_is_not_a_capture(self):
before = "enum E {\n /// Doc A.\n A,\n /// Doc B.\n B,\n}\n"
after = "enum E {\n /// Doc B.\n B,\n /// Doc A.\n A,\n}\n"
self.assertEqual(gate.reassigned_docs(before, after), [])
def test_a_renamed_item_is_not_a_capture(self):
before = "/// Doc for alpha.\nfn alpha() {}\n"
after = "/// Doc for alpha.\nfn renamed() {}\n"
self.assertEqual(gate.reassigned_docs(before, after), [])
def test_a_victim_that_keeps_a_doc_of_its_own_is_not_reported(self):
before = "enum E {\n /// Doc A.\n A,\n /// Doc B.\n B,\n}\n"
after = (
"enum E {\n /// Doc A.\n Inserted,\n"
" /// Doc A, still here.\n A,\n /// Doc B.\n B,\n}\n"
)
self.assertEqual(gate.reassigned_docs(before, after), [])
def test_a_doc_line_that_repeats_in_the_file_is_not_a_capture(self):
before = (
"struct A {\n /// The width, in cells.\n w: u16,\n}\n"
"struct B {\n /// The width, in cells.\n x: u16,\n}\n"
)
after = (
"struct A {\n /// The width, in cells.\n width: u16,\n}\n"
"struct B {\n x: u16,\n}\n"
)
self.assertEqual(gate.reassigned_docs(before, after), [])
def test_a_bare_separator_line_is_not_a_doc_that_moved(self):
before = "/// Alpha.\n///\nfn a() {}\n"
after = "/// Alpha.\n///\nfn zz() {}\n\nfn a() {}\n"
moved = [f for f in gate.reassigned_docs(before, after) if f[1] == "///"]
self.assertEqual(moved, [], "a separator is not evidence of anything")
def test_a_two_hop_capture_names_the_item_that_lost_its_doc(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "enum E {\n /// Doc for A.\n A,\n}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"enum E {\n /// Doc for A.\n /// Doc for B.\n B,\n A,\n}\n",
)
repo.commit(
"a.rs",
"enum E {\n /// Doc for A.\n /// Doc for B.\n"
" /// Doc for C.\n C,\n B,\n A,\n}\n",
)
code, text = repo.run_gate()
self.assertEqual(code, 1)
self.assertIn(
"described 'A,'",
text,
f"the victim is the item that had the doc at the base: {text}",
)
def test_a_capture_made_between_two_branch_commits_is_caught(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "fn existing() {}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"fn existing() {}\n\nenum E {\n /// Doc for A.\n A,\n}\n",
)
repo.commit(
"a.rs",
"fn existing() {}\n\nenum E {\n /// Doc for A.\n"
" /// Doc for B.\n B,\n A,\n}\n",
)
self.assertEqual(repo.exit_code(), 1)
def test_a_capture_a_later_commit_repaired_passes(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "enum E {\n /// Doc for A.\n A,\n}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"enum E {\n /// Doc for A.\n /// Doc for B.\n B,\n A,\n}\n",
)
repo.commit(
"a.rs",
"enum E {\n /// Doc for B.\n B,\n /// Doc for A.\n A,\n}\n",
)
self.assertEqual(repo.exit_code(), 0)
def test_a_declared_removal_exempts_a_variant_too(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "enum E {\n /// Doc for A.\n A,\n}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"enum E {\n /// Doc for A.\n /// Doc for B.\n B,\n A,\n}\n",
message="feat: b\n\ndoc-removal: a.rs::A",
)
self.assertEqual(repo.exit_code(), 0)
def test_the_diff_pass_stays_out_of_a_capture_the_others_report(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "enum E {\n /// Doc for A.\n A,\n}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"enum E {\n /// Doc for A.\n\n /// Doc for B.\n B,\n A,\n}\n",
)
code, text = repo.run_gate()
self.assertEqual(code, 1)
self.assertNotIn(
"#455",
text,
f"the diff pass has nothing to say about a stranded block: {text}",
)
self.assertEqual(
text.count("::error"),
1,
f"the head-only pass alone: {text}",
)
def test_a_raw_identifier_is_one_name(self):
self.assertEqual(gate.subject_key(" r#type,"), "r#type")
self.assertEqual(gate.subject_key(" r#match,"), "r#match")
self.assertEqual(gate.subject_key(" pub r#fn: u8,"), "r#fn")
def test_a_declared_removal_of_a_raw_identifier_is_exempt(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "enum E {\n /// Doc for the type arm.\n r#type,\n}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"enum E {\n /// Doc for the type arm.\n /// Doc for the match arm.\n"
" r#match,\n r#type,\n}\n",
message="feat: match\n\ndoc-removal: a.rs::r#type",
)
self.assertEqual(repo.exit_code(), 0)
def test_a_declaration_naming_a_different_raw_identifier_does_not_excuse_it(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "enum E {\n /// Doc for the type arm.\n r#type,\n}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"enum E {\n /// Doc for the type arm.\n /// Doc for the match arm.\n"
" r#match,\n r#type,\n}\n",
message="feat: match\n\ndoc-removal: a.rs::r#match",
)
self.assertEqual(repo.exit_code(), 1)
def test_merging_main_does_not_report_what_main_did(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "enum E {\n /// Doc for Toggle.\n Toggle,\n}\n")
repo.branch("feat")
repo.commit(
"a.rs",
"enum E {\n /// Doc for Toggle.\n Toggle,\n}\n\npub fn helper() {}\n",
)
repo.checkout("main")
repo.commit(
"a.rs",
"enum E {\n /// Doc for Toggle.\n /// Doc for Load.\n"
" Load,\n Toggle,\n}\n",
message="feat: load\n\ndoc-removal: a.rs::Toggle",
)
repo.checkout("feat")
repo.merge("main")
self.assertEqual(
repo.exit_code(base="main"),
0,
"main's own change, declared on main, is not this branch's capture",
)
def test_a_capture_after_a_merge_is_still_caught(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "enum E {\n /// Doc for A.\n A,\n}\n")
repo.branch("feat")
repo.commit("b.rs", "fn b() {}\n")
repo.checkout("main")
repo.commit("c.rs", "fn c() {}\n")
repo.checkout("feat")
repo.merge("main")
repo.commit(
"a.rs",
"enum E {\n /// Doc for A.\n /// Doc for B.\n B,\n A,\n}\n",
)
self.assertEqual(repo.exit_code(base="main"), 1)
def test_a_capture_split_across_two_commits_is_caught(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "enum E {\n /// Doc for A.\n A,\n}\n")
repo.branch("feat")
repo.commit("a.rs", "enum E {\n B,\n /// Doc for A.\n A,\n}\n")
repo.commit("a.rs", "enum E {\n /// Doc for A.\n B,\n A,\n}\n")
self.assertEqual(repo.exit_code(), 1)
def test_a_keyword_led_subject_keys_on_the_name(self):
for line, key in [
("mod theme;", "theme"),
("pub mod pane;", "pane"),
("impl Foo {", "Foo"),
(" A,", "A"),
(" r#type,", "r#type"),
("pub(crate) fn foo(", "foo"),
('pub async unsafe extern "C" fn bar(', "bar"),
("macro_rules! m {", "m"),
("impl fmt::Display for Foo {", "fmt::Display for Foo"),
("impl fmt::Debug for Foo {", "fmt::Debug for Foo"),
("unsafe impl Send for X {}", "Send for X"),
("impl<T> Foo<T> {", "Foo"),
]:
self.assertEqual(gate.subject_key(line), key, line)
def test_two_raw_methods_in_one_impl_are_two_keys(self):
text = (
"impl Foo {\n /// Doc for type.\n pub fn r#type(&self) {}\n\n"
" /// Doc for match.\n pub fn r#match(&self) {}\n}\n"
)
keys = gate.documented(text)
self.assertIn("Foo::r#type", keys)
self.assertIn("Foo::r#match", keys)
def test_two_impls_of_one_type_are_two_declarations(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
before = (
"struct Foo;\n\n/// Doc for the Display impl.\n"
"impl fmt::Display for Foo {}\n\n/// Doc for the Debug impl.\n"
"impl fmt::Debug for Foo {}\n"
)
repo.commit("a.rs", before)
repo.branch("feat")
repo.commit(
"a.rs",
"struct Foo;\n\n/// Doc for the Display impl.\n"
"/// Doc for the inserted impl.\n"
"impl fmt::LowerHex for Foo {}\n"
"impl fmt::Display for Foo {}\n\n/// Doc for the Debug impl.\n"
"impl fmt::Debug for Foo {}\n",
message="feat: hex\n\ndoc-removal: a.rs::fmt::Debug for Foo",
)
self.assertEqual(
repo.exit_code(),
1,
"a declaration naming the DEBUG impl must not excuse the Display one",
)
def test_a_declaration_naming_the_captured_impl_does_excuse_it(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit(
"a.rs",
"struct Foo;\n\n/// Doc for the Display impl.\n"
"impl fmt::Display for Foo {}\n\n/// Doc for the Debug impl.\n"
"impl fmt::Debug for Foo {}\n",
)
repo.branch("feat")
repo.commit(
"a.rs",
"struct Foo;\n\n/// Doc for the Display impl.\n"
"/// Doc for the inserted impl.\n"
"impl fmt::LowerHex for Foo {}\n"
"impl fmt::Display for Foo {}\n\n/// Doc for the Debug impl.\n"
"impl fmt::Debug for Foo {}\n",
message="feat: hex\n\ndoc-removal: a.rs::fmt::Display for Foo",
)
self.assertEqual(repo.exit_code(), 0)
def test_a_capture_inside_a_merge_resolution_is_a_known_gap(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("a.rs", "enum E {\n /// Doc for A.\n A,\n Z,\n}\n")
repo.branch("feat")
repo.commit("a.rs", "enum E {\n /// Doc for A.\n A,\n Zed,\n}\n")
repo.checkout("main")
repo.commit("a.rs", "enum E {\n /// Doc for A.\n A,\n Z,\n B,\n}\n")
repo.checkout("feat")
run(repo.path, "git", "merge", "--no-commit", "main", check=False)
(repo.path / "a.rs").write_text(
"enum E {\n /// Doc for A.\n B,\n A,\n Zed,\n}\n"
)
run(repo.path, "git", "add", "-A")
run(repo.path, "git", "commit", "-q", "--no-edit")
self.assertEqual(
repo.exit_code(base="main"),
0,
"known gap: a resolution that moves an existing line under a doc block",
)
def test_a_commit_with_no_parent_does_not_abort_the_gate(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Repo(Path(tmp))
repo.commit("seed.rs", "fn seed() {}\n")
run(repo.path, "git", "checkout", "-q", "--orphan", "detached")
run(repo.path, "git", "rm", "-rq", "--cached", ".")
repo.commit("a.rs", "/// Doc for a.\nfn a() {}\n")
self.assertEqual(
repo.exit_code(base="main"),
0,
"a parentless commit is skipped, not fatal",
)
def test_a_block_doc_closer_is_not_prose(self):
before = "/**\n */\nfn a() {}\n"
after = "/**\n */\nfn zz() {}\n\nfn a() {}\n"
self.assertEqual(
gate.reassigned_docs(before, after),
[],
"the delimiter is not the documentation",
)
def test_a_captured_block_doc_is_reported_once(self):
before = "/** Doc for A.\n * More.\n */\nfn a() {}\n"
after = "/** Doc for A.\n * More.\n */\nfn zz() {}\n\nfn a() {}\n"
found = gate.reassigned_docs(before, after)
self.assertEqual(
len(found), 1, f"one block above one item is one report: {found}"
)
self.assertEqual(found[0][1], "/** Doc for A.", "and it names the block's first line")