test_client.py 17 KB

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