Aserción

(No version information available, might only be in Git)

AserciónVerifica si la aserción es false

Descripción

PHP 5 y 7

assert(mixed $assertion, string $description = ?): bool

PHP 7

assert(mixed $assertion, Throwable $exception = ?): bool

La función assert() revisará el parámetro assertion proporcionado y tomará la acción apropiada si su resultado es false.

Aserciones tradicionales (PHP 5 y 7)

Si el parámetro assertion es proporcionado como un string será evaluado como código PHP por la función assert(). Las ventajas de un parámetro assertion como string es que son menos sobrecargados cuando la comprobación de la aserción está deshabilitada y los mensajes que contienen la expresión assertion, la expresión falla. Esto significa que si pasa una condición de tipo boolean como assertion esta condición no se mostrará como parámetro a la función de aserción la cual tiene que haber definido con la función assert_options(), la condición es convertida a un string antes de llamar ese manejador de función, y el tipo boolean false es convertido como el string vacío.

Las aserciones deberían ser utilizadas solamente como una característica de depuración. Debería utilizarlas para las revisiones de buen funcionamiento las cuales comprueban las condiciones que siempre deberían ser true y que indican algunos errores de programación o si no, para revisar la presencia de algunas características, como funciones de extensión o ciertos límites del sistema y características.

Las aserciones no deberían utilizarse para operaciones normales en tiempo de ejecución como revisiones de parámetros de entrada. Como regla general su código siempre debería ser capaz de funcionar correctamente aún si la verificación de aserción no está activada.

El comportamiento de la función assert() podría ser configurado por la función assert_options() o por .ini-settings el cual está descrito en la página del manual de esas funciones.

La función assert_options() y/o la directiva de configuración ASSERT_CALLBACK permite que una función de llamada de retorno sea establecida para manejar aseciones fallidas.

Las llamadas de retorno assert() son particularmente útiles para construir conjuntos de pruebas automatizadas porque le permiten capturar fácilmente el código pasado a la aserción, junto con la información en donde fue hecha la aserción. Mientras que la información puede ser capturada a través de otros métodos, utilizar asernciones lo hace mucho más rápido y más fácil!

La función de llamada de retorno debería aceptar tres argumentos. El primero contendrá el fichero en que falló la aserción. El segundo contendrá la línea en la que falló la aserción y el tercer argumento contendrá la expresión que falló (si la hubiera — valores literales tales como 1 o "dos" no se pasarán a través de este argumento). Los usuarios de PHP 5.4.8 y versiones posteriores también podrían proveer un cuarto argumento opcional, que contendrá el parámetro description proporcionado a la función assert(), si fue establecido.

Expectativas (solamente PHP 7)

La función assert() es una construcción de lenguaje en PHP 7, que permite la definición de expectativas: las aserciones que surten efecto en ambientes de desarrollo y pruebas, pero que se optimizan para que tengan costo cero en la producción.

************* desde aqui *************** Mientras que assert_options() puede ser utilizada para controlar el comportamiento como se describe anteriormente por la compatibilidad con versiones anteriores, el código PHP 7 sólo debería usar las dos directivas nuevas de configuración para controlar el comportamiento de assert() y no llamar a assert_options().

*************** DESDE AQUI **************** PHP 7 configuration directives for assert()
Directive Default value Possible values
zend.assertions 1
  • 1: generate and execute code (development mode)
  • 0: generate code but jump around it at runtime
  • -1: do not generate code (production mode)
assert.exception 0
  • 1: throw when the assertion fails, either by throwing the object provided as the exception or by throwing a new AssertionError object if exception wasn't provided
  • 0: use or generate a Throwable as described above, but only generate a warning based on that object rather than throwing it (compatible with PHP 5 behaviour)

Parámetros

assertion

The assertion. In PHP 5, this must be either a string to be evaluated or a boolean to be tested. In PHP 7, this may also be any expression that returns a value, which will be executed and the result used to indicate whether the assertion succeeded or failed.

description

An optional description that will be included in the failure message if the assertion fails.

exception

In PHP 7, the second parameter can be a Throwable object instead of a descriptive string, in which case this is the object that will be thrown if the assertion fails and the assert.exception configuration directive is enabled.

Valores devueltos

false if the assertion is false, true otherwise.

Historial de cambios

Versión Descripción
7.0.0 assert() is now a language construct and not a function. assertion() can now be an expression. The second parameter is now interpreted either as an exception (if a Throwable object is given), or as the description supported from PHP 5.4.8 onwards.
5.4.8 The description parameter was added. The description is also now provided to a callback function in ASSERT_CALLBACK mode as the fourth argument.

Ejemplos

Traditional assertions (PHP 5 and 7)

Ejemplo #1 Handle a failed assertion with a custom handler

<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE1);
assert_options(ASSERT_WARNING0);
assert_options(ASSERT_QUIET_EVAL1);

// 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("")');
?>

Ejemplo #2 Using a custom handler to print a description

<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE1);
assert_options(ASSERT_WARNING0);
assert_options(ASSERT_QUIET_EVAL1);

// Create a handler function
function my_assert_handler($file$line$code$desc null)
{
    echo 
"Assertion failed at $file:$line$code";
    if (
$desc) {
        echo 
": $desc";
    }
    echo 
"\n";
}

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

// Make an assertion that should fail
assert('2 < 1');
assert('2 < 1''Two is less than one');
?>

El resultado del ejemplo sería:

 Assertion failed at test.php:21: 2 < 1
 Assertion failed at test.php:22: 2 < 1: Two is less than one
 

Expectations (PHP 7 only)

Ejemplo #3 Expectations without a custom exception

<?php
assert
(true == false);
echo 
'Hi!';
?>

With zend.assertions set to 0, the above example will output:

Hi!

With zend.assertions set to 1 and assert.exception set to 0, the above example will output:

Warning: assert(): assert(true == false) failed in - on line 2
Hi!

With zend.assertions set to 1 and assert.exception set to 1, the above example will output:

Fatal error: Uncaught AssertionError: assert(true == false) in -:2
Stack trace:
#0 -(2): assert(false, 'assert(true == ...')
#1 {main}
  thrown in - on line 2

Ejemplo #4 Expectations with a custom exception

<?php
class CustomError extends AssertionError {}

assert(true == false, new CustomError('True is not false!'));
echo 
'Hi!';
?>

With zend.assertions set to 0, the above example will output:

Hi!

With zend.assertions set to 1 and assert.exception set to 0, the above example will output:

Warning: assert(): CustomError: True is not false! in -:4
Stack trace:
#0 {main} failed in - on line 4
Hi!

With zend.assertions set to 1 and assert.exception set to 1, the above example will output:

Fatal error: Uncaught CustomError: True is not false! in -:4
Stack trace:
#0 {main}
  thrown in - on line 4

Ver también

  • assert_options() - Establecer/obtener valores de las directivas relacionadas con las aserciones

add a note add a note

User Contributed Notes 8 notes

up
18
hodgman at ali dot com dot au
15 years ago
As noted on Wikipedia - "assertions are primarily a development tool, they are often disabled when a program is released to the public." and "Assertions should be used to document logically impossible situations and discover programming errors— if the 'impossible' occurs, then something fundamental is clearly wrong. This is distinct from error handling: most error conditions are possible, although some may be extremely unlikely to occur in practice. Using assertions as a general-purpose error handling mechanism is usually unwise: assertions do not allow for graceful recovery from errors, and an assertion failure will often halt the program's execution abruptly. Assertions also do not display a user-friendly error message."

This means that the advice given by "gk at proliberty dot com" to force assertions to be enabled, even when they have been disabled manually, goes against best practices of only using them as a development tool.
up
5
mail<at>aaron-mueller.de
17 years ago
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);

?>
up
2
Krzysztof &#39;ChanibaL&#39; Bociurko
16 years ago
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...)
up
0
Tom
4 years ago
When migrating older code to PHP 7.2+, you may get E_DEPRECATED warnings for every call to assert() you ever wrote, urging you to not pass the assertion as a string.

It may be tempting to just run a regular expression across your files to convert all strings within "assert(...)" to statements. But, before you do that, be aware of the following caveat!

For example, this code simply asserts that $input is not empty.

assert('$input;');

This works, because the string passed to assert() is evaluated as a PHP statement and the result cast to Boolean.

If you want to have an equivalent statement that doesn't pass the first parameter as a string, your regular expression should rewrite this statement as:

assert((bool) ($input));

However, this looks a bit bulky and it is tempting to instead opt for the more direct approach to convert the above line to this:

assert($input);

But! This new statement will do one of three things:

1) Looks as if it worked as intended because $input just happens to be Boolean to begin with
2) Throw a parse error if $input is a string (best case)
3) Allow an attacker on a poorly configured server to execute arbitrary PHP-Code (worst case)

The reason is that, even though on PHP 7.2+ a E_DEPRECATED warning is raised, if assert() finds the first parameter to be a string, it will still execute it as PHP-Code, just as if it was called with a string to begin with.

If an attacker finds a way to manipulate the contents of $input, you might end up with a remote code execution vulnerability. So just be extra careful when migrating assertions.
up
-3
jason at jaypha dot com
6 years ago
You can take advantage of how assert is handled to use it for crude conditional compilation.

For example

<?php
  assert
(print("Some debug message\n"));
 
assert(($val = "dev") || true);
?>

Since print() always returns 1, the topmost assertion will pass. For others, you may need to add a || true. Always enclose the expression in ().

In a development environment where zend.assertions=1, the above code will execute. In production environments where zend.assertions=-1, it wont even compile, thus not burdening performance.

Another, more real world, example.

<?php
  $cssSrc
= 'https://code.jquery.com/jquery-3.2.1.min.js';
 
assert(($cssSrc = 'http://dev.local/jquery-3.2.1.js') || true);
  echo
"<link rel='stylesheet' type='text/css' href='$cssSrc'/>\n";
?>

In a production environment, The website will use the minified version from the CDN. In a development environment, a development version, sourced locally, will be used instead.

Note: This will not work for everything. Only code that can be embedded in an expression will work.
up
-6
uramihsayibok, gmail, com
13 years ago
There's a nice advantage to giving assert() some code to execute, as a string, rather than a simple true/false value: commenting.

<?php

assert
('is_int($int) /* $int parameter must be an int, not just numeric */');

// and my personal favorite
assert('false /* not yet implemented */');

?>

The comment will show up in the output (or in your assertion handler) and doesn't require someone debugging to go through your code trying to figure out why the assertion happened. That's no excuse to not comment your code, of course.

You need to use a block comment (/*...*/) because a line comment (//...) creates an "unexpected $end" parse error in the evaluated code. Bug? Could be.
(You can get around it with "false // not yet implemented\n" but that screws up the message)
up
-2
Ben
7 years ago
if there was no 'warning' message when assertion failed (FALSE), try reset the error handler:
<?php
set_error_handler
( null );
up
-9
office dot stojmenovic at gmail dot com
10 years ago
Example from Ikac Framework how they use assert()

<?php

   
/**
     * Set Assertion Debug
     *
     * This method will check the given assertion and take appropriate -
     * action if its result is FALSE.
     *
     * This file is part of Ikac Framework.
     *
     * @package Ikac Framework
     * @author Ivan Stojmenovic Ikac <contact.@stojmenovic.info>
     *
     * @param mixed $assertion  The assertion.
     * @param mixed $callback Callback to call on failed assertions
     * @param array $options  Set the various control options or just query their current settings.
     * @param string $description  An optional description that will be included in the failure message if the assertion fails.
     */
   
public function setAssertionDebug($assertion, $callback, array $options, $description = null)
    {
        if (
is_array($options)) {
            foreach (
$options AS $option => $value) {
               
assert_options($option, $value);
            }
        }
        if (
$callback) {
           
assert_options(ASSERT_CALLBACK, $callback);
        }
       
        return
assert($assertion, $description);
    }
   
?>

How to use:

<?php
     
use Ikac\Component\SystemBehaviour\OptionsInfo;

     
$system = new OptionsInfo();

     
$option = array(ASSERT_ACTIVE => 1,ASSERT_WARNING => 0,ASSERT_QUIET_EVAL => 1);

    
$system->setAssertionDebug('2<1', function(){
            echo
"Assertion failed";
     },
$option);

?>
To Top