With all the discussion of how to best to use assert, I thought I would put my two cents in. I feel that errors should be thrown for potential things that could go wrong in production like failed database connections, but asserts should be used for sanity checks that should never fire unless there is an actual bug in the code.
When writing difficult code I use asserts to check for hard to find mistakes like unexpected race conditions. Then I leave them on (but logging only of course) in production. My assert statements tend to be very computationally cheap. In fact generally my assert statements are as simple as checking the return value from boolean functions.
This means I generally end up with alot of code like the following:
<?php
$result = flock($file, LOCK_EX); assert('$result');
$result = ftruncate($file, 0); assert('$result');
$result = fclose($file); assert('$result');
?>
I recently realized that I could write the much cleaner:
<?php
flock($file, LOCK_EX) or assert(0);
ftruncate($file, 0) or assert(0);
fclose($file) or assert(0);
?>
Much cleaner. Of course the error message doesn't tell me anything about the failure like it does when you pass a string. But an assertion failing means I have a major bug in my code, so its not too much work to look up the line number and figure out the error.
Also note that I don't use this for every boolean statement, since sometimes a failure isn't cause for an error. For example when I create a new user in the database, if the query fails its not an error, it just means the username is taken. If I did an assert there it would have to check that the query was successful or the mysql_errno was what I anticipated. But I could do that as follows:
<?php
mysql_query("INSERT INTO users (username, password) VALUES ('{$username}','{$password}')") or assert('mysql_errno()===1061');
?>
assert
(PHP 4, PHP 5)
assert — Vérifie si une assertion est fausse
Description
assert() va vérifier l'assertion assertion et prendre la mesure appropriée si le résultat est FALSE.
Si assertion est donnée sous la forme d'une chaîne, elle sera évaluée comme un code PHP par la fonction assert(). Les avantages de ce type d'assertion sont d'être moins lourd si la vérification d'assertion est désactivée, et les messages contenant l'assertion lorsque l'assertion échoue. Cela signifie que si vous passez une condition booléenne en tant qu'assertion, cette condition ne sera pas considérée comme un paramètre par la fonction d'assertion que vous avez définie avec la fonction assert_options(), la condition est convertie en chaîne de caractères avant l'appel à ce gestionnaire de fonction, et le booléen FALSE sera converti en chaîne de caractères vide.
Il est recommandé de n'utiliser les assertions que comme outil de déboguage. Vous pouvez les utiliser pour les vérifications d'usage : ces conditions doivent normalement être vraies, et indiquer une erreur de programmation si ce n'est pas le cas. Vous pouvez aussi vérifier la présence de certaines extensions ou limitations du système.
Les assertions ne doivent pas être utilisées pour faire des opérations de vérifications en production, comme des vérifications de valeur d'argument. En conditions normales, votre code doit être en état de fonctionner si la vérification d'assertion est désactivée.
Le comportement de assert() peut être configuré par assert_options() ou par les configurations .ini décrites dans la page de manuel de cette fonction.
La fonction assert_options() et la directive ASSERT_CALLBACK permettent de configurer une fonction qui sera appelée lorsque l'assertion échoue.
Les fonctions de rappel pour assert() sont particulièrement utiles pour bâtir des suites de tests automatiques, car elles vous permettent de capturer facilement le code passé à l'assertion, ainsi que des informations sur le lieu et le moment de l'assertion. Même si ces informations peuvent être appelées par d'autres méthodes, les assertions sont plus rapides et plus faciles.
La fonction de rappel doit accepter trois arguments. Le premier contient le nom du fichier qui a vu l'assertion échouer. Le second contient le numéro de ligne dans le fichier précédent. Le troisième argument contient l'expression qui a échoué (s'il y en a : les valeurs littérales comme 1 ou "deux" ne seront pas passées par cet argument).
Liste de paramètres
- assertion
-
L'assertion.
Valeurs de retour
FALSE si l'assertion est fausse, TRUE sinon.
Exemples
Exemple #1 Gestion des assertions avec un gestionnaire personnalisé
<?php
// Activation des assertions et mise en mode discret
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);
// Création d'un gestionnaire d'assertions
function my_assert_handler($file, $line, $code)
{
echo "<hr>Échec de l'assertion :
File '$file'<br />
Line '$line'<br />
Code '$code'<br /><hr />";
}
// Configuration de la méthode de callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');
// Utilisation d'une assertion qui va échouer
assert('mysql_query("")');
?>
assert
23-Jan-2008 08:24
29-Nov-2007 02:19
Summary: turn assert() checking in production site, and use plain conditionals coupled with error reporting (trigger_error() or throw) for check that must be performed always.
I'd like to support oppinion of Matthew (matthew, at teh dot ath dot cx), and oppose the one of Tom (tom russo at gmail dot com).
When developing a program, you clearly want to check for various conditions, for example input validity and conformance of results of computation to various constraints, like database format. However, while some of the checks are mandatory, because supplied data varies with every request, others aren't, for example result of computations. Well written function will behave reasonably for *any* input -- either compute result/perform action, or signal error, be it return value or exception. And if a function takes input from trusted source, like another function you wrote, you don't need to check for all possible problems.
This is important distinction -- while developing, your incomplete and/or buggy function may return invalid result. Or a wrong kind of argument may be passed to your function. Or the code may, in some corner case, generate suprious data. This is where assertion comes in hand, to detect such conditions, signal to developer, and possibly stop execution, to prevent data loss.
However, the assumption is, that you ship code not earlier than the functions are complete. This means, you should not need checking of such conditions. If your code is incomplete, you don't ship, simple as that. Or label it as test version.
For checks that are required for every execution of code, you want plain IFs, is_* functions and so on, coupled with trigger_error() and/or throw statement. Wrapping assertions around those will not help it at all, even slightly impact performance. There simply is no point in using assert() there. You can get as detailed error reports with throw and exception handlers or with trigger_error() as with assert().
On the other hand, for checks that are needed only during development, you use assert(' condition ' ), since it can be turned off, and no performance impact occurs.
There is also a catch: error report form assert() may be verbose enough to reveal confidential data. What if you forget to turn assertion checking off and one is triggered in database connection setup code, with stack backtrace revealing DB username and password?
01-Oct-2007 06:13
Note that func_get_args() should be used carefully and never in a string! For example:
<?php
function asserted_normal($a, $b) {
assert(var_dump(func_get_args()));
}
function asserted_string($a, $b) {
assert('var_dump(func_get_args())');
}
?>
<?php asserted_normal(1,2) ?> prints
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}
but <?php asserted_string(3,4) ?> prints
array(1) {
[0]=>
string(25) "var_dump(func_get_args())"
}
This is because of that the string passed to assert() is being evaled inside assert, and not your function. Also, note that this works correctly, because of the eval scope:
<?php
function asserted_evaled_string($a, $b) {
assert(eval('var_dump(func_get_args())'));
}
asserted_evaled_string(5,6);
?>
array(2) {
[0]=>
int(5)
[1]=>
int(6)
}
(oh, and for simplicity's sake the evaled code doesn't return true, so don't worry that it fails assertion...)
16-Sep-2007 08:15
Much of the value of assertions comes from the assumption that you can do performance intensive checking for debugging that will not affect the code in production. Breaking the assumption that assertions will not be routinely enabled in production prohibits this usage and is counterproductive.
24-Dec-2006 03:25
hodgman at ali dot com dot au said:
"Assertions should only be enabled during testing/development, and then disabled once your code reaches a production stage."
Assertions should _not_ be turned off in production code. Although it's common to do so, turning off assertions in production is a bad practice.
If your production code fails an assert, YOU WANT TO KNOW ABOUT IT. Asserts are a debugging tool, but you should not stop debugging your code just because it has gone into production.
Many people claim that removing asserts gives a performance benefit. In modern programming languages this simply isn't true. If you were doing an assert on something that is extremely slow/expensive to compute, you might consider turning that assert off. But in practice this really isn't how asserts are used.
There's a good discussion of this issue in the book The Pragmatic Programmer.
13-Sep-2006 10:51
Here is a simple demonstration of Design By Contract with PHP
<?php
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_BAIL, 1);
assert_options(ASSERT_CALLBACK, 'dcb_callback');
function dcb_callback($script, $line, $message) {
echo "<h1>Condition failed!</h1><br />
Script: <strong>$script</strong><br />
Line: <strong>$line</strong><br />
Condition: <br /><pre>$message</pre>";
}
// Parameters
$a = 5;
$b = 'Simple DCB with PHP';
// Pre-Condition
assert('
is_integer($a) &&
($a > 0) &&
($a < 20) &&
is_string($b) &&
(strlen($b) > 5);
');
// Function
function combine($a, $b) {
return "Kombined: " . $b . $a;
}
$result = combine($a, $b);
// Post-Condition
assert('
is_string($result) &&
(strlen($result) > 0);
');
// All right, the Function works fine
var_dump($result);
?>
10-Aug-2006 04:45
I dont agree with gk at proliberty dot com's statements below.
If you are constantly enabling assertions before each assertion, then you are removing the functionality provided by being able to turn off assertions in the first place.
Assertions should only be enabled during testing/development, and then disabled once your code reaches a production stage.
This means you should either leave disabling/enabling assertions up to the INI file, or let the entry point of the script decide.
If you need an assertion to be there in the final copy of the code, then you are using the wrong tool. Assertions are a tool for debugging only.
26-Aug-2005 07: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()
28-Mar-2005 07: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.
26-Aug-2002 06: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.
