test_client.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. # test_client.py -- Compatibilty tests for git client.
  2. # Copyright (C) 2010 Google, Inc.
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Compatibilty tests between the Dulwich client and the cgit server."""
  21. import copy
  22. from io import BytesIO
  23. import os
  24. import select
  25. import signal
  26. import subprocess
  27. import sys
  28. import tarfile
  29. import tempfile
  30. import threading
  31. try:
  32. from urlparse import unquote
  33. except ImportError:
  34. from urllib.parse import unquote
  35. try:
  36. import BaseHTTPServer
  37. import SimpleHTTPServer
  38. except ImportError:
  39. import http.server
  40. BaseHTTPServer = http.server
  41. SimpleHTTPServer = http.server
  42. from dulwich import (
  43. client,
  44. errors,
  45. file,
  46. index,
  47. protocol,
  48. objects,
  49. repo,
  50. )
  51. from dulwich.tests import (
  52. SkipTest,
  53. expectedFailure,
  54. )
  55. from dulwich.tests.compat.utils import (
  56. CompatTestCase,
  57. check_for_daemon,
  58. import_repo_to_dir,
  59. rmtree_ro,
  60. run_git_or_fail,
  61. _DEFAULT_GIT,
  62. )
  63. if sys.platform == 'win32':
  64. import ctypes
  65. class DulwichClientTestBase(object):
  66. """Tests for client/server compatibility."""
  67. def setUp(self):
  68. self.gitroot = os.path.dirname(
  69. import_repo_to_dir('server_new.export').rstrip(os.sep))
  70. self.dest = os.path.join(self.gitroot, 'dest')
  71. file.ensure_dir_exists(self.dest)
  72. run_git_or_fail(['init', '--quiet', '--bare'], cwd=self.dest)
  73. def tearDown(self):
  74. rmtree_ro(self.gitroot)
  75. def assertDestEqualsSrc(self):
  76. repo_dir = os.path.join(self.gitroot, 'server_new.export')
  77. dest_repo_dir = os.path.join(self.gitroot, 'dest')
  78. with repo.Repo(repo_dir) as src:
  79. with repo.Repo(dest_repo_dir) as dest:
  80. self.assertReposEqual(src, dest)
  81. def _client(self):
  82. raise NotImplementedError()
  83. def _build_path(self):
  84. raise NotImplementedError()
  85. def _do_send_pack(self):
  86. c = self._client()
  87. srcpath = os.path.join(self.gitroot, 'server_new.export')
  88. with repo.Repo(srcpath) as src:
  89. sendrefs = dict(src.get_refs())
  90. del sendrefs[b'HEAD']
  91. c.send_pack(self._build_path('/dest'), lambda _: sendrefs,
  92. src.object_store.generate_pack_data)
  93. def test_send_pack(self):
  94. self._do_send_pack()
  95. self.assertDestEqualsSrc()
  96. def test_send_pack_nothing_to_send(self):
  97. self._do_send_pack()
  98. self.assertDestEqualsSrc()
  99. # nothing to send, but shouldn't raise either.
  100. self._do_send_pack()
  101. def test_send_without_report_status(self):
  102. c = self._client()
  103. c._send_capabilities.remove(b'report-status')
  104. srcpath = os.path.join(self.gitroot, 'server_new.export')
  105. with repo.Repo(srcpath) as src:
  106. sendrefs = dict(src.get_refs())
  107. del sendrefs[b'HEAD']
  108. c.send_pack(self._build_path('/dest'), lambda _: sendrefs,
  109. src.object_store.generate_pack_data)
  110. self.assertDestEqualsSrc()
  111. def make_dummy_commit(self, dest):
  112. b = objects.Blob.from_string(b'hi')
  113. dest.object_store.add_object(b)
  114. t = index.commit_tree(dest.object_store, [(b'hi', b.id, 0o100644)])
  115. c = objects.Commit()
  116. c.author = c.committer = b'Foo Bar <foo@example.com>'
  117. c.author_time = c.commit_time = 0
  118. c.author_timezone = c.commit_timezone = 0
  119. c.message = b'hi'
  120. c.tree = t
  121. dest.object_store.add_object(c)
  122. return c.id
  123. def disable_ff_and_make_dummy_commit(self):
  124. # disable non-fast-forward pushes to the server
  125. dest = repo.Repo(os.path.join(self.gitroot, 'dest'))
  126. run_git_or_fail(['config', 'receive.denyNonFastForwards', 'true'],
  127. cwd=dest.path)
  128. commit_id = self.make_dummy_commit(dest)
  129. return dest, commit_id
  130. def compute_send(self, src):
  131. sendrefs = dict(src.get_refs())
  132. del sendrefs[b'HEAD']
  133. return sendrefs, src.object_store.generate_pack_data
  134. def test_send_pack_one_error(self):
  135. dest, dummy_commit = self.disable_ff_and_make_dummy_commit()
  136. dest.refs[b'refs/heads/master'] = dummy_commit
  137. repo_dir = os.path.join(self.gitroot, 'server_new.export')
  138. with repo.Repo(repo_dir) as src:
  139. sendrefs, gen_pack = self.compute_send(src)
  140. c = self._client()
  141. try:
  142. c.send_pack(self._build_path('/dest'),
  143. lambda _: sendrefs, gen_pack)
  144. except errors.UpdateRefsError as e:
  145. self.assertEqual('refs/heads/master failed to update',
  146. e.args[0])
  147. self.assertEqual({b'refs/heads/branch': b'ok',
  148. b'refs/heads/master': b'non-fast-forward'},
  149. e.ref_status)
  150. def test_send_pack_multiple_errors(self):
  151. dest, dummy = self.disable_ff_and_make_dummy_commit()
  152. # set up for two non-ff errors
  153. branch, master = b'refs/heads/branch', b'refs/heads/master'
  154. dest.refs[branch] = dest.refs[master] = dummy
  155. repo_dir = os.path.join(self.gitroot, 'server_new.export')
  156. with repo.Repo(repo_dir) as src:
  157. sendrefs, gen_pack = self.compute_send(src)
  158. c = self._client()
  159. try:
  160. c.send_pack(self._build_path('/dest'), lambda _: sendrefs,
  161. gen_pack)
  162. except errors.UpdateRefsError as e:
  163. self.assertIn(
  164. str(e),
  165. ['{0}, {1} failed to update'.format(
  166. branch.decode('ascii'), master.decode('ascii')),
  167. '{1}, {0} failed to update'.format(
  168. branch.decode('ascii'), master.decode('ascii'))])
  169. self.assertEqual({branch: b'non-fast-forward',
  170. master: b'non-fast-forward'},
  171. e.ref_status)
  172. def test_archive(self):
  173. c = self._client()
  174. f = BytesIO()
  175. c.archive(self._build_path('/server_new.export'), b'HEAD', f.write)
  176. f.seek(0)
  177. tf = tarfile.open(fileobj=f)
  178. self.assertEqual(['baz', 'foo'], tf.getnames())
  179. def test_fetch_pack(self):
  180. c = self._client()
  181. with repo.Repo(os.path.join(self.gitroot, 'dest')) as dest:
  182. result = c.fetch(self._build_path('/server_new.export'), dest)
  183. for r in result.refs.items():
  184. dest.refs.set_if_equals(r[0], None, r[1])
  185. self.assertDestEqualsSrc()
  186. def test_incremental_fetch_pack(self):
  187. self.test_fetch_pack()
  188. dest, dummy = self.disable_ff_and_make_dummy_commit()
  189. dest.refs[b'refs/heads/master'] = dummy
  190. c = self._client()
  191. repo_dir = os.path.join(self.gitroot, 'server_new.export')
  192. with repo.Repo(repo_dir) as dest:
  193. result = c.fetch(self._build_path('/dest'), dest)
  194. for r in result.refs.items():
  195. dest.refs.set_if_equals(r[0], None, r[1])
  196. self.assertDestEqualsSrc()
  197. def test_fetch_pack_no_side_band_64k(self):
  198. c = self._client()
  199. c._fetch_capabilities.remove(b'side-band-64k')
  200. with repo.Repo(os.path.join(self.gitroot, 'dest')) as dest:
  201. result = c.fetch(self._build_path('/server_new.export'), dest)
  202. for r in result.refs.items():
  203. dest.refs.set_if_equals(r[0], None, r[1])
  204. self.assertDestEqualsSrc()
  205. def test_fetch_pack_zero_sha(self):
  206. # zero sha1s are already present on the client, and should
  207. # be ignored
  208. c = self._client()
  209. with repo.Repo(os.path.join(self.gitroot, 'dest')) as dest:
  210. result = c.fetch(
  211. self._build_path('/server_new.export'), dest,
  212. lambda refs: [protocol.ZERO_SHA])
  213. for r in result.refs.items():
  214. dest.refs.set_if_equals(r[0], None, r[1])
  215. def test_send_remove_branch(self):
  216. with repo.Repo(os.path.join(self.gitroot, 'dest')) as dest:
  217. dummy_commit = self.make_dummy_commit(dest)
  218. dest.refs[b'refs/heads/master'] = dummy_commit
  219. dest.refs[b'refs/heads/abranch'] = dummy_commit
  220. sendrefs = dict(dest.refs)
  221. sendrefs[b'refs/heads/abranch'] = b"00" * 20
  222. del sendrefs[b'HEAD']
  223. def gen_pack(have, want, ofs_delta=False):
  224. return 0, []
  225. c = self._client()
  226. self.assertEqual(dest.refs[b"refs/heads/abranch"], dummy_commit)
  227. c.send_pack(
  228. self._build_path('/dest'), lambda _: sendrefs, gen_pack)
  229. self.assertFalse(b"refs/heads/abranch" in dest.refs)
  230. def test_get_refs(self):
  231. c = self._client()
  232. refs = c.get_refs(self._build_path('/server_new.export'))
  233. repo_dir = os.path.join(self.gitroot, 'server_new.export')
  234. with repo.Repo(repo_dir) as dest:
  235. self.assertDictEqual(dest.refs.as_dict(), refs)
  236. class DulwichTCPClientTest(CompatTestCase, DulwichClientTestBase):
  237. def setUp(self):
  238. CompatTestCase.setUp(self)
  239. DulwichClientTestBase.setUp(self)
  240. if check_for_daemon(limit=1):
  241. raise SkipTest('git-daemon was already running on port %s' %
  242. protocol.TCP_GIT_PORT)
  243. fd, self.pidfile = tempfile.mkstemp(prefix='dulwich-test-git-client',
  244. suffix=".pid")
  245. os.fdopen(fd).close()
  246. args = [_DEFAULT_GIT, 'daemon', '--verbose', '--export-all',
  247. '--pid-file=%s' % self.pidfile,
  248. '--base-path=%s' % self.gitroot,
  249. '--enable=receive-pack', '--enable=upload-archive',
  250. '--listen=localhost', '--reuseaddr',
  251. self.gitroot]
  252. self.process = subprocess.Popen(
  253. args, cwd=self.gitroot,
  254. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  255. if not check_for_daemon():
  256. raise SkipTest('git-daemon failed to start')
  257. def tearDown(self):
  258. with open(self.pidfile) as f:
  259. pid = int(f.read().strip())
  260. if sys.platform == 'win32':
  261. PROCESS_TERMINATE = 1
  262. handle = ctypes.windll.kernel32.OpenProcess(
  263. PROCESS_TERMINATE, False, pid)
  264. ctypes.windll.kernel32.TerminateProcess(handle, -1)
  265. ctypes.windll.kernel32.CloseHandle(handle)
  266. else:
  267. try:
  268. os.kill(pid, signal.SIGKILL)
  269. os.unlink(self.pidfile)
  270. except (OSError, IOError):
  271. pass
  272. self.process.wait()
  273. self.process.stdout.close()
  274. self.process.stderr.close()
  275. DulwichClientTestBase.tearDown(self)
  276. CompatTestCase.tearDown(self)
  277. def _client(self):
  278. return client.TCPGitClient('localhost')
  279. def _build_path(self, path):
  280. return path
  281. if sys.platform == 'win32':
  282. @expectedFailure
  283. def test_fetch_pack_no_side_band_64k(self):
  284. DulwichClientTestBase.test_fetch_pack_no_side_band_64k(self)
  285. class TestSSHVendor(object):
  286. @staticmethod
  287. def run_command(host, command, username=None, port=None,
  288. password=None, key_filename=None):
  289. cmd, path = command.split(' ')
  290. cmd = cmd.split('-', 1)
  291. path = path.replace("'", "")
  292. p = subprocess.Popen(cmd + [path], bufsize=0, stdin=subprocess.PIPE,
  293. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  294. return client.SubprocessWrapper(p)
  295. class DulwichMockSSHClientTest(CompatTestCase, DulwichClientTestBase):
  296. def setUp(self):
  297. CompatTestCase.setUp(self)
  298. DulwichClientTestBase.setUp(self)
  299. self.real_vendor = client.get_ssh_vendor
  300. client.get_ssh_vendor = TestSSHVendor
  301. def tearDown(self):
  302. DulwichClientTestBase.tearDown(self)
  303. CompatTestCase.tearDown(self)
  304. client.get_ssh_vendor = self.real_vendor
  305. def _client(self):
  306. return client.SSHGitClient('localhost')
  307. def _build_path(self, path):
  308. return self.gitroot + path
  309. class DulwichSubprocessClientTest(CompatTestCase, DulwichClientTestBase):
  310. def setUp(self):
  311. CompatTestCase.setUp(self)
  312. DulwichClientTestBase.setUp(self)
  313. def tearDown(self):
  314. DulwichClientTestBase.tearDown(self)
  315. CompatTestCase.tearDown(self)
  316. def _client(self):
  317. return client.SubprocessGitClient(stderr=subprocess.PIPE)
  318. def _build_path(self, path):
  319. return self.gitroot + path
  320. class GitHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
  321. """HTTP Request handler that calls out to 'git http-backend'."""
  322. # Make rfile unbuffered -- we need to read one line and then pass
  323. # the rest to a subprocess, so we can't use buffered input.
  324. rbufsize = 0
  325. def do_POST(self):
  326. self.run_backend()
  327. def do_GET(self):
  328. self.run_backend()
  329. def send_head(self):
  330. return self.run_backend()
  331. def log_request(self, code='-', size='-'):
  332. # Let's be quiet, the test suite is noisy enough already
  333. pass
  334. def run_backend(self):
  335. """Call out to git http-backend."""
  336. # Based on CGIHTTPServer.CGIHTTPRequestHandler.run_cgi:
  337. # Copyright (c) 2001-2010 Python Software Foundation;
  338. # All Rights Reserved
  339. # Licensed under the Python Software Foundation License.
  340. rest = self.path
  341. # find an explicit query string, if present.
  342. i = rest.rfind('?')
  343. if i >= 0:
  344. rest, query = rest[:i], rest[i+1:]
  345. else:
  346. query = ''
  347. env = copy.deepcopy(os.environ)
  348. env['SERVER_SOFTWARE'] = self.version_string()
  349. env['SERVER_NAME'] = self.server.server_name
  350. env['GATEWAY_INTERFACE'] = 'CGI/1.1'
  351. env['SERVER_PROTOCOL'] = self.protocol_version
  352. env['SERVER_PORT'] = str(self.server.server_port)
  353. env['GIT_PROJECT_ROOT'] = self.server.root_path
  354. env["GIT_HTTP_EXPORT_ALL"] = "1"
  355. env['REQUEST_METHOD'] = self.command
  356. uqrest = unquote(rest)
  357. env['PATH_INFO'] = uqrest
  358. env['SCRIPT_NAME'] = "/"
  359. if query:
  360. env['QUERY_STRING'] = query
  361. host = self.address_string()
  362. if host != self.client_address[0]:
  363. env['REMOTE_HOST'] = host
  364. env['REMOTE_ADDR'] = self.client_address[0]
  365. authorization = self.headers.get("authorization")
  366. if authorization:
  367. authorization = authorization.split()
  368. if len(authorization) == 2:
  369. import base64
  370. import binascii
  371. env['AUTH_TYPE'] = authorization[0]
  372. if authorization[0].lower() == "basic":
  373. try:
  374. authorization = base64.decodestring(authorization[1])
  375. except binascii.Error:
  376. pass
  377. else:
  378. authorization = authorization.split(':')
  379. if len(authorization) == 2:
  380. env['REMOTE_USER'] = authorization[0]
  381. # XXX REMOTE_IDENT
  382. content_type = self.headers.get('content-type')
  383. if content_type:
  384. env['CONTENT_TYPE'] = content_type
  385. length = self.headers.get('content-length')
  386. if length:
  387. env['CONTENT_LENGTH'] = length
  388. referer = self.headers.get('referer')
  389. if referer:
  390. env['HTTP_REFERER'] = referer
  391. accept = []
  392. for line in self.headers.getallmatchingheaders('accept'):
  393. if line[:1] in "\t\n\r ":
  394. accept.append(line.strip())
  395. else:
  396. accept = accept + line[7:].split(',')
  397. env['HTTP_ACCEPT'] = ','.join(accept)
  398. ua = self.headers.get('user-agent')
  399. if ua:
  400. env['HTTP_USER_AGENT'] = ua
  401. co = self.headers.get('cookie')
  402. if co:
  403. env['HTTP_COOKIE'] = co
  404. # XXX Other HTTP_* headers
  405. # Since we're setting the env in the parent, provide empty
  406. # values to override previously set values
  407. for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
  408. 'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
  409. env.setdefault(k, "")
  410. self.wfile.write(b"HTTP/1.1 200 Script output follows\r\n")
  411. self.wfile.write(
  412. ("Server: %s\r\n" % self.server.server_name).encode('ascii'))
  413. self.wfile.write(
  414. ("Date: %s\r\n" % self.date_time_string()).encode('ascii'))
  415. decoded_query = query.replace('+', ' ')
  416. try:
  417. nbytes = int(length)
  418. except (TypeError, ValueError):
  419. nbytes = 0
  420. if self.command.lower() == "post" and nbytes > 0:
  421. data = self.rfile.read(nbytes)
  422. else:
  423. data = None
  424. # throw away additional data [see bug #427345]
  425. while select.select([self.rfile._sock], [], [], 0)[0]:
  426. if not self.rfile._sock.recv(1):
  427. break
  428. args = ['http-backend']
  429. if '=' not in decoded_query:
  430. args.append(decoded_query)
  431. stdout = run_git_or_fail(
  432. args, input=data, env=env, stderr=subprocess.PIPE)
  433. self.wfile.write(stdout)
  434. class HTTPGitServer(BaseHTTPServer.HTTPServer):
  435. allow_reuse_address = True
  436. def __init__(self, server_address, root_path):
  437. BaseHTTPServer.HTTPServer.__init__(
  438. self, server_address, GitHTTPRequestHandler)
  439. self.root_path = root_path
  440. self.server_name = "localhost"
  441. def get_url(self):
  442. return 'http://%s:%s/' % (self.server_name, self.server_port)
  443. class DulwichHttpClientTest(CompatTestCase, DulwichClientTestBase):
  444. min_git_version = (1, 7, 0, 2)
  445. def setUp(self):
  446. CompatTestCase.setUp(self)
  447. DulwichClientTestBase.setUp(self)
  448. self._httpd = HTTPGitServer(("localhost", 0), self.gitroot)
  449. self.addCleanup(self._httpd.shutdown)
  450. threading.Thread(target=self._httpd.serve_forever).start()
  451. run_git_or_fail(['config', 'http.uploadpack', 'true'],
  452. cwd=self.dest)
  453. run_git_or_fail(['config', 'http.receivepack', 'true'],
  454. cwd=self.dest)
  455. def tearDown(self):
  456. DulwichClientTestBase.tearDown(self)
  457. CompatTestCase.tearDown(self)
  458. self._httpd.shutdown()
  459. self._httpd.socket.close()
  460. def _client(self):
  461. return client.HttpGitClient(self._httpd.get_url())
  462. def _build_path(self, path):
  463. return path
  464. def test_archive(self):
  465. raise SkipTest("exporting archives not supported over http")