Skip to content
13 changes: 8 additions & 5 deletions sdk/core/azure-core/azure/core/rest/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,14 @@ def set_content_body(content):

def set_json_body(json):
# type: (Any) -> Tuple[Dict[str, str], Any]
body = dumps(json, cls=AzureJSONEncoder)
return {
"Content-Type": "application/json",
"Content-Length": str(len(body))
}, body
headers = {"Content-Type": "application/json"}
if hasattr(json, "read"):
content_headers, body = set_content_body(json)
headers.update(content_headers)
else:
body = dumps(json, cls=AzureJSONEncoder)
headers.update({"Content-Length": str(len(body))})
return headers, body

def lookup_encoding(encoding):
# type: (str) -> bool
Expand Down
26 changes: 26 additions & 0 deletions sdk/core/azure-core/tests/test_rest_http_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,32 @@ def on_request(self, pipeline_request):
# work
assert "I entered the policies!" in str(ex.value)

def test_json_file_valid():
json_bytes = bytearray('{"more": "cowbell"}', encoding='utf-8')
with io.BytesIO(json_bytes) as json_file:
request = HttpRequest("PUT", "/fake", json=json_file)
assert request.headers == {"Content-Type": "application/json"}
assert request.content == json_file
assert not request.content.closed
assert request.content.read() == b'{"more": "cowbell"}'

def test_json_file_invalid():
json_bytes = bytearray('{"more": "cowbell" i am not valid', encoding='utf-8')
with io.BytesIO(json_bytes) as json_file:
request = HttpRequest("PUT", "/fake", json=json_file)
assert request.headers == {"Content-Type": "application/json"}
assert request.content == json_file
assert not request.content.closed
assert request.content.read() == b'{"more": "cowbell" i am not valid'

def test_json_file_content_type_input():
json_bytes = bytearray('{"more": "cowbell"}', encoding='utf-8')
with io.BytesIO(json_bytes) as json_file:
request = HttpRequest("PUT", "/fake", json=json_file, headers={"Content-Type": "application/json-special"})
assert request.headers == {"Content-Type": "application/json-special"}
assert request.content == json_file
assert not request.content.closed
assert request.content.read() == b'{"more": "cowbell"}'

# NOTE: For files, we don't allow list of tuples yet, just dict. Will uncomment when we add this capability
# def test_multipart_multiple_files_single_input_content():
Expand Down