Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions test/test_app_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,31 @@ def test_permission_check2(self, mock_abort):
except FileNotFoundError:
pass

def test_accept_format(self):
"""Test that `Accept` HTTP header causes change of response format

- Default `text/html` is tested by `TestView.test_directory`.
- `f=json` parameter is tested by `test_directory` in this class.
"""
with app.test_client() as c:

r = c.get(
'/subdir/',
query_string={'a': 'info'},
headers=[('Accept', 'application/json')])
self.assertEqual(r.status_code, 200)
self.assertEqual(r.headers['Content-Type'], 'application/json')
self.assertEqual(r.json, {
'success': True,
'data': {
'name': 'subdir',
'type': 'dir',
'size': None,
'last_modified': os.stat(os.path.join(server_root, 'subdir')).st_mtime,
'mime': None,
},
})

def test_directory(self):
with app.test_client() as c:
r = c.get('/subdir', query_string={'a': 'info', 'f': 'json'})
Expand Down Expand Up @@ -1263,6 +1288,18 @@ def test_sse_directory(self):
os.stat(os.path.join(server_root, 'subdir', 'sub')).st_mtime) in data)
self.assertTrue(data.endswith('\n\nevent: complete\ndata: \n\n'))

headers=[('Accept', 'text/event-stream')]
with self.subTest(headers=headers):
r = c.get('/subdir/', query_string={'a': 'list'}, headers=headers)
self.assertEqual(r.status_code, 200)
self.assertEqual(r.headers['Content-Type'], 'text/event-stream; charset=utf-8')
data = r.data.decode('UTF-8')
self.assertTrue('data: {{"name": "file.txt", "type": "file", "size": 3, "last_modified": {}}}\n\n'.format(
os.stat(os.path.join(server_root, 'subdir', 'file.txt')).st_mtime) in data)
self.assertTrue('data: {{"name": "sub", "type": "dir", "size": null, "last_modified": {}}}\n\n'.format(
os.stat(os.path.join(server_root, 'subdir', 'sub')).st_mtime) in data)
self.assertTrue(data.endswith('\n\nevent: complete\ndata: \n\n'))

def test_sse_directory_recursive(self):
with app.test_client() as c:
r = c.get('/subdir', query_string={'a': 'list', 'f': 'sse', 'recursive': 1})
Expand Down
8 changes: 7 additions & 1 deletion webscrapbook/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -585,7 +585,13 @@ def action(self):
@cached_property
def format(self):
"""Shortcut of the requested format."""
rv = request.values.get('f')
rv = None
best_accept = request.accept_mimetypes.best
if best_accept == 'application/json':
rv = 'json'
elif best_accept == 'text/event-stream':
rv = 'sse'
rv = request.values.get('f', default=rv)
rv = request.values.get('format', default=rv)
return rv

Expand Down