1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4#
5# Copyright 2017, Data61
6# Commonwealth Scientific and Industrial Research Organisation (CSIRO)
7# ABN 41 687 119 230.
8#
9# This software may be distributed and modified according to the terms of
10# the BSD 2-Clause license. Note that NO WARRANTY is provided.
11# See "LICENSE_BSD2.txt" for details.
12#
13# @TAG(DATA61_BSD)
14#
15
16'''
17Test harness for running jinja_lint.py across the templates.
18'''
19
20from __future__ import absolute_import, division, print_function, \
21    unicode_literals
22
23import os, re, subprocess, sys, unittest
24
25ME = os.path.abspath(__file__)
26
27# Make CAmkES importable
28sys.path.append(os.path.join(os.path.dirname(ME), '../../..'))
29
30from camkes.internal.tests.utils import CAmkESTest
31
32class TestLint(CAmkESTest):
33    def setUp(self):
34        super(TestLint, self).setUp()
35        self.lint = os.path.join(os.path.dirname(ME),
36            '../../../tools/jinja_lint.py')
37        self.assertTrue(os.access(self.lint, os.X_OK),
38            'jinja_lint.py not found or not executable')
39
40def _lint(self, path):
41    '''
42    Generic lint invoker that we'll curry below.
43    '''
44    p = subprocess.Popen([self.lint, '--block-start=/*-', '--block-end=-*/',
45        '--variable-start=/*?', '--variable-end=?*/', '--comment-start=/*#',
46        '--comment-end=#*/', path], stdout=subprocess.PIPE,
47        stderr=subprocess.PIPE, universal_newlines=True)
48    _, stderr = p.communicate()
49    self.assertEqual(p.returncode, 0, stderr)
50
51regex = re.compile(r'[^\w]')
52template_dir = os.path.abspath(os.path.join(os.path.dirname(ME), '..'))
53tests_dir = os.path.dirname(ME)
54
55# Find all the templates.
56for root, _, filenames in os.walk(template_dir):
57
58    if root.startswith(tests_dir):
59        # Don't analyse the test files.
60        continue
61
62    # For each template, monkey patch a test for it onto the test class.
63    for f in filenames:
64        if f.endswith('.swp'):
65            # Skip vim lock files.
66            continue
67        name = 'test_%s' % regex.sub('_', f)
68        path = os.path.join(root, f)
69        setattr(TestLint, name, lambda self, path=path: _lint(self, path))
70
71if __name__ == '__main__':
72    unittest.main()
73