Giter Site home page Giter Site logo

dbunit's Introduction

Hi!

I am Sebastian Bergmann. If you develop software using the PHP programming language then you may have come across my name. I am the creator and maintainer of PHPUnit as well as many other libraries and tools that are commonly used.


πŸ‘· Check out what I'm currently working on


πŸ”­ Latest releases I've contributed to


πŸ“« How to reach me

dbunit's People

Contributors

christeredvartsen avatar d4rkmindz avatar dmelo avatar dragonbe avatar elazar avatar elblinkin avatar exptom avatar grahamcampbell avatar gsouf avatar howkey666 avatar jeunito avatar jstruzik avatar m0003r avatar marcocova avatar michsindelar avatar mlively avatar naderman avatar neilime avatar paulyg avatar piotrbudny avatar proofek avatar sander-bol avatar sebastianbergmann avatar sicaine avatar sqmk avatar tehek avatar wakeless avatar whatthejeff avatar yparghi avatar zerkms avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dbunit's Issues

PHPUnit_Util_Type::toString()

I have fatal error
PHP Fatal error: Call to undefined method PHPUnit_Util_Type::toString() in /usr/share/php/PHPUnit/Extensions/Database/Constraint/TableIsEqual.php on line 106
About pear.phpunit.de/DbUnit-1.1.1

Release Type PEAR-style PHP-based Package
Name DbUnit
Channel pear.phpunit.de
Summary DbUnit port for PHP/PHPUnit to support database
interaction testing.
Description DbUnit port for PHP/PHPUnit to support database
interaction testing.
Maintainers Sebastian Bergmann [email protected]
(lead)
Release Date 2011-11-10 10:01:20
Release Version 1.1.1 (stable)
API Version 1.1.0 (stable)
License BSD License
Release Notes http://github.com/sebastianbergmann/dbunit/blob/master/README.markdown
Required Dependencies PHP version 5.2.7
PEAR installer version 1.9.4 or newer
Package pear.phpunit.de/PHPUnit
Version 3.6.0 or newer
Package pear.symfony-project.com/YAML
Version 1.0.2 or newer
Extension pdo
Extension reflection
Extension simplexml
Extension spl
package.xml version 2.0
Last Modified 2012-01-27 13:54
Previous Installed - None -
Version
About pear.phpunit.de/PHPUnit-3.6.10

Release Type PEAR-style PHP-based Package
Name PHPUnit
Channel pear.phpunit.de
Summary The PHP Unit Testing framework.
Description The PHP Unit Testing framework.
Maintainers Sebastian Bergmann [email protected] (lead)
Release Date 2012-01-27 10:49:19
Release Version 3.6.10 (stable)
API Version 3.6.0 (stable)
License BSD License
Release Notes http://github.com/sebastianbergmann/phpunit/blob/master/README.markdown
Required Dependencies PHP version 5.2.7
PEAR installer version 1.9.4 or newer
Package pear.phpunit.de/File_Iterator
Version 1.3.0 or newer
Package pear.phpunit.de/Text_Template
Version 1.1.1 or newer
Package pear.phpunit.de/PHP_CodeCoverage
Version 1.1.0 or newer
Package pear.phpunit.de/PHP_Timer
Version 1.0.1 or newer
Package pear.phpunit.de/PHPUnit_MockObject
Version 1.1.0 or newer
Package pear.symfony-project.com/YAML
Version 1.0.2 or newer
Extension dom
Extension pcre
Extension reflection
Extension spl
Optional Dependencies Package pear.phpunit.de/PHP_Invoker
Version 1.1.0 or newer
Extension json
Extension simplexml
Extension tokenizer
package.xml version 2.0
Last Modified 2012-01-27 13:51
Previous Installed - None -
Version

assertEquals() equates NULL and empty values

The assertEquals method in PHPUnit_Extensions_Database_DataSet_ReplacementTable and PHPUnit_Extensions_Database_DataSet_AbstractTable performs a not equal != comparison between $this->getValue($i, $columnName) and $other->getValue($i, $columnName). This leads to NULL and empty character fields, or int(0), being considered equivalent. Performing a not identical comparison !== here would differentiate NULL from other values.

Yaml DataSet - Symfony Yaml Componet changed in actual release

Hi,

I've installed the Symfony Yaml-Component via Pear as described in the documentation (http://symfony.com/components) and tried to use it. PHPUnit process exited with the message:

PHP Fatal error: main(): Failed opening required 'SymfonyComponents/YAML/sfYaml.php' ...

After checking the include paths I found out that neither the path nor the filename used to include the yaml component existed. A view into the Symfony Sources (https://github.com/symfony/symfony/tree/master/src/Symfony/Component/Yaml) shows that the required file no longer exists / the paths were changed.

Regards,

Robert

assertTablesEqual() relies on records' order.

Using PHPUnit-3.5.0 and PHP-5.3.3 on Ubuntu 10.10. Not tested with other versions.

The following test should not fail because it compares a dataset to itself.

Here is DatabaseTest.php:

<?php
require_once 'PHPUnit/Extensions/Database/TestCase.php';
require_once 'PHPUnit/Extensions/Database/DataSet/XmlDataSet.php';

class DatabaseTest extends PHPUnit_Extensions_Database_TestCase
{
  protected function getConnection()
  {
    $pdo = new PDO('sqlite:db/negozi.db');
    return $this->createDefaultDBConnection($pdo, 'negozi');
  }

  protected function getDataSet()
  {
    return $this->createXMLDataSet(dirname(__FILE__).'/dati-iniziali.xml');
  }

  public function testTableNazione() {
    $set = $this->createXMLDataSet(dirname(__FILE__).'/dati-iniziali.xml');

    $this->assertTablesEqual(
      $set->getTable('NAZIONE'),
      $this->getConnection()
           ->createDataSet()
           ->getTable('NAZIONE')
    );
  }
}
?>

Here is dati-iniziali.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dataset SYSTEM "dataset.dtd">
<dataset>
  <table name="NAZIONE">
    <column>CODICE_ISO</column>
    <column>NOME</column>
    <row>
      <value>IT</value>
      <value>Italia</value>
    </row>
    <row>
      <value>FR</value>
      <value>Francia</value>
    </row>
    <row>
      <value>SP</value>
      <value>Spagna</value>
    </row>
  </table>
</dataset>

The output of phpunit DatabaseTest.php is:

PHPUnit 3.5.0 by Sebastian Bergmann.

F

Time: 1 second, Memory: 3.75Mb

There was 1 failure:

1) DatabaseTest::testNuovoCliente
Failed asserting that actual 
+----------------------+----------------------+
| NAZIONE                                     |
+----------------------+----------------------+
|      CODICE_ISO      |         NOME         |
+----------------------+----------------------+
|          FR          |       Francia        |
+----------------------+----------------------+
|          IT          |        Italia        |
+----------------------+----------------------+
|          SP          |        Spagna        |
+----------------------+----------------------+

 is equal to expected 
PHPUnit_Extensions_Database_DataSet_DefaultTable Object
(
    [tableMetaData:protected] => PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData Object
        (
            [columns:protected] => Array
                (
                    [0] => CODICE_ISO
                    [1] => NOME
                )

            [primaryKeys:protected] => Array
                (
                )

            [tableName:protected] => NAZIONE
        )

    [data:protected] => Array
        (
            [0] => Array
                (
                    [CODICE_ISO] => IT
                    [NOME] => Italia
                )

            [1] => Array
                (
                    [CODICE_ISO] => FR
                    [NOME] => Francia
                )

            [2] => Array
                (
                    [CODICE_ISO] => SP
                    [NOME] => Spagna
                )

        )

)
 Reason: Expected value of IT for row 0 column CODICE_ISO, has a value of FR

/home/marcenuc/Tailor/workspace-php/ConfezioniSposo/remote/lib/DatabaseTest.php:26

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

CSV dataset - check that parameters passing to function array_combine have equal number of elements

I think that it would be great if in method "addTable" in class PHPUnit_Extensions_Database_DataSet_CsvDataSet will be check that parameters passing to function array_combine have equal number of elements. I want a know which dataset is wrong and do not see a PHP error. The method "addTable" can looks like this (I'm using PHPUnit 3.5.15):

/**
     * Adds a table to the dataset
     *
     * The table will be given the passed name. $csvFile should be a path to
     * a valid csv file (based on the arguments passed to the constructor.)
     *
     * @param string $tableName
     * @param string $csvFile
     */
    public function addTable($tableName, $csvFile)
    {
        if (!is_file($csvFile)) {
            throw new InvalidArgumentException("Could not find csv file: {$csvFile}");
        }

        if (!is_readable($csvFile)) {
            throw new InvalidArgumentException("Could not read csv file: {$csvFile}");
        }

        $fh      = fopen($csvFile, 'r');
        $columns = $this->getCsvRow($fh);
        $columnsCount = count($columns);

        if ($columns === FALSE)
        {
            throw new InvalidArgumentException("Could not determine the headers from the given file {$csvFile}");
        }

        $metaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData($tableName, $columns);
        $table    = new PHPUnit_Extensions_Database_DataSet_DefaultTable($metaData);

        while (($row = $this->getCsvRow($fh)) !== FALSE)
        {
            if ($columnsCount !== count($row)) {
                throw new Exception("Csv file: {$csvFile} and table: {$tableName} should have an equal number of elements");
            } 
            $table->addRow(array_combine($columns, $row));
        }

        $this->tables[$tableName] = $table;
    }

Support for Non-SQL databases

At our company we are using MongoDB as our main database for our current application.
Sadly, phpUnits database testing does not currently support MongoDB, right?

I would love to see that implemented.

QueryTable gives error if table is empty

Extensions\Database\DataSet\QueryTable::createTableMetaData()
throws error if table is empty.

Basically empty tables causes QueryTable::data to be empty => no array keys => error

How do I submit a patch? ^_^

Extensions\Database\DataSet\QueryTable : Line 162

protected function createTableMetaData()
{
    if ($this->tableMetaData === NULL)
    {
        $this->loadData();

        // if some rows are in the table
        $columns = array();
        if (isset($this->data[0]))
            // get column names from data
            $columns = array_keys($this->data[0]);
        else {
            // if no rows found, get column names from database
            $pdoStatement = $this->databaseConnection->getConnection()->prepare("SELECT column_name FROM information_schema.COLUMNS WHERE table_schema=:schema AND table_name=:table");
            $pdoStatement->execute(array(
                "table"        => $this->tableName,
                "schema"    => $this->databaseConnection->getSchema()
            ));

            $columns = $pdoStatement->fetchAll(PDO::FETCH_COLUMN, 0);
        }
        // create metadata
        $this->tableMetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData($this->tableName, $columns);
    }
}

assertTableRowCount causes fatal error when trying to call self::getConnection

DBUnit 1.2.2

PHPUnit_Extensions_Database_TestCase line 261

Method isn't static, call to get connection needs to be made using $this, to get the concrete class's getConnection() method.

When using $this->assertTableRowCount() I get:
Fatal error: Cannot call abstract method PHPUnit_Extensions_Database_TestCase::getConnection() in /usr/lib/php/pear/PHPUnit/Extensions/Database/TestCase.php on line 261

Forum Available for PHPUNit

Hello,

Is there any forum available for "PHPUnit" as we have for other softwares like jquery, symfony ?
Basically looking to discuss some modification, recommendations from community

Please delete the the issue, if it is wrongly discussed over here.

DbUnit 1.1dataset assertions don't work with PHPUnit 3.6

After upgrading to the recent versions of software on pear channel pear.phpunit.de (PHPUnit 3.6.0 and DbUnit 1.1.0) I've noticed that PHPUnit_Extensions_Database_Constraint_DataSetIsEqual and PHPUnit_Extensions_Database_Constraint_TableIsEqual don't work anymore (they work with PHPUnit 3.5.15 and DbUnit 1.0.3). A quick debug session shows that PHPUnit_Extensions_Database_Constraint_DataSetIsEqual::evaluate() detects the difference but just returns FALSE. Looking at core PHPUnit constraints (e.g. PHPUnit_Framework_Constraint::evaluate()) reveals that it isn't enough for proper failure report in 3.6.

Below is the simple test that reports 2 failures using PHPUnit 3.5.15 + DbUnit 1.0.3 but doesn't report using PHPUnit 3.6.0 + DbUnit 1.1.0:

ds1 = new MyApp_DbUnit_ArrayDataSet(array('t1' => array( array('c1' => '1', 'c2' => 'x') ))); $this->ds2 = new MyApp_DbUnit_ArrayDataSet(array('t1' => array( array('c1' => NULL, 'c2' => 'y') ))); } public function testDataSetIsEqual() { $this->assertThat($this->ds2, new PHPUnit_Extensions_Database_Constraint_DataSetIsEqual($this->ds1)); } public function testTableIsEqual() { $this->assertThat($this->ds2->getTable('t1'), new PHPUnit_Extensions_Database_Constraint_TableIsEqual( $this->ds1->getTable('t1'))); } ``` } class MyApp_DbUnit_ArrayDataSet extends PHPUnit_Extensions_Database_DataSet_AbstractDataSet { ``` /** * @var array */ protected $tables = array(); /** * @param array $data */ public function __construct(array $data) { foreach ($data AS $tableName => $rows) { $columns = array(); if (isset($rows[0])) { $columns = array_keys($rows[0]); } $metaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData($tableName, $columns); $table = new PHPUnit_Extensions_Database_DataSet_DefaultTable($metaData); foreach ($rows AS $row) { $table->addRow($row); } $this->tables[$tableName] = $table; } } protected function createIterator($reverse = FALSE) { return new PHPUnit_Extensions_Database_DataSet_DefaultTableIterator($this->tables, $reverse); } public function getTable($tableName) { if (!isset($this->tables[$tableName])) { throw new InvalidArgumentException("$tableName is not a table in the current database."); } return $this->tables[$tableName]; } ``` }

Refactoring to leverage Comparator Framework

PHPUnit 3.6 introduced a comparator framework that allows extensions to "overload" assertEquals() et. al. with custom comparison operations for objects. DbUnit should be refactored to leverage this by providing an implementation of PHPUnit_Framework_Comparator that can compare PHPUnit_Extensions_Database_DataSet objects and "just" provide convenience functionality to read data sets from CSV, XML, YAML, etc. as well as from a PDO connection.

CompositeDataSet: Mismatching documentation and implementation

CompositeDataSet's documentation (version 3.7) states that when several datasets contain the same table the rows are appended in the specified order. Subsequently, the code example composes two data sets like this:

class CompositeTest extends PHPUnit_Extensions_Database_TestCase
{
    public function getDataSet()
    {
        $ds1 = $this->createFlatXmlDataSet('fixture1.xml');
        $ds2 = $this->createFlatXmlDataSet('fixture2.xml');

        $compositeDs = new PHPUnit_Extensions_Database_DataSet_CompositeDataSet();
        $compositeDs->addDataSet($ds1);
        $compositeDs->addDataSet($ds2);

        return $compositeDs;
    }
}

The fixture files contain rows from the same table (guestbook).

Unfortunately, the code above doesn't work for two reasons:

  • CompositeDataSet()'s constructor expects a (non-optional) array.
  • More severely, the constructor will fail with an InvalidArgumentException: DataSet contains a table that already exists. That's because it iterates over each given data set and verifies that no table is specified more than once (see CompositeDataSet::addDataSet()).

I verified all of this by modifying the BankAccount sample and returning a composite BankAccountDBTest::getDataSet() which displayed the results outlined above.

It seems to me that the loop performed in addDataSet() shouldn't be required. I'd also prefer to have setters for data sets (either instead of or in addition to an optional constructor) to allow for them to be passed incrementally.

composer.json version/stability issue

composer install or composer update --dev run from a dbunit git clone results in this:

Loading composer repositories with package information
Installing dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package phpunit/phpunit >=3.8.0 could not be found.

Either the phpunit/phpunit version needs to be changed to 3.8.*@dev or minimum-stability: dev needs to be added.

assertTablesEqual - failure description, tables diff

When assertion that two tables are equal fails, whole content of both tables is printed out side by side.
Find what caused the failure in content of both tables can be really time consuming and uncofortable.
Some kind of diff output of both tables would be really helpful.

PHPUnit_Extensions_Database_TestCase::assertTableRowCount uses $this in object context

PHPUnit/Extensions/Database/TestCase.php on line 261

DbUnit Extension Version: 1.1.2

When I call this method, PHP will report 'PHP Fatal error: Using $this when not in object context in /usr/share/php/PHPUnit/Extensions/Database/TestCase.php on line 261'

<?php
/**
* Assert that a given table has a given amount of rows
*
* @Param string $tableName Name of the table
* @Param int $expected Expected amount of rows in the table
* @Param string $message Optional message
*/
public static function assertTableRowCount($tableName, $expected, $message = '')
{
    $constraint = new PHPUnit_Extensions_Database_Constraint_TableRowCount($tableName, $expected);
    $actual = $this->getConnection()->getRowCount($tableName);  // Using $this when not in object context 
    self::assertThat($actual, $constraint, $message);
}

Maximum Execution Time problems in the DBUnit component

I've suddenly started running into maximum execution time errors when running my tests in bulk (i.e. on an entire directory, rather than test by test). The errors always occur somewhere in DataSet/FlatXmlDataSet.php or DataSet/AbstractTable.php, e.g. "
Fatal error: Maximum execution time of 10 seconds exceeded in /usr/local/share/pear/PEAR/PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php on line 90".

I have tried setting max_execution_time and max_input_time to 0 in my php.ini, and have also tried setting them using the -d parameter to phpunit (e.g. phpunit -d max_input_time=0), but it does not have any affect.

When running the tests one by one, the problem does not occur.

The maximum execution time that it claims is always 10 seconds.

Version information

  • php5-cli 5.2.6.dfsg.1-1+lenny9
  • php5-xdebug 2.0.3-1
  • phpunit 3.4.14

Sqlite AUTOINCREMENT issue on Truncate

As described here http://www.sqlite.org/autoinc.html SQLite AUTOINCREMENT value is not reset with a simple "DELETE FROM tablename".

This causes a problem in PHPUnit_Extensions_Database_Operation_Truncate since SQLite requires two SQL commands to empty a table and reset the autoincrement value.

In PHPUnit_Extensions_Database_DB_MetaData_Sqlite there is a

protected $truncateCommand = 'DELETE FROM';

"PHPUnit_Extensions_Database_Operation_Truncate::execute()" should be slightly changed to allow PHPUnit_Extensions_Database_DB_MetaData_Sqlite::$truncateCommand to be an array like:

protected $truncateCommand = array('DELETE FROM' , 'DELETE FROM sqlite_sequence WHERE name = ?');

Local $tableNames variable not initialized in getTableNames method of Sqlite metadata implementation

When calling the getTableNames method in a PHPUnit_Extensions_Database_DB_MetaData_Sqlite object with an empty database, a PHP Notice will be thrown (local variable $tableNames is not initialized properly).

When running PHPUnit on strict mode this will cause the test to fail.

Note that this does not affect other implementations of the Metadata interface.

How to reproduce:

(...)

    public function testGetTableNamesOnEmptyDatabase()
    {
        $this->assertEmpty($this->getConnection()->getMetaData()->getTableNames());
        // Test failing on strict mode because of Undefined variable: tableNames
    }

    /**
     * @return \PHPUnit_Extensions_Database_DB_IDatabaseConnection
     */
    final public function getConnection()
    {
        return $this->createDefaultDBConnection(new \PDO('sqlite::memory:'), ':memory:');
    }

(...)

TRUNCATE implementation

I need truncate tables with cross references.
Now truncate implementation is
TRUNCATE table1;
...
TRUNCATE tableN;

For succesful execute command is required syntax:
TRUNCATE table,table2,tableN;

How set Operation to CASCADE ? There is no documentation on project web site or small example ?

Thanks
S.

Truncate on PostgresSQL does not reinitialize sequences values

Running DBUnit with fixtures may cause exceptions to be fired when trying to save new objects to database (for example with an ORM engine like Doctrine) or make asserts fail (especially assertTablesEqual) because of duplicate primary keys or primary keys not the same at each test run-tine. Example with the following:

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <table name="students">
        <column>stud_id</column>
        <column>stud_name</column>
        <column>stud_surname</column>
    </table>
    <row>
        <value>1</value>
        <value>John</value>
        <value>DOE</value>
    </row>
    <row>
        <value>2</value>
        <value>Jane</value>
        <value>DOE</value>
    </row>
    <row>
        <value>3</value>
        <value>Jack</value>
        <value>DOE</value>
    </row>
</dataset>

Running the code above may fail with a unique key constraint exception fired by Postgres as Doctrine will try to store a new Student object, using sequence next value whereas a Student already exists in database for the computed stud_id number.

$objStudent = new Student();
$objStudent->setSurname('James');
$objStudent->setName('DOE');
$objEntityManader->persist($objStudent);
$objEntityManader->flush(); // Exception may occur here

Same thing with the following:

$objTableQuery = $this->getConnection()->createQueryTable('student', 'SELECT * FROM student ORDER BY stud_id');
$objTableExpected = $this->createXmlDataSet(__DIR__ . '/PersistStudent.xml')->getTable('student');
$this->assertTablesEqual($objTableExpected, $objTableQuery);

having PersistStudent.xml as follow :

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <table name="students">
        <column>stud_id</column>
        <column>stud_name</column>
        <column>stud_surname</column>
    </table>
    <row>
        <value>1</value>
        <value>John</value>
        <value>DOE</value>
    </row>
    <row>
        <value>2</value>
        <value>Jane</value>
        <value>DOE</value>
    </row>
    <row>
        <value>3</value>
        <value>Jack</value>
        <value>DOE</value>
    </row>
    <row>
        <value>4</value>
        <value>James</value>
        <value>DOE</value>
    </row>
</dataset>

Here, we cannot figure out if stud_id will be 4 or something else, making assertTablesEqual fail. In fact, it may fail most of the time.

I'll try to find a fix and post it here.

YamlDataSet only looks at columns in first row instead of entire data set

If I have a yaml data set file like:

table:

column1: value
  • column1: value
    column2: value

Then only column 1 will be loaded into the database. The YamlDataSet should read the whole table and create a column set from all the rows in the table in the data set before setting the columns in the TableMetaData.

DBUnit Samples Failed asserting that

Hello Sebastian,

I have downloaded your example for work with Database "DB_unit Samples" in the class BankAccountCompositeTestBasic I have created a method based in the method testNewAccountCreations() like that:

public function testProof()
{
$tester = $this->getDatabaseTester();
$tester->onSetUp();

    //I dont insert in the database
    //$bank_account = new BankAccount('12345678912345678', $this->pdo);

    // I dont insert so the database is the same like in the begining
    $xml_dataset = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/_files/bank-account-seed.xml');
    PHPUnit_Extensions_Database_TestCase::assertDataSetsEqual($xml_dataset,  $tester->getConnection()->createDataSet());

    $tester->onTearDown();
}

?>
If I don't insert in the database... the database is the same like in the begining. BUT, I get this error "Failed asserting that...". I think is a exception "PHPUnit_Framework_ExpectationFailedException".... So I do not know why??

Regards

assertTablesEqual don't work in dbunit 1.1 & phpunit 3.6.2

Luego de actualizar los paquetes desde pear descargando phpunit 3.2.6 & dbunit 1.1.0 ha dejado de funcionar el mΓ©todo assertTablesEqual.

El problema que encontre es que no captura el error y siempre devuelve ok.

Para solucionar esto tuve que modificar los metodos evaluate, failureDescription y toString de la clase PHPUnit_Extensions_Database_Constraint_TableIsEqual:

Aca los cambios


public function evaluate($other, $description = '', $returnResult = FALSE)
    {
        if (!$other instanceof PHPUnit_Extensions_Database_DataSet_ITable) {
            throw new InvalidArgumentException(
              'PHPUnit_Extensions_Database_DataSet_ITable expected'
            );
        }

        try {
            $this->value->assertEquals($other);
            return TRUE;
        }

        catch (Exception $e) {
            $this->failure_reason = $e->getMessage();
            $this->fail($other, $description); //invocacion al metodo fail
            return FALSE;
        }
    }

Cambio de nombre del metodo:

protected function customFailureDescription($other, $description, $not) 

por

protected function failureDescription($other, $description=null, $not=null)

y por ultimo


public function toString()
    {
        return sprintf(
          //'is equal to expected %s', PHPUnit_Util_Type::toString($this->value)
          'is equal to expected %s', PHPUnit_Util_Type::export($this->value)
        );
    }

ArrayDataSet [humble contribution]

XML makes me a sad panda so I created an ArrayDataSet class. This class itself is not heavily tested but it seems to work as I expect it to.

Example Usage:
<?php
class MyTest extends PHPUnit_Extensions_Database_TestCase {
protected function getConnection() {
return $this->createDefaultDBConnection( new PDO( '...' ), 'baf' );
}

    protected function getDataSet() {
        $tables = array(
            'people' => array( 'badge', 'first', 'last', 'department', 'office', 'ext', 'modify_tm' )
            );
        $data = array(
            'people' => array()
            );
        return new PHPUnit_Extensions_Database_DataSet_ArrayDataSet( $tables, $data );
    }

    /**
    * Returns data row as array (who wants to type out all those keys?)
    * 
    * @param int $badge
    * @param string $first
    * @param string $last
    * @param [string] $department
    * @param [int] $office
    * @param [int] $ext
    * @param [string] $modify_tm
    * @return array    
    */
    protected function mkarr( $badge, $first, $last, $department = null, $office = null, $ext = null, $modify_tm = null ) {
        return array(
            'badge' => $badge,
            'first' => $first,
            'last' => $last,
            'department' => $department,
            'office' => $office,
            'ext' => $ext,
            'modify_tm' => $modify_tm
        );
    }

    /**
    * Returns data row as object (because I'm really lazy.)
    * 
    * @param int $badge
    * @param string $first
    * @param string $last
    * @param [string] $department
    * @param [int] $office
    * @param [int] $ext
    * @param [string] $modify_tm
    * @return array    
    */
    protected function mkobj( $badge, $first, $last, $department = null, $office = null, $ext = null, $modify_tm = null ) {
        return (object) $this->mkarr( $badge, $first, $last, $department, $office, $ext, $modify_tm );
    }

    public function testSomething() {
        // TODO: Your test

        // TODO: Assign actual dataset to $actual

        // Expected data set
        $tables = array( 
            'people' => array( 'badge', 'first', 'last', 'department', 'office', 'ext', 'modify_tm' ) 
            );
        $data = array(
            'people' => array(
                $this->mkobj( '100', 'Alexis', 'Carpenter', 'Payroll', 2, 632, '2011-01-01 03:34:30' ),
                $this->mkobj( '101', 'Rudyard', 'Harrell', 'Customer Relations', 6, 288, '2011-01-11 17:45:31' ),
                $this->mkobj( '102', 'Ifeoma', 'Keeper', 'Legal Department', 22, 999, '2011-01-12 16:05:24' ),
                $this->mkobj( '103', 'Hammett', 'Massey', 'Public Relations', 22, 599, '2011-01-02 16:16:24' )
            )
        );
        $expected = new PHPUnit_Extensions_Database_DataSet_ArrayDataSet( $tables, $data );

        $this->assertTablesEqual( $expected->getTable( 'people' ), $actual->getTable( 'people' ) );
    }

}
?>

The class file. I've named mine ArrayDataSet.php and dropped it in $PHPUNIT/Extensions/Database/DataSet/
0 ) { foreach( $tables as $table_name => $table_columns ) { if( is_array( $table_columns ) === false || count( $table_columns ) === 0 ) { throw new Exception( 'No columns specified for table: ' . $table_name ); } if( is_array( $primary_keys ) && array_key_exists( $table_name, $primary_keys ) ) { if( is_array( $primary_keys[ $table_name ] ) ) { $meta = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( $table_name, $table_columns, $primary_keys[ $table_name ] ); } else { throw new Exception( 'Primary key for table is not an array; table name is: ' . $table_name ); } } else { $meta = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( $table_name, $table_columns ); } $table = new PHPUnit_Extensions_Database_DataSet_DefaultTable( $meta ); if( is_array( $data ) && array_key_exists( $table_name, $data ) && is_array( $data[ $table_name ] ) ) { foreach( $data[ $table_name ] as $row ) { if( is_object( $row ) ) { $row = (array)$row; } else if( is_array( $row ) === false ) { throw new Exception( 'Table row is not an array or object; table name is: ' . $table_name ); } $table->addRow( $row ); } $this->addTable( $table ); } else { throw new Exception( 'Table data is not an array for table: ' . $table_name ); } } } } } ?>

Throw more specific exceptions

DbUnit throws Exception objects in quite a few of places where more specific exception objects should be thrown. This is especially a problem with DbUnit's test suite as tests must no longer expect an exception of the Exception type.

Oracle error when DBUnit read the metadatas of a table prefixed by a schema

Hi,

When I use a xml file as initialization dataset with tables names prefixed by the schema, there is an Oracle error when accessing to the metadata tables :
ORA-00904: "OWNER": invalid identifier: SELECT DISTINCT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME='TEST_PDO' AND OWNER = 'DENIS' ORDER BY COLUMN_NAME

The bug is coming from the class PHPUnit_Extensions_Database_DB_MetaData_Oci which is using the table USER_TAB_COLUMNS the get the columns of a table BUT there is no column OWNER in this table because it shows only the table columns the current user owns. Instead of this table, you should use the table ALL_TAB_COLUMNS which shows the tables the current user is granted.
Same problem to get the primary key of a table, you must replace the user_constraints and user_cons_columns tables by all_constraints and all_cons_columns

Furthermore, in the same class, I suggest that you use the SQL command DELETE FROM instead of TRUNCATE TABLE to initialize the tables (default behavior), since Oracle requires high privileges to truncate a table. I know that TRUNCATE is faster than DELETE and reset autoincrement keys but a simple user is rarely granted TRUNCATE privileges.

My PHP version is 5.3.5 and PHPUnit version is 3.5.14.
My db server is Oracle Express 10g and I used Windows XP SP3 for the client and the server.

Test script:

class MyTest extends PHPUnit_Extensions_Database_TestCase { 
static private $pdo = null;
private $conn = null; 
protected function getConnection() {
   if ($this->conn === null) {
     if (self::$pdo == null) {
       self::$pdo = new PDO('oci://localhost/XE', 'denis', 'mypassw');
     }
     $this->conn = $this->createDefaultDBConnection(self::$pdo, 'DENIS');
   } 
  self::$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
   return $this->conn; 
} 
protected function getDataSet() {
   return $this->createFlatXMLDataSet(dirname(__FILE__).'/files/seed.xml');
 } 
public function testDummy () {}
 } 

My xml file dataset seed.xml (replace table prefix by your schema) :

<?xml version="1.0" encoding="UTF-8"?>
 <dataset>
       <DENIS.TEST_PDO ID="1" VALUE="eviter les caracteres accentues" QTY="421.35" />
      <DENIS.TEST_PDO ID="2" VALUE="libelle sans accents" QTY="-17.85" />
 </dataset>

The SQL to create the test table :

CREATE TABLE "TEST_PDO"
 ( "ID" NUMBER, 
  "VALUE" VARCHAR2(250),
 "QTY" NUMBER, 
CONSTRAINT "TEST_PDO_PK" PRIMARY KEY ("ID") ENABLE )

Best Regards,

LoadSchemaFromFile method

It would be great to have a method to create database schema from a file or maybe with a string ...

$this->createSchemaFromFile('schema.sql');

Thanks.

Bug - database schema not working as expected

PHPUnit 3.5.7 by Sebastian Bergmann.
Ubuntu 9.04
PostgreSQL 8.3

class PDO_PgSql_BulkImporterTest extends PHPUnit_Extensions_Database_TestCase {
    protected function getConnection() {
        return $this->createDefaultDBConnection( new PDO('...'), 'baf' );
    }

    protected function getDataSet() {
        return new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet( 'myxmlfile.xml' );
    }

    protected function testSomething() {
        //
        // do something that manipulates data in table
        //

        // Expected data set
        $set = $this->createXMLDataSet( 'myexpected.xml' );

        // FAIL:
        // PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR:  relation "people" does not exist
        // The schema "baf" was not prefixed to the table by PHPUnit as I would expect
        $this->assertTablesEqual( $set->getTable( 'people' ), $this->getConnection()->createDataSet()->getTable( 'people' ) );

        // FAIL:
        // InvalidArgumentException: baf.people is not a table in the current database.
        // PHPUnit beleves the table does not exist before issuing statements to the database
        $this->assertTablesEqual( $set->getTable( 'people' ), $this->getConnection()->createDataSet()->getTable( 'baf.people' ) );
    }
}

Fixed by modifying PHPUnit_Extensions_Database_DB_DataSet::buildTableSelect()

Change lines 103 to 107 from:
if ($databaseConnection) {
$tableName = $databaseConnection->quoteSchemaObject($tableMetaData->getTableName());
} else {
$tableName = $tableMetaData->getTableName();
}

to:
if ($databaseConnection) {
$tableName = $databaseConnection->quoteSchemaObject($tableMetaData->getTableName());
$schemaName = $databaseConnection->quoteSchemaObject($databaseConnection->getMetaData()->getSchema()) . '.';
} else {
$tableName = $tableMetaData->getTableName();
$schemaName = '';
}

Change return statement from:
return "SELECT {$columnList} FROM {$tableName} {$orderBy}";

to:
return "SELECT {$columnList} FROM {$schemaName}{$tableName} {$orderBy}";

I then tested my change without using a schema. PHPUnit picked up the "public" schema automatically and worked as expected.

Boolean values are interpreted wrong for insertion

We are using PHPUnit with dbunit and beberlei's DoctrineExtensions for testing against a PostgreSQL database.

Today we spotted an error that occurs after trying to load a fixture which contains a boolean false value like in the following YAML fixture:

system_user:
 -
  id: 1
  is_active: false

This is the database exception: [SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type boolean: ""]

Interestingly this only happens when trying to insert 'false' but inserting 'true' works.

The exception is thrown during the setup phase while executing the insertion operation (PHPUnit_Extensions_Database_Operation_Insert). During investigation I've found that buildOperationArguments, which builds the arguments array for the query, calls $table->getValue(). This method converts the field values explicitly to strings. This means a bool(true) becomes string("1") and a bool(false) becomes string("") and leads to the exception because the database is able to interpret the "1" as a boolean value but it fails with the empty string which is interpreted as a NULL value.

Improperly formatted XML files trigger unhelpful error.

Version: PHPUnit 3.7.9
Copied from PHPUnit Issue #712 (as requested):

When using createXMLDataSet with an XML file that is not properly formatted, I get the following error message:

Fatal error: Call to a member function passed() on a non-object in /usr/share/php/PHPUnit/Framework/TestCase.php on line 1745

Call Stack:
0.0002 637768 1. {main}() /usr/bin/phpunit:0
0.0026 1272888 2. PHPUnit_TextUI_Command::main() /usr/bin/phpunit:46
0.0026 1273904 3. PHPUnit_TextUI_Command->run() /usr/share/php/PHPUnit/TextUI/Command.php:129
0.7654 91606968 4. PHPUnit_TextUI_TestRunner->doRun() /usr/share/php/PHPUnit/TextUI/Command.php:176
0.7669 91901832 5. PHPUnit_Framework_TestSuite->run() /usr/share/php/PHPUnit/TextUI/TestRunner.php:346
44.0137 103141872 6. PHPUnit_Framework_TestSuite->run() /usr/share/php/PHPUnit/Framework/TestSuite.php:705
44.0138 103142464 7. PHPUnit_Framework_TestSuite->runTest() /usr/share/php/PHPUnit/Framework/TestSuite.php:745
44.0138 103142464 8. PHPUnit_Framework_TestCase->run() /usr/share/php/PHPUnit/Framework/TestSuite.php:775
44.0138 103142464 9. PHPUnit_Framework_TestCase->handleDependencies() /usr/share/php/PHPUnit/Framework/TestCase.php:695

It appears that "$this->result" is not set on line 1745 of the TestCase.php file. The error is possibly because the lines before 695 in the run function do not actually use the class property or alternatively do not pass their result into "handleDependencies".

TRUNCATE compatibility

The default $truncateCommand of PHPUnit_Extensions_Database_DB_MetaData would be compatible with more systems if it were changed to 'TRUNCATE TABLE'.

Troels Arvin maintains a decent comparison of different SQL implementations, and I've included links to the documentation for systems I've used:

YamlDataSet does not respect empty tables

A YAML data set file with a table_name: followed by no rows should be treated like an empty table so that TRUNCATE, DELETE, DELETE_ALL, and CLEAN_INSERT can clear out that table on setUp() and tearDown() operations.

Looks like deleting lines 89-91 in the YamlDataSet should do it:
if (!is_array($rows)) {
continue;
}

As sfYaml seems to not return an empty array, and the remainder of the addYamlFile() seems to safely handle the case where $rows is not set when determining column names.

Sorted Dataset

Create a sorted dataset to allow for comparing datasets without considering order of data.

Feature Request - PHPUnit_Extensions_Database_TestCase::assertTablesEqual()

This is a request to add an optional parameter to this function that is an array of column names to ignore in the comparison.

  1. When testing inserts into a table with an auto-generating unique ID I don't really care what the assigned ID is in the table when asserting that the operation was successful. I assume the database performs this function correctly and I am only interested in knowing if the columns I care about were inserted correctly.

  2. If I have a table with many columns and am testing an operation that affects only a few of them, then I don't care what happens in the other columns.

Ideally any columns ignored would also not need to be present in the data set passed as expected. If my table has columns A through J and I am testing something which affects A through C, then I would want to include only columns A through C in my expected data set.

I see this feature as a time saving device for the tester. I can easily work around the lack of this feature by:

  1. Resetting the auto-generating ID to 1 in the setUp() or tearDown() methods of my test class.
  2. Copying from the test table into a temporary table and doing the assertTablesEqual there (assuming DBUnit will pick up the newly created table).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.