#!/usr/bin/env python3
"""Unit tests for header_lib (run: python3 scripts/test_header_lib.py)."""
from __future__ import annotations
import tempfile
import unittest
from pathlib import Path
from header_lib import (
apply_header_to_content,
format_identity,
has_valid_header,
is_excluded_path,
parse_identity,
resolve_header_contributor,
strip_existing_header,
)
from pathlib import Path
import header_lib
class HeaderLibTest(unittest.TestCase):
def test_strip_and_apply_java(self) -> None:
src = """package com.example;
public class Foo {
}
"""
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "Foo.java"
path.write_text(src, encoding="utf-8")
out = apply_header_to_content(path, src)
self.assertTrue(has_valid_header(out))
self.assertIn("package com.example;", out)
self.assertIn(" * class Foo", out)
self.assertIn("Digest: SHA256", out)
self.assertIn("Cursor Agent", out)
body, _ = strip_existing_header(out, ".java")
self.assertIn("public class Foo", body)
self.assertNotIn("package com.example", body.split("public class")[0])
def test_strip_php_opener(self) -> None:
src = " None:
self.assertEqual("Ada ", format_identity("Ada", "a@b.c"))
self.assertEqual("Ada", format_identity("Ada", ""))
name, mail = parse_identity("Ada ")
self.assertEqual(("Ada", "a@b.c"), (name, mail))
def test_excluded_third_party(self) -> None:
p = header_lib.REPO_ROOT / "third-party/libvpx/foo.c"
self.assertTrue(is_excluded_path(p))
def test_resolve_header_contributor_env(self) -> None:
import os
old = os.environ.get("HEADER_CONTRIBUTOR")
old_mail = os.environ.get("HEADER_CONTRIBUTOR_EMAIL")
try:
os.environ["HEADER_CONTRIBUTOR"] = "Test User"
os.environ.pop("HEADER_CONTRIBUTOR_EMAIL", None)
ident = resolve_header_contributor()
self.assertTrue(ident.startswith("Test User"))
finally:
if old is None:
os.environ.pop("HEADER_CONTRIBUTOR", None)
else:
os.environ["HEADER_CONTRIBUTOR"] = old
if old_mail is None:
os.environ.pop("HEADER_CONTRIBUTOR_EMAIL", None)
else:
os.environ["HEADER_CONTRIBUTOR_EMAIL"] = old_mail
if __name__ == "__main__":
unittest.main()