Skip to content

Instantly share code, notes, and snippets.

@peteristhegreat
Last active October 19, 2026 14:29
Show Gist options
  • Select an option

  • Save peteristhegreat/963c5635b7c6e92cf5bf6c3547e2cfba to your computer and use it in GitHub Desktop.

Select an option

Save peteristhegreat/963c5635b7c6e92cf5bf6c3547e2cfba to your computer and use it in GitHub Desktop.
Censor Profanity and Swearing in .epub files

EPUB censor

Requires Python 3.8 or newer. Uses only the standard library; no pip install is needed.

Write a censored copy:

python censor.py input.epub output.epub

Preview matched expressions and counts by chapter without writing files:

python censor.py --preview input.epub

Run python censor.py --help for command-line help.

The script censors text in UTF-8 .xhtml, .html, and .htm entries while preserving markup, attributes, links, scripts, styles, and other archive entries. It recognizes phrases across inline tags and character references, prefers complete phrases over shorter overlapping matches, and always censors God, Jesus, and Christ. The f-word family censors any whole word containing the case-insensitive spelling fuck, including unlisted compounds and inflections. Existing spaced and hyphenated expressions are also matched; other families retain whole-word rules. It excludes text in document heads, templates, and explicitly hidden elements; it does not evaluate external stylesheets or render pages.

Summary counts retain the -word families and group smaller families as body-parts/functions, vulgar insults, and name-in-vain. The remaining family is labeled h*ll. Preview mode still lists the matched expressions by chapter.

Input and output must be different files, including symlink and hard-link aliases. The output replaces its destination only after the entire archive has been written successfully. Chapters that cannot be decoded or parsed are reported and copied unchanged.

Run the tests:

python -m unittest -v
#!/usr/bin/env python3
# Example usage:
#
# python censor.py book-with-profanity.epub book-censored.epub
# python censor.py --preview book-with-profanity.epub
#
import argparse
import html
import os
import re
import tempfile
import zipfile
from collections import Counter
from contextlib import ExitStack
from dataclasses import dataclass, field
from html.parser import HTMLParser
from pathlib import Path
families = {
"f-word": [
r"fuck[-\s]?(?:ups?|off|faces?|heads?|wads?|wits?)",
# Censor the entire word, including unlisted compounds and inflections.
r"\w*fuck\w*",
r"mother[-\s]?fuck(?:er|ers|ing)?",
r"dumb[-\s]?fuck(?:s|er|ers)?",
r"cluster[-\s]?fuck(?:s|ed|ing)?",
],
"s-word": [
r"shit(?:s|ted|ting|ty|tier|tiest|head|heads|face|faced|show|storm|bag|bags)?",
r"bull[-\s]?shit(?:s|ted|ting|ter|ters)?",
r"horse[-\s]?shit",
r"dog[-\s]?shit",
r"bat[-\s]?shit",
r"dip[-\s]?shit(?:s)?",
r"shit[-\s]?(?:head|heads|face|show|storm|bag|bags)",
],
"b-word": [
r"bitch(?:es|ed|ing|y|ier|iest)?",
r"son[-\s]?of[-\s]?a[-\s]?bitch",
r"bitch[-\s]?(?:ass|slap|fest)",
],
"d-word": [
r"damn(?:s|ed|ing|it)?",
r"god[-\s]?damn(?:s|ed|ing|it)?",
r"god[-\s]?dammit",
r"dammit",
],
"a-word": [
r"ass[-\s]?(?:holes?|hats?|wipes?|wads?|clowns?)",
r"ass(?:es|hole|holes|hat|hats|wipe|wipes|wad|wads|clown|clowns)?",
r"dumb[-\s]?ass(?:es)?",
r"smart[-\s]?ass(?:es|ed)?",
r"bad[-\s]?ass(?:es)?",
r"jack[-\s]?ass(?:es)?",
r"half[-\s]?ass(?:ed|ing)?",
r"hard[-\s]?ass(?:es)?",
r"kick[-\s]?ass",
r"fat[-\s]?ass(?:es)?",
],
"body-parts/functions": [
r"dicks?",
r"crap(?:s|ped|ping|py|pier|piest)?",
r"crap[-\s]?(?:head|shoot)",
r"piss(?:es|ed|ing|y)?",
r"piss[-\s]?(?:off|poor)",
r"penis(?:es)?",
r"puss(?:y|ies)",
r"cock(?:s)?",
r"cunt(?:s)?",
r"tit(?:s)?",
r"titt(?:y|ies)",
r"boob(?:s)?",
r"boob(?:ie|ies)",
r"cum(?:s|ming)?",
r"jizz",
r"blow[-\s]?jobs?",
r"hand[-\s]?jobs?",
r"boners?",
r"jack[-\s]?offs?",
r"jerk[-\s]?offs?",
],
"vulgar insults": [
r"dick[-\s]?(?:heads?|wads?|faces?)",
r"bastard(?:s|ized|izing)?",
r"douche[-\s]?bags?",
r"douches?",
r"pricks?",
r"sluts?",
r"whores?",
r"skanks?",
r"twats?",
],
# Includes ordinary references to God, Jesus, and Christ.
# Matching is unconditional for the intended nonreligious books.
"name-in-vain": [
r"god",
r"oh[-\s]+my[-\s]+god",
r"oh[-\s]+god",
r"my[-\s]+god",
r"good[-\s]+god",
r"dear[-\s]+god",
r"for[-\s]+god(?:'|’)?s[-\s]+sake",
r"god(?:'|’)?s[-\s]+sake",
r"god[-\s]?almighty",
r"jesus",
r"jesus[-\s]+christ",
r"jesus[-\s]+h[-.\s]*christ",
r"jesus[-\s]+fucking[-\s]+christ",
r"jesus[-\s]+freaking[-\s]+christ",
r"jesus[-\s]+frigging[-\s]+christ",
r"oh[-\s]+jesus",
r"sweet[-\s]+jesus",
r"dear[-\s]+jesus",
r"christ",
r"christ[-\s]+almighty",
r"christ[-\s]+on[-\s]+a[-\s]+bike",
r"christ[-\s]+on[-\s]+a[-\s]+cracker",
r"for[-\s]+christ(?:'|’)?s[-\s]+sake",
],
"h*ll": [
r"hell",
r"hell(?:ish|hole|holes)?",
r"what[-\s]+the[-\s]+hell",
r"where[-\s]+the[-\s]+hell",
r"who[-\s]+the[-\s]+hell",
r"why[-\s]+the[-\s]+hell",
r"how[-\s]+the[-\s]+hell",
r"go[-\s]+to[-\s]+hell",
r"hell[-\s]+no",
r"hell[-\s]+yes",
r"hell[-\s]+yeah",
r"hell[-\s]+of[-\s]+a",
r"like[-\s]+hell",
],
}
# Keep patterns separate so short alternatives cannot hide longer phrases.
compiled = [
(family, re.compile(r"(?<!\w)(?:" + pattern + r")(?!\w)", re.IGNORECASE))
for family, patterns in families.items()
for pattern in patterns
]
def censor_text(match):
"""
Replace letters/digits with repeating @#$!, while preserving
spaces, hyphens, apostrophes, and punctuation.
Examples:
fucking -> @#$!@#$
bull-shit -> @#$!-!@#$
Jesus Christ -> @#$!@ @#$!@#
"""
chars = "@#$!"
i = 0
result = []
for ch in match.group():
if ch.isalnum():
result.append(chars[i % len(chars)])
i += 1
else:
result.append(ch)
return "".join(result)
def find_matches(text):
"""Choose the earliest match, preferring the longest at that position."""
candidates = [
(match.start(), -match.end(), order, family, match)
for order, (family, rx) in enumerate(compiled)
for match in rx.finditer(text)
]
end = 0
for start, _, _, family, match in sorted(candidates):
if start >= end:
yield family, match
end = match.end()
def censor_plain_text(text, counts):
result = []
end = 0
for family, match in find_matches(text):
result.extend((text[end:match.start()], censor_text(match)))
counts[family] += 1
end = match.end()
result.append(text[end:])
return "".join(result)
class TextCensor(HTMLParser):
"""Locate visible text without reserializing or changing HTML markup."""
blocks = set("address article aside blockquote br caption dd div dl dt fieldset "
"figcaption figure footer form h1 h2 h3 h4 h5 h6 header hr li main "
"nav ol p pre section table tbody td tfoot th thead tr ul".split())
voids = set("area base br col embed hr img input link meta param source track wbr".split())
excluded = {"head", "script", "style", "template"}
def __init__(self, source, counts, matches=None):
super().__init__(convert_charrefs=False)
self.source = source
self.counts = counts
self.matches = matches
self.line_starts = [0] + [i + 1 for i, ch in enumerate(source) if ch == "\n"]
self.stack = []
self.characters = []
self.positions = []
self.edits = {}
def source_offset(self):
line, column = self.getpos()
return self.line_starts[line - 1] + column
def flush(self):
text = "".join(self.characters)
for family, match in find_matches(text):
self.counts[family] += 1
if self.matches is not None:
self.matches[re.sub(r"\s+", " ", match.group()).casefold()] += 1
replacement = censor_text(match)
for index, ch in enumerate(match.group()):
if ch.isalnum():
span = self.positions[match.start() + index]
self.edits[span] = self.edits.get(span, "") + replacement[index]
self.characters.clear()
self.positions.clear()
def handle_starttag(self, tag, attrs):
attributes = dict(attrs)
hidden = (tag in self.excluded or "hidden" in attributes
or (attributes.get("aria-hidden") or "").lower() == "true"
or bool(re.search(r"(?:display\s*:\s*none|visibility\s*:\s*hidden)",
attributes.get("style") or "", re.IGNORECASE)))
if tag in self.blocks or hidden:
self.flush()
if tag not in self.voids:
self.stack.append((tag, hidden or bool(self.stack and self.stack[-1][1])))
def handle_endtag(self, tag):
if tag in self.blocks:
self.flush()
for index in range(len(self.stack) - 1, -1, -1):
if self.stack[index][0] == tag:
if self.stack[index][1]:
self.flush()
del self.stack[index:]
break
def handle_startendtag(self, tag, attrs):
self.handle_starttag(tag, attrs)
self.handle_endtag(tag)
def handle_data(self, data):
if self.stack and self.stack[-1][1]:
return
start = self.source_offset()
self.characters.extend(data)
self.positions.extend((start + i, start + i + 1) for i in range(len(data)))
def reference(self):
if self.stack and self.stack[-1][1]:
return
start = self.source_offset()
reference = re.match(r"&(?:#[xX][0-9a-fA-F]+|#\d+|[a-zA-Z][a-zA-Z0-9]*);?",
self.source[start:]).group()
decoded = html.unescape(reference)
self.characters.extend(decoded)
if decoded == reference:
self.positions.extend((start + i, start + i + 1) for i in range(len(reference)))
else:
self.positions.extend([(start, start + len(reference))] * len(decoded))
def handle_entityref(self, name):
self.reference()
def handle_charref(self, name):
self.reference()
def result(self):
self.feed(self.source)
self.close()
self.flush()
result = []
end = 0
for (start, stop), replacement in sorted(self.edits.items()):
result.extend((self.source[end:start], replacement))
end = stop
result.append(self.source[end:])
return "".join(result)
def censor_html(source, counts, matches=None):
return TextCensor(source, counts, matches).result()
@dataclass
class Report:
counts: Counter = field(default_factory=Counter)
matches: dict = field(default_factory=dict)
skipped: list = field(default_factory=list)
def censor_epub(src, dst=None, preview=False):
"""Preview matches or atomically write a censored EPUB."""
src = Path(src)
if not preview:
if dst is None:
raise ValueError("An output EPUB is required unless --preview is used.")
dst = Path(dst)
if src.resolve() == dst.resolve() or (dst.exists() and src.samefile(dst)):
raise ValueError("Input and output must be different files.")
report = Report()
temporary = None
try:
with ExitStack() as stack:
zin = stack.enter_context(zipfile.ZipFile(src, "r"))
zout = None
if not preview:
with tempfile.NamedTemporaryFile(
dir=dst.parent, prefix=f".{dst.name}.", suffix=".tmp", delete=False,
) as handle:
temporary = Path(handle.name)
zout = stack.enter_context(zipfile.ZipFile(temporary, "w"))
# EPUB requires "mimetype" to be first and uncompressed.
if "mimetype" in zin.namelist():
zout.writestr(
"mimetype", zin.read("mimetype"),
compress_type=zipfile.ZIP_STORED,
)
for info in zin.infolist():
if info.filename == "mimetype":
continue
is_html = info.filename.lower().endswith((".xhtml", ".html", ".htm"))
if preview and not is_html:
continue
data = zin.read(info)
if is_html:
chapter_counts, matches = Counter(), Counter()
try:
text = data.decode("utf-8")
text = censor_html(text, chapter_counts, matches)
except UnicodeDecodeError:
report.skipped.append((info.filename, "not valid UTF-8"))
except (ValueError, AssertionError) as error:
report.skipped.append((info.filename, f"HTML parsing failed: {error}"))
else:
report.counts.update(chapter_counts)
if preview and matches:
report.matches[info.filename] = matches
data = text.encode("utf-8")
if zout is not None:
zout.writestr(info, data)
if not preview:
os.replace(temporary, dst)
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
return report
def print_summary(report, preview=False):
if preview:
print("\nMatches by chapter:")
if not report.matches:
print("No matches found.")
for chapter, matches in report.matches.items():
print(f"{chapter!r}:")
for term, count in sorted(matches.items()):
print(f" {term!r}: {count:,}")
print("\nMatch summary:" if preview else "\nReplacement summary:")
label_width = max(10, *(len(family) for family in families))
separator = "-" * (label_width + 7)
print(separator)
for family in families:
print(f"{family:{label_width}} {report.counts[family]:6,}")
print(separator)
print(f"{'TOTAL':{label_width}} {sum(report.counts.values()):6,}")
if report.skipped:
print(f"\nSkipped chapters ({len(report.skipped)}; copied unchanged when writing):")
for chapter, reason in report.skipped:
print(f" {chapter!r}: {reason}")
def main(argv=None):
parser = argparse.ArgumentParser(description="Censor profanity in an EPUB book.")
parser.add_argument("src", type=Path, help="input EPUB")
parser.add_argument("dst", type=Path, nargs="?", help="output EPUB (required unless previewing)")
parser.add_argument("--preview", action="store_true", help="report matches without writing an EPUB")
args = parser.parse_args(argv)
if args.dst is None and not args.preview:
parser.error("output EPUB is required unless --preview is used")
try:
report = censor_epub(args.src, args.dst, preview=args.preview)
except (OSError, ValueError, zipfile.BadZipFile, RuntimeError) as error:
parser.exit(1, f"{parser.prog}: {error}\n")
print(f"Previewed {args.src}" if args.preview else f"Wrote {args.dst}")
print_summary(report, preview=args.preview)
if __name__ == "__main__":
main()
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>f&#117;ck</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 &amp; f&#117;ck &lt;test&gt;</p>'
counts = Counter()
result = censor.censor_html(source, counts)
self.assertEqual(result, '<p>@#$!@ <em>#$!@#$!</em> @#$!@# &amp; @#$! &lt;test&gt;</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&nbsp;my\nGod &unknown; &fuck; &#x66;uck</p>'
result = censor.censor_html(source, counts)
self.assertEqual(result, '<p>@#&nbsp;$!\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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment