feat: complete image-sharing appWSGI Tutorial

This commit is contained in:
2023-07-14 21:42:29 +08:00
parent d7bb7ee7c1
commit 2f56f9b5db
7 changed files with 238 additions and 9 deletions

View File

@@ -1,13 +1,25 @@
import io
from wsgiref.validate import InputWrapper
from unittest.mock import call, MagicMock, mock_open
import falcon
from falcon import testing
import msgpack
import pytest
from app.app import app
from app.app import create_app
from app.images import ImageStore
@pytest.fixture
def mock_store():
return MagicMock()
@pytest.fixture()
def client():
def client(mock_store):
app = create_app(mock_store)
return testing.TestClient(app)
@@ -24,4 +36,47 @@ def test_list_images(client):
result_doc = msgpack.unpackb(response.content, raw=False)
assert result_doc == doc
assert response.status == falcon.HTTP_OK
assert response.status == falcon.HTTP_OK
def test_posted_image(client, mock_store):
file_name = 'fake-image-name.xyz'
mock_store.save.return_value = file_name
image_content_type = 'image/xyz'
response = client.simulate_post(
'/images',
body=b'some-fake-bytes',
headers={'content-type': image_content_type}
)
assert response.status == falcon.HTTP_CREATED
assert response.headers['location'] == '/images/{}'.format(file_name)
saver_call = mock_store.save.call_args
assert isinstance(saver_call[0][0], InputWrapper)
assert saver_call[0][1] == image_content_type
def test_saving_image(monkeypatch):
# This still has some mocks, but they are more localized and do not
# have to be monkey-patched into standard library modules (always a
# risky business).
mock_file_open = mock_open()
fake_uuid = '123e4567-e89b-12d3-a456-426655440000'
def mock_uuidgen():
return fake_uuid
fake_image_bytes = b'fake-image-bytes'
fake_request_stream = io.BytesIO(fake_image_bytes)
storage_path = 'fake-storage-path'
store = ImageStore(
storage_path,
uuidgen=mock_uuidgen,
fopen=mock_file_open
)
assert store.save(fake_request_stream, 'image/png') == fake_uuid + '.png'
assert call().write(fake_image_bytes) in mock_file_open.mock_calls

26
tests/test_integration.py Normal file
View File

@@ -0,0 +1,26 @@
import os
import requests
def test_posted_image_gets_saved():
file_save_prefix = './images/'
location_prefix = '/images/'
fake_image_bytes = b'fake-image-bytes'
response = requests.post(
'http://localhost:8000/images',
data=fake_image_bytes,
headers={'content-type': 'image/png'}
)
assert response.status_code == 201
location = response.headers['location']
assert location.startswith(location_prefix)
image_name = location.replace(location_prefix, '')
file_path = file_save_prefix + image_name
with open(file_path, 'rb') as image_file:
assert image_file.read() == fake_image_bytes
os.remove(file_path)