|
import subprocess |
|
import sys |
|
import tempfile |
|
import unittest |
|
import zipfile |
|
from collections import Counter |
|
from contextlib import redirect_stdout |
|
from pathlib import Path |
|
from unittest.mock import patch |
|
|
|
import censor |
|
|
|
|
|
class MatchingTests(unittest.TestCase): |
|
def test_grouped_family_counts(self): |
|
counts = Counter() |
|
text = ("fuck shit bitch damn ass penis pussies dick cum blow-job " |
|
"bastard douchebag prick dickheads Jesus oh my God hell") |
|
censor.censor_plain_text(text, counts) |
|
self.assertEqual(counts, { |
|
"f-word": 1, "s-word": 1, "b-word": 1, "d-word": 1, "a-word": 1, |
|
"body-parts/functions": 5, "vulgar insults": 4, |
|
"name-in-vain": 2, "h*ll": 1, |
|
}) |
|
output = io.StringIO() |
|
with redirect_stdout(output): |
|
censor.print_summary(censor.Report(counts=counts)) |
|
rows = [line for line in output.getvalue().splitlines() |
|
if line.split() and line.split()[-1].isdigit()] |
|
self.assertEqual(len({len(row) for row in rows}), 1) |
|
self.assertIn("h*ll", output.getvalue()) |
|
|
|
def test_longest_phrases_across_families(self): |
|
for phrase, family in (("Jesus fucking Christ", "name-in-vain"), |
|
("oh my God", "name-in-vain"), ("God almighty", "name-in-vain"), |
|
("for Christ's sake", "name-in-vain"), |
|
("what the hell", "h*ll"), ("shit heads", "s-word"), |
|
("bitch slap", "b-word"), ("piss off", "body-parts/functions")): |
|
with self.subTest(phrase=phrase): |
|
counts = Counter() |
|
match = next(censor.find_matches(phrase))[1] |
|
self.assertEqual(censor.censor_plain_text(phrase, counts), censor.censor_text(match)) |
|
self.assertEqual(counts, {family: 1}) |
|
self.assertEqual(match.group(), phrase) |
|
|
|
def test_body_parts_boundaries_and_case(self): |
|
counts = Counter() |
|
text = "PUSSIES penises dick-faces titties boobies cockpit title cumulative" |
|
output = censor.censor_plain_text(text, counts) |
|
self.assertEqual(sum(counts.values()), 5) |
|
self.assertTrue(output.endswith("cockpit title cumulative")) |
|
self.assertNotIn("faces", output) |
|
|
|
def test_f_word_inside_any_word(self): |
|
words = ("fuckery", "fuckable", "unfuckwithable", "mindfucked", |
|
"absofuckinglutely", "fanfuckingtastic", "clusterfuckery", |
|
"motherfuckingly", "fuckfuck", "FuCkErY") |
|
counts = Counter() |
|
text = ", ".join(words) |
|
output = censor.censor_plain_text(text, counts) |
|
self.assertEqual(output, ", ".join( |
|
"".join("@#$!"[i % 4] for i in range(len(word))) for word in words |
|
)) |
|
self.assertEqual(counts, {"f-word": len(words)}) |
|
for word in words: |
|
self.assertEqual(next(censor.find_matches(word))[1].group(), word) |
|
|
|
def test_broader_f_word_keeps_other_families_bounded(self): |
|
text = "class assignment cockpit title cumulative Scunthorpe Suffolk" |
|
counts = Counter() |
|
self.assertEqual(censor.censor_plain_text(text, counts), text) |
|
self.assertEqual(counts, {}) |
|
|
|
def test_spaced_and_hyphenated_f_words_still_match(self): |
|
for phrase in ("fuck off", "fuck-ups", "mother fuckers", "mother-fuckers", |
|
"dumb fucks", "cluster-fucking"): |
|
with self.subTest(phrase=phrase): |
|
matches = list(censor.find_matches(phrase)) |
|
self.assertEqual(len(matches), 1) |
|
self.assertEqual(matches[0][0], "f-word") |
|
self.assertEqual(matches[0][1].group(), phrase) |
|
|
|
|
|
class HtmlTests(unittest.TestCase): |
|
def test_f_word_compounds_across_inline_tags_and_references(self): |
|
source = '<p id="fuckery">abso<em>fuck</em>inglutely</p>' |
|
counts, matches = Counter(), Counter() |
|
result = censor.censor_html(source, counts, matches) |
|
self.assertEqual(result, '<p id="fuckery">@#$!<em>@#$!</em>@#$!@#$!@</p>') |
|
self.assertEqual(counts, {"f-word": 1}) |
|
self.assertEqual(matches, {"absofuckinglutely": 1}) |
|
|
|
def test_only_visible_text_changes(self): |
|
source = ('<?xml version="1.0"?><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml">' |
|
'<head><title>God</title><style>.shit { color: red; }</style></head>' |
|
'<body><!-- fuck --><script>fuck()</script><p id="shit" class="ass">' |
|
'<a href="Jesus.xhtml" title="God">fuck</a></p>' |
|
'<p hidden="hidden">shit</p><span aria-hidden="true">God</span>' |
|
'<span style="display: none">Jesus</span></body></html>') |
|
counts = Counter() |
|
self.assertEqual(censor.censor_html(source, counts), source.replace('>fuck</a>', '>@#$!</a>')) |
|
self.assertEqual(counts, {"f-word": 1}) |
|
|
|
def test_phrases_across_inline_tags_and_entities(self): |
|
source = '<p>Jesus <em>fucking</em> Christ & fuck <test></p>' |
|
counts = Counter() |
|
result = censor.censor_html(source, counts) |
|
self.assertEqual(result, '<p>@#$!@ <em>#$!@#$!</em> @#$!@# & @#$! <test></p>') |
|
self.assertEqual(counts, {"name-in-vain": 1, "f-word": 1}) |
|
|
|
def test_block_boundaries_stop_phrases(self): |
|
counts = Counter() |
|
result = censor.censor_html('<p>oh my</p><p>God</p>Jesus<br/>Christ', counts) |
|
self.assertEqual(result, '<p>oh my</p><p>@#$</p>@#$!@<br/>@#$!@#') |
|
self.assertEqual(counts, {"name-in-vain": 3}) |
|
|
|
def test_multiline_positions_and_entity_preservation(self): |
|
counts = Counter() |
|
source = '<p>oh my\nGod &unknown; &fuck; fuck</p>' |
|
result = censor.censor_html(source, counts) |
|
self.assertEqual(result, '<p>@# $!\n@#$ &unknown; &@#$!; @#$!</p>') |
|
self.assertEqual(counts, {"name-in-vain": 1, "f-word": 2}) |
|
|
|
|
|
class EpubTests(unittest.TestCase): |
|
def setUp(self): |
|
self.temp = tempfile.TemporaryDirectory() |
|
self.addCleanup(self.temp.cleanup) |
|
self.src = Path(self.temp.name) / "input.epub" |
|
self.dst = Path(self.temp.name) / "output.epub" |
|
with zipfile.ZipFile(self.src, "w") as book: |
|
book.writestr("chapter.xhtml", "<p>fuck</p>") |
|
book.writestr("mimetype", "application/epub+zip") |
|
book.writestr("asset.bin", b"\x00\xfffuck") |
|
|
|
def test_reject_input_aliases(self): |
|
original = self.src.read_bytes() |
|
alias = self.src.with_name("alias.epub") |
|
alias.symlink_to(self.src) |
|
hardlink = self.src.with_name("hardlink.epub") |
|
hardlink.hardlink_to(self.src) |
|
for dst in (self.src, alias, hardlink): |
|
with self.subTest(dst=dst), self.assertRaises(ValueError): |
|
censor.censor_epub(self.src, dst) |
|
self.assertEqual(self.src.read_bytes(), original) |
|
|
|
def test_failure_preserves_existing_output(self): |
|
self.dst.write_bytes(b"existing output") |
|
with patch.object(censor.os, "replace", side_effect=OSError("failed")): |
|
with self.assertRaises(OSError): |
|
censor.censor_epub(self.src, self.dst) |
|
self.assertEqual(self.dst.read_bytes(), b"existing output") |
|
self.assertEqual(list(self.dst.parent.glob("*.tmp")), []) |
|
|
|
def test_epub_output(self): |
|
original = self.src.read_bytes() |
|
report = censor.censor_epub(self.src, self.dst) |
|
self.assertEqual(report.counts["f-word"], 1) |
|
self.assertEqual(self.src.read_bytes(), original) |
|
with zipfile.ZipFile(self.dst) as book: |
|
self.assertEqual(book.read("chapter.xhtml"), b"<p>@#$!</p>") |
|
self.assertEqual(book.read("asset.bin"), b"\x00\xfffuck") |
|
self.assertEqual(book.infolist()[0].filename, "mimetype") |
|
self.assertEqual(book.infolist()[0].compress_type, zipfile.ZIP_STORED) |
|
|
|
def test_cli_errors_and_help(self): |
|
script = str(Path(censor.__file__)) |
|
for args, expected in (([], "usage:"), (["--help"], "input EPUB"), |
|
([str(self.src), str(self.src)], "different files")): |
|
result = subprocess.run([sys.executable, script, *args], capture_output=True, text=True) |
|
self.assertIn(expected, result.stdout + result.stderr) |
|
self.assertNotIn("Traceback", result.stderr) |
|
self.assertEqual(result.returncode == 0, args == ["--help"]) |
|
|
|
def test_preview_reports_matches_without_writes(self): |
|
original = self.src.read_bytes() |
|
self.dst.write_bytes(b"existing output") |
|
with patch.object(censor.tempfile, "NamedTemporaryFile", side_effect=AssertionError("write")): |
|
preview = censor.censor_epub(self.src, self.dst, preview=True) |
|
self.assertEqual(preview.matches, {"chapter.xhtml": {"fuck": 1}}) |
|
self.assertEqual(self.src.read_bytes(), original) |
|
self.assertEqual(self.dst.read_bytes(), b"existing output") |
|
written = censor.censor_epub(self.src, self.dst) |
|
self.assertEqual(preview.counts, written.counts) |
|
result = subprocess.run([sys.executable, censor.__file__, "--preview", str(self.src)], |
|
capture_output=True, text=True) |
|
self.assertEqual(result.returncode, 0, result.stderr) |
|
self.assertIn("'fuck': 1", result.stdout) |
|
self.assertNotIn("Wrote", result.stdout) |
|
|
|
def test_skipped_chapters_are_reported_and_preserved(self): |
|
with zipfile.ZipFile(self.src, "a") as book: |
|
book.writestr("invalid.xhtml", b"<p>\xfffuck</p>") |
|
preview = censor.censor_epub(self.src, preview=True) |
|
written = censor.censor_epub(self.src, self.dst) |
|
self.assertEqual(preview.skipped, written.skipped) |
|
self.assertEqual(len(written.skipped), 1) |
|
self.assertEqual(written.counts, {"f-word": 1}) |
|
with zipfile.ZipFile(self.src) as original, zipfile.ZipFile(self.dst) as output: |
|
for name, _ in written.skipped: |
|
self.assertEqual(original.read(name), output.read(name)) |
|
|
|
def test_parser_failure_does_not_count_partial_matches(self): |
|
def fail(text, counts, matches): |
|
counts["f-word"] = 99 |
|
raise ValueError("cannot parse chapter") |
|
|
|
with patch.object(censor, "censor_html", side_effect=fail): |
|
report = censor.censor_epub(self.src, self.dst) |
|
self.assertEqual(report.counts, {}) |
|
self.assertEqual(report.skipped, [("chapter.xhtml", "HTML parsing failed: cannot parse chapter")]) |
|
with zipfile.ZipFile(self.dst) as book: |
|
self.assertEqual(book.read("chapter.xhtml"), b"<p>fuck</p>") |
|
|
|
def test_invalid_and_missing_input_have_clear_errors(self): |
|
self.src.write_bytes(b"not an EPUB") |
|
for src in (self.src, self.src.with_name("missing.epub")): |
|
result = subprocess.run([sys.executable, censor.__file__, str(src), str(self.dst)], |
|
capture_output=True, text=True) |
|
self.assertEqual(result.returncode, 1) |
|
self.assertNotIn("Traceback", result.stderr) |
|
self.assertFalse(self.dst.exists()) |
|
|
|
|
|
if __name__ == "__main__": |
|
unittest.main() |
|
import io |