test_client.py 19 KB

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