- moved common methods into the OscTestCase class
[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         # "rename" method otherwise we cannot specify a TestCaseClass.testName
58         # cmdline arg when using unittest.main()
59         wrapped_test_method.__name__ = test_method.__name__
60         return wrapped_test_method
61     return decorate
62
63 def addExpectedRequest(method, url, **kwargs):
64     global EXPECTED_REQUESTS
65     EXPECTED_REQUESTS.append((method, url, kwargs))
66
67 class OscTestCase(unittest.TestCase):
68     def setUp(self):
69         osc.core.conf.get_config(override_conffile=os.path.join(self._get_fixtures_dir(), 'oscrc'))
70         self.tmpdir = tempfile.mkdtemp(prefix='osc_test')
71         shutil.copytree(os.path.join(self._get_fixtures_dir(), 'osctest'), os.path.join(self.tmpdir, 'osctest'))
72         global EXPECTED_REQUESTS
73         EXPECTED_REQUESTS = []
74         urllib2.install_opener(urllib2.build_opener(MyHTTPHandler(EXPECTED_REQUESTS, self._get_fixtures_dir())))
75         self.stdout = sys.stdout
76         sys.stdout = StringIO.StringIO()
77
78     def tearDown(self):
79         self.assertTrue(len(EXPECTED_REQUESTS) == 0)
80         sys.stdout = self.stdout
81         try:
82             shutil.rmtree(self.tmpdir)
83         except:
84             pass
85
86     def _get_fixtures_dir(self):
87         raise NotImplementedError('subclasses should implement this method')
88
89     def _change_to_pkg(self, name):
90         os.chdir(os.path.join(self.tmpdir, 'osctest', name))
91
92     def __check_list(self, fname, exp):
93         fname = os.path.join('.osc', fname)
94         self.assertTrue(os.path.exists(fname))
95         self.assertEqual(open(fname, 'r').read(), exp)
96
97     def _check_addlist(self, exp):
98         self.__check_list('_to_be_added', exp)
99
100     def _check_deletelist(self, exp):
101         self.__check_list('_to_be_deleted', exp)
102
103     def _check_conflictlist(self, exp):
104         self.__check_list('_in_conflict', exp)
105
106     def _check_status(self, p, fname, exp):
107         self.assertEqual(p.status(fname), exp)