Mercurial and Git clients can push and pull from this alias URL to interact with this repository. You can change to which repository an alias points by going to the Aliases link on the project page.
# test_client.py -- Compatibilty tests for git client.# Copyright (C) 2010 Google, Inc.## This program is free software; you can redistribute it and/or# modify it under the terms of the GNU General Public License# as published by the Free Software Foundation; version 2# of the License or (at your option) any later version of# the License.## This program is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with this program; if not, write to the Free Software# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,# MA 02110-1301, USA."""Compatibilty tests between the Dulwich client and the cgit server."""fromcStringIOimportStringIOimportBaseHTTPServerimportSimpleHTTPServerimportcopyimportosimportselectimportshutilimportsignalimportsubprocessimporttarfileimport tempfile
import threading
import urllib
+from socket import gethostnamefrom dulwich import (
client,
errors,file,index,protocol,objects,repo,)fromdulwich.testsimport(get_safe_env,SkipTest,)fromdulwich.tests.compat.utilsimport(CompatTestCase,check_for_daemon,import_repo_to_dir,run_git_or_fail,)fromdulwich.tests.compat.server_utilsimport(ShutdownServerMixIn,)classDulwichClientTestBase(object):"""Tests for client/server compatibility."""defsetUp(self):self.gitroot=os.path.dirname(import_repo_to_dir('server_new.export'))self.dest=os.path.join(self.gitroot,'dest')file.ensure_dir_exists(self.dest)run_git_or_fail(['init','--quiet','--bare'],cwd=self.dest)deftearDown(self):shutil.rmtree(self.gitroot)defassertDestEqualsSrc(self):src=repo.Repo(os.path.join(self.gitroot,'server_new.export'))dest=repo.Repo(os.path.join(self.gitroot,'dest'))self.assertReposEqual(src,dest)def_client(self):raiseNotImplementedError()def_build_path(self):raiseNotImplementedError()def_do_send_pack(self):c=self._client()srcpath=os.path.join(self.gitroot,'server_new.export')src=repo.Repo(srcpath)sendrefs=dict(src.get_refs())delsendrefs['HEAD']c.send_pack(self._build_path('/dest'),lambda_:sendrefs,src.object_store.generate_pack_contents)deftest_send_pack(self):self._do_send_pack()self.assertDestEqualsSrc()deftest_send_pack_nothing_to_send(self):self._do_send_pack()self.assertDestEqualsSrc()# nothing to send, but shouldn't raise either.self._do_send_pack()deftest_send_without_report_status(self):c=self._client()c._send_capabilities.remove('report-status')srcpath=os.path.join(self.gitroot,'server_new.export')src=repo.Repo(srcpath)sendrefs=dict(src.get_refs())delsendrefs['HEAD']c.send_pack(self._build_path('/dest'),lambda_:sendrefs,src.object_store.generate_pack_contents)self.assertDestEqualsSrc()defmake_dummy_commit(self,dest):b=objects.Blob.from_string('hi')dest.object_store.add_object(b)t=index.commit_tree(dest.object_store,[('hi',b.id,0100644)])c=objects.Commit()c.author=c.committer='Foo Bar <foo@example.com>'c.author_time=c.commit_time=0c.author_timezone=c.commit_timezone=0c.message='hi'c.tree=tdest.object_store.add_object(c)returnc.iddefdisable_ff_and_make_dummy_commit(self):# disable non-fast-forward pushes to the serverdest=repo.Repo(os.path.join(self.gitroot,'dest'))run_git_or_fail(['config','receive.denyNonFastForwards','true'],cwd=dest.path)commit_id=self.make_dummy_commit(dest)returndest,commit_iddefcompute_send(self):srcpath=os.path.join(self.gitroot,'server_new.export')src=repo.Repo(srcpath)sendrefs=dict(src.get_refs())delsendrefs['HEAD']returnsendrefs,src.object_store.generate_pack_contentsdeftest_send_pack_one_error(self):dest,dummy_commit=self.disable_ff_and_make_dummy_commit()dest.refs['refs/heads/master']=dummy_commitsendrefs,gen_pack=self.compute_send()c=self._client()try:c.send_pack(self._build_path('/dest'),lambda_:sendrefs,gen_pack)excepterrors.UpdateRefsError,e:self.assertEqual('refs/heads/master failed to update',str(e))self.assertEqual({'refs/heads/branch':'ok','refs/heads/master':'non-fast-forward'},e.ref_status)deftest_send_pack_multiple_errors(self):dest,dummy=self.disable_ff_and_make_dummy_commit()# set up for two non-ff errorsdest.refs['refs/heads/branch']=dest.refs['refs/heads/master']=dummysendrefs,gen_pack=self.compute_send()c=self._client()try:c.send_pack(self._build_path('/dest'),lambda_:sendrefs,gen_pack)excepterrors.UpdateRefsError,e:self.assertEqual('refs/heads/branch, refs/heads/master failed to ''update',str(e))self.assertEqual({'refs/heads/branch':'non-fast-forward','refs/heads/master':'non-fast-forward'},e.ref_status)deftest_archive(self):c=self._client()f=StringIO()c.archive(self._build_path('/server_new.export'),'HEAD',f.write)f.seek(0)tf=tarfile.open(fileobj=f)self.assertEqual(['baz','foo'],tf.getnames())deftest_fetch_pack(self):c=self._client()dest=repo.Repo(os.path.join(self.gitroot,'dest'))refs=c.fetch(self._build_path('/server_new.export'),dest)map(lambdar:dest.refs.set_if_equals(r[0],None,r[1]),refs.items())self.assertDestEqualsSrc()deftest_incremental_fetch_pack(self):self.test_fetch_pack()dest,dummy=self.disable_ff_and_make_dummy_commit()dest.refs['refs/heads/master']=dummyc=self._client()dest=repo.Repo(os.path.join(self.gitroot,'server_new.export'))refs=c.fetch(self._build_path('/dest'),dest)map(lambdar:dest.refs.set_if_equals(r[0],None,r[1]),refs.items())self.assertDestEqualsSrc()deftest_fetch_pack_zero_sha(self):# zero sha1s are already present on the client, and should# be ignoredc=self._client()dest=repo.Repo(os.path.join(self.gitroot,'dest'))refs=c.fetch(self._build_path('/server_new.export'),dest,lambdarefs:[protocol.ZERO_SHA])map(lambdar:dest.refs.set_if_equals(r[0],None,r[1]),refs.items())deftest_send_remove_branch(self):dest=repo.Repo(os.path.join(self.gitroot,'dest'))dummy_commit=self.make_dummy_commit(dest)dest.refs['refs/heads/master']=dummy_commitdest.refs['refs/heads/abranch']=dummy_commitsendrefs=dict(dest.refs)sendrefs['refs/heads/abranch']="00"*20delsendrefs['HEAD']gen_pack=lambdahave,want:[]c=self._client()self.assertEqual(dest.refs["refs/heads/abranch"],dummy_commit)c.send_pack(self._build_path('/dest'),lambda_:sendrefs,gen_pack)self.assertFalse("refs/heads/abranch"indest.refs)classDulwichTCPClientTest(CompatTestCase,DulwichClientTestBase):defsetUp(self):CompatTestCase.setUp(self)DulwichClientTestBase.setUp(self)ifcheck_for_daemon(limit=1):raiseSkipTest('git-daemon was already running on port %s'%protocol.TCP_GIT_PORT)fd,self.pidfile=tempfile.mkstemp(prefix='dulwich-test-git-client',suffix=".pid")os.fdopen(fd).close()run_git_or_fail(['daemon','--verbose','--export-all','--pid-file=%s'%self.pidfile,'--base-path=%s'%self.gitroot,'--detach','--reuseaddr','--enable=receive-pack','--enable=upload-archive','--listen=localhost',self.gitroot],cwd=self.gitroot)ifnotcheck_for_daemon():raiseSkipTest('git-daemon failed to start')deftearDown(self):try:os.kill(int(open(self.pidfile).read().strip()),signal.SIGKILL)os.unlink(self.pidfile)except(OSError,IOError):passDulwichClientTestBase.tearDown(self)CompatTestCase.tearDown(self)def_client(self):returnclient.TCPGitClient('localhost')def_build_path(self,path):returnpathclassTestSSHVendor(object):@staticmethoddefconnect_ssh(host,command,username=None,port=None):cmd,path=command[0].replace("'",'').split(' ')cmd=cmd.split('-',1)p=subprocess.Popen(cmd+[path],env=get_safe_env(),stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)returnclient.SubprocessWrapper(p)classDulwichMockSSHClientTest(CompatTestCase,DulwichClientTestBase):defsetUp(self):CompatTestCase.setUp(self)DulwichClientTestBase.setUp(self)self.real_vendor=client.get_ssh_vendorclient.get_ssh_vendor=TestSSHVendordeftearDown(self):DulwichClientTestBase.tearDown(self)CompatTestCase.tearDown(self)client.get_ssh_vendor=self.real_vendordef_client(self):returnclient.SSHGitClient('localhost')def_build_path(self,path):returnself.gitroot+pathclassDulwichSubprocessClientTest(CompatTestCase,DulwichClientTestBase):defsetUp(self):CompatTestCase.setUp(self)DulwichClientTestBase.setUp(self)deftearDown(self):DulwichClientTestBase.tearDown(self)CompatTestCase.tearDown(self)def_client(self):returnclient.SubprocessGitClient(stderr=subprocess.PIPE)def_build_path(self,path):returnself.gitroot+pathclassGitHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):"""HTTP Request handler that calls out to 'git http-backend'."""# Make rfile unbuffered -- we need to read one line and then pass# the rest to a subprocess, so we can't use buffered input.rbufsize=0defdo_POST(self):self.run_backend()defdo_GET(self):self.run_backend()defsend_head(self):returnself.run_backend()deflog_request(self,code='-',size='-'):# Let's be quiet, the test suite is noisy enough alreadypassdefrun_backend(self):"""Call out to git http-backend."""# Based on CGIHTTPServer.CGIHTTPRequestHandler.run_cgi:# Copyright (c) 2001-2010 Python Software Foundation; All Rights Reserved# Licensed under the Python Software Foundation License.rest=self.path# find an explicit query string, if present.i=rest.rfind('?')ifi>=0:rest,query=rest[:i],rest[i+1:]else:query=''env=copy.deepcopy(os.environ)env['SERVER_SOFTWARE']=self.version_string()env['SERVER_NAME']=self.server.server_nameenv['GATEWAY_INTERFACE']='CGI/1.1'env['SERVER_PROTOCOL']=self.protocol_versionenv['SERVER_PORT']=str(self.server.server_port)env['GIT_PROJECT_ROOT']=self.server.root_pathenv["GIT_HTTP_EXPORT_ALL"]="1"env['REQUEST_METHOD']=self.commanduqrest=urllib.unquote(rest)env['PATH_INFO']=uqrestenv['SCRIPT_NAME']="/"ifquery:env['QUERY_STRING']=queryhost=self.address_string()ifhost!=self.client_address[0]:env['REMOTE_HOST']=hostenv['REMOTE_ADDR']=self.client_address[0]authorization=self.headers.getheader("authorization")ifauthorization:authorization=authorization.split()iflen(authorization)==2:importbase64,binasciienv['AUTH_TYPE']=authorization[0]ifauthorization[0].lower()=="basic":try:authorization=base64.decodestring(authorization[1])exceptbinascii.Error:passelse:authorization=authorization.split(':')iflen(authorization)==2:env['REMOTE_USER']=authorization[0]# XXX REMOTE_IDENTifself.headers.typeheaderisNone:env['CONTENT_TYPE']=self.headers.typeelse:env['CONTENT_TYPE']=self.headers.typeheaderlength=self.headers.getheader('content-length')iflength:env['CONTENT_LENGTH']=lengthreferer=self.headers.getheader('referer')ifreferer:env['HTTP_REFERER']=refereraccept=[]forlineinself.headers.getallmatchingheaders('accept'):ifline[:1]in"\t\n\r ":accept.append(line.strip())else:accept=accept+line[7:].split(',')env['HTTP_ACCEPT']=','.join(accept)ua=self.headers.getheader('user-agent')ifua:env['HTTP_USER_AGENT']=uaco=filter(None,self.headers.getheaders('cookie'))ifco:env['HTTP_COOKIE']=', '.join(co)# XXX Other HTTP_* headers# Since we're setting the env in the parent, provide empty# values to override previously set valuesforkin('QUERY_STRING','REMOTE_HOST','CONTENT_LENGTH','HTTP_USER_AGENT','HTTP_COOKIE','HTTP_REFERER'):env.setdefault(k,"")self.send_response(200,"Script output follows")decoded_query=query.replace('+',' ')try:nbytes=int(length)except(TypeError,ValueError):nbytes=0ifself.command.lower()=="post"andnbytes>0:data=self.rfile.read(nbytes)else:data=None# throw away additional data [see bug #427345]whileselect.select([self.rfile._sock],[],[],0)[0]:ifnotself.rfile._sock.recv(1):breakargs=['http-backend']if'='notindecoded_query:args.append(decoded_query)stdout=run_git_or_fail(args,input=data,env=env,stderr=subprocess.PIPE)self.wfile.write(stdout)classHTTPGitServer(BaseHTTPServer.HTTPServer):allow_reuse_address=True def __init__(self, server_address, root_path):
BaseHTTPServer.HTTPServer.__init__(self, server_address, GitHTTPRequestHandler)
self.root_path = root_path
+ self.server_name = "localhost" def get_url(self):
return 'http://%s:%s/' % (self.server_name, self.server_port)
ifnotgetattr(HTTPGitServer,'shutdown',None):_HTTPGitServer=HTTPGitServerclassTCPGitServer(ShutdownServerMixIn,HTTPGitServer):"""Subclass of HTTPGitServer that can be shut down."""def__init__(self,*args,**kwargs):# BaseServer is old-style so we have to call both __init__sShutdownServerMixIn.__init__(self)_HTTPGitServer.__init__(self,*args,**kwargs)classDulwichHttpClientTest(CompatTestCase,DulwichClientTestBase):min_git_version=(1,7,0,2)defsetUp(self):CompatTestCase.setUp(self)DulwichClientTestBase.setUp(self)self._httpd=HTTPGitServer(("localhost",0),self.gitroot)self.addCleanup(self._httpd.shutdown)threading.Thread(target=self._httpd.serve_forever).start()run_git_or_fail(['config','http.uploadpack','true'],cwd=self.dest)run_git_or_fail(['config','http.receivepack','true'],cwd=self.dest)deftearDown(self):DulwichClientTestBase.tearDown(self)CompatTestCase.tearDown(self)def_client(self):returnclient.HttpGitClient(self._httpd.get_url())def_build_path(self,path):returnpathdeftest_archive(self):raiseSkipTest("exporting archives not supported over http")
Attach a Trello Card
Add a tag
Your session has expired
You are no longer logged in. Please log in and try your request again.
Filter RSS Feed
This RSS feed URL allows you to see the contents of your current filter using any feed reader.
This link includes a special authentication token. If you share the URL with anyone else, they can see this RSS feed's activity. You can disable these tokens when needed.
Your current filter is unsaved; changing it won't affect this RSS feed.