Skip to content

Commit aae68c3

Browse files
committed
unit tests, updated custom header getters/setters
1 parent ef28538 commit aae68c3

File tree

3 files changed

+87
-15
lines changed

3 files changed

+87
-15
lines changed

examples/language.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,9 @@ def run(key, altUrl='https://api.rosette.com/rest/v1/'):
1616
api = API(user_key=key, service_url=altUrl)
1717

1818
language_data = "Por favor Señorita, says the man."
19-
app_header = []
20-
app_header.append("X-RosetteAPI-App")
21-
app_header.append("python-app")
22-
headers = []
23-
headers.append(app_header)
2419
params = DocumentParameters()
25-
2620
params["content"] = language_data
27-
params["customHeaders"] = headers
21+
api.setCustomHeaders("X-RosetteAPI-App", "python-app")
2822
return api.language(params)
2923

3024

rosette/api.py

Lines changed: 61 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import os
2727
from socket import gaierror
2828
import requests
29+
import re
2930

3031
_BINDING_VERSION = '1.1.1'
3132
_GZIP_BYTEARRAY = bytearray([0x1F, 0x8b, 0x08])
@@ -186,7 +187,7 @@ class DocumentParameters(_DocumentParamSetBase):
186187
def __init__(self):
187188
"""Create a L{DocumentParameters} object."""
188189
_DocumentParamSetBase.__init__(
189-
self, ("content", "contentUri", "language", "genre", "customHeaders"))
190+
self, ("content", "contentUri", "language", "genre"))
190191
self.file_name = ""
191192
self.useMultipart = False
192193

@@ -268,8 +269,7 @@ def __init__(self):
268269
"sourceScript",
269270
"targetScript",
270271
"targetScheme",
271-
"genre",
272-
"customHeaders"))
272+
"genre"))
273273

274274
def validate(self):
275275
"""Internal. Do not use."""
@@ -302,7 +302,7 @@ class NameSimilarityParameters(_DocumentParamSetBase):
302302

303303
def __init__(self):
304304
self.useMultipart = False
305-
_DocumentParamSetBase.__init__(self, ("name1", "name2", "customHeaders"))
305+
_DocumentParamSetBase.__init__(self, ("name1", "name2"))
306306

307307
def validate(self):
308308
"""Internal. Do not use."""
@@ -367,6 +367,17 @@ def info(self):
367367
identifying data."""
368368
url = self.service_url + "info"
369369
headers = {'Accept': 'application/json', 'X-RosetteAPI-Binding': 'python', 'X-RosetteAPI-Binding-Version': _BINDING_VERSION}
370+
371+
customHeaders = self.api.getCustomHeaders()
372+
pattern = re.compile('^X-RosetteAPI-')
373+
if customHeaders is not None:
374+
for key in customHeaders.keys():
375+
if pattern.match(key) is not None:
376+
headers[key] = customHeaders[key]
377+
else:
378+
raise RosetteException("badHeader", "Custom header name must begin with \"X-RosetteAPI-\"", key);
379+
self.api.clearCustomHeaders()
380+
370381
if self.debug:
371382
headers['X-RosetteAPI-Devel'] = 'true'
372383
self.logger.info('info: ' + url)
@@ -383,6 +394,17 @@ def ping(self):
383394

384395
url = self.service_url + 'ping'
385396
headers = {'Accept': 'application/json', 'X-RosetteAPI-Binding': 'python', 'X-RosetteAPI-Binding-Version': _BINDING_VERSION}
397+
398+
customHeaders = self.api.getCustomHeaders()
399+
pattern = re.compile('^X-RosetteAPI-')
400+
if customHeaders is not None:
401+
for key in customHeaders.keys():
402+
if pattern.match(key) is not None:
403+
headers[key] = customHeaders[key]
404+
else:
405+
raise RosetteException("badHeader", "Custom header name must begin with \"X-RosetteAPI-\"", key);
406+
self.api.clearCustomHeaders()
407+
386408
if self.debug:
387409
headers['X-RosetteAPI-Devel'] = 'true'
388410
self.logger.info('Ping: ' + url)
@@ -428,14 +450,20 @@ def call(self, parameters):
428450
headers = {}
429451
if self.user_key is not None:
430452

431-
if parameters["customHeaders"] is not None:
432-
for h in parameters["customHeaders"]:
433-
headers[h[0]] = h[1]
434-
parameters["customHeaders"] = None
453+
customHeaders = self.api.getCustomHeaders()
454+
pattern = re.compile('^X-RosetteAPI-')
455+
if customHeaders is not None:
456+
for key in customHeaders.keys():
457+
if pattern.match(key) is not None:
458+
headers[key] = customHeaders[key]
459+
else:
460+
raise RosetteException("badHeader", "Custom header name must begin with \"X-RosetteAPI-\"", key);
461+
self.api.clearCustomHeaders()
435462

436463
headers["X-RosetteAPI-Key"] = self.user_key
437464
headers["X-RosetteAPI-Binding"] = "python"
438465
headers["X-RosetteAPI-Binding-Version"] = _BINDING_VERSION
466+
439467
if self.useMultipart:
440468
params = dict(
441469
(key,
@@ -509,6 +537,7 @@ def __init__(
509537
self.connection_refresh_duration = refresh_duration
510538
self.http_connection = None
511539
self.options = {}
540+
self.customHeaders = {}
512541

513542
def _connect(self, parsedUrl):
514543
""" Simple connection method
@@ -645,6 +674,30 @@ def clearOptions(self):
645674
"""
646675
self.options.clear()
647676

677+
def setCustomHeaders(self, name, value):
678+
"""
679+
Sets custom headers
680+
681+
@param headers: array of custom headers to be set
682+
"""
683+
if value is None:
684+
self.customHeaders.pop(name, None)
685+
else:
686+
self.customHeaders[name] = value
687+
688+
def getCustomHeaders(self):
689+
"""
690+
Get custom headers
691+
"""
692+
return self.customHeaders
693+
694+
def clearCustomHeaders(self):
695+
"""
696+
Clears custom headers
697+
"""
698+
699+
self.customHeaders.clear()
700+
648701
def ping(self):
649702
"""
650703
Create a ping L{EndpointCaller} for the server and ping it.

tests/test_rosette_api.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,10 +82,35 @@ def test_option_clear_single_option(api):
8282
api.setOption('test', None)
8383
assert api.getOption('test') is None
8484

85+
# Test the custom header set/get/clear
86+
87+
88+
def test_custom_header_get_set_clear(api):
89+
key = 'X-RosetteAPI-Test'
90+
value = 'foo'
91+
api.setCustomHeaders(key, value)
92+
assert value == api.getCustomHeaders()[key]
93+
94+
api.clearCustomHeaders()
95+
assert len(api.getCustomHeaders()) is 0
96+
97+
# Test for invalid header name
98+
99+
100+
def test_invalid_header(api):
101+
key = 'test'
102+
value = 'foo'
103+
api.setCustomHeaders(key, value)
104+
105+
with pytest.raises(RosetteException) as e_rosette:
106+
result = api.info()
107+
108+
assert e_rosette.value.status == 'badHeader'
85109

86110
# Test that pinging the API is working properly
87111
# @httpretty.activate
88112

113+
89114
def test_ping(api, json_response):
90115
httpretty.enable()
91116
httpretty.register_uri(httpretty.GET, "https://api.rosette.com/rest/v1/ping",

0 commit comments

Comments
 (0)