##// END OF EJS Templates
Fix sessionmanager test
Thomas Kluyver -
Show More
@@ -1,185 +1,182 b''
1 """A base class session manager.
1 """A base class session manager.
2
2
3 Authors:
3 Authors:
4
4
5 * Zach Sailer
5 * Zach Sailer
6 """
6 """
7
7
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9 # Copyright (C) 2013 The IPython Development Team
9 # Copyright (C) 2013 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 import uuid
19 import uuid
20 import sqlite3
20 import sqlite3
21
21
22 from tornado import web
22 from tornado import web
23
23
24 from IPython.config.configurable import LoggingConfigurable
24 from IPython.config.configurable import LoggingConfigurable
25 from IPython.utils.traitlets import TraitError
25 from IPython.utils.traitlets import TraitError
26
26
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28 # Classes
28 # Classes
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30
30
31 class SessionManager(LoggingConfigurable):
31 class SessionManager(LoggingConfigurable):
32
32
33 # Session database initialized below
33 # Session database initialized below
34 _cursor = None
34 _cursor = None
35 _connection = None
35 _connection = None
36
36
37 @property
37 @property
38 def cursor(self):
38 def cursor(self):
39 """Start a cursor and create a database called 'session'"""
39 """Start a cursor and create a database called 'session'"""
40 if self._cursor is None:
40 if self._cursor is None:
41 self._cursor = self.connection.cursor()
41 self._cursor = self.connection.cursor()
42 self._cursor.execute("""CREATE TABLE session
42 self._cursor.execute("""CREATE TABLE session
43 (id, name, path, kernel_id, ws_url)""")
43 (id, name, path, kernel_id, ws_url)""")
44 return self._cursor
44 return self._cursor
45
45
46 @property
46 @property
47 def connection(self):
47 def connection(self):
48 """Start a database connection"""
48 """Start a database connection"""
49 if self._connection is None:
49 if self._connection is None:
50 self._connection = sqlite3.connect(':memory:')
50 self._connection = sqlite3.connect(':memory:')
51 self._connection.row_factory = sqlite3.Row
51 self._connection.row_factory = sqlite3.Row
52 return self._connection
52 return self._connection
53
53
54 def __del__(self):
54 def __del__(self):
55 """Close connection once SessionManager closes"""
55 """Close connection once SessionManager closes"""
56 self.cursor.close()
56 self.cursor.close()
57
57
58 def session_exists(self, name, path):
58 def session_exists(self, name, path):
59 """Check to see if the session for the given notebook exists"""
59 """Check to see if the session for the given notebook exists"""
60 self.cursor.execute("SELECT * FROM session WHERE name=? AND path=?", (name,path))
60 self.cursor.execute("SELECT * FROM session WHERE name=? AND path=?", (name,path))
61 reply = self.cursor.fetchone()
61 reply = self.cursor.fetchone()
62 if reply is None:
62 if reply is None:
63 return False
63 return False
64 else:
64 else:
65 return True
65 return True
66
66
67 def get_session_id(self):
67 def get_session_id(self):
68 "Create a uuid for a new session"
68 "Create a uuid for a new session"
69 return unicode(uuid.uuid4())
69 return unicode(uuid.uuid4())
70
70
71 def create_session(self, name=None, path=None, kernel_id=None, ws_url=None):
71 def create_session(self, name=None, path=None, kernel_id=None, ws_url=None):
72 """Creates a session and returns its model"""
72 """Creates a session and returns its model"""
73 session_id = self.get_session_id()
73 session_id = self.get_session_id()
74 return self.save_session(session_id, name=name, path=path, kernel_id=kernel_id, ws_url=ws_url)
74 return self.save_session(session_id, name=name, path=path, kernel_id=kernel_id, ws_url=ws_url)
75
75
76 def save_session(self, session_id, name=None, path=None, kernel_id=None, ws_url=None):
76 def save_session(self, session_id, name=None, path=None, kernel_id=None, ws_url=None):
77 """Saves the items for the session with the given session_id
77 """Saves the items for the session with the given session_id
78
78
79 Given a session_id (and any other of the arguments), this method
79 Given a session_id (and any other of the arguments), this method
80 creates a row in the sqlite session database that holds the information
80 creates a row in the sqlite session database that holds the information
81 for a session.
81 for a session.
82
82
83 Parameters
83 Parameters
84 ----------
84 ----------
85 session_id : str
85 session_id : str
86 uuid for the session; this method must be given a session_id
86 uuid for the session; this method must be given a session_id
87 name : str
87 name : str
88 the .ipynb notebook name that started the session
88 the .ipynb notebook name that started the session
89 path : str
89 path : str
90 the path to the named notebook
90 the path to the named notebook
91 kernel_id : str
91 kernel_id : str
92 a uuid for the kernel associated with this session
92 a uuid for the kernel associated with this session
93 ws_url : str
93 ws_url : str
94 the websocket url
94 the websocket url
95
95
96 Returns
96 Returns
97 -------
97 -------
98 model : dict
98 model : dict
99 a dictionary of the session model
99 a dictionary of the session model
100 """
100 """
101 self.cursor.execute("""INSERT INTO session VALUES
101 self.cursor.execute("""INSERT INTO session VALUES
102 (?,?,?,?,?)""", (session_id, name, path, kernel_id, ws_url))
102 (?,?,?,?,?)""", (session_id, name, path, kernel_id, ws_url))
103 self.connection.commit()
103 self.connection.commit()
104 return self.get_session(id=session_id)
104 return self.get_session(id=session_id)
105
105
106 def get_session(self, **kwargs):
106 def get_session(self, **kwargs):
107 """Returns the model for a particular session.
107 """Returns the model for a particular session.
108
108
109 Takes a keyword argument and searches for the value in the session
109 Takes a keyword argument and searches for the value in the session
110 database, then returns the rest of the session's info.
110 database, then returns the rest of the session's info.
111
111
112 Parameters
112 Parameters
113 ----------
113 ----------
114 **kwargs : keyword argument
114 **kwargs : keyword argument
115 must be given one of the keywords and values from the session database
115 must be given one of the keywords and values from the session database
116 (i.e. session_id, name, path, kernel_id, ws_url)
116 (i.e. session_id, name, path, kernel_id, ws_url)
117
117
118 Returns
118 Returns
119 -------
119 -------
120 model : dict
120 model : dict
121 returns a dictionary that includes all the information from the
121 returns a dictionary that includes all the information from the
122 session described by the kwarg.
122 session described by the kwarg.
123 """
123 """
124 column = kwargs.keys()[0] # uses only the first kwarg that is entered
124 column = kwargs.keys()[0] # uses only the first kwarg that is entered
125 value = kwargs.values()[0]
125 value = kwargs.values()[0]
126 try:
126 try:
127 self.cursor.execute("SELECT * FROM session WHERE %s=?" %column, (value,))
127 self.cursor.execute("SELECT * FROM session WHERE %s=?" %column, (value,))
128 except sqlite3.OperationalError:
128 except sqlite3.OperationalError:
129 raise TraitError("The session database has no column: %s" %column)
129 raise TraitError("The session database has no column: %s" %column)
130 reply = self.cursor.fetchone()
130 reply = self.cursor.fetchone()
131 if reply is not None:
131 if reply is not None:
132 model = self.reply_to_dictionary_model(reply)
132 model = self.reply_to_dictionary_model(reply)
133 else:
133 else:
134 raise web.HTTPError(404, u'Session not found: %s=%r' % (column, value))
134 raise web.HTTPError(404, u'Session not found: %s=%r' % (column, value))
135 return model
135 return model
136
136
137 def update_session(self, session_id, **kwargs):
137 def update_session(self, session_id, **kwargs):
138 """Updates the values in the session database.
138 """Updates the values in the session database.
139
139
140 Changes the values of the session with the given session_id
140 Changes the values of the session with the given session_id
141 with the values from the keyword arguments.
141 with the values from the keyword arguments.
142
142
143 Parameters
143 Parameters
144 ----------
144 ----------
145 session_id : str
145 session_id : str
146 a uuid that identifies a session in the sqlite3 database
146 a uuid that identifies a session in the sqlite3 database
147 **kwargs : str
147 **kwargs : str
148 the key must correspond to a column title in session database,
148 the key must correspond to a column title in session database,
149 and the value replaces the current value in the session
149 and the value replaces the current value in the session
150 with session_id.
150 with session_id.
151 """
151 """
152 for kwarg in kwargs:
152 for kwarg in kwargs:
153 try:
153 try:
154 self.cursor.execute("UPDATE session SET %s=? WHERE id=?" %kwarg, (kwargs[kwarg], session_id))
154 self.cursor.execute("UPDATE session SET %s=? WHERE id=?" %kwarg, (kwargs[kwarg], session_id))
155 self.connection.commit()
155 self.connection.commit()
156 except sqlite3.OperationalError:
156 except sqlite3.OperationalError:
157 raise TraitError("No session exists with ID: %s" %session_id)
157 raise TraitError("No session exists with ID: %s" %session_id)
158
158
159 def reply_to_dictionary_model(self, reply):
159 def reply_to_dictionary_model(self, reply):
160 """Takes sqlite database session row and turns it into a dictionary"""
160 """Takes sqlite database session row and turns it into a dictionary"""
161 model = {'id': reply['id'],
161 model = {'id': reply['id'],
162 'notebook': {'name': reply['name'], 'path': reply['path']},
162 'notebook': {'name': reply['name'], 'path': reply['path']},
163 'kernel': {'id': reply['kernel_id'], 'ws_url': reply['ws_url']}}
163 'kernel': {'id': reply['kernel_id'], 'ws_url': reply['ws_url']}}
164 return model
164 return model
165
165
166 def list_sessions(self):
166 def list_sessions(self):
167 """Returns a list of dictionaries containing all the information from
167 """Returns a list of dictionaries containing all the information from
168 the session database"""
168 the session database"""
169 session_list=[]
169 session_list=[]
170 self.cursor.execute("SELECT * FROM session")
170 self.cursor.execute("SELECT * FROM session")
171 sessions = self.cursor.fetchall()
171 sessions = self.cursor.fetchall()
172 for session in sessions:
172 for session in sessions:
173 model = self.reply_to_dictionary_model(session)
173 model = self.reply_to_dictionary_model(session)
174 session_list.append(model)
174 session_list.append(model)
175 return session_list
175 return session_list
176
176
177 def delete_session(self, session_id):
177 def delete_session(self, session_id):
178 """Deletes the row in the session database with given session_id"""
178 """Deletes the row in the session database with given session_id"""
179 # Check that session exists before deleting
179 # Check that session exists before deleting
180 model = self.get_session(id=session_id)
180 model = self.get_session(id=session_id)
181 if model is None:
181 self.cursor.execute("DELETE FROM session WHERE id=?", (session_id,))
182 raise TraitError("The session does not exist: %s" %session_id)
182 self.connection.commit() No newline at end of file
183 else:
184 self.cursor.execute("DELETE FROM session WHERE id=?", (session_id,))
185 self.connection.commit() No newline at end of file
@@ -1,86 +1,84 b''
1 """Tests for the session manager."""
1 """Tests for the session manager."""
2
2
3 import os
4
5 from unittest import TestCase
3 from unittest import TestCase
6 from tempfile import NamedTemporaryFile
7
4
8 from IPython.utils.tempdir import TemporaryDirectory
5 from tornado import web
6
9 from IPython.utils.traitlets import TraitError
7 from IPython.utils.traitlets import TraitError
10
8
11 from ..sessionmanager import SessionManager
9 from ..sessionmanager import SessionManager
12
10
13 class TestSessionManager(TestCase):
11 class TestSessionManager(TestCase):
14
12
15 def test_get_session(self):
13 def test_get_session(self):
16 sm = SessionManager()
14 sm = SessionManager()
17 session_id = sm.get_session_id()
15 session_id = sm.get_session_id()
18 sm.save_session(session_id=session_id, name='test.ipynb', path='/path/to/', kernel_id='5678', ws_url='ws_url')
16 sm.save_session(session_id=session_id, name='test.ipynb', path='/path/to/', kernel_id='5678', ws_url='ws_url')
19 model = sm.get_session(id=session_id)
17 model = sm.get_session(id=session_id)
20 expected = {'id':session_id, 'notebook':{'name':u'test.ipynb', 'path': u'/path/to/'}, 'kernel':{'id':u'5678', 'ws_url':u'ws_url'}}
18 expected = {'id':session_id, 'notebook':{'name':u'test.ipynb', 'path': u'/path/to/'}, 'kernel':{'id':u'5678', 'ws_url':u'ws_url'}}
21 self.assertEqual(model, expected)
19 self.assertEqual(model, expected)
22
20
23 def test_bad_get_session(self):
21 def test_bad_get_session(self):
24 # Should raise error if a bad key is passed to the database.
22 # Should raise error if a bad key is passed to the database.
25 sm = SessionManager()
23 sm = SessionManager()
26 session_id = sm.get_session_id()
24 session_id = sm.get_session_id()
27 sm.save_session(session_id=session_id, name='test.ipynb', path='/path/to/', kernel_id='5678', ws_url='ws_url')
25 sm.save_session(session_id=session_id, name='test.ipynb', path='/path/to/', kernel_id='5678', ws_url='ws_url')
28 self.assertRaises(TraitError, sm.get_session, bad_id=session_id) # Bad keyword
26 self.assertRaises(TraitError, sm.get_session, bad_id=session_id) # Bad keyword
29
27
30 def test_list_sessions(self):
28 def test_list_sessions(self):
31 sm = SessionManager()
29 sm = SessionManager()
32 session_id1 = sm.get_session_id()
30 session_id1 = sm.get_session_id()
33 session_id2 = sm.get_session_id()
31 session_id2 = sm.get_session_id()
34 session_id3 = sm.get_session_id()
32 session_id3 = sm.get_session_id()
35 sm.save_session(session_id=session_id1, name='test1.ipynb', path='/path/to/1/', kernel_id='5678', ws_url='ws_url')
33 sm.save_session(session_id=session_id1, name='test1.ipynb', path='/path/to/1/', kernel_id='5678', ws_url='ws_url')
36 sm.save_session(session_id=session_id2, name='test2.ipynb', path='/path/to/2/', kernel_id='5678', ws_url='ws_url')
34 sm.save_session(session_id=session_id2, name='test2.ipynb', path='/path/to/2/', kernel_id='5678', ws_url='ws_url')
37 sm.save_session(session_id=session_id3, name='test3.ipynb', path='/path/to/3/', kernel_id='5678', ws_url='ws_url')
35 sm.save_session(session_id=session_id3, name='test3.ipynb', path='/path/to/3/', kernel_id='5678', ws_url='ws_url')
38 sessions = sm.list_sessions()
36 sessions = sm.list_sessions()
39 expected = [{'id':session_id1, 'notebook':{'name':u'test1.ipynb',
37 expected = [{'id':session_id1, 'notebook':{'name':u'test1.ipynb',
40 'path': u'/path/to/1/'}, 'kernel':{'id':u'5678', 'ws_url': 'ws_url'}},
38 'path': u'/path/to/1/'}, 'kernel':{'id':u'5678', 'ws_url': 'ws_url'}},
41 {'id':session_id2, 'notebook': {'name':u'test2.ipynb',
39 {'id':session_id2, 'notebook': {'name':u'test2.ipynb',
42 'path': u'/path/to/2/'}, 'kernel':{'id':u'5678', 'ws_url': 'ws_url'}},
40 'path': u'/path/to/2/'}, 'kernel':{'id':u'5678', 'ws_url': 'ws_url'}},
43 {'id':session_id3, 'notebook':{'name':u'test3.ipynb',
41 {'id':session_id3, 'notebook':{'name':u'test3.ipynb',
44 'path': u'/path/to/3/'}, 'kernel':{'id':u'5678', 'ws_url': 'ws_url'}}]
42 'path': u'/path/to/3/'}, 'kernel':{'id':u'5678', 'ws_url': 'ws_url'}}]
45 self.assertEqual(sessions, expected)
43 self.assertEqual(sessions, expected)
46
44
47 def test_update_session(self):
45 def test_update_session(self):
48 sm = SessionManager()
46 sm = SessionManager()
49 session_id = sm.get_session_id()
47 session_id = sm.get_session_id()
50 sm.save_session(session_id=session_id, name='test.ipynb', path='/path/to/', kernel_id=None, ws_url='ws_url')
48 sm.save_session(session_id=session_id, name='test.ipynb', path='/path/to/', kernel_id=None, ws_url='ws_url')
51 sm.update_session(session_id, kernel_id='5678')
49 sm.update_session(session_id, kernel_id='5678')
52 sm.update_session(session_id, name='new_name.ipynb')
50 sm.update_session(session_id, name='new_name.ipynb')
53 model = sm.get_session(id=session_id)
51 model = sm.get_session(id=session_id)
54 expected = {'id':session_id, 'notebook':{'name':u'new_name.ipynb', 'path': u'/path/to/'}, 'kernel':{'id':u'5678', 'ws_url': 'ws_url'}}
52 expected = {'id':session_id, 'notebook':{'name':u'new_name.ipynb', 'path': u'/path/to/'}, 'kernel':{'id':u'5678', 'ws_url': 'ws_url'}}
55 self.assertEqual(model, expected)
53 self.assertEqual(model, expected)
56
54
57 def test_bad_update_session(self):
55 def test_bad_update_session(self):
58 # try to update a session with a bad keyword ~ raise error
56 # try to update a session with a bad keyword ~ raise error
59 sm = SessionManager()
57 sm = SessionManager()
60 session_id = sm.get_session_id()
58 session_id = sm.get_session_id()
61 sm.save_session(session_id=session_id, name='test.ipynb', path='/path/to/', kernel_id='5678', ws_url='ws_url')
59 sm.save_session(session_id=session_id, name='test.ipynb', path='/path/to/', kernel_id='5678', ws_url='ws_url')
62 self.assertRaises(TraitError, sm.update_session, session_id=session_id, bad_kw='test.ipynb') # Bad keyword
60 self.assertRaises(TraitError, sm.update_session, session_id=session_id, bad_kw='test.ipynb') # Bad keyword
63
61
64 def test_delete_session(self):
62 def test_delete_session(self):
65 sm = SessionManager()
63 sm = SessionManager()
66 session_id1 = sm.get_session_id()
64 session_id1 = sm.get_session_id()
67 session_id2 = sm.get_session_id()
65 session_id2 = sm.get_session_id()
68 session_id3 = sm.get_session_id()
66 session_id3 = sm.get_session_id()
69 sm.save_session(session_id=session_id1, name='test1.ipynb', path='/path/to/1/', kernel_id='5678', ws_url='ws_url')
67 sm.save_session(session_id=session_id1, name='test1.ipynb', path='/path/to/1/', kernel_id='5678', ws_url='ws_url')
70 sm.save_session(session_id=session_id2, name='test2.ipynb', path='/path/to/2/', kernel_id='5678', ws_url='ws_url')
68 sm.save_session(session_id=session_id2, name='test2.ipynb', path='/path/to/2/', kernel_id='5678', ws_url='ws_url')
71 sm.save_session(session_id=session_id3, name='test3.ipynb', path='/path/to/3/', kernel_id='5678', ws_url='ws_url')
69 sm.save_session(session_id=session_id3, name='test3.ipynb', path='/path/to/3/', kernel_id='5678', ws_url='ws_url')
72 sm.delete_session(session_id2)
70 sm.delete_session(session_id2)
73 sessions = sm.list_sessions()
71 sessions = sm.list_sessions()
74 expected = [{'id':session_id1, 'notebook':{'name':u'test1.ipynb',
72 expected = [{'id':session_id1, 'notebook':{'name':u'test1.ipynb',
75 'path': u'/path/to/1/'}, 'kernel':{'id':u'5678', 'ws_url': 'ws_url'}},
73 'path': u'/path/to/1/'}, 'kernel':{'id':u'5678', 'ws_url': 'ws_url'}},
76 {'id':session_id3, 'notebook':{'name':u'test3.ipynb',
74 {'id':session_id3, 'notebook':{'name':u'test3.ipynb',
77 'path': u'/path/to/3/'}, 'kernel':{'id':u'5678', 'ws_url': 'ws_url'}}]
75 'path': u'/path/to/3/'}, 'kernel':{'id':u'5678', 'ws_url': 'ws_url'}}]
78 self.assertEqual(sessions, expected)
76 self.assertEqual(sessions, expected)
79
77
80 def test_bad_delete_session(self):
78 def test_bad_delete_session(self):
81 # try to delete a session that doesn't exist ~ raise error
79 # try to delete a session that doesn't exist ~ raise error
82 sm = SessionManager()
80 sm = SessionManager()
83 session_id = sm.get_session_id()
81 session_id = sm.get_session_id()
84 sm.save_session(session_id=session_id, name='test.ipynb', path='/path/to/', kernel_id='5678', ws_url='ws_url')
82 sm.save_session(session_id=session_id, name='test.ipynb', path='/path/to/', kernel_id='5678', ws_url='ws_url')
85 self.assertRaises(TraitError, sm.delete_session, session_id='23424') # Bad keyword
83 self.assertRaises(web.HTTPError, sm.delete_session, session_id='23424') # Bad keyword
86
84
General Comments 0
You need to be logged in to leave comments. Login now