summaryrefslogtreecommitdiff
path: root/test/test_keepalive.py
blob: f0d18d22ff899699f7fd2df00e3b015e2f261d2d (plain)
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
#!/usr/bin/python -t

#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License as published by the Free Software Foundation; either
#   version 2.1 of the License, or (at your option) any later version.
#
#   This library is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#   Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public
#   License along with this library; if not, write to the 
#      Free Software Foundation, Inc., 
#      59 Temple Place, Suite 330, 
#      Boston, MA  02111-1307  USA

# This file is part of urlgrabber, a high-level cross-protocol url-grabber
# Copyright 2002-2004 Michael D. Stenner, Ryan Tomayko

"""keepalive.py tests"""

# $Id: test_keepalive.py,v 1.9 2005/02/14 21:55:06 mstenner Exp $

import sys
import os
import time
import urllib2
import threading
import re

from urllib2 import URLError, HTTPError

from base_test_code import *

from urlgrabber import keepalive

class CorruptionTests(TestCase):
    def setUp(self):
        self.kh = keepalive.HTTPHandler()
        self.opener = urllib2.build_opener(self.kh)
        self.ref = ref_http
        self.fo = self.opener.open(self.ref)
        
    def tearDown(self):
        self.fo.close()
        self.kh.close_all()
        
    def test_readall(self):
        "download a file with a single call to read()"
        data = self.fo.read()
        self.assert_(data == reference_data)

    def test_readline(self):
        "download a file with multiple calls to readline()"
        data = ''
        while 1:
            s = self.fo.readline()
            if s: data = data + s
            else: break
        self.assert_(data == reference_data)

    def test_readlines(self):
        "download a file with a single call to readlines()"
        lines = self.fo.readlines()
        data = ''.join(lines)
        self.assert_(data == reference_data)

    def test_smallread(self):
        "download a file with multiple calls to read(23)"
        data = ''
        while 1:
            s = self.fo.read(23)
            if s: data = data + s
            else: break
        self.assert_(data == reference_data)

    def test_mixed_read(self):
        "download a file with mixed readline() and read(23) calls"
        data = ''
        while 1:
            s = self.fo.read(23)
            if s: data = data + s
            else: break
            s = self.fo.readline()
            if s: data = data + s
            else: break
        self.assert_(data == reference_data)

class HTTPErrorTests(TestCase):
    def setUp(self):
        self.kh = keepalive.HTTPHandler()
        self.opener = urllib2.build_opener(self.kh)
        import sys
        self.python_version = map(int, sys.version.split()[0].split('.'))
        
    def tearDown(self):
        self.kh.close_all()
        keepalive.HANDLE_ERRORS = 1

    def test_200_handler_on(self):
        "test that 200 works with fancy handler"
        keepalive.HANDLE_ERRORS = 1
        fo = self.opener.open(ref_http)
        data = fo.read()
        fo.close()
        self.assertEqual((fo.status, fo.reason), (200, 'OK'))

    def test_200_handler_off(self):
        "test that 200 works without fancy handler"
        keepalive.HANDLE_ERRORS = 0
        fo = self.opener.open(ref_http)
        data = fo.read()
        fo.close()
        self.assertEqual((fo.status, fo.reason), (200, 'OK'))

    def test_404_handler_on(self):
        "test that 404 works with fancy handler"
        keepalive.HANDLE_ERRORS = 1
        self.assertRaises(URLError, self.opener.open, ref_404)

    def test_404_handler_off(self):
        "test that 404 works without fancy handler"
        keepalive.HANDLE_ERRORS = 0
        ## see the HANDLE_ERRORS note in keepalive.py for discussion of
        ## the changes in python 2.4
        if self.python_version >= [2, 4]:
            self.assertRaises(URLError, self.opener.open, ref_404)
        else:
            fo = self.opener.open(ref_404)
            data = fo.read()
            fo.close()
            self.assertEqual((fo.status, fo.reason), (404, 'Not Found'))

    def test_403_handler_on(self):
        "test that 403 works with fancy handler"
        keepalive.HANDLE_ERRORS = 1
        self.assertRaises(URLError, self.opener.open, ref_403)

    def test_403_handler_off(self):
        "test that 403 works without fancy handler"
        keepalive.HANDLE_ERRORS = 0
        ## see the HANDLE_ERRORS note in keepalive.py for discussion of
        ## the changes in python 2.4
        if self.python_version >= [2, 4]:
            self.assertRaises(URLError, self.opener.open, ref_403)
        else:
            fo = self.opener.open(ref_403)
            data = fo.read()
            fo.close()
            self.assertEqual((fo.status, fo.reason), (403, 'Forbidden'))

class DroppedConnectionTests(TestCase):
    def setUp(self):
        self.kh = keepalive.HTTPHandler()
        self.opener = urllib2.build_opener(self.kh)
        self.snarfed_logs = []
        self.dbp = keepalive.DBPRINT
        keepalive.DBPRINT = self.logsnarf
        keepalive.DEBUG = 1
        
    def tearDown(self):
        self.kh.close_all()
        keepalive.DBPRINT = self.dbp
        keepalive.DEBUG = 0
        
    def logsnarf(self, message):
        self.snarfed_logs.append(message)
        
    def test_dropped_connection(self):
        "testing connection restarting (20-second delay, ctrl-c to skip)"
        # the server has a 15-second keepalive timeout (the apache default)
        fo = self.opener.open(ref_http)
        data1 = fo.read()
        fo.close()

        try: time.sleep(20)
        except KeyboardInterrupt: self.skip()
        
        fo = self.opener.open(ref_http)
        data2 = fo.read()
        fo.close()
        
        reference_logs = [
            'creating new connection to www.linux.duke.edu',
            'STATUS: 200, OK',
            'failed to re-use connection to www.linux.duke.edu',
            'creating new connection to www.linux.duke.edu',
            'STATUS: 200, OK'
            ]
        self.assert_(data1 == data2)
        l = [ re.sub(r'\s+\(-?\d+\)$', r'', line) for \
              line in self.snarfed_logs ]
        self.assert_(l == reference_logs)
        
class ThreadingTests(TestCase):
    def setUp(self):
        self.kh = keepalive.HTTPHandler()
        self.opener = urllib2.build_opener(self.kh)
        self.snarfed_logs = []
        self.dbp = keepalive.DBPRINT
        keepalive.DBPRINT = self.logsnarf
        keepalive.DEBUG = 1

    def tearDown(self):
        self.kh.close_all()
        keepalive.DBPRINT = self.dbp
        keepalive.DEBUG = 0
        
    def logsnarf(self, message):
        self.snarfed_logs.append(message)

    def test_basic_threading(self):
        "use 3 threads, each getting a file 4 times"
        numthreads = 3
        cond = threading.Condition()
        self.threads = []
        for i in range(numthreads):
            t = Fetcher(self.opener, ref_http, 4)
            t.start()
            self.threads.append(t)
        for t in self.threads: t.join()
        l = [ re.sub(r'\s+\(-?\d+\)$', r'', line) for line in self.snarfed_logs ]
        l.sort()
        creating = ['creating new connection to www.linux.duke.edu'] * 3
        status = ['STATUS: 200, OK'] * 12
        reuse = ['re-using connection to www.linux.duke.edu'] * 9
        reference_logs = creating + status + reuse
        reference_logs.sort()
        #print '--------------------'
        #for log in l: print log
        #print '--------------------'
        #for log in reference_logs: print log
        #print '--------------------'
        self.assert_(l == reference_logs)
            
class Fetcher(threading.Thread):
    def __init__(self, opener, url, num):
        threading.Thread.__init__(self)
        self.opener = opener
        self.url = url
        self.num = num
        
    def run(self):
        for i in range(self.num):
            fo = self.opener.open(self.url)
            data = fo.read()
            fo.close()
    
def suite():
    tl = TestLoader()
    return tl.loadTestsFromModule(sys.modules[__name__])

if __name__ == '__main__':
    runner = TextTestRunner(stream=sys.stdout,descriptions=1,verbosity=2)
    runner.run(suite())