LOC-24 Added tests for kick/ban functionality
[LocalChat.git] / tests / run_tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
#!/usr/bin/env python
#
# apt-get install:
#   python-psutil
#
import subprocess
import psutil
import os
import sys
import time
import sqlite3
import traceback
import json
 
 
try:
    from subprocess import DEVNULL # py3k
except ImportError:
    import os
    DEVNULL = open(os.devnull, 'wb')
 
 
DB_FILE = "%s/localchat-testing.db" % (os.getcwd(),)
PARENT_DIR = "%s/.." % (os.path.dirname(os.path.abspath(__file__)),)
sys.path.append('%s/client/' % (PARENT_DIR,))
 
import LocalChatClient
STORAGE = {}
 
 
def restartServer(proc1):
    ''' Start the server component
    
    If already running (i.e. proc1 != False) kill the existing instance
    '''
    
    # If we've already got a process, kill it
    if proc1:
        kill(proc1.pid)
    
    try:
        serverloc = "%s/server/LocalChat.py" % (PARENT_DIR,)
        proc1 = subprocess.Popen([serverloc,'--testing-mode-enable'],stderr=subprocess.STDOUT,stdout=DEVNULL)
    except Exception as e:
        print "Failed to start server"
        print e
        return False
    
    # Give it time to start up
    time.sleep(5)
    return proc1
 
 
def getClientInstance():
    ''' Get an instance of the client class
    '''
    return LocalChatClient.msgHandler()
 
 
def exit(proc1,code=0):
    ''' Tidy up and exit
    '''
    
    if proc1:
        kill(proc1.pid)
        
    sys.exit(code)
 
 
 
def kill(proc_pid):
    ''' Kill the process and it's children
    
    From https://stackoverflow.com/a/25134985
    
    We use this because proc1.kill() doesn't seem to kill of the child thread of the server, even if shell=True
    '''
    process = psutil.Process(proc_pid)
    for proc in process.children(recursive=True):
        proc.kill()
    process.kill()
 
 
 
def make_table(columns, data):
    """Create an ASCII table and return it as a string.
 
    Pass a list of strings to use as columns in the table and a list of
    dicts. The strings in 'columns' will be used as the keys to the dicts in
    'data.'
 
 
    https://snippets.bentasker.co.uk/page-1705192300-Make-ASCII-Table-Python.html
    """
    # Calculate how wide each cell needs to be
    cell_widths = {}
    for c in columns:
        lens = []
        values = [lens.append(len(str(d.get(c, "")))) for d in data]
        lens.append(len(c))
        lens.sort()
        cell_widths[c] = max(lens)
 
    # Used for formatting rows of data
    row_template = "|" + " {} |" * len(columns)
 
    # CONSTRUCT THE TABLE
 
    # The top row with the column titles
    justified_column_heads = [c.ljust(cell_widths[c]) for c in columns]
    header = row_template.format(*justified_column_heads)
    # The second row contains separators
    sep = "|" + "-" * (len(header) - 2) + "|"
    end = "-" * len(header)
    # Rows of data
    rows = []
 
    for d in data:
        fields = [str(d.get(c, "")).ljust(cell_widths[c]) for c in columns]
        row = row_template.format(*fields)
        rows.append(row)
    rows.append(end)
    return "\n".join([header, sep] + rows)
 
 
 
def opendb():
    ''' We'll do this and then close after every query to make sure we don't
    inadvertantly lock the DB and force tests to fail.
    
    '''
    CONN = sqlite3.connect(DB_FILE)
    CURSOR = CONN.cursor()
 
    return [CONN,CURSOR]
    
 
def run_tests():
    
    # Get an instance of the client
    msg = getClientInstance();
    
    test_results = []
    tests = ['test_one','test_two','test_three','test_four',
             'test_five','test_six','test_seven','test_eight',
             'test_nine','test_ten','test_eleven','test_twelve']
    x = 1
    for test in tests:
        print "Running %s " % (test,)
        stat,isFatal = globals()[test](msg)
        stat['No'] = x
        test_results.append(stat)
        if isFatal and stat['Result'] == 'FAIL':
            break
 
        x = x + 1
 
    return test_results
 
 
 
 
def test_one(msg):
    ''' Create a room and verify that it gets created
    '''
    
    result = {'Test' : 'Create a Room','Result' : 'FAIL', 'Notes': '' }
    isFatal = True
    # Test 1 - create a room and check it's recorded in the DB
    n = msg.createRoom('TestRoom1','testadmin')
    
    if not n:
        result['Notes'] = 'Empty Response'
        return [result,isFatal]
    
    # The client should have given us two passwords
    if len(n) < 2:
        result['Notes'] = 'Response too small'
        return [result,isFatal]
    
    # Seperate out the return value
    roompass = n[0]
    userpass = n[1] # user specific password    
 
    STORAGE['room'] = {"name":"TestRoom1",
                       "RoomPass":roompass,
                       "UserPass":userpass,
                       'User':'testadmin'
                       }
    
    
    CONN,CURSOR = opendb()
    
    # Check the DB to ensure the room was actually created
    CURSOR.execute("SELECT * from rooms where name=?",('TestRoom1',))
    r = CURSOR.fetchone()
    CONN.close()
    
    if not r:
        result['Notes'] = 'Room not in DB'
        return [result,isFatal]
    
    result['Result'] = 'Pass'
    return [result,isFatal]
 
 
 
 
def test_two(msg):
    ''' Try joining the previously created room with invalid credentials
    '''
    
    result = {'Test' : 'Join the room with invalid creds','Result' : 'FAIL', 'Notes': '' }
    isFatal = False
    n = msg.joinRoom(STORAGE['room']['User'],STORAGE['room']['name'],
                     "%s:%s" % (STORAGE['room']['RoomPass'],'BlatantlyWrong'))
    
    if n:
        result['Notes'] = 'Allowed to join with invalid pass'
        return [result,isFatal]
    
    
    # Now try with an invalid username
    result = {'Test' : 'Join the room with invalid creds','Result' : 'FAIL', 'Notes': '' }
    n = msg.joinRoom('AlsoWrong',STORAGE['room']['name'],"%s:%s" % (STORAGE['room']['RoomPass'],'BlatantlyWrong'))
    
    if n:
        result['Notes'] = 'Invalid user Allowed to join'
        return [result,isFatal]
        
    result['Result'] = 'Pass'
    return [result,isFatal]
 
 
 
 
def test_three(msg):
    ''' Join the previously created room
    '''
    
    result = {'Test' : 'Join the room','Result' : 'FAIL', 'Notes': '' }
    isFatal = True
    n = msg.joinRoom(STORAGE['room']['User'],STORAGE['room']['name'],
                     "%s:%s" % (STORAGE['room']['RoomPass'],STORAGE['room']['UserPass'])
                     )
    
    if not n:
        result['Notes'] = 'Could not join'
        return [result,isFatal]
    
    CONN,CURSOR = opendb()
    
    # Check the DB to ensure we're now active
    CURSOR.execute("SELECT * from users where username=? and active=1",(STORAGE['room']['User'],))
    r = CURSOR.fetchone()
    CONN.close()
    
    if not r:
        result['Notes'] = 'Not Active in DB'
        return [result,isFatal]
    
    # Check we've got a session token
    if not msg.sesskey:
        result['Notes'] = 'No Session Key'
        return [result,isFatal]
        
    # Check the client has recorded what it needs to
    if not msg.room:
        result['Notes'] = 'Client forgot room'
        return [result,isFatal]
 
    if not msg.user:
        result['Notes'] = 'Client forgot user'
        return [result,isFatal]
 
    if not msg.roompass:
        result['Notes'] = 'Client forgot roompass'
        return [result,isFatal]
 
    if not msg.syskey:
        result['Notes'] = 'No SYSTEM key'
        return [result,isFatal]
    
    
    result['Result'] = 'Pass'
    return [result,isFatal]
 
 
def test_four(msg):
    ''' When we joined, SYSTEM will have pushed a message. Ensure it's encrypted
    '''
    
    result = {'Test' : 'SYSTEM uses E2E','Result' : 'FAIL', 'Notes': '' }
    isFatal = False
 
 
    CONN,CURSOR = opendb()
 
    CURSOR.execute("SELECT msg FROM messages where user='SYSTEM' ORDER BY ts DESC")
    r = CURSOR.fetchone()
    CONN.close()
    
    if not r:
        result['Notes'] = 'No System Message'
        return [result,isFatal]
    
    
    try:
        json.loads(r[0])
        result['Notes'] = 'System Message not E2E encrypted'
        return [result,isFatal]       
    except:
        # This is a good thing in this case!
        
        # Now try and decrypt the message
        m = msg.decrypt(r[0],'SYSTEM')
        if not m:
            result['Notes'] = 'Could not decrypt'
            return [result,isFatal]     
    
        # Now check we got valid json
        try:
            j = json.loads(m)
            # Finally
            if "text" not in j or "verb" not in j:
                result['Notes'] = 'Not valid msg payload'
                return [result,isFatal]              
            
            # Otherwise, we're good
            result['Result'] = 'Pass'
            return [result,isFatal]
            
        except:
            result['Notes'] = 'Not valid JSON'
            return [result,isFatal]              
    
 
def test_five(msg):
    ''' Send a message and ensure it's encrypted in the DB
    '''
    
    result = {'Test' : 'Ensure payloads are encrypted','Result' : 'FAIL', 'Notes': '' }
    isFatal = False
    
    msg.sendMsg('Hello World')
    
    CONN,CURSOR = opendb()
    
    CURSOR.execute("SELECT msg FROM messages where user=? ORDER BY ts DESC",(STORAGE['room']['User'],))
    r = CURSOR.fetchone()
    CONN.close()
    
    if not r:
        result['Notes'] = 'Message not recorded'
        return [result,isFatal]
    
    
    try:
        json.loads(r[0])
        result['Notes'] = 'Message not E2E encrypted'
        return [result,isFatal]       
    except:
        # This is a good thing in this case!
        
        # Now try and decrypt the message
        m = msg.decrypt(r[0],STORAGE['room']['User'])
        if not m:
            result['Notes'] = 'Could not decrypt'
            return [result,isFatal]     
    
        # Now check we got valid json
        try:
            j = json.loads(m)
            # Finally
            if "text" not in j or "verb" not in j:
                result['Notes'] = 'Not valid msg payload'
                return [result,isFatal]              
            
            # Otherwise, we're good
            result['Result'] = 'Pass'
            return [result,isFatal]
            
        except:
            result['Notes'] = 'Not valid JSON'
            return [result,isFatal]              
    
 
 
def test_six(msg):
    ''' Invite a user
    '''
    result = {'Test' : 'Invite a user','Result' : 'FAIL', 'Notes': '' }
    isFatal = True
    
    n = msg.inviteUser('testuser')
    if not n:
        result['Notes'] = 'Could not invite testuser'
        return [result,isFatal]
    
    if len(n) < 4:
        result['Notes'] = 'Client returned too short response'
        return [result,isFatal]
        
    # Otherwise, we've got details for a new user to be able to join
    #
    # Store them for a later test
    
    STORAGE['testuser'] = {
        'room':n[0],
        'pass':"%s:%s" % (n[1],n[2]),
        'User':n[3]
        }
    
    result['Result'] = "Pass"
    return [result,isFatal]
 
 
 
def test_seven(msg):
    ''' Have the previously invited user join from a new client instance
    '''
    result = {'Test' : 'Join as Invited User','Result' : 'FAIL', 'Notes': '' }
    isFatal = True
    
    usermsg = getClientInstance();
    n = usermsg.joinRoom(STORAGE['testuser']['User'],STORAGE['testuser']['room'],STORAGE['testuser']['pass'])
    
    if not n:
        result['Notes'] = 'Could not join'
        return [result,isFatal]
    
    STORAGE['testuser']['clientInstance'] = usermsg
    
    CONN,CURSOR = opendb()
    
    # Check the DB to ensure we're now active
    CURSOR.execute("SELECT * from users where username=? and active=1",(STORAGE['testuser']['User'],))
    r = CURSOR.fetchone()
    CONN.close()
    
    if not r:
        result['Notes'] = 'Not Active in DB'
        return [result,isFatal]
    
    # Check we've got a session token
    if not msg.sesskey:
        result['Notes'] = 'No Session Key'
        return [result,isFatal]
        
    # Check the client has recorded what it needs to
    if not msg.room:
        result['Notes'] = 'Client forgot room'
        return [result,isFatal]
 
    if not msg.user:
        result['Notes'] = 'Client forgot user'
        return [result,isFatal]
 
    if not msg.roompass:
        result['Notes'] = 'Client forgot roompass'
        return [result,isFatal]
 
    if not msg.syskey:
        result['Notes'] = 'No SYSTEM key'
        return [result,isFatal]
    
    
    result['Result'] = 'Pass'
    return [result,isFatal]
 
 
def test_eight(msg):
    ''' Have the testuser send a message and ensure that the adminuser receives it
    
    We first call pollMsg to flush the message queue
    '''
    
    result = {'Test' : 'Send a Message','Result' : 'FAIL', 'Notes': '' }
    isFatal = False
        
    # Poll for messages to clear the queue
    f = msg.pollForMessage()
    
    testpayload = 'The admin is a ....'
    # Now send a message as test user
    STORAGE['testuser']['clientInstance'].sendMsg(testpayload)
    
    # Now call pollMsg as admin to ensure we receive the message
    received = msg.pollForMessage()
 
    # Poll as testuser to clear the queue ready for future tests
    f = STORAGE['testuser']['clientInstance'].pollForMessage()
    
    if len(received) < 1:
        result['Notes'] = 'No messages received'
        return [result,isFatal]
    
    if len(received[0]) < 2:
        result['Notes'] = 'Malformed message returned'
        return [result,isFatal]
        
    # Now check the payload
    #
    # We need to trim out the timestamp etc
    r = received[0][1].split('>')
    m = r[1].lstrip()
    if testpayload != m:
        result['Notes'] = 'Incorrect message received: (%s)v(%s)' % (testpayload,m)
        return [result,isFatal]
        
    result['Result'] = 'Pass'
    return [result,isFatal]
 
 
 
def test_nine(msg):
    ''' Try to maliciously invite SYSTEM (as a precursor to logging in as them)
    
    Essentially a regression test for LOC-5
    
    '''
    
    result = {'Test' : 'LOC-5 Try to invite SYSTEM','Result' : 'FAIL', 'Notes': '' }
    isFatal = False
        
    # Poll for messages to clear the queue
    f = msg.pollForMessage()
    
    # Now have the test user try to invite SYSTEM
    n = STORAGE['testuser']['clientInstance'].inviteUser('SYSTEM')
    if n:
        result['Notes'] = 'Allowed to invite SYSTEM'
        return [result,isFatal]
    
    # Now call pollMsg as admin to ensure we received the warning message
    received = msg.pollForMessage()
 
    # Poll as testuser to clear the queue ready for future tests
    f = STORAGE['testuser']['clientInstance'].pollForMessage()
    
    if len(received) < 1:
        result['Notes'] = 'No warning message received'
        return [result,isFatal]
    
    if len(received[0]) < 2:
        result['Notes'] = 'Malformed message returned'
        return [result,isFatal]
        
    # Now check the payload
    #
    # We need to trim out the timestamp etc
    r = received[0][1].split('>')
    m = r[1].lstrip()
    
    expected = "ALERT: User %s tried to invite SYSTEM" % (STORAGE['testuser']['User'],)
 
    if expected != m:
        result['Notes'] = 'Unexpected message received: %s' % (m)
        return [result,isFatal]
        
    result['Result'] = 'Pass'
    return [result,isFatal]
 
 
def test_ten(msg):
    ''' Send a direct message and ensure it's received
    
    '''
    
    result = {'Test' : 'Send a Direct Message','Result' : 'FAIL', 'Notes': '' }
    isFatal = False
    
    # Poll for messages to clear the queue
    f = msg.pollForMessage()
    f = STORAGE['testuser']['clientInstance'].pollForMessage()
    
    testpayload = 'Hi Hi'
    
    # Now send a direct message from test user to admin
    n = STORAGE['testuser']['clientInstance'].sendDirectMsg(testpayload,'testadmin')
    if not n:
        result['Notes'] = 'Could not send direct message'
        return [result,isFatal]
    
    # Poll as the admin user to ensure it was received
    received = msg.pollForMessage()
    
    # Poll as testuser to clear the queue ready for future tests
    f = STORAGE['testuser']['clientInstance'].pollForMessage()
    
    if len(received) < 1:
        result['Notes'] = 'No messages received'
        return [result,isFatal]
    
    if len(received[0]) < 2:
        result['Notes'] = 'Malformed message returned'
        return [result,isFatal]
        
    # Now check the payload
    #
    # We need to trim out the timestamp etc
    r = received[0][1].split('>')
    m = r[1].lstrip()
    if testpayload != m:
        result['Notes'] = 'Incorrect message received: (%s)v(%s)' % (testpayload,m)
        return [result,isFatal]
        
    if "DM" not in r[0]:
        result['Notes'] = 'Envelope not marked as DM: %s' % (r[0],)
        return [result,isFatal]
        
    result['Result'] = 'Pass'
    return [result,isFatal]
    
 
 
def test_eleven(msg):
    ''' Invite a new user and then have admin kick them to ensure they're 
    actually kicked out of the room
    
    '''
    result = {'Test' : 'Invite and kick a user','Result' : 'FAIL', 'Notes': '' }
    isFatal = True
    
    n = msg.inviteUser('testuser2')
    if not n:
        result['Notes'] = 'Could not invite testuser2'
        return [result,isFatal]
    
    if len(n) < 4:
        result['Notes'] = 'Client returned too short response'
        return [result,isFatal]
        
    # Otherwise, we've got details for a new user to be able to join
    #
    # Store them for a later test
    
    STORAGE['testuser2'] = {
        'room':n[0],
        'pass':"%s:%s" % (n[1],n[2]),
        'User':n[3]
        }
    
    # Create a new instance so we can join as testuser2
    usermsg = getClientInstance();
    n = usermsg.joinRoom(STORAGE['testuser2']['User'],STORAGE['testuser2']['room'],STORAGE['testuser2']['pass'])
    
    if not n:
        result['Notes'] = 'User could not join'
        return [result,isFatal]
    
    STORAGE['testuser2']['clientInstance'] = usermsg
    
    # Now have the admin kick (but not ban) them
    msg.kickUser('testuser2',False)
    
    
    # Check that a failure message was written
    CONN,CURSOR = opendb()
    CURSOR.execute("SELECT msg FROM failuremsgs where username=?",(STORAGE['testuser2']['User'],))
    r = CURSOR.fetchone()
    CONN.close()
    
    if not r:
        result['Notes'] = 'User not notified'
        return [result,isFatal]  
        
    # Poll to receive the failure message and verify it's deleted
    msgs = STORAGE['testuser2']['clientInstance'].pollForMessage()
    
    if len(msgs) < 1:
        result['Notes'] = "User didn't receive notification"
        return [result,isFatal]        
    
    CONN,CURSOR = opendb()
    CURSOR.execute("SELECT msg FROM failuremsgs where username=?",(STORAGE['testuser2']['User'],))
    r = CURSOR.fetchone()
    CONN.close()
    
    if r:
        result['Notes'] = 'Notification not purged on poll'
        return [result,isFatal]  
    
    # Now check that their session was suspended
    CONN,CURSOR = opendb()
    CURSOR.execute("SELECT username FROM users where username=? and active=1",(STORAGE['testuser2']['User'],))
    r = CURSOR.fetchone()
    CONN.close()
    
    if r:
        result['Notes'] = 'User still considered active in room'
        return [result,isFatal]         
    
    # Check if their session still exists
    CONN,CURSOR = opendb()
    CURSOR.execute("SELECT username FROM sessions where username=?",(STORAGE['testuser2']['User'],))
    r = CURSOR.fetchone()
    CONN.close()    
    if r:
        result['Notes'] = 'User still has active session'
        return [result,isFatal]        
    
    # Otherwise, looks good
    result['Result'] = "Pass"
    return [result,isFatal]
 
 
def test_twelve(msg):
    ''' Rejoin as the previously invited user, and then ban them
    
    
    '''
    result = {'Test' : 'Ban a user','Result' : 'FAIL', 'Notes': '' }
    isFatal = True
    
    # Flush the failedmessage queue
    f = STORAGE['testuser2']['clientInstance'].pollForMessage()
    
    # Re-join as testuser2
    n = STORAGE['testuser2']['clientInstance'].joinRoom(STORAGE['testuser2']['User'],
                                                        STORAGE['testuser2']['room'],STORAGE['testuser2']['pass'])
    
    if not n:
        result['Notes'] = 'TestUser2 could not join'
        return [result,isFatal]
    
    # Now have the admin ban them
    msg.kickUser('testuser2',True)
    
    
    # Check that a failure message was written
    CONN,CURSOR = opendb()
    CURSOR.execute("SELECT msg FROM failuremsgs where username=?",(STORAGE['testuser2']['User'],))
    r = CURSOR.fetchone()
    CONN.close()
    
    if not r:
        result['Notes'] = 'User not notified'
        return [result,isFatal]  
    
    # Poll to receive the failure message and verify it's deleted
    msgs = STORAGE['testuser2']['clientInstance'].pollForMessage()
    
    if len(msgs) < 1:
        result['Notes'] = "User didn't receive notification"
        return [result,isFatal]        
    
    CONN,CURSOR = opendb()
    CURSOR.execute("SELECT msg FROM failuremsgs where username=?",(STORAGE['testuser2']['User'],))
    r = CURSOR.fetchone()
    CONN.close()
    
    if r:
        result['Notes'] = 'Notification not purged on poll'
        return [result,isFatal]  
   
    # Now check that their session was suspended
    CONN,CURSOR = opendb()
    CURSOR.execute("SELECT username FROM users where username=?",(STORAGE['testuser2']['User'],))
    r = CURSOR.fetchone()
    CONN.close()
    
    if r:
        result['Notes'] = 'User still exists for room'
        return [result,isFatal]         
    
    # Check if their session still exists
    CONN,CURSOR = opendb()
    CURSOR.execute("SELECT username FROM sessions where username=?",(STORAGE['testuser2']['User'],))
    r = CURSOR.fetchone()
    CONN.close()    
    if r:
        result['Notes'] = 'User still has active session'
        return [result,isFatal]        
    
    # We don't need this any more
    del STORAGE['testuser2']
    
    # Otherwise, looks good
    result['Result'] = "Pass"
    return [result,isFatal]
 
 
    
 
 
if __name__ == '__main__':
    # Start the server
    proc1 = restartServer(False)
 
    if not proc1:
        # Server start failed.
        # abort, abort, abort
        exit(proc1,1)
 
    
    try:
        # I don't like generic catchall exceptions
        # but, we want to make sure we kill the background
        # process if there is one.
        results = run_tests()
    except Exception as e:
        print traceback.format_exc()
        print e
        exit(proc1,1)
    
    cols = ['No','Test','Result','Notes']
    print make_table(cols,results)
    
    exit(proc1,0)