My favorites | Sign in
Project Logo
                
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
import urlparse
import urllib
import httplib2
from email import message_from_string, message_from_file
import os



class MockHttp:
"""
A mock for httplib2.Http that takes its
response headers and bodies from files on disk
"""
def __init__(self, directory):
self.directory = directory
self.hit_counter = {}

def request(self, uri, method="GET", body=None, headers=None, redirections=5):
counter = self.hit_counter.get(method+uri, 0)
counter += 1
self.hit_counter[method+uri] = counter
path = urlparse.urlparse(uri)[2]
fname = os.path.join(self.directory, method, urllib.quote(path.strip("/")) + ".file")
fname_next = fname + "." + str(counter)
if os.path.exists(fname_next):
fname = fname_next
if os.path.exists(fname):
f = file(fname, "r")
response = message_from_file(f)
f.close()
body = response.get_payload()
headers = httplib2.Response(response)
return (headers, body)
else:
return (httplib2.Response({"status": "404"}), "")

def add_credentials(self, name, password):
pass


class MockRecorder(httplib2.Http):
def __init__(self, h, directory):
self.h = h
self.directory = directory
self.hit_counter = {}

def request(self, uri, method="GET", body=None, headers=None, redirections=5):
counter = self.hit_counter.get(method+uri, 0)
counter += 1
self.hit_counter[method+uri] = counter
headers, body = self.h.request(uri, method, body, headers, redirections)
path = urlparse.urlparse(uri)[2]
fname = os.path.join(self.directory, method, urllib.quote(path.strip("/")) + ".file")
if counter >= 2:
fname = fname + "." + str(counter)
dirname = os.path.dirname(fname)
if not os.path.exists(dirname):
os.makedirs(dirname)

f = file(fname, "w")
f.write(
"\r\n".join(["%s: %s" % (key, value) for key, value in headers.iteritems()])
)
f.write("\r\n\r\n")
f.write(body)
f.close()
return (headers, body)

def add_credentials(self, name, password):
h.add_credentials(name, password)
Show details Hide details

Change log

r971 by joe.gregorio on Mar 01, 2008   Diff
now quoting the generated filenames when
mocking
Go to: 
Project members, sign in to write a code review

Older revisions

r970 by joe.gregorio on Mar 01, 2008   Diff
Changed MockHttp so that it got the
src directory passed into it.
r969 by joe.gregorio on Mar 01, 2008   Diff
fixed bug in URI numberings
r968 by joe.gregorio on Mar 01, 2008   Diff
Added counters to mock uris so that we
can have multiple requests to the same
uri
All revisions of this file

File info

Size: 2313 bytes, 70 lines

File properties

svn:mime-type
text/x-python
svn:eol-style
native
svn:executable
*
svn:keywords
Id
Hosted by Google Code