-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_hardcoded_urls.py
More file actions
85 lines (56 loc) · 2.2 KB
/
Copy pathtest_hardcoded_urls.py
File metadata and controls
85 lines (56 loc) · 2.2 KB
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
"""
Check if templates contain hardcoded URL's
Django Templates shouldn't have hardcoded URL's in them
the static tag.
"""
from re import findall
from os import walk, path
from configparser import ConfigParser
from os.path import dirname, abspath, join
from django.test import TestCase
# Load Config file
config = ConfigParser()
parent_dir = dirname(abspath(__file__))
config_file = join(parent_dir, 'config.ini')
config.read(config_file)
DEFAULT_EXCLUDED_FOLDERS = ['/node_modules', '/coverage']
try:
EXCLUDED_FOLDERS = config['Static Assets']['excluded_folders'].split(',')
EXCLUDED_FOLDERS += DEFAULT_EXCLUDED_FOLDERS
except KeyError:
UNWANTED_FIELDS = []
EXCLUDED_FOLDERS = DEFAULT_EXCLUDED_FOLDERS
HARDCODED_URLS_REGEX = r"<(link|script|img)+.*(href|src)+=[\"']((?!http|{|//)[^\s]+)[\"']"
class HardCodedURLTestCase(TestCase):
"""Test Case for Hardcoded URL's"""
pass
def filter_templates(templates):
"""Remove templates in EXCLUDED_FOLDERS."""
result = []
for template in templates:
if not any(folder in template for folder in EXCLUDED_FOLDERS):
result.append(template)
return result
def get_templates():
"""Walk the project root and return all templates."""
templates = []
for root, _, files in walk('.'):
for file in files:
if '.html' in file:
templates.append(path.join(root, file))
templates = filter_templates(templates)
return templates
for template in get_templates():
with open(template) as html_file:
content = html_file.read()
hardcoded_urls = findall(HARDCODED_URLS_REGEX, content)
# get the third capturing group for all matches
matches = [match[2] for match in hardcoded_urls]
def test_func(self, matches=matches):
"""Test function that's dynamically injected to the test case."""
self.assertEqual(len(matches), 0, matches)
test_name = 'test_{}_has_no_hardcoded_urls'.format(template)
test_doc = 'test that {} has no hardcoded urls'.format(template)
test_func.__name__ = test_name
test_func.__doc__ = test_doc
setattr(HardCodedURLTestCase, test_name, test_func)