#!/usr/bin/env python3 """Testes reais do relatorio LaTeX `medical-robotic`. Compila o documento (latexmk) e verifica factos conhecidos sobre o resultado: o PDF existe e tem paginas, o log nao tem erros fatais, todas as figuras referenciadas existem em disco, nao ha \\cite sem bibliografia e nao ha referencias cruzadas por resolver. Uso: python3 tests/test_report.py [--root DIR] [--no-build] Sai com codigo 0 se tudo passar, 1 se algo falhar. """ import argparse import os import re import subprocess import sys # ---------------------------------------------------------------- factos conhecidos # Fixos: qualquer mudanca aqui e uma mudanca de conteudo e tem de ser deliberada. MIN_PAGES = 1 EXPECTED_PAGES = 12 # latexmk -pdf report.tex -> 12 paginas EXPECTED_FIGURES = 31 # \includegraphics no caminho de compilacao EXPECTED_EPS = 25 # exportacoes Matlab em imgs/ EXPECTED_BIB = 0 # nenhum ficheiro .bib, nenhum \cite # Ficheiros que o documento inclui, por ordem (report.tex) ACTIVE_SOURCES = [ "report.tex", "structure/introduction.tex", "structure/Control_Design.tex", "structure/Trajectory_Design.tex", "structure/Free_research.tex", "structure/Conclusion.tex", ] # \ref{} com argumento vazio: herdado do documento original, nao resolvivel. # Contados como defeito conhecido, nao como falha do build. KNOWN_EMPTY_REFS = 3 FAILURES = [] CHECKS = [] def check(name, ok, detail=""): CHECKS.append((name, bool(ok), detail)) if not ok: FAILURES.append("%s -- %s" % (name, detail)) return ok def read(path): with open(path, encoding="utf-8", errors="replace") as fh: return fh.read() def scan_source(root): """Devolve (graphics, cites, refs, inputs) lidos do caminho de compilacao.""" graphics, cites, refs, inputs = [], [], [], [] for rel in ACTIVE_SOURCES: path = os.path.join(root, rel) if not os.path.exists(path): continue body = read(path) graphics += [ (rel, g) for g in re.findall( r"\\includegraphics(?:\[[^\]]*\])?\{([^}]*)\}", body ) ] cites += re.findall( r"\\cite[a-zA-Z]*\*?(?:\[[^\]]*\])*\{([^}]*)\}", body ) refs += re.findall(r"\\(?:eqref|ref|pageref|autoref)\{([^}]*)\}", body) inputs += re.findall(r"\\(?:input|include)\{([^}]*)\}", body) return graphics, cites, refs, inputs def resolve_graphic(root, g): """Encontra o ficheiro real para um \\includegraphics{g}.""" cand = os.path.join(root, g) if os.path.exists(cand): return cand base = os.path.splitext(cand)[0] for ext in (".eps", ".pdf", ".png", ".jpg", ".jpeg"): if os.path.exists(base + ext): return base + ext return None def log_facts(log_path): if not os.path.exists(log_path): return None text = read(log_path) lines = text.splitlines() pages = re.findall(r"Output written on .*?\((\d+)\s+pages?\b", text) return { "text": text, "fatal": [ l for l in lines if re.match(r"^!", l) or "Fatal error occurred" in l or "Emergency stop" in l ], "undefined_refs": [ l for l in lines if "Reference" in l and "undefined" in l ], "undefined_cites": [ l for l in lines if "Citation" in l and "undefined" in l ], "overfull": [l for l in lines if l.startswith("Overfull")], "underfull": [l for l in lines if l.startswith("Underfull")], "not_found": sorted(set(re.findall(r"File `([^']+)' not found", text))), "pages": [int(p) for p in pages], } def pdf_pages(path): """Numero de paginas, via pdfinfo se existir.""" for cmd in (["pdfinfo", path],): try: out = subprocess.run(cmd, capture_output=True, text=True, timeout=60) except (OSError, subprocess.SubprocessError): continue if out.returncode == 0: m = re.search(r"^Pages:\s+(\d+)", out.stdout, re.M) if m: return int(m.group(1)) return None # ------------------------------------------------------------------------ build def build(root): cmd = ["latexmk", "-pdf", "-interaction=nonstopmode", "report.tex"] print("$ " + " ".join(cmd)) proc = subprocess.run(cmd, cwd=root, capture_output=True, text=True) tail = (proc.stdout or "")[-1500:] print(tail) return proc.returncode # ------------------------------------------------------------------------ testes def run(root, do_build, mutate=None): """Corre a bateria. `mutate` permite a injecao de falhas (teste negativo).""" CHECKS.clear() FAILURES.clear() if mutate: mutate(root) if do_build: rc = build(root) check("compilacao: latexmk termina com codigo 0", rc == 0, "latexmk devolveu %s" % rc) pdf = os.path.join(root, "report.pdf") log = os.path.join(root, "report.log") # 1. o PDF e gerado exists = os.path.exists(pdf) check("pdf: report.pdf existe", exists, "ficheiro ausente") if exists: check("pdf: nao esta vazio", os.path.getsize(pdf) > 10000, "tem %d bytes" % os.path.getsize(pdf)) # 2. numero de paginas facts = log_facts(log) pages = pdf_pages(pdf) if exists else None if pages is None and facts: pages = facts["pages"][0] if facts["pages"] else None check("pdf: pdfinfo/latexmk reporta paginas", pages is not None, "nao foi possivel determinar o numero de paginas") if pages is not None: check("pdf: paginas > 0", pages >= MIN_PAGES, "tem %s paginas" % pages) check("pdf: %d paginas (facto conhecido)" % EXPECTED_PAGES, pages == EXPECTED_PAGES, "tem %s paginas" % pages) # 3. log sem erros fatais if facts is None: check("log: report.log existe", False, "log ausente; nada a verificar") else: check("log: sem erros fatais", not facts["fatal"], "; ".join(facts["fatal"][:3])) check("log: sem ficheiros em falta", not facts["not_found"], "; ".join(facts["not_found"][:5])) # 4. figuras referenciadas existem todas graphics, cites, refs, inputs = scan_source(root) missing = [] for rel, g in graphics: if resolve_graphic(root, g) is None: missing.append("%s (%s)" % (g, rel)) check("figuras: todas as \\includegraphics existem em disco", not missing, "; ".join(missing[:5])) check("figuras: %d referenciadas (facto conhecido)" % EXPECTED_FIGURES, len(graphics) == EXPECTED_FIGURES, "encontradas %d" % len(graphics)) # 5. citacoes sem entrada na bibliografia bibs = [f for f in os.listdir(root) if f.endswith(".bib")] if cites: ok = bool(bibs) check("citacoes: \\cite tem bibliografia", ok, "%d \\cite sem ficheiro .bib" % len(cites)) else: check("citacoes: sem \\cite (nao ha bibliografia a faltar)", not bibs or True, "") if facts is not None: check("citacoes: nenhuma citacao por resolver no log", not facts["undefined_cites"], "; ".join(facts["undefined_cites"][:3])) # 6. referencias cruzadas por resolver if facts is not None: unresolved = facts["undefined_refs"] empty = [l for l in unresolved if "Reference `'" in l] other = [l for l in unresolved if l not in empty] check("refs: defeito conhecido = %d \\ref{} vazios" % KNOWN_EMPTY_REFS, len(empty) == KNOWN_EMPTY_REFS, "encontrados %d" % len(empty)) check("refs: nenhuma outra referencia por resolver", not other, "; ".join(o.strip()[:120] for o in other[:3])) # 7. integridade dos \input for i in inputs: p = i if i.endswith(".tex") else i + ".tex" check("input: %s existe" % i, os.path.exists(os.path.join(root, p)), "em falta") return FAILURES, CHECKS def main(): ap = argparse.ArgumentParser() ap.add_argument("--root", default=os.path.dirname(os.path.dirname( os.path.abspath(__file__)))) ap.add_argument("--no-build", action="store_true", help="nao recompila; verifica apenas os artefactos existentes") args = ap.parse_args() print("=" * 68) print("medical-robotic -- testes do relatorio LaTeX") print("raiz: %s" % args.root) print("=" * 68) failures, checks = run(args.root, not args.no_build) print() for name, ok, detail in checks: print(" [%s] %s%s" % ("PASS" if ok else "FAIL", name, (" -- " + detail) if detail and not ok else "")) print() print("%d/%d verificacoes passaram" % (len(checks) - len(failures), len(checks))) if failures: print("\nFALHAS:") for f in failures: print(" -", f) return 1 print("OK") return 0 if __name__ == "__main__": sys.exit(main())