"""Checks for margin.py, numbered as in CARD.md.

Run: uv run python -m unittest test_margin.py
Every terminal check drives a real pseudo-terminal (pty.fork) or tmux, never a mock.
"""

import ast
import fcntl
import os
import pty
import re
import select
import shlex
import shutil
import signal
import struct
import subprocess
import sys
import tempfile
import termios
import time
import unittest

import margin

HERE = os.path.dirname(os.path.abspath(__file__))
MARGIN = shlex.quote(os.path.join(HERE, "margin.py"))
BEL, ESC = b"\x07", b"\x1b"
FLASH_ON, FLASH_OFF = b"\x1b[?5h", b"\x1b[?5l"
REPAINT = b"\x1b[J"
LETTERS = "abcdefghijklmnopqrstuvwxyz"


def letters(n):
    return (LETTERS * 4)[:n]


def at(bells):
    """Positions (1 based) of the keys that rang."""
    return [i for i, b in enumerate(bells, 1) if b]


def say(*parts):
    """Prints what was observed, so the verbose run is its own evidence."""
    print("    observed:", *parts, file=sys.stderr)


class Pty:
    """A shell command under a real pseudo-terminal, driven one key at a time."""

    def __init__(self, command, cwd, size=True, env=None):
        pid, fd = pty.fork()
        if pid == 0:
            try:
                os.chdir(cwd)
                os.execvpe("sh", ["sh", "-c", command], env or os.environ)
            finally:
                os._exit(127)
        self.pid, self.fd, self.log, self.closed = pid, fd, bytearray(), False
        if size:  # a fresh pty reports 0 by 0
            fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 24, 80, 0, 0))

    def echo_on(self):
        return bool(termios.tcgetattr(self.fd)[3] & termios.ECHO)

    def read(self, until=b"", quiet=0.05, timeout=5.0):
        """Reads until `until` has arrived, then until the pty is quiet for `quiet` seconds."""
        start, deadline = len(self.log), time.monotonic() + timeout
        seen = not until
        while time.monotonic() < deadline and not self.closed:
            if seen and quiet == 0:
                break
            if select.select([self.fd], [], [], quiet if seen else 0.01)[0]:
                try:
                    data = os.read(self.fd, 4096)
                except OSError:  # EIO once the child side is closed
                    data = b""
                self.closed = not data
                self.log += data
                seen = seen or until in self.log[start:]
            elif seen:
                break
        new = bytes(self.log[start:])
        if not seen:
            raise AssertionError(f"waited for {until!r}, read {new!r}")
        return new

    def wait_raw(self, timeout=10.0):
        """Waits until the tool has switched ECHO off, so no key is echoed by cooked mode."""
        deadline = time.monotonic() + timeout
        while self.echo_on():
            if time.monotonic() > deadline:
                raise AssertionError("ECHO never went off")
            self.read(quiet=0.01, timeout=0.01)
        self.read(quiet=0.05)

    def key(self, data, echo=None):
        """Sends one key in its own write and returns what arrived for it."""
        if isinstance(data, str):
            data = data.encode()
        os.write(self.fd, data)
        return self.read(until=data if echo is None else echo)

    def finish(self, timeout=10.0):
        """Reads to the end and returns the exit code."""
        deadline = time.monotonic() + timeout
        while not self.closed and time.monotonic() < deadline:
            self.read(quiet=0.2, timeout=0.5)
        _, status = os.waitpid(self.pid, 0)
        os.close(self.fd)
        return os.waitstatus_to_exitcode(status)


class Tmux:
    """A private tmux server with one pane, for checks that need a real screen."""

    def __init__(self, command, cwd, cols, rows=10):
        self.sock, self.cwd = os.path.join(cwd, "tmux.sock"), cwd
        self.t("-f", "/dev/null", "new-session", "-d", "-x", str(cols), "-y", str(rows),
               "-c", cwd, command)
        self.t("set-option", "-g", "status", "off")
        self.pipe = os.path.join(cwd, "pane.bin")
        self.t("pipe-pane", "-O", f"cat >> {shlex.quote(self.pipe)}")
        self.tty = self.t("display-message", "-p", "#{pane_tty}").strip()

    def t(self, *args):
        return subprocess.run(["tmux", "-S", self.sock, *args], check=True,
                              capture_output=True, text=True).stdout

    def echo_on(self):
        fd = os.open(self.tty, os.O_RDONLY | os.O_NOCTTY)
        try:
            return bool(termios.tcgetattr(fd)[3] & termios.ECHO)
        finally:
            os.close(fd)

    def wait_echo(self, on, timeout=10.0):
        deadline = time.monotonic() + timeout
        while self.echo_on() != on:
            if time.monotonic() > deadline:
                raise AssertionError(f"ECHO never became {on}")
            time.sleep(0.01)

    def send(self, *keys, literal=False):
        self.t("send-keys", *(["-l"] if literal else []), *keys)
        time.sleep(0.2)

    def screen(self):
        return self.t("capture-pane", "-p").rstrip("\n").split("\n")

    def bells(self):
        try:
            with open(self.pipe, "rb") as f:
                return f.read().count(BEL)
        except FileNotFoundError:
            return 0

    def wait_out(self, timeout=10.0):
        """Waits for the tool to write its line; the pane closes when it exits."""
        path, deadline = os.path.join(self.cwd, "out.txt"), time.monotonic() + timeout
        while time.monotonic() < deadline:
            with open(path, "rb") as f:
                if f.read().endswith(b"\n"):
                    return
            time.sleep(0.05)
        raise AssertionError("no line in out.txt")

    def close(self):
        subprocess.run(["tmux", "-S", self.sock, "kill-server"], capture_output=True)


class Terminal(unittest.TestCase):
    def setUp(self):
        self.dir = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, self.dir, True)

    def out(self, name="out.txt"):
        with open(os.path.join(self.dir, name), "rb") as f:
            return f.read()

    def margin(self, args="", size=True, redirect="> out.txt"):
        s = Pty(f"{MARGIN} {args} {redirect}", self.dir, size=size)
        s.wait_raw()
        return s

    def type(self, s, text):
        return [s.key(c).count(BEL) for c in text]

    def test_01_02_bell_positions_and_no_readout(self):
        """1, 2: bells at 15, 20, 21, 22, 23; nothing else on the pty"""
        s = self.margin("20")
        bells = self.type(s, letters(23))
        s.key("\r", b"\r\n")
        self.assertEqual(s.finish(), 0)
        self.assertEqual(bells, [0] * 14 + [1] + [0] * 4 + [1, 1, 1, 1])
        self.assertEqual(self.out(), letters(23).encode() + b"\n")
        log = bytes(s.log)
        self.assertEqual(log.replace(BEL, b""), letters(23).encode() + b"\r\n")
        self.assertIsNone(re.search(rb"[0-9]", log))
        self.assertNotIn(ESC, log)
        say("run 1 rang at", at(bells), "out.txt", self.out(), "pty", log)

        s = self.margin("20")
        self.assertEqual(sum(self.type(s, letters(15))), 1)
        self.assertEqual(s.key("\x7f", REPAINT).count(BEL), 0)
        self.assertEqual(self.type(s, "o"), [1])  # n reaches 15 again
        self.assertEqual(self.type(s, "pqrst"), [0, 0, 0, 0, 1])
        self.assertEqual(s.key("\x7f", REPAINT).count(BEL), 0)
        self.assertEqual(self.type(s, "t"), [1])  # n reaches 20 again
        s.key("\r", b"\r\n")
        self.assertEqual(s.finish(), 0)
        self.assertEqual(self.out(), letters(20).encode() + b"\n")
        say("run 2 out.txt", self.out())

        s = self.margin("", size=False)  # window left at 0 by 0
        self.assertEqual(s.key("\x7f", b""), b"")  # empty line: nothing at all in 50 ms
        self.type(s, "abc")
        self.assertIn(REPAINT, s.key("\x7f", REPAINT))
        s.key("\r", b"\r\n")
        self.assertEqual(s.finish(), 0)
        self.assertEqual(self.out(), b"ab\n")
        say("run 3 (0 by 0) Backspace on empty line gave", b"", "out.txt", self.out(), "exit 0")

    def test_03_git_and_the_copies(self):
        """3: $(margin) in a real git commit, read back from log, format-patch, shortlog, alias"""
        bindir, repo = os.path.join(self.dir, "bin"), os.path.join(self.dir, "repo")
        os.mkdir(bindir)
        shutil.copy(os.path.join(HERE, "margin.py"), os.path.join(bindir, "margin"))
        os.chmod(os.path.join(bindir, "margin"), 0o755)
        env = dict(os.environ, PATH=bindir + os.pathsep + os.environ["PATH"],
                   GIT_CONFIG_GLOBAL=os.path.join(self.dir, "gitconfig"), GIT_CONFIG_NOSYSTEM="1",
                   GIT_AUTHOR_NAME="margin check", GIT_AUTHOR_EMAIL="check@example.invalid",
                   GIT_COMMITTER_NAME="margin check", GIT_COMMITTER_EMAIL="check@example.invalid")

        def git(*args):
            return subprocess.run(["git", *args], cwd=repo, env=env, check=True,
                                  capture_output=True, text=True).stdout

        subprocess.run(["git", "init", "-q", repo], env=env, check=True, capture_output=True)

        def commit(command, subject):
            s = Pty(command, repo, env=env)
            s.wait_raw()
            self.type(s, subject)
            s.key("\r", b"\r\n")
            self.assertEqual(s.finish(), 0)
            self.assertEqual(git("log", "-1", "--format=%s"), subject + "\n")
            body = git("log", "-1", "--format=%B")
            self.assertEqual(body.strip("\n"), subject)
            self.assertFalse(set(body) & {"\x07", "\x1b", "\r"})
            say(command, "->", repr(git("log", "-1", "--format=%s")))

        subject = "Fix the thing that was broken"
        commit('git commit --allow-empty -m "$(margin 30)"', subject)
        self.assertTrue(git("log", "--oneline").rstrip("\n").endswith(" " + subject))
        self.assertIn(f"Subject: [PATCH] {subject}\n", git("format-patch", "-1", "--stdout"))
        self.assertIn(f"      {subject}\n", git("shortlog", "HEAD"))
        say("oneline", repr(git("log", "--oneline")),
            "patch", [x for x in git("format-patch", "-1", "--stdout").splitlines()
                      if x.startswith("Subject:")],
            "shortlog", repr(git("shortlog", "HEAD")))

        with open(os.path.join(HERE, "README.md")) as f:
            alias = [line for line in f if line.startswith("git config --global alias.cm")]
        self.assertEqual(len(alias), 1)
        subprocess.run(["sh", "-c", alias[0]], env=env, check=True)
        commit("git cm --allow-empty", "Second line, by alias")

    def test_04_characters_not_bytes(self):
        """4: precomposed, decomposed and wide characters each count one"""
        for unit in ["\u00e9", "e\u0301", "\u5b57"]:
            s = self.margin("20")
            bells = [sum(s.key(c).count(BEL) for c in unit) for _ in range(15)]
            s.key("\r", b"\r\n")
            self.assertEqual(s.finish(), 0)
            self.assertEqual(bells, [0] * 14 + [1], unit)
            self.assertEqual(self.out(), (unit * 15).encode() + b"\n")
            say(ascii(unit), "rang at", at(bells), "out.txt", self.out())

    def test_05_editing_and_wrap(self):
        """5: a 20 column tmux pane, a 40 wide margin, repaint across wrapped rows"""
        tm = Tmux(f"echo margin 40; {MARGIN} 40 > out.txt", self.dir, cols=20)
        self.addCleanup(tm.close)
        tm.wait_echo(False)
        head = ["margin 40"]

        def shows(buf):
            return head + [buf[i:i + 20] for i in range(0, len(buf), 20)]

        for c in letters(45):
            tm.send(c, literal=True)
        self.assertEqual(tm.screen(), shows(letters(45)))
        self.assertEqual(tm.bells(), 7)  # 35, 40, then 41 to 45
        say("45 letters", tm.screen(), "bells", tm.bells())
        for n in range(44, 33, -1):  # through exactly 40, down to 34
            tm.send("BSpace")
            self.assertEqual(tm.screen(), shows(letters(n)), n)
            if n in (40, 34):
                say("after Backspace to", n, tm.screen())
        self.assertEqual(tm.bells(), 7)
        tm.send(letters(35)[-1], literal=True)
        self.assertEqual(tm.bells(), 8)  # n is 35 again
        for c in " ab":
            tm.send(c, literal=True)
        self.assertEqual(tm.bells(), 8)
        tm.send("C-w")
        self.assertEqual(tm.t("display-message", "-p", "#{cursor_x}").strip(), "16")
        self.assertEqual(tm.screen(), shows(letters(35)))
        say("Ctrl-W", tm.screen(), "cursor_x 16")
        tm.send("C-u")
        self.assertEqual(tm.screen(), head)
        self.assertEqual(tm.bells(), 8)
        for c in letters(20):
            tm.send(c, literal=True)
        tm.send("BSpace")
        self.assertEqual(tm.screen(), shows(letters(19)))
        say("20 then Backspace", tm.screen(), "bells", tm.bells())
        tm.send("Enter")
        tm.wait_out()
        self.assertEqual(self.out(), letters(19).encode() + b"\n")

    def test_06_withdraw_and_restore(self):
        """6: Ctrl-C, Ctrl-D empty, Ctrl-D with text; the terminal is cooked afterwards"""
        cases = [("abc", "\x03", b"\r\n", 130, b""), ("", "\x04", b"", 1, b""),
                 ("abc", "\x04", b"\r\n", 0, b"abc\n")]
        for text, last, echo, rc, out in cases:
            s = self.margin(redirect="> out.txt; echo rc=$?; stty -a")
            self.type(s, text)
            s.key(last, echo)
            s.finish()
            log = bytes(s.log).decode()
            self.assertIn(f"rc={rc}", log)
            self.assertEqual(self.out(), out)
            words = re.split(r"[\s;]+", log)
            for word in ("echo", "icanon"):
                self.assertIn(word, words)
                self.assertNotIn("-" + word, words)
            self.assertEqual("Line withdrawn." in log, rc == 130)
            say(repr(text + last), f"rc={rc}", "out.txt", self.out(),
                [w for w in words if w.lstrip("-") in ("echo", "icanon")])

    def test_07_paste(self):
        """7: one chunk is one bell; escapes inside a chunk are dropped; Return ends it"""
        s = self.margin()
        chunk = (letters(26) + " ") * 7 + letters(11)
        self.assertEqual(len(chunk), 200)
        got = s.key(chunk, chunk[-10:].encode())
        self.assertLessEqual(got.count(BEL), 1)
        say("200 character chunk: BEL bytes", got.count(BEL))
        s.key("\r", b"\r\n")
        self.assertEqual(s.finish(), 0)
        self.assertEqual(self.out(), chunk.encode() + b"\n")

        s = self.margin()
        s.key("abc\x1b[Adef", b"abcdef")
        s.key("\r", b"\r\n")
        self.assertEqual(s.finish(), 0)
        self.assertEqual(self.out(), b"abcdef\n")

        s = self.margin()
        os.write(s.fd, b"ab\rcd")
        self.assertEqual(s.finish(), 0)
        self.assertEqual(self.out(), b"ab\n")

        s = self.margin()
        os.write(s.fd, ESC)
        self.assertEqual(s.read(quiet=0.1), b"")  # a bare Esc echoes nothing
        s.key("b")
        s.key("\r", b"\r\n")
        self.assertEqual(s.finish(), 0)
        self.assertEqual(self.out(), b"b\n")
        say("arrow, Return mid chunk and bare Esc all held")

    def test_08_no_terminal(self):
        """8: a pipe, /dev/null and usage errors; no bell without a terminal"""
        s = Pty(f"printf 'hello\\n' | {MARGIN} > out.txt; echo rc=$?", self.dir)
        s.finish()
        self.assertEqual(self.out(), b"hello\n")
        self.assertIn(b"rc=0", s.log)
        self.assertNotIn(BEL, s.log)
        self.assertNotIn(BEL, self.out())

        def run(*args, stdin=None):
            return subprocess.run([os.path.join(HERE, "margin.py"), *args], stdin=stdin,
                                  capture_output=True, start_new_session=True)

        with open(os.devnull) as null:
            p = run(stdin=null)
        self.assertEqual((p.returncode, p.stdout), (1, b""))
        p = run("abc")
        self.assertEqual((p.returncode, p.stdout, p.stderr), (2, b"", b"margin: 'abc' is not a width.\n"))
        self.assertEqual(run("0").returncode, 2)
        say("pipe -> hello, /dev/null -> 1, abc ->", p.stderr, "0 -> 2")

    def test_09_flash(self):
        """9: --flash at the same moments, never delaying a key, never left on; --ring"""
        s = self.margin("--flash 20")
        for n, c in enumerate(letters(23), 1):
            got = s.key(c, FLASH_OFF if n in (15, 20, 21, 22, 23) else None)
            self.assertEqual(FLASH_ON in got, n in (15, 20, 21, 22, 23), n)
            if FLASH_ON in got:
                self.assertLess(got.index(FLASH_ON), got.index(FLASH_OFF))
        s.key("\r", b"\r\n")
        self.assertEqual(s.finish(), 0)
        self.assertNotIn(BEL, s.log)
        self.assertEqual((s.log.count(FLASH_ON), s.log.count(FLASH_OFF)), (5, 5))
        self.assertEqual(self.out(), letters(23).encode() + b"\n")
        say("flash on/off pairs", s.log.count(FLASH_ON), "BEL", s.log.count(BEL))

        s = self.margin("--flash 20")
        self.type(s, letters(14))
        os.write(s.fd, b"o")
        s.read(FLASH_ON, quiet=0)
        mark, lit = len(s.log), time.monotonic()
        time.sleep(0.01)
        os.write(s.fd, b"p")
        s.read(b"p", quiet=0)
        echoed = time.monotonic() - lit
        if FLASH_OFF not in s.log[mark:]:
            s.read(FLASH_OFF)
        tail = bytes(s.log[mark:])
        self.assertLess(tail.index(b"p"), tail.index(FLASH_OFF))  # the key is not held back
        say(f"16th key echoed {echoed * 1000:.0f} ms into the flash, flash off after it")
        s.key("\r", b"\r\n")
        self.assertEqual(s.finish(), 0)
        self.assertEqual(self.out(), letters(16).encode() + b"\n")

        s = self.margin("--flash 20")
        self.type(s, letters(14))
        os.write(s.fd, b"o")
        s.read(FLASH_ON, quiet=0)
        os.write(s.fd, b"\x03")
        self.assertEqual(s.finish(), 130)
        tail = bytes(s.log[s.log.index(FLASH_ON):])
        self.assertIn(FLASH_OFF, tail)
        self.assertEqual(self.out(), b"")

        footnote = margin.FOOTNOTE[False].encode()
        s = Pty(f"{MARGIN} --ring > out.txt", self.dir)
        self.assertEqual(s.finish(), 0)
        self.assertEqual(s.log.count(BEL), 1)
        self.assertIn(footnote, s.log)
        self.assertEqual(self.out(), b"")
        s = Pty(f"{MARGIN} --ring > out.txt 2> err.txt", self.dir)
        self.assertEqual(s.finish(), 0)
        self.assertEqual(s.log.count(BEL), 1)
        self.assertNotIn(footnote, s.log)
        self.assertEqual(self.out("err.txt"), b"")
        s = Pty(f"{MARGIN} --ring --flash > out.txt", self.dir)
        self.assertEqual(s.finish(), 0)
        self.assertNotIn(BEL, s.log)
        self.assertLess(s.log.index(FLASH_ON), s.log.index(FLASH_OFF))
        say("--ring --flash", bytes(s.log))

    def test_13_start_margin(self):
        """13: keys typed while the tool starts are kept, and shown once"""
        tm = Tmux(f"sleep 1; {MARGIN} 20 > out.txt", self.dir, cols=80)
        self.addCleanup(tm.close)
        self.assertTrue(tm.echo_on())
        tm.send("Early ", literal=True)
        tm.wait_echo(False)
        for c in "bird":
            tm.send(c, literal=True)
        screen = [row for row in tm.screen() if row.strip()]
        self.assertEqual(screen[-1], "Early bird")
        self.assertEqual("\n".join(screen).count("Early"), 1)
        tm.send("Enter")
        tm.wait_out()
        self.assertEqual(self.out(), b"Early bird\n")
        say("screen", screen, "out.txt", self.out())

    def test_14_sigterm(self):
        """SIGTERM during a flash: the flash comes off and the terminal is restored"""
        s = Pty(f"trap '' TERM; {MARGIN} --flash 20 > out.txt; echo rc=$?; stty -a", self.dir)
        s.wait_raw()
        self.type(s, letters(14))
        os.write(s.fd, b"o")
        s.read(FLASH_ON, quiet=0)
        os.killpg(s.pid, signal.SIGTERM)
        s.finish()
        log = bytes(s.log)
        self.assertIn(FLASH_OFF, log[log.index(FLASH_ON):])
        self.assertIn(b"rc=143", log)
        words = re.split(rb"[\s;]+", log)
        self.assertIn(b"echo", words)
        self.assertIn(b"icanon", words)
        say("rc=143, flash off after on, echo and icanon restored")


class HouseRules(unittest.TestCase):
    def read(self, name):
        with open(os.path.join(HERE, name), encoding="utf-8") as f:
            return f.read()

    def test_10_house_rules(self):
        """10: no long dash, no spaced double hyphen, stdlib only, a narrow plain --help"""
        dash, spaced = "\u2014", " " + "-" * 2 + " "
        for name in ("margin.py", "README.md", "test_margin.py"):
            text = self.read(name)
            self.assertNotIn(dash, text, name)
            self.assertNotIn(spaced, text, name)
        tree = ast.parse(self.read("margin.py"))
        names = {a.name.split(".")[0] for n in ast.walk(tree) if isinstance(n, ast.Import)
                 for a in n.names}
        names |= {n.module.split(".")[0] for n in ast.walk(tree)
                  if isinstance(n, ast.ImportFrom)}
        self.assertTrue(names <= set(sys.stdlib_module_names), names)
        p = subprocess.run([os.path.join(HERE, "margin.py"), "--help"], capture_output=True)
        self.assertEqual(p.returncode, 0)
        self.assertNotIn(ESC, p.stdout)
        for line in p.stdout.decode().splitlines():
            self.assertLess(len(line), 60, line)
        self.assertIn("No counter is supplied.", p.stdout.decode())

    def test_11_the_card(self):
        """11: install line, alias line, parts 1 to 4 in order, narrow, no n/m readout"""
        text = self.read("README.md")
        lines = text.splitlines()
        self.assertIn("PATH as margin", lines[0])
        self.assertTrue(lines[1].startswith("git config --global alias.cm "))
        parts = ["1. Margin stop", "2. Margin bell", "3. Carriage return", "4. Line release"]
        at = [next(i for i, line in enumerate(lines) if line.startswith(p)) for p in parts]
        self.assertEqual(at, sorted(at))
        for line in lines:
            self.assertLess(len(line), 60, line)
        self.assertIsNone(re.search(r"\d+\s*/\s*\d+", text))


class Core(unittest.TestCase):
    def bells(self, width, text):
        buf, out = "", []
        for c in text:
            buf, b = margin.press(buf, c, width)
            out.append(b)
        return out

    def test_12_core(self):
        """12: the pure editor, the chunk split and the row walk"""
        self.assertEqual(self.bells(1, "ab"), [1, 1])
        self.assertEqual(self.bells(2, "abc"), [1, 1, 1])
        self.assertEqual(self.bells(6, "abcdefg"), [1, 0, 0, 0, 0, 1, 1])
        self.assertEqual(self.bells(20, letters(25)), [0] * 14 + [1] + [0] * 4 + [1] * 6)
        self.assertEqual(self.bells(20, letters(14) + "\u0301" + "o"), [0] * 15 + [1])
        self.assertEqual(margin.count("e\u0301" * 3), 3)
        self.assertEqual(margin.press("ab", "\u0301", 3), ("ab\u0301", 0))

        word = letters(26) + letters(9)
        self.assertEqual(margin.press(word + " ab", "\x17", 40), (word + " ", 0))
        self.assertEqual(margin.press(word + "  ", "\x17", 40), ("", 0))
        self.assertEqual(margin.press("ae\u0301", "\x7f", 40), ("a", 0))
        self.assertEqual(margin.press("", "\x7f", 40), ("", 0))
        self.assertEqual(margin.press("abc", "\x15", 40), ("", 0))

        split = margin.split_keys
        self.assertEqual(split("a\x1b[Ab"), ["a", "b"])
        self.assertEqual(split("\x1b[1;5Cz"), ["z"])
        self.assertEqual(split("\x1bOP"), [])
        self.assertEqual(split("x\x1bby"), ["x", "y"])
        self.assertEqual(split("a\x1b"), ["a"])
        self.assertEqual(split("b"), ["b"])
        self.assertEqual(split("\t\x01"), [])
        self.assertEqual(split("\x08\x7f\x15\x17\r\x03\x04"),
                         ["\x7f", "\x7f", "\x15", "\x17", "\r", "\x03", "\x04"])

        rows = margin.rows
        self.assertEqual(rows("e\u0301" * 20, 20), 1)
        self.assertEqual(rows(letters(19) + "\u5b57", 20), 2)
        self.assertEqual(rows(letters(20), 20), 1)
        self.assertEqual(rows(letters(40), 20), 2)
        self.assertEqual(rows(letters(41), 20), 3)
        self.assertEqual(rows(letters(200), 0), 1)
        self.assertEqual(margin.parse(["50", "--flash"]), (50, True, False))
        self.assertIsNone(margin.parse(["--help"]))


if __name__ == "__main__":
    unittest.main()
