Skip to content

Commit 9040eb1

Browse files
author
Vladimir Kotal
committed
refactor call_rest_api(), add tests
1 parent b9d1d0a commit 9040eb1

File tree

3 files changed

+134
-32
lines changed

3 files changed

+134
-32
lines changed

opengrok-tools/src/main/python/opengrok_tools/utils/commandsequence.py

Lines changed: 4 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -18,18 +18,17 @@
1818
#
1919

2020
#
21-
# Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
21+
# Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
2222
#
2323

2424
import logging
2525
from .command import Command
26-
from .webutil import put, post, delete
2726
from .utils import is_web_uri
2827
from .exitvals import (
2928
CONTINUE_EXITVAL,
3029
SUCCESS_EXITVAL
3130
)
32-
import json
31+
from .restful import call_rest_api
3332
import re
3433

3534

@@ -100,33 +99,6 @@ def run_command(self, command):
10099

101100
return cmd.getretcode()
102101

103-
def call_rest_api(self, command):
104-
"""
105-
Make RESTful API call. Occurrence of PROJECT_SUBST in the URI will be
106-
replaced by project name.
107-
"""
108-
command = command.get("command")
109-
uri = command[0].replace(self.PROJECT_SUBST, self.name)
110-
verb = command[1]
111-
data = command[2]
112-
113-
headers = None
114-
json_data = None
115-
if data:
116-
headers = {'Content-Type': 'application/json'}
117-
json_data = json.dumps(data).replace(self.PROJECT_SUBST, self.name)
118-
self.logger.debug("JSON data: {}".format(json_data))
119-
120-
if verb == 'PUT':
121-
put(self.logger, uri, headers=headers, data=json_data)
122-
elif verb == 'POST':
123-
post(self.logger, uri, headers=headers, data=json_data)
124-
elif verb == 'DELETE':
125-
delete(self.logger, uri, data)
126-
else:
127-
self.logger.error('Unknown HTTP verb in command {}'.
128-
format(command))
129-
130102
def run(self):
131103
"""
132104
Run the sequence of commands and capture their output and return code.
@@ -145,7 +117,7 @@ def run(self):
145117

146118
for command in self.commands:
147119
if is_web_uri(command.get("command")[0]):
148-
self.call_rest_api(command)
120+
call_rest_api(command, self.PROJECT_SUBST, self.name)
149121
else:
150122
retcode = self.run_command(command)
151123

@@ -184,7 +156,7 @@ def run_cleanup(self):
184156

185157
for cleanup_cmd in self.cleanup:
186158
if is_web_uri(cleanup_cmd.get("command")[0]):
187-
self.call_rest_api(cleanup_cmd)
159+
call_rest_api(cleanup_cmd, self.PROJECT_SUBST, self.name)
188160
else:
189161
command_args = cleanup_cmd.get("command")
190162
self.logger.debug("Running cleanup command '{}'".
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#
2+
# CDDL HEADER START
3+
#
4+
# The contents of this file are subject to the terms of the
5+
# Common Development and Distribution License (the "License").
6+
# You may not use this file except in compliance with the License.
7+
#
8+
# See LICENSE.txt included in this distribution for the specific
9+
# language governing permissions and limitations under the License.
10+
#
11+
# When distributing Covered Code, include this CDDL HEADER in each
12+
# file and include the License file at LICENSE.txt.
13+
# If applicable, add the following below this CDDL HEADER, with the
14+
# fields enclosed by brackets "[]" replaced with your own identifying
15+
# information: Portions Copyright [yyyy] [name of copyright owner]
16+
#
17+
# CDDL HEADER END
18+
#
19+
20+
#
21+
# Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
22+
#
23+
24+
import logging
25+
from .webutil import put, post, delete
26+
import json
27+
28+
29+
def do_api_call(command, uri, headers, json_data):
30+
logger = logging.getLogger(__name__)
31+
32+
if verb == 'PUT':
33+
return put(logger, uri, headers=headers, data=json_data)
34+
elif verb == 'POST':
35+
return post(logger, uri, headers=headers, data=json_data)
36+
elif verb == 'DELETE':
37+
return delete(logger, uri, headers=headers)
38+
else:
39+
raise Exception('Unknown HTTP verb in command {}'.
40+
format(command))
41+
42+
43+
def call_rest_api(command, pattern, name):
44+
"""
45+
Make RESTful API call. Occurrence of the pattern in the URI
46+
(first part of the command) or data payload will be replaced by the name.
47+
48+
:param command: command (list of URI, HTTP verb, data payload)
49+
:param pattern: pattern for command name and/or data substitution
50+
:param name: command name
51+
:return return value from given requests method
52+
"""
53+
command = command.get("command")
54+
uri = command[0].replace(pattern, name)
55+
verb = command[1]
56+
data = command[2]
57+
58+
logger = logging.getLogger(__name__)
59+
60+
headers = None
61+
json_data = None
62+
if data:
63+
headers = {'Content-Type': 'application/json'}
64+
json_data = json.dumps(data).replace(pattern, name)
65+
logger.debug("JSON data: {}".format(json_data))
66+
67+
return do_api_call(command, uri, headers, json_data)
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/usr/bin/env python3
2+
3+
#
4+
# CDDL HEADER START
5+
#
6+
# The contents of this file are subject to the terms of the
7+
# Common Development and Distribution License (the "License").
8+
# You may not use this file except in compliance with the License.
9+
#
10+
# See LICENSE.txt included in this distribution for the specific
11+
# language governing permissions and limitations under the License.
12+
#
13+
# When distributing Covered Code, include this CDDL HEADER in each
14+
# file and include the License file at LICENSE.txt.
15+
# If applicable, add the following below this CDDL HEADER, with the
16+
# fields enclosed by brackets "[]" replaced with your own identifying
17+
# information: Portions Copyright [yyyy] [name of copyright owner]
18+
#
19+
# CDDL HEADER END
20+
#
21+
22+
#
23+
# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
24+
#
25+
26+
import pytest
27+
from opengrok_tools.utils.restful import call_rest_api
28+
29+
30+
def test_restful_verbs(monkeypatch):
31+
okay_status = 200
32+
33+
class MockResponse:
34+
def __init__(self):
35+
self.status_code = okay_status
36+
37+
def mock_response(command, uri, headers, json_data):
38+
# Spying on mocked function is maybe too much so verify
39+
# the arguments here.
40+
assert uri == "http://localhost:8080/source/api/v1/BAR"
41+
assert json_data == '"fooBARbar"'
42+
43+
return MockResponse()
44+
45+
for verb in ["PUT", "POST", "DELETE"]:
46+
command = {"command": ["http://localhost:8080/source/api/v1/%FOO%",
47+
verb, "foo%FOO%bar"]}
48+
pattern = "%FOO%"
49+
value = "BAR"
50+
with monkeypatch.context() as m:
51+
m.setattr("opengrok_tools.utils.restful.do_api_call",
52+
mock_response)
53+
assert call_rest_api(command, pattern, value). \
54+
status_code == okay_status
55+
56+
57+
def test_unknown_verb():
58+
command = {"command": ["http://localhost:8080/source/api/v1/foo",
59+
"FOOBAR", "data"]}
60+
pattern = "%FOO%"
61+
value = "BAR"
62+
with pytest.raises(Exception):
63+
call_rest_api(command, pattern, value)

0 commit comments

Comments
 (0)