~bzr-pqm/bzr/bzr.dev

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# Copyright (C) 2005 by Canonical Ltd

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import BaseHTTPServer, SimpleHTTPServer
from bzrlib.selftest import TestCaseInTempDir


class WebserverNotAvailable(Exception):
    pass

class BadWebserverPath(ValueError):
    def __str__(self):
        return 'path %s is not in %s' % self.args

class TestingHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def log_message(self, format, *args):
        self.server.test_case.log("webserver - %s - - [%s] %s\n" %
                                  (self.address_string(),
                                   self.log_date_time_string(),
                                   format%args))

class TestingHTTPServer(BaseHTTPServer.HTTPServer):
    def __init__(self, server_address, RequestHandlerClass, test_case):
        BaseHTTPServer.HTTPServer.__init__(self, server_address,
                                                RequestHandlerClass)
        self.test_case = test_case

class TestCaseWithWebserver(TestCaseInTempDir):
    """Derived class that starts a localhost-only webserver
    (in addition to what TestCaseInTempDir does).

    This is useful for testing RemoteBranch.
    """

    _HTTP_PORTS = range(13000, 0x8000)

    def _http_start(self):
        import SimpleHTTPServer, BaseHTTPServer, socket, errno
        httpd = None
        for port in self._HTTP_PORTS:
            try:
                httpd = TestingHTTPServer(('localhost', port),
                                          TestingHTTPRequestHandler,
                                          self)
            except socket.error, e:
                if e.args[0] == errno.EADDRINUSE:
                    continue
                print >>sys.stderr, "Cannot run webserver :-("
                raise
            else:
                break

        if httpd is None:
            raise WebserverNotAvailable("Cannot run webserver :-( "
                                        "no free ports in range %s..%s" %
                                        (_HTTP_PORTS[0], _HTTP_PORTS[-1]))

        self._http_base_url = 'http://localhost:%s/' % port
        self._http_starting.release()
        httpd.socket.settimeout(1)

        while self._http_running:
            try:
                httpd.handle_request()
            except socket.timeout:
                pass

    def get_remote_url(self, path):
        import os

        path_parts = path.split(os.path.sep)
        if os.path.isabs(path):
            if path_parts[:len(self._local_path_parts)] != \
                   self._local_path_parts:
                raise BadWebserverPath(path, self.test_dir)
            remote_path = '/'.join(path_parts[len(self._local_path_parts):])
        else:
            remote_path = '/'.join(path_parts)

        self._http_starting.acquire()
        self._http_starting.release()
        return self._http_base_url + remote_path

    def setUp(self):
        super(TestCaseWithWebserver, self).setUp()
        import threading, os
        self._local_path_parts = self.test_dir.split(os.path.sep)
        self._http_starting = threading.Lock()
        self._http_starting.acquire()
        self._http_running = True
        self._http_base_url = None
        self._http_thread = threading.Thread(target=self._http_start)
        self._http_thread.setDaemon(True)
        self._http_thread.start()

    def tearDown(self):
        self._http_running = False
        self._http_thread.join()
        super(TestCaseWithWebserver, self).tearDown()