11 class RequestWrongOrder(Exception):
12 """issued if an unexpected request is issued to urllib2"""
13 def __init__(self, url, exp_url, method, exp_method):
14 Exception.__init__(self)
16 self.exp_url = exp_url
18 self.exp_method = exp_method
21 return '%s, %s, %s, %s' % (self.url, self.exp_url, self.method, self.exp_method)
23 class MyHTTPHandler(urllib2.HTTPHandler):
24 def __init__(self, exp_requests, fixtures_dir):
25 urllib2.HTTPHandler.__init__(self)
26 self.__exp_requests = exp_requests
27 self.__fixtures_dir = fixtures_dir
29 def http_open(self, req):
30 r = self.__exp_requests.pop(0)
31 if req.get_full_url() != r[1] and req.get_method() == r[0]:
32 raise RequestWrongOrder(req.get_full_url(), r[1], req.get_method(), r[0])
33 if req.get_method() == 'GET':
34 return self.__mock_GET(r[1], **r[2])
36 def __mock_GET(self, fullurl, **kwargs):
37 return self.__get_response(fullurl, **kwargs)
39 def __get_response(self, url, **kwargs):
41 if not kwargs.has_key('text') and kwargs.has_key('file'):
42 f = StringIO.StringIO(open(os.path.join(self.__fixtures_dir, kwargs['file']), 'r').read())
43 elif kwargs.has_key('text') and not kwargs.has_key('file'):
44 f = StringIO.StringIO(kwargs['text'])
46 raise RuntimeError('either specify text or file')
47 resp = urllib2.addinfourl(f, '', url)
52 def GET(fullurl, **kwargs):
53 def decorate(test_method):
54 def wrapped_test_method(*args):
55 addExpectedRequest('GET', fullurl, **kwargs)
57 return wrapped_test_method
60 def addExpectedRequest(method, url, **kwargs):
61 global EXPECTED_REQUESTS
62 EXPECTED_REQUESTS.append((method, url, kwargs))
64 class OscTestCase(unittest.TestCase):
66 osc.core.conf.get_config(override_conffile=os.path.join(self._get_fixtures_dir(), 'oscrc'))
67 self.tmpdir = tempfile.mkdtemp(prefix='osc_test')
68 shutil.copytree(os.path.join(self._get_fixtures_dir(), 'osctest'), os.path.join(self.tmpdir, 'osctest'))
69 global EXPECTED_REQUESTS
70 EXPECTED_REQUESTS = []
71 urllib2.install_opener(urllib2.build_opener(MyHTTPHandler(EXPECTED_REQUESTS, self._get_fixtures_dir())))
72 self.stdout = sys.stdout
73 sys.stdout = StringIO.StringIO()
76 self.assertTrue(len(EXPECTED_REQUESTS) == 0)
77 sys.stdout = self.stdout
79 shutil.rmtree(self.tmpdir)
83 def _get_fixtures_dir(self):
84 raise NotImplementedError('subclasses should implement this method')
86 def _change_to_pkg(self, name):
87 os.chdir(os.path.join(self.tmpdir, 'osctest', name))