Exemplo n.º 1
0
def test_links(tmpdir):
    with tmpdir.as_cwd():
        Path("test.ini").write_text('''
[links]
next-url=https://example.com
next-title=The Next Document
mylink-title=AnotherTitle
''')
        config = defaultConfig()
        config.read("test.ini")

        parser = ArgumentParser()
        config.registerArgparse(parser)
        data = vars(
            parser.parse_args([
                "--link", "prev", "https://example.com/2", "Prev Document",
                "--link", "secondlink", "ATitle"
            ]))
        config.updateFromDict(data)

        assert config["links"]["links"] == {
            "next-url": "https://example.com",
            "next-title": "The Next Document",
            "mylink-title": "AnotherTitle",
            "prev-url": "https://example.com/2",
            "prev-title": "Prev Document",
            "secondlink-title": "ATitle",
        }
Exemplo n.º 2
0
def test_package_resource(tmpdir):
    config = defaultConfig()
    config['general'].data['packages-dirs'].value = [
        str(Path(__file__).parent)
    ]
    addConfig(config)
    doc = TeXDocument(config=config)
    tex = TeX(doc)
    tex.input("""
            \\documentclass{article}
            \\usepackage{examplePackage}
            \\begin{document}
            \\emph{Hello}
            \\end{document}""")

    doc = tex.parse()
    doc.userdata['working-dir'] = os.path.dirname(__file__)

    with tmpdir.as_cwd():
        Renderer().render(doc)

    assert tmpdir.join('styles', 'test.css').isfile()
    assert tmpdir.join('js', 'test.js').isfile()
    assert 'class="em"' in tmpdir.join('index.html').read()
    assert doc.userdata['testing'] == 'test'
Exemplo n.º 3
0
def test_charsub():
    config = defaultConfig()

    doc = TeXDocument(config=config)
    tex = TeX(doc)

    p = tex.input(r'''{``'' '---}''').parse()[0]
    p.paragraphs()
    assert p.textContent == "“” ’—"
Exemplo n.º 4
0
def test_modify_charsub():
    config = defaultConfig()
    config["document"]["disable-charsub"] = ["'"]

    doc = TeXDocument(config=config)
    tex = TeX(doc)

    p = tex.input(r'''{``'' '---}''').parse()[0]
    p.paragraphs()
    assert p.textContent == "“” '—"
Exemplo n.º 5
0
def test_interpolate():
    config = defaultConfig()
    config["general"]["renderer"] = "HTML5"
    config["files"]["split-level"] = 5
    config["general"]["theme"] = "%(renderer)s-%%-theme-%(split-level)d"
    assert config["general"]["theme"] == "HTML5-%-theme-5"

    config["document"]["disable-charsub"] = [
        "%(renderer)s-foo", "%(theme)s-bar"
    ]
    assert config["document"]["disable-charsub"] == [
        "HTML5-foo", "HTML5-%-theme-5-bar"
    ]
Exemplo n.º 6
0
 def __init__(self, name='', *args, **kwargs):
     _Logger.__init__(self, name, *args, **kwargs)
     self.propagate = 0
     level = locals().get(defaultConfig()['logging']['logging'].get(name))
     if not name:
         handler = StreamHandler()
         handler.setFormatter(StreamFormatter(ROOT_LOG_FORMAT))
     elif name in ['status', '(status)']:
         handler = StatusHandler()
         handler.setFormatter(StreamFormatter(STATUS_FORMAT))
         level = INFO
     else:
         handler = StreamHandler()
         handler.setFormatter(StreamFormatter(LOG_FORMAT))
     self.addHandler(handler)
     if level is not None:
         self.setLevel(level)
Exemplo n.º 7
0
def run(f: Path, target_dir: str, options={}):
    f = f.absolute()  # We will later change directories
    source_dir = f.parent

    if f.suffix != ".tex":
        raise ValueError("{} does not have extension .tex".format(f))

    print("Compiling {}".format(f.name))

    cwd = Path.cwd()
    os.chdir(str(source_dir))

    with TemporaryDirectory() as tmp_dir:
        config = defaultConfig()
        addConfig(config)

        config["images"]["imager"] = "gspdfpng"
        config["images"]["vector-imager"] = "pdf2svg"
        config["images"]["scale-factor"] = 1.4
        config["general"]["renderer"] = "CustomRenderer"
        config["general"]["load-tex-packages"] = False
        config["general"]["plugins"] = ["plugin"]
        config["files"]["directory"] = tmp_dir
        config["document"]["disable-charsub"] = "'"

        for key, value in options.items():
            config["custom"][key] = value

        run_(f.name, config)

        mkpath(target_dir)
        rm_tree(target_dir)
        copy_tree(tmp_dir, target_dir)
        shutil.copy(f.name, target_dir)
        try:
            shutil.copy(f.stem + ".pdf", target_dir)
        except OSError:
            pass

        try:
            os.remove(f.stem + ".paux")
        except OSError:
            pass

    os.chdir(str(cwd))
Exemplo n.º 8
0
def test_logging(tmpdir):
    with tmpdir.as_cwd():
        Path("test.ini").write_text('''
[logging]
parse.environments=DEBUG
''')
        config = defaultConfig()
        config.read("test.ini")

        parser = ArgumentParser()
        config.registerArgparse(parser)
        data = vars(parser.parse_args(["--logging", "test", "INFO"]))
        config.updateFromDict(data)

        assert config["logging"]["logging"] == \
                {
                    "parse.environments": "DEBUG",
                    "test": "INFO",
                }
Exemplo n.º 9
0
    def runDocument(packages='', content=''):
        """
        Compile a document with the given content

        Arguments:
        packages - string containing comma separated packages to use
        content - string containing the content of the document

        Returns: TeX document

        """

        doc = TeXDocument(config=defaultConfig())
        tex = TeX(doc)
        tex.disableLogging()
        tex.input(r'''
                \documentclass{article}
                \usepackage{%s}
                \begin{document}%s\end{document}''' % (packages, content))
        doc = tex.parse()
        doc.userdata['working-dir'] = os.path.dirname(__file__)
        return doc
Exemplo n.º 10
0
def test_amsthm(tmpdir):
    root = Path(__file__).parent
    config = defaultConfig()
    addConfig(config)
    config['files']['split-level'] = -100
    tex = TeX(TeXDocument(config=config))
    tex.input((root / 'source.tex').read_text())
    doc = tex.parse()
    doc.userdata['working-dir'] = Path(__file__).parent

    with tmpdir.as_cwd():
        Renderer().render(doc)

    css = Path(tmpdir) / 'styles' / 'amsthm.css'
    css_bench = root / 'benchmark.css'
    html = Path(tmpdir) / 'index.html'
    html_bench = root / 'benchmark.html'
    assert html.exists()
    text = re.sub('id="[^"]*"', '', html.read_text())
    bench = re.sub('id="[^"]*"', '', html_bench.read_text())
    assert text.strip() == bench.strip()
    assert css.exists()
    assert css.read_text() == css_bench.read_text()
Exemplo n.º 11
0
def test_counter(tmpdir):
    with tmpdir.as_cwd():
        Path("test.ini").write_text('''
[counters]
chapter=4
part=2
''')
        config = defaultConfig()
        config.read("test.ini")

        parser = ArgumentParser()
        config.registerArgparse(parser)
        data = vars(
            parser.parse_args(
                ["--counter", "section", "4", "--counter", "subsection", "7"]))
        config.updateFromDict(data)

        assert config["counters"]["counters"] == \
                {
                    "chapter": 4,
                    "part": 2,
                    "section": 4,
                    "subsection": 7
                }
Exemplo n.º 12
0
 def __init__(self, name):
     self.name = name
     self.filename = '%s.tex' % name
     self.config = defaultConfig()
     self.config['general']['renderer'] = 'Epub'
     self.config['general']['theme'] = 'default'
Exemplo n.º 13
0
def test_interpolate_fail():
    config = defaultConfig()
    config["general"]["theme"] = "%(nonexistent)s"
    with pytest.raises(KeyError):
        x = config["general"]["theme"]
Exemplo n.º 14
0
def test_interpolate_recursion():
    config = defaultConfig()
    config["general"]["theme"] = "%(renderer)s"
    config["general"]["renderer"] = "%(theme)s"
    with pytest.raises(RecursionError):
        x = config["general"]["theme"]
Exemplo n.º 15
0
def test_tikz(tmpdir):
    try:
        tmpdir = Path(tmpdir)
    except TypeError:  # Fallback for older python
        tmpdir = Path(str(tmpdir))

    root = Path(__file__).parent
    test_id = "tikz-pdf2svg-gspdfpng"

    benchdir = root / "benchmarks" / test_id
    newdir = root / "new" / test_id

    images = [
        "images/img-0001.svg", "images/img-0002.svg", "images/img-0001.png",
        "images/img-0002.png"
    ]

    config = defaultConfig()
    config['images']['vector-imager'] = 'pdf2svg'
    config['images']['imager'] = 'gspdfpng'

    doc = TeXDocument(config=config)
    tex = TeX(doc)

    tex.input(r'''
    \documentclass{article}
    \usepackage{tikz}
    \usepackage{tikz-cd}
    \begin{document}
    \begin{tikzpicture}
        \draw (0, 0) -- (0, 2) -- (2, 0) -- (0, 0);
    \end{tikzpicture}

    \begin{tikzcd}
        A \ar[r, "i"] & B \ar[d, "p"] \\ & C
    \end{tikzcd}
    \end{document}
    ''')

    renderer = Renderer()

    def render_image(obj):
        return "{}\n{}\n".format(obj.vectorImage.url, obj.image.url)

    renderer["tikzpicture"] = render_image
    renderer["tikzcd"] = render_image

    cwd = os.getcwd()
    os.chdir(str(tmpdir))
    renderer.render(tex.parse())
    os.chdir(cwd)

    def new_file(base: str):
        newfile = newdir / base
        newfile.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy(str(tmpdir / base), str(newfile))

    # Compare image output
    error = False

    try:
        if not filecmp.cmp(
                str(tmpdir / "index"), str(benchdir / "index"), shallow=False):
            print('Differences were found: index', file=sys.stderr)
            error = True
            new_file("index")

    except FileNotFoundError as e:
        error = True
        if e.filename == str(tmpdir / "index"):
            print("Missing output file: index", file=sys.stderr)
        else:
            print("Missing benchmark file: index", file=sys.stderr)
            new_file("index")

    for f in images:
        if not (tmpdir / f).exists():
            error = True
            print('Missing output file: %s' % f, file=sys.stderr)
        elif not (benchdir / f).exists():
            error = True
            print('Missing benchmark file: %s' % f, file=sys.stderr)
            new_file(f)

        diff = cmp_img(str(tmpdir / f), str(benchdir / f))
        if diff > 0.0001:
            error = True
            print('Differences were found: {} ({})'.format(f, diff),
                  file=sys.stderr)
            new_file(f)

    if error:
        assert False