Skip to content

Commit 2cf506d

Browse files
committed
Address readability comments
1 parent 65c10cd commit 2cf506d

File tree

4 files changed

+46
-55
lines changed

4 files changed

+46
-55
lines changed

test/cluster/keytar/keytar.py

Lines changed: 30 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@
2323

2424
app = flask.Flask(__name__)
2525
results = {}
26+
_TEMPLATE = (
27+
'python {directory}/test_runner.py -c "{config}" -t {timestamp} '
28+
'-d {tempdir} -s {server}')
2629

2730

2831
class KeytarError(Exception):
@@ -44,23 +47,28 @@ def run_test_config(config):
4447
current_dir = os.getcwd()
4548

4649
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M')
47-
_add_new_result(timestamp)
48-
results[timestamp]['docker_image'] = config['docker_image']
50+
results[timestamp] = {
51+
'timestamp': timestamp,
52+
'status': 'Start',
53+
'tests': {},
54+
'docker_image': config['docker_image']
55+
}
4956

5057
# Generate a test script with the steps described in the configuration,
5158
# as well as the command to execute the test_runner.
5259
with tempfile.NamedTemporaryFile(dir=tempdir, delete=False) as f:
5360
tempscript = f.name
5461
f.write('#!/bin/bash\n')
5562
if 'before_test' in config:
63+
# Change to the github repo directory, any steps to be run before the
64+
# tests should be executed from there.
5665
os.chdir(github_repo_dir)
5766
for before_step in config['before_test']:
5867
f.write('%s\n' % before_step)
59-
f.write(
60-
'python %s/test_runner.py -c "%s" -t %s -d %s -s '
61-
'http://localhost:%d' % (
62-
current_dir, yaml.dump(config), timestamp, tempdir,
63-
app.config['port']))
68+
server = 'http://localhost:%d' % app.config['port']
69+
f.write(_TEMPLATE.format(
70+
directory=current_dir, config=yaml.dump(config), timestamp=timestamp,
71+
tempdir=tempdir, server=server))
6472
os.chmod(tempscript, 0775)
6573

6674
try:
@@ -79,12 +87,7 @@ def index():
7987

8088
@app.route('/test_results')
8189
def test_results():
82-
# Get all test results or a specific test result in JSON.
83-
if 'name' not in flask.request.args:
84-
return json.dumps([results[x] for x in sorted(results)])
85-
else:
86-
return json.dumps(
87-
[x for x in results.itervalues() if x == flask.request.args['name']])
90+
return json.dumps([results[x] for x in sorted(results)])
8891

8992

9093
@app.route('/test_log')
@@ -99,9 +102,8 @@ def test_log():
99102
def update_results():
100103
# Update the results dict, called from the test_runner.
101104
update_args = flask.request.get_json()
102-
time = update_args['time']
103-
for k, v in update_args.iteritems():
104-
results[time][k] = v
105+
timestamp = update_args['timestamp']
106+
results[timestamp].update(update_args)
105107
return 'OK'
106108

107109

@@ -170,31 +172,25 @@ def handle_cluster_setup(cluster_setup):
170172
# Add authentication steps to allow keytar to start clusters on GKE.
171173
gcloud_args = ['gcloud', 'auth', 'activate-service-account',
172174
'--key-file', cluster_setup['keyfile']]
173-
logging.info('authenticating using keyfile: %s',
174-
cluster_setup['keyfile'])
175+
logging.info('authenticating using keyfile: %s', cluster_setup['keyfile'])
175176
subprocess.call(gcloud_args)
176-
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = (
177-
cluster_setup['keyfile'])
177+
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = cluster_setup['keyfile']
178178

179179
# Ensure that a project name is correctly set. Use the name if provided
180180
# in the configuration, otherwise use the current project name, or else
181181
# the first available project name.
182182
if 'project_name' in cluster_setup:
183-
logging.info('Setting gcloud project to %s',
184-
cluster_setup['project_name'])
183+
logging.info('Setting gcloud project to %s', cluster_setup['project_name'])
185184
subprocess.call(
186-
['gcloud', 'config', 'set', 'project',
187-
cluster_setup['project_name']])
185+
['gcloud', 'config', 'set', 'project', cluster_setup['project_name']])
188186
else:
189187
config = subprocess.check_output(
190188
['gcloud', 'config', 'list', '--format', 'json'])
191189
project_name = json.loads(config)['core']['project']
192190
if not project_name:
193-
projects = subprocess.check_output(
194-
['gcloud', 'projects', 'list'])
191+
projects = subprocess.check_output(['gcloud', 'projects', 'list'])
195192
first_project = projects[0]['projectId']
196-
logging.info('gcloud project is unset, setting it to %s',
197-
first_project)
193+
logging.info('gcloud project is unset, setting it to %s', first_project)
198194
subprocess.check_output(
199195
['gcloud', 'config', 'set', 'project', first_project])
200196

@@ -208,9 +204,8 @@ def handle_install_steps(keytar_config):
208204
if 'install' not in keytar_config:
209205
return
210206
install_config = keytar_config['install']
211-
if 'cluster_setup' in install_config:
212-
for cluster_setup in install_config['cluster_setup']:
213-
handle_cluster_setup(cluster_setup)
207+
for cluster_setup in install_config.get('cluster_setup', []):
208+
handle_cluster_setup(cluster_setup)
214209

215210
# Install any dependencies using apt-get.
216211
if 'dependencies' in install_config:
@@ -221,19 +216,12 @@ def handle_install_steps(keytar_config):
221216
['apt-get', 'install', '-y', '--no-install-recommends', dep])
222217

223218
# Run any additional commands if provided.
224-
if 'extra' in install_config:
225-
for step in install_config['extra']:
226-
os.system(step)
219+
for step in install_config.get('extra', []):
220+
os.system(step)
227221

228222
# Update path environment variable.
229-
if 'path' in install_config:
230-
for path in install_config['path']:
231-
os.environ['PATH'] = '%s:%s' % (path, os.environ['PATH'])
232-
233-
234-
def _add_new_result(timestamp):
235-
result = {'time': timestamp, 'status': 'Start', 'tests': {}}
236-
results[timestamp] = result
223+
for path in install_config.get('path', []):
224+
os.environ['PATH'] = '%s:%s' % (path, os.environ['PATH'])
237225

238226

239227
def _get_download_github_repo_args(tempdir, github_config):
@@ -308,4 +296,3 @@ def main():
308296

309297
if __name__ == '__main__':
310298
main()
311-

test/cluster/keytar/keytar_test.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,23 +62,27 @@ def test_results(self):
6262
self.assertEqual(json.loads(test_results.data), [])
6363

6464
# Create a test_result, GET test_results should return an entry now.
65-
keytar._add_new_result(self.timestamp)
65+
keytar.results[self.timestamp] = {
66+
'timestamp': self.timestamp,
67+
'status': 'Start',
68+
'tests': {},
69+
}
6670
test_results = tester.get('/test_results')
6771
self.assertEqual(test_results.status_code, 200)
6872
self.assertEqual(
6973
json.loads(test_results.data),
70-
[{'time': self.timestamp, 'status': 'Start', 'tests': {}}])
74+
[{'timestamp': self.timestamp, 'status': 'Start', 'tests': {}}])
7175

7276
# Call POST update_results, GET test_results should return a changed entry.
7377
tester.post(
7478
'/update_results', data=json.dumps(dict(
75-
time='20160101_0000', status='Complete')),
79+
timestamp='20160101_0000', status='Complete')),
7680
follow_redirects=True, content_type='application/json')
7781
test_results = tester.get('/test_results')
7882
self.assertEqual(test_results.status_code, 200)
7983
self.assertEqual(
8084
json.loads(test_results.data),
81-
[{'time': self.timestamp, 'status': 'Complete', 'tests': {}}])
85+
[{'timestamp': self.timestamp, 'status': 'Complete', 'tests': {}}])
8286

8387

8488
if __name__ == '__main__':

test/cluster/keytar/keytar_web_test.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,11 @@ class TestKeytarWeb(unittest.TestCase):
1919
@classmethod
2020
def setUpClass(cls):
2121
cls.driver = environment.create_webdriver()
22+
port = environment.reserve_ports(1)
23+
keytar_folder = os.path.join(environment.vttop, 'test/cluster/keytar')
2224
cls.flask_process = subprocess.Popen(
23-
[os.path.join(environment.vttop, 'test/cluster/keytar/keytar.py'),
25+
[os.path.join(keytar_folder, 'keytar.py'),
26+
os.path.join(keytar_folder, 'test_config.yaml'),
2427
'--config_file=test_config.yaml', '--port=%d' % port,
2528
'--password=foo'],
2629
preexec_fn=os.setsid)
@@ -35,11 +38,10 @@ def _wait_for_complete_status(self, timeout_s=180):
3538
start_time = time.time()
3639
while time.time() - start_time < timeout_s:
3740
if 'Complete' in self.driver.find_element_by_id('results').text:
38-
break
41+
return
3942
self.driver.refresh()
4043
time.sleep(5)
41-
else:
42-
self.fail('Timed out waiting for test to finish.')
44+
self.fail('Timed out waiting for test to finish.')
4345

4446
def test_keytar_web(self):
4547
self.driver.get(self.flask_addr)

test/cluster/keytar/test_runner.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def run_test_config():
9090
if subprocess.call(test_args, stdout=results_file, stderr=results_file):
9191
test_results[test_name] = 'FAILED'
9292
else:
93-
test_results[os.path.basename(test_file)] = 'PASSED'
93+
test_results[test_name] = 'PASSED'
9494
update_result('tests', test_results)
9595
update_result('status', 'Tests Complete')
9696
except Exception as e: # pylint: disable=broad-except
@@ -109,9 +109,7 @@ def run_test_config():
109109
parser.add_argument('-s', '--server', help='keytar server address')
110110
keytar_args = parser.parse_args()
111111
config = yaml.load(keytar_args.config)
112-
repo_prefix = 'github'
113-
if 'repo_prefix' in config['github']:
114-
repo_prefix = config['github']['repo_prefix']
112+
repo_prefix = config['github'].get('repo_prefix', 'github')
115113
repo_dir = os.path.join(keytar_args.dir, repo_prefix)
116114

117115
run_test_config()

0 commit comments

Comments
 (0)