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'''
17Tests that look for incorrect Python idioms in 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 TestBadIdioms(CAmkESTest):
33    pass
34
35def _string_addition(self, path):
36    '''
37    Look for string addition instead of using format strings.
38    '''
39    regex = re.compile(r'(\'.*?\'\s*\+|\+\s*\'.*?\')')
40    with open(path, 'rt') as f:
41        for lineno, line in enumerate(f, 1):
42            if regex.search(line) is not None:
43                self.fail('%s:%d: %s\nstring addition instead of format string?'
44                    % (path, lineno, line))
45
46regex = re.compile(r'[^\w]')
47template_dir = os.path.abspath(os.path.join(os.path.dirname(ME), '..'))
48tests_dir = os.path.dirname(ME)
49
50# Find all the templates.
51for root, _, filenames in os.walk(template_dir):
52
53    if root.startswith(tests_dir):
54        # Don't analyse the test files.
55        continue
56
57    # For each template, monkey patch a test for it onto the test class.
58    for f in filenames:
59        if f.endswith('.swp') or f.endswith('.py'):
60            # Skip vim lock files.
61            continue
62        name = 'test_%s' % regex.sub('_', f)
63        path = os.path.join(root, f)
64        setattr(TestBadIdioms, name, lambda self, path=path: _string_addition(self, path))
65
66if __name__ == '__main__':
67    unittest.main()
68