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

来源:互联网 发布:星星知我心 胡家玮 编辑:程序博客网 时间:2024/05/01 22:35
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
.Zrd262{display:none;}

今天发现个函数assert和assert_options,他们组合可以完成一个简单的PHPunit的功能,但是实在是太简单,所以用处不太大,但是还是记录一下好了.
 
主要问题是不能灵活的自己定义错误的提示信息,只能提示出问题的文件和行数.

具体的使用方法可以看<>或者<>

同时可以结合<>中"XXVII.ErrorHandlingandLoggingFunctions"章节里的东西,共同使用.

下面是我写的一个测试文件,包含了所有的功能的测试,不过ASSERT_QUIET_EVAL一直不太明白,没测试出来具体有什么样作用


<?PHP

functionassert_failed($file,$line,$expr){

   print"Assertionfailedin$file[$line]:$expr<br/>";

}

//error_reporting设置为0,相当于调用assert_options(ASSERT_WARNING,0);

//error_reporting(0);

//是否启用对ASSERT_ACTIVE的支持

assert_options(ASSERT_ACTIVE,1);

//是否在发送第一次wanning的时候,停止脚本的执行

assert_options(ASSERT_BAIL,0);

//没搞定,还不明白具体怎么用,偶测试不出来

//assert_options(ASSERT_QUIET_EVAL,0);

echo"step1<br/>";

assert(1==1);

echo"step2<br/>";

assert(2==1);

echo"step3<br/>";

//设定assert的callback样式,可以自己定义wanning信息显示时的样式

assert_options(ASSERT_CALLBACK,'assert_failed');

//不显示assert()自己产生warnning信息,如果设置了ASSERT_CALLBACK,仍然还会显示ASSERT_CALLBACK函数对应的信息,但是函数中传入的$expr参数不起作用.

//assert_options(ASSERT_WARNING,1);

assert(1==1);

assert((1/0)>2);

echo"step4<br/>";

?>

 

Theassert()functionisacleverone  
thatworksalongthesamelinesasourprintstatements,butitonlyworksifacertainconditionisnotmatched.Essentially,assert()isusedtosay"Thisstatementmustbetrueifitisn't,pleasetellme."Forexample:

   print"Stage1/n";

   assert(1= =1);

   print"Stage2/n";

   assert(1= =2);

   print"Stage3/n";

Herewehavetwoassert()s,withthefirstcallassertingthatonemustbeequaltoone,andthesecondcallassertingthatonemustbeequaltotwo.Asitisimpossibletoredefineconstantslike1and2,thefirstassert()willalwaysevaluatetotrue,andthesecondwillalwaysevaluatetofalse.Hereistheoutputfromthescript:

   Stage1

   Stage2

   Warning:assert()[http://www.PHP.net/function.assert]:Assertionfailed

           in/home/paul/sandbox/PHP/assert.PHPonline5

   Stage3

Thefirstassert()isnotseenintheoutputatallbecauseitevaluatedtoTRue,whereasthesecondassert()evaluatedtofalse,sowegetawarningaboutanassertionfailure.However,scriptexecutioncarriesonsothatwesee"Stage3"aftertheassertionfailurewarning.Aslongasassertionsevaluatetotrue,theyhavenoeffectontherunningofthescript,whichmeansyoucaninsertthemfordebuggingpurposesandnothavetoworryabouttakingthemoutonceyouarefinisheddebugging.

Ifyouareworriedaboutyourassertionsslowingexecutiondown,which,althoughthespeedhitwillbeminimal,isstillavalidconcern,youcandisableexecutionofassert()byusingtheassert_options()functionorbysettingassert.activetoOffinyourPHP.inifile.Ifyouwanttouseassert_options(),ittakestwoparameters:theoptiontosetandthevalueyouwishtosetitto.

Table22-1showsthelistofoptionsyoucanuseforthefirstparameterofassert_options():

Table22-1.Firstparameterofassert_options()

Parameter         Default   Description

ASSERT_ACTIVE     On        Enablesevaluationofassert()calls

ASSERT_WARNING    On        MakesPHPoutputawarningforeachfailedassertion

ASSERT_BAIL       Off       ForcesPHPtoendscriptexecutiononafailedassertion

ASSERT_QUIET_EVAL Off       Ignoreserrorsinassert()calls

ASSERT_CALLBACK   Off       Namesuserfunctiontocallonafailedassertion

Todisableassert()calls,usethislineofcode:

   assert_options(ASSERT_ACTIVE,0);

AndtomakePHPendscriptexecutionratherthanjustissueawarning,wecanusethislineofcode:

   assert_options(ASSERT_BAIL,1);

NotethatalloftheseoptionscanbesetinyourPHP.inifilesothattheyarealwaysineffect.Theoptionstochangethereareassert.active,assert.warning,assert.bail,assert.quiet_eval,andassert_callback.

ASSERT_CALLBACKisausefuloption,asitallowsyoutowriteanerrorhandlerforwhenyourcodefailsanassertion.Ittakesthestringnameofafunctiontoexecutewhenassertionsfail,andthefunctionyoudefinemusttakethreeparameters:onetoholdthefilewheretheassertionoccurred,onetoholdtheline,andonetoholdtheexpression.Usingallthreetogetherinyourcallbackfunctionallowsyoutogeneratemeaningfulerrormessagesthatyoucandebug.Forexample:

   functionassert_failed($file,$line,$expr){

           print"Assertionfailedin$fileonline$line:$expr/n";

   }

   assert_options(ASSERT_CALLBACK,'assert_failed');

   assert_options(ASSERT_WARNING,0);

   $foo=10;

   $bar=11;

   assert($foo>$bar);

Thatexampleshowsacallbackfunctiondefinedthattakes$file,$line,and$exprforthethreevariablespassedin,andoutputsthemwheneveranassertionfails.Tomakethatresultactuallyhappen,assert_options()iscalledtoletPHPknowthatassert_failed()isthecorrectfunctiontouseasacallbacknotethattherearenobracketsafterthestringbeingpassedintoassert_options().

ASSERT_WARNINGisalsodisabled,whichstopsPHPfromoutputtingawarningaswellasrunningthecallbackfunction.Finally,twovariablesareset,andareusedaspartofacalltoassert()asyoucansee,$fooisquiteclearlynotgreaterthan$bar,whichmeanstheassertionwillfailandcallourcallback.So,theoutputfromthescriptis:Assertionfailedin/home/paul/tmp/blerg.PHPonline9:$foo>$bar.

Youcanassert()anystatementyoulike,aslongasitwillreturneitherTRueorfalse.Thismakestheassert()functionincrediblypowerfulevenmoresowhenyouthinkthatyoucanjustturnoffassertionexecutiontomakethecoderunatfullspeed.

Herearesomemoreexamplesofassert()ablethings:

   assert($savings>=$salary/10);

   assert($myarray= =array("apone","burke","hicks"));

   assert(preg_match("/wildsheepchase/",$book));

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击