~nskaggs/help-app/functional-test-template

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
import codecs
from html.parser import HTMLParser
import os
import shutil
import subprocess
import tempfile
from unittest import TestCase
import urllib.parse

from translations.utils import use_top_level_dir


def require_build(build):
    tempdir = tempfile.mkdtemp()
    env = {}
    if build == 'app':
        env = {'OUTPUTDIR_APP': tempdir}
    if build == 'web':
        env = {'OUTPUTDIR_WEB': tempdir}
    pwd = use_top_level_dir()
    ret = subprocess.call(['make', '-es', build], env=env)
    os.chdir(pwd)
    return (ret, tempdir)


def clean_tempdir(tempdir):
    if os.path.exists(tempdir):
        shutil.rmtree(tempdir)


class MyHTMLParser(HTMLParser):
    links = []

    def handle_starttag(self, tag, attrs):
        if tag == "a":
            for name, value in attrs:
                if name == "href":
                    url = urllib.parse.urlparse(value)
                    if not value.startswith('#') and \
                       url.netloc in [None, '', 'localhost']:
                        self.links += [value]

    def reload(self):
        links = self.links
        self.links = []
        return links


class HelpTestCase(TestCase):
    def __init__(self, *args):
        self.pwd = os.getcwd()
        self.htmlparser = MyHTMLParser()
        TestCase.__init__(self, *args)

    def __del__(self):
        os.chdir(self.pwd)

    def _test_local_links(self, build):
        (ret, tempdir) = require_build(build)
        if ret:
            return False
        for dirpath, dirnames, filenames in os.walk(tempdir):
            for fn in filenames:
                full_fn = os.path.join(dirpath, fn)
                os.chdir(dirpath)
                if full_fn.endswith('.html'):
                    html = codecs.open(full_fn, encoding='utf-8').read()
                    self.htmlparser.feed(html)
                links = self.htmlparser.reload()
                for link in links:
                    rel_path = os.path.relpath(link, full_fn)
                    path = os.path.normpath(os.path.join(full_fn, rel_path))
                    self.assertTrue(os.path.exists(path))
        clean_tempdir(tempdir)
        return True

    def test_local_phone_links(self):
        return self._test_local_links('html')

    def test_local_web_links(self):
        return self._test_local_links('web')