[app] turn these info into debug logs (this being too chatty for .info)
# copyright 2010-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr## This file is part of CubicWeb.## CubicWeb is free software: you can redistribute it and/or modify it under the# terms of the GNU Lesser General Public License as published by the Free# Software Foundation, either version 2.1 of the License, or (at your option)# any later version.## CubicWeb 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 Lesser General Public License for more# details.## You should have received a copy of the GNU Lesser General Public License along# with CubicWeb. If not, see <http://www.gnu.org/licenses/>.importos,os.pathasospimportsignalfromtempfileimportmkdtemp,NamedTemporaryFile,TemporaryFileimporttempfilefromQueueimportQueue,EmptyfromsubprocessimportPopen,check_call,CalledProcessErrorfromshutilimportrmtree,copyascopyfilefromuuidimportuuid4# imported by default to simplify further import statementsfromlogilab.common.testlibimportunittest_main,with_tempdir,InnerTest,Tagsfromlogilab.common.shellutilsimportgetloginimportcubicwebfromcubicweb.viewimportStartupViewfromcubicweb.web.controllerimportControllerfromcubicweb.devtools.httptestimportCubicWebServerTCclassVerboseCalledProcessError(CalledProcessError):def__init__(self,returncode,command,stdout,stderr):super(VerboseCalledProcessError,self).__init__(returncode,command)self.stdout=stdoutself.stderr=stderrdef__str__(self):str=[super(VerboseCalledProcessError,self).__str__()]ifself.stdout.strip():str.append('******************')str.append('* process stdout *')str.append('******************')str.append(self.stdout)ifself.stderr.strip():str.append('******************')str.append('* process stderr *')str.append('******************')str.append(self.stderr)return'\n'.join(str)classFirefoxHelper(object):profile_name_mask='PYTEST_PROFILE_%(uid)s'def__init__(self,url=None):self._process=Noneself._tmp_dir=mkdtemp(prefix='cwtest-ffxprof-')self._profile_data={'uid':uuid4()}self._profile_name=self.profile_name_mask%self._profile_datafnull=open(os.devnull,'w')stdout=TemporaryFile()stderr=TemporaryFile()self.firefox_cmd=['firefox','-no-remote']ifos.name=='posix':self.firefox_cmd=[osp.join(osp.dirname(__file__),'data','xvfb-run.sh'),'-a']+self.firefox_cmdtry:home=osp.expanduser('~')user=getlogin()assertos.access(home,os.W_OK), \'No write access to your home directory, Firefox will crash.'\' Are you sure "%s" is a valid home for user "%s"'%(home,user)check_call(self.firefox_cmd+['-CreateProfile','%s%s'%(self._profile_name,self._tmp_dir)],stdout=stdout,stderr=stderr)exceptCalledProcessError,cpe:stdout.seek(0)stderr.seek(0)raiseVerboseCalledProcessError(cpe.returncode,cpe.cmd,stdout.read(),stderr.read())defstart(self,url):self.stop()fnull=open(os.devnull,'w')self._process=Popen(self.firefox_cmd+['-P',self._profile_name,url],stdout=fnull,stderr=fnull)defstop(self):ifself._processisnotNone:assertself._process.returncodeisNone,self._process.returncodeos.kill(self._process.pid,signal.SIGTERM)self._process.wait()self._process=Nonedef__del__(self):self.stop()rmtree(self._tmp_dir)classQUnitTestCase(CubicWebServerTC):tags=CubicWebServerTC.tags|Tags(('qunit',))# testfile, (dep_a, dep_b)all_js_tests=()defsetUp(self):super(QUnitTestCase,self).setUp()self.test_queue=Queue()classMyQUnitResultController(QUnitResultController):tc=selftest_queue=self.test_queueself._qunit_controller=MyQUnitResultControllerself.vreg.register(MyQUnitResultController)deftearDown(self):super(QUnitTestCase,self).tearDown()self.vreg.unregister(self._qunit_controller)defabspath(self,path):"""use self.__module__ to build absolute path if necessary"""ifnotosp.isabs(path):dirname=osp.dirname(__import__(self.__module__).__file__)returnosp.abspath(osp.join(dirname,path))returnpathdeftest_javascripts(self):forargsinself.all_js_tests:test_file=self.abspath(args[0])iflen(args)>1:depends=[self.abspath(dep)fordepinargs[1]]else:depends=()iflen(args)>2:data=[self.abspath(data)fordatainargs[2]]else:data=()forjs_testinself._test_qunit(test_file,depends,data):yieldjs_test@with_tempdirdef_test_qunit(self,test_file,depends=(),data_files=(),timeout=30):assertosp.exists(test_file),test_filefordepindepends:assertosp.exists(dep),depfordataindata_files:assertosp.exists(data),data# generate html test filejquery_dir='file://'+self.config.locate_resource('jquery.js')[0]html_test_file=NamedTemporaryFile(suffix='.html')html_test_file.write(make_qunit_html(test_file,depends,base_url=self.config['base-url'],web_data_path=jquery_dir))html_test_file.flush()# copying data filefordataindata_files:copyfile(data,tempfile.tempdir)whilenotself.test_queue.empty():self.test_queue.get(False)browser=FirefoxHelper()browser.start(html_test_file.name)test_count=0error=Falsedefraise_exception(cls,*data):raisecls(*data)whilenoterror:try:result,test_name,msg=self.test_queue.get(timeout=timeout)test_name='%s (%s)'%(test_name,test_file)self.set_description(test_name)ifresultisNone:breaktest_count+=1ifresult:yieldInnerTest(test_name,lambda:1)else:yieldInnerTest(test_name,self.fail,msg)exceptEmpty:error=TrueyieldInnerTest(test_file,raise_exception,RuntimeError,"%s did not report execution end. %i test processed so far."%(test_file,test_count))browser.stop()iftest_count<=0andnoterror:yieldInnerTest(test_name,raise_exception,RuntimeError,'No test yielded by qunit for %s'%test_file)classQUnitResultController(Controller):__regid__='qunit_result'# Class variables to circumvent the instantiation of a new Controller for each request._log_stack=[]# store QUnit log messages_current_module_name=''# store the current QUnit module namedefpublish(self,rset=None):event=self._cw.form['event']getattr(self,'handle_%s'%event)()defhandle_module_start(self):self.__class__._current_module_name=self._cw.form.get('name','')defhandle_test_done(self):name='%s // %s'%(self._current_module_name,self._cw.form.get('name',''))failures=int(self._cw.form.get('failures',0))total=int(self._cw.form.get('total',0))self._log_stack.append('%i/%i assertions failed'%(failures,total))msg='\n'.join(self._log_stack)iffailures:self.tc.test_queue.put((False,name,msg))else:self.tc.test_queue.put((True,name,msg))self._log_stack[:]=[]defhandle_done(self):self.tc.test_queue.put((None,None,None))defhandle_log(self):result=self._cw.form['result']message=self._cw.form['message']self._log_stack.append('%s: %s'%(result,message))defcw_path(*paths):returnfile_path(osp.join(cubicweb.CW_SOFTWARE_ROOT,*paths))deffile_path(path):return'file://'+osp.abspath(path)defbuild_js_script(host):return""" var host = '%s'; QUnit.moduleStart = function (name) { jQuery.ajax({ url: host+'/qunit_result', data: {"event": "module_start", "name": name}, async: false}); } QUnit.testDone = function (name, failures, total) { jQuery.ajax({ url: host+'/qunit_result', data: {"event": "test_done", "name": name, "failures": failures, "total":total}, async: false}); } QUnit.done = function (failures, total) { jQuery.ajax({ url: host+'/qunit_result', data: {"event": "done", "failures": failures, "total":total}, async: false}); window.close(); } QUnit.log = function (result, message) { jQuery.ajax({ url: host+'/qunit_result', data: {"event": "log", "result": result, "message": message}, async: false}); } """%hostdefmake_qunit_html(test_file,depends=(),base_url=None,web_data_path=cw_path('web','data')):""""""data={'web_data':web_data_path,'web_test':cw_path('devtools','data'),}html=['''<html> <head> <!-- JS lib used as testing framework --> <link rel="stylesheet" type="text/css" media="all" href="%(web_test)s/qunit.css" /> <script src="%(web_data)s/jquery.js" type="text/javascript"></script> <script src="%(web_test)s/cwmock.js" type="text/javascript"></script> <script src="%(web_test)s/qunit.js" type="text/javascript"></script>'''%data]ifbase_urlisnotNone:html.append('<!-- result report tools -->')html.append('<script type="text/javascript">')html.append(build_js_script(base_url))html.append('</script>')html.append('<!-- Test script dependencies (tested code for example) -->')fordepindepends:html.append(' <script src="%s" type="text/javascript"></script>'%file_path(dep))html.append(' <!-- Test script itself -->')html.append(' <script src="%s" type="text/javascript"></script>'%(file_path(test_file),))html.append(''' </head> <body> <div id="main"> </div> <h1 id="qunit-header">QUnit example</h1> <h2 id="qunit-banner"></h2> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"> </body></html>''')returnu'\n'.join(html)if__name__=='__main__':unittest_main()