Skip to content

Commit

Permalink
fix: Ensure result storage is passed results in bytes
Browse files Browse the repository at this point in the history
When results are text, such as JSON content for `/meta/` endpoints,
ensure the results are converted to bytes before passing them to a
result storage.

Fix #1577
  • Loading branch information
scorphus committed Jul 1, 2023
1 parent 04030f7 commit e1dc517
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
29 changes: 29 additions & 0 deletions tests/handlers/test_base_handler_with_result_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com thumbor@googlegroups.com

import json
import os
from os.path import dirname
from shutil import which
Expand Down Expand Up @@ -77,6 +78,34 @@ async def test_saves_image_to_result_storage(self, instance_mock):
expect(expected_path).to_exist()
expect(response.body).to_be_similar_to(animated_image())

@patch("tornado.ioloop.IOLoop.instance")
@gen_test
async def test_saves_meta_to_result_storage(self, instance_mock):
instance_mock.return_value = self.io_loop
response = await self.async_fetch(
"/oGi9XL4nHJKGEKVHjHEp1Jg1KpM=/meta/animated.gif"
)
expect(response.code).to_equal(200)

self.context.request = Mock(
accepts_webp=False,
)
expected_path = self.result_storage.normalize_path(
"/oGi9XL4nHJKGEKVHjHEp1Jg1KpM=/meta/animated.gif"
)
expect(expected_path).to_exist()

expected_source = {
"frameCount": 2,
"height": 100,
"url": "animated.gif",
"width": 100,
}
metadata = json.loads(response.body)
expect(metadata).to_include("thumbor")
expect(metadata["thumbor"]).to_include("source")
expect(metadata["thumbor"]["source"]).to_be_like(expected_source)


class ImageOperationsResultStorageOnlyTestCase(BaseImagingTestCase):
def get_context(self):
Expand Down
6 changes: 6 additions & 0 deletions thumbor/handlers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,11 +657,17 @@ async def finish_request(self, result_from_storage=None):
await self._write_results_to_client(results, content_type)

if should_store:
results = self._ensure_bytes(results)
await self._store_results(result_storage, metrics, results)

# can't cleanup before storing results as the storage requires context
self._cleanup()

def _ensure_bytes(self, results):
if isinstance(results, str):
return results.encode()
return results

def _cleanup(self):
self.context.request_handler = None

Expand Down

0 comments on commit e1dc517

Please sign in to comment.