"""Fake objects to ease testing of cubicweb without a fully working environment:organization: Logilab:copyright: 2001-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr"""__docformat__="restructuredtext en"fromlogilab.common.testlibimportmock_objectasMockfromlogilab.common.adbhimportget_adv_func_helperfromindexerimportget_indexerfromcubicwebimportRequestSessionMixInfromcubicweb.web.requestimportCubicWebRequestBasefromcubicweb.devtoolsimportBASE_URL,BaseApptestConfigurationclassFakeConfig(dict,BaseApptestConfiguration):translations={}apphome=Nonedef__init__(self,appid='data',apphome=None,cubes=()):self.appid=appidself.apphome=apphomeself._cubes=cubesself['auth-mode']='cookie'self['uid']=Noneself['base-url']=BASE_URLself['rql-cache-size']=100defcubes(self,expand=False):returnself._cubesdefsources(self):return{}classFakeVReg(object):def__init__(self,schema=None,config=None):self.schema=schemaself.config=configorFakeConfig()self.properties={'ui.encoding':'UTF8','ui.language':'en',}defproperty_value(self,key):returnself.properties[key]_registries={'controllers':[Mock(id='view'),Mock(id='login'),Mock(id='logout'),Mock(id='edit')],'views':[Mock(id='primary'),Mock(id='secondary'),Mock(id='oneline'),Mock(id='list')],}defregistry_objects(self,name,oid=None):returnself._registries[name]defetype_class(self,etype):classEntity(dict):e_schema=self.schema[etype]def__init__(self,session,eid,row=0,col=0):self.req=sessionself.eid=eidself.row,self.col=row,coldefset_eid(self,eid):self.eid=self['eid']=eidreturnEntityclassFakeRequest(CubicWebRequestBase):"""test implementation of an cubicweb request object"""def__init__(self,*args,**kwargs):ifnot(argsor'vreg'inkwargs):kwargs['vreg']=FakeVReg()kwargs['https']=Falseself._url=kwargs.pop('url','view?rql=Blop&vid=blop')super(FakeRequest,self).__init__(*args,**kwargs)self._session_data={}self._headers={}defheader_accept_language(self):"""returns an ordered list of preferred languages"""return('en',)defheader_if_modified_since(self):returnNonedefbase_url(self):"""return the root url of the application"""returnBASE_URLdefrelative_path(self,includeparams=True):"""return the normalized path of the request (ie at least relative to the application's root, but some other normalization may be needed so that the returned path may be used to compare to generated urls """ifself._url.startswith(BASE_URL):url=self._url[len(BASE_URL):]else:url=self._urlifincludeparams:returnurlreturnurl.split('?',1)[0]defset_content_type(self,content_type,filename=None,encoding=None):"""set output content type for this request. An optional filename may be given """passdefset_header(self,header,value):"""set an output HTTP header"""passdefadd_header(self,header,value):"""set an output HTTP header"""passdefremove_header(self,header):"""remove an output HTTP header"""passdefget_header(self,header,default=None):"""return the value associated with the given input header, raise KeyError if the header is not set """returnself._headers.get(header,default)defset_cookie(self,cookie,key,maxage=300):"""set / update a cookie key by default, cookie will be available for the next 5 minutes """passdefremove_cookie(self,cookie,key):"""remove a cookie by expiring it"""passdefvalidate_cache(self):pass# session compatibility (in some test are using this class to test server# side views...)defactual_session(self):"""return the original parent session if any, else self"""returnselfdefunsafe_execute(self,*args,**kwargs):"""return the original parent session if any, else self"""kwargs.pop('propagate',None)returnself.execute(*args,**kwargs)classFakeUser(object):login='toto'eid=0defin_groups(self,groups):returnTrueclassFakeSession(RequestSessionMixIn):def__init__(self,repo=None,user=None):self.repo=repoself.vreg=getattr(self.repo,'vreg',FakeVReg())self.pool=FakePool()self.user=userorFakeUser()self.is_internal_session=Falseself.is_super_session=self.user.eid==-1self._query_data={}defexecute(self,*args):passdefcommit(self,*args):self._query_data.clear()defclose(self,*args):passdefsystem_sql(self,sql,args=None):passdefdecorate_rset(self,rset,propagate=False):rset.vreg=self.vregrset.req=selfreturnrsetdefset_entity_cache(self,entity):passclassFakeRepo(object):querier=Nonedef__init__(self,schema,vreg=None,config=None):self.extids={}self.eids={}self._count=0self.schema=schemaself.vreg=vregorFakeVReg()self.config=configorFakeConfig()definternal_session(self):returnFakeSession(self)defextid2eid(self,source,extid,etype,session,insert=True):try:returnself.extids[extid]exceptKeyError:ifnotinsert:returnNoneself._count+=1eid=self._countentity=source.before_entity_insertion(session,extid,etype,eid)self.extids[extid]=eidself.eids[eid]=extidsource.after_entity_insertion(session,extid,entity)returneiddefeid2extid(self,source,eid,session=None):returnself.eids[eid]classFakeSource(object):dbhelper=get_adv_func_helper('sqlite')indexer=get_indexer('sqlite','UTF8')dbhelper.fti_uid_attr=indexer.uid_attrdbhelper.fti_table=indexer.tabledbhelper.fti_restriction_sql=indexer.restriction_sqldbhelper.fti_need_distinct_query=indexer.need_distinctdef__init__(self,uri):self.uri=uriclassFakePool(object):defsource(self,uri):returnFakeSource(uri)# commented until proven to be useful## from logging import getLogger## from cubicweb import set_log_methods## for cls in (FakeConfig, FakeVReg, FakeRequest, FakeSession, FakeRepo,## FakeSource, FakePool):## set_log_methods(cls, getLogger('fake'))