summaryrefslogtreecommitdiff
path: root/tests/test_build.py
blob: e1511968163ad61e1dea568bb86026477606cdbf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# -*- coding: utf-8 -*-
"""
    test_build
    ~~~~~~~~~~

    Test the entire build process with the test root.

    :copyright: 2008 by Georg Brandl.
    :license: BSD.
"""

import os
import difflib
import htmlentitydefs
from StringIO import StringIO
from subprocess import Popen, PIPE

from util import *
from etree13 import ElementTree as ET

from sphinx.builder import StandaloneHTMLBuilder, LaTeXBuilder
from sphinx.latexwriter import LaTeXTranslator


html_warnfile = StringIO()
latex_warnfile = StringIO()

ENV_WARNINGS = """\
WARNING: %(root)s/images.txt:9: Image file not readable: foo.png
WARNING: %(root)s/images.txt:20: Nonlocal image URI found: http://www.python.org/logo.png
WARNING: %(root)s/includes.txt:: (WARNING/2) Encoding 'utf-8' used for reading included file u'wrongenc.inc' seems to be wrong, try giving an :encoding: option
"""

HTML_WARNINGS = ENV_WARNINGS + """\
WARNING: %(root)s/images.txt:: no matching candidate for image URI u'foo.*'
"""

LATEX_WARNINGS = ENV_WARNINGS + """\
WARNING: None:: no matching candidate for image URI u'foo.*'
"""

HTML_XPATH = {
    'images.html': {
        ".//img[@src='_images/img.png']": '',
        ".//img[@src='_images/img1.png']": '',
    },
    'includes.html': {
        ".//pre/span[@class='s']": u'üöä',
        ".//pre": u'Max Strauß',
    },
}

class NslessParser(ET.XMLParser):
    """XMLParser that throws away namespaces in tag names."""

    def _fixname(self, key):
        try:
            return self._names[key]
        except KeyError:
            name = key
            br = name.find('}')
            if br > 0:
                name = name[br+1:]
            self._names[key] = name = self._fixtext(name)
            return name


@with_app(buildername='html', warning=html_warnfile)
def test_html(app):
    app.builder.build_all()
    html_warnings = html_warnfile.getvalue().replace(os.sep, '/')
    html_warnings_exp = HTML_WARNINGS % {'root': app.srcdir}
    assert html_warnings == html_warnings_exp, 'Warnings don\'t match:\n' + \
           '\n'.join(difflib.ndiff(html_warnings_exp.splitlines(),
                                   html_warnings.splitlines()))

    if not ET:
        return
    for fname, paths in HTML_XPATH.iteritems():
        parser = NslessParser()
        parser.entity.update(htmlentitydefs.entitydefs)
        etree = ET.parse(os.path.join(app.outdir, fname), parser)
        for path, text in paths.iteritems():
            nodes = list(etree.findall(path))
            assert nodes != []
            if not text:
                # only check for node presence
                continue
            for node in nodes:
                if node.text and text in node.text:
                    break
            else:
                assert False, ('%r not found in any node matching '
                               'path %s in %s' % (text, path, fname))


@with_app(buildername='latex', warning=latex_warnfile)
def test_latex(app):
    LaTeXTranslator.ignore_missing_images = True
    app.builder.build_all()
    latex_warnings = latex_warnfile.getvalue().replace(os.sep, '/')
    latex_warnings_exp = LATEX_WARNINGS % {'root': app.srcdir}
    assert latex_warnings == latex_warnings_exp, 'Warnings don\'t match:\n' + \
           '\n'.join(difflib.ndiff(latex_warnings_exp.splitlines(),
                                   latex_warnings.splitlines()))

    # now, try to run latex over it
    cwd = os.getcwd()
    os.chdir(app.outdir)
    try:
        try:
            p = Popen(['pdflatex', '--interaction=nonstopmode', 'SphinxTests.tex'],
                      stdout=PIPE, stderr=PIPE)
        except OSError, err:
            pass  # most likely pdflatex was not found
        else:
            stdout, stderr = p.communicate()
            if p.returncode != 0:
                print stdout
                del app.cleanup_trees[:]
                assert False, 'latex exited with error'
    finally:
        os.chdir(cwd)

# just let the remaining ones run for now

@with_app(buildername='linkcheck')
def test_linkcheck(app):
    app.builder.build_all()

@with_app(buildername='text')
def test_text(app):
    app.builder.build_all()

@with_app(buildername='changes', cleanenv=True)
def test_changes(app):
    app.builder.build_all()