-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
bigquery_test.py
executable file
·156 lines (134 loc) · 5.27 KB
/
bigquery_test.py
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#!/usr/bin/env python3
# Copyright 2017 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for bigquery.py"""
import argparse
import os
import re
import shutil
import sys
import tempfile
import unittest
import ruamel.yaml as yaml
import bigquery
class TestBigquery(unittest.TestCase):
"""Tests the bigquery scenario."""
def test_configs(self):
"""All yaml files in metrics are valid."""
config_metrics = set()
for path in bigquery.all_configs(search='**'):
name = os.path.basename(path)
if name in ['BUILD', 'BUILD.bazel', 'README.md']:
continue
if not path.endswith('.yaml'):
self.fail('Only .yaml files allowed: %s' % path)
with open(path) as config_file:
try:
config = yaml.safe_load(config_file)
except yaml.YAMLError:
self.fail(path)
self.assertIn('metric', config)
self.assertIn('query', config)
self.assertIn('jqfilter', config)
self.assertIn('description', config)
metric = config['metric'].strip()
bigquery.validate_metric_name(metric)
config_metrics.add(metric)
configs = bigquery.all_configs()
self.assertTrue(all(p.endswith('.yaml') for p in configs), configs)
# Check that the '**' search finds the same number of yaml
# files as the default search.
self.assertEqual(len(configs), len(config_metrics), "verify the `metric` feild is unique")
# Check that config files correlate with metrics listed in
# test-infra/metrics/README.md.
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file:
readme = readme_file.read()
readme_metrics = set(re.findall(
r'\(http://storage\.googleapis\.com/k8s-metrics/([\w-]+)-latest\.json\)',
readme,
))
missing = config_metrics - readme_metrics
if missing:
self.fail(
'test-infra/metrics/README.md is missing entries for metrics: %s.'
% ', '.join(sorted(missing)),
)
extra = readme_metrics - config_metrics
if extra:
self.fail(
'test-infra/metrics/README.md includes metrics that are missing config files: %s.'
% ', '.join(sorted(extra)),
)
# Check that all configs are linked in readme.
self.assertTrue(all(os.path.basename(p) in readme for p in configs))
def test_jq(self):
"""do_jq executes a jq filter properly."""
def check(expr, data, expected):
"""Check a test scenario."""
with open(self.data_filename, 'w') as data_file:
data_file.write(data)
bigquery.do_jq(
expr,
self.data_filename,
self.out_filename,
jq_bin=ARGS.jq,
)
with open(self.out_filename) as out_file:
actual = out_file.read().replace(' ', '').replace('\n', '')
self.assertEqual(actual, expected)
check(
expr='.',
data='{ "field": "value" }',
expected='{"field":"value"}',
)
check(
expr='.field',
data='{ "field": "value" }',
expected='"value"',
)
def test_validate_metric_name(self):
"""validate_metric_name rejects invalid metric names."""
bigquery.validate_metric_name('normal')
def check(test):
"""Check invalid names."""
self.assertRaises(ValueError, bigquery.validate_metric_name, test)
check('invalid#metric')
check('invalid/metric')
check('in\\valid')
check('invalid?yes')
check('*invalid')
check('[metric]')
check('metric\n')
check('met\ric')
check('metric& invalid')
def setUp(self):
self.assertTrue(ARGS.jq)
self.tmpdir = tempfile.mkdtemp(prefix='bigquery_test_')
self.out_filename = os.path.join(self.tmpdir, 'out.json')
self.data_filename = os.path.join(self.tmpdir, 'data.json')
def tearDown(self):
shutil.rmtree(self.tmpdir)
if __name__ == '__main__':
PARSER = argparse.ArgumentParser()
PARSER.add_argument('--jq', default='jq', help='path to jq binary')
ARGS, _ = PARSER.parse_known_args()
# Remove the --jq flag and its value so that unittest.main can parse the remaining args without
# complaining about an unknown flag.
for i in range(len(sys.argv)):
if sys.argv[i].startswith('--jq'):
arg = sys.argv.pop(i)
if '=' not in arg:
del sys.argv[i]
break
unittest.main()