test_client.py 23 KB

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