Source code for django.test.client

importjsonimportmimetypesimportosimportreimportsysfromcopyimportcopyfromfunctoolsimportpartialfromhttpimportHTTPStatusfromimportlibimportimport_modulefromioimportBytesIOfromurllib.parseimportunquote_to_bytes,urljoin,urlparse,urlsplitfromdjango.confimportsettingsfromdjango.core.handlers.baseimportBaseHandlerfromdjango.core.handlers.wsgiimportWSGIRequestfromdjango.core.serializers.jsonimportDjangoJSONEncoderfromdjango.core.signalsimport(got_request_exception,request_finished,request_started,)fromdjango.dbimportclose_old_connectionsfromdjango.httpimportHttpRequest,QueryDict,SimpleCookiefromdjango.templateimportTemplateDoesNotExistfromdjango.testimportsignalsfromdjango.test.utilsimportContextListfromdjango.urlsimportresolvefromdjango.utils.encodingimportforce_bytesfromdjango.utils.functionalimportSimpleLazyObjectfromdjango.utils.httpimporturlencodefromdjango.utils.itercompatimportis_iterable__all__=('Client','RedirectCycleError','RequestFactory','encode_file','encode_multipart')BOUNDARY='BoUnDaRyStRiNg'MULTIPART_CONTENT='multipart/form-data; boundary=%s'%BOUNDARYCONTENT_TYPE_RE=re.compile(r'.*; charset=([\w\d-]+);?')# Structured suffix spec: https://tools.ietf.org/html/rfc6838#section-4.2.8JSON_CONTENT_TYPE_RE=re.compile(r'^application\/(.+\+)?json')classRedirectCycleError(Exception):"""The test client has been asked to follow a redirect loop."""def__init__(self,message,last_response):super().__init__(message)self.last_response=last_responseself.redirect_chain=last_response.redirect_chainclassFakePayload:""" A wrapper around BytesIO that restricts what can be read since data from the network can't be seeked and cannot be read outside of its content length. This makes sure that views can't do anything under the test client that wouldn't work in real life. """def__init__(self,content=None):self.__content=BytesIO()self.__len=0self.read_started=FalseifcontentisnotNone:self.write(content)def__len__(self):returnself.__lendefread(self,num_bytes=None):ifnotself.read_started:self.__content.seek(0)self.read_started=Trueifnum_bytesisNone:num_bytes=self.__lenor0assertself.__len>=num_bytes,"Cannot read more than the available bytes from the HTTP incoming data."content=self.__content.read(num_bytes)self.__len-=num_bytesreturncontentdefwrite(self,content):ifself.read_started:raiseValueError("Unable to write a payload after he's been read")content=force_bytes(content)self.__content.write(content)self.__len+=len(content)defclosing_iterator_wrapper(iterable,close):try:yield fromiterablefinally:request_finished.disconnect(close_old_connections)close()# will fire request_finishedrequest_finished.connect(close_old_connections)defconditional_content_removal(request,response):""" Simulate the behavior of most Web servers by removing the content of responses for HEAD requests, 1xx, 204, and 304 responses. Ensure compliance with RFC 7230, section 3.3.3. """if100<=response.status_code<200orresponse.status_codein(204,304):ifresponse.streaming:response.streaming_content=[]else:response.content=b''ifrequest.method=='HEAD':ifresponse.streaming:response.streaming_content=[]else:response.content=b''returnresponseclassClientHandler(BaseHandler):""" A HTTP Handler that can be used for testing purposes. Use the WSGI interface to compose requests, but return the raw HttpResponse object with the originating WSGIRequest attached to its ``wsgi_request`` attribute. """def__init__(self,enforce_csrf_checks=True,*args,**kwargs):self.enforce_csrf_checks=enforce_csrf_checkssuper().__init__(*args,**kwargs)def__call__(self,environ):# Set up middleware if needed. We couldn't do this earlier, because# settings weren't available.ifself._middleware_chainisNone:self.load_middleware()request_started.disconnect(close_old_connections)request_started.send(sender=self.__class__,environ=environ)request_started.connect(close_old_connections)request=WSGIRequest(environ)# sneaky little hack so that we can easily get round# CsrfViewMiddleware. This makes life easier, and is probably# required for backwards compatibility with external tests against# admin views.request._dont_enforce_csrf_checks=notself.enforce_csrf_checks# Request goes through middleware.response=self.get_response(request)# Simulate behaviors of most Web servers.conditional_content_removal(request,response)# Attach the originating request to the response so that it could be# later retrieved.response.wsgi_request=request# Emulate a WSGI server by calling the close method on completion.ifresponse.streaming:response.streaming_content=closing_iterator_wrapper(response.streaming_content,response.close)else:request_finished.disconnect(close_old_connections)response.close()# will fire request_finishedrequest_finished.connect(close_old_connections)returnresponsedefstore_rendered_templates(store,signal,sender,template,context,**kwargs):""" Store templates and contexts that are rendered. The context is copied so that it is an accurate representation at the time of rendering. """store.setdefault('templates',[]).append(template)if'context'notinstore:store['context']=ContextList()store['context'].append(copy(context))defencode_multipart(boundary,data):""" Encode multipart POST data from a dictionary of form values. The key will be used as the form data name; the value will be transmitted as content. If the value is a file, the contents of the file will be sent as an application/octet-stream; otherwise, str(value) will be sent. """lines=[]defto_bytes(s):returnforce_bytes(s,settings.DEFAULT_CHARSET)# Not by any means perfect, but good enough for our purposes.defis_file(thing):returnhasattr(thing,"read")andcallable(thing.read)# Each bit of the multipart form data could be either a form value or a# file, or a *list* of form values and/or files. Remember that HTTP field# names can be duplicated!for(key,value)indata.items():ifvalueisNone:raiseTypeError('Cannot encode None as POST data. Did you mean to pass an ''empty string or omit the value?')elifis_file(value):lines.extend(encode_file(boundary,key,value))elifnotisinstance(value,str)andis_iterable(value):foriteminvalue:ifis_file(item):lines.extend(encode_file(boundary,key,item))else:lines.extend(to_bytes(val)forvalin['--%s'%boundary,'Content-Disposition: form-data; name="%s"'%key,'',item])else:lines.extend(to_bytes(val)forvalin['--%s'%boundary,'Content-Disposition: form-data; name="%s"'%key,'',value])lines.extend([to_bytes('--%s--'%boundary),b'',])returnb'\r\n'.join(lines)defencode_file(boundary,key,file):defto_bytes(s):returnforce_bytes(s,settings.DEFAULT_CHARSET)# file.name might not be a string. For example, it's an int for# tempfile.TemporaryFile().file_has_string_name=hasattr(file,'name')andisinstance(file.name,str)filename=os.path.basename(file.name)iffile_has_string_nameelse''ifhasattr(file,'content_type'):content_type=file.content_typeeliffilename:content_type=mimetypes.guess_type(filename)[0]else:content_type=Noneifcontent_typeisNone:content_type='application/octet-stream'filename=filenameorkeyreturn[to_bytes('--%s'%boundary),to_bytes('Content-Disposition: form-data; name="%s"; filename="%s"'%(key,filename)),to_bytes('Content-Type: %s'%content_type),b'',to_bytes(file.read())]

[docs]classRequestFactory:""" Class that lets you create mock Request objects for use in testing. Usage: rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, just as if that view had been hooked up using a URLconf. """def__init__(self,*,json_encoder=DjangoJSONEncoder,**defaults):self.json_encoder=json_encoderself.defaults=defaultsself.cookies=SimpleCookie()self.errors=BytesIO()def_base_environ(self,**request):""" The base environment for a request. """# This is a minimal valid WSGI environ dictionary, plus:# - HTTP_COOKIE: for cookie support,# - REMOTE_ADDR: often useful, see #8551.# See https://www.python.org/dev/peps/pep-3333/#environ-variablesreturn{'HTTP_COOKIE':'; '.join(sorted('%s=%s'%(morsel.key,morsel.coded_value)formorselinself.cookies.values())),'PATH_INFO':'/','REMOTE_ADDR':'127.0.0.1','REQUEST_METHOD':'GET','SCRIPT_NAME':'','SERVER_NAME':'testserver','SERVER_PORT':'80','SERVER_PROTOCOL':'HTTP/1.1','wsgi.version':(1,0),'wsgi.url_scheme':'http','wsgi.input':FakePayload(b''),'wsgi.errors':self.errors,'wsgi.multiprocess':True,'wsgi.multithread':False,'wsgi.run_once':False,**self.defaults,**request,}defrequest(self,**request):"Construct a generic request object."returnWSGIRequest(self._base_environ(**request))def_encode_data(self,data,content_type):ifcontent_typeisMULTIPART_CONTENT:returnencode_multipart(BOUNDARY,data)else:# Encode the content so that the byte representation is correct.match=CONTENT_TYPE_RE.match(content_type)ifmatch:charset=match.group(1)else:charset=settings.DEFAULT_CHARSETreturnforce_bytes(data,encoding=charset)def_encode_json(self,data,content_type):""" Return encoded JSON if data is a dict, list, or tuple and content_type is application/json. """should_encode=JSON_CONTENT_TYPE_RE.match(content_type)andisinstance(data,(dict,list,tuple))returnjson.dumps(data,cls=self.json_encoder)ifshould_encodeelsedatadef_get_path(self,parsed):path=parsed.path# If there are parameters, add themifparsed.params:path+=";"+parsed.paramspath=unquote_to_bytes(path)# Replace the behavior where non-ASCII values in the WSGI environ are# arbitrarily decoded with ISO-8859-1.# Refs comment in `get_bytes_from_wsgi()`.returnpath.decode('iso-8859-1')defget(self,path,data=None,secure=False,**extra):"""Construct a GET request."""data={}ifdataisNoneelsedatareturnself.generic('GET',path,secure=secure,**{'QUERY_STRING':urlencode(data,doseq=True),**extra,})defpost(self,path,data=None,content_type=MULTIPART_CONTENT,secure=False,**extra):"""Construct a POST request."""data=self._encode_json({}ifdataisNoneelsedata,content_type)post_data=self._encode_data(data,content_type)returnself.generic('POST',path,post_data,content_type,secure=secure,**extra)defhead(self,path,data=None,secure=False,**extra):"""Construct a HEAD request."""data={}ifdataisNoneelsedatareturnself.generic('HEAD',path,secure=secure,**{'QUERY_STRING':urlencode(data,doseq=True),**extra,})deftrace(self,path,secure=False,**extra):"""Construct a TRACE request."""returnself.generic('TRACE',path,secure=secure,**extra)defoptions(self,path,data='',content_type='application/octet-stream',secure=False,**extra):"Construct an OPTIONS request."returnself.generic('OPTIONS',path,data,content_type,secure=secure,**extra)defput(self,path,data='',content_type='application/octet-stream',secure=False,**extra):"""Construct a PUT request."""data=self._encode_json(data,content_type)returnself.generic('PUT',path,data,content_type,secure=secure,**extra)defpatch(self,path,data='',content_type='application/octet-stream',secure=False,**extra):"""Construct a PATCH request."""data=self._encode_json(data,content_type)returnself.generic('PATCH',path,data,content_type,secure=secure,**extra)defdelete(self,path,data='',content_type='application/octet-stream',secure=False,**extra):"""Construct a DELETE request."""data=self._encode_json(data,content_type)returnself.generic('DELETE',path,data,content_type,secure=secure,**extra)defgeneric(self,method,path,data='',content_type='application/octet-stream',secure=False,**extra):"""Construct an arbitrary HTTP request."""parsed=urlparse(str(path))# path can be lazydata=force_bytes(data,settings.DEFAULT_CHARSET)r={'PATH_INFO':self._get_path(parsed),'REQUEST_METHOD':method,'SERVER_PORT':'443'ifsecureelse'80','wsgi.url_scheme':'https'ifsecureelse'http',}ifdata:r.update({'CONTENT_LENGTH':str(len(data)),'CONTENT_TYPE':content_type,'wsgi.input':FakePayload(data),})r.update(extra)# If QUERY_STRING is absent or empty, we want to extract it from the URL.ifnotr.get('QUERY_STRING'):# WSGI requires latin-1 encoded strings. See get_path_info().query_string=parsed[4].encode().decode('iso-8859-1')r['QUERY_STRING']=query_stringreturnself.request(**r)

[docs]classClient(RequestFactory):""" A class that can act as a client for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. Client objects are stateful - they will retain cookie (and thus session) details for the lifetime of the Client instance. This is not intended as a replacement for Twill/Selenium or the like - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """def__init__(self,enforce_csrf_checks=False,**defaults):super().__init__(**defaults)self.handler=ClientHandler(enforce_csrf_checks)self.exc_info=Nonedefstore_exc_info(self,**kwargs):"""Store exceptions when they are generated by a view."""self.exc_info=sys.exc_info()@propertydefsession(self):"""Return the current session variables."""engine=import_module(settings.SESSION_ENGINE)cookie=self.cookies.get(settings.SESSION_COOKIE_NAME)ifcookie:returnengine.SessionStore(cookie.value)session=engine.SessionStore()session.save()self.cookies[settings.SESSION_COOKIE_NAME]=session.session_keyreturnsessiondefrequest(self,**request):""" The master request method. Compose the environment dictionary and pass to the handler, return the result of the handler. Assume defaults for the query environment, which can be overridden using the arguments to the request. """environ=self._base_environ(**request)# Curry a data dictionary into an instance of the template renderer# callback function.data={}on_template_render=partial(store_rendered_templates,data)signal_uid="template-render-%s"%id(request)signals.template_rendered.connect(on_template_render,dispatch_uid=signal_uid)# Capture exceptions created by the handler.exception_uid="request-exception-%s"%id(request)got_request_exception.connect(self.store_exc_info,dispatch_uid=exception_uid)try:try:response=self.handler(environ)exceptTemplateDoesNotExistase:# If the view raises an exception, Django will attempt to show# the 500.html template. If that template is not available,# we should ignore the error in favor of re-raising the# underlying exception that caused the 500 error. Any other# template found to be missing during view error handling# should be reported as-is.ife.args!=('500.html',):raise# Look for a signalled exception, clear the current context# exception data, then re-raise the signalled exception.# Also make sure that the signalled exception is cleared from# the local cache!ifself.exc_info:_,exc_value,_=self.exc_infoself.exc_info=Noneraiseexc_value# Save the client and request that stimulated the response.response.client=selfresponse.request=request# Add any rendered template detail to the response.response.templates=data.get("templates",[])response.context=data.get("context")response.json=partial(self._parse_json,response)# Attach the ResolverMatch instance to the responseresponse.resolver_match=SimpleLazyObject(lambda:resolve(request['PATH_INFO']))# Flatten a single context. Not really necessary anymore thanks to# the __getattr__ flattening in ContextList, but has some edge-case# backwards-compatibility implications.ifresponse.contextandlen(response.context)==1:response.context=response.context[0]# Update persistent cookie data.ifresponse.cookies:self.cookies.update(response.cookies)returnresponsefinally:signals.template_rendered.disconnect(dispatch_uid=signal_uid)got_request_exception.disconnect(dispatch_uid=exception_uid)

[docs]defget(self,path,data=None,follow=False,secure=False,**extra):"""Request a response from the server using GET."""response=super().get(path,data=data,secure=secure,**extra)iffollow:response=self._handle_redirects(response,data=data,**extra)returnresponse

[docs]defpost(self,path,data=None,content_type=MULTIPART_CONTENT,follow=False,secure=False,**extra):"""Request a response from the server using POST."""response=super().post(path,data=data,content_type=content_type,secure=secure,**extra)iffollow:response=self._handle_redirects(response,data=data,content_type=content_type,**extra)returnresponse

[docs]defhead(self,path,data=None,follow=False,secure=False,**extra):"""Request a response from the server using HEAD."""response=super().head(path,data=data,secure=secure,**extra)iffollow:response=self._handle_redirects(response,data=data,**extra)returnresponse

[docs]defoptions(self,path,data='',content_type='application/octet-stream',follow=False,secure=False,**extra):"""Request a response from the server using OPTIONS."""response=super().options(path,data=data,content_type=content_type,secure=secure,**extra)iffollow:response=self._handle_redirects(response,data=data,content_type=content_type,**extra)returnresponse

[docs]defput(self,path,data='',content_type='application/octet-stream',follow=False,secure=False,**extra):"""Send a resource to the server using PUT."""response=super().put(path,data=data,content_type=content_type,secure=secure,**extra)iffollow:response=self._handle_redirects(response,data=data,content_type=content_type,**extra)returnresponse

[docs]defpatch(self,path,data='',content_type='application/octet-stream',follow=False,secure=False,**extra):"""Send a resource to the server using PATCH."""response=super().patch(path,data=data,content_type=content_type,secure=secure,**extra)iffollow:response=self._handle_redirects(response,data=data,content_type=content_type,**extra)returnresponse

[docs]defdelete(self,path,data='',content_type='application/octet-stream',follow=False,secure=False,**extra):"""Send a DELETE request to the server."""response=super().delete(path,data=data,content_type=content_type,secure=secure,**extra)iffollow:response=self._handle_redirects(response,data=data,content_type=content_type,**extra)returnresponse

[docs]deftrace(self,path,data='',follow=False,secure=False,**extra):"""Send a TRACE request to the server."""response=super().trace(path,data=data,secure=secure,**extra)iffollow:response=self._handle_redirects(response,data=data,**extra)returnresponse

[docs]deflogin(self,**credentials):""" Set the Factory to appear as if it has successfully logged into a site. Return True if login is possible; False if the provided credentials are incorrect. """fromdjango.contrib.authimportauthenticateuser=authenticate(**credentials)ifuser:self._login(user)returnTrueelse:returnFalse

def_login(self,user,backend=None):fromdjango.contrib.authimportloginengine=import_module(settings.SESSION_ENGINE)# Create a fake request to store login details.request=HttpRequest()ifself.session:request.session=self.sessionelse:request.session=engine.SessionStore()login(request,user,backend)# Save the session values.request.session.save()# Set the cookie to represent the session.session_cookie=settings.SESSION_COOKIE_NAMEself.cookies[session_cookie]=request.session.session_keycookie_data={'max-age':None,'path':'/','domain':settings.SESSION_COOKIE_DOMAIN,'secure':settings.SESSION_COOKIE_SECUREorNone,'expires':None,}self.cookies[session_cookie].update(cookie_data)

[docs]deflogout(self):"""Log out the user by removing the cookies and session object."""fromdjango.contrib.authimportget_user,logoutrequest=HttpRequest()engine=import_module(settings.SESSION_ENGINE)ifself.session:request.session=self.sessionrequest.user=get_user(request)else:request.session=engine.SessionStore()logout(request)self.cookies=SimpleCookie()

def_parse_json(self,response,**extra):ifnothasattr(response,'_json'):ifnotJSON_CONTENT_TYPE_RE.match(response.get('Content-Type')):raiseValueError('Content-Type header is "{0}", not "application/json"'.format(response.get('Content-Type')))response._json=json.loads(response.content.decode(),**extra)returnresponse._jsondef_handle_redirects(self,response,data='',content_type='',**extra):""" Follow any redirects by requesting responses from the server using GET. """response.redirect_chain=[]redirect_status_codes=(HTTPStatus.MOVED_PERMANENTLY,HTTPStatus.FOUND,HTTPStatus.SEE_OTHER,HTTPStatus.TEMPORARY_REDIRECT,HTTPStatus.PERMANENT_REDIRECT,)whileresponse.status_codeinredirect_status_codes:response_url=response.urlredirect_chain=response.redirect_chainredirect_chain.append((response_url,response.status_code))url=urlsplit(response_url)ifurl.scheme:extra['wsgi.url_scheme']=url.schemeifurl.hostname:extra['SERVER_NAME']=url.hostnameifurl.port:extra['SERVER_PORT']=str(url.port)# Prepend the request path to handle relative path redirectspath=url.pathifnotpath.startswith('/'):path=urljoin(response.request['PATH_INFO'],path)ifresponse.status_codein(HTTPStatus.TEMPORARY_REDIRECT,HTTPStatus.PERMANENT_REDIRECT):# Preserve request method post-redirect for 307/308 responses.request_method=getattr(self,response.request['REQUEST_METHOD'].lower())else:request_method=self.getdata=QueryDict(url.query)content_type=Noneresponse=request_method(path,data=data,content_type=content_type,follow=False,**extra)response.redirect_chain=redirect_chainifredirect_chain[-1]inredirect_chain[:-1]:# Check that we're not redirecting to somewhere we've already# been to, to prevent loops.raiseRedirectCycleError("Redirect loop detected.",last_response=response)iflen(redirect_chain)>20:# Such a lengthy chain likely also means a loop, but one with# a growing path, changing view, or changing query argument;# 20 is the value of "network.http.redirection-limit" from Firefox.raiseRedirectCycleError("Too many redirects.",last_response=response)returnresponse