assert

(PHP 4, PHP 5)

assert -- Checks if assertion is FALSE

Description

bool assert ( mixed assertion )

assert() will check the given assertion and take appropriate action if its result is FALSE.

If the assertion is given as a string it will be evaluated as PHP code by assert(). The advantages of a string assertion are less overhead when assertion checking is off and messages containing the assertion expression when an assertion fails. This means that if you pass a boolean condition as assertion this condition will not show up as parameter to the assertion function which you may have defined with the assert_options() function, the condition is converted to a string before calling that handler function, and the boolean FALSE is converted as the empty string.

Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.

Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.

The behavior of assert() may be configured by assert_options() or by .ini-settings described in that functions manual page.

The assert_options() function and/or ASSERT_CALLBACK configuration directive allow a callback function to be set to handle failed assertions.

assert() callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier!

The callback function should accept three arguments. The first argument will contain the file the assertion failed in. The second argument will contain the line the assertion failed on and the third argument will contain the expression that failed (if any - literal values such as 1 or "two" will not be passed via this argument)

例子 1. Handle a failed assertion with a custom handler

<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Create a handler function
function my_assert_handler($file, $line, $code)
{
    echo
"<hr>Assertion Failed:
        File '$file'<br />
        Line '$line'<br />
        Code '$code'<br /><hr />"
;
}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert('mysql_query("")');
?>


add a note add a note User Contributed Notes
gk at proliberty dot com
27-Aug-2005 10:35
If you expect your code to be able to work well with other code, then you should not make any assumptions about the current state of assert_options() flags, prior to calling assert(): other code may disable ASSERT_ACTIVE, without you knowing it - this would render assert() useless!

To avoid this, ALWAYS set assert_options() IMMEDIATELY before calling assert(), per the C++ paradigm for assertion usage:

In one C++ source file, you can define and undefine NDEBUG multiple times, each time followed by #include <cassert>, to enable or disable the assert macro multiple times in the same source file.

Here is how I workaround this issue in my PHP code:

//////////////////////////////////////////////////////////////////////
/// phpxAssertHandler_f
//////////////////////////////////////////////////////////////////////
/**
 * @desc    Handler which also sets up assert options if not being called as handler
                 Always fatal when assertion fails
                 Always make sure assertion is enabled
                 Cannot depend on other code not using assert or using its own assert handler!
           USAGE:
           // customize error level of assertion (php assert_options() only allows E_WARNING or nothing at all):
               phpxAssertHandler_f(E_USER_NOTICE);
           // control assertion active state: not dependent on anything another piece of code might do with ASSERT_ACTIVE
               $GLOBALS['MY_ASSERT_ACTIVE']=false;
               phpxAssertHandler_f(E_USER_NOTICE,$GLOBALS['MY_ASSERT_ACTIVE']);
           // use alternate assertion callback function:
           // NOTE: pass null as custom options parameter to use default options
           // NOTE: pass no values for assert options parameter array elements to use default options
               $GLOBALS['MY_ASSERT_ACTIVE']=false;
               $GLOBALS['MY_ASSERT_CALLBACK']='myAssertCallback';
               phpxAssertHandler_f(
                   null,
                   array(
                       0=>$GLOBALS['MY_ASSERT_ACTIVE'],
                       3=>$GLOBALS['MY_ASSERT_CALLBACK'],
                   )
               );
                
 * @param  mixed = file or options
 * @param  line
 * @param  code
 * @return  void
 */
function phpxAssertHandler_f($file_or_custom_options=null, $line_or_assert_options=null, $code=null){

   static $custom_options;
   $debug = false;

   if (is_null($code)){
       // set default assert_options
       $assert_options[]=1;//ASSERT_ACTIVE
       $assert_options[]=0;//ASSERT_WARNING -
       $assert_options[]=0;//ASSERT_QUIET_EVAL
       $assert_options[]=__FUNCTION__;//ASSERT_CALLBACK       

       // set default custom_options
       $custom_options[]=E_USER_ERROR;// error level           

       if (!is_null($line_or_assert_options)){
           // assert_options are passed in
           if (!is_array($line_or_assert_options)){
               $line_or_assert_options=array($line_or_assert_options);
           }
           foreach ($line_or_assert_options as $i=>$assert_option){
               if ($assert_option===true) $assert_option=1;
               if ($assert_option===false) $assert_option=0;
               $assert_options[$i]=$assert_option;
               if($debug) echo ("assert_options[$i]=$assert_option\n");
           }
       }

       if (!is_null($file_or_custom_options)){
           // custom_options are passed in
           if (!is_array($file_or_custom_options)){
               $file_or_custom_options=array($file_or_custom_options);
           }
           foreach ($file_or_custom_options as $i=>$custom_option){
               if ($custom_option===true) $custom_option=1;
               if ($custom_option===false) $custom_option=0;
               $custom_options[$i]=$custom_option;
               if($debug) echo ("custom_options[$i]=$custom_option\n");
           }
       }

       // set assert options
       @assert_options (ASSERT_ACTIVE, $assert_options[0]);
       @assert_options (ASSERT_WARNING, $assert_options[1]);
       @assert_options (ASSERT_QUIET_EVAL, $assert_options[2]);
       @assert_options (ASSERT_CALLBACK, $assert_options[3]);       

   } else {
   // we are acting as a callback function
       $file = $file_or_custom_options;
       $line = $line_or_assert_options;
       $msg="ASSERTION FAILED: $code";
       phpxErrorHandler_f ($custom_options[0],$msg,$file,$line);
   }
}//phpxAssertHandler_f()
Thomas
28-Mar-2005 11:56
Another very good unit testing framework is SimpleTest, which can be found at http://www.lastcraft.com/simple_test.php

It has very good documentation, support for mock objects and tools for automating testing of entire web sites.
nyk at forumone dot com
27-Aug-2002 09:56
Assertion is a useful debugging feature, but for building unit tests and automated regression tests you should seriously consider using the PHPtest in the PEAR archive (http://pear.php.net/package-info.php?pacid=38) that is based on the JUnit framework for Java. There is also another unit testing framework, also based on JUnit and also called PHPunit on SourceForge (http://sourceforge.net/projects/phpunit/). I believe it is an independent effort from that on PEAR.