Skip to content

Commit c34ee2e

Browse files
author
Vladimir Kotal
committed
check command structure in call_rest_api()
add tests
1 parent 5b8788b commit c34ee2e

File tree

2 files changed

+28
-8
lines changed

2 files changed

+28
-8
lines changed

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

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -60,23 +60,27 @@ def call_rest_api(command, pattern, name):
6060

6161
logger = logging.getLogger(__name__)
6262

63-
command = command.get(COMMAND_PROPERTY)
64-
if pattern and name:
65-
uri = command[0].replace(pattern, name)
66-
else:
67-
uri = command[0]
63+
if not isinstance(command, dict) or command.get(COMMAND_PROPERTY) is None:
64+
raise Exception("invalid command")
6865

69-
verb = command[1]
70-
data = command[2]
66+
command = command[COMMAND_PROPERTY]
7167

68+
uri, verb, data, *_ = command
69+
if verb not in ['PUT', 'POST', 'DELETE']:
70+
raise Exception("invalid verb: {}".format(verb))
7271
try:
7372
headers = command[3]
73+
if headers and not isinstance(headers, dict):
74+
raise Exception("headers must be a dictionary")
7475
except IndexError:
7576
headers = {}
7677

77-
if not headers:
78+
if headers is None:
7879
headers = {}
7980

81+
if pattern and name:
82+
uri = uri.replace(pattern, name)
83+
8084
header_names = [x.lower() for x in headers.keys()]
8185

8286
if data:

opengrok-tools/src/test/python/test_restful.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import pytest
2727
from opengrok_tools.utils.restful import call_rest_api,\
2828
CONTENT_TYPE, APPLICATION_JSON
29+
from opengrok_tools.utils.patterns import COMMAND_PROPERTY
2930

3031

3132
def test_replacement(monkeypatch):
@@ -88,3 +89,18 @@ def mock_response(command, uri, verb, headers_arg, data):
8889
m.setattr("opengrok_tools.utils.restful.do_api_call",
8990
mock_response)
9091
call_rest_api(command, None, None)
92+
93+
94+
def test_invalid_command_negative():
95+
with pytest.raises(Exception):
96+
call_rest_api(None, None, None)
97+
98+
with pytest.raises(Exception):
99+
call_rest_api({"foo": "bar"}, None, None)
100+
101+
with pytest.raises(Exception):
102+
call_rest_api(["foo", "bar"], None, None)
103+
104+
with pytest.raises(Exception):
105+
call_rest_api({COMMAND_PROPERTY: ["foo", "PUT", "data", "headers"]},
106+
None, None)

0 commit comments

Comments
 (0)