«
PHP自带可以代替echo调试的unit函数

时间:2008-5-31    作者:Deri    分类: 分享


   <p>  今天发现个函数 assert 和 assert_options, 他们组合可以完成一个简单的phpunit的功能, 但是实在是太简单, 所以用处不太大, 但是还是记录一下好了.</p><p>  主要问题是不能灵活的自己定义错误的提示信息,只能提示出问题的文件和行数.</p><p>  具体的使用方法可以看 <> 或者 <></p><p>  同时可以结合 <>中 "XXVII. Error Handling and Logging Functions" 章节里的东西,共同使用.</p><p>  下面是我写的一个测试文件, 包含了所有的功能的测试,不过ASSERT_QUIET_EVAL一直不太明白,没测试出来具体有什么样作用</p><code>以下是引用片段:<br /><?php<br />functionassert_failed($file,$line,$expr){<br />  print"Assertionfailedin$file[$line]:$expr<br/>";<br />}<br />//error_reporting设置为0,相当于调用assert_options(ASSERT_WARNING,0);<br />//error_reporting(0);<br />//是否启用对ASSERT_ACTIVE的支持<br />assert_options(ASSERT_ACTIVE,1);<br />//是否在发送第一次wanning的时候,停止脚本的执行<br />assert_options(ASSERT_BAIL,0);<br />//没搞定,还不明白具体怎么用,偶测试不出来<br />//assert_options(ASSERT_QUIET_EVAL,0);<br />echo"step1<br/>";<br />assert(1==1);<br />echo"step2<br/>";<br />assert(2==1);<br />echo"step3<br/>";<br />//设定assert的callback样式,可以自己定义wanning信息显示时的样式<br />assert_options(ASSERT_CALLBACK,'assert_failed');<br />//不显示assert()自己产生warnning信息,如果设置了ASSERT_CALLBACK,仍然还会显示ASSERT_CALLBACK函数对应的信息,但是函数中传入的$expr参数不起作用.<br />//assert_options(ASSERT_WARNING,1); <br />assert(1==1);<br />assert((1/0)>2);<br />echo"step4<br/>";<br />?></code></p>
<p> </p>

   <p>  下面的一段话是直接从 中copy出来的</p><code>以下是引用片段:<br />Theassert()functionisacleveronethatworksalongthesamelinesasourprintstatements,butitonlyworksifacertainconditionisnotmatched.Essentially,assert()isusedtosay"Thisstatementmustbetrueifitisn't,pleasetellme."Forexample:<br />  print"Stage1<br />";<br />  assert(1= =1);<br />  print"Stage2<br />";<br />  assert(1= =2);<br />  print"Stage3<br />";<br />Herewehavetwoassert()s,withthefirstcallassertingthatonemustbeequaltoone,andthesecondcallassertingthatonemustbeequaltotwo.Asitisimpossibletoredefineconstantslike1and2,thefirstassert()willalwaysevaluatetotrue,andthesecondwillalwaysevaluatetofalse.Hereistheoutputfromthescript:<br />  Stage1<br />  Stage2<br />  Warning:assert()[http://www.php.net/function.assert]:Assertionfailed<br />      in/home/paul/sandbox/php/assert.phponline5<br />  Stage3<br />Thefirstassert()isnotseenintheoutputatallbecauseitevaluatedtoTRue,whereasthesecondassert()evaluatedtofalse,sowegetawarningaboutanassertionfailure.However,scriptexecutioncarriesonsothatwesee"Stage3"aftertheassertionfailurewarning.Aslongasassertionsevaluatetotrue,theyhavenoeffectontherunningofthescript,whichmeansyoucaninsertthemfordebuggingpurposesandnothavetoworryabouttakingthemoutonceyouarefinisheddebugging.<br />Ifyouareworriedaboutyourassertionsslowingexecutiondown,which,althoughthespeedhitwillbeminimal,isstillavalidconcern,youcandisableexecutionofassert()byusingtheassert_options()functionorbysettingassert.activetoOffinyourphp.inifile.Ifyouwanttouseassert_options(),ittakestwoparameters:theoptiontosetandthevalueyouwishtosetitto.<br />Table22-1showsthelistofoptionsyoucanuseforthefirstparameterofassert_options():<br />Table22-1.Firstparameterofassert_options() <br />Parameter     Default  Description<br /> <br />ASSERT_ACTIVE   On    Enablesevaluationofassert()calls<br /> <br />ASSERT_WARNING  On    MakesPHPoutputawarningforeachfailedassertion<br /> <br />ASSERT_BAIL    Off    ForcesPHPtoendscriptexecutiononafailedassertion<br /> <br />ASSERT_QUIET_EVAL Off    Ignoreserrorsinassert()calls<br /> <br />ASSERT_CALLBACK  Off    Namesuserfunctiontocallonafailedassertion<br /> <br />Todisableassert()calls,usethislineofcode:<br />  assert_options(ASSERT_ACTIVE,0);<br />AndtomakePHPendscriptexecutionratherthanjustissueawarning,wecanusethislineofcode:<br />  assert_options(ASSERT_BAIL,1);<br />Notethatalloftheseoptionscanbesetinyourphp.inifilesothattheyarealwaysineffect.Theoptionstochangethereareassert.active,assert.warning,assert.bail,assert.quiet_eval,andassert_callback.<br />ASSERT_CALLBACKisausefuloption,asitallowsyoutowriteanerrorhandlerforwhenyourcodefailsanassertion.Ittakesthestringnameofafunctiontoexecutewhenassertionsfail,andthefunctionyoudefinemusttakethreeparameters:onetoholdthefilewheretheassertionoccurred,onetoholdtheline,andonetoholdtheexpression.Usingallthreetogetherinyourcallbackfunctionallowsyoutogeneratemeaningfulerrormessagesthatyoucandebug.Forexample:<br />  functionassert_failed($file,$line,$expr){<br />      print"Assertionfailedin$fileonline$line:$expr<br />";<br />  }<br />  assert_options(ASSERT_CALLBACK,'assert_failed');<br />  assert_options(ASSERT_WARNING,0);<br />  $foo=10;<br />  $bar=11;<br />  assert($foo>$bar);<br />Thatexampleshowsacallbackfunctiondefinedthattakes$file,$line,and$exprforthethreevariablespassedin,andoutputsthemwheneveranassertionfails.Tomakethatresultactuallyhappen,assert_options()iscalledtoletPHPknowthatassert_failed()isthecorrectfunctiontouseasacallbacknotethattherearenobracketsafterthestringbeingpassedintoassert_options().<br />ASSERT_WARNINGisalsodisabled,whichstopsPHPfromoutputtingawarningaswellasrunningthecallbackfunction.Finally,twovariablesareset,andareusedaspartofacalltoassert()asyoucansee,$fooisquiteclearlynotgreaterthan$bar,whichmeanstheassertionwillfailandcallourcallback.So,theoutputfromthescriptis:Assertionfailedin/home/paul/tmp/blerg.phponline9:$foo>$bar.<br />Youcanassert()anystatementyoulike,aslongasitwillreturneitherTRueorfalse.Thismakestheassert()functionincrediblypowerfulevenmoresowhenyouthinkthatyoucanjustturnoffassertionexecutiontomakethecoderunatfullspeed.<br />Herearesomemoreexamplesofassert()ablethings:<br />  assert($savings>=$salary/10);<br />  assert($myarray= =array("apone","burke","hicks"));<br />  assert(preg_match("/wildsheepchase/",$book));</code></p>