- moved __change_to_pkg into common module (new name _change_to_pkg)
[opensuse:osc.git] / tests / common.py
1 import unittest
2 import urllib2
3 import osc.core
4 import StringIO
5 import shutil
6 import tempfile
7 import os
8 import sys
9 EXPECTED_REQUESTS = []
10
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)
15         self.url = url
16         self.exp_url = exp_url
17         self.method = method
18         self.exp_method = exp_method
19
20     def __str__(self):
21         return '%s, %s, %s, %s' % (self.url, self.exp_url, self.method, self.exp_method)
22
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
28
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])
35
36     def __mock_GET(self, fullurl, **kwargs):
37         return self.__get_response(fullurl, **kwargs)
38
39     def __get_response(self, url, **kwargs):
40         f = None
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'])
45         else:
46             raise RuntimeError('either specify text or file')
47         resp = urllib2.addinfourl(f, '', url)
48         resp.code = 200
49         resp.msg = ''
50         return resp
51
52 def GET(fullurl, **kwargs):
53     def decorate(test_method):
54         def wrapped_test_method(*args):
55             addExpectedRequest('GET', fullurl, **kwargs)
56             test_method(*args)
57         return wrapped_test_method
58     return decorate
59
60 def addExpectedRequest(method, url, **kwargs):
61     global EXPECTED_REQUESTS
62     EXPECTED_REQUESTS.append((method, url, kwargs))
63
64 class OscTestCase(unittest.TestCase):
65     def setUp(self):
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()
74
75     def tearDown(self):
76         self.assertTrue(len(EXPECTED_REQUESTS) == 0)
77         sys.stdout = self.stdout
78         try:
79             shutil.rmtree(self.tmpdir)
80         except:
81             pass
82
83     def _get_fixtures_dir(self):
84         raise NotImplementedError('subclasses should implement this method')
85
86     def _change_to_pkg(self, name):
87         os.chdir(os.path.join(self.tmpdir, 'osctest', name))