Wrapping statuses with json.

This commit is contained in:
Roland 2019-10-14 13:11:23 -06:00
parent 281de05b83
commit 0ce9f5fca7
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
2 changed files with 15 additions and 13 deletions

View file

@ -35,10 +35,12 @@ class SettingsAPI(object):
return json.dumps({'success': 'Settings saved'})
def newline_streamer(func):
def add_newlines(*a, **kw):
yield from (f'{i}\n' for i in func(*a, **kw))
return add_newlines
def json_statuses_streamer(func):
"""Wraps status lines in JSON objects. Adds a new line after each JSON string."""
def wrap(*a, **kw):
yield from (json.dumps({'status': i}) + '\n' for i in func(*a, **kw))
yield json.dumps({'success': 'stream-complete'}) + '\n'
return wrap
@cherrypy.expose
@ -47,11 +49,10 @@ class Refresh(object):
def POST(self):
cherrypy.response.headers['Content-Type'] = 'text/event-stream'
@newline_streamer
@json_statuses_streamer
def streamer():
with get_db_context(commit=True) as (db_conn, db):
yield from refresh_videos(db)
yield 'stream-complete'
return streamer()
@ -64,12 +65,11 @@ class Download(object):
def POST(self):
cherrypy.response.headers['Content-Type'] = 'text/event-stream'
@newline_streamer
@json_statuses_streamer
def streamer():
with get_db_context(commit=True) as (db_conn, db):
yield from update_channels(db_conn, db)
yield from download_all_missing_videos(db_conn, db)
yield 'stream-complete'
return streamer()

View file

@ -57,11 +57,13 @@ class TestAPI(unittest.TestCase):
# TODO this test is very fragile :(
streamer = api.settings.refresh.POST()
statuses = list(streamer)
self.assertIn('Verifying videos in DB exist in file system\n', statuses)
self.assertIn('Deleting video files no longer in file system\n', statuses)
self.assertIn('Checking Big Buck Bunny directory for new videos\n', statuses)
self.assertEqual('stream-complete\n', statuses[-1])
statuses = [json.loads(s) for s in streamer]
self.assertEqual({'success': 'stream-complete'}, statuses.pop(-1))
statuses = [s['status'] for s in statuses]
self.assertIn('Verifying videos in DB exist in file system', statuses)
self.assertIn('Deleting video files no longer in file system', statuses)
self.assertIn('Checking Big Buck Bunny directory for new videos', statuses)
with get_db_context() as (db_conn, db):
Video, Channel = db['video'], db['channel']