import json
import os.path


class MockedResponse(object):
    # used to mock out KoalityBackend._get_response
    def __init__(self, base_url, fixture_root):
        self.base_url = base_url
        self.fixture_root = fixture_root

    def __call__(self, method, url, **kwargs):
        fixture = self.load_fixture(method, url, **kwargs)
        if fixture is None:
            # TODO:
            raise Exception

        fixture = os.path.join(self.fixture_root, fixture)

        with open(fixture) as fp:
            return json.load(fp)

    def load_fixture(self, method, url, **kwargs):
        return os.path.join(method.upper(), self.url_to_filename(url))

    def url_to_filename(self, url):
        assert url.startswith(self.base_url)
        return url[len(self.base_url) + 1:].strip('/').replace('/', '__') + '.json'

@@ -21,16 +21,48 @@
 s.path%0A%0A
+from cStringIO import StringIO%0A%0A
 %0Aclass M
@@ -858,8 +858,746 @@
 '.json'%0A
+%0A%0Aclass MockedHTTPConnection(object):%0A    def __init__(self, *args, **kwargs):%0A        self.responder = MockedResponse(*args, **kwargs)%0A%0A    def __call__(self, host, **kwargs):%0A        %22%22%22%0A        Acts as HTTPConnection.__init__%0A        %22%22%22%0A        self._host = host%0A        self._request = None%0A        return self%0A%0A    def request(self, method, path, body=None, headers=%7B%7D):%0A        assert self._request is None%0A        self._request = %7B%0A            'method': method,%0A            'url': 'http://%7B0%7D/%7B1%7D'.format(self._host, path),%0A            'data': body,%0A            'headers': headers,%0A        %7D%0A%0A    def getresponse(self):%0A        assert self._request is not None%0A        return StringIO(json.dumps(self.responder(**self._request)))%0A

Add MockHTTPConnection to testutils