test_client.py 18 KB

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