test_client.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. # test_client.py -- Compatibility 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. """Compatibility tests between the Dulwich client and the cgit server."""
  21. import copy
  22. import http.server
  23. import os
  24. import select
  25. import signal
  26. import stat
  27. import subprocess
  28. import sys
  29. import tarfile
  30. import tempfile
  31. import threading
  32. from io import BytesIO
  33. from urllib.parse import unquote
  34. from dulwich import client, file, index, objects, protocol, repo
  35. from dulwich.tests import SkipTest, expectedFailure
  36. from dulwich.tests.compat.utils import (_DEFAULT_GIT, CompatTestCase,
  37. check_for_daemon, import_repo_to_dir,
  38. rmtree_ro, run_git_or_fail)
  39. if sys.platform == "win32":
  40. import ctypes
  41. class DulwichClientTestBase:
  42. """Tests for client/server compatibility."""
  43. def setUp(self):
  44. self.gitroot = os.path.dirname(
  45. import_repo_to_dir("server_new.export").rstrip(os.sep)
  46. )
  47. self.dest = os.path.join(self.gitroot, "dest")
  48. file.ensure_dir_exists(self.dest)
  49. run_git_or_fail(["init", "--quiet", "--bare"], cwd=self.dest)
  50. def tearDown(self):
  51. rmtree_ro(self.gitroot)
  52. def assertDestEqualsSrc(self):
  53. repo_dir = os.path.join(self.gitroot, "server_new.export")
  54. dest_repo_dir = os.path.join(self.gitroot, "dest")
  55. with repo.Repo(repo_dir) as src:
  56. with repo.Repo(dest_repo_dir) as dest:
  57. self.assertReposEqual(src, dest)
  58. def _client(self):
  59. raise NotImplementedError()
  60. def _build_path(self):
  61. raise NotImplementedError()
  62. def _do_send_pack(self):
  63. c = self._client()
  64. srcpath = os.path.join(self.gitroot, "server_new.export")
  65. with repo.Repo(srcpath) as src:
  66. sendrefs = dict(src.get_refs())
  67. del sendrefs[b"HEAD"]
  68. c.send_pack(
  69. self._build_path("/dest"),
  70. lambda _: sendrefs,
  71. src.generate_pack_data,
  72. )
  73. def test_send_pack(self):
  74. self._do_send_pack()
  75. self.assertDestEqualsSrc()
  76. def test_send_pack_nothing_to_send(self):
  77. self._do_send_pack()
  78. self.assertDestEqualsSrc()
  79. # nothing to send, but shouldn't raise either.
  80. self._do_send_pack()
  81. @staticmethod
  82. def _add_file(repo, tree_id, filename, contents):
  83. tree = repo[tree_id]
  84. blob = objects.Blob()
  85. blob.data = contents.encode("utf-8")
  86. repo.object_store.add_object(blob)
  87. tree.add(filename.encode("utf-8"), stat.S_IFREG | 0o644, blob.id)
  88. repo.object_store.add_object(tree)
  89. return tree.id
  90. def test_send_pack_from_shallow_clone(self):
  91. c = self._client()
  92. server_new_path = os.path.join(self.gitroot, "server_new.export")
  93. run_git_or_fail(["config", "http.uploadpack", "true"], cwd=server_new_path)
  94. run_git_or_fail(["config", "http.receivepack", "true"], cwd=server_new_path)
  95. remote_path = self._build_path("/server_new.export")
  96. with repo.Repo(self.dest) as local:
  97. result = c.fetch(remote_path, local, depth=1)
  98. for r in result.refs.items():
  99. local.refs.set_if_equals(r[0], None, r[1])
  100. tree_id = local[local.head()].tree
  101. for filename, contents in [
  102. ("bar", "bar contents"),
  103. ("zop", "zop contents"),
  104. ]:
  105. tree_id = self._add_file(local, tree_id, filename, contents)
  106. commit_id = local.do_commit(
  107. message=b"add " + filename.encode("utf-8"),
  108. committer=b"Joe Example <joe@example.com>",
  109. tree=tree_id,
  110. )
  111. sendrefs = dict(local.get_refs())
  112. del sendrefs[b"HEAD"]
  113. c.send_pack(remote_path, lambda _: sendrefs, local.generate_pack_data)
  114. with repo.Repo(server_new_path) as remote:
  115. self.assertEqual(remote.head(), commit_id)
  116. def test_send_without_report_status(self):
  117. c = self._client()
  118. c._send_capabilities.remove(b"report-status")
  119. srcpath = os.path.join(self.gitroot, "server_new.export")
  120. with repo.Repo(srcpath) as src:
  121. sendrefs = dict(src.get_refs())
  122. del sendrefs[b"HEAD"]
  123. c.send_pack(
  124. self._build_path("/dest"),
  125. lambda _: sendrefs,
  126. src.generate_pack_data,
  127. )
  128. self.assertDestEqualsSrc()
  129. def make_dummy_commit(self, dest):
  130. b = objects.Blob.from_string(b"hi")
  131. dest.object_store.add_object(b)
  132. t = index.commit_tree(dest.object_store, [(b"hi", b.id, 0o100644)])
  133. c = objects.Commit()
  134. c.author = c.committer = b"Foo Bar <foo@example.com>"
  135. c.author_time = c.commit_time = 0
  136. c.author_timezone = c.commit_timezone = 0
  137. c.message = b"hi"
  138. c.tree = t
  139. dest.object_store.add_object(c)
  140. return c.id
  141. def disable_ff_and_make_dummy_commit(self):
  142. # disable non-fast-forward pushes to the server
  143. dest = repo.Repo(os.path.join(self.gitroot, "dest"))
  144. run_git_or_fail(
  145. ["config", "receive.denyNonFastForwards", "true"], cwd=dest.path
  146. )
  147. commit_id = self.make_dummy_commit(dest)
  148. return dest, commit_id
  149. def compute_send(self, src):
  150. sendrefs = dict(src.get_refs())
  151. del sendrefs[b"HEAD"]
  152. return sendrefs, src.generate_pack_data
  153. def test_send_pack_one_error(self):
  154. dest, dummy_commit = self.disable_ff_and_make_dummy_commit()
  155. dest.refs[b"refs/heads/master"] = dummy_commit
  156. repo_dir = os.path.join(self.gitroot, "server_new.export")
  157. with repo.Repo(repo_dir) as src:
  158. sendrefs, gen_pack = self.compute_send(src)
  159. c = self._client()
  160. result = c.send_pack(
  161. self._build_path("/dest"), lambda _: sendrefs, gen_pack
  162. )
  163. self.assertEqual(
  164. {
  165. b"refs/heads/branch": None,
  166. b"refs/heads/master": "non-fast-forward",
  167. },
  168. result.ref_status,
  169. )
  170. def test_send_pack_multiple_errors(self):
  171. dest, dummy = self.disable_ff_and_make_dummy_commit()
  172. # set up for two non-ff errors
  173. branch, master = b"refs/heads/branch", b"refs/heads/master"
  174. dest.refs[branch] = dest.refs[master] = dummy
  175. repo_dir = os.path.join(self.gitroot, "server_new.export")
  176. with repo.Repo(repo_dir) as src:
  177. sendrefs, gen_pack = self.compute_send(src)
  178. c = self._client()
  179. result = c.send_pack(
  180. self._build_path("/dest"), lambda _: sendrefs, gen_pack
  181. )
  182. self.assertEqual(
  183. {branch: "non-fast-forward", master: "non-fast-forward"},
  184. result.ref_status,
  185. )
  186. def test_archive(self):
  187. c = self._client()
  188. f = BytesIO()
  189. c.archive(self._build_path("/server_new.export"), b"HEAD", f.write)
  190. f.seek(0)
  191. tf = tarfile.open(fileobj=f)
  192. self.assertEqual(["baz", "foo"], tf.getnames())
  193. def test_fetch_pack(self):
  194. c = self._client()
  195. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  196. result = c.fetch(self._build_path("/server_new.export"), dest)
  197. for r in result.refs.items():
  198. dest.refs.set_if_equals(r[0], None, r[1])
  199. self.assertDestEqualsSrc()
  200. def test_fetch_pack_depth(self):
  201. c = self._client()
  202. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  203. result = c.fetch(self._build_path("/server_new.export"), dest, depth=1)
  204. for r in result.refs.items():
  205. dest.refs.set_if_equals(r[0], None, r[1])
  206. self.assertEqual(
  207. dest.get_shallow(),
  208. {
  209. b"35e0b59e187dd72a0af294aedffc213eaa4d03ff",
  210. b"514dc6d3fbfe77361bcaef320c4d21b72bc10be9",
  211. },
  212. )
  213. def test_repeat(self):
  214. c = self._client()
  215. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  216. result = c.fetch(self._build_path("/server_new.export"), dest)
  217. for r in result.refs.items():
  218. dest.refs.set_if_equals(r[0], None, r[1])
  219. self.assertDestEqualsSrc()
  220. result = c.fetch(self._build_path("/server_new.export"), dest)
  221. for r in result.refs.items():
  222. dest.refs.set_if_equals(r[0], None, r[1])
  223. self.assertDestEqualsSrc()
  224. def test_fetch_empty_pack(self):
  225. c = self._client()
  226. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  227. result = c.fetch(self._build_path("/server_new.export"), dest)
  228. for r in result.refs.items():
  229. dest.refs.set_if_equals(r[0], None, r[1])
  230. self.assertDestEqualsSrc()
  231. def dw(refs, **kwargs):
  232. return list(refs.values())
  233. result = c.fetch(
  234. self._build_path("/server_new.export"),
  235. dest,
  236. determine_wants=dw,
  237. )
  238. for r in result.refs.items():
  239. dest.refs.set_if_equals(r[0], None, r[1])
  240. self.assertDestEqualsSrc()
  241. def test_incremental_fetch_pack(self):
  242. self.test_fetch_pack()
  243. dest, dummy = self.disable_ff_and_make_dummy_commit()
  244. dest.refs[b"refs/heads/master"] = dummy
  245. c = self._client()
  246. repo_dir = os.path.join(self.gitroot, "server_new.export")
  247. with repo.Repo(repo_dir) as dest:
  248. result = c.fetch(self._build_path("/dest"), dest)
  249. for r in result.refs.items():
  250. dest.refs.set_if_equals(r[0], None, r[1])
  251. self.assertDestEqualsSrc()
  252. def test_fetch_pack_no_side_band_64k(self):
  253. c = self._client()
  254. c._fetch_capabilities.remove(b"side-band-64k")
  255. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  256. result = c.fetch(self._build_path("/server_new.export"), dest)
  257. for r in result.refs.items():
  258. dest.refs.set_if_equals(r[0], None, r[1])
  259. self.assertDestEqualsSrc()
  260. def test_fetch_pack_zero_sha(self):
  261. # zero sha1s are already present on the client, and should
  262. # be ignored
  263. c = self._client()
  264. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  265. result = c.fetch(
  266. self._build_path("/server_new.export"),
  267. dest,
  268. lambda refs, **kwargs: [protocol.ZERO_SHA],
  269. )
  270. for r in result.refs.items():
  271. dest.refs.set_if_equals(r[0], None, r[1])
  272. def test_send_remove_branch(self):
  273. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  274. dummy_commit = self.make_dummy_commit(dest)
  275. dest.refs[b"refs/heads/master"] = dummy_commit
  276. dest.refs[b"refs/heads/abranch"] = dummy_commit
  277. sendrefs = dict(dest.refs)
  278. sendrefs[b"refs/heads/abranch"] = b"00" * 20
  279. del sendrefs[b"HEAD"]
  280. def gen_pack(have, want, ofs_delta=False, progress=None):
  281. return 0, []
  282. c = self._client()
  283. self.assertEqual(dest.refs[b"refs/heads/abranch"], dummy_commit)
  284. c.send_pack(self._build_path("/dest"), lambda _: sendrefs, gen_pack)
  285. self.assertNotIn(b"refs/heads/abranch", dest.refs)
  286. def test_send_new_branch_empty_pack(self):
  287. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  288. dummy_commit = self.make_dummy_commit(dest)
  289. dest.refs[b"refs/heads/master"] = dummy_commit
  290. dest.refs[b"refs/heads/abranch"] = dummy_commit
  291. sendrefs = {b"refs/heads/bbranch": dummy_commit}
  292. def gen_pack(have, want, ofs_delta=False, progress=None):
  293. return 0, []
  294. c = self._client()
  295. self.assertEqual(dest.refs[b"refs/heads/abranch"], dummy_commit)
  296. c.send_pack(self._build_path("/dest"), lambda _: sendrefs, gen_pack)
  297. self.assertEqual(dummy_commit, dest.refs[b"refs/heads/abranch"])
  298. def test_get_refs(self):
  299. c = self._client()
  300. refs = c.get_refs(self._build_path("/server_new.export"))
  301. repo_dir = os.path.join(self.gitroot, "server_new.export")
  302. with repo.Repo(repo_dir) as dest:
  303. self.assertDictEqual(dest.refs.as_dict(), refs)
  304. class DulwichTCPClientTest(CompatTestCase, DulwichClientTestBase):
  305. def setUp(self):
  306. CompatTestCase.setUp(self)
  307. DulwichClientTestBase.setUp(self)
  308. if check_for_daemon(limit=1):
  309. raise SkipTest(
  310. "git-daemon was already running on port %s" % protocol.TCP_GIT_PORT
  311. )
  312. fd, self.pidfile = tempfile.mkstemp(
  313. prefix="dulwich-test-git-client", suffix=".pid"
  314. )
  315. os.fdopen(fd).close()
  316. args = [
  317. _DEFAULT_GIT,
  318. "daemon",
  319. "--verbose",
  320. "--export-all",
  321. "--pid-file=%s" % self.pidfile,
  322. "--base-path=%s" % self.gitroot,
  323. "--enable=receive-pack",
  324. "--enable=upload-archive",
  325. "--listen=localhost",
  326. "--reuseaddr",
  327. self.gitroot,
  328. ]
  329. self.process = subprocess.Popen(
  330. args,
  331. cwd=self.gitroot,
  332. stdout=subprocess.PIPE,
  333. stderr=subprocess.PIPE,
  334. )
  335. if not check_for_daemon():
  336. raise SkipTest("git-daemon failed to start")
  337. def tearDown(self):
  338. with open(self.pidfile) as f:
  339. pid = int(f.read().strip())
  340. if sys.platform == "win32":
  341. PROCESS_TERMINATE = 1
  342. handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, pid)
  343. ctypes.windll.kernel32.TerminateProcess(handle, -1)
  344. ctypes.windll.kernel32.CloseHandle(handle)
  345. else:
  346. try:
  347. os.kill(pid, signal.SIGKILL)
  348. os.unlink(self.pidfile)
  349. except OSError:
  350. pass
  351. self.process.wait()
  352. self.process.stdout.close()
  353. self.process.stderr.close()
  354. DulwichClientTestBase.tearDown(self)
  355. CompatTestCase.tearDown(self)
  356. def _client(self):
  357. return client.TCPGitClient("localhost")
  358. def _build_path(self, path):
  359. return path
  360. if sys.platform == "win32":
  361. @expectedFailure
  362. def test_fetch_pack_no_side_band_64k(self):
  363. DulwichClientTestBase.test_fetch_pack_no_side_band_64k(self)
  364. def test_send_remove_branch(self):
  365. # This test fails intermittently on my machine, probably due to some sort
  366. # of race condition. Probably also related to #1015
  367. self.skipTest('skip flaky test; see #1015')
  368. class TestSSHVendor:
  369. @staticmethod
  370. def run_command(
  371. host,
  372. command,
  373. username=None,
  374. port=None,
  375. password=None,
  376. key_filename=None,
  377. ):
  378. cmd, path = command.split(" ")
  379. cmd = cmd.split("-", 1)
  380. path = path.replace("'", "")
  381. p = subprocess.Popen(
  382. cmd + [path],
  383. bufsize=0,
  384. stdin=subprocess.PIPE,
  385. stdout=subprocess.PIPE,
  386. stderr=subprocess.PIPE,
  387. )
  388. return client.SubprocessWrapper(p)
  389. class DulwichMockSSHClientTest(CompatTestCase, DulwichClientTestBase):
  390. def setUp(self):
  391. CompatTestCase.setUp(self)
  392. DulwichClientTestBase.setUp(self)
  393. self.real_vendor = client.get_ssh_vendor
  394. client.get_ssh_vendor = TestSSHVendor
  395. def tearDown(self):
  396. DulwichClientTestBase.tearDown(self)
  397. CompatTestCase.tearDown(self)
  398. client.get_ssh_vendor = self.real_vendor
  399. def _client(self):
  400. return client.SSHGitClient("localhost")
  401. def _build_path(self, path):
  402. return self.gitroot + path
  403. class DulwichSubprocessClientTest(CompatTestCase, DulwichClientTestBase):
  404. def setUp(self):
  405. CompatTestCase.setUp(self)
  406. DulwichClientTestBase.setUp(self)
  407. def tearDown(self):
  408. DulwichClientTestBase.tearDown(self)
  409. CompatTestCase.tearDown(self)
  410. def _client(self):
  411. return client.SubprocessGitClient()
  412. def _build_path(self, path):
  413. return self.gitroot + path
  414. class GitHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
  415. """HTTP Request handler that calls out to 'git http-backend'."""
  416. # Make rfile unbuffered -- we need to read one line and then pass
  417. # the rest to a subprocess, so we can't use buffered input.
  418. rbufsize = 0
  419. def do_POST(self):
  420. self.run_backend()
  421. def do_GET(self):
  422. self.run_backend()
  423. def send_head(self):
  424. return self.run_backend()
  425. def log_request(self, code="-", size="-"):
  426. # Let's be quiet, the test suite is noisy enough already
  427. pass
  428. def run_backend(self): # noqa: C901
  429. """Call out to git http-backend."""
  430. # Based on CGIHTTPServer.CGIHTTPRequestHandler.run_cgi:
  431. # Copyright (c) 2001-2010 Python Software Foundation;
  432. # All Rights Reserved
  433. # Licensed under the Python Software Foundation License.
  434. rest = self.path
  435. # find an explicit query string, if present.
  436. i = rest.rfind("?")
  437. if i >= 0:
  438. rest, query = rest[:i], rest[i + 1 :]
  439. else:
  440. query = ""
  441. env = copy.deepcopy(os.environ)
  442. env["SERVER_SOFTWARE"] = self.version_string()
  443. env["SERVER_NAME"] = self.server.server_name
  444. env["GATEWAY_INTERFACE"] = "CGI/1.1"
  445. env["SERVER_PROTOCOL"] = self.protocol_version
  446. env["SERVER_PORT"] = str(self.server.server_port)
  447. env["GIT_PROJECT_ROOT"] = self.server.root_path
  448. env["GIT_HTTP_EXPORT_ALL"] = "1"
  449. env["REQUEST_METHOD"] = self.command
  450. uqrest = unquote(rest)
  451. env["PATH_INFO"] = uqrest
  452. env["SCRIPT_NAME"] = "/"
  453. if query:
  454. env["QUERY_STRING"] = query
  455. host = self.address_string()
  456. if host != self.client_address[0]:
  457. env["REMOTE_HOST"] = host
  458. env["REMOTE_ADDR"] = self.client_address[0]
  459. authorization = self.headers.get("authorization")
  460. if authorization:
  461. authorization = authorization.split()
  462. if len(authorization) == 2:
  463. import base64
  464. import binascii
  465. env["AUTH_TYPE"] = authorization[0]
  466. if authorization[0].lower() == "basic":
  467. try:
  468. authorization = base64.decodestring(authorization[1])
  469. except binascii.Error:
  470. pass
  471. else:
  472. authorization = authorization.split(":")
  473. if len(authorization) == 2:
  474. env["REMOTE_USER"] = authorization[0]
  475. # XXX REMOTE_IDENT
  476. content_type = self.headers.get("content-type")
  477. if content_type:
  478. env["CONTENT_TYPE"] = content_type
  479. length = self.headers.get("content-length")
  480. if length:
  481. env["CONTENT_LENGTH"] = length
  482. referer = self.headers.get("referer")
  483. if referer:
  484. env["HTTP_REFERER"] = referer
  485. accept = []
  486. for line in self.headers.getallmatchingheaders("accept"):
  487. if line[:1] in "\t\n\r ":
  488. accept.append(line.strip())
  489. else:
  490. accept = accept + line[7:].split(",")
  491. env["HTTP_ACCEPT"] = ",".join(accept)
  492. ua = self.headers.get("user-agent")
  493. if ua:
  494. env["HTTP_USER_AGENT"] = ua
  495. co = self.headers.get("cookie")
  496. if co:
  497. env["HTTP_COOKIE"] = co
  498. # XXX Other HTTP_* headers
  499. # Since we're setting the env in the parent, provide empty
  500. # values to override previously set values
  501. for k in (
  502. "QUERY_STRING",
  503. "REMOTE_HOST",
  504. "CONTENT_LENGTH",
  505. "HTTP_USER_AGENT",
  506. "HTTP_COOKIE",
  507. "HTTP_REFERER",
  508. ):
  509. env.setdefault(k, "")
  510. self.wfile.write(b"HTTP/1.1 200 Script output follows\r\n")
  511. self.wfile.write(("Server: %s\r\n" % self.server.server_name).encode("ascii"))
  512. self.wfile.write(("Date: %s\r\n" % self.date_time_string()).encode("ascii"))
  513. decoded_query = query.replace("+", " ")
  514. try:
  515. nbytes = int(length)
  516. except (TypeError, ValueError):
  517. nbytes = -1
  518. if self.command.lower() == "post":
  519. if nbytes > 0:
  520. data = self.rfile.read(nbytes)
  521. elif self.headers.get('transfer-encoding') == 'chunked':
  522. chunks = []
  523. while True:
  524. line = self.rfile.readline()
  525. length = int(line.rstrip(), 16)
  526. chunk = self.rfile.read(length + 2)
  527. chunks.append(chunk[:-2])
  528. if length == 0:
  529. break
  530. data = b''.join(chunks)
  531. env["CONTENT_LENGTH"] = str(len(data))
  532. else:
  533. raise AssertionError
  534. else:
  535. data = None
  536. env["CONTENT_LENGTH"] = "0"
  537. # throw away additional data [see bug #427345]
  538. while select.select([self.rfile._sock], [], [], 0)[0]:
  539. if not self.rfile._sock.recv(1):
  540. break
  541. args = ["http-backend"]
  542. if "=" not in decoded_query:
  543. args.append(decoded_query)
  544. stdout = run_git_or_fail(args, input=data, env=env, stderr=subprocess.PIPE)
  545. self.wfile.write(stdout)
  546. class HTTPGitServer(http.server.HTTPServer):
  547. allow_reuse_address = True
  548. def __init__(self, server_address, root_path):
  549. http.server.HTTPServer.__init__(self, server_address, GitHTTPRequestHandler)
  550. self.root_path = root_path
  551. self.server_name = "localhost"
  552. def get_url(self):
  553. return "http://{}:{}/".format(self.server_name, self.server_port)
  554. class DulwichHttpClientTest(CompatTestCase, DulwichClientTestBase):
  555. min_git_version = (1, 7, 0, 2)
  556. def setUp(self):
  557. CompatTestCase.setUp(self)
  558. DulwichClientTestBase.setUp(self)
  559. self._httpd = HTTPGitServer(("localhost", 0), self.gitroot)
  560. self.addCleanup(self._httpd.shutdown)
  561. threading.Thread(target=self._httpd.serve_forever).start()
  562. run_git_or_fail(["config", "http.uploadpack", "true"], cwd=self.dest)
  563. run_git_or_fail(["config", "http.receivepack", "true"], cwd=self.dest)
  564. def tearDown(self):
  565. DulwichClientTestBase.tearDown(self)
  566. CompatTestCase.tearDown(self)
  567. self._httpd.shutdown()
  568. self._httpd.socket.close()
  569. def _client(self):
  570. return client.HttpGitClient(self._httpd.get_url())
  571. def _build_path(self, path):
  572. return path
  573. def test_archive(self):
  574. raise SkipTest("exporting archives not supported over http")