propel library added to 3rd party php tools

This commit is contained in:
naomiaro 2010-11-04 17:47:31 -04:00
parent fe5337e9db
commit 649656779c
415 changed files with 109614 additions and 0 deletions

View file

@ -0,0 +1,70 @@
<?php
/*
* $Id: AutoAddPkBehaviorTest.php 1612 2010-03-16 22:56:21Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests for AutoAddPkBehavior class
*
* @author François Zaninotto
* @version $Revision: 1612 $
* @package generator.behavior
*/
class AutoAddPkBehaviorTest extends BookstoreTestBase
{
public function testDefault()
{
$table6 = Table6Peer::getTableMap();
$this->assertEquals(count($table6->getColumns()), 2, 'auto_add_pk adds one column by default');
$pks = $table6->getPrimaryKeys();
$this->assertEquals(count($pks), 1, 'auto_add_pk adds a simple primary key by default');
$pk = array_pop($pks);
$this->assertEquals($pk->getName(), 'ID', 'auto_add_pk adds an id column by default');
$this->assertEquals($pk->getType(), 'INTEGER', 'auto_add_pk adds an integer column by default');
$this->assertTrue($pk->isPrimaryKey(), 'auto_add_pk adds a primary key column by default');
$this->assertTrue($table6->isUseIdGenerator(), 'auto_add_pk adds an autoIncrement column by default');
}
public function testNoTrigger()
{
$table7 = Table7Peer::getTableMap();
$this->assertEquals(count($table7->getColumns()), 2, 'auto_add_pk does not add a column when the table already has a primary key');
$this->assertFalse(method_exists('Table7', 'getId'), 'auto_add_pk does not add an id column when the table already has a primary key');
$pks = $table7->getPrimaryKeys();
$pk = array_pop($pks);
$this->assertEquals($pk->getName(), 'FOO', 'auto_add_pk does not change an existing primary key');
}
public function testParameters()
{
$table8 = Table8Peer::getTableMap();
$this->assertEquals(count($table8->getColumns()), 3, 'auto_add_pk adds one column with custom parameters');
$pks = $table8->getPrimaryKeys();
$pk = array_pop($pks);
$this->assertEquals($pk->getName(), 'IDENTIFIER', 'auto_add_pk accepts customization of pk column name');
$this->assertEquals($pk->getType(), 'BIGINT', 'auto_add_pk accepts customization of pk column type');
$this->assertTrue($pk->isPrimaryKey(), 'auto_add_pk adds a primary key column with custom parameters');
$this->assertFalse($table8->isUseIdGenerator(), 'auto_add_pk accepts customization of pk column autoIncrement');
}
public function testForeignKey()
{
$t6 = new Table6();
$t6->setTitle('foo');
$t6->save();
$t8 = new Table8();
$t8->setIdentifier(1);
$t8->setTable6($t6);
$t8->save();
$this->assertEquals($t8->getFooId(), $t6->getId(), 'Auto added pkeys can be used in relations');
$t8->delete();
$t6->delete();
}
}

View file

@ -0,0 +1,152 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests the generated Object behavior hooks.
*
* @author Francois Zaninotto
* @package generator.behavior
*/
class ObjectBehaviorTest extends BookstoreTestBase
{
public function testObjectAttributes()
{
$t = new Table3();
$this->assertEquals($t->customAttribute, 1, 'objectAttributes hook is called when adding attributes');
}
public function testPreSave()
{
$t = new Table3();
$t->preSave = 0;
$t->save();
$this->assertEquals($t->preSave, 1, 'preSave hook is called on object insertion');
$this->assertEquals($t->preSaveBuilder, 'PHP5ObjectBuilder', 'preSave hook is called with the object builder as parameter');
$this->assertFalse($t->preSaveIsAfterSave, 'preSave hook is called before save');
$t->preSave = 0;
$t->setTitle('foo');
$t->save();
$this->assertEquals($t->preSave, 1, 'preSave hook is called on object modification');
}
public function testPostSave()
{
$t = new Table3();
$t->postSave = 0;
$t->save();
$this->assertEquals($t->postSave, 1, 'postSave hook is called on object insertion');
$this->assertEquals($t->postSaveBuilder, 'PHP5ObjectBuilder', 'postSave hook is called with the object builder as parameter');
$this->assertTrue($t->postSaveIsAfterSave, 'postSave hook is called after save');
$t->postSave = 0;
$t->setTitle('foo');
$t->save();
$this->assertEquals($t->postSave, 1, 'postSave hook is called on object modification');
}
public function testPreInsert()
{
$t = new Table3();
$t->preInsert = 0;
$t->save();
$this->assertEquals($t->preInsert, 1, 'preInsert hook is called on object insertion');
$this->assertEquals($t->preInsertBuilder, 'PHP5ObjectBuilder', 'preInsert hook is called with the object builder as parameter');
$this->assertFalse($t->preInsertIsAfterSave, 'preInsert hook is called before save');
$t->preInsert = 0;
$t->setTitle('foo');
$t->save();
$this->assertEquals($t->preInsert, 0, 'preInsert hook is not called on object modification');
}
public function testPostInsert()
{
$t = new Table3();
$t->postInsert = 0;
$t->save();
$this->assertEquals($t->postInsert, 1, 'postInsert hook is called on object insertion');
$this->assertEquals($t->postInsertBuilder, 'PHP5ObjectBuilder', 'postInsert hook is called with the object builder as parameter');
$this->assertTrue($t->postInsertIsAfterSave, 'postInsert hook is called after save');
$t->postInsert = 0;
$t->setTitle('foo');
$t->save();
$this->assertEquals($t->postInsert, 0, 'postInsert hook is not called on object modification');
}
public function testPreUpdate()
{
$t = new Table3();
$t->preUpdate = 0;
$t->save();
$this->assertEquals($t->preUpdate, 0, 'preUpdate hook is not called on object insertion');
$t->preUpdate = 0;
$t->setTitle('foo');
$t->save();
$this->assertEquals($t->preUpdate, 1, 'preUpdate hook is called on object modification');
$this->assertEquals($t->preUpdateBuilder, 'PHP5ObjectBuilder', 'preUpdate hook is called with the object builder as parameter');
$this->assertFalse($t->preUpdateIsAfterSave, 'preUpdate hook is called before save');
}
public function testPostUpdate()
{
$t = new Table3();
$t->postUpdate = 0;
$t->save();
$this->assertEquals($t->postUpdate, 0, 'postUpdate hook is not called on object insertion');
$t->postUpdate = 0;
$t->setTitle('foo');
$t->save();
$this->assertEquals($t->postUpdate, 1, 'postUpdate hook is called on object modification');
$this->assertEquals($t->postUpdateBuilder, 'PHP5ObjectBuilder', 'postUpdate hook is called with the object builder as parameter');
$this->assertTrue($t->postUpdateIsAfterSave, 'postUpdate hook is called after save');
}
public function testPreDelete()
{
$t = new Table3();
$t->save();
$this->preDelete = 0;
$t->delete();
$this->assertEquals($t->preDelete, 1, 'preDelete hook is called on object deletion');
$this->assertEquals($t->preDeleteBuilder, 'PHP5ObjectBuilder', 'preDelete hook is called with the object builder as parameter');
$this->assertTrue($t->preDeleteIsBeforeDelete, 'preDelete hook is called before deletion');
}
public function testPostDelete()
{
$t = new Table3();
$t->save();
$this->postDelete = 0;
$t->delete();
$this->assertEquals($t->postDelete, 1, 'postDelete hook is called on object deletion');
$this->assertEquals($t->postDeleteBuilder, 'PHP5ObjectBuilder', 'postDelete hook is called with the object builder as parameter');
$this->assertFalse($t->postDeleteIsBeforeDelete, 'postDelete hook is called before deletion');
}
public function testObjectMethods()
{
$t = new Table3();
$this->assertTrue(method_exists($t, 'hello'), 'objectMethods hook is called when adding methods');
$this->assertEquals($t->hello(), 'PHP5ObjectBuilder', 'objectMethods hook is called with the object builder as parameter');
}
public function testObjectCall()
{
$t = new Table3();
$this->assertEquals('bar', $t->foo(), 'objectCall hook is called when building the magic __call()');
}
public function testObjectFilter()
{
$t = new Table3();
$this->assertTrue(class_exists('testObjectFilter'), 'objectFilter hook allows complete manipulation of the generated script');
$this->assertEquals(testObjectFilter::FOO, 'PHP5ObjectBuilder', 'objectFilter hook is called with the object builder as parameter');
}
}

View file

@ -0,0 +1,61 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests the generated Peer behavior hooks.
*
* @author Francois Zaninotto
* @package generator.behavior
*/
class PeerBehaviorTest extends BookstoreTestBase
{
public function testStaticAttributes()
{
$this->assertEquals(Table3Peer::$customStaticAttribute, 1, 'staticAttributes hook is called when adding attributes');
$this->assertEquals(Table3Peer::$staticAttributeBuilder, 'PHP5PeerBuilder', 'staticAttributes hook is called with the peer builder as parameter');
}
public function testStaticMethods()
{
$this->assertTrue(method_exists('Table3Peer', 'hello'), 'staticMethods hook is called when adding methods');
$this->assertEquals(Table3Peer::hello(), 'PHP5PeerBuilder', 'staticMethods hook is called with the peer builder as parameter');
}
public function testPreSelect()
{
$con = Propel::getConnection(Table3Peer::DATABASE_NAME, Propel::CONNECTION_READ);
$con->preSelect = 0;
Table3Peer::doSelect(new Criteria, $con);
$this->assertNotEquals($con->preSelect, 0, 'preSelect hook is called in doSelect()');
$con->preSelect = 0;
Table3Peer::doSelectOne(new Criteria, $con);
$this->assertNotEquals($con->preSelect, 0, 'preSelect hook is called in doSelectOne()');
$con->preSelect = 0;
Table3Peer::doCount(new Criteria, $con);
$this->assertNotEquals($con->preSelect, 0, 'preSelect hook is called in doCount()');
$con->preSelect = 0;
Table3Peer::doSelectStmt(new Criteria, $con);
$this->assertNotEquals($con->preSelect, 0, 'preSelect hook is called in doSelectStmt()');
// and for the doSelectJoin and doCountJoin methods, well just believe my word
$con->preSelect = 0;
Table3Peer::doSelect(new Criteria, $con);
$this->assertEquals($con->preSelect, 'PHP5PeerBuilder', 'preSelect hook is called with the peer builder as parameter');
}
public function testPeerFilter()
{
Table3Peer::TABLE_NAME;
$this->assertTrue(class_exists('testPeerFilter'), 'peerFilter hook allows complete manipulation of the generated script');
$this->assertEquals(testPeerFilter::FOO, 'PHP5PeerBuilder', 'peerFilter hook is called with the peer builder as parameter');
}
}

View file

@ -0,0 +1,360 @@
<?php
/*
* $Id: SoftDeleteBehaviorTest.php 1806 2010-06-17 10:37:11Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests for SoftDeleteBehavior class
*
* @author François Zaninotto
* @version $Revision: 1806 $
* @package generator.behavior
*/
class SoftDeleteBehaviorTest extends BookstoreTestBase
{
protected function setUp()
{
parent::setUp();
Table4Peer::disableSoftDelete();
Table4Peer::doDeleteAll();
Table4Peer::enableSoftDelete();
}
public function testParameters()
{
$table2 = Table4Peer::getTableMap();
$this->assertEquals(count($table2->getColumns()), 3, 'SoftDelete adds one columns by default');
$this->assertTrue(method_exists('Table4', 'getDeletedAt'), 'SoftDelete adds an updated_at column by default');
$table1 = Table5Peer::getTableMap();
$this->assertEquals(count($table1->getColumns()), 3, 'SoftDelete does not add a column when it already exists');
$this->assertTrue(method_exists('Table5', 'getDeletedOn'), 'SoftDelete allows customization of deleted_column name');
}
public function testStaticSoftDeleteStatus()
{
$this->assertTrue(Table4Peer::isSoftDeleteEnabled(), 'The static soft delete is enabled by default');
Table4Peer::disableSoftDelete();
$this->assertFalse(Table4Peer::isSoftDeleteEnabled(), 'disableSoftDelete() disables the static soft delete');
Table4Peer::enableSoftDelete();
$this->assertTrue(Table4Peer::isSoftDeleteEnabled(), 'enableSoftDelete() enables the static soft delete');
}
public function testInstancePoolingAndSoftDelete()
{
Table4Peer::doForceDeleteAll($this->con);
$t = new Table4();
$t->save($this->con);
Table4Peer::enableSoftDelete();
$t->delete($this->con);
$t2 = Table4Peer::retrieveByPk($t->getPrimaryKey(), $this->con);
$this->assertNull($t2, 'An object is removed from the instance pool on soft deletion');
Table4Peer::disableSoftDelete();
$t2 = Table4Peer::retrieveByPk($t->getPrimaryKey(), $this->con);
$this->assertNotNull($t2);
Table4Peer::enableSoftDelete();
$t2 = Table4Peer::retrieveByPk($t->getPrimaryKey(), $this->con);
$this->assertNull($t2, 'A soft deleted object is removed from the instance pool when the soft delete behavior is enabled');
}
public function testStaticDoForceDelete()
{
$t1 = new Table4();
$t1->save();
Table4Peer::doForceDelete($t1);
Table4Peer::disableSoftDelete();
$this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doForceDelete() actually deletes records');
}
public function testStaticDoSoftDelete()
{
$t1 = new Table4();
$t1->save();
$t2 = new Table4();
$t2->save();
$t3 = new Table4();
$t3->save();
// softDelete with a criteria
$c = new Criteria();
$c->add(Table4Peer::ID, $t1->getId());
Table4Peer::doSoftDelete($c);
Table4Peer::disableSoftDelete();
$this->assertEquals(3, Table4Peer::doCount(new Criteria()), 'doSoftDelete() keeps deleted record in the database');
Table4Peer::enableSoftDelete();
$this->assertEquals(2, Table4Peer::doCount(new Criteria()), 'doSoftDelete() marks deleted record as deleted');
// softDelete with a value
Table4Peer::doSoftDelete(array($t2->getId()));
Table4Peer::disableSoftDelete();
$this->assertEquals(3, Table4Peer::doCount(new Criteria()), 'doSoftDelete() keeps deleted record in the database');
Table4Peer::enableSoftDelete();
$this->assertEquals(1, Table4Peer::doCount(new Criteria()), 'doSoftDelete() marks deleted record as deleted');
// softDelete with an object
Table4Peer::doSoftDelete($t3);
Table4Peer::disableSoftDelete();
$this->assertEquals(3, Table4Peer::doCount(new Criteria()), 'doSoftDelete() keeps deleted record in the database');
Table4Peer::enableSoftDelete();
$this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doSoftDelete() marks deleted record as deleted');
}
public function testStaticDoDelete()
{
$t1 = new Table4();
$t1->save();
$t2 = new Table4();
$t2->save();
Table4Peer::disableSoftDelete();
Table4Peer::doDelete($t1);
Table4Peer::disableSoftDelete();
$this->assertEquals(1, Table4Peer::doCount(new Criteria()), 'doDelete() calls doForceDelete() when soft delete is disabled');
Table4Peer::enableSoftDelete();
Table4Peer::doDelete($t2);
Table4Peer::disableSoftDelete();
$this->assertEquals(1, Table4Peer::doCount(new Criteria()), 'doDelete() calls doSoftDelete() when soft delete is enabled');
Table4Peer::enableSoftDelete();
$this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doDelete() calls doSoftDelete() when soft delete is enabled');
}
public function testStaticDoForceDeleteAll()
{
$t1 = new Table4();
$t1->save();
Table4Peer::doForceDeleteAll();
Table4Peer::disableSoftDelete();
$this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doForceDeleteAll() actually deletes records');
}
public function testStaticDoSoftDeleteAll()
{
$t1 = new Table4();
$t1->save();
$t2 = new Table4();
$t2->save();
Table4Peer::enableSoftDelete();
Table4Peer::doSoftDeleteAll();
Table4Peer::disableSoftDelete();
$this->assertEquals(2, Table4Peer::doCount(new Criteria()), 'doSoftDeleteAll() keeps deleted record in the database');
Table4Peer::enableSoftDelete();
$this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doSoftDeleteAll() marks deleted record as deleted');
}
public function testStaticDoDeleteAll()
{
$t1 = new Table4();
$t1->save();
$t2 = new Table4();
$t2->save();
Table4Peer::disableSoftDelete();
Table4Peer::doDeleteAll();
Table4Peer::disableSoftDelete();
$this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doDeleteAll() calls doForceDeleteAll() when soft delete is disabled');
$t1 = new Table4();
$t1->save();
$t2 = new Table4();
$t2->save();
Table4Peer::enableSoftDelete();
Table4Peer::doDeleteAll();
Table4Peer::disableSoftDelete();
$this->assertEquals(2, Table4Peer::doCount(new Criteria()), 'doDeleteAll() calls doSoftDeleteAll() when soft delete is disabled');
Table4Peer::enableSoftDelete();
$this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doDeleteAll() calls doSoftDeleteAll() when soft delete is disabled');
}
public function testSelect()
{
$t = new Table4();
$t->setDeletedAt(123);
$t->save();
Table4Peer::enableSoftDelete();
$this->assertEquals(0, Table4Peer::doCount(new Criteria), 'rows with a deleted_at date are hidden for select queries');
Table4Peer::disableSoftDelete();
$this->assertEquals(1, Table4Peer::doCount(new Criteria), 'rows with a deleted_at date are visible for select queries once the static soft_delete is enabled');
$this->assertTrue(Table4Peer::isSoftDeleteEnabled(), 'Executing a select query enables the static soft delete again');
}
public function testDelete()
{
$t = new Table4();
$t->save();
$this->assertNull($t->getDeletedAt(), 'deleted_column is null by default');
$t->delete();
$this->assertNotNull($t->getDeletedAt(), 'deleted_column is not null after a soft delete');
$this->assertEquals(0, Table4Peer::doCount(new Criteria), 'soft deleted rows are hidden for select queries');
Table4Peer::disableSoftDelete();
$this->assertEquals(1, Table4Peer::doCount(new Criteria), 'soft deleted rows are still present in the database');
}
public function testDeleteUndeletable()
{
$t = new UndeletableTable4();
$t->save();
$t->delete();
$this->assertNull($t->getDeletedAt(), 'soft_delete is not triggered for objects wit ha preDelete hook returning false');
$this->assertEquals(1, Table4Peer::doCount(new Criteria), 'soft_delete is not triggered for objects wit ha preDelete hook returning false');
}
public function testUnDelete()
{
$t = new Table4();
$t->save();
$t->delete();
$t->undelete();
$this->assertNull($t->getDeletedAt(), 'deleted_column is null again after an undelete');
$this->assertEquals(1, Table4Peer::doCount(new Criteria), 'undeleted rows are visible for select queries');
}
public function testForceDelete()
{
$t = new Table4();
$t->save();
$t->forceDelete();
$this->assertTrue($t->isDeleted(), 'forceDelete() actually deletes a row');
Table4Peer::disableSoftDelete();
$this->assertEquals(0, Table4Peer::doCount(new Criteria), 'forced deleted rows are not present in the database');
}
public function testQueryIncludeDeleted()
{
$t = new Table4();
$t->setDeletedAt(123);
$t->save();
Table4Peer::enableSoftDelete();
$this->assertEquals(0, Table4Query::create()->count(), 'rows with a deleted_at date are hidden for select queries');
$this->assertEquals(1, Table4Query::create()->includeDeleted()->count(), 'rows with a deleted_at date are visible for select queries using includeDeleted()');
}
public function testQueryForceDelete()
{
$t1 = new Table4();
$t1->save();
Table4Query::create()->filterById($t1->getId())->forceDelete();
Table4Peer::disableSoftDelete();
$this->assertEquals(0, Table4Query::create()->count(), 'forceDelete() actually deletes records');
}
public function testQuerySoftDelete()
{
$t1 = new Table4();
$t1->save();
$t2 = new Table4();
$t2->save();
$t3 = new Table4();
$t3->save();
Table4Query::create()
->filterById($t1->getId())
->softDelete();
Table4Peer::disableSoftDelete();
$this->assertEquals(3, Table4Query::create()->count(), 'softDelete() keeps deleted record in the database');
Table4Peer::enableSoftDelete();
$this->assertEquals(2, Table4Query::create()->count(), 'softDelete() marks deleted record as deleted');
}
public function testQueryDelete()
{
$t1 = new Table4();
$t1->save();
$t2 = new Table4();
$t2->save();
Table4Peer::disableSoftDelete();
Table4Query::create()->filterById($t1->getId())->delete();
Table4Peer::disableSoftDelete();
$this->assertEquals(1, Table4Query::create()->count(), 'delete() calls forceDelete() when soft delete is disabled');
Table4Peer::enableSoftDelete();
Table4Query::create()->filterById($t2->getId())->delete();
Table4Peer::disableSoftDelete();
$this->assertEquals(1, Table4Query::create()->count(), 'delete() calls softDelete() when soft delete is enabled');
Table4Peer::enableSoftDelete();
$this->assertEquals(0, Table4Query::create()->count(), 'delete() calls softDelete() when soft delete is enabled');
}
public function testQueryForceDeleteAll()
{
$t1 = new Table4();
$t1->save();
Table4Query::create()->forceDeleteAll();
Table4Peer::disableSoftDelete();
$this->assertEquals(0, Table4Query::create()->count(), 'forceDeleteAll() actually deletes records');
}
public function testQuerySoftDeleteAll()
{
$t1 = new Table4();
$t1->save();
$t2 = new Table4();
$t2->save();
Table4Peer::enableSoftDelete();
Table4Query::create()->softDelete();
Table4Peer::disableSoftDelete();
$this->assertEquals(2, Table4Query::create()->count(), 'softDelete() keeps deleted record in the database');
Table4Peer::enableSoftDelete();
$this->assertEquals(0, Table4Query::create()->count(), 'softDelete() marks deleted record as deleted');
}
public function testQueryDeleteAll()
{
$t1 = new Table4();
$t1->save();
$t2 = new Table4();
$t2->save();
Table4Peer::disableSoftDelete();
Table4Query::create()->deleteAll();
Table4Peer::disableSoftDelete();
$this->assertEquals(0, Table4Query::create()->count(), 'deleteAll() calls forceDeleteAll() when soft delete is disabled');
$t1 = new Table4();
$t1->save();
$t2 = new Table4();
$t2->save();
Table4Peer::enableSoftDelete();
Table4Query::create()->deleteAll();
Table4Peer::disableSoftDelete();
$this->assertEquals(2, Table4Query::create()->count(), 'deleteAll() calls softDeleteAll() when soft delete is disabled');
Table4Peer::enableSoftDelete();
$this->assertEquals(0, Table4Query::create()->count(), 'deleteAll() calls softDeleteAll() when soft delete is disabled');
}
public function testQuerySelect()
{
$t = new Table4();
$t->setDeletedAt(123);
$t->save();
Table4Peer::enableSoftDelete();
$this->assertEquals(0, Table4Query::create()->count(), 'rows with a deleted_at date are hidden for select queries');
Table4Peer::disableSoftDelete();
$this->assertEquals(1, Table4Query::create()->count(), 'rows with a deleted_at date are visible for select queries once the static soft_delete is enabled');
$this->assertTrue(Table4Peer::isSoftDeleteEnabled(), 'Executing a select query enables the static soft delete again');
}
public function testCustomization()
{
Table5Peer::disableSoftDelete();
Table5Peer::doDeleteAll();
Table5Peer::enableSoftDelete();
$t = new Table5();
$t->save();
$this->assertNull($t->getDeletedOn(), 'deleted_column is null by default');
$t->delete();
$this->assertNotNull($t->getDeletedOn(), 'deleted_column is not null after a soft delete');
$this->assertEquals(0, Table5Peer::doCount(new Criteria), 'soft deleted rows are hidden for select queries');
Table5Peer::disableSoftDelete();
$this->assertEquals(1, Table5Peer::doCount(new Criteria), 'soft deleted rows are still present in the database');
}
}
class UndeletableTable4 extends Table4
{
public function preDelete(PropelPDO $con = null)
{
parent::preDelete($con);
$this->setTitle('foo');
return false;
}
}

View file

@ -0,0 +1,34 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
/**
* Tests the table structure behavior hooks.
*
* @author Francois Zaninotto
* @package generator.behavior
*/
class TableBehaviorTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
parent::setUp();
set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes");
require_once 'behavior/alternative_coding_standards/map/Table3TableMap.php';
require_once 'behavior/alternative_coding_standards/Table3Peer.php';
}
public function testModifyTable()
{
$t = Table3Peer::getTableMap();
$this->assertTrue($t->hasColumn('test'), 'modifyTable hook is called when building the model structure');
}
}

View file

@ -0,0 +1,215 @@
<?php
/*
* $Id: TimestampableBehaviorTest.php 1683 2010-04-16 20:36:38Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests for TimestampableBehavior class
*
* @author François Zaninotto
* @version $Revision: 1683 $
* @package generator.behavior
*/
class TimestampableBehaviorTest extends BookstoreTestBase
{
public function testParameters()
{
$table2 = Table2Peer::getTableMap();
$this->assertEquals(count($table2->getColumns()), 4, 'Timestampable adds two columns by default');
$this->assertTrue(method_exists('Table2', 'getCreatedAt'), 'Timestamplable adds a created_at column by default');
$this->assertTrue(method_exists('Table2', 'getUpdatedAt'), 'Timestamplable adds an updated_at column by default');
$table1 = Table1Peer::getTableMap();
$this->assertEquals(count($table1->getColumns()), 4, 'Timestampable does not add two columns when they already exist');
$this->assertTrue(method_exists('Table1', 'getCreatedOn'), 'Timestamplable allows customization of create_column name');
$this->assertTrue(method_exists('Table1', 'getUpdatedOn'), 'Timestamplable allows customization of update_column name');
}
public function testPreSave()
{
$t1 = new Table2();
$this->assertNull($t1->getUpdatedAt());
$tsave = time();
$t1->save();
$this->assertEquals($t1->getUpdatedAt('U'), $tsave, 'Timestampable sets updated_column to time() on creation');
sleep(1);
$t1->setTitle('foo');
$tupdate = time();
$t1->save();
$this->assertEquals($t1->getUpdatedAt('U'), $tupdate, 'Timestampable changes updated_column to time() on update');
}
public function testPreSaveNoChange()
{
$t1 = new Table2();
$this->assertNull($t1->getUpdatedAt());
$tsave = time();
$t1->save();
$this->assertEquals($t1->getUpdatedAt('U'), $tsave, 'Timestampable sets updated_column to time() on creation');
sleep(1);
$tupdate = time();
$t1->save();
$this->assertEquals($t1->getUpdatedAt('U'), $tsave, 'Timestampable only changes updated_column if the object was modified');
}
public function testPreSaveManuallyUpdated()
{
$t1 = new Table2();
$t1->setUpdatedAt(time() - 10);
$tsave = time();
$t1->save();
$this->assertNotEquals($t1->getUpdatedAt('U'), $tsave, 'Timestampable does not set updated_column to time() on creation when it is set by the user');
// tip: if I set it to time()-10 a second time, the object sees that I want to change it to the same value
// and skips the update, therefore the updated_at is not in the list of modified columns,
// and the behavior changes it to the current date... let's say it's an edge case
$t1->setUpdatedAt(time() - 15);
$tupdate = time();
$t1->save();
$this->assertNotEquals($t1->getUpdatedAt('U'), $tupdate, 'Timestampable does not change updated_column to time() on update when it is set by the user');
}
public function testPreInsert()
{
$t1 = new Table2();
$this->assertNull($t1->getCreatedAt());
$tsave = time();
$t1->save();
$this->assertEquals($t1->getCreatedAt('U'), $tsave, 'Timestampable sets created_column to time() on creation');
sleep(1);
$t1->setTitle('foo');
$tupdate = time();
$t1->save();
$this->assertEquals($t1->getCreatedAt('U'), $tsave, 'Timestampable does not update created_column on update');
}
public function testPreInsertManuallyUpdated()
{
$t1 = new Table2();
$t1->setCreatedAt(time() - 10);
$tsave = time();
$t1->save();
$this->assertNotEquals($t1->getCreatedAt('U'), $tsave, 'Timestampable does not set created_column to time() on creation when it is set by the user');
}
public function testObjectKeepUpdateDateUnchanged()
{
$t1 = new Table2();
$t1->setUpdatedAt(time() - 10);
$tsave = time();
$t1->save();
$this->assertNotEquals($t1->getUpdatedAt('U'), $tsave);
// let's save it a second time; the updated_at should be changed
$t1->setTitle('foo');
$tsave = time();
$t1->save();
$this->assertEquals($t1->getUpdatedAt('U'), $tsave);
// now let's do this a second time
$t1 = new Table2();
$t1->setUpdatedAt(time() - 10);
$tsave = time();
$t1->save();
$this->assertNotEquals($t1->getUpdatedAt('U'), $tsave);
// let's save it a second time; the updated_at should be changed
$t1->keepUpdateDateUnchanged();
$t1->setTitle('foo');
$tsave = time();
$t1->save();
$this->assertNotEquals($t1->getUpdatedAt('U'), $tsave, 'keepUpdateDateUnchanged() prevents the behavior from updating the update date');
}
protected function populateUpdatedAt()
{
Table2Query::create()->deleteAll();
$ts = new PropelObjectCollection();
$ts->setModel('Table2');
for ($i=0; $i < 10; $i++) {
$t = new Table2();
$t->setTitle('UpdatedAt' . $i);
$t->setUpdatedAt(time() - $i * 24 * 60 * 60);
$ts[]= $t;
}
$ts->save();
}
protected function populateCreatedAt()
{
Table2Query::create()->deleteAll();
$ts = new PropelObjectCollection();
$ts->setModel('Table2');
for ($i=0; $i < 10; $i++) {
$t = new Table2();
$t->setTitle('CreatedAt' . $i);
$t->setCreatedAt(time() - $i * 24 * 60 * 60);
$ts[]= $t;
}
$ts->save();
}
public function testQueryRecentlyUpdated()
{
$q = Table2Query::create()->recentlyUpdated();
$this->assertTrue($q instanceof Table2Query, 'recentlyUpdated() returns the current Query object');
$this->populateUpdatedAt();
$ts = Table2Query::create()->recentlyUpdated()->count();
$this->assertEquals(8, $ts, 'recentlyUpdated() returns the elements updated in the last 7 days by default');
$ts = Table2Query::create()->recentlyUpdated(5)->count();
$this->assertEquals(6, $ts, 'recentlyUpdated() accepts a number of days as parameter');
}
public function testQueryRecentlyCreated()
{
$q = Table2Query::create()->recentlyCreated();
$this->assertTrue($q instanceof Table2Query, 'recentlyCreated() returns the current Query object');
$this->populateCreatedAt();
$ts = Table2Query::create()->recentlyCreated()->count();
$this->assertEquals(8, $ts, 'recentlyCreated() returns the elements created in the last 7 days by default');
$ts = Table2Query::create()->recentlyCreated(5)->count();
$this->assertEquals(6, $ts, 'recentlyCreated() accepts a number of days as parameter');
}
public function testQueryLastUpdatedFirst()
{
$q = Table2Query::create()->lastUpdatedFirst();
$this->assertTrue($q instanceof Table2Query, 'lastUpdatedFirst() returns the current Query object');
$this->populateUpdatedAt();
$t = Table2Query::create()->lastUpdatedFirst()->findOne();
$this->assertEquals('UpdatedAt0', $t->getTitle(), 'lastUpdatedFirst() returns element with most recent update date first');
}
public function testQueryFirstUpdatedFirst()
{
$q = Table2Query::create()->firstUpdatedFirst();
$this->assertTrue($q instanceof Table2Query, 'firstUpdatedFirst() returns the current Query object');
$this->populateUpdatedAt();
$t = Table2Query::create()->firstUpdatedFirst()->findOne();
$this->assertEquals('UpdatedAt9', $t->getTitle(), 'firstUpdatedFirst() returns the element with oldest updated date first');
}
public function testQueryLastCreatedFirst()
{
$q = Table2Query::create()->lastCreatedFirst();
$this->assertTrue($q instanceof Table2Query, 'lastCreatedFirst() returns the current Query object');
$this->populateCreatedAt();
$t = Table2Query::create()->lastCreatedFirst()->findOne();
$this->assertEquals('CreatedAt0', $t->getTitle(), 'lastCreatedFirst() returns element with most recent create date first');
}
public function testQueryFirstCreatedFirst()
{
$q = Table2Query::create()->firstCreatedFirst();
$this->assertTrue($q instanceof Table2Query, 'firstCreatedFirst() returns the current Query object');
$this->populateCreatedAt();
$t = Table2Query::create()->firstCreatedFirst()->findOne();
$this->assertEquals('CreatedAt9', $t->getTitle(), 'firstCreatedFirst() returns the element with oldest create date first');
}
}

View file

@ -0,0 +1,254 @@
<?php
/*
* $Id: SoftDeleteBehaviorTest.php 1612 2010-03-16 22:56:21Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests for AggregateColumnBehavior class
*
* @author François Zaninotto
* @version $Revision: 1779 $
* @package generator.behavior.aggregate_column
*/
class AggregateColumnBehaviorTest extends BookstoreTestBase
{
public function testParameters()
{
$postTable = AggregatePostPeer::getTableMap();
$this->assertEquals(count($postTable->getColumns()), 2, 'AggregateColumn adds one column by default');
$this->assertTrue(method_exists('AggregatePost', 'getNbComments'));
}
public function testCompute()
{
AggregateCommentQuery::create()->deleteAll($this->con);
AggregatePostQuery::create()->deleteAll($this->con);
$post = new AggregatePost();
$post->save($this->con);
$this->assertEquals(0, $post->computeNbComments($this->con), 'The compute method returns 0 for objects with no related objects');
$comment1 = new AggregateComment();
$comment1->setAggregatePost($post);
$comment1->save($this->con);
$this->assertEquals(1, $post->computeNbComments($this->con), 'The compute method computes the aggregate function on related objects');
$comment2 = new AggregateComment();
$comment2->setAggregatePost($post);
$comment2->save($this->con);
$this->assertEquals(2, $post->computeNbComments($this->con), 'The compute method computes the aggregate function on related objects');
$comment1->delete($this->con);
$this->assertEquals(1, $post->computeNbComments($this->con), 'The compute method computes the aggregate function on related objects');
}
public function testUpdate()
{
AggregateCommentQuery::create()->deleteAll($this->con);
AggregatePostQuery::create()->deleteAll($this->con);
$post = new AggregatePost();
$post->save($this->con);
$comment = new TestableComment();
$comment->setAggregatePost($post);
$comment->save($this->con);
$this->assertNull($post->getNbComments());
$post->updateNbComments($this->con);
$this->assertEquals(1, $post->getNbComments(), 'The update method updates the aggregate column');
$comment->delete($this->con);
$this->assertEquals(1, $post->getNbComments());
$post->updateNbComments($this->con);
$this->assertEquals(0, $post->getNbComments(), 'The update method updates the aggregate column');
}
public function testCreateRelated()
{
AggregateCommentQuery::create()->deleteAll($this->con);
AggregatePostQuery::create()->deleteAll($this->con);
$post = new AggregatePost();
$post->save($this->con);
$comment1 = new AggregateComment();
$comment1->save($this->con);
$this->assertNull($post->getNbComments(), 'Adding a new foreign object does not update the aggregate column');
$comment2 = new AggregateComment();
$comment2->setAggregatePost($post);
$comment2->save($this->con);
$this->assertEquals(1, $post->getNbComments(), 'Adding a new related object updates the aggregate column');
$comment3 = new AggregateComment();
$comment3->setAggregatePost($post);
$comment3->save($this->con);
$this->assertEquals(2, $post->getNbComments(), 'Adding a new related object updates the aggregate column');
}
public function testUpdateRelated()
{
list($poll, $item1, $item2) = $this->populatePoll();
$this->assertEquals(19, $poll->getTotalScore());
$item1->setScore(10);
$item1->save($this->con);
$this->assertEquals(17, $poll->getTotalScore(), 'Updating a related object updates the aggregate column');
}
public function testDeleteRelated()
{
list($poll, $item1, $item2) = $this->populatePoll();
$this->assertEquals(19, $poll->getTotalScore());
$item1->delete($this->con);
$this->assertEquals(7, $poll->getTotalScore(), 'Deleting a related object updates the aggregate column');
$item2->delete($this->con);
$this->assertNull($poll->getTotalScore(), 'Deleting a related object updates the aggregate column');
}
public function testUpdateRelatedWithQuery()
{
list($poll, $item1, $item2) = $this->populatePoll();
$this->assertEquals(19, $poll->getTotalScore());
AggregateItemQuery::create()
->update(array('Score' => 4), $this->con);
$this->assertEquals(8, $poll->getTotalScore(), 'Updating related objects with a query updates the aggregate column');
}
public function testUpdateRelatedWithQueryUsingAlias()
{
list($poll, $item1, $item2) = $this->populatePoll();
$this->assertEquals(19, $poll->getTotalScore());
AggregateItemQuery::create()
->setModelAlias('foo', true)
->update(array('Score' => 4), $this->con);
$this->assertEquals(8, $poll->getTotalScore(), 'Updating related objects with a query using alias updates the aggregate column');
}
public function testDeleteRelatedWithQuery()
{
list($poll, $item1, $item2) = $this->populatePoll();
$this->assertEquals(19, $poll->getTotalScore());
AggregateItemQuery::create()
->deleteAll($this->con);
$this->assertNull($poll->getTotalScore(), 'Deleting related objects with a query updates the aggregate column');
}
public function testDeleteRelatedWithQueryUsingAlias()
{
list($poll, $item1, $item2) = $this->populatePoll();
$this->assertEquals(19, $poll->getTotalScore());
AggregateItemQuery::create()
->setModelAlias('foo', true)
->filterById($item1->getId())
->delete($this->con);
$this->assertEquals(7, $poll->getTotalScore(), 'Deleting related objects with a query using alias updates the aggregate column');
}
public function testRemoveRelation()
{
AggregateCommentQuery::create()->deleteAll($this->con);
AggregatePostQuery::create()->deleteAll($this->con);
$post = new AggregatePost();
$post->save($this->con);
$comment1 = new AggregateComment();
$comment1->setAggregatePost($post);
$comment1->save($this->con);
$comment2 = new AggregateComment();
$comment2->setAggregatePost($post);
$comment2->save($this->con);
$this->assertEquals(2, $post->getNbComments());
$comment2->setAggregatePost(null);
$comment2->save($this->con);
$this->assertEquals(1, $post->getNbComments(), 'Removing a relation changes the related object aggregate column');
}
public function testReplaceRelation()
{
AggregateCommentQuery::create()->deleteAll($this->con);
AggregatePostQuery::create()->deleteAll($this->con);
$post1 = new AggregatePost();
$post1->save($this->con);
$post2 = new AggregatePost();
$post2->save($this->con);
$comment = new AggregateComment();
$comment->setAggregatePost($post1);
$comment->save($this->con);
$this->assertEquals(1, $post1->getNbComments());
$this->assertNull($post2->getNbComments());
$comment->setAggregatePost($post2);
$comment->save($this->con);
$this->assertEquals(0, $post1->getNbComments(), 'Replacing a relation changes the related object aggregate column');
$this->assertEquals(1, $post2->getNbComments(), 'Replacing a relation changes the related object aggregate column');
}
protected function populatePoll()
{
AggregateItemQuery::create()->deleteAll($this->con);
AggregatePollQuery::create()->deleteAll($this->con);
$poll = new AggregatePoll();
$poll->save($this->con);
$item1 = new AggregateItem();
$item1->setScore(12);
$item1->setAggregatePoll($poll);
$item1->save($this->con);
$item2 = new AggregateItem();
$item2->setScore(7);
$item2->setAggregatePoll($poll);
$item2->save($this->con);
return array($poll, $item1, $item2);
}
}
class TestableComment extends AggregateComment
{
// overrides the parent save() to bypass behavior hooks
public function save(PropelPDO $con = null)
{
$con->beginTransaction();
try {
$affectedRows = $this->doSave($con);
AggregateCommentPeer::addInstanceToPool($this);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
}
// overrides the parent delete() to bypass behavior hooks
public function delete(PropelPDO $con = null)
{
$con->beginTransaction();
try {
TestableAggregateCommentQuery::create()
->filterByPrimaryKey($this->getPrimaryKey())
->delete($con);
$con->commit();
$this->setDeleted(true);
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
}
}
class TestableAggregateCommentQuery extends AggregateCommentQuery
{
public static function create($modelAlias = null, $criteria = null)
{
return new TestableAggregateCommentQuery();
}
// overrides the parent basePreDelete() to bypass behavior hooks
protected function basePreDelete(PropelPDO $con)
{
return $this->preDelete($con);
}
// overrides the parent basePostDelete() to bypass behavior hooks
protected function basePostDelete($affectedRows, PropelPDO $con)
{
return $this->postDelete($affectedRows, $con);
}
}

View file

@ -0,0 +1,202 @@
<?php
/*
* $Id: ConcreteInheritanceBehaviorTest.php 1458 2010-01-13 16:09:51Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests for ConcreteInheritanceBehavior class
*
* @author François Zaniontto
* @version $Revision: 1774 $
* @package generator.behavior.concrete_inheritance
*/
class ConcreteInheritanceBehaviorTest extends BookstoreTestBase
{
public function testParentBehavior()
{
$behaviors = ConcreteContentPeer::getTableMap()->getBehaviors();
$this->assertTrue(array_key_exists('concrete_inheritance_parent', $behaviors), 'modifyTable() gives the parent table the concrete_inheritance_parent behavior');
$this->assertEquals('descendant_class', $behaviors['concrete_inheritance_parent']['descendant_column'], 'modifyTable() passed the descendent_column parameter to the parent behavior');
}
public function testModifyTableAddsParentColumn()
{
$contentColumns = array('id', 'title', 'category_id');
$article = ConcreteArticlePeer::getTableMap();
foreach ($contentColumns as $column) {
$this->assertTrue($article->containsColumn($column), 'modifyTable() adds the columns of the parent table');
}
$quizz = ConcreteQuizzPeer::getTableMap();
$this->assertEquals(3, count($quizz->getColumns()), 'modifyTable() does not add a column of the parent table if a similar column exists');
}
public function testModifyTableCopyDataAddsOneToOneRelationships()
{
$article = ConcreteArticlePeer::getTableMap();
$this->assertTrue($article->hasRelation('ConcreteContent'), 'modifyTable() adds a relationship to the parent');
$relation = $article->getRelation('ConcreteContent');
$this->assertEquals(RelationMap::MANY_TO_ONE, $relation->getType(), 'modifyTable adds a one-to-one relationship');
$content = ConcreteContentPeer::getTableMap();
$relation = $content->getRelation('ConcreteArticle');
$this->assertEquals(RelationMap::ONE_TO_ONE, $relation->getType(), 'modifyTable adds a one-to-one relationship');
}
public function testModifyTableNoCopyDataNoParentRelationship()
{
$quizz = ConcreteQuizzPeer::getTableMap();
$this->assertFalse($quizz->hasRelation('ConcreteContent'), 'modifyTable() does not add a relationship to the parent when copy_data is false');
}
public function testModifyTableCopyDataRemovesAutoIncrement()
{
$content = new ConcreteContent();
$content->save();
$c = new Criteria;
$c->add(ConcreteArticlePeer::ID, $content->getId());
try {
ConcreteArticlePeer::doInsert($c);
$this->assertTrue(true, 'modifyTable() removed autoIncrement from copied Primary keys');
} catch (PropelException $e) {
$this->fail('modifyTable() removed autoIncrement from copied Primary keys');
}
}
/**
* @expectedException PropelException
*/
public function testModifyTableNoCopyDataKeepsAutoIncrement()
{
$content = new ConcreteContent();
$content->save();
$c = new Criteria;
$c->add(ConcreteQuizzPeer::ID, $content->getId());
ConcreteQuizzPeer::doInsert($c);
}
public function testModifyTableAddsForeignKeys()
{
$article = ConcreteArticlePeer::getTableMap();
$this->assertTrue($article->hasRelation('ConcreteCategory'), 'modifyTable() copies relationships from parent table');
}
public function testModifyTableAddsForeignKeysWithoutDuplicates()
{
$article = ConcreteAuthorPeer::getTableMap();
$this->assertTrue($article->hasRelation('ConcreteNews'), 'modifyTable() copies relationships from parent table and removes hardcoded refPhpName');
}
public function testModifyTableAddsValidators()
{
$article = ConcreteArticlePeer::getTableMap();
$this->assertTrue($article->getColumn('title')->hasValidators(), 'modifyTable() copies validators from parent table');
}
// no way to test copying of indices and uniques, except by reverse engineering the db...
public function testParentObjectClass()
{
$article = new ConcreteArticle(); // to autoload the BaseConcreteArticle class
$r = new ReflectionClass('BaseConcreteArticle');
$this->assertEquals('ConcreteContent', $r->getParentClass()->getName(), 'concrete_inheritance changes the parent class of the Model Object to the parent object class');
$quizz = new ConcreteQuizz(); // to autoload the BaseConcreteQuizz class
$r = new ReflectionClass('BaseConcreteQuizz');
$this->assertEquals('ConcreteContent', $r->getParentClass()->getName(), 'concrete_inheritance changes the parent class of the Model Object to the parent object class');
}
public function testParentQueryClass()
{
$q = new ConcreteArticleQuery(); // to autoload the BaseConcreteArticleQuery class
$r = new ReflectionClass('BaseConcreteArticleQuery');
$this->assertEquals('ConcreteContentQuery', $r->getParentClass()->getName(), 'concrete_inheritance changes the parent class of the Query Object to the parent object class');
$q = new ConcreteQuizzQuery(); // to autoload the BaseConcreteQuizzQuery class
$r = new ReflectionClass('BaseConcreteQuizzQuery');
$this->assertEquals('ConcreteContentQuery', $r->getParentClass()->getName(), 'concrete_inheritance changes the parent class of the Query Object to the parent object class');
}
public function testPreSaveCopyData()
{
ConcreteArticleQuery::create()->deleteAll();
ConcreteQuizzQuery::create()->deleteAll();
ConcreteContentQuery::create()->deleteAll();
ConcreteCategoryQuery::create()->deleteAll();
$category = new ConcreteCategory();
$category->setName('main');
$article = new ConcreteArticle();
$article->setConcreteCategory($category);
$article->save();
$this->assertNotNull($article->getId());
$this->assertNotNull($category->getId());
$content = ConcreteContentQuery::create()->findPk($article->getId());
$this->assertNotNull($content);
$this->assertEquals($category->getId(), $content->getCategoryId());
}
public function testPreSaveNoCopyData()
{
ConcreteArticleQuery::create()->deleteAll();
ConcreteQuizzQuery::create()->deleteAll();
ConcreteContentQuery::create()->deleteAll();
$quizz = new ConcreteQuizz();
$quizz->save();
$this->assertNotNull($quizz->getId());
$content = ConcreteContentQuery::create()->findPk($quizz->getId());
$this->assertNull($content);
}
public function testGetParentOrCreateNew()
{
$article = new ConcreteArticle();
$content = $article->getParentOrCreate();
$this->assertTrue($content instanceof ConcreteContent, 'getParentOrCreate() returns an instance of the parent class');
$this->assertTrue($content->isNew(), 'getParentOrCreate() returns a new instance of the parent class if the object is new');
$this->assertEquals('ConcreteArticle', $content->getDescendantClass(), 'getParentOrCreate() correctly sets the descendant_class of the parent object');
}
public function testGetParentOrCreateExisting()
{
$article = new ConcreteArticle();
$article->save();
ConcreteContentPeer::clearInstancePool();
$content = $article->getParentOrCreate();
$this->assertTrue($content instanceof ConcreteContent, 'getParentOrCreate() returns an instance of the parent class');
$this->assertFalse($content->isNew(), 'getParentOrCreate() returns an existing instance of the parent class if the object is persisted');
$this->assertEquals($article->getId(), $content->getId(), 'getParentOrCreate() returns the parent object related to the current object');
}
public function testGetSyncParent()
{
$category = new ConcreteCategory();
$category->setName('main');
$article = new ConcreteArticle();
$article->setTitle('FooBar');
$article->setConcreteCategory($category);
$content = $article->getSyncParent();
$this->assertEquals('FooBar', $content->getTitle(), 'getSyncParent() returns a synchronized parent object');
$this->assertEquals($category, $content->getConcreteCategory(), 'getSyncParent() returns a synchronized parent object');
}
public function testPostDeleteCopyData()
{
ConcreteArticleQuery::create()->deleteAll();
ConcreteQuizzQuery::create()->deleteAll();
ConcreteContentQuery::create()->deleteAll();
ConcreteCategoryQuery::create()->deleteAll();
$category = new ConcreteCategory();
$category->setName('main');
$article = new ConcreteArticle();
$article->setConcreteCategory($category);
$article->save();
$id = $article->getId();
$article->delete();
$this->assertNull(ConcreteContentQuery::create()->findPk($id), 'delete() removes the parent record as well');
}
}

View file

@ -0,0 +1,53 @@
<?php
/*
* $Id: ConcreteInheritanceBehaviorTest.php 1458 2010-01-13 16:09:51Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests for ConcreteInheritanceParentBehavior class
*
* @author François Zaniontto
* @version $Revision: 1612 $
* @package generator.behavior.concrete_inheritance
*/
class ConcreteInheritanceParentBehaviorTest extends BookstoreTestBase
{
public function testHasChildObject()
{
ConcreteArticleQuery::create()->deleteAll();
ConcreteQuizzQuery::create()->deleteAll();
ConcreteContentQuery::create()->deleteAll();
$content = new ConcreteContent();
$content->save();
$this->assertFalse($content->hasChildObject());
$article = new ConcreteArticle();
$article->save();
$content = $article->getConcreteContent();
$this->assertTrue($content->hasChildObject());
}
public function testGetChildObject()
{
ConcreteArticleQuery::create()->deleteAll();
ConcreteQuizzQuery::create()->deleteAll();
ConcreteContentQuery::create()->deleteAll();
$content = new ConcreteContent();
$content->save();
$this->assertNull($content->getChildObject());
$article = new ConcreteArticle();
$article->save();
$content = $article->getConcreteContent();
$this->assertEquals($article, $content->getChildObject());
}
}

View file

@ -0,0 +1,551 @@
<?php
/*
* $Id: NestedSetBehaviorObjectBuilderModifierWithScopeTest.php 1612 2010-03-16 22:56:21Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/behavior/BookstoreNestedSetTestBase.php';
/**
* Tests for NestedSetBehaviorObjectBuilderModifier class
*
* @author François Zaninotto
* @version $Revision: 1612 $
* @package generator.behavior.nestedset
*/
class NestedSetBehaviorObjectBuilderModifierWithScopeTest extends BookstoreNestedSetTestBase
{
protected function getByTitle($title)
{
$c = new Criteria();
$c->add(Table10Peer::TITLE, $title);
return Table10Peer::doSelectOne($c);
}
public function testDelete()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$t5->delete();
$expected = array(
't1' => array(1, 8, 0),
't2' => array(2, 3, 1),
't3' => array(4, 7, 1),
't4' => array(5, 6, 2),
);
$this->assertEquals($expected, $this->dumpTreeWithScope(1), 'delete() deletes all descendants and shifts the entire subtree correctly');
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($expected, $this->dumpTreeWithScope(2), 'delete() does not delete anything out of the scope');
}
public function testIsDescendantOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$this->assertFalse($t8->isDescendantOf($t9), 'root is not seen as a child of root');
$this->assertTrue($t9->isDescendantOf($t8), 'direct child is seen as a child of root');
try {
$t2->isDescendantOf($t8);
$this->fail('isDescendantOf() throws an exception when comparing two nodes of different trees');
} catch (PropelException $e) {
$this->assertTrue(true, 'isDescendantOf() throws an exception when comparing two nodes of different trees');
}
}
public function testGetParent()
{
$this->initTreeWithScope();
$t1 = $this->getByTitle('t1');
$this->assertNull($t1->getParent($this->con), 'getParent() return null for root nodes');
$t2 = $this->getByTitle('t2');
$this->assertEquals($t2->getParent($this->con), $t1, 'getParent() correctly retrieves parent for leafs');
$t3 = $this->getByTitle('t3');
$this->assertEquals($t3->getParent($this->con), $t1, 'getParent() correctly retrieves parent for nodes');
$t4 = $this->getByTitle('t4');
$this->assertEquals($t4->getParent($this->con), $t3, 'getParent() retrieves the same parent for nodes');
}
public function testGetPrevSibling()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$this->assertNull($t1->getPrevSibling($this->con), 'getPrevSibling() returns null for root nodes');
$this->assertNull($t2->getPrevSibling($this->con), 'getPrevSibling() returns null for first siblings');
$this->assertEquals($t3->getPrevSibling($this->con), $t2, 'getPrevSibling() correctly retrieves prev sibling');
$this->assertNull($t6->getPrevSibling($this->con), 'getPrevSibling() returns null for first siblings');
$this->assertEquals($t7->getPrevSibling($this->con), $t6, 'getPrevSibling() correctly retrieves prev sibling');
}
public function testGetNextSibling()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$this->assertNull($t1->getNextSibling($this->con), 'getNextSibling() returns null for root nodes');
$this->assertEquals($t2->getNextSibling($this->con), $t3, 'getNextSibling() correctly retrieves next sibling');
$this->assertNull($t3->getNextSibling($this->con), 'getNextSibling() returns null for last siblings');
$this->assertEquals($t6->getNextSibling($this->con), $t7, 'getNextSibling() correctly retrieves next sibling');
$this->assertNull($t7->getNextSibling($this->con), 'getNextSibling() returns null for last siblings');
}
public function testGetDescendants()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$descendants = $t3->getDescendants();
$expected = array(
't4' => array(5, 6, 2),
't5' => array(7, 12, 2),
't6' => array(8, 9, 3),
't7' => array(10, 11, 3),
);
$this->assertEquals($expected, $this->dumpNodes($descendants), 'getDescendants() returns descendants from the current scope only');
}
public function testGetAncestors()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$this->assertEquals(array(), $t1->getAncestors(), 'getAncestors() returns an empty array for roots');
$ancestors = $t5->getAncestors();
$expected = array(
't1' => array(1, 14, 0),
't3' => array(4, 13, 1),
);
$this->assertEquals($expected, $this->dumpNodes($ancestors), 'getAncestors() returns ancestors from the current scope only');
}
public function testInsertAsFirstChildOf()
{
$this->assertTrue(method_exists('Table10', 'insertAsFirstChildOf'), 'nested_set adds a insertAsFirstChildOf() method');
$fixtures = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$t11 = new PublicTable10();
$t11->setTitle('t11');
$t11->insertAsFirstChildOf($fixtures[2]); // first child of t3
$this->assertEquals(1, $t11->getScopeValue(), 'insertAsFirstChildOf() sets the scope value correctly');
$t11->save();
$expected = array(
't1' => array(1, 16, 0),
't2' => array(2, 3, 1),
't3' => array(4, 15, 1),
't4' => array(7, 8, 2),
't5' => array(9, 14, 2),
't6' => array(10, 11, 3),
't7' => array(12, 13, 3),
't11' => array(5, 6, 2)
);
$this->assertEquals($expected, $this->dumpTreeWithScope(1), 'insertAsFirstChildOf() shifts the other nodes correctly');
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($expected, $this->dumpTreeWithScope(2), 'insertAsFirstChildOf() does not shift anything out of the scope');
}
public function testInsertAsLastChildOf()
{
$this->assertTrue(method_exists('Table10', 'insertAsLastChildOf'), 'nested_set adds a insertAsLastChildOf() method');
$fixtures = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$t11 = new PublicTable10();
$t11->setTitle('t11');
$t11->insertAsLastChildOf($fixtures[2]); // last child of t3
$this->assertEquals(1, $t11->getScopeValue(), 'insertAsLastChildOf() sets the scope value correctly');
$t11->save();
$expected = array(
't1' => array(1, 16, 0),
't2' => array(2, 3, 1),
't3' => array(4, 15, 1),
't4' => array(5, 6, 2),
't5' => array(7, 12, 2),
't6' => array(8, 9, 3),
't7' => array(10, 11, 3),
't11' => array(13, 14, 2)
);
$this->assertEquals($expected, $this->dumpTreeWithScope(1), 'insertAsLastChildOf() shifts the other nodes correctly');
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($expected, $this->dumpTreeWithScope(2), 'insertAsLastChildOf() does not shift anything out of the scope');
}
public function testInsertAsPrevSiblingOf()
{
$this->assertTrue(method_exists('Table10', 'insertAsPrevSiblingOf'), 'nested_set adds a insertAsPrevSiblingOf() method');
$fixtures = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$t11 = new PublicTable10();
$t11->setTitle('t11');
$t11->insertAsPrevSiblingOf($fixtures[2]); // prev sibling of t3
$this->assertEquals(1, $t11->getScopeValue(), 'insertAsPrevSiblingOf() sets the scope value correctly');
$t11->save();
$expected = array(
't1' => array(1, 16, 0),
't2' => array(2, 3, 1),
't3' => array(6, 15, 1),
't4' => array(7, 8, 2),
't5' => array(9, 14, 2),
't6' => array(10, 11, 3),
't7' => array(12, 13, 3),
't11' => array(4, 5, 1)
);
$this->assertEquals($expected, $this->dumpTreeWithScope(1), 'insertAsPrevSiblingOf() shifts the other nodes correctly');
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($expected, $this->dumpTreeWithScope(2), 'insertAsPrevSiblingOf() does not shift anything out of the scope');
}
public function testInsertAsNextSiblingOf()
{
$this->assertTrue(method_exists('Table10', 'insertAsNextSiblingOf'), 'nested_set adds a insertAsNextSiblingOf() method');
$fixtures = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$t11 = new PublicTable10();
$t11->setTitle('t11');
$t11->insertAsNextSiblingOf($fixtures[2]); // next sibling of t3
$this->assertEquals(1, $t11->getScopeValue(), 'insertAsNextSiblingOf() sets the scope value correctly');
$t11->save();
$expected = array(
't1' => array(1, 16, 0),
't2' => array(2, 3, 1),
't3' => array(4, 13, 1),
't4' => array(5, 6, 2),
't5' => array(7, 12, 2),
't6' => array(8, 9, 3),
't7' => array(10, 11, 3),
't11' => array(14, 15, 1)
);
$this->assertEquals($expected, $this->dumpTreeWithScope(1), 'insertAsNextSiblingOf() shifts the other nodes correctly');
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($expected, $this->dumpTreeWithScope(2), 'insertAsNextSiblingOf() does not shift anything out of the scope');
}
public function testMoveToFirstChildOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
try {
$t8->moveToFirstChildOf($t3);
$this->fail('moveToFirstChildOf() throws an exception when the target is in a different tree');
} catch (PropelException $e) {
$this->assertTrue(true, 'moveToFirstChildOf() throws an exception when the target is in a different tree');
}
try {
$t5->moveToLastChildOf($t2);
$this->assertTrue(true, 'moveToFirstChildOf() does not throw an exception when the target is in the same tree');
} catch (PropelException $e) {
$this->fail('moveToFirstChildOf() does not throw an exception when the target is in the same tree');
}
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($expected, $this->dumpTreeWithScope(2), 'moveToFirstChildOf() does not shift anything out of the scope');
}
public function testMoveToLastChildOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
try {
$t8->moveToLastChildOf($t3);
$this->fail('moveToLastChildOf() throws an exception when the target is in a different tree');
} catch (PropelException $e) {
$this->assertTrue(true, 'moveToLastChildOf() throws an exception when the target is in a different tree');
}
try {
$t5->moveToLastChildOf($t2);
$this->assertTrue(true, 'moveToLastChildOf() does not throw an exception when the target is in the same tree');
} catch (PropelException $e) {
$this->fail('moveToLastChildOf() does not throw an exception when the target is in the same tree');
}
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($expected, $this->dumpTreeWithScope(2), 'moveToLastChildOf() does not shift anything out of the scope');
}
public function testMoveToPrevSiblingOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
try {
$t8->moveToPrevSiblingOf($t3);
$this->fail('moveToPrevSiblingOf() throws an exception when the target is in a different tree');
} catch (PropelException $e) {
$this->assertTrue(true, 'moveToPrevSiblingOf() throws an exception when the target is in a different tree');
}
try {
$t5->moveToPrevSiblingOf($t2);
$this->assertTrue(true, 'moveToPrevSiblingOf() does not throw an exception when the target is in the same tree');
} catch (PropelException $e) {
$this->fail('moveToPrevSiblingOf() does not throw an exception when the target is in the same tree');
}
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($expected, $this->dumpTreeWithScope(2), 'moveToPrevSiblingOf() does not shift anything out of the scope');
}
public function testMoveToNextSiblingOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
try {
$t8->moveToNextSiblingOf($t3);
$this->fail('moveToNextSiblingOf() throws an exception when the target is in a different tree');
} catch (PropelException $e) {
$this->assertTrue(true, 'moveToNextSiblingOf() throws an exception when the target is in a different tree');
}
try {
$t5->moveToNextSiblingOf($t2);
$this->assertTrue(true, 'moveToNextSiblingOf() does not throw an exception when the target is in the same tree');
} catch (PropelException $e) {
$this->fail('moveToNextSiblingOf() does not throw an exception when the target is in the same tree');
}
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($expected, $this->dumpTreeWithScope(2), 'moveToNextSiblingOf() does not shift anything out of the scope');
}
public function testDeleteDescendants()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$this->assertEquals(4, $t3->deleteDescendants(), 'deleteDescendants() returns the number of deleted nodes');
$expected = array(
't1' => array(1, 6, 0),
't2' => array(2, 3, 1),
't3' => array(4, 5, 1),
);
$this->assertEquals($expected, $this->dumpTreeWithScope(1), 'deleteDescendants() shifts the entire subtree correctly');
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($expected, $this->dumpTreeWithScope(2), 'deleteDescendants() does not delete anything out of the scope');
}
}

View file

@ -0,0 +1,350 @@
<?php
/*
* $Id: NestedSetBehaviorPeerBuilderModifierTest.php 1612 2010-03-16 22:56:21Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/behavior/BookstoreNestedSetTestBase.php';
/**
* Tests for NestedSetBehaviorPeerBuilderModifier class
*
* @author François Zaninotto
* @version $Revision: 1612 $
* @package generator.behavior.nestedset
*/
class NestedSetBehaviorPeerBuilderModifierTest extends BookstoreNestedSetTestBase
{
public function testConstants()
{
$this->assertEquals(Table9Peer::LEFT_COL, 'table9.TREE_LEFT', 'nested_set adds a LEFT_COL constant');
$this->assertEquals(Table9Peer::RIGHT_COL, 'table9.TREE_RIGHT', 'nested_set adds a RIGHT_COL constant');
$this->assertEquals(Table9Peer::LEVEL_COL, 'table9.TREE_LEVEL', 'nested_set adds a LEVEL_COL constant');
}
public function testRetrieveRoot()
{
$this->assertTrue(method_exists('Table9Peer', 'retrieveRoot'), 'nested_set adds a retrieveRoot() method');
Table9Peer::doDeleteAll();
$this->assertNull(Table9Peer::retrieveRoot(), 'retrieveRoot() returns null as long as no root node is defined');
$t1 = new Table9();
$t1->setLeftValue(123);
$t1->setRightValue(456);
$t1->save();
$this->assertNull(Table9Peer::retrieveRoot(), 'retrieveRoot() returns null as long as no root node is defined');
$t2 = new Table9();
$t2->setLeftValue(1);
$t2->setRightValue(2);
$t2->save();
$this->assertEquals(Table9Peer::retrieveRoot(), $t2, 'retrieveRoot() retrieves the root node');
}
public function testRetrieveTree()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree();
$tree = Table9Peer::retrieveTree();
$this->assertEquals(array($t1, $t2, $t3, $t4, $t5, $t6, $t7), $tree, 'retrieveTree() retrieves the whole tree');
$c = new Criteria();
$c->add(Table9Peer::LEFT_COL, 4, Criteria::GREATER_EQUAL);
$tree = Table9Peer::retrieveTree($c);
$this->assertEquals(array($t3, $t4, $t5, $t6, $t7), $tree, 'retrieveTree() accepts a Criteria as first parameter');
}
public function testIsValid()
{
$this->assertTrue(method_exists('Table9Peer', 'isValid'), 'nested_set adds an isValid() method');
$this->assertFalse(Table9Peer::isValid(null), 'isValid() returns false when passed null ');
$t1 = new Table9();
$this->assertFalse(Table9Peer::isValid($t1), 'isValid() returns false when passed an empty node object');
$t2 = new Table9();
$t2->setLeftValue(5)->setRightValue(2);
$this->assertFalse(Table9Peer::isValid($t2), 'isValid() returns false when passed a node object with left > right');
$t3 = new Table9();
$t3->setLeftValue(5)->setRightValue(5);
$this->assertFalse(Table9Peer::isValid($t3), 'isValid() returns false when passed a node object with left = right');
$t4 = new Table9();
$t4->setLeftValue(2)->setRightValue(5);
$this->assertTrue(Table9Peer::isValid($t4), 'isValid() returns true when passed a node object with left < right');
}
public function testDeleteTree()
{
$this->initTree();
Table9Peer::deleteTree();
$this->assertEquals(array(), Table9Peer::doSelect(new Criteria()), 'deleteTree() deletes the whole tree');
}
public function testShiftRLValuesDelta()
{
$this->initTree();
Table9Peer::shiftRLValues($delta = 1, $left = 1);
Table9Peer::clearInstancePool();
$expected = array(
't1' => array(2, 15, 0),
't2' => array(3, 4, 1),
't3' => array(5, 14, 1),
't4' => array(6, 7, 2),
't5' => array(8, 13, 2),
't6' => array(9, 10, 3),
't7' => array(11, 12, 3),
);
$this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues shifts all nodes with a positive amount');
$this->initTree();
Table9Peer::shiftRLValues($delta = -1, $left = 1);
Table9Peer::clearInstancePool();
$expected = array(
't1' => array(0, 13, 0),
't2' => array(1, 2, 1),
't3' => array(3, 12, 1),
't4' => array(4, 5, 2),
't5' => array(6, 11, 2),
't6' => array(7, 8, 3),
't7' => array(9, 10, 3),
);
$this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues can shift all nodes with a negative amount');
$this->initTree();
Table9Peer::shiftRLValues($delta = 3, $left = 1);
Table9Peer::clearInstancePool();
$expected = array(
't1'=> array(4, 17, 0),
't2' => array(5, 6, 1),
't3' => array(7, 16, 1),
't4' => array(8, 9, 2),
't5' => array(10, 15, 2),
't6' => array(11, 12, 3),
't7' => array(13, 14, 3),
);
$this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues shifts all nodes several units to the right');
Table9Peer::shiftRLValues($delta = -3, $left = 1);
Table9Peer::clearInstancePool();
$expected = array(
't1' => array(1, 14, 0),
't2' => array(2, 3, 1),
't3' => array(4, 13, 1),
't4' => array(5, 6, 2),
't5' => array(7, 12, 2),
't6' => array(8, 9, 3),
't7' => array(10, 11, 3),
);
$this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues shifts all nodes several units to the left');
}
public function testShiftRLValuesLeftLimit()
{
$this->initTree();
Table9Peer::shiftRLValues($delta = 1, $left = 15);
Table9Peer::clearInstancePool();
$expected = array(
't1' => array(1, 14, 0),
't2' => array(2, 3, 1),
't3' => array(4, 13, 1),
't4' => array(5, 6, 2),
't5' => array(7, 12, 2),
't6' => array(8, 9, 3),
't7' => array(10, 11, 3),
);
$this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues does not shift anything when the left parameter is higher than the highest right value');
$this->initTree();
Table9Peer::shiftRLValues($delta = 1, $left = 5);
Table9Peer::clearInstancePool();
$expected = array(
't1' => array(1, 15, 0),
't2' => array(2, 3, 1),
't3' => array(4, 14, 1),
't4' => array(6, 7, 2),
't5' => array(8, 13, 2),
't6' => array(9, 10, 3),
't7' => array(11, 12, 3),
);
$this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues shifts only the nodes having a LR value higher than the given left parameter');
$this->initTree();
Table9Peer::shiftRLValues($delta = 1, $left = 1);
Table9Peer::clearInstancePool();
$expected = array(
't1'=> array(2, 15, 0),
't2' => array(3, 4, 1),
't3' => array(5, 14, 1),
't4' => array(6, 7, 2),
't5' => array(8, 13, 2),
't6' => array(9, 10, 3),
't7' => array(11, 12, 3),
);
$this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues shifts all nodes when the left parameter is 1');
}
public function testShiftRLValuesRightLimit()
{
$this->initTree();
Table9Peer::shiftRLValues($delta = 1, $left = 1, $right = 0);
Table9Peer::clearInstancePool();
$expected = array(
't1' => array(1, 14, 0),
't2' => array(2, 3, 1),
't3' => array(4, 13, 1),
't4' => array(5, 6, 2),
't5' => array(7, 12, 2),
't6' => array(8, 9, 3),
't7' => array(10, 11, 3),
);
$this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues does not shift anything when the right parameter is 0');
$this->initTree();
Table9Peer::shiftRLValues($delta = 1, $left = 1, $right = 5);
Table9Peer::clearInstancePool();
$expected = array(
't1' => array(2, 14, 0),
't2' => array(3, 4, 1),
't3' => array(5, 13, 1),
't4' => array(6, 6, 2),
't5' => array(7, 12, 2),
't6' => array(8, 9, 3),
't7' => array(10, 11, 3),
);
$this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues shiftRLValues shifts only the nodes having a LR value lower than the given right parameter');
$this->initTree();
Table9Peer::shiftRLValues($delta = 1, $left = 1, $right = 15);
Table9Peer::clearInstancePool();
$expected = array(
't1'=> array(2, 15, 0),
't2' => array(3, 4, 1),
't3' => array(5, 14, 1),
't4' => array(6, 7, 2),
't5' => array(8, 13, 2),
't6' => array(9, 10, 3),
't7' => array(11, 12, 3),
);
$this->assertEquals($this->dumpTree(), $expected, 'shiftRLValues shifts all nodes when the right parameter is higher than the highest right value');
}
public function testShiftLevel()
{
/* Tree used for tests
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
*/
$this->initTree();
Table9Peer::shiftLevel($delta = 1, $first = 7, $last = 12);
Table9Peer::clearInstancePool();
$expected = array(
't1' => array(1, 14, 0),
't2' => array(2, 3, 1),
't3' => array(4, 13, 1),
't4' => array(5, 6, 2),
't5' => array(7, 12, 3),
't6' => array(8, 9, 4),
't7' => array(10, 11, 4),
);
$this->assertEquals($this->dumpTree(), $expected, 'shiftLevel shifts all nodes with a left value between the first and last');
$this->initTree();
Table9Peer::shiftLevel($delta = -1, $first = 7, $last = 12);
Table9Peer::clearInstancePool();
$expected = array(
't1' => array(1, 14, 0),
't2' => array(2, 3, 1),
't3' => array(4, 13, 1),
't4' => array(5, 6, 2),
't5' => array(7, 12, 1),
't6' => array(8, 9, 2),
't7' => array(10, 11, 2),
);
$this->assertEquals($this->dumpTree(), $expected, 'shiftLevel shifts all nodes wit ha negative amount');
}
public function testUpdateLoadedNodes()
{
$this->assertTrue(method_exists('Table9Peer', 'updateLoadedNodes'), 'nested_set adds a updateLoadedNodes() method');
$fixtures = $this->initTree();
Table9Peer::shiftRLValues(1, 5);
$expected = array(
't1' => array(1, 14),
't2' => array(2, 3),
't3' => array(4, 13),
't4' => array(5, 6),
't5' => array(7, 12),
't6' => array(8, 9),
't7' => array(10, 11),
);
$actual = array();
foreach ($fixtures as $t) {
$actual[$t->getTitle()] = array($t->getLeftValue(), $t->getRightValue());
}
$this->assertEquals($actual, $expected, 'Loaded nodes are not in sync before calling updateLoadedNodes()');
Table9Peer::updateLoadedNodes();
$expected = array(
't1' => array(1, 15),
't2' => array(2, 3),
't3' => array(4, 14),
't4' => array(6, 7),
't5' => array(8, 13),
't6' => array(9, 10),
't7' => array(11, 12),
);
$actual = array();
foreach ($fixtures as $t) {
$actual[$t->getTitle()] = array($t->getLeftValue(), $t->getRightValue());
}
$this->assertEquals($actual, $expected, 'Loaded nodes are in sync after calling updateLoadedNodes()');
}
public function testMakeRoomForLeaf()
{
$this->assertTrue(method_exists('Table9Peer', 'makeRoomForLeaf'), 'nested_set adds a makeRoomForLeaf() method');
list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree();
/* Tree used for tests
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
*/
$t = Table9Peer::makeRoomForLeaf(5); // first child of t3
$expected = array(
't1' => array(1, 16, 0),
't2' => array(2, 3, 1),
't3' => array(4, 15, 1),
't4' => array(7, 8, 2),
't5' => array(9, 14, 2),
't6' => array(10, 11, 3),
't7' => array(12, 13, 3),
);
$this->assertEquals($expected, $this->dumpTree(), 'makeRoomForLeaf() shifts the other nodes correctly');
foreach ($expected as $key => $values)
{
$this->assertEquals($values, array($$key->getLeftValue(), $$key->getRightValue(), $$key->getLevel()), 'makeRoomForLeaf() updates nodes already in memory');
}
}
public function testFixLevels()
{
$fixtures = $this->initTree();
// reset the levels
foreach ($fixtures as $node) {
$node->setLevel(null)->save();
}
// fix the levels
Table9Peer::fixLevels();
$expected = array(
't1' => array(1, 14, 0),
't2' => array(2, 3, 1),
't3' => array(4, 13, 1),
't4' => array(5, 6, 2),
't5' => array(7, 12, 2),
't6' => array(8, 9, 3),
't7' => array(10, 11, 3),
);
$this->assertEquals($expected, $this->dumpTree(), 'fixLevels() fixes the levels correctly');
Table9Peer::fixLevels();
$this->assertEquals($expected, $this->dumpTree(), 'fixLevels() can be called several times');
}
}

View file

@ -0,0 +1,253 @@
<?php
/*
* $Id: NestedSetBehaviorPeerBuilderModifierWithScopeTest.php 1612 2010-03-16 22:56:21Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/behavior/BookstoreNestedSetTestBase.php';
/**
* Tests for NestedSetBehaviorPeerBuilderModifier class
*
* @author François Zaninotto
* @version $Revision: 1612 $
* @package generator.behavior.nestedset
*/
class NestedSetBehaviorPeerBuilderModifierWithScopeTest extends BookstoreNestedSetTestBase
{
public function testConstants()
{
$this->assertEquals(Table10Peer::LEFT_COL, 'table10.MY_LEFT_COLUMN', 'nested_set adds a LEFT_COL constant using the custom left_column parameter');
$this->assertEquals(Table10Peer::RIGHT_COL, 'table10.MY_RIGHT_COLUMN', 'nested_set adds a RIGHT_COL constant using the custom right_column parameter');
$this->assertEquals(Table10Peer::LEVEL_COL, 'table10.MY_LEVEL_COLUMN', 'nested_set adds a LEVEL_COL constant using the custom level_column parameter');
$this->assertEquals(Table10Peer::SCOPE_COL, 'table10.MY_SCOPE_COLUMN', 'nested_set adds a SCOPE_COL constant when the use_scope parameter is true');
}
public function testRetrieveRoots()
{
$this->assertTrue(method_exists('Table10Peer', 'retrieveRoots'), 'nested_set adds a retrieveRoots() method for trees that use scope');
$this->assertFalse(method_exists('Table9Peer', 'retrieveRoots'), 'nested_set does not add a retrieveRoots() method for trees that don\'t use scope');
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$this->assertEquals(array($t1, $t8), Table10Peer::retrieveRoots(), 'retrieveRoots() returns the tree roots');
$c = new Criteria();
$c->add(Table10Peer::TITLE, 't1');
$this->assertEquals(array($t1), Table10Peer::retrieveRoots($c), 'retrieveRoots() accepts a Criteria as first parameter');
}
public function testRetrieveRoot()
{
$this->assertTrue(method_exists('Table10Peer', 'retrieveRoot'), 'nested_set adds a retrieveRoot() method');
Table10Peer::doDeleteAll();
$t1 = new Table10();
$t1->setLeftValue(1);
$t1->setRightValue(2);
$t1->setScopeValue(2);
$t1->save();
$this->assertNull(Table10Peer::retrieveRoot(1), 'retrieveRoot() returns null as long as no root node is defined in the required scope');
$t2 = new Table10();
$t2->setLeftValue(1);
$t2->setRightValue(2);
$t2->setScopeValue(1);
$t2->save();
$this->assertEquals(Table10Peer::retrieveRoot(1), $t2, 'retrieveRoot() retrieves the root node in the required scope');
}
public function testRetrieveTree()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$tree = Table10Peer::retrieveTree(1);
$this->assertEquals(array($t1, $t2, $t3, $t4, $t5, $t6, $t7), $tree, 'retrieveTree() retrieves the scoped tree');
$tree = Table10Peer::retrieveTree(2);
$this->assertEquals(array($t8, $t9, $t10), $tree, 'retrieveTree() retrieves the scoped tree');
$c = new Criteria();
$c->add(Table10Peer::LEFT_COL, 4, Criteria::GREATER_EQUAL);
$tree = Table10Peer::retrieveTree(1, $c);
$this->assertEquals(array($t3, $t4, $t5, $t6, $t7), $tree, 'retrieveTree() accepts a Criteria as first parameter');
}
public function testDeleteTree()
{
$this->initTreeWithScope();
Table10Peer::deleteTree(1);
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($this->dumpTreeWithScope(2), $expected, 'deleteTree() does not delete anything out of the scope');
}
public function testShiftRLValues()
{
$this->assertTrue(method_exists('Table10Peer', 'shiftRLValues'), 'nested_set adds a shiftRLValues() method');
$this->initTreeWithScope();
Table10Peer::shiftRLValues(1, 100, null, 1);
Table10Peer::clearInstancePool();
$expected = array(
't1' => array(1, 14, 0),
't2' => array(2, 3, 1),
't3' => array(4, 13, 1),
't4' => array(5, 6, 2),
't5' => array(7, 12, 2),
't6' => array(8, 9, 3),
't7' => array(10, 11, 3),
);
$this->assertEquals($this->dumpTreeWithScope(1), $expected, 'shiftRLValues does not shift anything when the first parameter is higher than the highest right value');
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($this->dumpTreeWithScope(2), $expected, 'shiftRLValues does not shift anything out of the scope');
$this->initTreeWithScope();
Table10Peer::shiftRLValues(1, 1, null, 1);
Table10Peer::clearInstancePool();
$expected = array(
't1' => array(2, 15, 0),
't2' => array(3, 4, 1),
't3' => array(5, 14, 1),
't4' => array(6, 7, 2),
't5' => array(8, 13, 2),
't6' => array(9, 10, 3),
't7' => array(11, 12, 3),
);
$this->assertEquals($this->dumpTreeWithScope(1), $expected, 'shiftRLValues can shift all nodes to the right');
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($this->dumpTreeWithScope(2), $expected, 'shiftRLValues does not shift anything out of the scope');
$this->initTreeWithScope();
Table10Peer::shiftRLValues(-1, 1, null, 1);
Table10Peer::clearInstancePool();
$expected = array(
't1' => array(0, 13, 0),
't2' => array(1, 2, 1),
't3' => array(3, 12, 1),
't4' => array(4, 5, 2),
't5' => array(6, 11, 2),
't6' => array(7, 8, 3),
't7' => array(9, 10, 3),
);
$this->assertEquals($this->dumpTreeWithScope(1), $expected, 'shiftRLValues can shift all nodes to the left');
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($this->dumpTreeWithScope(2), $expected, 'shiftRLValues does not shift anything out of the scope');
$this->initTreeWithScope();
Table10Peer::shiftRLValues(1, 5, null, 1);
Table10Peer::clearInstancePool();
$expected = array(
't1' => array(1, 15, 0),
't2' => array(2, 3, 1),
't3' => array(4, 14, 1),
't4' => array(6, 7, 2),
't5' => array(8, 13, 2),
't6' => array(9, 10, 3),
't7' => array(11, 12, 3),
);
$this->assertEquals($this->dumpTreeWithScope(1), $expected, 'shiftRLValues can shift some nodes to the right');
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($this->dumpTreeWithScope(2), $expected, 'shiftRLValues does not shift anything out of the scope');
}
public function testShiftLevel()
{
$this->initTreeWithScope();
Table10Peer::shiftLevel($delta = 1, $first = 7, $last = 12, $scope = 1);
Table10Peer::clearInstancePool();
$expected = array(
't1' => array(1, 14, 0),
't2' => array(2, 3, 1),
't3' => array(4, 13, 1),
't4' => array(5, 6, 2),
't5' => array(7, 12, 3),
't6' => array(8, 9, 4),
't7' => array(10, 11, 4),
);
$this->assertEquals($this->dumpTreeWithScope(1), $expected, 'shiftLevel can shift level whith a scope');
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($this->dumpTreeWithScope(2), $expected, 'shiftLevel does not shift anything out of the scope');
}
public function testMakeRoomForLeaf()
{
$this->assertTrue(method_exists('Table10Peer', 'makeRoomForLeaf'), 'nested_set adds a makeRoomForLeaf() method');
$fixtures = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$t = Table10Peer::makeRoomForLeaf(5, 1); // first child of t3
$expected = array(
't1' => array(1, 16, 0),
't2' => array(2, 3, 1),
't3' => array(4, 15, 1),
't4' => array(7, 8, 2),
't5' => array(9, 14, 2),
't6' => array(10, 11, 3),
't7' => array(12, 13, 3),
);
$this->assertEquals($expected, $this->dumpTreeWithScope(1), 'makeRoomForLeaf() shifts the other nodes correctly');
$expected = array(
't8' => array(1, 6, 0),
't9' => array(2, 3, 1),
't10' => array(4, 5, 1),
);
$this->assertEquals($expected, $this->dumpTreeWithScope(2), 'makeRoomForLeaf() does not shift anything out of the scope');
}
}

View file

@ -0,0 +1,283 @@
<?php
/*
* $Id: NestedSetBehaviorQueryBuilderModifierTest.php 1347 2009-12-03 21:06:36Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/behavior/BookstoreNestedSetTestBase.php';
/**
* Tests for NestedSetBehaviorQueryBuilderModifier class
*
* @author François Zaninotto
* @version $Revision: 1612 $
* @package generator.behavior.nestedset
*/
class NestedSetBehaviorQueryBuilderModifierTest extends BookstoreNestedSetTestBase
{
public function testDescendantsOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree();
/* Tree used for tests
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
*/
$objs = Table9Query::create()
->descendantsOf($t7)
->orderByBranch()
->find();
$coll = $this->buildCollection(array());
$this->assertEquals($coll, $objs, 'decendantsOf() filters by descendants');
$objs = Table9Query::create()
->descendantsOf($t3)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t4, $t5, $t6, $t7));
$this->assertEquals($coll, $objs, 'decendantsOf() filters by descendants');
}
public function testBranchOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree();
/* Tree used for tests
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
*/
$objs = Table9Query::create()
->branchOf($t7)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t7));
$this->assertEquals($coll, $objs, 'branchOf() filters by descendants and includes object passed as parameter');
$objs = Table9Query::create()
->branchOf($t3)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t3, $t4, $t5, $t6, $t7));
$this->assertEquals($coll, $objs, 'branchOf() filters by descendants and includes object passed as parameter');
$objs = Table9Query::create()
->branchOf($t1)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t1, $t2, $t3, $t4, $t5, $t6, $t7));
$this->assertEquals($coll, $objs, 'branchOf() returns the whole tree for the root node');
}
public function testChildrenOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree();
/* Tree used for tests
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
*/
$objs = Table9Query::create()
->childrenOf($t6)
->orderByBranch()
->find();
$coll = $this->buildCollection(array());
$this->assertEquals($coll, $objs, 'childrenOf() returns empty collection for leaf nodes');
$objs = Table9Query::create()
->childrenOf($t5)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t6, $t7));
$this->assertEquals($coll, $objs, 'childrenOf() filters by children');
$objs = Table9Query::create()
->childrenOf($t3)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t4, $t5));
$this->assertEquals($coll, $objs, 'childrenOf() filters by children and not by descendants');
}
public function testSiblingsOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree();
/* Tree used for tests
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
*/
$desc = Table9Query::create()
->siblingsOf($t1)
->orderByBranch()
->find();
$coll = $this->buildCollection(array());
$this->assertEquals($coll, $desc, 'siblingsOf() returns empty collection for the root node');
$desc = Table9Query::create()
->siblingsOf($t3)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t2));
$this->assertEquals($coll, $desc, 'siblingsOf() filters by siblings');
}
public function testAncestorsOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree();
/* Tree used for tests
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
*/
$objs = Table9Query::create()
->ancestorsOf($t1)
->orderByBranch()
->find();
$coll = $this->buildCollection(array());
$this->assertEquals($coll, $objs, 'ancestorsOf() returns empty collection for root node');
$objs = Table9Query::create()
->ancestorsOf($t3)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t1));
$this->assertEquals($coll, $objs, 'ancestorsOf() filters by ancestors');
$objs = Table9Query::create()
->ancestorsOf($t7)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t1, $t3, $t5));
$this->assertEquals($coll, $objs, 'childrenOf() filters by ancestors');
}
public function testRootsOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree();
/* Tree used for tests
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
*/
$objs = Table9Query::create()
->rootsOf($t1)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t1));
$this->assertEquals($coll, $objs, 'rootsOf() returns the root node for root node');
$objs = Table9Query::create()
->rootsOf($t3)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t1, $t3));
$this->assertEquals($coll, $objs, 'rootsOf() filters by ancestors and includes the node passed as parameter');
$objs = Table9Query::create()
->rootsOf($t7)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t1, $t3, $t5, $t7));
$this->assertEquals($coll, $objs, 'rootsOf() filters by ancestors and includes the node passed as parameter');
}
public function testOrderByBranch()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree();
$t5->moveToPrevSiblingOf($t4);
/* Results in
t1
| \
t2 t3
| \
t5 t4
| \
t6 t7
*/
$objs = Table9Query::create()
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t1, $t2, $t3, $t5, $t6, $t7, $t4), 'orderByBranch() orders by branch left to right');
$objs = Table9Query::create()
->orderByBranch(true)
->find();
$coll = $this->buildCollection(array($t4, $t7, $t6, $t5, $t3, $t2, $t1), 'orderByBranch(true) orders by branch right to left');
}
public function testOrderByLevel()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree();
$t5->moveToPrevSiblingOf($t4);
/* Results in
t1
| \
t2 t3
| \
t5 t4
| \
t6 t7
*/
$objs = Table9Query::create()
->orderByLevel()
->find();
$coll = $this->buildCollection(array($t1, $t2, $t5, $t4, $t6, $t7), 'orderByLevel() orders by level, from the root to the leaf');
$objs = Table9Query::create()
->orderByLevel(true)
->find();
$coll = $this->buildCollection(array($t7, $t6, $t4, $t5, $t2, $t1), 'orderByLevel(true) orders by level, from the leaf to the root');
}
public function testFindRoot()
{
$this->assertTrue(method_exists('Table9Query', 'findRoot'), 'nested_set adds a findRoot() method');
Table9Query::create()->deleteAll();
$this->assertNull(Table9Query::create()->findRoot(), 'findRoot() returns null as long as no root node is defined');
$t1 = new Table9();
$t1->setLeftValue(123);
$t1->setRightValue(456);
$t1->save();
$this->assertNull(Table9Query::create()->findRoot(), 'findRoot() returns null as long as no root node is defined');
$t2 = new Table9();
$t2->setLeftValue(1);
$t2->setRightValue(2);
$t2->save();
$this->assertEquals(Table9Query::create()->findRoot(), $t2, 'findRoot() retrieves the root node');
}
public function testfindTree()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree();
$tree = Table9Query::create()->findTree();
$coll = $this->buildCollection(array($t1, $t2, $t3, $t4, $t5, $t6, $t7));
$this->assertEquals($coll, $tree, 'findTree() retrieves the whole tree, ordered by branch');
}
protected function buildCollection($arr)
{
$coll = new PropelObjectCollection();
$coll->setData($arr);
$coll->setModel('Table9');
return $coll;
}
}

View file

@ -0,0 +1,285 @@
<?php
/*
* $Id: NestedSetBehaviorQueryBuilderModifierTest.php 1347 2009-12-03 21:06:36Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/behavior/BookstoreNestedSetTestBase.php';
/**
* Tests for NestedSetBehaviorQueryBuilderModifier class with scope enabled
*
* @author François Zaninotto
* @version $Revision: 1612 $
* @package generator.behavior.nestedset
*/
class NestedSetBehaviorQueryBuilderModifierWithScopeTest extends BookstoreNestedSetTestBase
{
public function testTreeRoots()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$objs = Table10Query::create()
->treeRoots()
->find();
$coll = $this->buildCollection(array($t1, $t8));
$this->assertEquals($coll, $objs, 'treeRoots() filters by roots');
}
public function testInTree()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$tree = Table10Query::create()
->inTree(1)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t1, $t2, $t3, $t4, $t5, $t6, $t7));
$this->assertEquals($coll, $tree, 'inTree() filters by node');
$tree = Table10Query::create()
->inTree(2)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t8, $t9, $t10));
$this->assertEquals($coll, $tree, 'inTree() filters by node');
}
public function testDescendantsOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$objs = Table10Query::create()
->descendantsOf($t1)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t2, $t3, $t4, $t5, $t6, $t7));
$this->assertEquals($coll, $objs, 'decendantsOf() filters by descendants of the same scope');
}
public function testBranchOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$objs = Table10Query::create()
->branchOf($t1)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t1, $t2, $t3, $t4, $t5, $t6, $t7));
$this->assertEquals($coll, $objs, 'branchOf() filters by branch of the same scope');
}
public function testChildrenOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$objs = Table10Query::create()
->childrenOf($t1)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t2, $t3));
$this->assertEquals($coll, $objs, 'childrenOf() filters by children of the same scope');
}
public function testSiblingsOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$desc = Table10Query::create()
->siblingsOf($t3)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t2));
$this->assertEquals($coll, $desc, 'siblingsOf() returns filters by siblings of the same scope');
}
public function testAncestorsOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$objs = Table10Query::create()
->ancestorsOf($t5)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t1, $t3), 'ancestorsOf() filters by ancestors of the same scope');
}
public function testRootsOf()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$objs = Table10Query::create()
->rootsOf($t5)
->orderByBranch()
->find();
$coll = $this->buildCollection(array($t1, $t3, $t5), 'rootsOf() filters by ancestors of the same scope');
}
public function testFindRoot()
{
$this->assertTrue(method_exists('Table10Query', 'findRoot'), 'nested_set adds a findRoot() method');
Table10Query::create()->deleteAll();
$this->assertNull(Table10Query::create()->findRoot(1), 'findRoot() returns null as long as no root node is defined');
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$this->assertEquals($t1, Table10Query::create()->findRoot(1), 'findRoot() returns a tree root');
$this->assertEquals($t8, Table10Query::create()->findRoot(2), 'findRoot() returns a tree root');
}
public function testFindTree()
{
list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope();
/* Tree used for tests
Scope 1
t1
| \
t2 t3
| \
t4 t5
| \
t6 t7
Scope 2
t8
| \
t9 t10
*/
$tree = Table10Query::create()->findTree(1);
$coll = $this->buildCollection(array($t1, $t2, $t3, $t4, $t5, $t6, $t7));
$this->assertEquals($coll, $tree, 'findTree() retrieves the tree of a scope, ordered by branch');
$tree = Table10Query::create()->findTree(2);
$coll = $this->buildCollection(array($t8, $t9, $t10));
$this->assertEquals($coll, $tree, 'findTree() retrieves the tree of a scope, ordered by branch');
}
protected function buildCollection($arr)
{
$coll = new PropelObjectCollection();
$coll->setData($arr);
$coll->setModel('Table10');
return $coll;
}
}

View file

@ -0,0 +1,48 @@
<?php
/*
* $Id: NestedSetBehaviorTest.php 1612 2010-03-16 22:56:21Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests for NestedSetBehavior class
*
* @author François Zaninotto
* @version $Revision: 1612 $
* @package generator.behavior.nestedset
*/
class NestedSetBehaviorTest extends BookstoreTestBase
{
public function testDefault()
{
$table9 = Table9Peer::getTableMap();
$this->assertEquals(count($table9->getColumns()), 5, 'nested_set adds three column by default');
$this->assertTrue(method_exists('Table9', 'getTreeLeft'), 'nested_set adds a tree_left column by default');
$this->assertTrue(method_exists('Table9', 'getLeftValue'), 'nested_set maps the left_value getter with the tree_left column');
$this->assertTrue(method_exists('Table9', 'getTreeRight'), 'nested_set adds a tree_right column by default');
$this->assertTrue(method_exists('Table9', 'getRightValue'), 'nested_set maps the right_value getter with the tree_right column');
$this->assertTrue(method_exists('Table9', 'getTreeLevel'), 'nested_set adds a tree_level column by default');
$this->assertTrue(method_exists('Table9', 'getLevel'), 'nested_set maps the level getter with the tree_level column');
$this->assertFalse(method_exists('Table9', 'getTreeScope'), 'nested_set does not add a tree_scope column by default');
$this->assertFalse(method_exists('Table9', 'getScopeValue'), 'nested_set does not map the scope_value getter with the tree_scope column by default');
}
public function testParameters()
{
$table10 = Table10Peer::getTableMap();
$this->assertEquals(count($table10->getColumns()), 6, 'nested_set does not add columns when they already exist');
$this->assertTrue(method_exists('Table10', 'getLeftValue'), 'nested_set maps the left_value getter with the tree_left column');
$this->assertTrue(method_exists('Table10', 'getRightValue'), 'nested_set maps the right_value getter with the tree_right column');
$this->assertTrue(method_exists('Table10', 'getLevel'), 'nested_set maps the level getter with the tree_level column');
$this->assertTrue(method_exists('Table10', 'getScopeValue'), 'nested_set maps the scope_value getter with the tree_scope column when the use_scope parameter is true');
}
}

View file

@ -0,0 +1,299 @@
<?php
/*
* $Id: TimestampableBehaviorTest.php 1460 2010-01-17 22:36:48Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests for SluggableBehavior class
*
* @author François Zaninotto
* @version $Revision: 1629 $
* @package generator.behavior.sluggable
*/
class SluggableBehaviorTest extends BookstoreTestBase
{
public function testParameters()
{
$table13 = Table13Peer::getTableMap();
$this->assertEquals(count($table13->getColumns()), 3, 'Sluggable adds one columns by default');
$this->assertTrue(method_exists('Table13', 'getSlug'), 'Sluggable adds a slug column by default');
$table14 = Table14Peer::getTableMap();
$this->assertEquals(count($table14->getColumns()), 3, 'Sluggable does not add a column when it already exists');
$this->assertTrue(method_exists('Table14', 'getUrl'), 'Sluggable allows customization of slug_column name');
$this->assertTrue(method_exists('Table14', 'getSlug'), 'Sluggable adds a standard getter for the slug column');
}
public function testObjectGetter()
{
$this->assertTrue(method_exists('Table13', 'getSlug'), 'Sluggable adds a getter for the slug column');
$t = new Table13();
$t->setSlug('foo');
$this->assertEquals('foo', $t->getSlug(), 'getSlug() returns the object slug');
$this->assertTrue(method_exists('Table14', 'getSlug'), 'Sluggable adds a getter for the slug column, even if the column does not have the default name');
$t = new Table14();
$t->setUrl('foo');
$this->assertEquals('foo', $t->getSlug(), 'getSlug() returns the object slug');
}
public function testObjectSetter()
{
$this->assertTrue(method_exists('Table13', 'setSlug'), 'Sluggable adds a setter for the slug column');
$t = new Table13();
$t->setSlug('foo');
$this->assertEquals('foo', $t->getSlug(), 'setSlug() sets the object slug');
$this->assertTrue(method_exists('Table14', 'setSlug'), 'Sluggable adds a setter for the slug column, even if the column does not have the default name');
$t = new Table14();
$t->setSlug('foo');
$this->assertEquals('foo', $t->getUrl(), 'setSlug() sets the object slug');
}
public function testObjectCreateRawSlug()
{
$t = new TestableTable13();
$this->assertEquals('n-a', $t->createRawSlug(), 'createRawSlug() returns an empty string for an empty object with no pattern');
$t->setTitle('Hello, World');
$this->assertEquals('hello-world', $t->createRawSlug(), 'createRawSlug() returns the cleaned up object string representation by default');
$t = new TestableTable14();
$this->assertEquals('/foo/n-a/bar', $t->createRawSlug(), 'createRawSlug() returns a slug for an empty object with a pattern');
$t->setTitle('Hello, World');
$this->assertEquals('/foo/hello-world/bar', $t->createRawSlug(), 'createRawSlug() returns a slug based on a pattern');
}
public static function cleanupSlugProvider()
{
return array(
array('', 'n-a'),
array('foo', 'foo'),
array('foo bar', 'foo-bar'),
array('foo bar', 'foo-bar'),
array('FoO', 'foo'),
array('fôo', 'foo'),
array(' foo ', 'foo'),
array('f/o:o', 'f-o-o'),
array('foo1', 'foo1'),
);
}
/**
* @dataProvider cleanupSlugProvider
*/
public function testObjectCleanupSlugPart($in, $out)
{
$t = new TestableTable13();
$this->assertEquals($out, $t->cleanupSlugPart($in), 'cleanupSlugPart() cleans up the slug part');
}
public static function limitSlugSizeProvider()
{
return array(
array('123', '123'),
array(str_repeat('*', 80), str_repeat('*', 80)),
array(str_repeat('*', 97), str_repeat('*', 97)),
array(str_repeat('*', 98), str_repeat('*', 97)),
array(str_repeat('*', 99), str_repeat('*', 97)),
array(str_repeat('*', 100), str_repeat('*', 97)),
array(str_repeat('*', 150), str_repeat('*', 97)),
);
}
/**
* @dataProvider limitSlugSizeProvider
*/
public function testObjectLimitSlugSize($in, $out)
{
$t = new TestableTable14();
$this->assertEquals($out, $t->limitSlugSize($in), 'limitSlugsize() limits the slug size');
}
public function testObjectMakeSlugUnique()
{
Table13Query::create()->deleteAll();
$t = new TestableTable13();
$this->assertEquals('', $t->makeSlugUnique(''), 'makeSlugUnique() returns the input slug when the input is empty');
$this->assertEquals('foo', $t->makeSlugUnique('foo'), 'makeSlugUnique() returns the input slug when the table is empty');
$t->setSlug('foo');
$t->save();
$t = new TestableTable13();
$this->assertEquals('bar', $t->makeSlugUnique('bar'), 'makeSlugUnique() returns the input slug when the table does not contain a similar slug');
$t->save();
$t = new TestableTable13();
$this->assertEquals('foo-1', $t->makeSlugUnique('foo'), 'makeSlugUnique() returns an incremented input when it already exists');
$t->setSlug('foo-1');
$t->save();
$t = new TestableTable13();
$this->assertEquals('foo-2', $t->makeSlugUnique('foo'), 'makeSlugUnique() returns an incremented input when it already exists');
}
public function testObjectCreateSlug()
{
Table13Query::create()->deleteAll();
$t = new TestableTable13();
$this->assertEquals('n-a', $t->createSlug(), 'createSlug() returns n-a for an empty object');
$t->setTitle('Hello, World!');
$this->assertEquals('hello-world', $t->createSlug(), 'createSlug() returns a cleaned up slug');
$t->setSlug('hello-world');
$t->save();
$t = new TestableTable13();
$t->setTitle('Hello; wOrld');
$this->assertEquals('hello-world-1', $t->createSlug(), 'createSlug() returns a unique slug');
Table14Query::create()->deleteAll();
$t = new TestableTable14();
$this->assertEquals('/foo/n-a/bar', $t->createSlug(), 'createSlug() returns a slug for an empty object with a pattern');
$t->setTitle('Hello, World!');
$this->assertEquals('/foo/hello-world/bar', $t->createSlug(), 'createSlug() returns a cleaned up slug');
$t->setSlug('/foo/hello-world/bar');
$t->save();
$t = new TestableTable14();
$t->setTitle('Hello; wOrld:');
$this->assertEquals('/foo/hello-world/bar/1', $t->createSlug(), 'createSlug() returns a unique slug');
}
public function testObjectPreSave()
{
Table14Query::create()->deleteAll();
$t = new Table14();
$t->save();
$this->assertEquals('/foo/n-a/bar', $t->getSlug(), 'preSave() sets a default slug for empty objects');
$t = new Table14();
$t->setTitle('Hello, World');
$t->save();
$this->assertEquals('/foo/hello-world/bar', $t->getSlug(), 'preSave() sets a cleanued up slug for objects');
$t = new Table14();
$t->setTitle('Hello, World');
$t->save();
$this->assertEquals('/foo/hello-world/bar/1', $t->getSlug(), 'preSave() sets a unique slug for objects');
$t = new Table14();
$t->setTitle('Hello, World');
$t->setSlug('/foo/custom/bar');
$t->save();
$this->assertEquals('/foo/custom/bar', $t->getSlug(), 'preSave() uses the given slug if it exists');
$t = new Table14();
$t->setTitle('Hello, World');
$t->setSlug('/foo/custom/bar');
$t->save();
$this->assertEquals('/foo/custom/bar/1', $t->getSlug(), 'preSave() uses the given slug if it exists and makes it unique');
}
public function testObjectSlugLifecycle()
{
Table13Query::create()->deleteAll();
$t = new Table13();
$t->setTitle('Hello, World');
$t->save();
$this->assertEquals('hello-world', $t->getSlug(), 'preSave() creates a slug for new objects');
$t->setSlug('hello-bar');
$t->save();
$this->assertEquals('hello-bar', $t->getSlug(), 'setSlug() allows to override default slug');
$t->setSlug('');
$t->save();
$this->assertEquals('hello-world', $t->getSlug(), 'setSlug(null) relaunches the slug generation');
Table14Query::create()->deleteAll();
$t = new Table14();
$t->setTitle('Hello, World2');
$t->setSlug('hello-bar2');
$t->save();
$this->assertEquals('hello-bar2', $t->getSlug(), 'setSlug() allows to override default slug, even before save');
$t->setSlug('');
$t->save();
$this->assertEquals('/foo/hello-world2/bar', $t->getSlug(), 'setSlug(null) relaunches the slug generation');
}
public function testObjectSlugAutoUpdate()
{
Table13Query::create()->deleteAll();
$t = new Table13();
$t->setTitle('Hello, World');
$t->save();
$this->assertEquals('hello-world', $t->getSlug(), 'preSave() creates a slug for new objects');
$t->setTitle('Hello, My World');
$t->save();
$this->assertEquals('hello-my-world', $t->getSlug(), 'preSave() autoupdates slug on object change');
$t->setTitle('Hello, My Whole New World');
$t->setSlug('hello-bar');
$t->save();
$this->assertEquals('hello-bar', $t->getSlug(), 'preSave() does not autoupdate slug when it was set by the user');
}
public function testObjectSlugAutoUpdatePermanent()
{
Table14Query::create()->deleteAll();
$t = new Table14();
$t->setTitle('Hello, World');
$t->save();
$this->assertEquals('/foo/hello-world/bar', $t->getSlug(), 'preSave() creates a slug for new objects');
$t->setTitle('Hello, My World');
$t->save();
$this->assertEquals('/foo/hello-world/bar', $t->getSlug(), 'preSave() does not autoupdate slug on object change for permanent slugs');
$t->setSlug('hello-bar');
$t->save();
$this->assertEquals('hello-bar', $t->getSlug(), 'setSlug() still works for permanent slugs');
}
public function testQueryFindOneBySlug()
{
$this->assertTrue(method_exists('Table13Query', 'findOneBySlug'), 'The generated query provides a findOneBySlug() method');
$this->assertTrue(method_exists('Table14Query', 'findOneBySlug'), 'The generated query provides a findOneBySlug() method even if the slug column doesnt have the default name');
Table14Query::create()->deleteAll();
$t1 = new Table14();
$t1->setTitle('Hello, World');
$t1->save();
$t2 = new Table14();
$t2->setTitle('Hello, Cruel World');
$t2->save();
$t = Table14Query::create()->findOneBySlug('/foo/hello-world/bar');
$this->assertEquals($t1, $t, 'findOneBySlug() returns a single object matching the slug');
}
}
class TestableTable13 extends Table13
{
public function createSlug()
{
return parent::createSlug();
}
public function createRawSlug()
{
return parent::createRawSlug();
}
public static function cleanupSlugPart($slug, $separator = '-')
{
return parent::cleanupSlugPart($slug, $separator);
}
public function makeSlugUnique($slug, $separator = '-', $increment = 0)
{
return parent::makeSlugUnique($slug, $separator, $increment);
}
}
class TestableTable14 extends Table14
{
public function createSlug()
{
return parent::createSlug();
}
public function createRawSlug()
{
return parent::createRawSlug();
}
public static function limitSlugSize($slug, $incrementReservedSpace = 3)
{
return parent::limitSlugSize($slug, $incrementReservedSpace);
}
}

View file

@ -0,0 +1,279 @@
<?php
/*
* $Id: SortableBehaviorTest.php 1356 2009-12-11 16:36:55Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/behavior/BookstoreSortableTestBase.php';
/**
* Tests for SortableBehavior class
*
* @author Massimiliano Arione
* @version $Revision: 1612 $
* @package generator.behavior.sortable
*/
class SortableBehaviorObjectBuilderModifierTest extends BookstoreSortableTestBase
{
protected function setUp()
{
parent::setUp();
$this->populateTable11();
}
public function testPreInsert()
{
Table11Peer::doDeleteAll();
$t1 = new Table11();
$t1->save();
$this->assertEquals($t1->getRank(), 1, 'Sortable inserts new line in first position if no row present');
$t2 = new Table11();
$t2->setTitle('row2');
$t2->save();
$this->assertEquals($t2->getRank(), 2, 'Sortable inserts new line in last position');
}
public function testPreDelete()
{
$max = Table11Peer::getMaxRank();
$t3 = Table11Peer::retrieveByRank(3);
$t3->delete();
$this->assertEquals($max - 1, Table11Peer::getMaxRank(), 'Sortable rearrange subsequent rows on delete');
$c = new Criteria();
$c->add(Table11Peer::TITLE, 'row4');
$t4 = Table11Peer::doSelectOne($c);
$this->assertEquals(3, $t4->getRank(), 'Sortable rearrange subsequent rows on delete');
}
public function testIsFirst()
{
$first = Table11Peer::retrieveByRank(1);
$middle = Table11Peer::retrieveByRank(2);
$last = Table11Peer::retrieveByRank(4);
$this->assertTrue($first->isFirst(), 'isFirst() returns true for the first in the rank');
$this->assertFalse($middle->isFirst(), 'isFirst() returns false for a middle rank');
$this->assertFalse($last->isFirst(), 'isFirst() returns false for the last in the rank');
}
public function testIsLast()
{
$first = Table11Peer::retrieveByRank(1);
$middle = Table11Peer::retrieveByRank(2);
$last = Table11Peer::retrieveByRank(4);
$this->assertFalse($first->isLast(), 'isLast() returns false for the first in the rank');
$this->assertFalse($middle->isLast(), 'isLast() returns false for a middle rank');
$this->assertTrue($last->isLast(), 'isLast() returns true for the last in the rank');
}
public function testGetNext()
{
$t = Table11Peer::retrieveByRank(3);
$this->assertEquals(4, $t->getNext()->getRank(), 'getNext() returns the next object in rank');
$t = Table11Peer::retrieveByRank(4);
$this->assertNull($t->getNext(), 'getNext() returns null for the last object');
}
public function testGetPrevious()
{
$t = Table11Peer::retrieveByRank(3);
$this->assertEquals(2, $t->getPrevious()->getRank(), 'getPrevious() returns the previous object in rank');
$t = Table11Peer::retrieveByRank(1);
$this->assertNull($t->getPrevious(), 'getPrevious() returns null for the first object');
}
public function testInsertAtRank()
{
$t = new Table11();
$t->setTitle('new');
$t->insertAtRank(2);
$this->assertEquals(2, $t->getRank(), 'insertAtRank() sets the position');
$this->assertTrue($t->isNew(), 'insertAtRank() doesn\'t save the object');
$t->save();
$expected = array(1 => 'row1', 2 => 'new', 3 => 'row2', 4 => 'row3', 5 => 'row4');
$this->assertEquals($expected, $this->getFixturesArray(), 'insertAtRank() shifts the entire suite');
}
public function testInsertAtMaxRankPlusOne()
{
$t = new Table11();
$t->setTitle('new');
$t->insertAtRank(5);
$this->assertEquals(5, $t->getRank(), 'insertAtRank() sets the position');
$t->save();
$expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4', 5 => 'new');
$this->assertEquals($expected, $this->getFixturesArray(), 'insertAtRank() can insert an object at the end of the list');
}
/**
* @expectedException PropelException
*/
public function testInsertAtNegativeRank()
{
$t = new Table11();
$t->insertAtRank(0);
}
/**
* @expectedException PropelException
*/
public function testInsertAtOverMaxRank()
{
$t = new Table11();
$t->insertAtRank(6);
}
public function testInsertAtBottom()
{
$t = new Table11();
$t->setTitle('new');
$t->insertAtBottom();
$this->assertEquals(5, $t->getRank(), 'insertAtBottom() sets the position to the last');
$this->assertTrue($t->isNew(), 'insertAtBottom() doesn\'t save the object');
$t->save();
$expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4', 5 => 'new');
$this->assertEquals($expected, $this->getFixturesArray(), 'insertAtBottom() does not shift the entire suite');
}
public function testInsertAtTop()
{
$t = new Table11();
$t->setTitle('new');
$t->insertAtTop();
$this->assertEquals(1, $t->getRank(), 'insertAtTop() sets the position to 1');
$this->assertTrue($t->isNew(), 'insertAtTop() doesn\'t save the object');
$t->save();
$expected = array(1 => 'new', 2 => 'row1', 3 => 'row2', 4 => 'row3', 5 => 'row4');
$this->assertEquals($expected, $this->getFixturesArray(), 'insertAtTop() shifts the entire suite');
}
public function testMoveToRank()
{
$t2 = Table11Peer::retrieveByRank(2);
$t2->moveToRank(3);
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArray(), 'moveToRank() can move up');
$t2->moveToRank(1);
$expected = array(1 => 'row2', 2 => 'row1', 3 => 'row3', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArray(), 'moveToRank() can move to the first rank');
$t2->moveToRank(4);
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
$this->assertEquals($expected, $this->getFixturesArray(), 'moveToRank() can move to the last rank');
$t2->moveToRank(2);
$expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArray(), 'moveToRank() can move down');
}
/**
* @expectedException PropelException
*/
public function testMoveToNewObject()
{
$t = new Table11();
$t->moveToRank(2);
}
/**
* @expectedException PropelException
*/
public function testMoveToNegativeRank()
{
$t = Table11Peer::retrieveByRank(2);
$t->moveToRank(0);
}
/**
* @expectedException PropelException
*/
public function testMoveToOverMaxRank()
{
$t = Table11Peer::retrieveByRank(2);
$t->moveToRank(5);
}
public function testSwapWith()
{
$t2 = Table11Peer::retrieveByRank(2);
$t4 = Table11Peer::retrieveByRank(4);
$t2->swapWith($t4);
$expected = array(1 => 'row1', 2 => 'row4', 3 => 'row3', 4 => 'row2');
$this->assertEquals($expected, $this->getFixturesArray(), 'swapWith() swaps ranks of the two objects and leaves the other ranks unchanged');
}
public function testMoveUp()
{
$t3 = Table11Peer::retrieveByRank(3);
$res = $t3->moveUp();
$this->assertEquals($t3, $res, 'moveUp() returns the current object');
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArray(), 'moveUp() swaps ranks with the object of higher rank');
$t3->moveUp();
$expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArray(), 'moveUp() swaps ranks with the object of higher rank');
$res = $t3->moveUp();
$expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArray(), 'moveUp() changes nothing when called on the object at the top');
}
public function testMoveDown()
{
$t2 = Table11Peer::retrieveByRank(2);
$res = $t2->moveDown();
$this->assertEquals($t2, $res, 'moveDown() returns the current object');
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArray(), 'moveDown() swaps ranks with the object of lower rank');
$t2->moveDown();
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
$this->assertEquals($expected, $this->getFixturesArray(), 'moveDown() swaps ranks with the object of lower rank');
$res = $t2->moveDown();
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
$this->assertEquals($expected, $this->getFixturesArray(), 'moveDown() changes nothing when called on the object at the bottom');
}
public function testMoveToTop()
{
$t3 = Table11Peer::retrieveByRank(3);
$res = $t3->moveToTop();
$this->assertEquals($t3, $res, 'moveToTop() returns the current oobject');
$expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArray(), 'moveToTop() moves to the top');
$res = $t3->moveToTop();
$expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArray(), 'moveToTop() changes nothing when called on the top node');
}
public function testMoveToBottom()
{
$t2 = Table11Peer::retrieveByRank(2);
$res = $t2->moveToBottom();
$this->assertEquals($t2, $res, 'moveToBottom() returns the current object');
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
$this->assertEquals($expected, $this->getFixturesArray(), 'moveToBottom() moves to the bottom');
$res = $t2->moveToBottom();
$this->assertFalse($res, 'moveToBottom() returns false when called on the bottom node');
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
$this->assertEquals($expected, $this->getFixturesArray(), 'moveToBottom() changes nothing when called on the bottom node');
}
public function testRemoveFromList()
{
$t2 = Table11Peer::retrieveByRank(2);
$res = $t2->removeFromList();
$this->assertTrue($res instanceof Table11, 'removeFromList() returns the current object');
$this->assertNull($res->getRank(), 'removeFromList() resets the object\'s rank');
Table11Peer::clearInstancePool();
$expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArray(), 'removeFromList() does not change the list until the object is saved');
$t2->save();
Table11Peer::clearInstancePool();
$expected = array(null => 'row2', 1 => 'row1', 2 => 'row3', 3 => 'row4');
$this->assertEquals($expected, $this->getFixturesArray(), 'removeFromList() changes the list once the object is saved');
}
}

View file

@ -0,0 +1,335 @@
<?php
/*
* $Id: SortableBehaviorTest.php 1356 2009-12-11 16:36:55Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/behavior/BookstoreSortableTestBase.php';
/**
* Tests for SortableBehavior class
*
* @author Massimiliano Arione
* @version $Revision: 1612 $
* @package generator.behavior.sortable
*/
class SortableBehaviorObjectBuilderModifierWithScopeTest extends BookstoreSortableTestBase
{
protected function setUp()
{
parent::setUp();
$this->populateTable12();
}
public function testPreInsert()
{
Table12Peer::doDeleteAll();
$t1 = new Table12();
$t1->setScopeValue(1);
$t1->save();
$this->assertEquals($t1->getRank(), 1, 'Sortable inserts new line in first position if no row present');
$t2 = new Table12();
$t2->setScopeValue(1);
$t2->save();
$this->assertEquals($t2->getRank(), 2, 'Sortable inserts new line in last position');
$t2 = new Table12();
$t2->setScopeValue(2);
$t2->save();
$this->assertEquals($t2->getRank(), 1, 'Sortable inserts new line in last position');
}
public function testPreDelete()
{
$max = Table12Peer::getMaxRank(1);
$t3 = Table12Peer::retrieveByRank(3, 1);
$t3->delete();
$this->assertEquals($max - 1, Table12Peer::getMaxRank(1), 'Sortable rearrange subsequent rows on delete');
$c = new Criteria();
$c->add(Table12Peer::TITLE, 'row4');
$t4 = Table12Peer::doSelectOne($c);
$this->assertEquals(3, $t4->getRank(), 'Sortable rearrange subsequent rows on delete');
$expected = array(1 => 'row5', 2 => 'row6');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'delete() leaves other suites unchanged');
}
public function testIsFirst()
{
$first = Table12Peer::retrieveByRank(1, 1);
$middle = Table12Peer::retrieveByRank(2, 1);
$last = Table12Peer::retrieveByRank(4, 1);
$this->assertTrue($first->isFirst(), 'isFirst() returns true for the first in the rank');
$this->assertFalse($middle->isFirst(), 'isFirst() returns false for a middle rank');
$this->assertFalse($last->isFirst(), 'isFirst() returns false for the last in the rank');
$first = Table12Peer::retrieveByRank(1, 2);
$last = Table12Peer::retrieveByRank(2, 2);
$this->assertTrue($first->isFirst(), 'isFirst() returns true for the first in the rank');
$this->assertFalse($last->isFirst(), 'isFirst() returns false for the last in the rank');
}
public function testIsLast()
{
$first = Table12Peer::retrieveByRank(1, 1);
$middle = Table12Peer::retrieveByRank(2, 1);
$last = Table12Peer::retrieveByRank(4, 1);
$this->assertFalse($first->isLast(), 'isLast() returns false for the first in the rank');
$this->assertFalse($middle->isLast(), 'isLast() returns false for a middle rank');
$this->assertTrue($last->isLast(), 'isLast() returns true for the last in the rank');
$first = Table12Peer::retrieveByRank(1, 2);
$last = Table12Peer::retrieveByRank(2, 2);
$this->assertFalse($first->isLast(), 'isLast() returns false for the first in the rank');
$this->assertTrue($last->isLast(), 'isLast() returns true for the last in the rank');
}
public function testGetNext()
{
$t = Table12Peer::retrieveByRank(1, 1);
$this->assertEquals('row2', $t->getNext()->getTitle(), 'getNext() returns the next object in rank in the same suite');
$t = Table12Peer::retrieveByRank(1, 2);
$this->assertEquals('row6', $t->getNext()->getTitle(), 'getNext() returns the next object in rank in the same suite');
$t = Table12Peer::retrieveByRank(3, 1);
$this->assertEquals(4, $t->getNext()->getRank(), 'getNext() returns the next object in rank');
$t = Table12Peer::retrieveByRank(4, 1);
$this->assertNull($t->getNext(), 'getNext() returns null for the last object');
}
public function testGetPrevious()
{
$t = Table12Peer::retrieveByRank(2, 1);
$this->assertEquals('row1', $t->getPrevious()->getTitle(), 'getPrevious() returns the previous object in rank in the same suite');
$t = Table12Peer::retrieveByRank(2, 2);
$this->assertEquals('row5', $t->getPrevious()->getTitle(), 'getPrevious() returns the previous object in rank in the same suite');
$t = Table12Peer::retrieveByRank(3, 1);
$this->assertEquals(2, $t->getPrevious()->getRank(), 'getPrevious() returns the previous object in rank');
$t = Table12Peer::retrieveByRank(1, 1);
$this->assertNull($t->getPrevious(), 'getPrevious() returns null for the first object');
}
public function testInsertAtRank()
{
$t = new Table12();
$t->setTitle('new');
$t->setScopeValue(1);
$t->insertAtRank(2);
$this->assertEquals(2, $t->getRank(), 'insertAtRank() sets the position');
$this->assertTrue($t->isNew(), 'insertAtTop() doesn\'t save the object');
$t->save();
$expected = array(1 => 'row1', 2 => 'new', 3 => 'row2', 4 => 'row3', 5 => 'row4');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'insertAtRank() shifts the entire suite');
$expected = array(1 => 'row5', 2 => 'row6');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'insertAtRank() leaves other suites unchanged');
}
/**
* @expectedException PropelException
*/
public function testInsertAtNegativeRank()
{
$t = new Table12();
$t->setScopeValue(1);
$t->insertAtRank(0);
}
/**
* @expectedException PropelException
*/
public function testInsertAtOverMaxRank()
{
$t = new Table12();
$t->setScopeValue(1);
$t->insertAtRank(6);
}
/**
* @expectedException PropelException
*/
public function testInsertAtNoScope()
{
$t = new Table12();
$t->insertAtRank(3);
}
public function testInsertAtBottom()
{
$t = new Table12();
$t->setTitle('new');
$t->setScopeValue(1);
$t->insertAtBottom();
$this->assertEquals(5, $t->getRank(), 'insertAtBottom() sets the position to the last');
$this->assertTrue($t->isNew(), 'insertAtTop() doesn\'t save the object');
$t->save();
$expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4', 5 => 'new');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'insertAtBottom() does not shift the entire suite');
$expected = array(1 => 'row5', 2 => 'row6');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'insertAtBottom() leaves other suites unchanged');
}
/**
* @expectedException PropelException
*/
public function testInsertAtBottomNoScope()
{
$t = new Table12();
$t->insertAtBottom();
}
public function testInsertAtTop()
{
$t = new Table12();
$t->setTitle('new');
$t->setScopeValue(1);
$t->insertAtTop();
$this->assertEquals(1, $t->getRank(), 'insertAtTop() sets the position to 1');
$this->assertTrue($t->isNew(), 'insertAtTop() doesn\'t save the object');
$t->save();
$expected = array(1 => 'new', 2 => 'row1', 3 => 'row2', 4 => 'row3', 5 => 'row4');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'insertAtTop() shifts the entire suite');
$expected = array(1 => 'row5', 2 => 'row6');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'insertAtTop() leaves other suites unchanged');
}
public function testMoveToRank()
{
$t2 = Table12Peer::retrieveByRank(2, 1);
$t2->moveToRank(3);
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToRank() can move up');
$expected = array(1 => 'row5', 2 => 'row6');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'moveToRank() leaves other suites unchanged');
$t2->moveToRank(1);
$expected = array(1 => 'row2', 2 => 'row1', 3 => 'row3', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToRank() can move to the first rank');
$t2->moveToRank(4);
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToRank() can move to the last rank');
$t2->moveToRank(2);
$expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToRank() can move down');
}
/**
* @expectedException PropelException
*/
public function testMoveToNewObject()
{
$t = new Table12();
$t->moveToRank(2);
}
/**
* @expectedException PropelException
*/
public function testMoveToNegativeRank()
{
$t = Table12Peer::retrieveByRank(2, 1);
$t->moveToRank(0);
}
/**
* @expectedException PropelException
*/
public function testMoveToOverMaxRank()
{
$t = Table12Peer::retrieveByRank(2, 1);
$t->moveToRank(5);
}
public function testSwapWith()
{
$t2 = Table12Peer::retrieveByRank(2, 1);
$t4 = Table12Peer::retrieveByRank(4, 1);
$t2->swapWith($t4);
$expected = array(1 => 'row1', 2 => 'row4', 3 => 'row3', 4 => 'row2');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'swapWith() swaps ranks of the two objects and leaves the other ranks unchanged');
$expected = array(1 => 'row5', 2 => 'row6');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'swapWith() leaves other suites unchanged');
}
public function testMoveUp()
{
$t3 = Table12Peer::retrieveByRank(3, 1);
$res = $t3->moveUp();
$this->assertEquals($t3, $res, 'moveUp() returns the current object');
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveUp() swaps ranks with the object of higher rank');
$expected = array(1 => 'row5', 2 => 'row6');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'moveUp() leaves other suites unchanged');
$t3->moveUp();
$expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveUp() swaps ranks with the object of higher rank');
$res = $t3->moveUp();
$expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveUp() changes nothing when called on the object at the top');
}
public function testMoveDown()
{
$t2 = Table12Peer::retrieveByRank(2, 1);
$res = $t2->moveDown();
$this->assertEquals($t2, $res, 'moveDown() returns the current object');
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row2', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveDown() swaps ranks with the object of lower rank');
$expected = array(1 => 'row5', 2 => 'row6');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'moveDown() leaves other suites unchanged');
$t2->moveDown();
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveDown() swaps ranks with the object of lower rank');
$res = $t2->moveDown();
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveDown() changes nothing when called on the object at the bottom');
}
public function testMoveToTop()
{
$t3 = Table12Peer::retrieveByRank(3, 1);
$res = $t3->moveToTop();
$this->assertEquals($t3, $res, 'moveToTop() returns the current object');
$expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToTop() moves to the top');
$expected = array(1 => 'row5', 2 => 'row6');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'moveToTop() leaves other suites unchanged');
$res = $t3->moveToTop();
$expected = array(1 => 'row3', 2 => 'row1', 3 => 'row2', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToTop() changes nothing when called on the top node');
}
public function testMoveToBottom()
{
$t2 = Table12Peer::retrieveByRank(2, 1);
$res = $t2->moveToBottom();
$this->assertEquals($t2, $res, 'moveToBottom() returns the current object');
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToBottom() moves to the bottom');
$expected = array(1 => 'row5', 2 => 'row6');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'moveToBottom() leaves other suites unchanged');
$res = $t2->moveToBottom();
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'moveToBottom() changes nothing when called on the bottom node');
}
public function testRemoveFromList()
{
$t2 = Table12Peer::retrieveByRank(2, 1);
$res = $t2->removeFromList();
$this->assertTrue($res instanceof Table12, 'removeFromList() returns the current object');
$this->assertNull($res->getRank(), 'removeFromList() resets the object\'s rank');
Table12Peer::clearInstancePool();
$expected = array(1 => 'row1', 2 => 'row2', 3 => 'row3', 4 => 'row4');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'removeFromList() does not change the list until the object is saved');
$t2->save();
Table12Peer::clearInstancePool();
$expected = array(1 => 'row1', 2 => 'row3', 3 => 'row4');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'removeFromList() changes the list once the object is saved');
$expected = array(1 => 'row5', 2 => 'row6');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'removeFromList() leaves other suites unchanged');
}
}

View file

@ -0,0 +1,83 @@
<?php
/*
* $Id: SortableBehaviorTest.php 1356 2009-12-11 16:36:55Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/behavior/BookstoreSortableTestBase.php';
/**
* Tests for SortableBehavior class
*
* @author Massimiliano Arione
* @version $Revision: 1612 $
* @package generator.behavior.sortable
*/
class SortableBehaviorPeerBuilderModifierTest extends BookstoreSortableTestBase
{
protected function setUp()
{
parent::setUp();
$this->populateTable11();
}
public function testStaticAttributes()
{
$this->assertEquals(Table11Peer::RANK_COL, 'table11.SORTABLE_RANK');
}
public function testGetMaxRank()
{
$this->assertEquals(4, Table11Peer::getMaxRank(), 'getMaxRank() returns the maximum rank');
$t4 = Table11Peer::retrieveByRank(4);
$t4->delete();
$this->assertEquals(3, Table11Peer::getMaxRank(), 'getMaxRank() returns the maximum rank');
Table11Peer::doDeleteAll();
$this->assertNull(Table11Peer::getMaxRank(), 'getMaxRank() returns null for empty tables');
}
public function testRetrieveByRank()
{
$t = Table11Peer::retrieveByRank(5);
$this->assertNull($t, 'retrieveByRank() returns null for an unknown rank');
$t3 = Table11Peer::retrieveByRank(3);
$this->assertEquals(3, $t3->getRank(), 'retrieveByRank() returns the object with the required rank');
$this->assertEquals('row3', $t3->getTitle(), 'retrieveByRank() returns the object with the required rank');
}
public function testReorder()
{
$objects = Table11Peer::doSelect(new Criteria());
$ids = array();
foreach ($objects as $object) {
$ids[]= $object->getPrimaryKey();
}
$ranks = array(4, 3, 2, 1);
$order = array_combine($ids, $ranks);
Table11Peer::reorder($order);
$expected = array(1 => 'row3', 2 => 'row2', 3 => 'row4', 4 => 'row1');
$this->assertEquals($expected, $this->getFixturesArray(), 'reorder() reorders the suite');
}
public function testDoSelectOrderByRank()
{
$objects = Table11Peer::doSelectOrderByRank();
$oldRank = 0;
while ($object = array_shift($objects)) {
$this->assertTrue($object->getRank() > $oldRank);
$oldRank = $object->getRank();
}
$objects = Table11Peer::doSelectOrderByRank(null, Criteria::DESC);
$oldRank = 10;
while ($object = array_shift($objects)) {
$this->assertTrue($object->getRank() < $oldRank);
$oldRank = $object->getRank();
}
}
}

View file

@ -0,0 +1,114 @@
<?php
/*
* $Id: SortableBehaviorTest.php 1356 2009-12-11 16:36:55Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/behavior/BookstoreSortableTestBase.php';
/**
* Tests for SortableBehavior class
*
* @author Massimiliano Arione
* @version $Revision: 1612 $
* @package generator.behavior.sortable
*/
class SortableBehaviorPeerBuilderModifierWithScopeTest extends BookstoreSortableTestBase
{
protected function setUp()
{
parent::setUp();
$this->populateTable12();
}
public function testStaticAttributes()
{
$this->assertEquals(Table12Peer::RANK_COL, 'table12.POSITION');
$this->assertEquals(Table12Peer::SCOPE_COL, 'table12.MY_SCOPE_COLUMN');
}
public function testGetMaxRank()
{
$this->assertEquals(4, Table12Peer::getMaxRank(1), 'getMaxRank() returns the maximum rank of the suite');
$this->assertEquals(2, Table12Peer::getMaxRank(2), 'getMaxRank() returns the maximum rank of the suite');
$t4 = Table12Peer::retrieveByRank(4, 1);
$t4->delete();
$this->assertEquals(3, Table12Peer::getMaxRank(1), 'getMaxRank() returns the maximum rank');
Table12Peer::doDeleteAll();
$this->assertNull(Table12Peer::getMaxRank(1), 'getMaxRank() returns null for empty tables');
}
public function testRetrieveByRank()
{
$t = Table12Peer::retrieveByRank(5, 1);
$this->assertNull($t, 'retrieveByRank() returns null for an unknown rank');
$t3 = Table12Peer::retrieveByRank(3, 1);
$this->assertEquals(3, $t3->getRank(), 'retrieveByRank() returns the object with the required rank in the required suite');
$this->assertEquals('row3', $t3->getTitle(), 'retrieveByRank() returns the object with the required rank in the required suite');
$t6 = Table12Peer::retrieveByRank(2, 2);
$this->assertEquals(2, $t6->getRank(), 'retrieveByRank() returns the object with the required rank in the required suite');
$this->assertEquals('row6', $t6->getTitle(), 'retrieveByRank() returns the object with the required rank in the required suite');
}
public function testReorder()
{
$c = new Criteria();
$c->add(Table12Peer::SCOPE_COL, 1);
$objects = Table12Peer::doSelectOrderByRank($c);
$ids = array();
foreach ($objects as $object) {
$ids[]= $object->getPrimaryKey();
}
$ranks = array(4, 3, 2, 1);
$order = array_combine($ids, $ranks);
Table12Peer::reorder($order);
$expected = array(1 => 'row4', 2 => 'row3', 3 => 'row2', 4 => 'row1');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'reorder() reorders the suite');
$expected = array(1 => 'row5', 2 => 'row6');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'reorder() leaves other suites unchanged');
}
public function testDoSelectOrderByRank()
{
$c = new Criteria();
$c->add(Table12Peer::SCOPE_COL, 1);
$objects = Table12Peer::doSelectOrderByRank($c);
$oldRank = 0;
while ($object = array_shift($objects)) {
$this->assertTrue($object->getRank() > $oldRank);
$oldRank = $object->getRank();
}
$c = new Criteria();
$c->add(Table12Peer::SCOPE_COL, 1);
$objects = Table12Peer::doSelectOrderByRank($c, Criteria::DESC);
$oldRank = 10;
while ($object = array_shift($objects)) {
$this->assertTrue($object->getRank() < $oldRank);
$oldRank = $object->getRank();
}
}
public function testRetrieveList()
{
$this->assertEquals(4, count(Table12Peer::retrieveList(1)), 'retrieveList() returns the list of objects in the scope');
$this->assertEquals(2, count(Table12Peer::retrieveList(2)), 'retrieveList() returns the list of objects in the scope');
}
public function testCountList()
{
$this->assertEquals(4, Table12Peer::countList(1), 'countList() returns the list of objects in the scope');
$this->assertEquals(2, Table12Peer::countList(2), 'countList() returns the list of objects in the scope');
}
public function testDeleteList()
{
$this->assertEquals(4, Table12Peer::deleteList(1), 'deleteList() returns the list of objects in the scope');
$this->assertEquals(2, Table12Peer::doCount(new Criteria()), 'deleteList() deletes the objects in the scope');
$this->assertEquals(2, Table12Peer::deleteList(2), 'deleteList() returns the list of objects in the scope');
$this->assertEquals(0, Table12Peer::doCount(new Criteria()), 'deleteList() deletes the objects in the scope');
}
}

View file

@ -0,0 +1,115 @@
<?php
/*
* $Id: SortableBehaviorTest.php 1356 2009-12-11 16:36:55Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/behavior/BookstoreSortableTestBase.php';
/**
* Tests for SortableBehavior class query modifier
*
* @author Francois Zaninotto
* @version $Revision: 1612 $
* @package generator.behavior.sortable
*/
class SortableBehaviorQueryBuilderModifierTest extends BookstoreSortableTestBase
{
protected function setUp()
{
parent::setUp();
$this->populateTable11();
}
public function testFilterByRank()
{
$this->assertTrue(Table11Query::create()->filterByRank(1) instanceof Table11Query, 'filterByRank() returns the current query object');
$this->assertEquals('row1', Table11Query::create()->filterByRank(1)->findOne()->getTitle(), 'filterByRank() filters on the rank');
$this->assertEquals('row4', Table11Query::create()->filterByRank(4)->findOne()->getTitle(), 'filterByRank() filters on the rank');
$this->assertNull(Table11Query::create()->filterByRank(5)->findOne(), 'filterByRank() filters on the rank, which makes the query return no result on a non-existent rank');
}
public function testOrderByRank()
{
$this->assertTrue(Table11Query::create()->orderByRank() instanceof Table11Query, 'orderByRank() returns the current query object');
// default order
$query = Table11Query::create()->orderByRank();
$expectedQuery = Table11Query::create()->addAscendingOrderByColumn(Table11Peer::SORTABLE_RANK);
$this->assertEquals($expectedQuery, $query, 'orderByRank() orders the query by rank asc');
// asc order
$query = Table11Query::create()->orderByRank(Criteria::ASC);
$expectedQuery = Table11Query::create()->addAscendingOrderByColumn(Table11Peer::SORTABLE_RANK);
$this->assertEquals($expectedQuery, $query, 'orderByRank() orders the query by rank, using the argument as sort direction');
// desc order
$query = Table11Query::create()->orderByRank(Criteria::DESC);
$expectedQuery = Table11Query::create()->addDescendingOrderByColumn(Table11Peer::SORTABLE_RANK);
$this->assertEquals($expectedQuery, $query, 'orderByRank() orders the query by rank, using the argument as sort direction');
}
/**
* @expectedException PropelException
*/
public function testOrderByRankIncorrectDirection()
{
Table11Query::create()->orderByRank('foo');
}
public function testFindList()
{
$ts = Table11Query::create()->findList();
$this->assertTrue($ts instanceof PropelObjectCollection, 'findList() returns a collection of objects');
$this->assertEquals(4, count($ts), 'findList() does not filter the query');
$this->assertEquals('row1', $ts[0]->getTitle(), 'findList() returns an ordered list');
$this->assertEquals('row2', $ts[1]->getTitle(), 'findList() returns an ordered list');
$this->assertEquals('row3', $ts[2]->getTitle(), 'findList() returns an ordered list');
$this->assertEquals('row4', $ts[3]->getTitle(), 'findList() returns an ordered list');
}
public function testFindOneByRank()
{
$this->assertTrue(Table11Query::create()->findOneByRank(1) instanceof Table11, 'findOneByRank() returns an instance of the model object');
$this->assertEquals('row1', Table11Query::create()->findOneByRank(1)->getTitle(), 'findOneByRank() returns a single item based on the rank');
$this->assertEquals('row4', Table11Query::create()->findOneByRank(4)->getTitle(), 'findOneByRank() returns a single item based on the rank');
$this->assertNull(Table11Query::create()->findOneByRank(5), 'findOneByRank() returns no result on a non-existent rank');
}
public function testGetMaxRank()
{
$this->assertEquals(4, Table11Query::create()->getMaxRank(), 'getMaxRank() returns the maximum rank');
// delete one
$t4 = Table11Query::create()->findOneByRank(4);
$t4->delete();
$this->assertEquals(3, Table11Query::create()->getMaxRank(), 'getMaxRank() returns the maximum rank');
// add one
$t = new Table11();
$t->save();
$this->assertEquals(4, Table11Query::create()->getMaxRank(), 'getMaxRank() returns the maximum rank');
// delete all
Table11Query::create()->deleteAll();
$this->assertNull(Table11Query::create()->getMaxRank(), 'getMaxRank() returns null for empty tables');
// add one
$t = new Table11();
$t->save();
$this->assertEquals(1, Table11Query::create()->getMaxRank(), 'getMaxRank() returns the maximum rank');
}
public function testReorder()
{
$objects = Table11Query::create()->find();
$ids = array();
foreach ($objects as $object) {
$ids[]= $object->getPrimaryKey();
}
$ranks = array(4, 3, 2, 1);
$order = array_combine($ids, $ranks);
Table11Query::create()->reorder($order);
$expected = array(1 => 'row3', 2 => 'row2', 3 => 'row4', 4 => 'row1');
$this->assertEquals($expected, $this->getFixturesArray(), 'reorder() reorders the suite');
}
}

View file

@ -0,0 +1,142 @@
<?php
/*
* $Id: SortableBehaviorTest.php 1356 2009-12-11 16:36:55Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/behavior/BookstoreSortableTestBase.php';
/**
* Tests for SortableBehavior class query modifier when the scope is enabled
*
* @author Francois Zaninotto
* @version $Revision: 1612 $
* @package generator.behavior.sortable
*/
class SortableBehaviorQueryBuilderModifierWithScopeTest extends BookstoreSortableTestBase
{
protected function setUp()
{
parent::setUp();
$this->populateTable12();
}
public function testInList()
{
/* List used for tests
scope=1 scope=2
row1 row5
row2 row6
row3
row4
*/
$query = Table12Query::create()->inList(1);
$expectedQuery = Table12Query::create()->add(Table12Peer::MY_SCOPE_COLUMN, 1, Criteria::EQUAL);
$this->assertEquals($expectedQuery, $query, 'inList() filters the query by scope');
$this->assertEquals(4, $query->count(), 'inList() filters the query by scope');
$query = Table12Query::create()->inList(2);
$expectedQuery = Table12Query::create()->add(Table12Peer::MY_SCOPE_COLUMN, 2, Criteria::EQUAL);
$this->assertEquals($expectedQuery, $query, 'inList() filters the query by scope');
$this->assertEquals(2, $query->count(), 'inList() filters the query by scope');
}
public function testFilterByRank()
{
/* List used for tests
scope=1 scope=2
row1 row5
row2 row6
row3
row4
*/
$this->assertEquals('row1', Table12Query::create()->filterByRank(1, 1)->findOne()->getTitle(), 'filterByRank() filters on the rank and the scope');
$this->assertEquals('row5', Table12Query::create()->filterByRank(1, 2)->findOne()->getTitle(), 'filterByRank() filters on the rank and the scope');
$this->assertEquals('row4', Table12Query::create()->filterByRank(4, 1)->findOne()->getTitle(), 'filterByRank() filters on the rank and the scope');
$this->assertNull(Table12Query::create()->filterByRank(4, 2)->findOne(), 'filterByRank() filters on the rank and the scope, which makes the query return no result on a non-existent rank');
}
public function testOrderByRank()
{
$this->assertTrue(Table12Query::create()->orderByRank() instanceof Table12Query, 'orderByRank() returns the current query object');
// default order
$query = Table12Query::create()->orderByRank();
$expectedQuery = Table12Query::create()->addAscendingOrderByColumn(Table12Peer::POSITION);
$this->assertEquals($expectedQuery, $query, 'orderByRank() orders the query by rank asc');
// asc order
$query = Table12Query::create()->orderByRank(Criteria::ASC);
$expectedQuery = Table12Query::create()->addAscendingOrderByColumn(Table12Peer::POSITION);
$this->assertEquals($expectedQuery, $query, 'orderByRank() orders the query by rank, using the argument as sort direction');
// desc order
$query = Table12Query::create()->orderByRank(Criteria::DESC);
$expectedQuery = Table12Query::create()->addDescendingOrderByColumn(Table12Peer::POSITION);
$this->assertEquals($expectedQuery, $query, 'orderByRank() orders the query by rank, using the argument as sort direction');
}
public function testFindList()
{
$ts = Table12Query::create()->findList(1);
$this->assertTrue($ts instanceof PropelObjectCollection, 'findList() returns a collection of objects');
$this->assertEquals(4, count($ts), 'findList() filters the query by scope');
$this->assertEquals('row1', $ts[0]->getTitle(), 'findList() returns an ordered scoped list');
$this->assertEquals('row2', $ts[1]->getTitle(), 'findList() returns an ordered scoped list');
$this->assertEquals('row3', $ts[2]->getTitle(), 'findList() returns an ordered scoped list');
$this->assertEquals('row4', $ts[3]->getTitle(), 'findList() returns an ordered scoped list');
$ts = Table12Query::create()->findList(2);
$this->assertEquals(2, count($ts), 'findList() filters the query by scope');
$this->assertEquals('row5', $ts[0]->getTitle(), 'findList() returns an ordered scoped list');
$this->assertEquals('row6', $ts[1]->getTitle(), 'findList() returns an ordered scoped list');
}
public function testFindOneByRank()
{
$this->assertTrue(Table12Query::create()->findOneByRank(1, 1) instanceof Table12, 'findOneByRank() returns an instance of the model object');
$this->assertEquals('row1', Table12Query::create()->findOneByRank(1, 1)->getTitle(), 'findOneByRank() returns a single item based on the rank and the scope');
$this->assertEquals('row5', Table12Query::create()->findOneByRank(1, 2)->getTitle(), 'findOneByRank() returns a single item based on the rank and the scope');
$this->assertEquals('row4', Table12Query::create()->findOneByRank(4, 1)->getTitle(), 'findOneByRank() returns a single item based on the rank a,d the scope');
$this->assertNull(Table12Query::create()->findOneByRank(4, 2), 'findOneByRank() returns no result on a non-existent rank and scope');
}
public function testGetMaxRank()
{
$this->assertEquals(4, Table12Query::create()->getMaxRank(1), 'getMaxRank() returns the maximum rank in the scope');
$this->assertEquals(2, Table12Query::create()->getMaxRank(2), 'getMaxRank() returns the maximum rank in the scope');
// delete one
$t4 = Table12Query::create()->findOneByRank(4, 1);
$t4->delete();
$this->assertEquals(3, Table12Query::create()->getMaxRank(1), 'getMaxRank() returns the maximum rank');
// add one
$t = new Table12();
$t->setMyScopeColumn(1);
$t->save();
$this->assertEquals(4, Table12Query::create()->getMaxRank(1), 'getMaxRank() returns the maximum rank');
// delete all
Table12Query::create()->deleteAll();
$this->assertNull(Table12Query::create()->getMaxRank(1), 'getMaxRank() returns null for empty tables');
// add one
$t = new Table12();
$t->setMyScopeColumn(1);
$t->save();
$this->assertEquals(1, Table12Query::create()->getMaxRank(1), 'getMaxRank() returns the maximum rank');
}
public function testReorder()
{
$objects = Table12Query::create()->findList(1);
$ids = array();
foreach ($objects as $object) {
$ids[]= $object->getPrimaryKey();
}
$ranks = array(4, 3, 2, 1);
$order = array_combine($ids, $ranks);
Table12Query::create()->reorder($order);
$expected = array(1 => 'row4', 2 => 'row3', 3 => 'row2', 4 => 'row1');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(1), 'reorder() reorders the suite');
$expected = array(1 => 'row5', 2 => 'row6');
$this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'reorder() leaves other suites unchanged');
}
}

View file

@ -0,0 +1,33 @@
<?php
/*
* $Id: SortableBehaviorTest.php 1612 2010-03-16 22:56:21Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests for SortableBehavior class
*
* @author Massimiliano Arione
* @version $Revision: 1612 $
* @package generator.behavior.sortable
*/
class SortableBehaviorTest extends BookstoreTestBase
{
public function testParameters()
{
$table11 = Table11Peer::getTableMap();
$this->assertEquals(count($table11->getColumns()), 3, 'Sortable adds one columns by default');
$this->assertTrue(method_exists('Table11', 'getRank'), 'Sortable adds a rank column by default');
$table12 = Table12Peer::getTableMap();
$this->assertEquals(count($table12->getColumns()), 4, 'Sortable does not add a column when it already exists');
$this->assertTrue(method_exists('Table12', 'getPosition'), 'Sortable allows customization of rank_column name');
}
}

View file

@ -0,0 +1,225 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/Propel.php';
set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/namespaced/build/classes");
/**
* Tests for Namespaces in generated classes class
* Requires a build of the 'namespaced' fixture
*
* @version $Revision: 1792 $
* @package generator.builder
*/
class NamespaceTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (version_compare(PHP_VERSION, '5.3.0') < 0) {
$this->markTestSkipped('Namespace support requires PHP 5.3');
}
parent::setUp();
Propel::init('fixtures/namespaced/build/conf/bookstore_namespaced-conf.php');
}
protected function tearDown()
{
parent::tearDown();
Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php');
}
public function testInsert()
{
$book = new \Foo\Bar\NamespacedBook();
$book->setTitle('foo');
$book->save();
$this->assertFalse($book->isNew());
$publisher = new \Baz\NamespacedPublisher();
$publisher->save();
$this->assertFalse($publisher->isNew());
}
public function testUpdate()
{
$book = new \Foo\Bar\NamespacedBook();
$book->setTitle('foo');
$book->save();
$book->setTitle('bar');
$book->save();
$this->assertFalse($book->isNew());
}
public function testRelate()
{
$author = new NamespacedAuthor();
$book = new \Foo\Bar\NamespacedBook();
$book->setNamespacedAuthor($author);
$book->save();
$this->assertFalse($book->isNew());
$this->assertFalse($author->isNew());
$author = new NamespacedAuthor();
$book = new \Foo\Bar\NamespacedBook();
$author->addNamespacedBook($book);
$author->save();
$this->assertFalse($book->isNew());
$this->assertFalse($author->isNew());
$publisher = new \Baz\NamespacedPublisher();
$book = new \Foo\Bar\NamespacedBook();
$book->setNamespacedPublisher($publisher);
$book->save();
$this->assertFalse($book->isNew());
$this->assertFalse($publisher->isNew());
}
public function testBasicQuery()
{
\Foo\Bar\NamespacedBookQuery::create()->deleteAll();
\Baz\NamespacedPublisherQuery::create()->deleteAll();
$noNamespacedBook = \Foo\Bar\NamespacedBookQuery::create()->findOne();
$this->assertNull($noNamespacedBook);
$noPublihser = \Baz\NamespacedPublisherQuery::create()->findOne();
$this->assertNull($noPublihser);
}
public function testFind()
{
\Foo\Bar\NamespacedBookQuery::create()->deleteAll();
$book = new \Foo\Bar\NamespacedBook();
$book->setTitle('War And Peace');
$book->save();
$book2 = \Foo\Bar\NamespacedBookQuery::create()->findPk($book->getId());
$this->assertEquals($book, $book2);
$book3 = \Foo\Bar\NamespacedBookQuery::create()->findOneByTitle($book->getTitle());
$this->assertEquals($book, $book3);
}
public function testGetRelatedManyToOne()
{
\Foo\Bar\NamespacedBookQuery::create()->deleteAll();
\Baz\NamespacedPublisherQuery::create()->deleteAll();
$publisher = new \Baz\NamespacedPublisher();
$book = new \Foo\Bar\NamespacedBook();
$book->setNamespacedPublisher($publisher);
$book->save();
\Foo\Bar\NamespacedBookPeer::clearInstancePool();
\Baz\NamespacedPublisherPeer::clearInstancePool();
$book2 = \Foo\Bar\NamespacedBookQuery::create()->findPk($book->getId());
$publisher2 = $book2->getNamespacedPublisher();
$this->assertEquals($publisher->getId(), $publisher2->getId());
}
public function testGetRelatedOneToMany()
{
\Foo\Bar\NamespacedBookQuery::create()->deleteAll();
\Baz\NamespacedPublisherQuery::create()->deleteAll();
$author = new NamespacedAuthor();
$book = new \Foo\Bar\NamespacedBook();
$book->setNamespacedAuthor($author);
$book->save();
\Foo\Bar\NamespacedBookPeer::clearInstancePool();
NamespacedAuthorPeer::clearInstancePool();
$author2 = NamespacedAuthorQuery::create()->findPk($author->getId());
$book2 = $author2->getNamespacedBooks()->getFirst();
$this->assertEquals($book->getId(), $book2->getId());
}
public function testFindWithManyToOne()
{
\Foo\Bar\NamespacedBookQuery::create()->deleteAll();
\Baz\NamespacedPublisherQuery::create()->deleteAll();
$publisher = new \Baz\NamespacedPublisher();
$book = new \Foo\Bar\NamespacedBook();
$book->setNamespacedPublisher($publisher);
$book->save();
\Foo\Bar\NamespacedBookPeer::clearInstancePool();
\Baz\NamespacedPublisherPeer::clearInstancePool();
$book2 = \Foo\Bar\NamespacedBookQuery::create()
->joinWith('NamespacedPublisher')
->findPk($book->getId());
$publisher2 = $book2->getNamespacedPublisher();
$this->assertEquals($publisher->getId(), $publisher2->getId());
}
public function testFindWithOneToMany()
{
\Foo\Bar\NamespacedBookQuery::create()->deleteAll();
NamespacedAuthorQuery::create()->deleteAll();
$author = new NamespacedAuthor();
$book = new \Foo\Bar\NamespacedBook();
$book->setNamespacedAuthor($author);
$book->save();
\Foo\Bar\NamespacedBookPeer::clearInstancePool();
NamespacedAuthorPeer::clearInstancePool();
$author2 = NamespacedAuthorQuery::create()
->joinWith('NamespacedBook')
->findPk($author->getId());
$book2 = $author2->getNamespacedBooks()->getFirst();
$this->assertEquals($book->getId(), $book2->getId());
}
public function testSingleTableInheritance()
{
\Foo\Bar\NamespacedBookstoreEmployeeQuery::create()->deleteAll();
$emp = new \Foo\Bar\NamespacedBookstoreEmployee();
$emp->setName('Henry');
$emp->save();
$man = new \Foo\Bar\NamespacedBookstoreManager();
$man->setName('John');
$man->save();
$cas = new \Foo\Bar\NamespacedBookstoreCashier();
$cas->setName('William');
$cas->save();
$emps = \Foo\Bar\NamespacedBookstoreEmployeeQuery::create()
->orderByName()
->find();
$this->assertEquals(3, count($emps));
$this->assertTrue($emps[0] instanceof \Foo\Bar\NamespacedBookstoreEmployee);
$this->assertTrue($emps[1] instanceof \Foo\Bar\NamespacedBookstoreManager);
$this->assertTrue($emps[2] instanceof \Foo\Bar\NamespacedBookstoreCashier);
$nbMan = \Foo\Bar\NamespacedBookstoreManagerQuery::create()
->count();
$this->assertEquals(1, $nbMan);
}
public function testManyToMany()
{
\Foo\Bar\NamespacedBookQuery::create()->deleteAll();
\Baz\NamespacedBookClubQuery::create()->deleteAll();
NamespacedBookListRelQuery::create()->deleteAll();
$book1 = new \Foo\Bar\NamespacedBook();
$book1->setTitle('bar');
$book1->save();
$book2 = new \Foo\Bar\NamespacedBook();
$book2->setTitle('foo');
$book2->save();
$bookClub1 = new \Baz\NamespacedBookClub();
$bookClub1->addNamespacedBook($book1);
$bookClub1->addNamespacedBook($book2);
$bookClub1->save();
$bookClub2 = new \Baz\NamespacedBookClub();
$bookClub2->addNamespacedBook($book1);
$bookClub2->save();
$this->assertEquals(2, $book1->countNamespacedBookClubs());
$this->assertEquals(1, $book2->countNamespacedBookClubs());
$nbRels = NamespacedBookListRelQuery::create()->count();
$this->assertEquals(3, $nbRels);
$con = Propel::getConnection(NamespacedBookListRelPeer::DATABASE_NAME);
$books = \Foo\Bar\NamespacedBookQuery::create()
->orderByTitle()
->joinWith('NamespacedBookListRel')
->joinWith('NamespacedBookListRel.NamespacedBookClub')
->find($con);
}
}

View file

@ -0,0 +1,187 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/cms/CmsTestBase.php';
/**
* Tests the generated nested-set Object classes.
*
* This test uses generated Bookstore-Cms classes to test the behavior of various
* object operations. The _idea_ here is to test every possible generated method
* from Object.tpl; if necessary, bookstore will be expanded to accommodate this.
*
* The database is relaoded before every test and flushed after every test. This
* means that you can always rely on the contents of the databases being the same
* for each test method in this class. See the CmsDataPopulator::populate()
* method for the exact contents of the database.
*
* @see CmsDataPopulator
* @package generator.builder.om
*/
class GeneratedNestedSetObjectTest extends CmsTestBase
{
/**
* Test xxxNestedSet::isRoot() as true
*/
public function testObjectIsRootTrue()
{
$pp = PagePeer::retrieveRoot(1);
$this->assertTrue($pp->isRoot(), 'Node must be root');
}
/**
* Test xxxNestedSet::isRoot() as false
*/
public function testObjectIsRootFalse()
{
$c = new Criteria(PagePeer::DATABASE_NAME);
$c->add(PagePeer::TITLE, 'school', Criteria::EQUAL);
$school = PagePeer::doSelectOne($c);
$this->assertFalse($school->isRoot(), 'Node must not be root');
}
/**
* Test xxxNestedSet::retrieveParent() as true.
*/
public function testObjectRetrieveParentTrue()
{
$c = new Criteria(PagePeer::DATABASE_NAME);
$c->add(PagePeer::TITLE, 'school', Criteria::EQUAL);
$school = PagePeer::doSelectOne($c);
$this->assertNotNull($school->retrieveParent(), 'Parent node must exist');
}
/**
* Test xxxNestedSet::retrieveParent() as false.
*/
public function testObjectRetrieveParentFalse()
{
$c = new Criteria(PagePeer::DATABASE_NAME);
$c->add(PagePeer::TITLE, 'home', Criteria::EQUAL);
$home = PagePeer::doSelectOne($c);
$this->assertNull($home->retrieveParent(), 'Parent node must not exist and retrieved not be null');
}
/**
* Test xxxNestedSet::hasParent() as true.
*/
public function testObjectHasParentTrue()
{
$c = new Criteria();
$c->add(PagePeer::TITLE, 'school', Criteria::EQUAL);
$school = PagePeer::doSelectOne($c);
$this->assertTrue($school->hasParent(), 'Node must have parent node');
}
/**
* Test xxxNestedSet::hasParent() as false
*/
public function testObjectHasParentFalse()
{
$c = new Criteria();
$c->add(PagePeer::TITLE, 'home', Criteria::EQUAL);
$home = PagePeer::doSelectOne($c);
$this->assertFalse($home->hasParent(), 'Root node must not have parent');
}
/**
* Test xxxNestedSet::isLeaf() as true.
*/
public function testObjectIsLeafTrue()
{
$c = new Criteria();
$c->add(PagePeer::TITLE, 'simulator', Criteria::EQUAL);
$simulator = PagePeer::doSelectOne($c);
$this->assertTrue($simulator->isLeaf($simulator), 'Node must be a leaf');
}
/**
* Test xxxNestedSet::isLeaf() as false
*/
public function testObjectIsLeafFalse()
{
$c = new Criteria();
$c->add(PagePeer::TITLE, 'contact', Criteria::EQUAL);
$contact = PagePeer::doSelectOne($c);
$this->assertFalse($contact->isLeaf($contact), 'Node must not be a leaf');
}
/**
* Test xxxNestedSet::makeRoot()
*/
public function testObjectMakeRoot()
{
$page = new Page();
$page->makeRoot();
$this->assertEquals(1, $page->getLeftValue(), 'Node left value must equal 1');
$this->assertEquals(2, $page->getRightValue(), 'Node right value must equal 2');
}
/**
* Test xxxNestedSet::makeRoot() exception
* @expectedException PropelException
*/
public function testObjectMakeRootException()
{
$c = new Criteria();
$c->add(PagePeer::TITLE, 'home', Criteria::EQUAL);
$home = PagePeer::doSelectOne($c);
$home->makeRoot();
}
/**
* Test xxxNestedSet::getDescendants()
*/
public function testPeerGetDescendants()
{
$nodesWithoutPool = array();
CategoryPeer::clearInstancePool();
$cat = CategoryPeer::retrieveRoot(1);
$children = $cat->getDescendants();
foreach($children as $child)
{
$nodesWithoutPool[] = $child->getTitle();
}
$this->assertEquals($nodesWithoutPool, array('Cat_1_1', 'Cat_1_1_1', 'Cat_1_1_1_1'));
}
/**
* Test xxxNestedSet::getDescendantsTwice()
*/
public function testPeerGetDescendantsTwice()
{
$nodesWithoutPool = array();
$nodesWithPool = array();
CategoryPeer::clearInstancePool();
$cat = CategoryPeer::retrieveRoot(1);
$children = $cat->getDescendants();
foreach($children as $child)
{
$nodesWithoutPool[] = $child->getTitle();
}
$cat = CategoryPeer::retrieveRoot(1);
$children = $cat->getDescendants();
foreach($children as $child)
{
$nodesWithPool[] = $child->getTitle();
}
$this->assertEquals($nodesWithoutPool, $nodesWithPool, 'Retrieved nodes must be the same with and without InstancePooling');
}
}

View file

@ -0,0 +1,188 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/cms/CmsTestBase.php';
/**
* Tests the generated nested-set Object classes.
*
* This test uses generated Bookstore-Cms classes to test the behavior of various
* object operations. The _idea_ here is to test every possible generated method
* from Object.tpl; if necessary, bookstore will be expanded to accommodate this.
*
* The database is relaoded before every test and flushed after every test. This
* means that you can always rely on the contents of the databases being the same
* for each test method in this class. See the CmsDataPopulator::populate()
* method for the exact contents of the database.
*
* @see CmsDataPopulator
* @package generator.builder.om
*/
class GeneratedNestedSetPeerTest extends CmsTestBase
{
/**
* Test retrieveRoot() as true
*/
public function testRetrieveRootExist()
{
$pp = PagePeer::retrieveRoot(1);
$this->assertNotNull($pp, 'Node must exist and not be null');
$this->assertEquals(1, $pp->getLeftValue(), 'Node left value must be equal to 1');
}
/**
* Test retrieveRoot() as false
*/
public function testRetrieveRootNotExist()
{
$pp = PagePeer::retrieveRoot(2);
$this->assertNull($pp, 'Root with such scopeId must not exist');
}
/**
* Test xxxNestedSetPeer::isRoot() as true
*/
public function testPeerIsRootTrue()
{
$pp = PagePeer::retrieveRoot(1);
$this->assertTrue(PagePeer::isRoot($pp), 'Node must be root');
}
/**
* Test xxxNestedSetPeer::isRoot() as false
*/
public function testPeerIsRootFalse()
{
$c = new Criteria(PagePeer::DATABASE_NAME);
$c->add(PagePeer::TITLE, 'school', Criteria::EQUAL);
$school = PagePeer::doSelectOne($c);
$this->assertFalse(PagePeer::isRoot($school), 'Node must not be root');
}
/**
* Test xxxNestedSetPeer::retrieveParent() as true.
*/
public function testPeerRetrieveParentTrue()
{
$c = new Criteria(PagePeer::DATABASE_NAME);
$c->add(PagePeer::TITLE, 'school', Criteria::EQUAL);
$school = PagePeer::doSelectOne($c);
$this->assertNotNull(PagePeer::retrieveParent($school), 'Parent node must exist');
}
/**
* Test xxxNestedSetPeer::retrieveParent() as false.
*/
public function testPeerRetrieveParentFalse()
{
$c = new Criteria(PagePeer::DATABASE_NAME);
$c->add(PagePeer::TITLE, 'home', Criteria::EQUAL);
$home = PagePeer::doSelectOne($c);
$this->assertNull(PagePeer::retrieveParent($home), 'Parent node must not exist and retrieved not be null');
}
/**
* Test xxxNestedSetPeer::hasParent() as true.
*/
public function testPeerHasParentTrue()
{
$c = new Criteria();
$c->add(PagePeer::TITLE, 'school', Criteria::EQUAL);
$school = PagePeer::doSelectOne($c);
$this->assertTrue(PagePeer::hasParent($school), 'Node must have parent node');
}
/**
* Test xxxNestedSetPeer::hasParent() as false
*/
public function testPeerHasParentFalse()
{
$c = new Criteria();
$c->add(PagePeer::TITLE, 'home', Criteria::EQUAL);
$home = PagePeer::doSelectOne($c);
$this->assertFalse(PagePeer::hasParent($home), 'Root node must not have parent');
}
/**
* Test xxxNestedSetPeer::isValid() as true.
*/
public function testPeerIsValidTrue()
{
$c = new Criteria();
$c->add(PagePeer::TITLE, 'school', Criteria::EQUAL);
$school = PagePeer::doSelectOne($c);
$this->assertTrue(PagePeer::isValid($school), 'Node must be valid');
}
/**
* Test xxxNestedSetPeer::isValid() as false
*/
public function testPeerIsValidFalse()
{
$page = new Page();
$this->assertFalse(PagePeer::isValid($page), 'Node left and right values must be invalid');
$this->assertFalse(PagePeer::isValid(null), 'Null must be invalid');
}
/**
* Test xxxNestedSetPeer::isLeaf() as true.
*/
public function testPeerIsLeafTrue()
{
$c = new Criteria();
$c->add(PagePeer::TITLE, 'simulator', Criteria::EQUAL);
$simulator = PagePeer::doSelectOne($c);
$this->assertTrue(PagePeer::isLeaf($simulator), 'Node must be a leaf');
}
/**
* Test xxxNestedSetPeer::isLeaf() as false
*/
public function testPeerIsLeafFalse()
{
$c = new Criteria();
$c->add(PagePeer::TITLE, 'contact', Criteria::EQUAL);
$contact = PagePeer::doSelectOne($c);
$this->assertFalse(PagePeer::isLeaf($contact), 'Node must not be a leaf');
}
/**
* Test xxxNestedSetPeer::createRoot()
*/
public function testPeerCreateRoot()
{
$page = new Page();
PagePeer::createRoot($page);
$this->assertEquals(1, $page->getLeftValue(), 'Node left value must equal 1');
$this->assertEquals(2, $page->getRightValue(), 'Node right value must equal 2');
}
/**
* Test xxxNestedSetPeer::createRoot() exception
* @expectedException PropelException
*/
public function testPeerCreateRootException()
{
$c = new Criteria();
$c->add(PagePeer::TITLE, 'home', Criteria::EQUAL);
$home = PagePeer::doSelectOne($c);
PagePeer::createRoot($home);
}
}

View file

@ -0,0 +1,120 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/cms/CmsTestBase.php';
/**
* Tests the generated nested-set Object classes.
*
* This test uses generated Bookstore-Cms classes to test the behavior of various
* object operations. The _idea_ here is to test every possible generated method
* from Object.tpl; if necessary, bookstore will be expanded to accommodate this.
*
* The database is relaoded before every test and flushed after every test. This
* means that you can always rely on the contents of the databases being the same
* for each test method in this class. See the CmsDataPopulator::populate()
* method for the exact contents of the database.
*
* @see CmsDataPopulator
* @package generator.builder.om
*/
class GeneratedNestedSetTest extends CmsTestBase
{
/**
* A convenience method to dump the page rows.
*/
private function showPageItems()
{
$tree = PagePeer::retrieveTree();
$iterator = new RecursiveIteratorIterator($tree, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $item) { /* @var $item Page */
echo str_repeat('- ', $iterator->getDepth())
, $item->getId() , ': '
, $item->getTitle()
, ' [', $item->getLeftValue(), ':', $item->getRightValue() , ']'
. "\n";
}
}
/**
* Adds a new Page row with specified parent Id.
*
* @param int $parentId
*/
protected function addNewChildPage($parentId)
{
$db = Propel::getConnection(PagePeer::DATABASE_NAME);
//$db->beginTransaction();
$parent = PagePeer::retrieveByPK($parentId);
$page = new Page();
$page->setTitle('new page '.time());
$page->insertAsLastChildOf($parent);
$page->save();
//$db->commit();
}
/**
* Asserts that the Page table tree integrity is intact.
*/
protected function assertPageTreeIntegrity()
{
$db = Propel::getConnection(PagePeer::DATABASE_NAME);
$values = array();
$log = '';
foreach ($db->query('SELECT Id, LeftChild, RightChild, Title FROM Page', PDO::FETCH_NUM) as $row) {
list($id, $leftChild, $rightChild, $title) = $row;
if (!in_array($leftChild, $values)) {
$values[] = (int) $leftChild;
} else {
$this->fail('Duplicate LeftChild value '.$leftChild);
}
if (!in_array($rightChild, $values)) {
$values[] = (int) $rightChild;
} else {
$this->fail('Duplicate RightChild value '.$rightChild);
}
$log .= "[$id($leftChild:$rightChild)]";
}
sort($values);
if ($values[count($values)-1] != count($values)) {
$message = sprintf("Tree integrity NOT ok (%s)\n", $log);
$message .= sprintf('Integrity error: value count: %d, high value: %d', count($values), $values[count($values)-1]);
$this->fail($message);
}
}
/**
* Tests adding a node to the Page tree.
*/
public function testAdd()
{
$db = Propel::getConnection(PagePeer::DATABASE_NAME);
// I'm not sure if the specific ID matters, but this should match original
// code. The ID will change with subsequent runs (e.g. the first time it will be 11)
$startId = $db->query('SELECT MIN(Id) FROM Page')->fetchColumn();
$this->addNewChildPage($startId + 10);
$this->assertPageTreeIntegrity();
}
}

View file

@ -0,0 +1,289 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Tests the generated Object classes and LOB behavior.
*
* This test uses generated Bookstore classes to test the behavior of various
* object operations. The _idea_ here is to test every possible generated method
* from Object.tpl; if necessary, bookstore will be expanded to accommodate this.
*
* The database is relaoded before every test and flushed after every test. This
* means that you can always rely on the contents of the databases being the same
* for each test method in this class. See the BookstoreDataPopulator::populate()
* method for the exact contents of the database.
*
* @see BookstoreDataPopulator
* @author Hans Lellelid <hans@xmpl.org>
* @package generator.builder.om
*/
class GeneratedObjectLobTest extends BookstoreEmptyTestBase
{
/**
* Array of filenames pointing to blob/clob files indexed by the basename.
*
* @var array string[]
*/
protected $sampleLobFiles = array();
protected function setUp()
{
parent::setUp();
BookstoreDataPopulator::populate();
$this->sampleLobFiles['tin_drum.gif'] = TESTS_BASE_DIR . '/etc/lob/tin_drum.gif';
$this->sampleLobFiles['tin_drum.txt'] = TESTS_BASE_DIR . '/etc/lob/tin_drum.txt';
$this->sampleLobFiles['propel.gif'] = TESTS_BASE_DIR . '/etc/lob/propel.gif';
}
/**
* Gets a LOB filename.
*
* @param string $basename Basename of LOB filename to return (if left blank, will choose random file).
* @return string
* @throws Exception - if specified basename doesn't correspond to a registered LOB filename
*/
protected function getLobFile($basename = null)
{
if ($basename === null) {
$basename = array_rand($this->sampleLobFiles);
}
if (isset($this->sampleLobFiles[$basename])) {
return $this->sampleLobFiles[$basename];
} else {
throw new Exception("Invalid base LOB filename: $basename");
}
}
/**
* Test the LOB results returned in a resultset.
*/
public function testLobResults()
{
$blob_path = $this->getLobFile('tin_drum.gif');
$clob_path = $this->getLobFile('tin_drum.txt');
$book = BookPeer::doSelectOne(new Criteria());
$m1 = new Media();
$m1->setBook($book);
$m1->setCoverImage(file_get_contents($blob_path));
$m1->setExcerpt(file_get_contents($clob_path));
$m1->save();
$m1_id = $m1->getId();
$m1->reload();
$img = $m1->getCoverImage();
$txt = $m1->getExcerpt();
$this->assertType('resource', $img, "Expected results of BLOB method to be a resource.");
$this->assertType('string', $txt, "Expected results of CLOB method to be a string.");
$stat = fstat($img);
$size = $stat['size'];
$this->assertEquals(filesize($blob_path), $size, "Expected filesize to match stat(blobrsc)");
$this->assertEquals(filesize($clob_path), strlen($txt), "Expected filesize to match clob strlen");
}
/**
* Test to make sure that file pointer is not when it is fetched
* from the object.
*
* This is actually a test for correct behavior and does not completely fix
* the associated ticket (which was resolved wontfix).
*
* This does test the rewind-after-save functionality, however.
*
* @link http://propel.phpdb.org/trac/ticket/531
*/
public function testLobRepeatRead()
{
$blob_path = $this->getLobFile('tin_drum.gif');
$clob_path = $this->getLobFile('tin_drum.txt');
$book = BookPeer::doSelectOne(new Criteria());
$m1 = new Media();
$m1->setBook($book);
$m1->setCoverImage(file_get_contents($blob_path));
$m1->setExcerpt(file_get_contents($clob_path));
$m1->save();
$img = $m1->getCoverImage();
// 1) Assert that this resource has been rewound.
$this->assertEquals(0, ftell($img), "Expected position of cursor in file pointer to be 0");
// 1) Assert that we've got a valid stream to start with
$this->assertType('resource', $img, "Expected results of BLOB method to be a resource.");
// read first 100 bytes
$firstBytes = fread($img, 100);
$img2 = $m1->getCoverImage();
$this->assertSame($img, $img2, "Assert that the two resources are the same.");
// read next 100 bytes
$nextBytes = fread($img, 100);
$this->assertNotEquals(bin2hex($firstBytes), bin2hex($nextBytes), "Expected the first 100 and next 100 bytes to not be identical.");
}
/**
* Tests the setting of null LOBs
*/
public function testLobNulls()
{
$book = BookPeer::doSelectOne(new Criteria());
$m1 = new Media();
$m1->setBook($book);
$this->assertTrue($m1->getCoverImage() === null, "Initial LOB value for a new object should be null.");
$m1->save();
$m1_id = $m1->getId();
$m2 = new Media();
$m2->setBook($book);
$m2->setCoverImage(null);
$this->assertTrue($m2->getCoverImage() === null, "Setting a LOB to null should cause accessor to return null.");
$m2->save();
$m2_id = $m2->getId();
$m1->reload();
$this->assertTrue($m1->getCoverImage() === null, "Default null LOB value should be null after a reload.");
$m2->reload();
$this->assertTrue($m2->getCoverImage() === null, "LOB value set to null should be null after a reload.");
}
/**
* Tests the setting of LOB (BLOB and CLOB) values.
*/
public function testLobSetting()
{
$blob_path = $this->getLobFile('tin_drum.gif');
$blob2_path = $this->getLobFile('propel.gif');
$clob_path = $this->getLobFile('tin_drum.txt');
$book = BookPeer::doSelectOne(new Criteria());
$m1 = new Media();
$m1->setBook($book);
$m1->setCoverImage(file_get_contents($blob_path));
$m1->setExcerpt(file_get_contents($clob_path));
$m1->save();
$m1_id = $m1->getId();
// 1) Assert that we've got a valid stream to start with
$img = $m1->getCoverImage();
$this->assertType('resource', $img, "Expected results of BLOB method to be a resource.");
// 2) Test setting a BLOB column with file contents
$m1->setCoverImage(file_get_contents($blob2_path));
$this->assertType('resource', $m1->getCoverImage(), "Expected to get a resource back after setting BLOB with file contents.");
// commit those changes & reload
$m1->save();
// 3) Verify that we've got a valid resource after reload
$m1->reload();
$this->assertType('resource', $m1->getCoverImage(), "Expected to get a resource back after setting reloading object.");
// 4) Test isModified() behavior
$fp = fopen("php://temp", "r+");
fwrite($fp, file_get_contents($blob2_path));
$m1->setCoverImage($fp);
$this->assertTrue($m1->isModified(), "Expected Media object to be modified, despite fact that stream is to same data");
// 5) Test external modification of the stream (and re-setting it into the object)
$stream = $m1->getCoverImage();
fwrite($stream, file_get_contents($blob_path)); // change the contents of the stream
$m1->setCoverImage($stream);
$this->assertTrue($m1->isModified(), "Expected Media object to be modified when stream contents changed.");
$this->assertNotEquals(file_get_contents($blob2_path), stream_get_contents($m1->getCoverImage()));
$m1->save();
// 6) Assert that when we call the setter with a stream, that the file in db gets updated.
$m1->reload(); // start with a fresh copy from db
// Ensure that object is set up correctly
$this->assertNotEquals(file_get_contents($blob_path), stream_get_contents($m1->getCoverImage()), "The object is not correctly set up to verify the stream-setting test.");
$fp = fopen($blob_path, "r");
$m1->setCoverImage($fp);
$m1->save();
$m1->reload(); // refresh from db
// Assert that we've updated the db
$this->assertEquals(file_get_contents($blob_path), stream_get_contents($m1->getCoverImage()), "Expected the updated BLOB value after setting with a stream.");
// 7) Assert that 'w' mode works
}
public function testLobSetting_WriteMode()
{
$blob_path = $this->getLobFile('tin_drum.gif');
$blob2_path = $this->getLobFile('propel.gif');
$clob_path = $this->getLobFile('tin_drum.txt');
$book = BookPeer::doSelectOne(new Criteria());
$m1 = new Media();
$m1->setBook($book);
$m1->setCoverImage(file_get_contents($blob_path));
$m1->setExcerpt(file_get_contents($clob_path));
$m1->save();
MediaPeer::clearInstancePool();
// make sure we have the latest from the db:
$m2 = MediaPeer::retrieveByPK($m1->getId());
// now attempt to assign a temporary stream, opened in 'w' mode, to the db
$stream = fopen("php://memory", 'w');
fwrite($stream, file_get_contents($blob2_path));
$m2->setCoverImage($stream);
$m2->save();
fclose($stream);
$m2->reload();
$this->assertEquals(file_get_contents($blob2_path), stream_get_contents($m2->getCoverImage()), "Expected contents to match when setting stream w/ 'w' mode");
$stream2 = fopen("php://memory", 'w+');
fwrite($stream2, file_get_contents($blob_path));
rewind($stream2);
$this->assertEquals(file_get_contents($blob_path), stream_get_contents($stream2), "Expecting setup to be correct");
$m2->setCoverImage($stream2);
$m2->save();
$m2->reload();
$this->assertEquals(file_get_contents($blob_path), stream_get_contents($m2->getCoverImage()), "Expected contents to match when setting stream w/ 'w+' mode");
}
}

View file

@ -0,0 +1,352 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Tests relationships between generated Object classes.
*
* This test uses generated Bookstore classes to test the behavior of various
* object operations. The _idea_ here is to test every possible generated method
* from Object.tpl; if necessary, bookstore will be expanded to accommodate this.
*
* The database is relaoded before every test and flushed after every test. This
* means that you can always rely on the contents of the databases being the same
* for each test method in this class. See the BookstoreDataPopulator::populate()
* method for the exact contents of the database.
*
* @see BookstoreDataPopulator
* @author Hans Lellelid <hans@xmpl.org>
* @package generator.builder.om
*/
class GeneratedObjectRelTest extends BookstoreEmptyTestBase
{
protected function setUp()
{
parent::setUp();
}
/**
* Tests one side of a bi-directional setting of many-to-many relationships.
*/
public function testManyToMany_Dir1()
{
$list = new BookClubList();
$list->setGroupLeader('Archimedes Q. Porter');
// No save ...
$book = new Book();
$book->setTitle( "Jungle Expedition Handbook" );
$book->setISBN('TEST');
// No save ...
$this->assertEquals(0, count($list->getBookListRels()) );
$this->assertEquals(0, count($book->getBookListRels()) );
$this->assertEquals(0, count(BookListRelPeer::doSelect(new Criteria())) );
$xref = new BookListRel();
$xref->setBook($book);
$list->addBookListRel($xref);
$this->assertEquals(1, count($list->getBookListRels()));
$this->assertEquals(1, count($book->getBookListRels()) );
$this->assertEquals(0, count(BookListRelPeer::doSelect(new Criteria())) );
$list->save();
$this->assertEquals(1, count($list->getBookListRels()) );
$this->assertEquals(1, count($book->getBookListRels()) );
$this->assertEquals(1, count(BookListRelPeer::doSelect(new Criteria())) );
}
/**
* Tests reverse setting of one of many-to-many relationship, with all saves cascaded.
*/
public function testManyToMany_Dir2_Unsaved()
{
$list = new BookClubList();
$list->setGroupLeader('Archimedes Q. Porter');
// No save ...
$book = new Book();
$book->setTitle( "Jungle Expedition Handbook" );
$book->setISBN('TEST');
// No save (yet) ...
$this->assertEquals(0, count($list->getBookListRels()) );
$this->assertEquals(0, count($book->getBookListRels()) );
$this->assertEquals(0, count(BookListRelPeer::doSelect(new Criteria())) );
$xref = new BookListRel();
$xref->setBookClubList($list);
$book->addBookListRel($xref);
$this->assertEquals(1, count($list->getBookListRels()) );
$this->assertEquals(1, count($book->getBookListRels()) );
$this->assertEquals(0, count(BookListRelPeer::doSelect(new Criteria())) );
$book->save();
$this->assertEquals(1, count($list->getBookListRels()) );
$this->assertEquals(1, count($book->getBookListRels()) );
$this->assertEquals(1, count(BookListRelPeer::doSelect(new Criteria())) );
}
/**
* Tests reverse setting of relationships, saving one of the objects first.
* @link http://propel.phpdb.org/trac/ticket/508
*/
public function testManyToMany_Dir2_Saved()
{
$list = new BookClubList();
$list->setGroupLeader('Archimedes Q. Porter');
$list->save();
$book = new Book();
$book->setTitle( "Jungle Expedition Handbook" );
$book->setISBN('TEST');
// No save (yet) ...
$this->assertEquals(0, count($list->getBookListRels()) );
$this->assertEquals(0, count($book->getBookListRels()) );
$this->assertEquals(0, count(BookListRelPeer::doSelect(new Criteria())) );
// Now set the relationship from the opposite direction.
$xref = new BookListRel();
$xref->setBookClubList($list);
$book->addBookListRel($xref);
$this->assertEquals(1, count($list->getBookListRels()) );
$this->assertEquals(1, count($book->getBookListRels()) );
$this->assertEquals(0, count(BookListRelPeer::doSelect(new Criteria())) );
$book->save();
$this->assertEquals(1, count($list->getBookListRels()) );
$this->assertEquals(1, count($book->getBookListRels()) );
$this->assertEquals(1, count(BookListRelPeer::doSelect(new Criteria())) );
}
public function testManyToManyGetterExists()
{
$this->assertTrue(method_exists('BookClubList', 'getBooks'), 'Object generator correcly adds getter for the crossRefFk');
$this->assertFalse(method_exists('BookClubList', 'getBookClubLists'), 'Object generator correcly adds getter for the crossRefFk');
}
public function testManyToManyGetterNewObject()
{
$blc1 = new BookClubList();
$books = $blc1->getBooks();
$this->assertTrue($books instanceof PropelObjectCollection, 'getCrossRefFK() returns a Propel collection');
$this->assertEquals('Book', $books->getModel(), 'getCrossRefFK() returns a collection of the correct model');
$this->assertEquals(0, count($books), 'getCrossRefFK() returns an empty list for new objects');
$query = BookQuery::create()
->filterByTitle('Harry Potter and the Order of the Phoenix');
$books = $blc1->getBooks($query);
$this->assertEquals(0, count($books), 'getCrossRefFK() accepts a query as first parameter');
}
public function testManyToManyGetter()
{
BookstoreDataPopulator::populate();
$blc1 = BookClubListQuery::create()->findOneByGroupLeader('Crazyleggs');
$books = $blc1->getBooks();
$this->assertTrue($books instanceof PropelObjectCollection, 'getCrossRefFK() returns a Propel collection');
$this->assertEquals('Book', $books->getModel(), 'getCrossRefFK() returns a collection of the correct model');
$this->assertEquals(2, count($books), 'getCrossRefFK() returns the correct list of objects');
$query = BookQuery::create()
->filterByTitle('Harry Potter and the Order of the Phoenix');
$books = $blc1->getBooks($query);
$this->assertEquals(1, count($books), 'getCrossRefFK() accepts a query as first parameter');
}
public function testManyToManyCounterExists()
{
$this->assertTrue(method_exists('BookClubList', 'countBooks'), 'Object generator correcly adds counter for the crossRefFk');
$this->assertFalse(method_exists('BookClubList', 'countBookClubLists'), 'Object generator correcly adds counter for the crossRefFk');
}
public function testManyToManyCounterNewObject()
{
$blc1 = new BookClubList();
$nbBooks = $blc1->countBooks();
$this->assertEquals(0, $nbBooks, 'countCrossRefFK() returns 0 for new objects');
$query = BookQuery::create()
->filterByTitle('Harry Potter and the Order of the Phoenix');
$nbBooks = $blc1->countBooks($query);
$this->assertEquals(0, $nbBooks, 'countCrossRefFK() accepts a query as first parameter');
}
public function testManyToManyCounter()
{
BookstoreDataPopulator::populate();
$blc1 = BookClubListQuery::create()->findOneByGroupLeader('Crazyleggs');
$nbBooks = $blc1->countBooks();
$this->assertEquals(2, $nbBooks, 'countCrossRefFK() returns the correct list of objects');
$query = BookQuery::create()
->filterByTitle('Harry Potter and the Order of the Phoenix');
$nbBooks = $blc1->countBooks($query);
$this->assertEquals(1, $nbBooks, 'countCrossRefFK() accepts a query as first parameter');
}
public function testManyToManyAdd()
{
$list = new BookClubList();
$list->setGroupLeader('Archimedes Q. Porter');
$book = new Book();
$book->setTitle( "Jungle Expedition Handbook" );
$book->setISBN('TEST');
$list->addBook($book);
$this->assertEquals(1, $list->countBooks(), 'addCrossFk() sets the internal collection properly');
$this->assertEquals(1, $list->countBookListRels(), 'addCrossFk() sets the internal cross reference collection properly');
$list->save();
$this->assertFalse($book->isNew(), 'related object is saved if added');
$rels = $list->getBookListRels();
$rel = $rels[0];
$this->assertFalse($rel->isNew(), 'cross object is saved if added');
$list->clearBookListRels();
$list->clearBooks();
$books = $list->getBooks();
$expected = new PropelObjectCollection(array($book));
$expected->setModel('Book');
$this->assertEquals($expected, $books, 'addCrossFk() adds the object properly');
$this->assertEquals(1, $list->countBookListRels());
}
/**
* Test behavior of columns that are implicated in multiple foreign keys.
* @link http://propel.phpdb.org/trac/ticket/228
*/
public function testMultiFkImplication()
{
BookstoreDataPopulator::populate();
// Create a new bookstore, contest, bookstore_contest, and bookstore_contest_entry
$b = new Bookstore();
$b->setStoreName("Foo!");
$b->save();
$c = new Contest();
$c->setName("Bookathon Contest");
$c->save();
$bc = new BookstoreContest();
$bc->setBookstore($b);
$bc->setContest($c);
$bc->save();
$c = new Customer();
$c->setName("Happy Customer");
$c->save();
$bce = new BookstoreContestEntry();
$bce->setBookstore($b);
$bce->setBookstoreContest($bc);
$bce->setCustomer($c);
$bce->save();
$bce->setBookstoreId(null);
$this->assertNull($bce->getBookstoreContest());
$this->assertNull($bce->getBookstore());
}
/**
* Test the clearing of related object collection.
* @link http://propel.phpdb.org/trac/ticket/529
*/
public function testClearRefFk()
{
BookstoreDataPopulator::populate();
$book = new Book();
$book->setISBN("Foo-bar-baz");
$book->setTitle("The book title");
// No save ...
$r = new Review();
$r->setReviewedBy('Me');
$r->setReviewDate(new DateTime("now"));
$book->addReview($r);
// No save (yet) ...
$this->assertEquals(1, count($book->getReviews()) );
$book->clearReviews();
$this->assertEquals(0, count($book->getReviews()));
}
/**
* This tests to see whether modified objects are being silently overwritten by calls to fk accessor methods.
* @link http://propel.phpdb.org/trac/ticket/509#comment:5
*/
public function testModifiedObjectOverwrite()
{
BookstoreDataPopulator::populate();
$author = new Author();
$author->setFirstName("John");
$author->setLastName("Public");
$books = $author->getBooks(); // empty, of course
$this->assertEquals(0, count($books), "Expected empty collection.");
$book = new Book();
$book->setTitle("A sample book");
$book->setISBN("INITIAL ISBN");
$author->addBook($book);
$author->save();
$book->setISBN("MODIFIED ISBN");
$books = $author->getBooks();
$this->assertEquals(1, count($books), "Expected 1 book.");
$this->assertSame($book, $books[0], "Expected the same object to be returned by fk accessor.");
$this->assertEquals("MODIFIED ISBN", $books[0]->getISBN(), "Expected the modified value NOT to have been overwritten.");
}
public function testFKGetterUseInstancePool()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$author = AuthorPeer::doSelectOne(new Criteria(), $con);
// populate book instance pool
$books = $author->getBooks(null, $con);
$sql = $con->getLastExecutedQuery();
$author = $books[0]->getAuthor($con);
$this->assertEquals($sql, $con->getLastExecutedQuery(), 'refFK getter uses instance pool if possible');
}
public function testRefFKGetJoin()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
PublisherPeer::clearInstancePool();
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$author = AuthorPeer::doSelectOne(new Criteria(), $con);
// populate book instance pool
$books = $author->getBooksJoinPublisher(null, $con);
$sql = $con->getLastExecutedQuery();
$publisher = $books[0]->getPublisher($con);
$this->assertEquals($sql, $con->getLastExecutedQuery(), 'refFK getter uses instance pool if possible');
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,545 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Tests the delete methods of the generated Peer classes.
*
* This test uses generated Bookstore classes to test the behavior of various
* peer operations.
*
* The database is relaoded before every test and flushed after every test. This
* means that you can always rely on the contents of the databases being the same
* for each test method in this class. See the BookstoreDataPopulator::populate()
* method for the exact contents of the database.
*
* @see BookstoreDataPopulator
* @author Hans Lellelid <hans@xmpl.org>
* @package generator.builder.om
*/
class GeneratedPeerDoDeleteTest extends BookstoreEmptyTestBase
{
protected function setUp()
{
parent::setUp();
BookstoreDataPopulator::populate();
}
/**
* Test ability to delete multiple rows via single Criteria object.
*/
public function testDoDelete_MultiTable() {
$selc = new Criteria();
$selc->add(BookPeer::TITLE, "Harry Potter and the Order of the Phoenix");
$hp = BookPeer::doSelectOne($selc);
// print "Attempting to delete [multi-table] by found pk: ";
$c = new Criteria();
$c->add(BookPeer::ID, $hp->getId());
// The only way for multi-delete to work currently
// is to specify the author_id and publisher_id (i.e. the fkeys
// have to be in the criteria).
$c->add(AuthorPeer::ID, $hp->getAuthorId());
$c->add(PublisherPeer::ID, $hp->getPublisherId());
$c->setSingleRecord(true);
BookPeer::doDelete($c);
//print_r(AuthorPeer::doSelect(new Criteria()));
// check to make sure the right # of records was removed
$this->assertEquals(3, count(AuthorPeer::doSelect(new Criteria())), "Expected 3 authors after deleting.");
$this->assertEquals(3, count(PublisherPeer::doSelect(new Criteria())), "Expected 3 publishers after deleting.");
$this->assertEquals(3, count(BookPeer::doSelect(new Criteria())), "Expected 3 books after deleting.");
}
/**
* Test using a complex criteria to delete multiple rows from a single table.
*/
public function testDoDelete_ComplexCriteria() {
//print "Attempting to delete books by complex criteria: ";
$c = new Criteria();
$cn = $c->getNewCriterion(BookPeer::ISBN, "043935806X");
$cn->addOr($c->getNewCriterion(BookPeer::ISBN, "0380977427"));
$cn->addOr($c->getNewCriterion(BookPeer::ISBN, "0140422161"));
$c->add($cn);
BookPeer::doDelete($c);
// now there should only be one book left; "The Tin Drum"
$books = BookPeer::doSelect(new Criteria());
$this->assertEquals(1, count($books), "Expected 1 book remaining after deleting.");
$this->assertEquals("The Tin Drum", $books[0]->getTitle(), "Expect the only remaining book to be 'The Tin Drum'");
}
/**
* Test that cascading deletes are happening correctly (whether emulated or native).
*/
public function testDoDelete_Cascade_Simple()
{
// The 'media' table will cascade from book deletes
// 1) Assert the row exists right now
$medias = MediaPeer::doSelect(new Criteria());
$this->assertTrue(count($medias) > 0, "Expected to find at least one row in 'media' table.");
$media = $medias[0];
$mediaId = $media->getId();
// 2) Delete the owning book
$owningBookId = $media->getBookId();
BookPeer::doDelete($owningBookId);
// 3) Assert that the media row is now also gone
$obj = MediaPeer::retrieveByPK($mediaId);
$this->assertNull($obj, "Expect NULL when retrieving on no matching Media.");
}
/**
* Test that cascading deletes are happening correctly for composite pk.
* @link http://propel.phpdb.org/trac/ticket/544
*/
public function testDoDelete_Cascade_CompositePK()
{
$origBceCount = BookstoreContestEntryPeer::doCount(new Criteria());
$cust1 = new Customer();
$cust1->setName("Cust1");
$cust1->save();
$cust2 = new Customer();
$cust2->setName("Cust2");
$cust2->save();
$c1 = new Contest();
$c1->setName("Contest1");
$c1->save();
$c2 = new Contest();
$c2->setName("Contest2");
$c2->save();
$store1 = new Bookstore();
$store1->setStoreName("Store1");
$store1->save();
$bc1 = new BookstoreContest();
$bc1->setBookstore($store1);
$bc1->setContest($c1);
$bc1->save();
$bc2 = new BookstoreContest();
$bc2->setBookstore($store1);
$bc2->setContest($c2);
$bc2->save();
$bce1 = new BookstoreContestEntry();
$bce1->setEntryDate("now");
$bce1->setCustomer($cust1);
$bce1->setBookstoreContest($bc1);
$bce1->save();
$bce2 = new BookstoreContestEntry();
$bce2->setEntryDate("now");
$bce2->setCustomer($cust1);
$bce2->setBookstoreContest($bc2);
$bce2->save();
// Now, if we remove $bc1, we expect *only* bce1 to be no longer valid.
BookstoreContestPeer::doDelete($bc1);
$newCount = BookstoreContestEntryPeer::doCount(new Criteria());
$this->assertEquals($origBceCount + 1, $newCount, "Expected new number of rows in BCE to be orig + 1");
$bcetest = BookstoreContestEntryPeer::retrieveByPK($store1->getId(), $c1->getId(), $cust1->getId());
$this->assertNull($bcetest, "Expected BCE for store1 to be cascade deleted.");
$bcetest2 = BookstoreContestEntryPeer::retrieveByPK($store1->getId(), $c2->getId(), $cust1->getId());
$this->assertNotNull($bcetest2, "Expected BCE for store2 to NOT be cascade deleted.");
}
/**
* Test that onDelete="SETNULL" is happening correctly (whether emulated or native).
*/
public function testDoDelete_SetNull() {
// The 'author_id' column in 'book' table will be set to null when author is deleted.
// 1) Get an arbitrary book
$c = new Criteria();
$book = BookPeer::doSelectOne($c);
$bookId = $book->getId();
$authorId = $book->getAuthorId();
unset($book);
// 2) Delete the author for that book
AuthorPeer::doDelete($authorId);
// 3) Assert that the book.author_id column is now NULL
$book = BookPeer::retrieveByPK($bookId);
$this->assertNull($book->getAuthorId(), "Expect the book.author_id to be NULL after the author was removed.");
}
/**
* Test deleting a row by passing in the primary key to the doDelete() method.
*/
public function testDoDelete_ByPK() {
// 1) get an arbitrary book
$book = BookPeer::doSelectOne(new Criteria());
$bookId = $book->getId();
// 2) now delete that book
BookPeer::doDelete($bookId);
// 3) now make sure it's gone
$obj = BookPeer::retrieveByPK($bookId);
$this->assertNull($obj, "Expect NULL when retrieving on no matching Book.");
}
public function testDoDelete_ByPks() {
// 1) get all of the books
$books = BookPeer::doSelect(new Criteria());
$bookCount = count($books);
// 2) we have enough books to do this test
$this->assertGreaterThan(1, $bookCount, 'There are at least two books');
// 3) select two random books
$book1 = $books[0];
$book2 = $books[1];
// 4) delete the books
BookPeer::doDelete(array($book1->getId(), $book2->getId()));
// 5) we should have two less books than before
$this->assertEquals($bookCount-2, BookPeer::doCount(new Criteria()), 'Two books deleted successfully.');
}
/**
* Test deleting a row by passing the generated object to doDelete().
*/
public function testDoDelete_ByObj() {
// 1) get an arbitrary book
$book = BookPeer::doSelectOne(new Criteria());
$bookId = $book->getId();
// 2) now delete that book
BookPeer::doDelete($book);
// 3) now make sure it's gone
$obj = BookPeer::retrieveByPK($bookId);
$this->assertNull($obj, "Expect NULL when retrieving on no matching Book.");
}
/**
* Test the doDeleteAll() method for single table.
*/
public function testDoDeleteAll() {
BookPeer::doDeleteAll();
$this->assertEquals(0, count(BookPeer::doSelect(new Criteria())), "Expect all book rows to have been deleted.");
}
/**
* Test the state of the instance pool after a doDeleteAll() call.
*/
public function testDoDeleteAllInstancePool()
{
$review = ReviewPeer::doSelectOne(new Criteria);
$book = $review->getBook();
BookPeer::doDeleteAll();
$this->assertNull(BookPeer::retrieveByPk($book->getId()), 'doDeleteAll invalidates instance pool');
$this->assertNull(ReviewPeer::retrieveByPk($review->getId()), 'doDeleteAll invalidates instance pool of releted tables with ON DELETE CASCADE');
}
/**
* Test the doDeleteAll() method when onDelete="CASCADE".
*/
public function testDoDeleteAll_Cascade() {
BookPeer::doDeleteAll();
$this->assertEquals(0, count(MediaPeer::doSelect(new Criteria())), "Expect all media rows to have been cascade deleted.");
$this->assertEquals(0, count(ReviewPeer::doSelect(new Criteria())), "Expect all review rows to have been cascade deleted.");
}
/**
* Test the doDeleteAll() method when onDelete="SETNULL".
*/
public function testDoDeleteAll_SetNull() {
$c = new Criteria();
$c->add(BookPeer::AUTHOR_ID, null, Criteria::NOT_EQUAL);
// 1) make sure there are some books with valid authors
$this->assertTrue(count(BookPeer::doSelect($c)) > 0, "Expect some book.author_id columns that are not NULL.");
// 2) delete all the authors
AuthorPeer::doDeleteAll();
// 3) now verify that the book.author_id columns are all nul
$this->assertEquals(0, count(BookPeer::doSelect($c)), "Expect all book.author_id columns to be NULL.");
}
/**
* @link http://propel.phpdb.org/trac/ticket/519
*/
public function testDoDeleteCompositePK()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
ReaderFavoritePeer::doDeleteAll();
// Create books with IDs 1 to 3
// Create readers with IDs 1 and 2
$this->createBookWithId(1);
$this->createBookWithId(2);
$this->createBookWithId(3);
$this->createReaderWithId(1);
$this->createReaderWithId(2);
for ($i=1; $i <= 3; $i++) {
for ($j=1; $j <= 2; $j++) {
$bo = new BookOpinion();
$bo->setBookId($i);
$bo->setReaderId($j);
$bo->save();
$rf = new ReaderFavorite();
$rf->setBookId($i);
$rf->setReaderId($j);
$rf->save();
}
}
$this->assertEquals(6, ReaderFavoritePeer::doCount(new Criteria()));
// Now delete 2 of those rows (2 is special in that it is the number of rows
// being deleted, as well as the number of things in the primary key)
ReaderFavoritePeer::doDelete(array(array(1,1), array(2,2)));
$this->assertEquals(4, ReaderFavoritePeer::doCount(new Criteria()));
//Note: these composite PK's are pairs of (BookId, ReaderId)
$this->assertNotNull(ReaderFavoritePeer::retrieveByPK(2,1));
$this->assertNotNull(ReaderFavoritePeer::retrieveByPK(1,2));
$this->assertNotNull(ReaderFavoritePeer::retrieveByPk(3,1));
$this->assertNotNull(ReaderFavoritePeer::retrieveByPk(3,2));
$this->assertNull(ReaderFavoritePeer::retrieveByPK(1,1));
$this->assertNull(ReaderFavoritePeer::retrieveByPK(2,2));
//test deletion of a single composite PK
ReaderFavoritePeer::doDelete(array(3,1));
$this->assertEquals(3, ReaderFavoritePeer::doCount(new Criteria()));
$this->assertNotNull(ReaderFavoritePeer::retrieveByPK(2,1));
$this->assertNotNull(ReaderFavoritePeer::retrieveByPK(1,2));
$this->assertNotNull(ReaderFavoritePeer::retrieveByPk(3,2));
$this->assertNull(ReaderFavoritePeer::retrieveByPK(1,1));
$this->assertNull(ReaderFavoritePeer::retrieveByPK(2,2));
$this->assertNull(ReaderFavoritePeer::retrieveByPk(3,1));
//test deleting the last three
ReaderFavoritePeer::doDelete(array(array(2,1), array(1,2), array(3,2)));
$this->assertEquals(0, ReaderFavoritePeer::doCount(new Criteria()));
}
/**
* Test the doInsert() method when passed a Criteria object.
*/
public function testDoInsert_Criteria() {
$name = "A Sample Publisher - " . time();
$values = new Criteria();
$values->add(PublisherPeer::NAME, $name);
PublisherPeer::doInsert($values);
$c = new Criteria();
$c->add(PublisherPeer::NAME, $name);
$matches = PublisherPeer::doSelect($c);
$this->assertEquals(1, count($matches), "Expect there to be exactly 1 publisher just-inserted.");
$this->assertTrue( 1 != $matches[0]->getId(), "Expected to have different ID than one put in values Criteria.");
}
/**
* Test the doInsert() method when passed a generated object.
*/
public function testDoInsert_Obj() {
$name = "A Sample Publisher - " . time();
$values = new Publisher();
$values->setName($name);
PublisherPeer::doInsert($values);
$c = new Criteria();
$c->add(PublisherPeer::NAME, $name);
$matches = PublisherPeer::doSelect($c);
$this->assertEquals(1, count($matches), "Expect there to be exactly 1 publisher just-inserted.");
$this->assertTrue( 1 != $matches[0]->getId(), "Expected to have different ID than one put in values Criteria.");
}
/**
* Tests the return type of doCount*() methods.
*/
public function testDoCountType()
{
$c = new Criteria();
$this->assertType('integer', BookPeer::doCount($c), "Expected doCount() to return an integer.");
$this->assertType('integer', BookPeer::doCountJoinAll($c), "Expected doCountJoinAll() to return an integer.");
$this->assertType('integer', BookPeer::doCountJoinAuthor($c), "Expected doCountJoinAuthor() to return an integer.");
}
/**
* Tests the doCount() method with limit/offset.
*/
public function testDoCountLimitOffset()
{
BookPeer::doDeleteAll();
for ($i=0; $i < 25; $i++) {
$b = new Book();
$b->setTitle("Book $i");
$b->setISBN("ISBN $i");
$b->save();
}
$c = new Criteria();
$totalCount = BookPeer::doCount($c);
$this->assertEquals(25, $totalCount);
$c2 = new Criteria();
$c2->setLimit(10);
$this->assertEquals(10, BookPeer::doCount($c2));
$c3 = new Criteria();
$c3->setOffset(10);
$this->assertEquals(15, BookPeer::doCount($c3));
$c4 = new Criteria();
$c4->setOffset(5);
$c4->setLimit(5);
$this->assertEquals(5, BookPeer::doCount($c4));
$c5 = new Criteria();
$c5->setOffset(20);
$c5->setLimit(10);
$this->assertEquals(5, BookPeer::doCount($c5));
}
/**
* Test doCountJoin*() methods.
*/
public function testDoCountJoin()
{
BookPeer::doDeleteAll();
for ($i=0; $i < 25; $i++) {
$b = new Book();
$b->setTitle("Book $i");
$b->setISBN("ISBN $i");
$b->save();
}
$c = new Criteria();
$totalCount = BookPeer::doCount($c);
$this->assertEquals($totalCount, BookPeer::doCountJoinAuthor($c));
$this->assertEquals($totalCount, BookPeer::doCountJoinPublisher($c));
}
/**
* Test doCountJoin*() methods with ORDER BY columns in Criteria.
* @link http://propel.phpdb.org/trac/ticket/627
*/
public function testDoCountJoinWithOrderBy()
{
$c = new Criteria(BookPeer::DATABASE_NAME);
$c->addAscendingOrderByColumn(BookPeer::ID);
// None of these should not throw an exception!
BookPeer::doCountJoinAll($c);
BookPeer::doCountJoinAllExceptAuthor($c);
BookPeer::doCountJoinAuthor($c);
}
/**
* Test passing null values to removeInstanceFromPool().
*/
public function testRemoveInstanceFromPool_Null()
{
// if it throws an exception, then it's broken.
try {
BookPeer::removeInstanceFromPool(null);
} catch (Exception $x) {
$this->fail("Expected to get no exception when removing an instance from the pool.");
}
}
/**
* @see testDoDeleteCompositePK()
*/
private function createBookWithId($id)
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$b = BookPeer::retrieveByPK($id);
if (!$b) {
$b = new Book();
$b->setTitle("Book$id")->setISBN("BookISBN$id")->save();
$b1Id = $b->getId();
$sql = "UPDATE " . BookPeer::TABLE_NAME . " SET id = ? WHERE id = ?";
$stmt = $con->prepare($sql);
$stmt->bindValue(1, $id);
$stmt->bindValue(2, $b1Id);
$stmt->execute();
}
}
/**
* @see testDoDeleteCompositePK()
*/
private function createReaderWithId($id)
{
$con = Propel::getConnection(BookReaderPeer::DATABASE_NAME);
$r = BookReaderPeer::retrieveByPK($id);
if (!$r) {
$r = new BookReader();
$r->setName('Reader'.$id)->save();
$r1Id = $r->getId();
$sql = "UPDATE " . BookReaderPeer::TABLE_NAME . " SET id = ? WHERE id = ?";
$stmt = $con->prepare($sql);
$stmt->bindValue(1, $id);
$stmt->bindValue(2, $r1Id);
$stmt->execute();
}
}
}

View file

@ -0,0 +1,439 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Tests the generated Peer classes.
*
* This test uses generated Bookstore classes to test the behavior of various
* peer operations.
*
* The database is relaoded before every test and flushed after every test. This
* means that you can always rely on the contents of the databases being the same
* for each test method in this class. See the BookstoreDataPopulator::populate()
* method for the exact contents of the database.
*
* @see BookstoreDataPopulator
* @author Hans Lellelid <hans@xmpl.org>
* @package generator.builder.om
*/
class GeneratedPeerDoSelectTest extends BookstoreEmptyTestBase
{
protected function setUp()
{
parent::setUp();
BookstoreDataPopulator::populate();
}
public function testDoSelect()
{
$books = BookPeer::doSelect(new Criteria());
$this->assertEquals(4, count($books), 'doSelect() with an empty Criteria returns all results');
$book1 = $books[0];
$c = new Criteria();
$c->add(BookPeer::ID, $book1->getId());
$res = BookPeer::doSelect($c);
$this->assertEquals(array($book1), $res, 'doSelect() accepts a Criteria object with a condition');
$c = new Criteria();
$c->add(BookPeer::ID, $book1->getId());
$c->add(BookPeer::TITLE, $book1->getTitle());
$res = BookPeer::doSelect($c);
$this->assertEquals(array($book1), $res, 'doSelect() accepts a Criteria object with several condition');
$c = new Criteria();
$c->add(BookPeer::ID, 'foo');
$res = BookPeer::doSelect($c);
$this->assertEquals(array(), $res, 'doSelect() accepts an incorrect Criteria');
}
/**
* Tests performing doSelect() and doSelectJoin() using LIMITs.
*/
public function testDoSelect_Limit() {
// 1) get the total number of items in a particular table
$count = BookPeer::doCount(new Criteria());
$this->assertTrue($count > 1, "Need more than 1 record in books table to perform this test.");
$limitcount = $count - 1;
$lc = new Criteria();
$lc->setLimit($limitcount);
$results = BookPeer::doSelect($lc);
$this->assertEquals($limitcount, count($results), "Expected $limitcount results from BookPeer::doSelect()");
// re-create it just to avoid side-effects
$lc2 = new Criteria();
$lc2->setLimit($limitcount);
$results2 = BookPeer::doSelectJoinAuthor($lc2);
$this->assertEquals($limitcount, count($results2), "Expected $limitcount results from BookPeer::doSelectJoinAuthor()");
}
/**
* Test the basic functionality of the doSelectJoin*() methods.
*/
public function testDoSelectJoin()
{
BookPeer::clearInstancePool();
$c = new Criteria();
$books = BookPeer::doSelect($c);
$obj = $books[0];
// $size = strlen(serialize($obj));
BookPeer::clearInstancePool();
$joinBooks = BookPeer::doSelectJoinAuthor($c);
$obj2 = $joinBooks[0];
$obj2Array = $obj2->toArray(BasePeer::TYPE_PHPNAME, true, true);
// $joinSize = strlen(serialize($obj2));
$this->assertEquals(count($books), count($joinBooks), "Expected to find same number of rows in doSelectJoin*() call as doSelect() call.");
// $this->assertTrue($joinSize > $size, "Expected a serialized join object to be larger than a non-join object.");
$this->assertTrue(array_key_exists('Author', $obj2Array));
}
/**
* Test the doSelectJoin*() methods when the related object is NULL.
*/
public function testDoSelectJoin_NullFk()
{
$b1 = new Book();
$b1->setTitle("Test NULLFK 1");
$b1->setISBN("NULLFK-1");
$b1->save();
$b2 = new Book();
$b2->setTitle("Test NULLFK 2");
$b2->setISBN("NULLFK-2");
$b2->setAuthor(new Author());
$b2->getAuthor()->setFirstName("Hans")->setLastName("L");
$b2->save();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
$c = new Criteria();
$c->add(BookPeer::ISBN, 'NULLFK-%', Criteria::LIKE);
$c->addAscendingOrderByColumn(BookPeer::ISBN);
$matches = BookPeer::doSelectJoinAuthor($c);
$this->assertEquals(2, count($matches), "Expected 2 matches back from new books; got back " . count($matches));
$this->assertNull($matches[0]->getAuthor(), "Expected first book author to be null");
$this->assertType('Author', $matches[1]->getAuthor(), "Expected valid Author object for second book.");
}
public function testDoSelectJoinOneToOne()
{
$con = Propel::getConnection();
$count = $con->getQueryCount();
Propel::disableInstancePooling();
$c = new Criteria();
$accs = BookstoreEmployeeAccountPeer::doSelectJoinBookstoreEmployee($c);
Propel::enableInstancePooling();
$this->assertEquals(1, $con->getQueryCount() - $count, 'doSelectJoin() makes only one query in a one-to-one relationship');
}
public function testDoSelectOne()
{
$books = BookPeer::doSelect(new Criteria());
$book1 = $books[0];
$c = new Criteria();
$c->add(BookPeer::ID, $book1->getId());
$res = BookPeer::doSelectOne($c);
$this->assertEquals($book1, $res, 'doSelectOne() returns a single object');
$c = new Criteria();
$c->add(BookPeer::ID, 'foo');
$res = BookPeer::doSelectOne($c);
$this->assertNull($res, 'doSelectOne() returns null if the Criteria matches no record');
}
public function testObjectInstances()
{
$sample = BookPeer::doSelectOne(new Criteria());
$samplePk = $sample->getPrimaryKey();
// 1) make sure consecutive calls to retrieveByPK() return the same object.
$b1 = BookPeer::retrieveByPK($samplePk);
$b2 = BookPeer::retrieveByPK($samplePk);
$sampleval = md5(microtime());
$this->assertTrue($b1 === $b2, "Expected object instances to match for calls with same retrieveByPK() method signature.");
// 2) make sure that calls to doSelect also return references to the same objects.
$allbooks = BookPeer::doSelect(new Criteria());
foreach ($allbooks as $testb) {
if ($testb->getPrimaryKey() == $b1->getPrimaryKey()) {
$this->assertTrue($testb === $b1, "Expected same object instance from doSelect() as from retrieveByPK()");
}
}
// 3) test fetching related objects
$book = BookPeer::retrieveByPK($samplePk);
$bookauthor = $book->getAuthor();
$author = AuthorPeer::retrieveByPK($bookauthor->getId());
$this->assertTrue($bookauthor === $author, "Expected same object instance when calling fk object accessor as retrieveByPK()");
// 4) test a doSelectJoin()
$morebooks = BookPeer::doSelectJoinAuthor(new Criteria());
for ($i=0,$j=0; $j < count($morebooks); $i++, $j++) {
$testb1 = $allbooks[$i];
$testb2 = $allbooks[$j];
$this->assertTrue($testb1 === $testb2, "Expected the same objects from consecutive doSelect() calls.");
// we could probably also test this by just verifying that $book & $testb are the same
if ($testb1->getPrimaryKey() === $book) {
$this->assertTrue($book->getAuthor() === $testb1->getAuthor(), "Expected same author object in calls to pkey-matching books.");
}
}
// 5) test creating a new object, saving it, and then retrieving that object (should all be same instance)
$b = new BookstoreEmployee();
$b->setName("Testing");
$b->setJobTitle("Testing");
$b->save();
$empId = $b->getId();
$this->assertSame($b, BookstoreEmployeePeer::retrieveByPK($empId), "Expected newly saved object to be same instance as pooled.");
}
/**
* Test inheritance features.
*/
public function testInheritance()
{
$manager = new BookstoreManager();
$manager->setName("Manager 1");
$manager->setJobTitle("Warehouse Manager");
$manager->save();
$managerId = $manager->getId();
$employee = new BookstoreEmployee();
$employee->setName("Employee 1");
$employee->setJobTitle("Janitor");
$employee->setSupervisorId($managerId);
$employee->save();
$empId = $employee->getId();
$cashier = new BookstoreCashier();
$cashier->setName("Cashier 1");
$cashier->setJobTitle("Cashier");
$cashier->save();
$cashierId = $cashier->getId();
// 1) test the pooled instances'
$c = new Criteria();
$c->add(BookstoreEmployeePeer::ID, array($managerId, $empId, $cashierId), Criteria::IN);
$c->addAscendingOrderByColumn(BookstoreEmployeePeer::ID);
$objects = BookstoreEmployeePeer::doSelect($c);
$this->assertEquals(3, count($objects), "Expected 3 objects to be returned.");
list($o1, $o2, $o3) = $objects;
$this->assertSame($o1, $manager);
$this->assertSame($o2, $employee);
$this->assertSame($o3, $cashier);
// 2) test a forced reload from database
BookstoreEmployeePeer::clearInstancePool();
list($o1,$o2,$o3) = BookstoreEmployeePeer::doSelect($c);
$this->assertTrue($o1 instanceof BookstoreManager, "Expected BookstoreManager object, got " . get_class($o1));
$this->assertTrue($o2 instanceof BookstoreEmployee, "Expected BookstoreEmployee object, got " . get_class($o2));
$this->assertTrue($o3 instanceof BookstoreCashier, "Expected BookstoreCashier object, got " . get_class($o3));
}
/**
* Test hydration of joined rows that contain lazy load columns.
* @link http://propel.phpdb.org/trac/ticket/464
*/
public function testHydrationJoinLazyLoad()
{
BookstoreEmployeeAccountPeer::doDeleteAll();
BookstoreEmployeePeer::doDeleteAll();
AcctAccessRolePeer::doDeleteAll();
$bemp2 = new BookstoreEmployee();
$bemp2->setName("Pieter");
$bemp2->setJobTitle("Clerk");
$bemp2->save();
$role = new AcctAccessRole();
$role->setName("Admin");
$bempacct = new BookstoreEmployeeAccount();
$bempacct->setBookstoreEmployee($bemp2);
$bempacct->setAcctAccessRole($role);
$bempacct->setLogin("john");
$bempacct->setPassword("johnp4ss");
$bempacct->save();
$c = new Criteria();
$results = BookstoreEmployeeAccountPeer::doSelectJoinAll($c);
$o = $results[0];
$this->assertEquals('Admin', $o->getAcctAccessRole()->getName());
}
/**
* Testing foreign keys with multiple referrer columns.
* @link http://propel.phpdb.org/trac/ticket/606
*/
public function testMultiColFk()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
ReaderFavoritePeer::doDeleteAll();
$b1 = new Book();
$b1->setTitle("Book1");
$b1->setISBN("ISBN-1");
$b1->save();
$r1 = new BookReader();
$r1-> setName("Me");
$r1->save();
$bo1 = new BookOpinion();
$bo1->setBookId($b1->getId());
$bo1->setReaderId($r1->getId());
$bo1->setRating(9);
$bo1->setRecommendToFriend(true);
$bo1->save();
$rf1 = new ReaderFavorite();
$rf1->setReaderId($r1->getId());
$rf1->setBookId($b1->getId());
$rf1->save();
$c = new Criteria(ReaderFavoritePeer::DATABASE_NAME);
$c->add(ReaderFavoritePeer::BOOK_ID, $b1->getId());
$c->add(ReaderFavoritePeer::READER_ID, $r1->getId());
$results = ReaderFavoritePeer::doSelectJoinBookOpinion($c);
$this->assertEquals(1, count($results), "Expected 1 result");
}
/**
* Testing foreign keys with multiple referrer columns.
* @link http://propel.phpdb.org/trac/ticket/606
*/
public function testMultiColJoin()
{
BookstoreContestPeer::doDeleteAll();
BookstoreContestEntryPeer::doDeleteAll();
$bs = new Bookstore();
$bs->setStoreName("Test1");
$bs->setPopulationServed(5);
$bs->save();
$bs1Id = $bs->getId();
$bs2 = new Bookstore();
$bs2->setStoreName("Test2");
$bs2->setPopulationServed(5);
$bs2->save();
$bs2Id = $bs2->getId();
$ct1 = new Contest();
$ct1->setName("Contest1!");
$ct1->save();
$ct1Id = $ct1->getId();
$ct2 = new Contest();
$ct2->setName("Contest2!");
$ct2->save();
$ct2Id = $ct2->getId();
$cmr = new Customer();
$cmr->setName("Customer1");
$cmr->save();
$cmr1Id = $cmr->getId();
$cmr2 = new Customer();
$cmr2->setName("Customer2");
$cmr2->save();
$cmr2Id = $cmr2->getId();
$contest = new BookstoreContest();
$contest->setBookstoreId($bs1Id);
$contest->setContestId($ct1Id);
$contest->save();
$contest = new BookstoreContest();
$contest->setBookstoreId($bs2Id);
$contest->setContestId($ct1Id);
$contest->save();
$entry = new BookstoreContestEntry();
$entry->setBookstoreId($bs1Id);
$entry->setContestId($ct1Id);
$entry->setCustomerId($cmr1Id);
$entry->save();
$entry = new BookstoreContestEntry();
$entry->setBookstoreId($bs1Id);
$entry->setContestId($ct1Id);
$entry->setCustomerId($cmr2Id);
$entry->save();
// Note: this test isn't really working very well. We setup fkeys that
// require that the BookstoreContest rows exist and then try to violate
// the rules ... :-/ This may work in some lenient databases, but an error
// is expected here.
/*
* Commented out for now ... though without it, this test may not really be testing anything
$entry = new BookstoreContestEntry();
$entry->setBookstoreId($bs1Id);
$entry->setContestId($ct2Id);
$entry->setCustomerId($cmr2Id);
$entry->save();
*/
$c = new Criteria();
$c->addJoin(array(BookstoreContestEntryPeer::BOOKSTORE_ID, BookstoreContestEntryPeer::CONTEST_ID), array(BookstoreContestPeer::BOOKSTORE_ID, BookstoreContestPeer::CONTEST_ID) );
$results = BookstoreContestEntryPeer::doSelect($c);
$this->assertEquals(2, count($results) );
foreach ($results as $result) {
$this->assertEquals($bs1Id, $result->getBookstoreId() );
$this->assertEquals($ct1Id, $result->getContestId() );
}
}
}

View file

@ -0,0 +1,90 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests the generated Peer classes.
*
* This test uses generated Bookstore classes to test the behavior of various
* peer operations.
*
* The database is relaoded before every test and flushed after every test. This
* means that you can always rely on the contents of the databases being the same
* for each test method in this class. See the BookstoreDataPopulator::populate()
* method for the exact contents of the database.
*
* @see BookstoreDataPopulator
* @author Hans Lellelid <hans@xmpl.org>
* @package generator.builder.om
*/
class GeneratedPeerTest extends BookstoreTestBase
{
public function testAlias()
{
$this->assertEquals('foo.ID', BookPeer::alias('foo', BookPeer::ID), 'alias() returns a column name using the table alias');
$this->assertEquals('book.ID', BookPeer::alias('book', BookPeer::ID), 'alias() returns a column name using the table alias');
$this->assertEquals('foo.COVER_IMAGE', MediaPeer::alias('foo', MediaPeer::COVER_IMAGE), 'alias() also works for lazy-loaded columns');
$this->assertEquals('foo.SUBTITLE', EssayPeer::alias('foo', EssayPeer::SUBTITLE), 'alias() also works for columns with custom phpName');
}
public function testAddSelectColumns()
{
$c = new Criteria();
BookPeer::addSelectColumns($c);
$expected = array(
BookPeer::ID,
BookPeer::TITLE,
BookPeer::ISBN,
BookPeer::PRICE,
BookPeer::PUBLISHER_ID,
BookPeer::AUTHOR_ID
);
$this->assertEquals($expected, $c->getSelectColumns(), 'addSelectColumns() adds the columns of the model to the criteria');
}
public function testAddSelectColumnsLazyLoad()
{
$c = new Criteria();
MediaPeer::addSelectColumns($c);
$expected = array(
MediaPeer::ID,
MediaPeer::BOOK_ID
);
$this->assertEquals($expected, $c->getSelectColumns(), 'addSelectColumns() does not add lazy loaded columns');
}
public function testAddSelectColumnsAlias()
{
$c = new Criteria();
BookPeer::addSelectColumns($c, 'foo');
$expected = array(
'foo.ID',
'foo.TITLE',
'foo.ISBN',
'foo.PRICE',
'foo.PUBLISHER_ID',
'foo.AUTHOR_ID'
);
$this->assertEquals($expected, $c->getSelectColumns(), 'addSelectColumns() uses the second parameter as a table alias');
}
public function testAddSelectColumnsAliasLazyLoad()
{
$c = new Criteria();
MediaPeer::addSelectColumns($c, 'bar');
$expected = array(
'bar.ID',
'bar.BOOK_ID'
);
$this->assertEquals($expected, $c->getSelectColumns(), 'addSelectColumns() does not add lazy loaded columns but uses the second parameter as an alias');
}
}

View file

@ -0,0 +1,149 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'model/Database.php';
require_once 'model/Table.php';
require_once 'builder/om/OMBuilder.php';
require_once 'platform/MysqlPlatform.php';
/**
* Test class for OMBuilder.
*
* @author François Zaninotto
* @version $Id: OMBuilderBuilderTest.php 1347 2009-12-03 21:06:36Z francois $
* @package generator.builder.om
*/
class OMBuilderNamespaceTest extends PHPUnit_Framework_TestCase
{
public function testNoNamespace()
{
$d = new Database('fooDb');
$t = new Table('fooTable');
$d->addTable($t);
$builder = new TestableOMBuilder2($t);
$this->assertNull($builder->getNamespace(), 'Builder namespace is null when neither the db nor the table have namespace');
}
public function testDbNamespace()
{
$d = new Database('fooDb');
$d->setNamespace('Foo\\Bar');
$t = new Table('fooTable');
$d->addTable($t);
$builder = new TestableOMBuilder2($t);
$this->assertEquals('Foo\\Bar', $builder->getNamespace(), 'Builder namespace is the database namespace when no table namespace is set');
}
public function testTableNamespace()
{
$d = new Database('fooDb');
$t = new Table('fooTable');
$t->setNamespace('Foo\\Bar');
$d->addTable($t);
$builder = new TestableOMBuilder2($t);
$this->assertEquals('Foo\\Bar', $builder->getNamespace(), 'Builder namespace is the table namespace when no database namespace is set');
}
public function testAbsoluteTableNamespace()
{
$d = new Database('fooDb');
$t = new Table('fooTable');
$t->setNamespace('\\Foo\\Bar');
$d->addTable($t);
$builder = new TestableOMBuilder2($t);
$this->assertEquals('Foo\\Bar', $builder->getNamespace(), 'Builder namespace is the table namespace when it is set as absolute');
}
public function testAbsoluteTableNamespaceAndDbNamespace()
{
$d = new Database('fooDb');
$d->setNamespace('Baz');
$t = new Table('fooTable');
$t->setNamespace('\\Foo\\Bar');
$d->addTable($t);
$builder = new TestableOMBuilder2($t);
$this->assertEquals('Foo\\Bar', $builder->getNamespace(), 'Builder namespace is the table namespace when it is set as absolute');
}
public function testTableNamespaceAndDbNamespace()
{
$d = new Database('fooDb');
$d->setNamespace('Baz');
$t = new Table('fooTable');
$t->setNamespace('Foo\\Bar');
$d->addTable($t);
$builder = new TestableOMBuilder2($t);
$this->assertEquals('Baz\\Foo\\Bar', $builder->getNamespace(), 'Builder namespace is composed from the database and table namespaces when both are set');
}
public function testDeclareClassNamespace()
{
$builder = new TestableOMBuilder2(new Table('fooTable'));
$builder->declareClassNamespace('Foo');
$this->assertEquals(array('' => array('Foo')), $builder->getDeclaredClasses());
$builder->declareClassNamespace('Bar');
$this->assertEquals(array('' => array('Foo', 'Bar')), $builder->getDeclaredClasses());
$builder->declareClassNamespace('Foo');
$this->assertEquals(array('' => array('Foo', 'Bar')), $builder->getDeclaredClasses());
$builder = new TestableOMBuilder2(new Table('fooTable'));
$builder->declareClassNamespace('Foo', 'Foo');
$this->assertEquals(array('Foo' => array('Foo')), $builder->getDeclaredClasses());
$builder->declareClassNamespace('Bar', 'Foo');
$this->assertEquals(array('Foo' => array('Foo', 'Bar')), $builder->getDeclaredClasses());
$builder->declareClassNamespace('Foo', 'Foo');
$this->assertEquals(array('Foo' => array('Foo', 'Bar')), $builder->getDeclaredClasses());
$builder->declareClassNamespace('Bar', 'Bar');
$this->assertEquals(array('Foo' => array('Foo', 'Bar'), 'Bar' => array('Bar')), $builder->getDeclaredClasses());
}
public function testGetDeclareClass()
{
$builder = new TestableOMBuilder2(new Table('fooTable'));
$this->assertEquals(array(), $builder->getDeclaredClasses());
$builder->declareClass('\\Foo');
$this->assertEquals(array('Foo'), $builder->getDeclaredClasses(''));
$builder->declareClass('Bar');
$this->assertEquals(array('Foo', 'Bar'), $builder->getDeclaredClasses(''));
$builder->declareClass('Foo\\Bar');
$this->assertEquals(array('Bar'), $builder->getDeclaredClasses('Foo'));
$builder->declareClass('Foo\\Bar\\Baz');
$this->assertEquals(array('Bar'), $builder->getDeclaredClasses('Foo'));
$this->assertEquals(array('Baz'), $builder->getDeclaredClasses('Foo\\Bar'));
$builder->declareClass('\\Hello\\World');
$this->assertEquals(array('World'), $builder->getDeclaredClasses('Hello'));
}
public function testDeclareClasses()
{
$builder = new TestableOMBuilder2(new Table('fooTable'));
$builder->declareClasses('Foo', '\\Bar', 'Baz\\Baz', 'Hello\\Cruel\\World');
$expected = array(
'' => array('Foo', 'Bar'),
'Baz' => array('Baz'),
'Hello\\Cruel' => array('World')
);
$this->assertEquals($expected, $builder->getDeclaredClasses());
}
}
class TestableOMBuilder2 extends OMBuilder
{
public static function getRelatedBySuffix(ForeignKey $fk)
{
return parent::getRelatedBySuffix($fk);
}
public static function getRefRelatedBySuffix(ForeignKey $fk)
{
return parent::getRefRelatedBySuffix($fk);
}
public function getUnprefixedClassname() {}
}

View file

@ -0,0 +1,89 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
require_once 'builder/om/OMBuilder.php';
require_once 'builder/util/XmlToAppData.php';
require_once 'platform/MysqlPlatform.php';
/**
* Test class for OMBuilder.
*
* @author François Zaninotto
* @version $Id: OMBuilderBuilderTest.php 1347 2009-12-03 21:06:36Z francois $
* @package generator.builder.om
*/
class OMBuilderTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null);
$appData = $xmlToAppData->parseFile('fixtures/bookstore/schema.xml');
$this->database = $appData->getDatabase("bookstore");
}
protected function getForeignKey($tableName, $index)
{
$fks = $this->database->getTable($tableName)->getForeignKeys();
return $fks[$index];
}
public static function getRelatedBySuffixDataProvider()
{
return array(
array('book', 0, '', ''),
array('essay', 0, 'RelatedByFirstAuthor', 'RelatedByFirstAuthor'),
array('essay', 1, 'RelatedBySecondAuthor', 'RelatedBySecondAuthor'),
array('essay', 2, 'RelatedById', 'RelatedByNextEssayId'),
array('bookstore_employee', 0, 'RelatedById', 'RelatedBySupervisorId'),
array('composite_essay', 0, 'RelatedById0', 'RelatedByFirstEssayId'),
array('composite_essay', 1, 'RelatedById1', 'RelatedBySecondEssayId'),
array('man', 0, 'RelatedByWifeId', 'RelatedByWifeId'),
array('woman', 0, 'RelatedByHusbandId', 'RelatedByHusbandId'),
);
}
/**
* @dataProvider getRelatedBySuffixDataProvider
*/
public function testGetRelatedBySuffix($table, $index, $expectedSuffix, $expectedReverseSuffix)
{
$fk = $this->getForeignKey($table, $index);
$this->assertEquals($expectedSuffix, TestableOMBuilder::getRefRelatedBySuffix($fk));
$this->assertEquals($expectedReverseSuffix, TestableOMBuilder::getRelatedBySuffix($fk));
}
public function testClear()
{
$b = new Book();
$b->setNew(false);
$b->clear();
$this->assertTrue($b->isNew(), 'clear() sets the object to new');
$b = new Book();
$b->setDeleted(true);
$b->clear();
$this->assertFalse($b->isDeleted(), 'clear() sets the object to not deleted');
}
}
class TestableOMBuilder extends OMBuilder
{
public static function getRelatedBySuffix(ForeignKey $fk)
{
return parent::getRelatedBySuffix($fk);
}
public static function getRefRelatedBySuffix(ForeignKey $fk)
{
return parent::getRefRelatedBySuffix($fk);
}
public function getUnprefixedClassname() {}
}

View file

@ -0,0 +1,149 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Test class for PHP5TableMapBuilder.
*
* @author François Zaninotto
* @version $Id: PHP5TableMapBuilderTest.php 1612 2010-03-16 22:56:21Z francois $
* @package generator.builder.om
*/
class PHP5TableMapBuilderTest extends BookstoreTestBase
{
protected $databaseMap;
protected function setUp()
{
parent::setUp();
$this->databaseMap = Propel::getDatabaseMap('bookstore');
}
public function testColumnDefaultValue()
{
$table = $this->databaseMap->getTableByPhpName('BookstoreEmployeeAccount');
$this->assertNull($table->getColumn('login')->getDefaultValue(), 'null default values are correctly mapped');
$this->assertEquals('\'@\'\'34"', $table->getColumn('password')->getDefaultValue(), 'string default values are correctly escaped and mapped');
$this->assertTrue($table->getColumn('enabled')->getDefaultValue(), 'boolean default values are correctly mapped');
$this->assertFalse($table->getColumn('not_enabled')->getDefaultValue(), 'boolean default values are correctly mapped');
$this->assertEquals('CURRENT_TIMESTAMP', $table->getColumn('created')->getDefaultValue(), 'expression default values are correctly mapped');
$this->assertNull($table->getColumn('role_id')->getDefaultValue(), 'explicit null default values are correctly mapped');
}
public function testRelationCount()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$this->assertEquals(9, count($bookTable->getRelations()), 'The map builder creates relations for both incoming and outgoing keys');
}
public function testSimpleRelationName()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$this->assertTrue($bookTable->hasRelation('Publisher'), 'The map builder creates relations based on the foreign table name, calemized');
$this->assertTrue($bookTable->hasRelation('BookListRel'), 'The map builder creates relations based on the foreign table phpName, if provided');
}
public function testAliasRelationName()
{
$bookEmpTable = $this->databaseMap->getTableByPhpName('BookstoreEmployee');
$this->assertTrue($bookEmpTable->hasRelation('Supervisor'), 'The map builder creates relations based on the foreign key phpName');
$this->assertTrue($bookEmpTable->hasRelation('Subordinate'), 'The map builder creates relations based on the foreign key refPhpName');
}
public function testDuplicateRelationName()
{
$essayTable = $this->databaseMap->getTableByPhpName('Essay');
$this->assertTrue($essayTable->hasRelation('AuthorRelatedByFirstAuthor'), 'The map builder creates relations based on the foreign table name and the foreign key');
$this->assertTrue($essayTable->hasRelation('AuthorRelatedBySecondAuthor'), 'The map builder creates relations based on the foreign table name and the foreign key');
}
public function testRelationDirectionManyToOne()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$this->assertEquals(RelationMap::MANY_TO_ONE, $bookTable->getRelation('Publisher')->getType(), 'The map builder creates MANY_TO_ONE relations for every foreign key');
$this->assertEquals(RelationMap::MANY_TO_ONE, $bookTable->getRelation('Author')->getType(), 'The map builder creates MANY_TO_ONE relations for every foreign key');
}
public function testRelationDirectionOneToMany()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$this->assertEquals(RelationMap::ONE_TO_MANY, $bookTable->getRelation('Review')->getType(), 'The map builder creates ONE_TO_MANY relations for every incoming foreign key');
$this->assertEquals(RelationMap::ONE_TO_MANY, $bookTable->getRelation('Media')->getType(), 'The map builder creates ONE_TO_MANY relations for every incoming foreign key');
$this->assertEquals(RelationMap::ONE_TO_MANY, $bookTable->getRelation('BookListRel')->getType(), 'The map builder creates ONE_TO_MANY relations for every incoming foreign key');
$this->assertEquals(RelationMap::ONE_TO_MANY, $bookTable->getRelation('BookOpinion')->getType(), 'The map builder creates ONE_TO_MANY relations for every incoming foreign key');
$this->assertEquals(RelationMap::ONE_TO_MANY, $bookTable->getRelation('ReaderFavorite')->getType(), 'The map builder creates ONE_TO_MANY relations for every incoming foreign key');
$this->assertEquals(RelationMap::ONE_TO_MANY, $bookTable->getRelation('BookstoreContest')->getType(), 'The map builder creates ONE_TO_MANY relations for every incoming foreign key');
}
public function testRelationDirectionOneToOne()
{
$bookEmpTable = $this->databaseMap->getTableByPhpName('BookstoreEmployee');
$this->assertEquals(RelationMap::ONE_TO_ONE, $bookEmpTable->getRelation('BookstoreEmployeeAccount')->getType(), 'The map builder creates ONE_TO_ONE relations for every incoming foreign key to a primary key');
}
public function testRelationDirectionManyToMAny()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$this->assertEquals(RelationMap::MANY_TO_MANY, $bookTable->getRelation('BookClubList')->getType(), 'The map builder creates MANY_TO_MANY relations for every cross key');
}
public function testRelationsColumns()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$expectedMapping = array('book.PUBLISHER_ID' => 'publisher.ID');
$this->assertEquals($expectedMapping, $bookTable->getRelation('Publisher')->getColumnMappings(), 'The map builder adds columns in the correct order for foreign keys');
$expectedMapping = array('review.BOOK_ID' => 'book.ID');
$this->assertEquals($expectedMapping, $bookTable->getRelation('Review')->getColumnMappings(), 'The map builder adds columns in the correct order for incoming foreign keys');
$publisherTable = $this->databaseMap->getTableByPhpName('Publisher');
$expectedMapping = array('book.PUBLISHER_ID' => 'publisher.ID');
$this->assertEquals($expectedMapping, $publisherTable->getRelation('Book')->getColumnMappings(), 'The map builder adds local columns where the foreign key lies');
$rfTable = $this->databaseMap->getTableByPhpName('ReaderFavorite');
$expectedMapping = array(
'reader_favorite.BOOK_ID' => 'book_opinion.BOOK_ID',
'reader_favorite.READER_ID' => 'book_opinion.READER_ID'
);
$this->assertEquals($expectedMapping, $rfTable->getRelation('BookOpinion')->getColumnMappings(), 'The map builder adds all columns for composite foreign keys');
$expectedMapping = array();
$this->assertEquals($expectedMapping, $bookTable->getRelation('BookClubList')->getColumnMappings(), 'The map builder provides no column mapping for many-to-many relationships');
}
public function testRelationOnDelete()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$this->assertEquals('SET NULL', $bookTable->getRelation('Publisher')->getOnDelete(), 'The map builder adds columns with the correct onDelete');
}
public function testRelationOnUpdate()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$this->assertNull($bookTable->getRelation('Publisher')->getOnUpdate(), 'The map builder adds columns with onDelete null by default');
$this->assertEquals('CASCADE', $bookTable->getRelation('Author')->getOnUpdate(), 'The map builder adds columns with the correct onUpdate');
}
public function testBehaviors()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$this->assertEquals($bookTable->getBehaviors(), array(), 'getBehaviors() returns an empty array when no behaviors are registered');
$tmap = Propel::getDatabaseMap(Table1Peer::DATABASE_NAME)->getTable(Table1Peer::TABLE_NAME);
$expectedBehaviorParams = array('timestampable' => array('create_column' => 'created_on', 'update_column' => 'updated_on'));
$this->assertEquals($tmap->getBehaviors(), $expectedBehaviorParams, 'The map builder creates a getBehaviors() method to retrieve behaviors parameters when behaviors are registered');
}
public function testSingleTableInheritance()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$this->assertFalse($bookTable->isSingleTableInheritance(), 'isSingleTabkeInheritance() returns false by default');
$empTable = $this->databaseMap->getTableByPhpName('BookstoreEmployee');
$this->assertTrue($empTable->isSingleTableInheritance(), 'isSingleTabkeInheritance() returns true for tables using single table inheritance');
}
}

View file

@ -0,0 +1,95 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
require_once 'tools/helpers/bookstore/BookstoreDataPopulator.php';
/**
* Test class for MultiExtensionQueryBuilder.
*
* @author François Zaninotto
* @version $Id: QueryBuilderTest.php 1347 2009-12-03 21:06:36Z francois $
* @package generator.builder.om
*/
class QueryBuilderInheritanceTest extends BookstoreTestBase
{
public function testConstruct()
{
$query = BookstoreCashierQuery::create();
$this->assertTrue($query instanceof BookstoreCashierQuery, 'the create() factory returns an instance of the correct class');
}
public function testFindFilter()
{
BookstoreDataPopulator::depopulate($this->con);
$employee = new BookstoreEmployee();
$employee->save($this->con);
$manager = new BookstoreManager();
$manager->save($this->con);
$cashier1 = new BookstoreCashier();
$cashier1->save($this->con);
$cashier2 = new BookstoreCashier();
$cashier2->save($this->con);
$nbEmp = BookstoreEmployeeQuery::create()->count($this->con);
$this->assertEquals(4, $nbEmp, 'find() in main query returns all results');
$nbMan = BookstoreManagerQuery::create()->count($this->con);
$this->assertEquals(1, $nbMan, 'find() in sub query returns only child results');
$nbCash = BookstoreCashierQuery::create()->count($this->con);
$this->assertEquals(2, $nbCash, 'find() in sub query returns only child results');
}
public function testUpdateFilter()
{
BookstoreDataPopulator::depopulate($this->con);
$manager = new BookstoreManager();
$manager->save($this->con);
$cashier1 = new BookstoreCashier();
$cashier1->save($this->con);
$cashier2 = new BookstoreCashier();
$cashier2->save($this->con);
BookstoreManagerQuery::create()->update(array('Name' => 'foo'), $this->con);
$nbMan = BookstoreEmployeeQuery::create()
->filterByName('foo')
->count($this->con);
$this->assertEquals(1, $nbMan, 'Update in sub query affects only child results');
}
public function testDeleteFilter()
{
BookstoreDataPopulator::depopulate($this->con);
$manager = new BookstoreManager();
$manager->save($this->con);
$cashier1 = new BookstoreCashier();
$cashier1->save($this->con);
$cashier2 = new BookstoreCashier();
$cashier2->save($this->con);
BookstoreManagerQuery::create()
->filterByName()
->delete();
$nbCash = BookstoreEmployeeQuery::create()->count();
$this->assertEquals(2, $nbCash, 'Delete in sub query affects only child results');
}
public function testDeleteAllFilter()
{
BookstoreDataPopulator::depopulate($this->con);
$manager = new BookstoreManager();
$manager->save($this->con);
$cashier1 = new BookstoreCashier();
$cashier1->save($this->con);
$cashier2 = new BookstoreCashier();
$cashier2->save($this->con);
BookstoreManagerQuery::create()->deleteAll();
$nbCash = BookstoreEmployeeQuery::create()->count();
$this->assertEquals(2, $nbCash, 'Delete in sub query affects only child results');
}
}

View file

@ -0,0 +1,912 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
require_once 'tools/helpers/bookstore/BookstoreDataPopulator.php';
/**
* Test class for QueryBuilder.
*
* @author François Zaninotto
* @version $Id: QueryBuilderTest.php 1347 2009-12-03 21:06:36Z francois $
* @package generator.builder.om
*/
class QueryBuilderTest extends BookstoreTestBase
{
public function testExtends()
{
$q = new BookQuery();
$this->assertTrue($q instanceof ModelCriteria, 'Model query extends ModelCriteria');
}
public function testConstructor()
{
$query = new BookQuery();
$this->assertEquals($query->getDbName(), 'bookstore', 'Constructor sets dabatase name');
$this->assertEquals($query->getModelName(), 'Book', 'Constructor sets model name');
}
public function testCreate()
{
$query = BookQuery::create();
$this->assertTrue($query instanceof BookQuery, 'create() returns an object of its class');
$this->assertEquals($query->getDbName(), 'bookstore', 'create() sets dabatase name');
$this->assertEquals($query->getModelName(), 'Book', 'create() sets model name');
$query = BookQuery::create('foo');
$this->assertTrue($query instanceof BookQuery, 'create() returns an object of its class');
$this->assertEquals($query->getDbName(), 'bookstore', 'create() sets dabatase name');
$this->assertEquals($query->getModelName(), 'Book', 'create() sets model name');
$this->assertEquals($query->getModelAlias(), 'foo', 'create() can set the model alias');
}
public function testCreateCustom()
{
// see the myBookQuery class definition at the end of this file
$query = myCustomBookQuery::create();
$this->assertTrue($query instanceof myCustomBookQuery, 'create() returns an object of its class');
$this->assertTrue($query instanceof BookQuery, 'create() returns an object of its class');
$this->assertEquals($query->getDbName(), 'bookstore', 'create() sets dabatase name');
$this->assertEquals($query->getModelName(), 'Book', 'create() sets model name');
$query = myCustomBookQuery::create('foo');
$this->assertTrue($query instanceof myCustomBookQuery, 'create() returns an object of its class');
$this->assertEquals($query->getDbName(), 'bookstore', 'create() sets dabatase name');
$this->assertEquals($query->getModelName(), 'Book', 'create() sets model name');
$this->assertEquals($query->getModelAlias(), 'foo', 'create() can set the model alias');
}
public function testBasePreSelect()
{
$method = new ReflectionMethod('Table2Query', 'basePreSelect');
$this->assertEquals('ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePreSelect() by default');
$method = new ReflectionMethod('Table3Query', 'basePreSelect');
$this->assertEquals('BaseTable3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePreSelect() when a behavior is registered');
}
public function testBasePreDelete()
{
$method = new ReflectionMethod('Table2Query', 'basePreDelete');
$this->assertEquals('ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePreDelete() by default');
$method = new ReflectionMethod('Table3Query', 'basePreDelete');
$this->assertEquals('BaseTable3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePreDelete() when a behavior is registered');
}
public function testBasePostDelete()
{
$method = new ReflectionMethod('Table2Query', 'basePostDelete');
$this->assertEquals('ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePostDelete() by default');
$method = new ReflectionMethod('Table3Query', 'basePostDelete');
$this->assertEquals('BaseTable3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePostDelete() when a behavior is registered');
}
public function testBasePreUpdate()
{
$method = new ReflectionMethod('Table2Query', 'basePreUpdate');
$this->assertEquals('ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePreUpdate() by default');
$method = new ReflectionMethod('Table3Query', 'basePreUpdate');
$this->assertEquals('BaseTable3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePreUpdate() when a behavior is registered');
}
public function testBasePostUpdate()
{
$method = new ReflectionMethod('Table2Query', 'basePostUpdate');
$this->assertEquals('ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePostUpdate() by default');
$method = new ReflectionMethod('Table3Query', 'basePostUpdate');
$this->assertEquals('BaseTable3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePostUpdate() when a behavior is registered');
}
public function testQuery()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
$q = new BookQuery();
$book = $q
->setModelAlias('b')
->where('b.Title like ?', 'Don%')
->orderBy('b.ISBN', 'desc')
->findOne();
$this->assertTrue($book instanceof Book);
$this->assertEquals('Don Juan', $book->getTitle());
}
public function testFindPk()
{
$method = new ReflectionMethod('Table4Query', 'findPk');
$this->assertEquals('BaseTable4Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides findPk()');
}
public function testFindPkSimpleKey()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
$con = Propel::getConnection('bookstore');
// prepare the test data
$c = new ModelCriteria('bookstore', 'Book');
$c->orderBy('Book.Id', 'desc');
$testBook = $c->findOne();
$count = $con->getQueryCount();
BookPeer::clearInstancePool();
$q = new BookQuery();
$book = $q->findPk($testBook->getId());
$this->assertEquals($testBook, $book, 'BaseQuery overrides findPk() to make it faster');
$this->assertEquals($count+1, $con->getQueryCount(), 'findPk() issues a database query when instance pool is empty');
$q = new BookQuery();
$book = $q->findPk($testBook->getId());
$this->assertEquals($testBook, $book, 'BaseQuery overrides findPk() to make it faster');
$this->assertEquals($count+1, $con->getQueryCount(), 'findPk() does not issue a database query when instance is in pool');
}
public function testFindPkCompositeKey()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
// save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved
$c = new ModelCriteria('bookstore', 'Book');
$books = $c->find();
foreach ($books as $book) {
$book->save();
}
BookPeer::clearInstancePool();
// retrieve the test data
$c = new ModelCriteria('bookstore', 'BookListRel');
$bookListRelTest = $c->findOne();
$pk = $bookListRelTest->getPrimaryKey();
$q = new BookListRelQuery();
$bookListRel = $q->findPk($pk);
$this->assertEquals($bookListRelTest, $bookListRel, 'BaseQuery overrides findPk() for composite primary keysto make it faster');
}
public function testFindPks()
{
$method = new ReflectionMethod('Table4Query', 'findPks');
$this->assertEquals('BaseTable4Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides findPks()');
}
public function testFindPksSimpleKey()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
// prepare the test data
$c = new ModelCriteria('bookstore', 'Book');
$c->orderBy('Book.Id', 'desc');
$testBooks = $c->find();
$testBook1 = $testBooks->pop();
$testBook2 = $testBooks->pop();
$q = new BookQuery();
$books = $q->findPks(array($testBook1->getId(), $testBook2->getId()));
$this->assertEquals(array($testBook1, $testBook2), $books->getData(), 'BaseQuery overrides findPks() to make it faster');
}
public function testFindPksCompositeKey()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
// save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved
$c = new ModelCriteria('bookstore', 'Book');
$books = $c->find();
foreach ($books as $book) {
$book->save();
}
BookPeer::clearInstancePool();
// retrieve the test data
$c = new ModelCriteria('bookstore', 'BookListRel');
$bookListRelTest = $c->find();
$search = array();
foreach ($bookListRelTest as $obj) {
$search[]= $obj->getPrimaryKey();
}
$q = new BookListRelQuery();
$objs = $q->findPks($search);
$this->assertEquals($bookListRelTest, $objs, 'BaseQuery overrides findPks() for composite primary keys to make it work');
}
public function testFilterBy()
{
foreach (BookPeer::getFieldNames(BasePeer::TYPE_PHPNAME) as $colName) {
$filterMethod = 'filterBy' . $colName;
$this->assertTrue(method_exists('BookQuery', $filterMethod), 'QueryBuilder adds filterByColumn() methods for every column');
$q = BookQuery::create()->$filterMethod(1);
$this->assertTrue($q instanceof BookQuery, 'filterByColumn() returns the current query instance');
}
}
public function testFilterByPrimaryKeySimpleKey()
{
$q = BookQuery::create()->filterByPrimaryKey(12);
$q1 = BookQuery::create()->add(BookPeer::ID, 12, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByPrimaryKey() translates to a Criteria::EQUAL in the PK column');
$q = BookQuery::create()->setModelAlias('b', true)->filterByPrimaryKey(12);
$q1 = BookQuery::create()->setModelAlias('b', true)->add('b.ID', 12, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByPrimaryKey() uses true table alias if set');
}
public function testFilterByPrimaryKeyCompositeKey()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
// save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved
$c = new ModelCriteria('bookstore', 'Book');
$books = $c->find();
foreach ($books as $book) {
$book->save();
}
BookPeer::clearInstancePool();
// retrieve the test data
$c = new ModelCriteria('bookstore', 'BookListRel');
$bookListRelTest = $c->findOne();
$pk = $bookListRelTest->getPrimaryKey();
$q = new BookListRelQuery();
$q->filterByPrimaryKey($pk);
$q1 = BookListRelQuery::create()
->add(BookListRelPeer::BOOK_ID, $pk[0], Criteria::EQUAL)
->add(BookListRelPeer::BOOK_CLUB_LIST_ID, $pk[1], Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByPrimaryKey() translates to a Criteria::EQUAL in the PK columns');
}
public function testFilterByPrimaryKeysSimpleKey()
{
$q = BookQuery::create()->filterByPrimaryKeys(array(10, 11, 12));
$q1 = BookQuery::create()->add(BookPeer::ID, array(10, 11, 12), Criteria::IN);
$this->assertEquals($q1, $q, 'filterByPrimaryKeys() translates to a Criteria::IN on the PK column');
$q = BookQuery::create()->setModelAlias('b', true)->filterByPrimaryKeys(array(10, 11, 12));
$q1 = BookQuery::create()->setModelAlias('b', true)->add('b.ID', array(10, 11, 12), Criteria::IN);
$this->assertEquals($q1, $q, 'filterByPrimaryKeys() uses true table alias if set');
}
public function testFilterByPrimaryKeysCompositeKey()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
// save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved
$c = new ModelCriteria('bookstore', 'Book');
$books = $c->find();
foreach ($books as $book) {
$book->save();
}
BookPeer::clearInstancePool();
// retrieve the test data
$c = new ModelCriteria('bookstore', 'BookListRel');
$bookListRelTest = $c->find();
$search = array();
foreach ($bookListRelTest as $obj) {
$search[]= $obj->getPrimaryKey();
}
$q = new BookListRelQuery();
$q->filterByPrimaryKeys($search);
$q1 = BookListRelQuery::create();
foreach ($search as $key) {
$cton0 = $q1->getNewCriterion(BookListRelPeer::BOOK_ID, $key[0], Criteria::EQUAL);
$cton1 = $q1->getNewCriterion(BookListRelPeer::BOOK_CLUB_LIST_ID, $key[1], Criteria::EQUAL);
$cton0->addAnd($cton1);
$q1->addOr($cton0);
}
$this->assertEquals($q1, $q, 'filterByPrimaryKeys() translates to a series of Criteria::EQUAL in the PK columns');
}
public function testFilterByIntegerPk()
{
$q = BookQuery::create()->filterById(12);
$q1 = BookQuery::create()->add(BookPeer::ID, 12, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByPkColumn() translates to a Criteria::EQUAL by default');
$q = BookQuery::create()->filterById(12, Criteria::NOT_EQUAL);
$q1 = BookQuery::create()->add(BookPeer::ID, 12, Criteria::NOT_EQUAL);
$this->assertEquals($q1, $q, 'filterByPkColumn() accepts an optional comparison operator');
$q = BookQuery::create()->setModelAlias('b', true)->filterById(12);
$q1 = BookQuery::create()->setModelAlias('b', true)->add('b.ID', 12, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByPkColumn() uses true table alias if set');
$q = BookQuery::create()->filterById(array(10, 11, 12));
$q1 = BookQuery::create()->add(BookPeer::ID, array(10, 11, 12), Criteria::IN);
$this->assertEquals($q1, $q, 'filterByPkColumn() translates to a Criteria::IN when passed a simple array key');
$q = BookQuery::create()->filterById(array(10, 11, 12), Criteria::NOT_IN);
$q1 = BookQuery::create()->add(BookPeer::ID, array(10, 11, 12), Criteria::NOT_IN);
$this->assertEquals($q1, $q, 'filterByPkColumn() accepts a comparison when passed a simple array key');
}
public function testFilterByNumber()
{
$q = BookQuery::create()->filterByPrice(12);
$q1 = BookQuery::create()->add(BookPeer::PRICE, 12, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByNumColumn() translates to a Criteria::EQUAL by default');
$q = BookQuery::create()->filterByPrice(12, Criteria::NOT_EQUAL);
$q1 = BookQuery::create()->add(BookPeer::PRICE, 12, Criteria::NOT_EQUAL);
$this->assertEquals($q1, $q, 'filterByNumColumn() accepts an optional comparison operator');
$q = BookQuery::create()->setModelAlias('b', true)->filterByPrice(12);
$q1 = BookQuery::create()->setModelAlias('b', true)->add('b.PRICE', 12, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByNumColumn() uses true table alias if set');
$q = BookQuery::create()->filterByPrice(array(10, 11, 12));
$q1 = BookQuery::create()->add(BookPeer::PRICE, array(10, 11, 12), Criteria::IN);
$this->assertEquals($q1, $q, 'filterByNumColumn() translates to a Criteria::IN when passed a simple array key');
$q = BookQuery::create()->filterByPrice(array(10, 11, 12), Criteria::NOT_IN);
$q1 = BookQuery::create()->add(BookPeer::PRICE, array(10, 11, 12), Criteria::NOT_IN);
$this->assertEquals($q1, $q, 'filterByNumColumn() accepts a comparison when passed a simple array key');
$q = BookQuery::create()->filterByPrice(array('min' => 10));
$q1 = BookQuery::create()->add(BookPeer::PRICE, 10, Criteria::GREATER_EQUAL);
$this->assertEquals($q1, $q, 'filterByNumColumn() translates to a Criteria::GREATER_EQUAL when passed a \'min\' key');
$q = BookQuery::create()->filterByPrice(array('max' => 12));
$q1 = BookQuery::create()->add(BookPeer::PRICE, 12, Criteria::LESS_EQUAL);
$this->assertEquals($q1, $q, 'filterByNumColumn() translates to a Criteria::LESS_EQUAL when passed a \'max\' key');
$q = BookQuery::create()->filterByPrice(array('min' => 10, 'max' => 12));
$q1 = BookQuery::create()
->add(BookPeer::PRICE, 10, Criteria::GREATER_EQUAL)
->addAnd(BookPeer::PRICE, 12, Criteria::LESS_EQUAL);
$this->assertEquals($q1, $q, 'filterByNumColumn() translates to a between when passed both a \'min\' and a \'max\' key');
}
public function testFilterByTimestamp()
{
$q = BookstoreEmployeeAccountQuery::create()->filterByCreated(12);
$q1 = BookstoreEmployeeAccountQuery::create()->add(BookstoreEmployeeAccountPeer::CREATED, 12, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByDateColumn() translates to a Criteria::EQUAL by default');
$q = BookstoreEmployeeAccountQuery::create()->filterByCreated(12, Criteria::NOT_EQUAL);
$q1 = BookstoreEmployeeAccountQuery::create()->add(BookstoreEmployeeAccountPeer::CREATED, 12, Criteria::NOT_EQUAL);
$this->assertEquals($q1, $q, 'filterByDateColumn() accepts an optional comparison operator');
$q = BookstoreEmployeeAccountQuery::create()->setModelAlias('b', true)->filterByCreated(12);
$q1 = BookstoreEmployeeAccountQuery::create()->setModelAlias('b', true)->add('b.CREATED', 12, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByDateColumn() uses true table alias if set');
$q = BookstoreEmployeeAccountQuery::create()->filterByCreated(array('min' => 10));
$q1 = BookstoreEmployeeAccountQuery::create()->add(BookstoreEmployeeAccountPeer::CREATED, 10, Criteria::GREATER_EQUAL);
$this->assertEquals($q1, $q, 'filterByDateColumn() translates to a Criteria::GREATER_EQUAL when passed a \'min\' key');
$q = BookstoreEmployeeAccountQuery::create()->filterByCreated(array('max' => 12));
$q1 = BookstoreEmployeeAccountQuery::create()->add(BookstoreEmployeeAccountPeer::CREATED, 12, Criteria::LESS_EQUAL);
$this->assertEquals($q1, $q, 'filterByDateColumn() translates to a Criteria::LESS_EQUAL when passed a \'max\' key');
$q = BookstoreEmployeeAccountQuery::create()->filterByCreated(array('min' => 10, 'max' => 12));
$q1 = BookstoreEmployeeAccountQuery::create()
->add(BookstoreEmployeeAccountPeer::CREATED, 10, Criteria::GREATER_EQUAL)
->addAnd(BookstoreEmployeeAccountPeer::CREATED, 12, Criteria::LESS_EQUAL);
$this->assertEquals($q1, $q, 'filterByDateColumn() translates to a between when passed both a \'min\' and a \'max\' key');
}
public function testFilterByString()
{
$q = BookQuery::create()->filterByTitle('foo');
$q1 = BookQuery::create()->add(BookPeer::TITLE, 'foo', Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::EQUAL by default');
$q = BookQuery::create()->filterByTitle('foo', Criteria::NOT_EQUAL);
$q1 = BookQuery::create()->add(BookPeer::TITLE, 'foo', Criteria::NOT_EQUAL);
$this->assertEquals($q1, $q, 'filterByStringColumn() accepts an optional comparison operator');
$q = BookQuery::create()->setModelAlias('b', true)->filterByTitle('foo');
$q1 = BookQuery::create()->setModelAlias('b', true)->add('b.TITLE', 'foo', Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByStringColumn() uses true table alias if set');
$q = BookQuery::create()->filterByTitle(array('foo', 'bar'));
$q1 = BookQuery::create()->add(BookPeer::TITLE, array('foo', 'bar'), Criteria::IN);
$this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::IN when passed an array');
$q = BookQuery::create()->filterByTitle(array('foo', 'bar'), Criteria::NOT_IN);
$q1 = BookQuery::create()->add(BookPeer::TITLE, array('foo', 'bar'), Criteria::NOT_IN);
$this->assertEquals($q1, $q, 'filterByStringColumn() accepts a comparison when passed an array');
$q = BookQuery::create()->filterByTitle('foo%');
$q1 = BookQuery::create()->add(BookPeer::TITLE, 'foo%', Criteria::LIKE);
$this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::LIKE when passed a string with a % wildcard');
$q = BookQuery::create()->filterByTitle('foo%', Criteria::NOT_LIKE);
$q1 = BookQuery::create()->add(BookPeer::TITLE, 'foo%', Criteria::NOT_LIKE);
$this->assertEquals($q1, $q, 'filterByStringColumn() accepts a comparison when passed a string with a % wildcard');
$q = BookQuery::create()->filterByTitle('foo%', Criteria::EQUAL);
$q1 = BookQuery::create()->add(BookPeer::TITLE, 'foo%', Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByStringColumn() accepts a comparison when passed a string with a % wildcard');
$q = BookQuery::create()->filterByTitle('*foo');
$q1 = BookQuery::create()->add(BookPeer::TITLE, '%foo', Criteria::LIKE);
$this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::LIKE when passed a string with a * wildcard, and turns * into %');
$q = BookQuery::create()->filterByTitle('*f%o*o%');
$q1 = BookQuery::create()->add(BookPeer::TITLE, '%f%o%o%', Criteria::LIKE);
$this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::LIKE when passed a string with mixed wildcards, and turns *s into %s');
}
public function testFilterByBoolean()
{
$q = ReviewQuery::create()->filterByRecommended(true);
$q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, true, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a Criteria::EQUAL by default');
$q = ReviewQuery::create()->filterByRecommended(true, Criteria::NOT_EQUAL);
$q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, true, Criteria::NOT_EQUAL);
$this->assertEquals($q1, $q, 'filterByBooleanColumn() accepts an optional comparison operator');
$q = ReviewQuery::create()->filterByRecommended(false);
$q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, false, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a Criteria::EQUAL by default');
$q = ReviewQuery::create()->setModelAlias('b', true)->filterByRecommended(true);
$q1 = ReviewQuery::create()->setModelAlias('b', true)->add('b.RECOMMENDED', true, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByBooleanColumn() uses true table alias if set');
$q = ReviewQuery::create()->filterByRecommended('true');
$q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, true, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = true when passed a true string');
$q = ReviewQuery::create()->filterByRecommended('yes');
$q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, true, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = true when passed a true string');
$q = ReviewQuery::create()->filterByRecommended('1');
$q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, true, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = true when passed a true string');
$q = ReviewQuery::create()->filterByRecommended('false');
$q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, false, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = false when passed a false string');
$q = ReviewQuery::create()->filterByRecommended('no');
$q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, false, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = false when passed a false string');
$q = ReviewQuery::create()->filterByRecommended('0');
$q1 = ReviewQuery::create()->add(ReviewPeer::RECOMMENDED, false, Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = false when passed a false string');
}
public function testFilterByFk()
{
$this->assertTrue(method_exists('BookQuery', 'filterByAuthor'), 'QueryBuilder adds filterByFk() methods');
$this->assertTrue(method_exists('BookQuery', 'filterByPublisher'), 'QueryBuilder adds filterByFk() methods for all fkeys');
$this->assertTrue(method_exists('EssayQuery', 'filterByAuthorRelatedByFirstAuthor'), 'QueryBuilder adds filterByFk() methods for several fkeys on the same table');
$this->assertTrue(method_exists('EssayQuery', 'filterByAuthorRelatedBySecondAuthor'), 'QueryBuilder adds filterByFk() methods for several fkeys on the same table');
}
public function testFilterByFkSimpleKey()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
// prepare the test data
$testBook = BookQuery::create()
->innerJoin('Book.Author') // just in case there are books with no author
->findOne();
$testAuthor = $testBook->getAuthor();
$book = BookQuery::create()
->filterByAuthor($testAuthor)
->findOne();
$this->assertEquals($testBook, $book, 'Generated query handles filterByFk() methods correctly for simple fkeys');
$q = BookQuery::create()->filterByAuthor($testAuthor);
$q1 = BookQuery::create()->add(BookPeer::AUTHOR_ID, $testAuthor->getId(), Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByFk() translates to a Criteria::EQUAL by default');
$q = BookQuery::create()->filterByAuthor($testAuthor, Criteria::NOT_EQUAL);
$q1 = BookQuery::create()->add(BookPeer::AUTHOR_ID, $testAuthor->getId(), Criteria::NOT_EQUAL);
$this->assertEquals($q1, $q, 'filterByFk() accepts an optional comparison operator');
}
public function testFilterByFkCompositeKey()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
BookstoreDataPopulator::populateOpinionFavorite();
// prepare the test data
$testOpinion = BookOpinionQuery::create()
->innerJoin('BookOpinion.ReaderFavorite') // just in case there are books with no author
->findOne();
$testFavorite = $testOpinion->getReaderFavorite();
$favorite = ReaderFavoriteQuery::create()
->filterByBookOpinion($testOpinion)
->findOne();
$this->assertEquals($testFavorite, $favorite, 'Generated query handles filterByFk() methods correctly for composite fkeys');
}
public function testFilterByRefFk()
{
$this->assertTrue(method_exists('BookQuery', 'filterByReview'), 'QueryBuilder adds filterByRefFk() methods');
$this->assertTrue(method_exists('BookQuery', 'filterByMedia'), 'QueryBuilder adds filterByRefFk() methods for all fkeys');
$this->assertTrue(method_exists('AuthorQuery', 'filterByEssayRelatedByFirstAuthor'), 'QueryBuilder adds filterByRefFk() methods for several fkeys on the same table');
$this->assertTrue(method_exists('AuthorQuery', 'filterByEssayRelatedBySecondAuthor'), 'QueryBuilder adds filterByRefFk() methods for several fkeys on the same table');
}
public function testFilterByRefFkSimpleKey()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
// prepare the test data
$testBook = BookQuery::create()
->innerJoin('Book.Author') // just in case there are books with no author
->findOne();
$testAuthor = $testBook->getAuthor();
$author = AuthorQuery::create()
->filterByBook($testBook)
->findOne();
$this->assertEquals($testAuthor, $author, 'Generated query handles filterByRefFk() methods correctly for simple fkeys');
$q = AuthorQuery::create()->filterByBook($testBook);
$q1 = AuthorQuery::create()->add(AuthorPeer::ID, $testBook->getAuthorId(), Criteria::EQUAL);
$this->assertEquals($q1, $q, 'filterByRefFk() translates to a Criteria::EQUAL by default');
$q = AuthorQuery::create()->filterByBook($testBook, Criteria::NOT_EQUAL);
$q1 = AuthorQuery::create()->add(AuthorPeer::ID, $testBook->getAuthorId(), Criteria::NOT_EQUAL);
$this->assertEquals($q1, $q, 'filterByRefFk() accepts an optional comparison operator');
}
public function testFilterByRefFkCompositeKey()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
BookstoreDataPopulator::populateOpinionFavorite();
// prepare the test data
$testOpinion = BookOpinionQuery::create()
->innerJoin('BookOpinion.ReaderFavorite') // just in case there are books with no author
->findOne();
$testFavorite = $testOpinion->getReaderFavorite();
$opinion = BookOpinionQuery::create()
->filterByReaderFavorite($testFavorite)
->findOne();
$this->assertEquals($testOpinion, $opinion, 'Generated query handles filterByRefFk() methods correctly for composite fkeys');
}
public function testFilterByCrossFK()
{
$this->assertTrue(method_exists('BookQuery', 'filterByBookClubList'), 'Generated query handles filterByCrossRefFK() for many-to-many relationships');
$this->assertFalse(method_exists('BookQuery', 'filterByBook'), 'Generated query handles filterByCrossRefFK() for many-to-many relationships');
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
$blc1 = BookClubListQuery::create()->findOneByGroupLeader('Crazyleggs');
$nbBooks = BookQuery::create()
->filterByBookClubList($blc1)
->count();
$this->assertEquals(2, $nbBooks, 'Generated query handles filterByCrossRefFK() methods correctly');
}
public function testJoinFk()
{
$q = BookQuery::create()
->joinAuthor();
$q1 = BookQuery::create()
->join('Book.Author', Criteria::LEFT_JOIN);
$this->assertTrue($q->equals($q1), 'joinFk() translates to a left join on non-required columns');
$q = ReviewQuery::create()
->joinBook();
$q1 = ReviewQuery::create()
->join('Review.Book', Criteria::INNER_JOIN);
$this->assertTrue($q->equals($q1), 'joinFk() translates to an inner join on required columns');
$q = BookQuery::create()
->joinAuthor('a');
$q1 = BookQuery::create()
->join('Book.Author a', Criteria::LEFT_JOIN);
$this->assertTrue($q->equals($q1), 'joinFk() accepts a relation alias as first parameter');
$q = BookQuery::create()
->joinAuthor('', Criteria::INNER_JOIN);
$q1 = BookQuery::create()
->join('Book.Author', Criteria::INNER_JOIN);
$this->assertTrue($q->equals($q1), 'joinFk() accepts a join type as second parameter');
$q = EssayQuery::create()
->joinAuthorRelatedBySecondAuthor();
$q1 = EssayQuery::create()
->join('Essay.AuthorRelatedBySecondAuthor', "INNER JOIN");
$this->assertTrue($q->equals($q1), 'joinFk() translates to a "INNER JOIN" when this is defined as defaultJoin in the schema');
}
public function testJoinFkAlias()
{
$q = BookQuery::create('b')
->joinAuthor('a');
$q1 = BookQuery::create('b')
->join('b.Author a', Criteria::LEFT_JOIN);
$this->assertTrue($q->equals($q1), 'joinFk() works fine with table aliases');
$q = BookQuery::create()
->setModelAlias('b', true)
->joinAuthor('a');
$q1 = BookQuery::create()
->setModelAlias('b', true)
->join('b.Author a', Criteria::LEFT_JOIN);
$this->assertTrue($q->equals($q1), 'joinFk() works fine with true table aliases');
}
public function testJoinRefFk()
{
$q = AuthorQuery::create()
->joinBook();
$q1 = AuthorQuery::create()
->join('Author.Book', Criteria::LEFT_JOIN);
$this->assertTrue($q->equals($q1), 'joinRefFk() translates to a left join on non-required columns');
$q = BookQuery::create()
->joinreview();
$q1 = BookQuery::create()
->join('Book.Review', Criteria::INNER_JOIN);
$this->assertTrue($q->equals($q1), 'joinRefFk() translates to an inner join on required columns');
$q = AuthorQuery::create()
->joinBook('b');
$q1 = AuthorQuery::create()
->join('Author.Book b', Criteria::LEFT_JOIN);
$this->assertTrue($q->equals($q1), 'joinRefFk() accepts a relation alias as first parameter');
$q = AuthorQuery::create()
->joinBook('', Criteria::INNER_JOIN);
$q1 = AuthorQuery::create()
->join('Author.Book', Criteria::INNER_JOIN);
$this->assertTrue($q->equals($q1), 'joinRefFk() accepts a join type as second parameter');
$q = AuthorQuery::create()
->joinEssayRelatedBySecondAuthor();
$q1 = AuthorQuery::create()
->join('Author.EssayRelatedBySecondAuthor', Criteria::INNER_JOIN);
$this->assertTrue($q->equals($q1), 'joinRefFk() translates to a "INNER JOIN" when this is defined as defaultJoin in the schema');
}
public function testUseFkQuerySimple()
{
$q = BookQuery::create()
->useAuthorQuery()
->filterByFirstName('Leo')
->endUse();
$q1 = BookQuery::create()
->join('Book.Author', Criteria::LEFT_JOIN)
->add(AuthorPeer::FIRST_NAME, 'Leo', Criteria::EQUAL);
$this->assertTrue($q->equals($q1), 'useFkQuery() translates to a condition on a left join on non-required columns');
$q = ReviewQuery::create()
->useBookQuery()
->filterByTitle('War And Peace')
->endUse();
$q1 = ReviewQuery::create()
->join('Review.Book', Criteria::INNER_JOIN)
->add(BookPeer::TITLE, 'War And Peace', Criteria::EQUAL);
$this->assertTrue($q->equals($q1), 'useFkQuery() translates to a condition on aninner join on required columns');
}
public function testUseFkQueryJoinType()
{
$q = BookQuery::create()
->useAuthorQuery(null, Criteria::LEFT_JOIN)
->filterByFirstName('Leo')
->endUse();
$q1 = BookQuery::create()
->join('Book.Author', Criteria::LEFT_JOIN)
->add(AuthorPeer::FIRST_NAME, 'Leo', Criteria::EQUAL);
$this->assertTrue($q->equals($q1), 'useFkQuery() accepts a join type as second parameter');
}
public function testUseFkQueryAlias()
{
$q = BookQuery::create()
->useAuthorQuery('a')
->filterByFirstName('Leo')
->endUse();
$join = new ModelJoin();
$join->setJoinType(Criteria::LEFT_JOIN);
$join->setTableMap(AuthorPeer::getTableMap());
$join->setRelationMap(BookPeer::getTableMap()->getRelation('Author'), null, 'a');
$join->setRelationAlias('a');
$q1 = BookQuery::create()
->addAlias('a', AuthorPeer::TABLE_NAME)
->addJoinObject($join, 'a')
->add('a.FIRST_NAME', 'Leo', Criteria::EQUAL);
$this->assertTrue($q->equals($q1), 'useFkQuery() uses the first argument as a table alias');
}
public function testUseFkQueryMixed()
{
$q = BookQuery::create()
->useAuthorQuery()
->filterByFirstName('Leo')
->endUse()
->filterByTitle('War And Peace');
$q1 = BookQuery::create()
->join('Book.Author', Criteria::LEFT_JOIN)
->add(AuthorPeer::FIRST_NAME, 'Leo', Criteria::EQUAL)
->add(BookPeer::TITLE, 'War And Peace', Criteria::EQUAL);
$this->assertTrue($q->equals($q1), 'useFkQuery() allows combining conditions on main and related query');
}
public function testUseFkQueryTwice()
{
$q = BookQuery::create()
->useAuthorQuery()
->filterByFirstName('Leo')
->endUse()
->useAuthorQuery()
->filterByLastName('Tolstoi')
->endUse();
$q1 = BookQuery::create()
->join('Book.Author', Criteria::LEFT_JOIN)
->add(AuthorPeer::FIRST_NAME, 'Leo', Criteria::EQUAL)
->add(AuthorPeer::LAST_NAME, 'Tolstoi', Criteria::EQUAL);
$this->assertTrue($q->equals($q1), 'useFkQuery() called twice on the same relation does not create two joins');
}
public function testUseFkQueryTwiceTwoAliases()
{
$q = BookQuery::create()
->useAuthorQuery('a')
->filterByFirstName('Leo')
->endUse()
->useAuthorQuery('b')
->filterByLastName('Tolstoi')
->endUse();
$join1 = new ModelJoin();
$join1->setJoinType(Criteria::LEFT_JOIN);
$join1->setTableMap(AuthorPeer::getTableMap());
$join1->setRelationMap(BookPeer::getTableMap()->getRelation('Author'), null, 'a');
$join1->setRelationAlias('a');
$join2 = new ModelJoin();
$join2->setJoinType(Criteria::LEFT_JOIN);
$join2->setTableMap(AuthorPeer::getTableMap());
$join2->setRelationMap(BookPeer::getTableMap()->getRelation('Author'), null, 'b');
$join2->setRelationAlias('b');
$q1 = BookQuery::create()
->addAlias('a', AuthorPeer::TABLE_NAME)
->addJoinObject($join1, 'a')
->add('a.FIRST_NAME', 'Leo', Criteria::EQUAL)
->addAlias('b', AuthorPeer::TABLE_NAME)
->addJoinObject($join2, 'b')
->add('b.LAST_NAME', 'Tolstoi', Criteria::EQUAL);
$this->assertTrue($q->equals($q1), 'useFkQuery() called twice on the same relation with two aliases creates two joins');
}
public function testUseFkQueryNested()
{
$q = ReviewQuery::create()
->useBookQuery()
->useAuthorQuery()
->filterByFirstName('Leo')
->endUse()
->endUse();
$q1 = ReviewQuery::create()
->join('Review.Book', Criteria::INNER_JOIN)
->join('Book.Author', Criteria::LEFT_JOIN)
->add(AuthorPeer::FIRST_NAME, 'Leo', Criteria::EQUAL);
// embedded queries create joins that keep a relation to the parent
// as this is not testable, we need to use another testing technique
$params = array();
$result = BasePeer::createSelectSql($q, $params);
$expectedParams = array();
$expectedResult = BasePeer::createSelectSql($q1, $expectedParams);
$this->assertEquals($expectedParams, $params, 'useFkQuery() called nested creates two joins');
$this->assertEquals($expectedResult, $result, 'useFkQuery() called nested creates two joins');
}
public function testUseFkQueryTwoRelations()
{
$q = BookQuery::create()
->useAuthorQuery()
->filterByFirstName('Leo')
->endUse()
->usePublisherQuery()
->filterByName('Penguin')
->endUse();
$q1 = BookQuery::create()
->join('Book.Author', Criteria::LEFT_JOIN)
->add(AuthorPeer::FIRST_NAME, 'Leo', Criteria::EQUAL)
->join('Book.Publisher', Criteria::LEFT_JOIN)
->add(PublisherPeer::NAME, 'Penguin', Criteria::EQUAL);
$this->assertTrue($q->equals($q1), 'useFkQuery() called twice on two relations creates two joins');
}
public function testPrune()
{
$q = BookQuery::create()->prune();
$this->assertTrue($q instanceof BookQuery, 'prune() returns the current Query object');
}
public function testPruneSimpleKey()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
$nbBooks = BookQuery::create()->prune()->count();
$this->assertEquals(4, $nbBooks, 'prune() does nothing when passed a null object');
$testBook = BookQuery::create()->findOne();
$nbBooks = BookQuery::create()->prune($testBook)->count();
$this->assertEquals(3, $nbBooks, 'prune() removes an object from the result');
}
public function testPruneCompositeKey()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
// save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved
$c = new ModelCriteria('bookstore', 'Book');
$books = $c->find();
foreach ($books as $book) {
$book->save();
}
BookPeer::clearInstancePool();
$nbBookListRel = BookListRelQuery::create()->prune()->count();
$this->assertEquals(2, $nbBookListRel, 'prune() does nothing when passed a null object');
$testBookListRel = BookListRelQuery::create()->findOne();
$nbBookListRel = BookListRelQuery::create()->prune($testBookListRel)->count();
$this->assertEquals(1, $nbBookListRel, 'prune() removes an object from the result');
}
}
class myCustomBookQuery extends BookQuery
{
public static function create($modelAlias = null, $criteria = null)
{
if ($criteria instanceof myCustomBookQuery) {
return $criteria;
}
$query = new myCustomBookQuery();
if (null !== $modelAlias) {
$query->setModelAlias($modelAlias);
}
if ($criteria instanceof Criteria) {
$query->mergeWith($criteria);
}
return $query;
}
}

View file

@ -0,0 +1,54 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'builder/util/PropelTemplate.php';
/**
* Tests for PropelTemplate class
*
* @version $Revision: 1784 $
* @package generator.builder.util
*/
class PropelTemplateTest extends PHPUnit_Framework_TestCase
{
public function testRenderStringNoParam()
{
$t = new PropelTemplate();
$t->setTemplate('Hello, <?php echo 1 + 2 ?>');
$res = $t->render();
$this->assertEquals('Hello, 3', $res);
}
public function testRenderStringOneParam()
{
$t = new PropelTemplate();
$t->setTemplate('Hello, <?php echo $name ?>');
$res = $t->render(array('name' => 'John'));
$this->assertEquals('Hello, John', $res);
}
public function testRenderStringParams()
{
$time = time();
$t = new PropelTemplate();
$t->setTemplate('Hello, <?php echo $name ?>, it is <?php echo $time ?> to go!');
$res = $t->render(array('name' => 'John', 'time' => $time));
$this->assertEquals('Hello, John, it is ' . $time . ' to go!', $res);
}
public function testRenderFile()
{
$t = new PropelTemplate();
$t->setTemplateFile(dirname(__FILE__).'/template.php');
$res = $t->render(array('name' => 'John'));
$this->assertEquals('Hello, John', $res);
}
}

View file

@ -0,0 +1 @@
Hello, <?php echo $name ?>

View file

@ -0,0 +1,113 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'platform/MysqlPlatform.php';
require_once 'model/Behavior.php';
require_once 'model/Table.php';
require_once 'platform/MysqlPlatform.php';
/**
* Tests for Behavior class
*
* @author <a href="mailto:mpoeschl@marmot.at>Martin Poeschl</a>
* @version $Revision: 1773 $
* @package generator.model
*/
class BehaviorTest extends PHPUnit_Framework_TestCase {
private $xmlToAppData;
private $appData;
public function testSetupObject()
{
$b = new Behavior();
$b->loadFromXML(array('name' => 'foo'));
$this->assertEquals($b->getName(), 'foo', 'setupObject() sets the Behavior name from XML attributes');
}
public function testName()
{
$b = new Behavior();
$this->assertNull($b->getName(), 'Behavior name is null by default');
$b->setName('foo');
$this->assertEquals($b->getName(), 'foo', 'setName() sets the name, and getName() gets it');
}
public function testTable()
{
$b = new Behavior();
$this->assertNull($b->getTable(), 'Behavior Table is null by default');
$t = new Table();
$t->setName('fooTable');
$b->setTable($t);
$this->assertEquals($b->getTable(), $t, 'setTable() sets the name, and getTable() gets it');
}
public function testParameters()
{
$b = new Behavior();
$this->assertEquals($b->getParameters(), array(), 'Behavior parameters is an empty array by default');
$b->addParameter(array('name' => 'foo', 'value' => 'bar'));
$this->assertEquals($b->getParameters(), array('foo' => 'bar'), 'addParameter() sets a parameter from an associative array');
$b->addParameter(array('name' => 'foo2', 'value' => 'bar2'));
$this->assertEquals($b->getParameters(), array('foo' => 'bar', 'foo2' => 'bar2'), 'addParameter() adds a parameter from an associative array');
$b->addParameter(array('name' => 'foo', 'value' => 'bar3'));
$this->assertEquals($b->getParameters(), array('foo' => 'bar3', 'foo2' => 'bar2'), 'addParameter() changes a parameter from an associative array');
$this->assertEquals($b->getParameter('foo'), 'bar3', 'getParameter() retrieves a parameter value by name');
$b->setParameters(array('foo3' => 'bar3', 'foo4' => 'bar4'));
$this->assertEquals($b->getParameters(), array('foo3' => 'bar3', 'foo4' => 'bar4'), 'setParameters() changes the whole parameter array');
}
/**
* test if the tables get the package name from the properties file
*
*/
public function testXmlToAppData()
{
include_once 'builder/util/XmlToAppData.php';
$this->xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null);
$this->appData = $this->xmlToAppData->parseFile('fixtures/bookstore/behavior-timestampable-schema.xml');
$table = $this->appData->getDatabase("bookstore-behavior")->getTable('table1');
$behaviors = $table->getBehaviors();
$this->assertEquals(count($behaviors), 1, 'XmlToAppData ads as many behaviors as there are behaviors tags');
$behavior = $table->getBehavior('timestampable');
$this->assertEquals($behavior->getTable()->getName(), 'table1', 'XmlToAppData sets the behavior table correctly');
$this->assertEquals($behavior->getParameters(), array('create_column' => 'created_on', 'update_column' => 'updated_on'), 'XmlToAppData sets the behavior parameters correctly');
}
public function testMofifyTable()
{
set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes");
Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php');
$tmap = Propel::getDatabaseMap(Table2Peer::DATABASE_NAME)->getTable(Table2Peer::TABLE_NAME);
$this->assertEquals(count($tmap->getColumns()), 4, 'A behavior can modify its table by implementing modifyTable()');
}
public function testModifyDatabase()
{
set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes");
require_once dirname(__FILE__) . '/../../../../runtime/lib/Propel.php';
Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php');
$tmap = Propel::getDatabaseMap(Table3Peer::DATABASE_NAME)->getTable(Table3Peer::TABLE_NAME);
$this->assertTrue(array_key_exists('do_nothing', $tmap->getBehaviors()), 'A database behavior is automatically copied to all its table');
}
public function testGetColumnForParameter()
{
$this->xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null);
$this->appData = $this->xmlToAppData->parseFile('fixtures/bookstore/behavior-timestampable-schema.xml');
$table = $this->appData->getDatabase("bookstore-behavior")->getTable('table1');
$behavior = $table->getBehavior('timestampable');
$this->assertEquals($table->getColumn('created_on'), $behavior->getColumnForParameter('create_column'), 'getColumnForParameter() returns the configured column for behavior based on a parameter name');
}
}

View file

@ -0,0 +1,81 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'model/Column.php';
require_once 'builder/util/XmlToAppData.php';
require_once 'platform/MysqlPlatform.php';
/**
* Tests for package handling.
*
* @author <a href="mailto:mpoeschl@marmot.at>Martin Poeschl</a>
* @version $Revision: 1612 $
* @package generator.model
*/
class ColumnTest extends PHPUnit_Framework_TestCase {
/**
* Tests static Column::makeList() method.
* @deprecated - Column::makeList() is deprecated and set to be removed in 1.3
*/
public function testMakeList()
{
$expected = "`Column0`, `Column1`, `Column2`, `Column3`, `Column4`";
$objArray = array();
for ($i=0; $i<5; $i++) {
$c = new Column();
$c->setName("Column" . $i);
$objArray[] = $c;
}
$list = Column::makeList($objArray, new MySQLPlatform());
$this->assertEquals($expected, $list, sprintf("Expected '%s' match, got '%s' ", var_export($expected, true), var_export($list,true)));
$strArray = array();
for ($i=0; $i<5; $i++) {
$strArray[] = "Column" . $i;
}
$list = Column::makeList($strArray, new MySQLPlatform());
$this->assertEquals($expected, $list, sprintf("Expected '%s' match, got '%s' ", var_export($expected, true), var_export($list,true)));
}
public function testPhpNamingMethod()
{
set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes");
Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php');
$bookTmap = Propel::getDatabaseMap(BookPeer::DATABASE_NAME)->getTable(BookPeer::TABLE_NAME);
$this->assertEquals('AuthorId', $bookTmap->getColumn('AUTHOR_ID')->getPhpName(), 'setPhpName() uses the default phpNamingMethod');
$pageTmap = Propel::getDatabaseMap(PagePeer::DATABASE_NAME)->getTable(PagePeer::TABLE_NAME);
$this->assertEquals('LeftChild', $pageTmap->getColumn('LEFTCHILD')->getPhpName(), 'setPhpName() uses the configured phpNamingMethod');
}
public function testGetConstantName()
{
$xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null);
$appData = $xmlToAppData->parseFile('fixtures/bookstore/behavior-timestampable-schema.xml');
$column = $appData->getDatabase("bookstore-behavior")->getTable('table1')->getColumn('title');
$this->assertEquals('Table1Peer::TITLE', $column->getConstantName(), 'getConstantName() returns the complete constant name by default');
}
public function testIsLocalColumnsRequired()
{
$xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null);
$appData = $xmlToAppData->parseFile('fixtures/bookstore/schema.xml');
$fk = $appData->getDatabase("bookstore")->getTable('book')->getColumnForeignKeys('publisher_id');
$this->assertFalse($fk[0]->isLocalColumnsRequired());
$fk = $appData->getDatabase("bookstore")->getTable('review')->getColumnForeignKeys('book_id');
$this->assertTrue($fk[0]->isLocalColumnsRequired());
}
}

View file

@ -0,0 +1,151 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/BaseTestCase.php';
require_once 'model/NameFactory.php';
require_once 'platform/MysqlPlatform.php';
require_once 'model/AppData.php';
/**
* <p>Unit tests for class <code>NameFactory</code> and known
* <code>NameGenerator</code> implementations.</p>
*
* <p>To add more tests, add entries to the <code>ALGORITHMS</code>,
* <code>INPUTS</code>, and <code>OUTPUTS</code> arrays, and code to
* the <code>makeInputs()</code> method.</p>
*
* <p>This test assumes that it's being run using the MySQL database
* adapter, <code>DBMM</code>. MySQL has a column length limit of 64
* characters.</p>
*
* @author <a href="mailto:dlr@collab.net">Daniel Rall</a>
* @version $Id: NameFactoryTest.php 1612 2010-03-16 22:56:21Z francois $
* @package generator.model
*/
class NameFactoryTest extends BaseTestCase
{
/** The database to mimic in generating the SQL. */
const DATABASE_TYPE = "mysql";
/**
* The list of known name generation algorithms, specified as the
* fully qualified class names to <code>NameGenerator</code>
* implementations.
*/
private static $ALGORITHMS = array(NameFactory::CONSTRAINT_GENERATOR, NameFactory::PHP_GENERATOR);
/**
* Two dimensional arrays of inputs for each algorithm.
*/
private static $INPUTS = array();
/**
* Given the known inputs, the expected name outputs.
*/
private static $OUTPUTS = array();
/**
* Used as an input.
*/
private $database;
/**
* Creates a new instance.
*
*/
public function __construct() {
self::$INPUTS = array(
array( array(self::makeString(61), "I", 1),
array(self::makeString(61), "I", 2),
array(self::makeString(65), "I", 3),
array(self::makeString(4), "FK", 1),
array(self::makeString(5), "FK", 2)
),
array(
array("MY_USER", NameGenerator::CONV_METHOD_UNDERSCORE),
array("MY_USER", NameGenerator::CONV_METHOD_PHPNAME),
array("MY_USER", NameGenerator::CONV_METHOD_NOCHANGE)
)
);
self::$OUTPUTS = array(
array(
self::makeString(60) . "_I_1",
self::makeString(60) . "_I_2",
self::makeString(60) . "_I_3",
self::makeString(4) . "_FK_1",
self::makeString(5) . "_FK_2"),
array("MyUser", "MYUSER", "MY_USER")
);
}
/**
* Creates a string of the specified length consisting entirely of
* the character <code>A</code>. Useful for simulating table
* names, etc.
*
* @param int $len the number of characters to include in the string
* @return a string of length <code>len</code> with every character an 'A'
*/
private static function makeString($len) {
$buf = "";
for ($i = 0; $i < $len; $i++) {
$buf .= 'A';
}
return $buf;
}
/** Sets up the Propel model. */
public function setUp()
{
$appData = new AppData(new MysqlPlatform());
$this->database = new Database();
$appData->addDatabase($this->database);
}
/**
* @throws Exception on fail
*/
public function testNames() {
for ($algoIndex = 0; $algoIndex < count(self::$ALGORITHMS); $algoIndex++) {
$algo = self::$ALGORITHMS[$algoIndex];
$algoInputs = self::$INPUTS[$algoIndex];
for ($i = 0; $i < count($algoInputs); $i++) {
$inputs = $this->makeInputs($algo, $algoInputs[$i]);
$generated = NameFactory::generateName($algo, $inputs);
$expected = self::$OUTPUTS[$algoIndex][$i];
$this->assertEquals($expected, $generated, 0, "Algorithm " . $algo . " failed to generate an unique name");
}
}
}
/**
* Creates the list of arguments to pass to the specified type of
* <code>NameGenerator</code> implementation.
*
* @param algo The class name of the <code>NameGenerator</code> to
* create an argument list for.
* @param inputs The (possibly partial) list inputs from which to
* generate the final list.
* @return the list of arguments to pass to the <code>NameGenerator</code>
*/
private function makeInputs($algo, $inputs)
{
if (NameFactory::CONSTRAINT_GENERATOR == $algo) {
array_unshift($inputs, $this->database);
}
return $inputs;
}
}

View file

@ -0,0 +1,55 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'model/PhpNameGenerator.php';
/**
* Tests for PhpNamleGenerator
*
* @author <a href="mailto:mpoeschl@marmot.at>Martin Poeschl</a>
* @version $Revision: 1612 $
* @package generator.model
*/
class PhpNameGeneratorTest extends PHPUnit_Framework_TestCase
{
public static function testPhpnameMethodDataProvider()
{
return array(
array('foo', 'Foo'),
array('Foo', 'Foo'),
array('FOO', 'FOO'),
array('123', '123'),
array('foo_bar', 'FooBar'),
array('bar_1', 'Bar1'),
array('bar_0', 'Bar0'),
array('my_CLASS_name', 'MyCLASSName'),
);
}
/**
* @dataProvider testPhpnameMethodDataProvider
*/
public function testPhpnameMethod($input, $output)
{
$generator = new TestablePhpNameGenerator();
$this->assertEquals($output, $generator->phpnameMethod($input));
}
}
class TestablePhpNameGenerator extends PhpNameGenerator
{
public function phpnameMethod($schemaName)
{
return parent::phpnameMethod($schemaName);
}
}

View file

@ -0,0 +1,109 @@
<?php
/*
* $Id: TableTest.php 1612 2010-03-16 22:56:21Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'builder/util/XmlToAppData.php';
require_once 'platform/MysqlPlatform.php';
require_once 'config/GeneratorConfig.php';
/**
* Tests for package handling.
*
* @author Martin Poeschl (mpoeschl@marmot.at)
* @version $Revision: 1612 $
* @package generator.model
*/
class TableTest extends PHPUnit_Framework_TestCase
{
private $xmlToAppData;
private $appData;
/**
* test if the tables get the package name from the properties file
*
*/
public function testIdMethodHandling() {
$this->xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null);
//$this->appData = $this->xmlToAppData->parseFile(dirname(__FILE__) . "/tabletest-schema.xml");
$this->appData = $this->xmlToAppData->parseFile("etc/schema/tabletest-schema.xml");
$db = $this->appData->getDatabase("iddb");
$expected = IDMethod::NATIVE;
$result = $db->getDefaultIdMethod();
$this->assertEquals($expected, $result);
$table2 = $db->getTable("table_native");
$expected = IDMethod::NATIVE;
$result = $table2->getIdMethod();
$this->assertEquals($expected, $result);
$table = $db->getTable("table_none");
$expected = IDMethod::NO_ID_METHOD;
$result = $table->getIdMethod();
$this->assertEquals($expected, $result);
}
public function testGeneratorConfig()
{
$xmlToAppData = new XmlToAppData(new MysqlPlatform(), "defaultpackage", null);
$appData = $xmlToAppData->parseFile('fixtures/bookstore/behavior-timestampable-schema.xml');
$table = $appData->getDatabase("bookstore-behavior")->getTable('table1');
$config = new GeneratorConfig();
$config->setBuildProperties(array('propel.foo.bar.class' => 'bazz'));
$table->getDatabase()->getAppData()->getPlatform()->setGeneratorConfig($config);
$this->assertThat($table->getGeneratorConfig(), $this->isInstanceOf('GeneratorConfig'), 'getGeneratorConfig() returns an instance of the generator configuration');
$this->assertEquals($table->getGeneratorConfig()->getBuildProperty('fooBarClass'), 'bazz', 'getGeneratorConfig() returns the instance of the generator configuration used in the platform');
}
public function testAddBehavior()
{
$platform = new MysqlPlatform();
$config = new GeneratorConfig();
$config->setBuildProperties(array(
'propel.behavior.timestampable.class' => 'behavior.TimestampableBehavior'
));
$platform->setGeneratorConfig($config);
$xmlToAppData = new XmlToAppData($platform, "defaultpackage", null);
$appData = $xmlToAppData->parseFile('fixtures/bookstore/behavior-timestampable-schema.xml');
$table = $appData->getDatabase("bookstore-behavior")->getTable('table1');
$this->assertThat($table->getBehavior('timestampable'), $this->isInstanceOf('TimestampableBehavior'), 'addBehavior() uses the behavior class defined in build.properties');
}
public function testUniqueColumnName()
{
$platform = new MysqlPlatform();
$config = new GeneratorConfig();
$platform->setGeneratorConfig($config);
$xmlToAppData = new XmlToAppData($platform, 'defaultpackage', null);
try
{
$appData = $xmlToAppData->parseFile('fixtures/unique-column/column-schema.xml');
$this->fail('Parsing file with duplicate column names in one table throws exception');
} catch (EngineException $e) {
$this->assertTrue(true, 'Parsing file with duplicate column names in one table throws exception');
}
}
public function testUniqueTableName()
{
$platform = new MysqlPlatform();
$config = new GeneratorConfig();
$platform->setGeneratorConfig($config);
$xmlToAppData = new XmlToAppData($platform, 'defaultpackage', null);
try {
$appData = $xmlToAppData->parseFile('fixtures/unique-column/table-schema.xml');
$this->fail('Parsing file with duplicate table name throws exception');
} catch (EngineException $e) {
$this->assertTrue(true, 'Parsing file with duplicate table name throws exception');
}
}
}

View file

@ -0,0 +1,45 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'generator/platform/PlatformTestBase.php';
/**
*
* @package generator.platform
*/
class DefaultPlatformTest extends PlatformTestBase
{
protected function setUp()
{
parent::setUp();
}
public function tearDown()
{
parent::tearDown();
}
public function testQuote()
{
$p = $this->getPlatform();
$unquoted = "Nice";
$quoted = $p->quote($unquoted);
$this->assertEquals("'$unquoted'", $quoted);
$unquoted = "Naughty ' string";
$quoted = $p->quote($unquoted);
$expected = "'Naughty '' string'";
$this->assertEquals($expected, $quoted);
}
}

View file

@ -0,0 +1,55 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
/**
*
* @package generator.platform
*/
class PlatformTestBase extends PHPUnit_Framework_TestCase
{
/**
* Platform object.
*
* @var Platform
*/
protected $platform;
/**
*
*/
protected function setUp()
{
parent::setUp();
$clazz = preg_replace('/Test$/', '', get_class($this));
include_once 'platform/' . $clazz . '.php';
$this->platform = new $clazz();
}
/**
*
*/
protected function tearDown()
{
parent::tearDown();
}
/**
*
* @return Platform
*/
protected function getPlatform()
{
return $this->platform;
}
}

View file

@ -0,0 +1,48 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'generator/platform/DefaultPlatformTest.php';
/**
*
* @package generator.platform
*/
class SqlitePlatformTest extends DefaultPlatformTest
{
/**
* @var PDO The PDO connection to SQLite DB.
*/
private $pdo;
protected function setUp()
{
parent::setUp();
$this->pdo = new PDO("sqlite::memory:");
}
public function tearDown()
{
parent::tearDown();
}
public function testQuoteConnected()
{
$p = $this->getPlatform();
$p->setConnection($this->pdo);
$unquoted = "Naughty ' string";
$quoted = $p->quote($unquoted);
$expected = "'Naughty '' string'";
$this->assertEquals($expected, $quoted);
}
}

View file

@ -0,0 +1,870 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
include_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Tests a functional scenario using the Bookstore model
*
* @author Francois Zaninotto
* @author Hans Lellelid <hans@xmpl.org>
* @package misc
*/
class BookstoreTest extends BookstoreEmptyTestBase
{
public function testScenario()
{
// Add publisher records
// ---------------------
try {
$scholastic = new Publisher();
$scholastic->setName("Scholastic");
// do not save, will do later to test cascade
$morrow = new Publisher();
$morrow->setName("William Morrow");
$morrow->save();
$morrow_id = $morrow->getId();
$penguin = new Publisher();
$penguin->setName("Penguin");
$penguin->save();
$penguin_id = $penguin->getId();
$vintage = new Publisher();
$vintage->setName("Vintage");
$vintage->save();
$vintage_id = $vintage->getId();
$this->assertTrue(true, 'Save Publisher records');
} catch (Exception $e) {
$this->fail('Save publisher records');
}
// Add author records
// ------------------
try {
$rowling = new Author();
$rowling->setFirstName("J.K.");
$rowling->setLastName("Rowling");
// do not save, will do later to test cascade
$stephenson = new Author();
$stephenson->setFirstName("Neal");
$stephenson->setLastName("Stephenson");
$stephenson->save();
$stephenson_id = $stephenson->getId();
$byron = new Author();
$byron->setFirstName("George");
$byron->setLastName("Byron");
$byron->save();
$byron_id = $byron->getId();
$grass = new Author();
$grass->setFirstName("Gunter");
$grass->setLastName("Grass");
$grass->save();
$grass_id = $grass->getId();
$this->assertTrue(true, 'Save Author records');
} catch (Exception $e) {
$this->fail('Save Author records');
}
// Add book records
// ----------------
try {
$phoenix = new Book();
$phoenix->setTitle("Harry Potter and the Order of the Phoenix");
$phoenix->setISBN("043935806X");
$phoenix->setAuthor($rowling);
$phoenix->setPublisher($scholastic);
$phoenix->save();
$phoenix_id = $phoenix->getId();
$this->assertFalse($rowling->isNew(), 'saving book also saves related author');
$this->assertFalse($scholastic->isNew(), 'saving book also saves related publisher');
$qs = new Book();
$qs->setISBN("0380977427");
$qs->setTitle("Quicksilver");
$qs->setAuthor($stephenson);
$qs->setPublisher($morrow);
$qs->save();
$qs_id = $qs->getId();
$dj = new Book();
$dj->setISBN("0140422161");
$dj->setTitle("Don Juan");
$dj->setAuthor($byron);
$dj->setPublisher($penguin);
$dj->save();
$dj_id = $qs->getId();
$td = new Book();
$td->setISBN("067972575X");
$td->setTitle("The Tin Drum");
$td->setAuthor($grass);
$td->setPublisher($vintage);
$td->save();
$td_id = $td->getId();
$this->assertTrue(true, 'Save Book records');
} catch (Exception $e) {
$this->fail('Save Author records');
}
// Add review records
// ------------------
try {
$r1 = new Review();
$r1->setBook($phoenix);
$r1->setReviewedBy("Washington Post");
$r1->setRecommended(true);
$r1->setReviewDate(time());
$r1->save();
$r1_id = $r1->getId();
$r2 = new Review();
$r2->setBook($phoenix);
$r2->setReviewedBy("New York Times");
$r2->setRecommended(false);
$r2->setReviewDate(time());
$r2->save();
$r2_id = $r2->getId();
$this->assertTrue(true, 'Save Review records');
} catch (Exception $e) {
$this->fail('Save Review records');
}
// Perform a "complex" search
// --------------------------
$crit = new Criteria();
$crit->add(BookPeer::TITLE, 'Harry%', Criteria::LIKE);
$results = BookPeer::doSelect($crit);
$this->assertEquals(1, count($results));
$crit2 = new Criteria();
$crit2->add(BookPeer::ISBN, array("0380977427", "0140422161"), Criteria::IN);
$results = BookPeer::doSelect($crit2);
$this->assertEquals(2, count($results));
// Perform a "limit" search
// ------------------------
$crit = new Criteria();
$crit->setLimit(2);
$crit->setOffset(1);
$crit->addAscendingOrderByColumn(BookPeer::TITLE);
$results = BookPeer::doSelect($crit);
$this->assertEquals(2, count($results));
// we ordered on book title, so we expect to get
$this->assertEquals("Harry Potter and the Order of the Phoenix", $results[0]->getTitle());
$this->assertEquals("Quicksilver", $results[1]->getTitle());
// Perform a lookup & update!
// --------------------------
// Updating just-created book title
// First finding book by PK (=$qs_id) ....
$qs_lookup = BookPeer::retrieveByPk($qs_id);
$this->assertNotNull($qs_lookup, 'just-created book can be found by pk');
$new_title = "Quicksilver (".crc32(uniqid(rand())).")";
// Attempting to update found object
$qs_lookup->setTitle($new_title);
$qs_lookup->save();
// Making sure object was correctly updated: ";
$qs_lookup2 = BookPeer::retrieveByPk($qs_id);
$this->assertEquals($new_title, $qs_lookup2->getTitle());
// Test some basic DATE / TIME stuff
// ---------------------------------
// that's the control timestamp.
$control = strtotime('2004-02-29 00:00:00');
// should be two in the db
$r = ReviewPeer::doSelectOne(new Criteria());
$r_id = $r->getId();
$r->setReviewDate($control);
$r->save();
$r2 = ReviewPeer::retrieveByPk($r_id);
$this->assertEquals(new Datetime('2004-02-29 00:00:00'), $r2->getReviewDate(null), 'ability to fetch DateTime');
$this->assertEquals($control, $r2->getReviewDate('U'), 'ability to fetch native unix timestamp');
$this->assertEquals('2-29-2004', $r2->getReviewDate('n-j-Y'), 'ability to use date() formatter');
// Handle BLOB/CLOB Columns
// ------------------------
$blob_path = dirname(__FILE__) . '/../../etc/lob/tin_drum.gif';
$blob2_path = dirname(__FILE__) . '/../../etc/lob/propel.gif';
$clob_path = dirname(__FILE__) . '/../../etc/lob/tin_drum.txt';
$m1 = new Media();
$m1->setBook($phoenix);
$m1->setCoverImage(file_get_contents($blob_path));
$m1->setExcerpt(file_get_contents($clob_path));
$m1->save();
$m1_id = $m1->getId();
$m1_lookup = MediaPeer::retrieveByPk($m1_id);
$this->assertNotNull($m1_lookup, 'Can find just-created media item');
$this->assertEquals(file_get_contents($blob_path), stream_get_contents($m1_lookup->getCoverImage()), 'BLOB was correctly updated');
$this->assertEquals(file_get_contents($clob_path), (string) $m1_lookup->getExcerpt(), 'CLOB was correctly updated');
// now update the BLOB column and save it & check the results
$m1_lookup->setCoverImage(file_get_contents($blob2_path));
$m1_lookup->save();
$m2_lookup = MediaPeer::retrieveByPk($m1_id);
$this->assertNotNull($m2_lookup, 'Can find just-created media item');
$this->assertEquals(file_get_contents($blob2_path), stream_get_contents($m2_lookup->getCoverImage()), 'BLOB was correctly overwritten');
// Test Validators
// ---------------
require_once 'tools/helpers/bookstore/validator/ISBNValidator.php';
$bk1 = new Book();
$bk1->setTitle("12345"); // min length is 10
$ret = $bk1->validate();
$this->assertFalse($ret, 'validation failed');
$failures = $bk1->getValidationFailures();
$this->assertEquals(1, count($failures), '1 validation message was returned');
$el = array_shift($failures);
$this->assertContains("must be more than", $el->getMessage(), 'Expected validation message was returned');
$bk2 = new Book();
$bk2->setTitle("Don Juan");
$ret = $bk2->validate();
$this->assertFalse($ret, 'validation failed');
$failures = $bk2->getValidationFailures();
$this->assertEquals(1, count($failures), '1 validation message was returned');
$el = array_shift($failures);
$this->assertContains("Book title already in database.", $el->getMessage(), 'Expected validation message was returned');
//Now trying some more complex validation.
$auth1 = new Author();
$auth1->setFirstName("Hans");
// last name required; will fail
$bk1->setAuthor($auth1);
$rev1 = new Review();
$rev1->setReviewDate("08/09/2001");
// will fail: reviewed_by column required
$bk1->addReview($rev1);
$ret2 = $bk1->validate();
$this->assertFalse($ret2, 'validation failed');
$failures2 = $bk1->getValidationFailures();
$this->assertEquals(3, count($failures2), '3 validation messages were returned');
$expectedKeys = array(
AuthorPeer::LAST_NAME,
BookPeer::TITLE,
ReviewPeer::REVIEWED_BY,
);
$this->assertEquals($expectedKeys, array_keys($failures2), 'correct columns failed');
$bk2 = new Book();
$bk2->setTitle("12345678901"); // passes
$auth2 = new Author();
$auth2->setLastName("Blah"); //passes
$auth2->setEmail("some@body.com"); //passes
$auth2->setAge(50); //passes
$bk2->setAuthor($auth2);
$rev2 = new Review();
$rev2->setReviewedBy("Me!"); // passes
$rev2->setStatus("new"); // passes
$bk2->addReview($rev2);
$ret3 = $bk2->validate();
$this->assertTrue($ret3, 'complex validation can pass');
// Testing doCount() functionality
// -------------------------------
$c = new Criteria();
$records = BookPeer::doSelect($c);
$count = BookPeer::doCount($c);
$this->assertEquals($count, count($records), 'correct number of results');
// Test many-to-many relationships
// ---------------
// init book club list 1 with 2 books
$blc1 = new BookClubList();
$blc1->setGroupLeader("Crazyleggs");
$blc1->setTheme("Happiness");
$brel1 = new BookListRel();
$brel1->setBook($phoenix);
$brel2 = new BookListRel();
$brel2->setBook($dj);
$blc1->addBookListRel($brel1);
$blc1->addBookListRel($brel2);
$blc1->save();
$this->assertNotNull($blc1->getId(), 'BookClubList 1 was saved');
// init book club list 2 with 1 book
$blc2 = new BookClubList();
$blc2->setGroupLeader("John Foo");
$blc2->setTheme("Default");
$brel3 = new BookListRel();
$brel3->setBook($phoenix);
$blc2->addBookListRel($brel3);
$blc2->save();
$this->assertNotNull($blc2->getId(), 'BookClubList 2 was saved');
// re-fetch books and lists from db to be sure that nothing is cached
$crit = new Criteria();
$crit->add(BookPeer::ID, $phoenix->getId());
$phoenix = BookPeer::doSelectOne($crit);
$this->assertNotNull($phoenix, "book 'phoenix' has been re-fetched from db");
$crit = new Criteria();
$crit->add(BookClubListPeer::ID, $blc1->getId());
$blc1 = BookClubListPeer::doSelectOne($crit);
$this->assertNotNull($blc1, 'BookClubList 1 has been re-fetched from db');
$crit = new Criteria();
$crit->add(BookClubListPeer::ID, $blc2->getId());
$blc2 = BookClubListPeer::doSelectOne($crit);
$this->assertNotNull($blc2, 'BookClubList 2 has been re-fetched from db');
$relCount = $phoenix->countBookListRels();
$this->assertEquals(2, $relCount, "book 'phoenix' has 2 BookListRels");
$relCount = $blc1->countBookListRels();
$this->assertEquals(2, $relCount, 'BookClubList 1 has 2 BookListRels');
$relCount = $blc2->countBookListRels();
$this->assertEquals(1, $relCount, 'BookClubList 2 has 1 BookListRel');
// Cleanup (tests DELETE)
// ----------------------
// Removing books that were just created
// First finding book by PK (=$phoenix_id) ....
$hp = BookPeer::retrieveByPk($phoenix_id);
$this->assertNotNull($hp, 'Could find just-created book');
// Attempting to delete [multi-table] by found pk
$c = new Criteria();
$c->add(BookPeer::ID, $hp->getId());
// The only way for cascading to work currently
// is to specify the author_id and publisher_id (i.e. the fkeys
// have to be in the criteria).
$c->add(AuthorPeer::ID, $hp->getAuthor()->getId());
$c->add(PublisherPeer::ID, $hp->getPublisher()->getId());
$c->setSingleRecord(true);
BookPeer::doDelete($c);
// Checking to make sure correct records were removed.
$this->assertEquals(3, AuthorPeer::doCount(new Criteria()), 'Correct records were removed from author table');
$this->assertEquals(3, PublisherPeer::doCount(new Criteria()), 'Correct records were removed from publisher table');
$this->assertEquals(3, BookPeer::doCount(new Criteria()), 'Correct records were removed from book table');
// Attempting to delete books by complex criteria
$c = new Criteria();
$cn = $c->getNewCriterion(BookPeer::ISBN, "043935806X");
$cn->addOr($c->getNewCriterion(BookPeer::ISBN, "0380977427"));
$cn->addOr($c->getNewCriterion(BookPeer::ISBN, "0140422161"));
$c->add($cn);
BookPeer::doDelete($c);
// Attempting to delete book [id = $td_id]
$td->delete();
// Attempting to delete authors
AuthorPeer::doDelete($stephenson_id);
AuthorPeer::doDelete($byron_id);
$grass->delete();
// Attempting to delete publishers
PublisherPeer::doDelete($morrow_id);
PublisherPeer::doDelete($penguin_id);
$vintage->delete();
// These have to be deleted manually also since we have onDelete
// set to SETNULL in the foreign keys in book. Is this correct?
$rowling->delete();
$scholastic->delete();
$blc1->delete();
$blc2->delete();
$this->assertEquals(array(), AuthorPeer::doSelect(new Criteria()), 'no records in [author] table');
$this->assertEquals(array(), PublisherPeer::doSelect(new Criteria()), 'no records in [publisher] table');
$this->assertEquals(array(), BookPeer::doSelect(new Criteria()), 'no records in [book] table');
$this->assertEquals(array(), ReviewPeer::doSelect(new Criteria()), 'no records in [review] table');
$this->assertEquals(array(), MediaPeer::doSelect(new Criteria()), 'no records in [media] table');
$this->assertEquals(array(), BookClubListPeer::doSelect(new Criteria()), 'no records in [book_club_list] table');
$this->assertEquals(array(), BookListRelPeer::doSelect(new Criteria()), 'no records in [book_x_list] table');
}
public function testScenarioUsingQuery()
{
// Add publisher records
// ---------------------
try {
$scholastic = new Publisher();
$scholastic->setName("Scholastic");
// do not save, will do later to test cascade
$morrow = new Publisher();
$morrow->setName("William Morrow");
$morrow->save();
$morrow_id = $morrow->getId();
$penguin = new Publisher();
$penguin->setName("Penguin");
$penguin->save();
$penguin_id = $penguin->getId();
$vintage = new Publisher();
$vintage->setName("Vintage");
$vintage->save();
$vintage_id = $vintage->getId();
$this->assertTrue(true, 'Save Publisher records');
} catch (Exception $e) {
$this->fail('Save publisher records');
}
// Add author records
// ------------------
try {
$rowling = new Author();
$rowling->setFirstName("J.K.");
$rowling->setLastName("Rowling");
// do not save, will do later to test cascade
$stephenson = new Author();
$stephenson->setFirstName("Neal");
$stephenson->setLastName("Stephenson");
$stephenson->save();
$stephenson_id = $stephenson->getId();
$byron = new Author();
$byron->setFirstName("George");
$byron->setLastName("Byron");
$byron->save();
$byron_id = $byron->getId();
$grass = new Author();
$grass->setFirstName("Gunter");
$grass->setLastName("Grass");
$grass->save();
$grass_id = $grass->getId();
$this->assertTrue(true, 'Save Author records');
} catch (Exception $e) {
$this->fail('Save Author records');
}
// Add book records
// ----------------
try {
$phoenix = new Book();
$phoenix->setTitle("Harry Potter and the Order of the Phoenix");
$phoenix->setISBN("043935806X");
$phoenix->setAuthor($rowling);
$phoenix->setPublisher($scholastic);
$phoenix->save();
$phoenix_id = $phoenix->getId();
$this->assertFalse($rowling->isNew(), 'saving book also saves related author');
$this->assertFalse($scholastic->isNew(), 'saving book also saves related publisher');
$qs = new Book();
$qs->setISBN("0380977427");
$qs->setTitle("Quicksilver");
$qs->setAuthor($stephenson);
$qs->setPublisher($morrow);
$qs->save();
$qs_id = $qs->getId();
$dj = new Book();
$dj->setISBN("0140422161");
$dj->setTitle("Don Juan");
$dj->setAuthor($byron);
$dj->setPublisher($penguin);
$dj->save();
$dj_id = $qs->getId();
$td = new Book();
$td->setISBN("067972575X");
$td->setTitle("The Tin Drum");
$td->setAuthor($grass);
$td->setPublisher($vintage);
$td->save();
$td_id = $td->getId();
$this->assertTrue(true, 'Save Book records');
} catch (Exception $e) {
$this->fail('Save Author records');
}
// Add review records
// ------------------
try {
$r1 = new Review();
$r1->setBook($phoenix);
$r1->setReviewedBy("Washington Post");
$r1->setRecommended(true);
$r1->setReviewDate(time());
$r1->save();
$r1_id = $r1->getId();
$r2 = new Review();
$r2->setBook($phoenix);
$r2->setReviewedBy("New York Times");
$r2->setRecommended(false);
$r2->setReviewDate(time());
$r2->save();
$r2_id = $r2->getId();
$this->assertTrue(true, 'Save Review records');
} catch (Exception $e) {
$this->fail('Save Review records');
}
// Perform a "complex" search
// --------------------------
$results = BookQuery::create()
->filterByTitle('Harry%')
->find();
$this->assertEquals(1, count($results));
$results = BookQuery::create()
->where('Book.ISBN IN ?', array("0380977427", "0140422161"))
->find();
$this->assertEquals(2, count($results));
// Perform a "limit" search
// ------------------------
$results = BookQuery::create()
->limit(2)
->offset(1)
->orderByTitle()
->find();
$this->assertEquals(2, count($results));
// we ordered on book title, so we expect to get
$this->assertEquals("Harry Potter and the Order of the Phoenix", $results[0]->getTitle());
$this->assertEquals("Quicksilver", $results[1]->getTitle());
// Perform a lookup & update!
// --------------------------
// Updating just-created book title
// First finding book by PK (=$qs_id) ....
$qs_lookup = BookQuery::create()->findPk($qs_id);
$this->assertNotNull($qs_lookup, 'just-created book can be found by pk');
$new_title = "Quicksilver (".crc32(uniqid(rand())).")";
// Attempting to update found object
$qs_lookup->setTitle($new_title);
$qs_lookup->save();
// Making sure object was correctly updated: ";
$qs_lookup2 = BookQuery::create()->findPk($qs_id);
$this->assertEquals($new_title, $qs_lookup2->getTitle());
// Test some basic DATE / TIME stuff
// ---------------------------------
// that's the control timestamp.
$control = strtotime('2004-02-29 00:00:00');
// should be two in the db
$r = ReviewQuery::create()->findOne();
$r_id = $r->getId();
$r->setReviewDate($control);
$r->save();
$r2 = ReviewQuery::create()->findPk($r_id);
$this->assertEquals(new Datetime('2004-02-29 00:00:00'), $r2->getReviewDate(null), 'ability to fetch DateTime');
$this->assertEquals($control, $r2->getReviewDate('U'), 'ability to fetch native unix timestamp');
$this->assertEquals('2-29-2004', $r2->getReviewDate('n-j-Y'), 'ability to use date() formatter');
// Handle BLOB/CLOB Columns
// ------------------------
$blob_path = dirname(__FILE__) . '/../../etc/lob/tin_drum.gif';
$blob2_path = dirname(__FILE__) . '/../../etc/lob/propel.gif';
$clob_path = dirname(__FILE__) . '/../../etc/lob/tin_drum.txt';
$m1 = new Media();
$m1->setBook($phoenix);
$m1->setCoverImage(file_get_contents($blob_path));
$m1->setExcerpt(file_get_contents($clob_path));
$m1->save();
$m1_id = $m1->getId();
$m1_lookup = MediaQuery::create()->findPk($m1_id);
$this->assertNotNull($m1_lookup, 'Can find just-created media item');
$this->assertEquals(file_get_contents($blob_path), stream_get_contents($m1_lookup->getCoverImage()), 'BLOB was correctly updated');
$this->assertEquals(file_get_contents($clob_path), (string) $m1_lookup->getExcerpt(), 'CLOB was correctly updated');
// now update the BLOB column and save it & check the results
$m1_lookup->setCoverImage(file_get_contents($blob2_path));
$m1_lookup->save();
$m2_lookup = MediaQuery::create()->findPk($m1_id);
$this->assertNotNull($m2_lookup, 'Can find just-created media item');
$this->assertEquals(file_get_contents($blob2_path), stream_get_contents($m2_lookup->getCoverImage()), 'BLOB was correctly overwritten');
// Test Validators
// ---------------
require_once 'tools/helpers/bookstore/validator/ISBNValidator.php';
$bk1 = new Book();
$bk1->setTitle("12345"); // min length is 10
$ret = $bk1->validate();
$this->assertFalse($ret, 'validation failed');
$failures = $bk1->getValidationFailures();
$this->assertEquals(1, count($failures), '1 validation message was returned');
$el = array_shift($failures);
$this->assertContains("must be more than", $el->getMessage(), 'Expected validation message was returned');
$bk2 = new Book();
$bk2->setTitle("Don Juan");
$ret = $bk2->validate();
$this->assertFalse($ret, 'validation failed');
$failures = $bk2->getValidationFailures();
$this->assertEquals(1, count($failures), '1 validation message was returned');
$el = array_shift($failures);
$this->assertContains("Book title already in database.", $el->getMessage(), 'Expected validation message was returned');
//Now trying some more complex validation.
$auth1 = new Author();
$auth1->setFirstName("Hans");
// last name required; will fail
$bk1->setAuthor($auth1);
$rev1 = new Review();
$rev1->setReviewDate("08/09/2001");
// will fail: reviewed_by column required
$bk1->addReview($rev1);
$ret2 = $bk1->validate();
$this->assertFalse($ret2, 'validation failed');
$failures2 = $bk1->getValidationFailures();
$this->assertEquals(3, count($failures2), '3 validation messages were returned');
$expectedKeys = array(
AuthorPeer::LAST_NAME,
BookPeer::TITLE,
ReviewPeer::REVIEWED_BY,
);
$this->assertEquals($expectedKeys, array_keys($failures2), 'correct columns failed');
$bk2 = new Book();
$bk2->setTitle("12345678901"); // passes
$auth2 = new Author();
$auth2->setLastName("Blah"); //passes
$auth2->setEmail("some@body.com"); //passes
$auth2->setAge(50); //passes
$bk2->setAuthor($auth2);
$rev2 = new Review();
$rev2->setReviewedBy("Me!"); // passes
$rev2->setStatus("new"); // passes
$bk2->addReview($rev2);
$ret3 = $bk2->validate();
$this->assertTrue($ret3, 'complex validation can pass');
// Testing doCount() functionality
// -------------------------------
// old way
$c = new Criteria();
$records = BookPeer::doSelect($c);
$count = BookPeer::doCount($c);
$this->assertEquals($count, count($records), 'correct number of results');
// new way
$count = BookQuery::create()->count();
$this->assertEquals($count, count($records), 'correct number of results');
// Test many-to-many relationships
// ---------------
// init book club list 1 with 2 books
$blc1 = new BookClubList();
$blc1->setGroupLeader("Crazyleggs");
$blc1->setTheme("Happiness");
$brel1 = new BookListRel();
$brel1->setBook($phoenix);
$brel2 = new BookListRel();
$brel2->setBook($dj);
$blc1->addBookListRel($brel1);
$blc1->addBookListRel($brel2);
$blc1->save();
$this->assertNotNull($blc1->getId(), 'BookClubList 1 was saved');
// init book club list 2 with 1 book
$blc2 = new BookClubList();
$blc2->setGroupLeader("John Foo");
$blc2->setTheme("Default");
$brel3 = new BookListRel();
$brel3->setBook($phoenix);
$blc2->addBookListRel($brel3);
$blc2->save();
$this->assertNotNull($blc2->getId(), 'BookClubList 2 was saved');
// re-fetch books and lists from db to be sure that nothing is cached
$crit = new Criteria();
$crit->add(BookPeer::ID, $phoenix->getId());
$phoenix = BookPeer::doSelectOne($crit);
$this->assertNotNull($phoenix, "book 'phoenix' has been re-fetched from db");
$crit = new Criteria();
$crit->add(BookClubListPeer::ID, $blc1->getId());
$blc1 = BookClubListPeer::doSelectOne($crit);
$this->assertNotNull($blc1, 'BookClubList 1 has been re-fetched from db');
$crit = new Criteria();
$crit->add(BookClubListPeer::ID, $blc2->getId());
$blc2 = BookClubListPeer::doSelectOne($crit);
$this->assertNotNull($blc2, 'BookClubList 2 has been re-fetched from db');
$relCount = $phoenix->countBookListRels();
$this->assertEquals(2, $relCount, "book 'phoenix' has 2 BookListRels");
$relCount = $blc1->countBookListRels();
$this->assertEquals(2, $relCount, 'BookClubList 1 has 2 BookListRels');
$relCount = $blc2->countBookListRels();
$this->assertEquals(1, $relCount, 'BookClubList 2 has 1 BookListRel');
// Cleanup (tests DELETE)
// ----------------------
// Removing books that were just created
// First finding book by PK (=$phoenix_id) ....
$hp = BookQuery::create()->findPk($phoenix_id);
$this->assertNotNull($hp, 'Could find just-created book');
// Attempting to delete [multi-table] by found pk
$c = new Criteria();
$c->add(BookPeer::ID, $hp->getId());
// The only way for cascading to work currently
// is to specify the author_id and publisher_id (i.e. the fkeys
// have to be in the criteria).
$c->add(AuthorPeer::ID, $hp->getAuthor()->getId());
$c->add(PublisherPeer::ID, $hp->getPublisher()->getId());
$c->setSingleRecord(true);
BookPeer::doDelete($c);
// Checking to make sure correct records were removed.
$this->assertEquals(3, AuthorPeer::doCount(new Criteria()), 'Correct records were removed from author table');
$this->assertEquals(3, PublisherPeer::doCount(new Criteria()), 'Correct records were removed from publisher table');
$this->assertEquals(3, BookPeer::doCount(new Criteria()), 'Correct records were removed from book table');
// Attempting to delete books by complex criteria
BookQuery::create()
->filterByISBN("043935806X")
->orWhere('Book.ISBN = ?', "0380977427")
->orWhere('Book.ISBN = ?', "0140422161")
->delete();
// Attempting to delete book [id = $td_id]
$td->delete();
// Attempting to delete authors
AuthorQuery::create()->filterById($stephenson_id)->delete();
AuthorQuery::create()->filterById($byron_id)->delete();
$grass->delete();
// Attempting to delete publishers
PublisherQuery::create()->filterById($morrow_id)->delete();
PublisherQuery::create()->filterById($penguin_id)->delete();
$vintage->delete();
// These have to be deleted manually also since we have onDelete
// set to SETNULL in the foreign keys in book. Is this correct?
$rowling->delete();
$scholastic->delete();
$blc1->delete();
$blc2->delete();
$this->assertEquals(array(), AuthorPeer::doSelect(new Criteria()), 'no records in [author] table');
$this->assertEquals(array(), PublisherPeer::doSelect(new Criteria()), 'no records in [publisher] table');
$this->assertEquals(array(), BookPeer::doSelect(new Criteria()), 'no records in [book] table');
$this->assertEquals(array(), ReviewPeer::doSelect(new Criteria()), 'no records in [review] table');
$this->assertEquals(array(), MediaPeer::doSelect(new Criteria()), 'no records in [media] table');
$this->assertEquals(array(), BookClubListPeer::doSelect(new Criteria()), 'no records in [book_club_list] table');
$this->assertEquals(array(), BookListRelPeer::doSelect(new Criteria()), 'no records in [book_x_list] table');
}
}

View file

@ -0,0 +1,112 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests the character encoding support of the adapter.
*
* This test assumes that the created database supports UTF-8. For this to work,
* this file also has to be UTF-8.
*
* The database is relaoded before every test and flushed after every test. This
* means that you can always rely on the contents of the databases being the same
* for each test method in this class. See the BookstoreDataPopulator::populate()
* method for the exact contents of the database.
*
* @see BookstoreDataPopulator
* @author Hans Lellelid <hans@xmpl.org>
* @package misc
*/
class CharacterEncodingTest extends BookstoreTestBase
{
/**
* Database adapter.
* @var DBAdapter
*/
private $adapter;
public function setUp()
{
parent::setUp();
if (!extension_loaded('iconv')) {
throw new Exception("Character-encoding tests require iconv extension to be loaded.");
}
}
public function testUtf8()
{
$this->markTestSkipped();
$db = Propel::getDB(BookPeer::DATABASE_NAME);
$title = "Смерть на брудершафт. Младенец и черт";
// 1234567890123456789012345678901234567
// 1 2 3
$a = new Author();
$a->setFirstName("Б.");
$a->setLastName("АКУНИН");
$p = new Publisher();
$p->setName("Детектив российский, остросюжетная проза");
$b = new Book();
$b->setTitle($title);
$b->setISBN("B-59246");
$b->setAuthor($a);
$b->setPublisher($p);
$b->save();
$b->reload();
$this->assertEquals(37, iconv_strlen($b->getTitle(), 'utf-8'), "Expected 37 characters (not bytes) in title.");
$this->assertTrue(strlen($b->getTitle()) > iconv_strlen($b->getTitle(), 'utf-8'), "Expected more bytes than characters in title.");
}
public function testInvalidCharset()
{
$this->markTestSkipped();
$db = Propel::getDB(BookPeer::DATABASE_NAME);
if ($db instanceof DBSQLite) {
$this->markTestSkipped();
}
$a = new Author();
$a->setFirstName("Б.");
$a->setLastName("АКУНИН");
$a->save();
$authorNameWindows1251 = iconv("utf-8", "windows-1251", $a->getLastName());
$a->setLastName($authorNameWindows1251);
// Different databases seem to handle invalid data differently (no surprise, I guess...)
if ($db instanceof DBPostgres) {
try {
$a->save();
$this->fail("Expected an exception when saving non-UTF8 data to database.");
} catch (Exception $x) {
print $x;
}
} else {
// No exception is thrown by MySQL ... (others need to be tested still)
$a->save();
$a->reload();
$this->assertEquals("",$a->getLastName(), "Expected last_name to be empty (after inserting invalid charset data)");
}
}
}

View file

@ -0,0 +1,396 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
/**
* Tests some of the methods of generated Object classes. These are:
*
* - Base[Object]Peer::getFieldNames()
* - Base[Object]Peer::translateFieldName()
* - BasePeer::getFieldNames()
* - BasePeer::translateFieldName()
* - Base[Object]::getByName()
* - Base[Object]::setByName()
* - Base[Object]::fromArray()
* - Base[Object]::toArray()
*
* I've pulled these tests from the GeneratedObjectTest because the don't
* need the BookstoreTestBase's setUp and tearDown (database de/population)
* behaviour. The tests will run faster this way.
*
* @author Sven Fuchs <svenfuchs@artweb-design.de>
* @package misc
*/
class FieldnameRelatedTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
parent::setUp();
set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes");
require_once 'bookstore/map/BookTableMap.php';
require_once 'bookstore/BookPeer.php';
require_once 'bookstore/Book.php';
}
/**
* Tests if fieldname type constants are defined
*/
public function testFieldNameTypeConstants () {
$result = defined('BasePeer::TYPE_PHPNAME');
$this->assertTrue($result);
}
/**
* Tests the Base[Object]Peer::getFieldNames() method
*/
public function testGetFieldNames ()
{
$types = array(
BasePeer::TYPE_PHPNAME,
BasePeer::TYPE_COLNAME,
BasePeer::TYPE_FIELDNAME,
BasePeer::TYPE_NUM
);
$expecteds = array (
BasePeer::TYPE_PHPNAME => array(
0 => 'Id',
1 => 'Title',
2 => 'ISBN',
3 => 'Price',
4 => 'PublisherId',
5 => 'AuthorId'
),
BasePeer::TYPE_STUDLYPHPNAME => array(
0 => 'id',
1 => 'title',
2 => 'iSBN',
3 => 'price',
4 => 'publisherId',
5 => 'authorId'
),
BasePeer::TYPE_COLNAME => array(
0 => 'book.ID',
1 => 'book.TITLE',
2 => 'book.ISBN',
3 => 'book.PRICE',
4 => 'book.PUBLISHER_ID',
5 => 'book.AUTHOR_ID'
),
BasePeer::TYPE_FIELDNAME => array(
0 => 'id',
1 => 'title',
2 => 'isbn',
3 => 'price',
4 => 'publisher_id',
5 => 'author_id'
),
BasePeer::TYPE_NUM => array(
0 => 0,
1 => 1,
2 => 2,
3 => 3,
4 => 4,
5 => 5
)
);
foreach ($types as $type) {
$results[$type] = BookPeer::getFieldnames($type);
$this->assertEquals(
$expecteds[$type],
$results[$type],
'expected was: ' . print_r($expecteds[$type], 1) .
'but getFieldnames() returned ' . print_r($results[$type], 1)
);
}
}
/**
* Tests the Base[Object]Peer::translateFieldName() method
*/
public function testTranslateFieldName () {
$types = array(
BasePeer::TYPE_PHPNAME,
BasePeer::TYPE_STUDLYPHPNAME,
BasePeer::TYPE_COLNAME,
BasePeer::TYPE_FIELDNAME,
BasePeer::TYPE_NUM
);
$expecteds = array (
BasePeer::TYPE_PHPNAME => 'AuthorId',
BasePeer::TYPE_STUDLYPHPNAME => 'authorId',
BasePeer::TYPE_COLNAME => 'book.AUTHOR_ID',
BasePeer::TYPE_FIELDNAME => 'author_id',
BasePeer::TYPE_NUM => 5,
);
foreach ($types as $fromType) {
foreach ($types as $toType) {
$name = $expecteds[$fromType];
$expected = $expecteds[$toType];
$result = BookPeer::translateFieldName($name, $fromType, $toType);
$this->assertEquals($expected, $result);
}
}
}
/**
* Tests the BasePeer::getFieldNames() method
*/
public function testGetFieldNamesStatic () {
$types = array(
BasePeer::TYPE_PHPNAME,
BasePeer::TYPE_STUDLYPHPNAME,
BasePeer::TYPE_COLNAME,
BasePeer::TYPE_FIELDNAME,
BasePeer::TYPE_NUM
);
$expecteds = array (
BasePeer::TYPE_PHPNAME => array(
0 => 'Id',
1 => 'Title',
2 => 'ISBN',
3 => 'Price',
4 => 'PublisherId',
5 => 'AuthorId'
),
BasePeer::TYPE_STUDLYPHPNAME => array(
0 => 'id',
1 => 'title',
2 => 'iSBN',
3 => 'price',
4 => 'publisherId',
5 => 'authorId'
),
BasePeer::TYPE_COLNAME => array(
0 => 'book.ID',
1 => 'book.TITLE',
2 => 'book.ISBN',
3 => 'book.PRICE',
4 => 'book.PUBLISHER_ID',
5 => 'book.AUTHOR_ID'
),
BasePeer::TYPE_FIELDNAME => array(
0 => 'id',
1 => 'title',
2 => 'isbn',
3 => 'price',
4 => 'publisher_id',
5 => 'author_id'
),
BasePeer::TYPE_NUM => array(
0 => 0,
1 => 1,
2 => 2,
3 => 3,
4 => 4,
5 => 5
)
);
foreach ($types as $type) {
$results[$type] = BasePeer::getFieldnames('Book', $type);
$this->assertEquals(
$expecteds[$type],
$results[$type],
'expected was: ' . print_r($expecteds[$type], 1) .
'but getFieldnames() returned ' . print_r($results[$type], 1)
);
}
}
/**
* Tests the BasePeer::translateFieldName() method
*/
public function testTranslateFieldNameStatic () {
$types = array(
BasePeer::TYPE_PHPNAME,
BasePeer::TYPE_STUDLYPHPNAME,
BasePeer::TYPE_COLNAME,
BasePeer::TYPE_FIELDNAME,
BasePeer::TYPE_NUM
);
$expecteds = array (
BasePeer::TYPE_PHPNAME => 'AuthorId',
BasePeer::TYPE_STUDLYPHPNAME => 'authorId',
BasePeer::TYPE_COLNAME => 'book.AUTHOR_ID',
BasePeer::TYPE_FIELDNAME => 'author_id',
BasePeer::TYPE_NUM => 5,
);
foreach ($types as $fromType) {
foreach ($types as $toType) {
$name = $expecteds[$fromType];
$expected = $expecteds[$toType];
$result = BasePeer::translateFieldName('Book', $name, $fromType, $toType);
$this->assertEquals($expected, $result);
}
}
}
/**
* Tests the Base[Object]::getByName() method
*/
public function testGetByName() {
$types = array(
BasePeer::TYPE_PHPNAME => 'Title',
BasePeer::TYPE_STUDLYPHPNAME => 'title',
BasePeer::TYPE_COLNAME => 'book.TITLE',
BasePeer::TYPE_FIELDNAME => 'title',
BasePeer::TYPE_NUM => 1
);
$book = new Book();
$book->setTitle('Harry Potter and the Order of the Phoenix');
$expected = 'Harry Potter and the Order of the Phoenix';
foreach ($types as $type => $name) {
$result = $book->getByName($name, $type);
$this->assertEquals($expected, $result);
}
}
/**
* Tests the Base[Object]::setByName() method
*/
public function testSetByName() {
$book = new Book();
$types = array(
BasePeer::TYPE_PHPNAME => 'Title',
BasePeer::TYPE_STUDLYPHPNAME => 'title',
BasePeer::TYPE_COLNAME => 'book.TITLE',
BasePeer::TYPE_FIELDNAME => 'title',
BasePeer::TYPE_NUM => 1
);
$title = 'Harry Potter and the Order of the Phoenix';
foreach ($types as $type => $name) {
$book->setByName($name, $title, $type);
$result = $book->getTitle();
$this->assertEquals($title, $result);
}
}
/**
* Tests the Base[Object]::fromArray() method
*
* this also tests populateFromArray() because that's an alias
*/
public function testFromArray(){
$types = array(
BasePeer::TYPE_PHPNAME,
BasePeer::TYPE_STUDLYPHPNAME,
BasePeer::TYPE_COLNAME,
BasePeer::TYPE_FIELDNAME,
BasePeer::TYPE_NUM
);
$expecteds = array (
BasePeer::TYPE_PHPNAME => array (
'Title' => 'Harry Potter and the Order of the Phoenix',
'ISBN' => '043935806X'
),
BasePeer::TYPE_STUDLYPHPNAME => array (
'title' => 'Harry Potter and the Order of the Phoenix',
'iSBN' => '043935806X'
),
BasePeer::TYPE_COLNAME => array (
'book.TITLE' => 'Harry Potter and the Order of the Phoenix',
'book.ISBN' => '043935806X'
),
BasePeer::TYPE_FIELDNAME => array (
'title' => 'Harry Potter and the Order of the Phoenix',
'isbn' => '043935806X'
),
BasePeer::TYPE_NUM => array (
'1' => 'Harry Potter and the Order of the Phoenix',
'2' => '043935806X'
)
);
$book = new Book();
foreach ($types as $type) {
$expected = $expecteds[$type];
$book->fromArray($expected, $type);
$result = array();
foreach (array_keys($expected) as $key) {
$result[$key] = $book->getByName($key, $type);
}
$this->assertEquals(
$expected,
$result,
'expected was: ' . print_r($expected, 1) .
'but fromArray() returned ' . print_r($result, 1)
);
}
}
/**
* Tests the Base[Object]::toArray() method
*/
public function testToArray(){
$types = array(
BasePeer::TYPE_PHPNAME,
BasePeer::TYPE_STUDLYPHPNAME,
BasePeer::TYPE_COLNAME,
BasePeer::TYPE_FIELDNAME,
BasePeer::TYPE_NUM
);
$book = new Book();
$book->fromArray(array (
'Title' => 'Harry Potter and the Order of the Phoenix',
'ISBN' => '043935806X'
));
$expecteds = array (
BasePeer::TYPE_PHPNAME => array (
'Title' => 'Harry Potter and the Order of the Phoenix',
'ISBN' => '043935806X'
),
BasePeer::TYPE_STUDLYPHPNAME => array (
'title' => 'Harry Potter and the Order of the Phoenix',
'iSBN' => '043935806X'
),
BasePeer::TYPE_COLNAME => array (
'book.TITLE' => 'Harry Potter and the Order of the Phoenix',
'book.ISBN' => '043935806X'
),
BasePeer::TYPE_FIELDNAME => array (
'title' => 'Harry Potter and the Order of the Phoenix',
'isbn' => '043935806X'
),
BasePeer::TYPE_NUM => array (
'1' => 'Harry Potter and the Order of the Phoenix',
'2' => '043935806X'
)
);
foreach ($types as $type) {
$expected = $expecteds[$type];
$result = $book->toArray($type);
// remove ID since its autoincremented at each test iteration
$result = array_slice($result, 1, 2, true);
$this->assertEquals(
$expected,
$result,
'expected was: ' . print_r($expected, 1) .
'but toArray() returned ' . print_r($result, 1)
);
}
}
}

View file

@ -0,0 +1,250 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/* It's only fair to admit that these tests were carefully crafted
after studying the current implementation to make it look as bad as
possible. I am really sorry. :-( */
/**
* @package misc
*/
class Ticket520Test extends BookstoreTestBase
{
public function testNewObjectsAvailableWhenSaveNotCalled()
{
$a = new Author();
$a->setFirstName("Douglas");
$a->setLastName("Adams");
$b1 = new Book();
$b1->setTitle("The Hitchhikers Guide To The Galaxy");
$a->addBook($b1);
$b2 = new Book();
$b2->setTitle("The Restaurant At The End Of The Universe");
$a->addBook($b2);
// Passing no Criteria means "use the internal collection or query the database"
// in that case two objects are added, so it should return 2
$books = $a->getBooks();
$this->assertEquals(2, count($books));
}
public function testNewObjectsNotAvailableWithCriteria()
{
$a = new Author();
$a->setFirstName("Douglas");
$a->setLastName("Adams");
$b1 = new Book();
$b1->setTitle("The Hitchhikers Guide To The Galaxy");
$a->addBook($b1);
$b2 = new Book();
$b2->setTitle("The Restaurant At The End Of The Universe");
$a->addBook($b2);
$c = new Criteria();
$c->add(BookPeer::TITLE, "%Hitchhiker%", Criteria::LIKE);
$guides = $a->getBooks($c);
$this->assertEquals(0, count($guides), 'Passing a Criteria means "force a database query"');
}
public function testNewObjectsAvailableAfterCriteria()
{
$a = new Author();
$a->setFirstName("Douglas");
$a->setLastName("Adams");
$b1 = new Book();
$b1->setTitle("The Hitchhikers Guide To The Galaxy");
$a->addBook($b1);
$b2 = new Book();
$b2->setTitle("The Restaurant At The End Of The Universe");
$a->addBook($b2);
$c = new Criteria();
$c->add(BookPeer::TITLE, "%Hitchhiker%", Criteria::LIKE);
$guides = $a->getBooks($c);
$books = $a->getBooks();
$this->assertEquals(2, count($books), 'A previous query with a Criteria does not erase the internal collection');
}
public function testSavedObjectsWithCriteria()
{
$a = new Author();
$a->setFirstName("Douglas");
$a->setLastName("Adams");
$b1 = new Book();
$b1->setTitle("The Hitchhikers Guide To The Galaxy");
$a->addBook($b1);
$b2 = new Book();
$b2->setTitle("The Restaurant At The End Of The Universe");
$a->addBook($b2);
$c = new Criteria();
$c->add(BookPeer::TITLE, "%Hitchhiker%", Criteria::LIKE);
$guides = $a->getBooks($c);
$a->save();
$booksAfterSave = $a->getBooks($c);
$this->assertEquals(1, count($booksAfterSave), 'A previous query with a Criteria is not cached');
}
public function testAddNewObjectAfterSave()
{
$a = new Author();
$a->setFirstName("Douglas");
$a->setLastName("Adams");
$a->save();
$b1 = new Book();
$b1->setTitle("The Hitchhikers Guide To The Galaxy");
$a->addBook($b1);
$books = $a->getBooks();
$this->assertEquals(1, count($books));
$this->assertTrue($books->contains($b1));
/* Now this is the initial ticket 520: If we have a saved author,
add a new book but happen to call getBooks() before we call save() again,
the book used to be lost. */
$a->save();
$this->assertFalse($b1->isNew(), 'related objects are also saved after fetching them');
}
public function testAddNewObjectAfterSaveWithPoisonedCache()
{
/* This is like testAddNewObjectAfterSave(),
but this time we "poison" the author's $colBooks cache
before adding the book by calling getBooks(). */
$a = new Author();
$a->setFirstName("Douglas");
$a->setLastName("Adams");
$a->save();
$a->getBooks();
$b1 = new Book();
$b1->setTitle("The Hitchhikers Guide To The Galaxy");
$a->addBook($b1);
$books = $a->getBooks();
$this->assertEquals(1, count($books));
$this->assertTrue($books->contains($b1), 'new related objects not deleted after fetching them');
}
public function testCachePoisoning()
{
/* Like testAddNewObjectAfterSaveWithPoisonedCache, emphasizing
cache poisoning. */
$a = new Author();
$a->setFirstName("Douglas");
$a->setLastName("Adams");
$a->save();
$c = new Criteria();
$c->add(BookPeer::TITLE, "%Restaurant%", Criteria::LIKE);
$this->assertEquals(0, count($a->getBooks($c)));
$b1 = new Book();
$b1->setTitle("The Hitchhikers Guide To The Galaxy");
$a->addBook($b1);
/* Like testAddNewObjectAfterSaveWithPoisonedCache, but this time
with a real criteria. */
$this->assertEquals(0, count($a->getBooks($c)));
$a->save();
$this->assertFalse($b1->isNew());
$this->assertEquals(0, count($a->getBooks($c)));
}
public function testDeletedBookDisappears()
{
$this->markTestSkipped();
$a = new Author();
$a->setFirstName("Douglas");
$a->setLastName("Adams");
$b1 = new Book();
$b1->setTitle("The Hitchhikers Guide To The Galaxy");
$a->addBook($b1);
$b2 = new Book();
$b2->setTitle("The Restaurant At The End Of The Universe");
$a->addBook($b2);
/* As you cannot write $a->remove($b2), you have to delete $b2
directly. */
/* All objects unsaved. As of revision 851, this circumvents the
$colBooks cache. Anyway, fails because getBooks() never checks if
a colBooks entry has been deleted. */
$this->assertEquals(2, count($a->getBooks()));
$b2->delete();
$this->assertEquals(1, count($a->getBooks()));
/* Even if we had saved everything before and the delete() had
actually updated the DB, the $b2 would still be a "zombie" in
$a's $colBooks field. */
}
public function testNewObjectsGetLostOnJoin() {
/* While testNewObjectsAvailableWhenSaveNotCalled passed as of
revision 851, in this case we call getBooksJoinPublisher() instead
of just getBooks(). get...Join...() does not contain the check whether
the current object is new, it will always consult the DB and lose the
new objects entirely. Thus the test fails. (At least for Propel 1.2 ?!?) */
$this->markTestSkipped();
$a = new Author();
$a->setFirstName("Douglas");
$a->setLastName("Adams");
$p = new Publisher();
$p->setName('Pan Books Ltd.');
$b1 = new Book();
$b1->setTitle("The Hitchhikers Guide To The Galaxy");
$b1->setPublisher($p); // uh... did not check that :^)
$a->addBook($b1);
$b2 = new Book();
$b2->setTitle("The Restaurant At The End Of The Universe");
$b2->setPublisher($p);
$a->addBook($b2);
$books = $a->getBooksJoinPublisher();
$this->assertEquals(2, count($books));
$this->assertContains($b1, $books);
$this->assertContains($b2, $books);
$a->save();
$this->assertFalse($b1->isNew());
$this->assertFalse($b2->isNew());
}
}

View file

@ -0,0 +1,47 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests the DbOracle adapter
*
* @see BookstoreDataPopulator
* @author Francois EZaninotto
* @package runtime.adapter
*/
class DBOracleTest extends BookstoreTestBase
{
public function testApplyLimitSimple()
{
Propel::setDb('oracle', new DBOracle());
$c = new Criteria();
$c->setDbName('oracle');
BookPeer::addSelectColumns($c);
$c->setLimit(1);
$params = array();
$sql = BasePeer::createSelectSql($c, $params);
$this->assertEquals('SELECT B.* FROM (SELECT A.*, rownum AS PROPEL_ROWNUM FROM (SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM book) A ) B WHERE B.PROPEL_ROWNUM <= 1', $sql, 'applyLimit() creates a subselect with the original column names by default');
}
public function testApplyLimitDuplicateColumnName()
{
Propel::setDb('oracle', new DBOracle());
$c = new Criteria();
$c->setDbName('oracle');
BookPeer::addSelectColumns($c);
AuthorPeer::addSelectColumns($c);
$c->setLimit(1);
$params = array();
$sql = BasePeer::createSelectSql($c, $params);
$this->assertEquals('SELECT B.* FROM (SELECT A.*, rownum AS PROPEL_ROWNUM FROM (SELECT book.ID AS book_ID, book.TITLE AS book_TITLE, book.ISBN AS book_ISBN, book.PRICE AS book_PRICE, book.PUBLISHER_ID AS book_PUBLISHER_ID, book.AUTHOR_ID AS book_AUTHOR_ID, author.ID AS author_ID, author.FIRST_NAME AS author_FIRST_NAME, author.LAST_NAME AS author_LAST_NAME, author.EMAIL AS author_EMAIL, author.AGE AS author_AGESELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID, author.ID, author.FIRST_NAME, author.LAST_NAME, author.EMAIL, author.AGE FROM book, author) A ) B WHERE B.PROPEL_ROWNUM <= 1', $sql, 'applyLimit() creates a subselect with aliased column names when a duplicate column name is found');
}
}

View file

@ -0,0 +1,152 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Test class for PropelObjectCollection.
*
* @author Francois Zaninotto
* @version $Id: PropelObjectCollectionTest.php 1348 2009-12-03 21:49:00Z francois $
* @package runtime.collection
*/
class PropelArrayCollectionTest extends BookstoreEmptyTestBase
{
protected function setUp()
{
parent::setUp();
BookstoreDataPopulator::populate($this->con);
}
public function testSave()
{
$books = PropelQuery::from('Book')->setFormatter(ModelCriteria::FORMAT_ARRAY)->find();
foreach ($books as &$book) {
$book['Title'] = 'foo';
}
$books->save();
// check that the modifications are persisted
BookPeer::clearInstancePool();
$books = PropelQuery::from('Book')->find();
foreach ($books as $book) {
$this->assertEquals('foo', $book->getTitle('foo'));
}
}
public function testDelete()
{
$books = PropelQuery::from('Book')->setFormatter(ModelCriteria::FORMAT_ARRAY)->find();
$books->delete();
// check that the modifications are persisted
BookPeer::clearInstancePool();
$books = PropelQuery::from('Book')->find();
$this->assertEquals(0, count($books));
}
public function testGetPrimaryKeys()
{
$books = PropelQuery::from('Book')->setFormatter(ModelCriteria::FORMAT_ARRAY)->find();
$pks = $books->getPrimaryKeys();
$this->assertEquals(4, count($pks));
$keys = array('Book_0', 'Book_1', 'Book_2', 'Book_3');
$this->assertEquals($keys, array_keys($pks));
$pks = $books->getPrimaryKeys(false);
$keys = array(0, 1, 2, 3);
$this->assertEquals($keys, array_keys($pks));
$bookObjects = PropelQuery::from('Book')->find();
foreach ($pks as $key => $value) {
$this->assertEquals($bookObjects[$key]->getPrimaryKey(), $value);
}
}
public function testFromArray()
{
$author = new Author();
$author->setFirstName('Jane');
$author->setLastName('Austen');
$author->save();
$books = array(
array('Title' => 'Mansfield Park', 'AuthorId' => $author->getId()),
array('Title' => 'Pride And PRejudice', 'AuthorId' => $author->getId())
);
$col = new PropelArrayCollection();
$col->setModel('Book');
$col->fromArray($books);
$col->save();
$nbBooks = PropelQuery::from('Book')->count();
$this->assertEquals(6, $nbBooks);
$booksByJane = PropelQuery::from('Book b')
->join('b.Author a')
->where('a.LastName = ?', 'Austen')
->count();
$this->assertEquals(2, $booksByJane);
}
public function testToArray()
{
$books = PropelQuery::from('Book')->setFormatter(ModelCriteria::FORMAT_ARRAY)->find();
$booksArray = $books->toArray();
$this->assertEquals(4, count($booksArray));
$bookObjects = PropelQuery::from('Book')->find();
foreach ($booksArray as $key => $book) {
$this->assertEquals($bookObjects[$key]->toArray(), $book);
}
$booksArray = $books->toArray();
$keys = array(0, 1, 2, 3);
$this->assertEquals($keys, array_keys($booksArray));
$booksArray = $books->toArray(null, true);
$keys = array('Book_0', 'Book_1', 'Book_2', 'Book_3');
$this->assertEquals($keys, array_keys($booksArray));
$booksArray = $books->toArray('Title');
$keys = array('Harry Potter and the Order of the Phoenix', 'Quicksilver', 'Don Juan', 'The Tin Drum');
$this->assertEquals($keys, array_keys($booksArray));
$booksArray = $books->toArray('Title', true);
$keys = array('Book_Harry Potter and the Order of the Phoenix', 'Book_Quicksilver', 'Book_Don Juan', 'Book_The Tin Drum');
$this->assertEquals($keys, array_keys($booksArray));
}
public function getWorkerObject()
{
$col = new TestablePropelArrayCollection();
$col->setModel('Book');
$book = $col->getWorkerObject();
$this->assertTrue($book instanceof Book, 'getWorkerObject() returns an object of the collection model');
$book->foo = 'bar';
$this->assertEqual('bar', $col->getWorkerObject()->foo, 'getWorkerObject() returns always the same object');
}
/**
* @expectedException PropelException
*/
public function testGetWorkerObjectNoModel()
{
$col = new TestablePropelArrayCollection();
$col->getWorkerObject();
}
}
class TestablePropelArrayCollection extends PropelArrayCollection
{
public function getWorkerObject()
{
return parent::getWorkerObject();
}
}

View file

@ -0,0 +1,353 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Test class for PropelCollection.
*
* @author Francois Zaninotto
* @version $Id: PropelCollectionTest.php 1348 2009-12-03 21:49:00Z francois $
* @package runtime.collection
*/
class PropelCollectionTest extends BookstoreTestBase
{
public function testArrayAccess()
{
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$this->assertEquals('bar1', $col[0], 'PropelCollection allows access via $foo[$index]');
$this->assertEquals('bar2', $col[1], 'PropelCollection allows access via $foo[$index]');
$this->assertEquals('bar3', $col[2], 'PropelCollection allows access via $foo[$index]');
}
public function testGetData()
{
$col = new PropelCollection();
$this->assertEquals(array(), $col->getData(), 'getData() returns an empty array for empty collections');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$this->assertEquals($data, $col->getData(), 'getData() returns the collection data');
$col[0] = 'bar4';
$this->assertEquals('bar1', $data[0], 'getData() returns a copy of the collection data');
}
public function testSetData()
{
$col = new PropelCollection();
$col->setData(array());
$this->assertEquals(array(), $col->getArrayCopy(), 'setData() can set data to an empty array');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection();
$col->setData($data);
$this->assertEquals($data, $col->getArrayCopy(), 'setData() sets the collection data');
}
public function testGetPosition()
{
$col = new PropelCollection();
$this->assertEquals(0, $col->getPosition(), 'getPosition() returns 0 on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$expectedPositions = array(0, 1, 2);
foreach ($col as $element) {
$this->assertEquals(array_shift($expectedPositions), $col->getPosition(), 'getPosition() returns the current position');
$this->assertEquals($element, $col->getCurrent(), 'getPosition() does not change the current position');
}
}
public function testGetFirst()
{
$col = new PropelCollection();
$this->assertNull($col->getFirst(), 'getFirst() returns null on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$this->assertEquals('bar1', $col->getFirst(), 'getFirst() returns value of the first element in the collection');
}
public function testIsFirst()
{
$col = new PropelCollection();
$this->assertTrue($col->isFirst(), 'isFirst() returns true on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$expectedRes = array(true, false, false);
foreach ($col as $element) {
$this->assertEquals(array_shift($expectedRes), $col->isFirst(), 'isFirst() returns true only for the first element');
$this->assertEquals($element, $col->getCurrent(), 'isFirst() does not change the current position');
}
}
public function testGetPrevious()
{
$col = new PropelCollection();
$this->assertNull($col->getPrevious(), 'getPrevious() returns null on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$this->assertNull($col->getPrevious(), 'getPrevious() returns null when the internal pointer is at the beginning of the list');
$col->getNext();
$this->assertEquals('bar1', $col->getPrevious(), 'getPrevious() returns the previous element');
$this->assertEquals('bar1', $col->getCurrent(), 'getPrevious() decrements the internal pointer');
}
public function testGetCurrent()
{
$col = new PropelCollection();
$this->assertNull($col->getCurrent(), 'getCurrent() returns null on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$this->assertEquals('bar1', $col->getCurrent(), 'getCurrent() returns the value of the first element when the internal pointer is at the beginning of the list');
foreach ($col as $key => $value) {
$this->assertEquals($value, $col->getCurrent(), 'getCurrent() returns the value of the current element in the collection');
}
}
public function testGetNext()
{
$col = new PropelCollection();
$this->assertNull($col->getNext(), 'getNext() returns null on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$this->assertEquals('bar2', $col->getNext(), 'getNext() returns the second element when the internal pointer is at the beginning of the list');
$this->assertEquals('bar2', $col->getCurrent(), 'getNext() increments the internal pointer');
$col->getNext();
$this->assertNull($col->getNext(), 'getNext() returns null when the internal pointer is at the end of the list');
}
public function testGetLast()
{
$col = new PropelCollection();
$this->assertNull($col->getLast(), 'getLast() returns null on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$this->assertEquals('bar3', $col->getLast(), 'getLast() returns the last element');
$this->assertEquals('bar3', $col->getCurrent(), 'getLast() moves the internal pointer to the last element');
}
public function testIsLAst()
{
$col = new PropelCollection();
$this->assertTrue($col->isLast(), 'isLast() returns true on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$expectedRes = array(false, false, true);
foreach ($col as $element) {
$this->assertEquals(array_shift($expectedRes), $col->isLast(), 'isLast() returns true only for the last element');
$this->assertEquals($element, $col->getCurrent(), 'isLast() does not change the current position');
}
}
public function testIsEmpty()
{
$col = new PropelCollection();
$this->assertTrue($col->isEmpty(), 'isEmpty() returns true on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$this->assertFalse($col->isEmpty(), 'isEmpty() returns false on a non empty collection');
}
public function testIsOdd()
{
$col = new PropelCollection();
$this->assertFalse($col->isOdd(), 'isOdd() returns false on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection();
$col->setData($data);
foreach ($col as $key => $value) {
$this->assertEquals((boolean) ($key % 2), $col->isOdd(), 'isOdd() returns true only when the key is odd');
}
}
public function testIsEven()
{
$col = new PropelCollection();
$this->assertTrue($col->isEven(), 'isEven() returns true on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection();
$col->setData($data);
foreach ($col as $key => $value) {
$this->assertEquals(!(boolean) ($key % 2), $col->isEven(), 'isEven() returns true only when the key is even');
}
}
public function testGet()
{
$col = new PropelCollection(array('foo', 'bar'));
$this->assertEquals('foo', $col->get(0), 'get() returns an element from its key');
}
/**
* @expectedException PropelException
*/
public function testGetUnknownOffset()
{
$col = new PropelCollection();
$bar = $col->get('foo');
}
public function testPop()
{
$col = new PropelCollection();
$this->assertNull($col->pop(), 'pop() returns null on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$this->assertEquals('bar3', $col->pop(), 'pop() returns the last element of the collection');
$this->assertEquals(array('bar1', 'bar2'), $col->getData(), 'pop() removes the last element of the collection');
}
public function testShift()
{
$col = new PropelCollection();
$this->assertNull($col->shift(), 'shift() returns null on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$this->assertEquals('bar1', $col->shift(), 'shift() returns the first element of the collection');
$this->assertEquals(array('bar2', 'bar3'), $col->getData(), 'shift() removes the first element of the collection');
}
public function testPrepend()
{
$col = new PropelCollection();
$this->assertEquals(1, $col->prepend('a'), 'prepend() returns 1 on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$this->assertEquals(4, $col->prepend('bar4'), 'prepend() returns the new number of elements in the collection when adding a variable');
$this->assertEquals(array('bar4', 'bar1', 'bar2', 'bar3'), $col->getData(), 'prepend() adds new element to the beginning of the collection');
}
public function testSet()
{
$col = new PropelCollection();
$col->set(4, 'bar');
$this->assertEquals(array(4 => 'bar'), $col->getData(), 'set() adds an element to the collection with a key');
$col = new PropelCollection();
$col->set(null, 'foo');
$col->set(null, 'bar');
$this->assertEquals(array('foo', 'bar'), $col->getData(), 'set() adds an element to the collection without a key');
}
public function testRemove()
{
$col = new PropelCollection();
$col[0] = 'bar';
$col[1] = 'baz';
$col->remove(1);
$this->assertEquals(array('bar'), $col->getData(), 'remove() removes an element from its key');
}
/**
* @expectedException PropelException
*/
public function testRemoveUnknownOffset()
{
$col = new PropelCollection();
$col->remove(2);
}
public function testClear()
{
$col = new PropelCollection();
$col->clear();
$this->assertEquals(array(), $col->getData(), 'clear() empties the collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$col->clear();
$this->assertEquals(array(), $col->getData(), 'clear() empties the collection');
}
public function testContains()
{
$col = new PropelCollection();
$this->assertFalse($col->contains('foo_1'), 'contains() returns false on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$this->assertTrue($col->contains('bar1'), 'contains() returns true when the key exists');
$this->assertFalse($col->contains('bar4'), 'contains() returns false when the key does not exist');
}
public function testSearch()
{
$col = new PropelCollection();
$this->assertFalse($col->search('bar1'), 'search() returns false on an empty collection');
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$this->assertEquals(1, $col->search('bar2'), 'search() returns the key when the element exists');
$this->assertFalse($col->search('bar4'), 'search() returns false when the element does not exist');
}
public function testSerializable()
{
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$col->setModel('Foo');
$serializedCol = serialize($col);
$col2 = unserialize($serializedCol);
$this->assertEquals($col, $col2, 'PropelCollection is serializable');
}
public function testGetIterator()
{
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$it1 = $col->getIterator();
$it2 = $col->getIterator();
$this->assertNotSame($it1, $it2, 'getIterator() returns always a new iterator');
}
public function testGetInternalIterator()
{
$data = array('bar1', 'bar2', 'bar3');
$col = new PropelCollection($data);
$it1 = $col->getInternalIterator();
$it2 = $col->getINternalIterator();
$this->assertSame($it1, $it2, 'getInternalIterator() returns always the same iterator');
$col->getInternalIterator()->next();
$this->assertEquals('bar2', $col->getInternalIterator()->current(), 'getInternalIterator() returns always the same iterator');
}
public function testGetPeerClass()
{
$col = new PropelCollection();
$col->setModel('Book');
$this->assertEquals('BookPeer', $col->getPeerClass(), 'getPeerClass() returns the Peer class for the collection model');
}
/**
* @expectedException PropelException
*/
public function testGetPeerClassNoModel()
{
$col = new PropelCollection();
$col->getPeerClass();
}
public function testGetConnection()
{
$col = new PropelCollection();
$col->setModel('Book');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$this->assertEquals($con, $col->getConnection(), 'getConnection() returns a connection for the collection model');
$con = Propel::getConnection(BookPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
$this->assertEquals($con, $col->getConnection(Propel::CONNECTION_WRITE), 'getConnection() accepts a connection type parameter');
}
/**
* @expectedException PropelException
*/
public function testGetConnectionNoModel()
{
$col = new PropelCollection();
$col->getConnection();
}
}

View file

@ -0,0 +1,236 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Test class for PropelObjectCollection.
*
* @author Francois Zaninotto
* @version $Id: PropelObjectCollectionTest.php 1348 2009-12-03 21:49:00Z francois $
* @package runtime.collection
*/
class PropelObjectCollectionTest extends BookstoreEmptyTestBase
{
protected function setUp()
{
parent::setUp();
BookstoreDataPopulator::populate($this->con);
}
public function testSave()
{
$books = PropelQuery::from('Book')->find();
foreach ($books as $book) {
$book->setTitle('foo');
}
$books->save();
// check that all the books are saved
foreach ($books as $book) {
$this->assertFalse($book->isModified());
}
// check that the modifications are persisted
BookPeer::clearInstancePool();
$books = PropelQuery::from('Book')->find();
foreach ($books as $book) {
$this->assertEquals('foo', $book->getTitle('foo'));
}
}
public function testDelete()
{
$books = PropelQuery::from('Book')->find();
$books->delete();
// check that all the books are deleted
foreach ($books as $book) {
$this->assertTrue($book->isDeleted());
}
// check that the modifications are persisted
BookPeer::clearInstancePool();
$books = PropelQuery::from('Book')->find();
$this->assertEquals(0, count($books));
}
public function testGetPrimaryKeys()
{
$books = PropelQuery::from('Book')->find();
$pks = $books->getPrimaryKeys();
$this->assertEquals(4, count($pks));
$keys = array('Book_0', 'Book_1', 'Book_2', 'Book_3');
$this->assertEquals($keys, array_keys($pks));
$pks = $books->getPrimaryKeys(false);
$keys = array(0, 1, 2, 3);
$this->assertEquals($keys, array_keys($pks));
foreach ($pks as $key => $value) {
$this->assertEquals($books[$key]->getPrimaryKey(), $value);
}
}
public function testFromArray()
{
$author = new Author();
$author->setFirstName('Jane');
$author->setLastName('Austen');
$author->save();
$books = array(
array('Title' => 'Mansfield Park', 'AuthorId' => $author->getId()),
array('Title' => 'Pride And PRejudice', 'AuthorId' => $author->getId())
);
$col = new PropelObjectCollection();
$col->setModel('Book');
$col->fromArray($books);
$col->save();
$nbBooks = PropelQuery::from('Book')->count();
$this->assertEquals(6, $nbBooks);
$booksByJane = PropelQuery::from('Book b')
->join('b.Author a')
->where('a.LastName = ?', 'Austen')
->count();
$this->assertEquals(2, $booksByJane);
}
public function testToArray()
{
$books = PropelQuery::from('Book')->find();
$booksArray = $books->toArray();
$this->assertEquals(4, count($booksArray));
foreach ($booksArray as $key => $book) {
$this->assertEquals($books[$key]->toArray(), $book);
}
$booksArray = $books->toArray();
$keys = array(0, 1, 2, 3);
$this->assertEquals($keys, array_keys($booksArray));
$booksArray = $books->toArray(null, true);
$keys = array('Book_0', 'Book_1', 'Book_2', 'Book_3');
$this->assertEquals($keys, array_keys($booksArray));
$booksArray = $books->toArray('Title');
$keys = array('Harry Potter and the Order of the Phoenix', 'Quicksilver', 'Don Juan', 'The Tin Drum');
$this->assertEquals($keys, array_keys($booksArray));
$booksArray = $books->toArray('Title', true);
$keys = array('Book_Harry Potter and the Order of the Phoenix', 'Book_Quicksilver', 'Book_Don Juan', 'Book_The Tin Drum');
$this->assertEquals($keys, array_keys($booksArray));
}
public function testGetArrayCopy()
{
$books = PropelQuery::from('Book')->find();
$booksArray = $books->getArrayCopy();
$this->assertEquals(4, count($booksArray));
foreach ($booksArray as $key => $book) {
$this->assertEquals($books[$key], $book);
}
$booksArray = $books->getArrayCopy();
$keys = array(0, 1, 2, 3);
$this->assertEquals($keys, array_keys($booksArray));
$booksArray = $books->getArrayCopy(null, true);
$keys = array('Book_0', 'Book_1', 'Book_2', 'Book_3');
$this->assertEquals($keys, array_keys($booksArray));
$booksArray = $books->getArrayCopy('Title');
$keys = array('Harry Potter and the Order of the Phoenix', 'Quicksilver', 'Don Juan', 'The Tin Drum');
$this->assertEquals($keys, array_keys($booksArray));
$booksArray = $books->getArrayCopy('Title', true);
$keys = array('Book_Harry Potter and the Order of the Phoenix', 'Book_Quicksilver', 'Book_Don Juan', 'Book_The Tin Drum');
$this->assertEquals($keys, array_keys($booksArray));
}
public function testToKeyValue()
{
$books = PropelQuery::from('Book')->find();
$expected = array();
foreach ($books as $book) {
$expected[$book->getTitle()] = $book->getISBN();
}
$booksArray = $books->toKeyValue('Title', 'ISBN');
$this->assertEquals(4, count($booksArray));
$this->assertEquals($expected, $booksArray, 'toKeyValue() turns the collection to an associative array');
$expected = array();
foreach ($books as $book) {
$expected[$book->getISBN()] = $book->getTitle();
}
$booksArray = $books->toKeyValue('ISBN');
$this->assertEquals($expected, $booksArray, 'toKeyValue() uses __toString() for the value if no second field name is passed');
$expected = array();
foreach ($books as $book) {
$expected[$book->getId()] = $book->getTitle();
}
$booksArray = $books->toKeyValue();
$this->assertEquals($expected, $booksArray, 'toKeyValue() uses primary key for the key and __toString() for the value if no field name is passed');
}
public function testPopulateRelation()
{
AuthorPeer::clearInstancePool();
BookPeer::clearInstancePool();
$authors = AuthorQuery::create()->find();
$books = $authors->populateRelation('Book');
$this->assertTrue($books instanceof PropelObjectCollection, 'populateRelation() returns a PropelCollection instance');
$this->assertEquals('Book', $books->getModel(), 'populateRelation() returns a collection of the related objects');
$this->assertEquals(4, count($books), 'populateRelation() the list of related objects');
}
public function testPopulateRelationCriteria()
{
AuthorPeer::clearInstancePool();
BookPeer::clearInstancePool();
$authors = AuthorQuery::create()->find();
$c = new Criteria();
$c->setLimit(3);
$books = $authors->populateRelation('Book', $c);
$this->assertEquals(3, count($books), 'populateRelation() accepts an optional criteria object to filter the query');
}
public function testPopulateRelationOneToMany()
{
$con = Propel::getConnection();
AuthorPeer::clearInstancePool();
BookPeer::clearInstancePool();
$authors = AuthorQuery::create()->find($con);
$count = $con->getQueryCount();
$books = $authors->populateRelation('Book', null, $con);
foreach ($authors as $author) {
foreach ($author->getBooks() as $book) {
$this->assertEquals($author, $book->getAuthor());
}
}
$this->assertEquals($count + 1, $con->getQueryCount(), 'populateRelation() populates a one-to-many relationship with a single supplementary query');
}
public function testPopulateRelationManyToOne()
{
$con = Propel::getConnection();
AuthorPeer::clearInstancePool();
BookPeer::clearInstancePool();
$books = BookQuery::create()->find($con);
$count = $con->getQueryCount();
$books->populateRelation('Author', null, $con);
foreach ($books as $book) {
$author = $book->getAuthor();
}
$this->assertEquals($count + 1, $con->getQueryCount(), 'populateRelation() populates a many-to-one relationship with a single supplementary query');
}
}

View file

@ -0,0 +1,76 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Test class for PropelOnDemandCollection.
*
* @author Francois Zaninotto
* @version $Id: PropelObjectCollectionTest.php 1348 2009-12-03 21:49:00Z francois $
* @package runtime.collection
*/
class PropelOnDemandCollectionTest extends BookstoreEmptyTestBase
{
protected function setUp()
{
parent::setUp();
BookstoreDataPopulator::populate($this->con);
$this->books = PropelQuery::from('Book')->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)->find();
}
public function testSetFormatter()
{
$this->assertTrue($this->books instanceof PropelOnDemandCollection);
$this->assertEquals(4, count($this->books));
}
public function testKeys()
{
$i = 0;
foreach ($this->books as $key => $book) {
$this->assertEquals($i, $key);
$i++;
}
}
/**
* @expectedException PropelException
*/
public function testoffsetExists()
{
$this->books->offsetExists(2);
}
/**
* @expectedException PropelException
*/
public function testoffsetGet()
{
$this->books->offsetGet(2);
}
/**
* @expectedException PropelException
*/
public function testoffsetSet()
{
$this->books->offsetSet(2, 'foo');
}
/**
* @expectedException PropelException
*/
public function testoffsetUnset()
{
$this->books->offsetUnset(2);
}
}

View file

@ -0,0 +1,59 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Test class for PropelOnDemandIterator.
*
* @author Francois Zaninotto
* @version $Id: PropelObjectCollectionTest.php 1348 2009-12-03 21:49:00Z francois $
* @package runtime.collection
*/
class PropelOnDemandIteratorTest extends BookstoreEmptyTestBase
{
protected function setUp()
{
parent::setUp();
BookstoreDataPopulator::populate($this->con);
}
public function testInstancePoolingDisabled()
{
Propel::enableInstancePooling();
$books = PropelQuery::from('Book')
->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
->find($this->con);
foreach ($books as $book) {
$this->assertFalse(Propel::isInstancePoolingEnabled());
}
}
public function testInstancePoolingReenabled()
{
Propel::enableInstancePooling();
$books = PropelQuery::from('Book')
->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
->find($this->con);
foreach ($books as $book) {
}
$this->assertTrue(Propel::isInstancePoolingEnabled());
Propel::disableInstancePooling();
$books = PropelQuery::from('Book')
->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
->find($this->con);
foreach ($books as $book) {
}
$this->assertFalse(Propel::isInstancePoolingEnabled());
Propel::enableInstancePooling();
}
}

View file

@ -0,0 +1,425 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/connection/PropelPDO.php';
set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes");
Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php');
/**
* Test for PropelPDO subclass.
*
* @package runtime.connection
*/
class PropelPDOTest extends PHPUnit_Framework_TestCase
{
public function testSetAttribute()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$this->assertFalse($con->getAttribute(PropelPDO::PROPEL_ATTR_CACHE_PREPARES));
$con->setAttribute(PropelPDO::PROPEL_ATTR_CACHE_PREPARES, true);
$this->assertTrue($con->getAttribute(PropelPDO::PROPEL_ATTR_CACHE_PREPARES));
$con->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$this->assertEquals(PDO::CASE_LOWER, $con->getAttribute(PDO::ATTR_CASE));
}
public function testNestedTransactionCommit()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$driver = $con->getAttribute(PDO::ATTR_DRIVER_NAME);
$this->assertEquals(0, $con->getNestedTransactionCount(), 'nested transaction is equal to 0 before transaction');
$this->assertFalse($con->isInTransaction(), 'PropelPDO is not in transaction by default');
$con->beginTransaction();
$this->assertEquals(1, $con->getNestedTransactionCount(), 'nested transaction is incremented after main transaction begin');
$this->assertTrue($con->isInTransaction(), 'PropelPDO is in transaction after main transaction begin');
try {
$a = new Author();
$a->setFirstName('Test');
$a->setLastName('User');
$a->save($con);
$authorId = $a->getId();
$this->assertNotNull($authorId, "Expected valid new author ID");
$con->beginTransaction();
$this->assertEquals(2, $con->getNestedTransactionCount(), 'nested transaction is incremented after nested transaction begin');
$this->assertTrue($con->isInTransaction(), 'PropelPDO is in transaction after nested transaction begin');
try {
$a2 = new Author();
$a2->setFirstName('Test2');
$a2->setLastName('User2');
$a2->save($con);
$authorId2 = $a2->getId();
$this->assertNotNull($authorId2, "Expected valid new author ID");
$con->commit();
$this->assertEquals(1, $con->getNestedTransactionCount(), 'nested transaction decremented after nested transaction commit');
$this->assertTrue($con->isInTransaction(), 'PropelPDO is in transaction after main transaction commit');
} catch (Exception $e) {
$con->rollBack();
throw $e;
}
$con->commit();
$this->assertEquals(0, $con->getNestedTransactionCount(), 'nested transaction decremented after main transaction commit');
$this->assertFalse($con->isInTransaction(), 'PropelPDO is not in transaction after main transaction commit');
} catch (Exception $e) {
$con->rollBack();
}
AuthorPeer::clearInstancePool();
$at = AuthorPeer::retrieveByPK($authorId);
$this->assertNotNull($at, "Committed transaction is persisted in database");
$at2 = AuthorPeer::retrieveByPK($authorId2);
$this->assertNotNull($at2, "Committed transaction is persisted in database");
}
/**
* @link http://propel.phpdb.org/trac/ticket/699
*/
public function testNestedTransactionRollBackRethrow()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$driver = $con->getAttribute(PDO::ATTR_DRIVER_NAME);
$con->beginTransaction();
try {
$a = new Author();
$a->setFirstName('Test');
$a->setLastName('User');
$a->save($con);
$authorId = $a->getId();
$this->assertNotNull($authorId, "Expected valid new author ID");
$con->beginTransaction();
$this->assertEquals(2, $con->getNestedTransactionCount(), 'nested transaction is incremented after nested transaction begin');
$this->assertTrue($con->isInTransaction(), 'PropelPDO is in transaction after nested transaction begin');
try {
$con->exec('INVALID SQL');
$this->fail("Expected exception on invalid SQL");
} catch (PDOException $x) {
$con->rollBack();
$this->assertEquals(1, $con->getNestedTransactionCount(), 'nested transaction decremented after nested transaction rollback');
$this->assertTrue($con->isInTransaction(), 'PropelPDO is in transaction after main transaction rollback');
throw $x;
}
$con->commit();
} catch (Exception $x) {
$con->rollBack();
}
AuthorPeer::clearInstancePool();
$at = AuthorPeer::retrieveByPK($authorId);
$this->assertNull($at, "Rolled back transaction is not persisted in database");
}
/**
* @link http://propel.phpdb.org/trac/ticket/699
*/
public function testNestedTransactionRollBackSwallow()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$driver = $con->getAttribute(PDO::ATTR_DRIVER_NAME);
$con->beginTransaction();
try {
$a = new Author();
$a->setFirstName('Test');
$a->setLastName('User');
$a->save($con);
$authorId = $a->getId();
$this->assertNotNull($authorId, "Expected valid new author ID");
$con->beginTransaction();
try {
$a2 = new Author();
$a2->setFirstName('Test2');
$a2->setLastName('User2');
$a2->save($con);
$authorId2 = $a2->getId();
$this->assertNotNull($authorId2, "Expected valid new author ID");
$con->exec('INVALID SQL');
$this->fail("Expected exception on invalid SQL");
} catch (PDOException $e) {
$con->rollBack();
// NO RETHROW
}
$a3 = new Author();
$a3->setFirstName('Test2');
$a3->setLastName('User2');
$a3->save($con);
$authorId3 = $a3->getId();
$this->assertNotNull($authorId3, "Expected valid new author ID");
$con->commit();
$this->fail("Commit fails after a nested rollback");
} catch (PropelException $e) {
$this->assertTrue(true, "Commit fails after a nested rollback");
$con->rollback();
}
AuthorPeer::clearInstancePool();
$at = AuthorPeer::retrieveByPK($authorId);
$this->assertNull($at, "Rolled back transaction is not persisted in database");
$at2 = AuthorPeer::retrieveByPK($authorId2);
$this->assertNull($at2, "Rolled back transaction is not persisted in database");
$at3 = AuthorPeer::retrieveByPK($authorId3);
$this->assertNull($at3, "Rolled back nested transaction is not persisted in database");
}
public function testNestedTransactionForceRollBack()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$driver = $con->getAttribute(PDO::ATTR_DRIVER_NAME);
// main transaction
$con->beginTransaction();
$a = new Author();
$a->setFirstName('Test');
$a->setLastName('User');
$a->save($con);
$authorId = $a->getId();
// nested transaction
$con->beginTransaction();
$a2 = new Author();
$a2->setFirstName('Test2');
$a2->setLastName('User2');
$a2->save($con);
$authorId2 = $a2->getId();
// force rollback
$con->forceRollback();
$this->assertEquals(0, $con->getNestedTransactionCount(), 'nested transaction is null after nested transaction forced rollback');
$this->assertFalse($con->isInTransaction(), 'PropelPDO is not in transaction after nested transaction force rollback');
AuthorPeer::clearInstancePool();
$at = AuthorPeer::retrieveByPK($authorId);
$this->assertNull($at, "Rolled back transaction is not persisted in database");
$at2 = AuthorPeer::retrieveByPK($authorId2);
$this->assertNull($at2, "Forced Rolled back nested transaction is not persisted in database");
}
public function testLatestQuery()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$con->setLastExecutedQuery(123);
$this->assertEquals(123, $con->getLastExecutedQuery(), 'PropelPDO has getter and setter for last executed query');
}
public function testLatestQueryMoreThanTenArgs()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$c = new Criteria();
$c->add(BookPeer::ID, array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), Criteria::IN);
$books = BookPeer::doSelect($c, $con);
$expected = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.ID IN (1,1,1,1,1,1,1,1,1,1,1,1)";
$this->assertEquals($expected, $con->getLastExecutedQuery(), 'PropelPDO correctly replaces arguments in queries');
}
public function testQueryCount()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$count = $con->getQueryCount();
$con->incrementQueryCount();
$this->assertEquals($count + 1, $con->getQueryCount(), 'PropelPDO has getter and incrementer for query count');
}
public function testUseDebug()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$con->useDebug(false);
$this->assertEquals(array('PDOStatement'), $con->getAttribute(PDO::ATTR_STATEMENT_CLASS), 'Statement is PDOStatement when debug is false');
$con->useDebug(true);
$this->assertEquals(array('DebugPDOStatement', array($con)), $con->getAttribute(PDO::ATTR_STATEMENT_CLASS), 'statement is DebugPDOStament when debug is true');
}
public function testDebugLatestQuery()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$c = new Criteria();
$c->add(BookPeer::TITLE, 'Harry%s', Criteria::LIKE);
$con->useDebug(false);
$this->assertEquals('', $con->getLastExecutedQuery(), 'PropelPDO reinitializes the latest query when debug is set to false');
$books = BookPeer::doSelect($c, $con);
$this->assertEquals('', $con->getLastExecutedQuery(), 'PropelPDO does not update the last executed query when useLogging is false');
$con->useDebug(true);
$books = BookPeer::doSelect($c, $con);
$latestExecutedQuery = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.TITLE LIKE 'Harry%s'";
if (!Propel::getDB(BookPeer::DATABASE_NAME)->useQuoteIdentifier()) {
$latestExecutedQuery = str_replace('`', '', $latestExecutedQuery);
}
$this->assertEquals($latestExecutedQuery, $con->getLastExecutedQuery(), 'PropelPDO updates the last executed query when useLogging is true');
BookPeer::doDeleteAll($con);
$latestExecutedQuery = "DELETE FROM `book`";
$this->assertEquals($latestExecutedQuery, $con->getLastExecutedQuery(), 'PropelPDO updates the last executed query on delete operations');
$sql = 'DELETE FROM book WHERE 1=1';
$con->exec($sql);
$this->assertEquals($sql, $con->getLastExecutedQuery(), 'PropelPDO updates the last executed query on exec operations');
$sql = 'DELETE FROM book WHERE 2=2';
$con->query($sql);
$this->assertEquals($sql, $con->getLastExecutedQuery(), 'PropelPDO updates the last executed query on query operations');
$stmt = $con->prepare('DELETE FROM book WHERE 1=:p1');
$stmt->bindValue(':p1', '2');
$stmt->execute();
$this->assertEquals("DELETE FROM book WHERE 1='2'", $con->getLastExecutedQuery(), 'PropelPDO updates the last executed query on prapared statements');
$con->useDebug(false);
$this->assertEquals('', $con->getLastExecutedQuery(), 'PropelPDO reinitializes the latest query when debug is set to false');
$con->useDebug(true);
}
public function testDebugQueryCount()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$c = new Criteria();
$c->add(BookPeer::TITLE, 'Harry%s', Criteria::LIKE);
$con->useDebug(false);
$this->assertEquals(0, $con->getQueryCount(), 'PropelPDO does not update the query count when useLogging is false');
$books = BookPeer::doSelect($c, $con);
$this->assertEquals(0, $con->getQueryCount(), 'PropelPDO does not update the query count when useLogging is false');
$con->useDebug(true);
$books = BookPeer::doSelect($c, $con);
$this->assertEquals(1, $con->getQueryCount(), 'PropelPDO updates the query count when useLogging is true');
BookPeer::doDeleteAll($con);
$this->assertEquals(2, $con->getQueryCount(), 'PropelPDO updates the query count on delete operations');
$sql = 'DELETE FROM book WHERE 1=1';
$con->exec($sql);
$this->assertEquals(3, $con->getQueryCount(), 'PropelPDO updates the query count on exec operations');
$sql = 'DELETE FROM book WHERE 2=2';
$con->query($sql);
$this->assertEquals(4, $con->getQueryCount(), 'PropelPDO updates the query count on query operations');
$stmt = $con->prepare('DELETE FROM book WHERE 1=:p1');
$stmt->bindValue(':p1', '2');
$stmt->execute();
$this->assertEquals(5, $con->getQueryCount(), 'PropelPDO updates the query count on prapared statements');
$con->useDebug(false);
$this->assertEquals(0, $con->getQueryCount(), 'PropelPDO reinitializes the query count when debug is set to false');
$con->useDebug(true);
}
public function testDebugLog()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$config = Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT);
// save data to return to normal state after test
$logger = $con->getLogger();
$testLog = new myLogger();
$con->setLogger($testLog);
$logEverything = array('PropelPDO::exec', 'PropelPDO::query', 'PropelPDO::beginTransaction', 'PropelPDO::commit', 'PropelPDO::rollBack', 'DebugPDOStatement::execute');
Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT)->setParameter("debugpdo.logging.methods", $logEverything);
$con->useDebug(true);
// test transaction log
$con->beginTransaction();
$this->assertEquals('log: Begin transaction', $testLog->latestMessage, 'PropelPDO logs begin transation in debug mode');
$con->commit();
$this->assertEquals('log: Commit transaction', $testLog->latestMessage, 'PropelPDO logs commit transation in debug mode');
$con->beginTransaction();
$con->rollBack();
$this->assertEquals('log: Rollback transaction', $testLog->latestMessage, 'PropelPDO logs rollback transation in debug mode');
$con->beginTransaction();
$testLog->latestMessage = '';
$con->beginTransaction();
$this->assertEquals('', $testLog->latestMessage, 'PropelPDO does not log nested begin transation in debug mode');
$con->commit();
$this->assertEquals('', $testLog->latestMessage, 'PropelPDO does not log nested commit transation in debug mode');
$con->beginTransaction();
$con->rollBack();
$this->assertEquals('', $testLog->latestMessage, 'PropelPDO does not log nested rollback transation in debug mode');
$con->rollback();
// test query log
$con->beginTransaction();
$c = new Criteria();
$c->add(BookPeer::TITLE, 'Harry%s', Criteria::LIKE);
$books = BookPeer::doSelect($c, $con);
$latestExecutedQuery = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.TITLE LIKE 'Harry%s'";
$this->assertEquals('log: ' . $latestExecutedQuery, $testLog->latestMessage, 'PropelPDO logs queries and populates bound parameters in debug mode');
BookPeer::doDeleteAll($con);
$latestExecutedQuery = "DELETE FROM `book`";
$this->assertEquals('log: ' . $latestExecutedQuery, $testLog->latestMessage, 'PropelPDO logs deletion queries in debug mode');
$latestExecutedQuery = 'DELETE FROM book WHERE 1=1';
$con->exec($latestExecutedQuery);
$this->assertEquals('log: ' . $latestExecutedQuery, $testLog->latestMessage, 'PropelPDO logs exec queries in debug mode');
$con->commit();
// return to normal state after test
$con->setLogger($logger);
$config->setParameter("debugpdo.logging.methods", array('PropelPDO::exec', 'PropelPDO::query', 'DebugPDOStatement::execute'));
}
}
class myLogger
{
public $latestMessage = '';
public function __call($method, $arguments)
{
$this->latestMessage = $method . ': ' . array_shift($arguments);
}
}

View file

@ -0,0 +1,129 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Test class for PropelArrayFormatter.
*
* @author Francois Zaninotto
* @version $Id: PropelArrayFormatterTest.php 1796 2010-06-14 11:45:49Z francois $
* @package runtime.formatter
*/
class PropelArrayFormatterTest extends BookstoreEmptyTestBase
{
protected function setUp()
{
parent::setUp();
BookstoreDataPopulator::populate();
}
public function testFormatNoCriteria()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelArrayFormatter();
try {
$books = $formatter->format($stmt);
$this->fail('PropelArrayFormatter::format() throws an exception when called with no valid criteria');
} catch (PropelException $e) {
$this->assertTrue(true,'PropelArrayFormatter::format() throws an exception when called with no valid criteria');
}
}
public function testFormatManyResults()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelArrayFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$books = $formatter->format($stmt);
$this->assertTrue($books instanceof PropelCollection, 'PropelArrayFormatter::format() returns a PropelCollection');
$this->assertEquals(4, count($books), 'PropelArrayFormatter::format() returns as many rows as the results in the query');
foreach ($books as $book) {
$this->assertTrue(is_array($book), 'PropelArrayFormatter::format() returns an array of arrays');
}
}
public function testFormatOneResult()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "Quicksilver"');
$formatter = new PropelArrayFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$books = $formatter->format($stmt);
$this->assertTrue($books instanceof PropelCollection, 'PropelArrayFormatter::format() returns a PropelCollection');
$this->assertEquals(1, count($books), 'PropelArrayFormatter::format() returns as many rows as the results in the query');
$book = $books->shift();
$this->assertTrue(is_array($book), 'PropelArrayFormatter::format() returns an array of arrays');
$this->assertEquals('Quicksilver', $book['Title'], 'PropelArrayFormatter::format() returns the arrays matching the query');
$expected = array('Id', 'Title', 'ISBN', 'Price', 'PublisherId', 'AuthorId');
$this->assertEquals($expected, array_keys($book), 'PropelArrayFormatter::format() returns an associative array with column phpNames as keys');
}
public function testFormatNoResult()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"');
$formatter = new PropelArrayFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$books = $formatter->format($stmt);
$this->assertTrue($books instanceof PropelCollection, 'PropelArrayFormatter::format() returns a PropelCollection');
$this->assertEquals(0, count($books), 'PropelArrayFormatter::format() returns as many rows as the results in the query');
}
public function testFormatOneNoCriteria()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelArrayFormatter();
try {
$book = $formatter->formatOne($stmt);
$this->fail('PropelArrayFormatter::formatOne() throws an exception when called with no valid criteria');
} catch (PropelException $e) {
$this->assertTrue(true,'PropelArrayFormatter::formatOne() throws an exception when called with no valid criteria');
}
}
public function testFormatOneManyResults()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelArrayFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$book = $formatter->formatOne($stmt);
$this->assertTrue(is_array($book), 'PropelArrayFormatter::formatOne() returns an array');
$this->assertEquals(array('Id', 'Title', 'ISBN', 'Price', 'PublisherId', 'AuthorId'), array_keys($book), 'PropelArrayFormatter::formatOne() returns a single row even if the query has many results');
}
public function testFormatOneNoResult()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"');
$formatter = new PropelArrayFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$book = $formatter->formatOne($stmt);
$this->assertNull($book, 'PropelArrayFormatter::formatOne() returns null when no result');
}
}

View file

@ -0,0 +1,383 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Test class for PropelArrayFormatter when Criteria uses with().
*
* @author Francois Zaninotto
* @version $Id: PropelArrayFormatterWithTest.php 1348 2009-12-03 21:49:00Z francois $
* @package runtime.formatter
*/
class PropelArrayFormatterWithTest extends BookstoreEmptyTestBase
{
protected function assertCorrectHydration1($c, $msg)
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$book = $c->findOne($con);
$count = $con->getQueryCount();
$this->assertEquals($book['Title'], 'Don Juan', 'Main object is correctly hydrated ' . $msg);
$author = $book['Author'];
$this->assertEquals($author['LastName'], 'Byron', 'Related object is correctly hydrated ' . $msg);
$publisher = $book['Publisher'];
$this->assertEquals($publisher['Name'], 'Penguin', 'Related object is correctly hydrated ' . $msg);
}
public function testFindOneWith()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$c->orderBy('Book.Title');
$c->join('Book.Author');
$c->with('Author');
$c->join('Book.Publisher');
$c->with('Publisher');
$this->assertCorrectHydration1($c, 'without instance pool');
}
public function testFindOneWithAlias()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$c->orderBy('Book.Title');
$c->join('Book.Author a');
$c->with('a');
$c->join('Book.Publisher p');
$c->with('p');
$this->assertCorrectHydration1($c, 'with alias');
}
public function testFindOneWithMainAlias()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$c->setModelAlias('b', true);
$c->orderBy('b.Title');
$c->join('b.Author a');
$c->with('a');
$c->join('b.Publisher p');
$c->with('p');
$this->assertCorrectHydration1($c, 'with main alias');
}
public function testFindOneWithUsingInstancePool()
{
BookstoreDataPopulator::populate();
// instance pool contains all objects by default, since they were just populated
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$c->orderBy('Book.Title');
$c->join('Book.Author');
$c->with('Author');
$c->join('Book.Publisher');
$c->with('Publisher');
$this->assertCorrectHydration1($c, 'with instance pool');
}
public function testFindOneWithEmptyLeftJoin()
{
// save a book with no author
$b = new Book();
$b->setTitle('Foo');
$b->save();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$c->where('Book.Title = ?', 'Foo');
$c->leftJoin('Book.Author');
$c->with('Author');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$book = $c->findOne($con);
$count = $con->getQueryCount();
$author = $book['Author'];
$this->assertEquals(array(), $author, 'Related object is not hydrated if empty');
}
public function testFindOneWithRelationName()
{
BookstoreDataPopulator::populate();
BookstoreEmployeePeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'BookstoreEmployee');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$c->join('BookstoreEmployee.Supervisor s');
$c->with('s');
$c->where('s.Name = ?', 'John');
$emp = $c->findOne();
$this->assertEquals($emp['Name'], 'Pieter', 'Main object is correctly hydrated');
$sup = $emp['Supervisor'];
$this->assertEquals($sup['Name'], 'John', 'Related object is correctly hydrated');
}
/**
* @see http://www.propelorm.org/ticket/959
*/
public function testFindOneWithSameRelatedObject()
{
BookPeer::doDeleteAll();
AuthorPeer::doDeleteAll();
$auth = new Author();
$auth->setFirstName('John');
$auth->save();
$book1 = new Book();
$book1->setTitle('Hello');
$book1->setAuthor($auth);
$book1->save();
$book2 = new Book();
$book2->setTitle('World');
$book2->setAuthor($auth);
$book2->save();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$c->join('Book.Author');
$c->with('Author');
$books = $c->find();
$this->assertEquals(2, count($books));
$firstBook = $books[0];
$this->assertTrue(isset($firstBook['Author']));
$secondBook = $books[1];
$this->assertTrue(isset($secondBook['Author']));
}
public function testFindOneWithDuplicateRelation()
{
EssayPeer::doDeleteAll();
$auth1 = new Author();
$auth1->setFirstName('John');
$auth1->save();
$auth2 = new Author();
$auth2->setFirstName('Jack');
$auth2->save();
$essay = new Essay();
$essay->setTitle('Foo');
$essay->setFirstAuthor($auth1->getId());
$essay->setSecondAuthor($auth2->getId());
$essay->save();
AuthorPeer::clearInstancePool();
EssayPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Essay');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$c->join('Essay.AuthorRelatedByFirstAuthor');
$c->with('AuthorRelatedByFirstAuthor');
$c->where('Essay.Title = ?', 'Foo');
$essay = $c->findOne();
$this->assertEquals($essay['Title'], 'Foo', 'Main object is correctly hydrated');
$firstAuthor = $essay['AuthorRelatedByFirstAuthor'];
$this->assertEquals($firstAuthor['FirstName'], 'John', 'Related object is correctly hydrated');
$this->assertFalse(array_key_exists('AuthorRelatedBySecondAuthor', $essay), 'Only related object specified in with() is hydrated');
}
public function testFindOneWithDistantClass()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Review');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$c->where('Review.Recommended = ?', true);
$c->join('Review.Book');
$c->with('Book');
$c->join('Book.Author');
$c->with('Author');
$review = $c->findOne();
$this->assertEquals($review['ReviewedBy'], 'Washington Post', 'Main object is correctly hydrated');
$book = $review['Book'];
$this->assertEquals('Harry Potter and the Order of the Phoenix', $book['Title'], 'Related object is correctly hydrated');
$author = $book['Author'];
$this->assertEquals('J.K.', $author['FirstName'], 'Related object is correctly hydrated');
}
/**
* @expectedException PropelException
*/
public function testFindOneWithOneToManyAndLimit()
{
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$c->add(BookPeer::ISBN, '043935806X');
$c->leftJoin('Book.Review');
$c->with('Review');
$c->limit(5);
$books = $c->find();
}
public function testFindOneWithOneToMany()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$c->add(BookPeer::ISBN, '043935806X');
$c->leftJoin('Book.Review');
$c->with('Review');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$books = $c->find($con);
$this->assertEquals(1, count($books), 'with() does not duplicate the main object');
$book = $books[0];
$this->assertEquals($book['Title'], 'Harry Potter and the Order of the Phoenix', 'Main object is correctly hydrated');
$this->assertEquals(array('Id', 'Title', 'ISBN', 'Price', 'PublisherId', 'AuthorId', 'Reviews'), array_keys($book), 'with() adds a plural index for the one to many relationship');
$reviews = $book['Reviews'];
$this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated');
$review1 = $reviews[0];
$this->assertEquals(array('Id', 'ReviewedBy', 'ReviewDate', 'Recommended', 'Status', 'BookId'), array_keys($review1), 'with() Related objects are correctly hydrated');
}
public function testFindOneWithOneToManyCustomOrder()
{
$author1 = new Author();
$author1->setFirstName('AA');
$author2 = new Author();
$author2->setFirstName('BB');
$book1 = new Book();
$book1->setTitle('Aaa');
$book1->setAuthor($author1);
$book1->save();
$book2 = new Book();
$book2->setTitle('Bbb');
$book2->setAuthor($author2);
$book2->save();
$book3 = new Book();
$book3->setTitle('Ccc');
$book3->setAuthor($author1);
$book3->save();
$authors = AuthorQuery::create()
->setFormatter(ModelCriteria::FORMAT_ARRAY)
->leftJoin('Author.Book')
->orderBy('Book.Title')
->with('Book')
->find();
$this->assertEquals(2, count($authors), 'with() used on a many-to-many doesn\'t change the main object count');
}
public function testFindOneWithOneToManyThenManyToOne()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Author');
$c->add(AuthorPeer::LAST_NAME, 'Rowling');
$c->leftJoinWith('Author.Book');
$c->leftJoinWith('Book.Review');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$authors = $c->find($con);
$this->assertEquals(1, count($authors), 'with() does not duplicate the main object');
$rowling = $authors[0];
$this->assertEquals($rowling['FirstName'], 'J.K.', 'Main object is correctly hydrated');
$books = $rowling['Books'];
$this->assertEquals(1, count($books), 'Related objects are correctly hydrated');
$book = $books[0];
$this->assertEquals($book['Title'], 'Harry Potter and the Order of the Phoenix', 'Related object is correctly hydrated');
$reviews = $book['Reviews'];
$this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated');
}
public function testFindOneWithOneToManyThenManyToOneUsingAlias()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Author');
$c->add(AuthorPeer::LAST_NAME, 'Rowling');
$c->leftJoinWith('Author.Book b');
$c->leftJoinWith('b.Review r');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$authors = $c->find($con);
$this->assertEquals(1, count($authors), 'with() does not duplicate the main object');
$rowling = $authors[0];
$this->assertEquals($rowling['FirstName'], 'J.K.', 'Main object is correctly hydrated');
$books = $rowling['Books'];
$this->assertEquals(1, count($books), 'Related objects are correctly hydrated');
$book = $books[0];
$this->assertEquals($book['Title'], 'Harry Potter and the Order of the Phoenix', 'Related object is correctly hydrated');
$reviews = $book['Reviews'];
$this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated');
}
public function testFindOneWithColumn()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$c->filterByTitle('The Tin Drum');
$c->join('Book.Author');
$c->withColumn('Author.FirstName', 'AuthorName');
$c->withColumn('Author.LastName', 'AuthorName2');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$book = $c->findOne($con);
$this->assertEquals(array('Id', 'Title', 'ISBN', 'Price', 'PublisherId', 'AuthorId', 'AuthorName', 'AuthorName2'), array_keys($book), 'withColumn() do not change the resulting model class');
$this->assertEquals('The Tin Drum', $book['Title']);
$this->assertEquals('Gunter', $book['AuthorName'], 'PropelArrayFormatter adds withColumns as columns');
$this->assertEquals('Grass', $book['AuthorName2'], 'PropelArrayFormatter correctly hydrates all as columns');
}
public function testFindOneWithClassAndColumn()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$c->filterByTitle('The Tin Drum');
$c->join('Book.Author');
$c->withColumn('Author.FirstName', 'AuthorName');
$c->withColumn('Author.LastName', 'AuthorName2');
$c->with('Author');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$book = $c->findOne($con);
$this->assertEquals(array('Id', 'Title', 'ISBN', 'Price', 'PublisherId', 'AuthorId', 'Author', 'AuthorName', 'AuthorName2'), array_keys($book), 'withColumn() do not change the resulting model class');
$this->assertEquals('The Tin Drum', $book['Title']);
$this->assertEquals('Gunter', $book['Author']['FirstName'], 'PropelArrayFormatter correctly hydrates withclass and columns');
$this->assertEquals('Gunter', $book['AuthorName'], 'PropelArrayFormatter adds withColumns as columns');
$this->assertEquals('Grass', $book['AuthorName2'], 'PropelArrayFormatter correctly hydrates all as columns');
}
public function testFindPkWithOneToMany()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$book = BookQuery::create()
->findOneByTitle('Harry Potter and the Order of the Phoenix', $con);
$pk = $book->getPrimaryKey();
BookPeer::clearInstancePool();
$book = BookQuery::create()
->setFormatter(ModelCriteria::FORMAT_ARRAY)
->joinWith('Review')
->findPk($pk, $con);
$reviews = $book['Reviews'];
$this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated');
}
}

View file

@ -0,0 +1,55 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Test class for PropelObjectFormatter.
*
* @author Francois Zaninotto
* @version $Id: PropelObjectFormatterTest.php 1374 2009-12-26 23:21:37Z francois $
* @package runtime.formatter
*/
class PropelObjectFormatterInheritanceTest extends BookstoreEmptyTestBase
{
protected function setUp()
{
parent::setUp();
$b1 = new BookstoreEmployee();
$b1->setName('b1');
$b1->save();
$b2 = new BookstoreManager();
$b2->setName('b2');
$b2->save();
$b3 = new BookstoreCashier();
$b3->setName('b3');
$b3->save();
}
public function testFormat()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
BookstoreEmployeePeer::clearInstancePool();
$stmt = $con->query('SELECT * FROM bookstore_employee');
$formatter = new PropelObjectFormatter();
$formatter->init(new ModelCriteria('bookstore', 'BookstoreEmployee'));
$emps = $formatter->format($stmt);
$expectedClass = array(
'b1' =>'BookstoreEmployee',
'b2' =>'BookstoreManager',
'b3' =>'BookstoreCashier'
);
foreach ($emps as $emp) {
$this->assertEquals($expectedClass[$emp->getName()], get_class($emp), 'format() creates objects of the correct class when using inheritance');
}
}
}

View file

@ -0,0 +1,125 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Test class for PropelObjectFormatter.
*
* @author Francois Zaninotto
* @version $Id: PropelObjectFormatterTest.php 1733 2010-05-04 14:25:27Z francois $
* @package runtime.formatter
*/
class PropelObjectFormatterTest extends BookstoreEmptyTestBase
{
protected function setUp()
{
parent::setUp();
BookstoreDataPopulator::populate();
}
public function testFormatNoCriteria()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelObjectFormatter();
try {
$books = $formatter->format($stmt);
$this->fail('PropelObjectFormatter::format() trows an exception when called with no valid criteria');
} catch (PropelException $e) {
$this->assertTrue(true,'PropelObjectFormatter::format() trows an exception when called with no valid criteria');
}
}
public function testFormatManyResults()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelObjectFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$books = $formatter->format($stmt);
$this->assertTrue($books instanceof PropelCollection, 'PropelObjectFormatter::format() returns a PropelCollection');
$this->assertEquals(4, count($books), 'PropelObjectFormatter::format() returns as many rows as the results in the query');
foreach ($books as $book) {
$this->assertTrue($book instanceof Book, 'PropelObjectFormatter::format() returns an array of Model objects');
}
}
public function testFormatOneResult()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "Quicksilver"');
$formatter = new PropelObjectFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$books = $formatter->format($stmt);
$this->assertTrue($books instanceof PropelCollection, 'PropelObjectFormatter::format() returns a PropelCollection');
$this->assertEquals(1, count($books), 'PropelObjectFormatter::format() returns as many rows as the results in the query');
$book = $books->shift();
$this->assertTrue($book instanceof Book, 'PropelObjectFormatter::format() returns an array of Model objects');
$this->assertEquals('Quicksilver', $book->getTitle(), 'PropelObjectFormatter::format() returns the model objects matching the query');
}
public function testFormatNoResult()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"');
$formatter = new PropelObjectFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$books = $formatter->format($stmt);
$this->assertTrue($books instanceof PropelCollection, 'PropelObjectFormatter::format() returns a PropelCollection');
$this->assertEquals(0, count($books), 'PropelObjectFormatter::format() returns as many rows as the results in the query');
}
public function testFormatOneNoCriteria()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelObjectFormatter();
try {
$book = $formatter->formatOne($stmt);
$this->fail('PropelObjectFormatter::formatOne() throws an exception when called with no valid criteria');
} catch (PropelException $e) {
$this->assertTrue(true,'PropelObjectFormatter::formatOne() throws an exception when called with no valid criteria');
}
}
public function testFormatOneManyResults()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelObjectFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$book = $formatter->formatOne($stmt);
$this->assertTrue($book instanceof Book, 'PropelObjectFormatter::formatOne() returns a model object');
}
public function testFormatOneNoResult()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"');
$formatter = new PropelObjectFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$book = $formatter->formatOne($stmt);
$this->assertNull($book, 'PropelObjectFormatter::formatOne() returns null when no result');
}
}

View file

@ -0,0 +1,406 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Test class for PropelObjectFormatter when Criteria uses with().
*
* @author Francois Zaninotto
* @version $Id: PropelObjectFormatterWithTest.php 1348 2009-12-03 21:49:00Z francois $
* @package runtime.formatter
*/
class PropelObjectFormatterWithTest extends BookstoreEmptyTestBase
{
protected function assertCorrectHydration1($c, $msg)
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$book = $c->findOne($con);
$count = $con->getQueryCount();
$this->assertEquals($book->getTitle(), 'Don Juan', 'Main object is correctly hydrated ' . $msg);
$author = $book->getAuthor();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ' . $msg);
$this->assertEquals($author->getLastName(), 'Byron', 'Related object is correctly hydrated ' . $msg);
$publisher = $book->getPublisher();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ' . $msg);
$this->assertEquals($publisher->getName(), 'Penguin', 'Related object is correctly hydrated ' . $msg);
}
public function testFindOneWith()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->orderBy('Book.Title');
$c->join('Book.Author');
$c->with('Author');
$c->join('Book.Publisher');
$c->with('Publisher');
$this->assertCorrectHydration1($c, 'without instance pool');
}
public function testFindOneWithAlias()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->orderBy('Book.Title');
$c->join('Book.Author a');
$c->with('a');
$c->join('Book.Publisher p');
$c->with('p');
$this->assertCorrectHydration1($c, 'with alias');
}
public function testFindOneWithMainAlias()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->setModelAlias('b', true);
$c->orderBy('b.Title');
$c->join('b.Author a');
$c->with('a');
$c->join('b.Publisher p');
$c->with('p');
$this->assertCorrectHydration1($c, 'with main alias');
}
public function testFindOneWithUsingInstancePool()
{
BookstoreDataPopulator::populate();
// instance pool contains all objects by default, since they were just populated
$c = new ModelCriteria('bookstore', 'Book');
$c->orderBy('Book.Title');
$c->join('Book.Author');
$c->with('Author');
$c->join('Book.Publisher');
$c->with('Publisher');
$this->assertCorrectHydration1($c, 'with instance pool');
}
public function testFindOneWithoutUsingInstancePool()
{
BookstoreDataPopulator::populate();
Propel::disableInstancePooling();
$c = new ModelCriteria('bookstore', 'Book');
$c->orderBy('Book.Title');
$c->join('Book.Author');
$c->with('Author');
$c->join('Book.Publisher');
$c->with('Publisher');
$this->assertCorrectHydration1($c, 'without instance pool');
Propel::enableInstancePooling();
}
public function testFindOneWithEmptyLeftJoin()
{
// save a book with no author
$b = new Book();
$b->setTitle('Foo');
$b->save();
$c = new ModelCriteria('bookstore', 'Book');
$c->where('Book.Title = ?', 'Foo');
$c->leftJoin('Book.Author');
$c->with('Author');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$book = $c->findOne($con);
$count = $con->getQueryCount();
$author = $book->getAuthor();
$this->assertNull($author, 'Related object is not hydrated if empty');
}
public function testFindOneWithRelationName()
{
BookstoreDataPopulator::populate();
BookstoreEmployeePeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'BookstoreEmployee');
$c->join('BookstoreEmployee.Supervisor s');
$c->with('s');
$c->where('s.Name = ?', 'John');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$emp = $c->findOne($con);
$count = $con->getQueryCount();
$this->assertEquals($emp->getName(), 'Pieter', 'Main object is correctly hydrated');
$sup = $emp->getSupervisor();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query');
$this->assertEquals($sup->getName(), 'John', 'Related object is correctly hydrated');
}
public function testFindOneWithDuplicateRelation()
{
EssayPeer::doDeleteAll();
$auth1 = new Author();
$auth1->setFirstName('John');
$auth1->save();
$auth2 = new Author();
$auth2->setFirstName('Jack');
$auth2->save();
$essay = new Essay();
$essay->setTitle('Foo');
$essay->setFirstAuthor($auth1->getId());
$essay->setSecondAuthor($auth2->getId());
$essay->save();
AuthorPeer::clearInstancePool();
EssayPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Essay');
$c->join('Essay.AuthorRelatedByFirstAuthor');
$c->with('AuthorRelatedByFirstAuthor');
$c->where('Essay.Title = ?', 'Foo');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$essay = $c->findOne($con);
$count = $con->getQueryCount();
$this->assertEquals($essay->getTitle(), 'Foo', 'Main object is correctly hydrated');
$firstAuthor = $essay->getAuthorRelatedByFirstAuthor();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query');
$this->assertEquals($firstAuthor->getFirstName(), 'John', 'Related object is correctly hydrated');
$secondAuthor = $essay->getAuthorRelatedBySecondAuthor();
$this->assertEquals($count + 1, $con->getQueryCount(), 'with() does not hydrate objects not in with');
}
public function testFindOneWithDistantClass()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
Propel::enableInstancePooling();
$c = new ModelCriteria('bookstore', 'Review');
$c->where('Review.Recommended = ?', true);
$c->join('Review.Book');
$c->with('Book');
$c->join('Book.Author');
$c->with('Author');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$review = $c->findOne($con);
$count = $con->getQueryCount();
$this->assertEquals($review->getReviewedBy(), 'Washington Post', 'Main object is correctly hydrated');
$book = $review->getBook();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query');
$this->assertEquals('Harry Potter and the Order of the Phoenix', $book->getTitle(), 'Related object is correctly hydrated');
$author = $book->getAuthor();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query');
$this->assertEquals('J.K.', $author->getFirstName(), 'Related object is correctly hydrated');
}
/**
* @expectedException PropelException
*/
public function testFindOneWithOneToManyAndLimit()
{
$c = new ModelCriteria('bookstore', 'Book');
$c->add(BookPeer::ISBN, '043935806X');
$c->leftJoin('Book.Review');
$c->with('Review');
$c->limit(5);
$books = $c->find();
}
public function testFindOneWithOneToMany()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->add(BookPeer::ISBN, '043935806X');
$c->leftJoin('Book.Review');
$c->with('Review');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$books = $c->find($con);
$this->assertEquals(1, count($books), 'with() does not duplicate the main object');
$book = $books[0];
$count = $con->getQueryCount();
$this->assertEquals($book->getTitle(), 'Harry Potter and the Order of the Phoenix', 'Main object is correctly hydrated');
$reviews = $book->getReviews();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ');
$this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated');
try {
$book->save();
} catch (Exception $e) {
$this->fail('with() does not force objects to be new');
}
}
public function testFindOneWithOneToManyCustomOrder()
{
$author1 = new Author();
$author1->setFirstName('AA');
$author2 = new Author();
$author2->setFirstName('BB');
$book1 = new Book();
$book1->setTitle('Aaa');
$book1->setAuthor($author1);
$book1->save();
$book2 = new Book();
$book2->setTitle('Bbb');
$book2->setAuthor($author2);
$book2->save();
$book3 = new Book();
$book3->setTitle('Ccc');
$book3->setAuthor($author1);
$book3->save();
$authors = AuthorQuery::create()
->leftJoin('Author.Book')
->orderBy('Book.Title')
->with('Book')
->find();
$this->assertEquals(2, count($authors), 'with() used on a many-to-many doesn\'t change the main object count');
}
public function testFindOneWithOneToManyThenManyToOne()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Author');
$c->add(AuthorPeer::LAST_NAME, 'Rowling');
$c->leftJoinWith('Author.Book');
$c->leftJoinWith('Book.Review');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$authors = $c->find($con);
$this->assertEquals(1, count($authors), 'with() does not duplicate the main object');
$rowling = $authors[0];
$count = $con->getQueryCount();
$this->assertEquals($rowling->getFirstName(), 'J.K.', 'Main object is correctly hydrated');
$books = $rowling->getBooks();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ');
$this->assertEquals(1, count($books), 'Related objects are correctly hydrated');
$book = $books[0];
$this->assertEquals($book->getTitle(), 'Harry Potter and the Order of the Phoenix', 'Related object is correctly hydrated');
$reviews = $book->getReviews();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ');
$this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated');
}
public function testFindOneWithOneToManyThenManyToOneUsingJoinRelated()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$con = Propel::getConnection(AuthorPeer::DATABASE_NAME);
$authors = AuthorQuery::create()
->filterByLastName('Rowling')
->joinBook('book')
->with('book')
->useQuery('book')
->joinReview('review')
->with('review')
->endUse()
->find($con);
$this->assertEquals(1, count($authors), 'with() does not duplicate the main object');
$rowling = $authors[0];
$count = $con->getQueryCount();
$this->assertEquals($rowling->getFirstName(), 'J.K.', 'Main object is correctly hydrated');
$books = $rowling->getBooks();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ');
$this->assertEquals(1, count($books), 'Related objects are correctly hydrated');
$book = $books[0];
$this->assertEquals($book->getTitle(), 'Harry Potter and the Order of the Phoenix', 'Related object is correctly hydrated');
$reviews = $book->getReviews();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ');
$this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated');
}
public function testFindOneWithOneToManyThenManyToOneUsingAlias()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Author');
$c->add(AuthorPeer::LAST_NAME, 'Rowling');
$c->leftJoinWith('Author.Book b');
$c->leftJoinWith('b.Review r');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$authors = $c->find($con);
$this->assertEquals(1, count($authors), 'with() does not duplicate the main object');
$rowling = $authors[0];
$count = $con->getQueryCount();
$this->assertEquals($rowling->getFirstName(), 'J.K.', 'Main object is correctly hydrated');
$books = $rowling->getBooks();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ');
$this->assertEquals(1, count($books), 'Related objects are correctly hydrated');
$book = $books[0];
$this->assertEquals($book->getTitle(), 'Harry Potter and the Order of the Phoenix', 'Related object is correctly hydrated');
$reviews = $book->getReviews();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ');
$this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated');
}
public function testFindOneWithColumn()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->filterByTitle('The Tin Drum');
$c->join('Book.Author');
$c->withColumn('Author.FirstName', 'AuthorName');
$c->withColumn('Author.LastName', 'AuthorName2');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$book = $c->findOne($con);
$this->assertTrue($book instanceof Book, 'withColumn() do not change the resulting model class');
$this->assertEquals('The Tin Drum', $book->getTitle());
$this->assertEquals('Gunter', $book->getVirtualColumn('AuthorName'), 'PropelObjectFormatter adds withColumns as virtual columns');
$this->assertEquals('Grass', $book->getVirtualColumn('AuthorName2'), 'PropelObjectFormatter correctly hydrates all virtual columns');
$this->assertEquals('Gunter', $book->getAuthorName(), 'PropelObjectFormatter adds withColumns as virtual columns');
}
public function testFindOneWithClassAndColumn()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->filterByTitle('The Tin Drum');
$c->join('Book.Author');
$c->withColumn('Author.FirstName', 'AuthorName');
$c->withColumn('Author.LastName', 'AuthorName2');
$c->with('Author');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$book = $c->findOne($con);
$this->assertTrue($book instanceof Book, 'withColumn() do not change the resulting model class');
$this->assertEquals('The Tin Drum', $book->getTitle());
$this->assertTrue($book->getAuthor() instanceof Author, 'PropelObjectFormatter correctly hydrates with class');
$this->assertEquals('Gunter', $book->getAuthor()->getFirstName(), 'PropelObjectFormatter correctly hydrates with class');
$this->assertEquals('Gunter', $book->getVirtualColumn('AuthorName'), 'PropelObjectFormatter adds withColumns as virtual columns');
$this->assertEquals('Grass', $book->getVirtualColumn('AuthorName2'), 'PropelObjectFormatter correctly hydrates all virtual columns');
}
public function testFindPkWithOneToMany()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$book = BookQuery::create()
->findOneByTitle('Harry Potter and the Order of the Phoenix', $con);
$pk = $book->getPrimaryKey();
BookPeer::clearInstancePool();
$book = BookQuery::create()
->joinWith('Review')
->findPk($pk, $con);
$count = $con->getQueryCount();
$reviews = $book->getReviews();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ');
$this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated');
}
}

View file

@ -0,0 +1,151 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Test class for PropelOnDemandFormatter.
*
* @author Francois Zaninotto
* @version $Id: PropelOnDemandFormatterTest.php 1374 2009-12-26 23:21:37Z francois $
* @package runtime.formatter
*/
class PropelOnDemandFormatterTest extends BookstoreEmptyTestBase
{
public function testFormatNoCriteria()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelOnDemandFormatter();
try {
$books = $formatter->format($stmt);
$this->fail('PropelOnDemandFormatter::format() trows an exception when called with no valid criteria');
} catch (PropelException $e) {
$this->assertTrue(true,'PropelOnDemandFormatter::format() trows an exception when called with no valid criteria');
}
}
public function testFormatManyResults()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
BookstoreDataPopulator::populate($con);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelOnDemandFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$books = $formatter->format($stmt);
$this->assertTrue($books instanceof PropelOnDemandCollection, 'PropelOnDemandFormatter::format() returns a PropelOnDemandCollection');
$this->assertEquals(4, count($books), 'PropelOnDemandFormatter::format() returns a collection that counts as many rows as the results in the query');
foreach ($books as $book) {
$this->assertTrue($book instanceof Book, 'PropelOnDemandFormatter::format() returns an traversable collection of Model objects');
}
}
/**
* @expectedException PropelException
*/
public function testFormatManyResultsIteratedTwice()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
BookstoreDataPopulator::populate($con);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelOnDemandFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$books = $formatter->format($stmt);
foreach ($books as $book) {
// do nothing
}
foreach ($books as $book) {
// this should throw a PropelException since we're iterating a second time over a stream
}
}
public function testFormatALotOfResults()
{
$nbBooks = 50;
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
Propel::disableInstancePooling();
$book = new Book();
for ($i=0; $i < $nbBooks; $i++) {
$book->clear();
$book->setTitle('BookTest' . $i);
$book->save($con);
}
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelOnDemandFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$books = $formatter->format($stmt);
$this->assertTrue($books instanceof PropelOnDemandCollection, 'PropelOnDemandFormatter::format() returns a PropelOnDemandCollection');
$this->assertEquals($nbBooks, count($books), 'PropelOnDemandFormatter::format() returns a collection that counts as many rows as the results in the query');
$i = 0;
foreach ($books as $book) {
$this->assertTrue($book instanceof Book, 'PropelOnDemandFormatter::format() returns a collection of Model objects');
$this->assertEquals('BookTest' . $i, $book->getTitle(), 'PropelOnDemandFormatter::format() returns the model objects matching the query');
$i++;
}
Propel::enableInstancePooling();
}
public function testFormatOneResult()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
BookstoreDataPopulator::populate($con);
$stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "Quicksilver"');
$formatter = new PropelOnDemandFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$books = $formatter->format($stmt);
$this->assertTrue($books instanceof PropelOnDemandCollection, 'PropelOnDemandFormatter::format() returns a PropelOnDemandCollection');
$this->assertEquals(1, count($books), 'PropelOnDemandFormatter::format() returns a collection that counts as many rows as the results in the query');
foreach ($books as $book) {
$this->assertTrue($book instanceof Book, 'PropelOnDemandFormatter::format() returns a collection of Model objects');
$this->assertEquals('Quicksilver', $book->getTitle(), 'PropelOnDemandFormatter::format() returns the model objects matching the query');
}
}
public function testFormatNoResult()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"');
$formatter = new PropelOnDemandFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$books = $formatter->format($stmt);
$this->assertTrue($books instanceof PropelOnDemandCollection, 'PropelOnDemandFormatter::format() returns a PropelCollection');
$this->assertEquals(0, count($books), 'PropelOnDemandFormatter::format() returns an empty collection when no record match the query');
foreach ($books as $book) {
$this->fail('PropelOnDemandFormatter returns an empty iterator when no record match the query');
}
}
public function testFormatOneManyResults()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
BookstoreDataPopulator::populate($con);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelOnDemandFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$book = $formatter->formatOne($stmt);
$this->assertTrue($book instanceof Book, 'PropelOnDemandFormatter::formatOne() returns a model object');
}
}

View file

@ -0,0 +1,277 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Test class for PropelOnDemandFormatter when Criteria uses with().
*
* @author Francois Zaninotto
* @version $Id: PropelOnDemandFormatterWithTest.php 1348 2009-12-03 21:49:00Z francois $
* @package runtime.formatter
*/
class PropelOnDemandFormatterWithTest extends BookstoreEmptyTestBase
{
protected function assertCorrectHydration1($c, $msg)
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$c->limit(1);
$books = $c->find($con);
foreach ($books as $book) {
break;
}
$count = $con->getQueryCount();
$this->assertEquals($book->getTitle(), 'Don Juan', 'Main object is correctly hydrated ' . $msg);
$author = $book->getAuthor();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ' . $msg);
$this->assertEquals($author->getLastName(), 'Byron', 'Related object is correctly hydrated ' . $msg);
$publisher = $book->getPublisher();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query ' . $msg);
$this->assertEquals($publisher->getName(), 'Penguin', 'Related object is correctly hydrated ' . $msg);
}
public function testFindOneWith()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND);
$c->orderBy('Book.Title');
$c->join('Book.Author');
$c->with('Author');
$c->join('Book.Publisher');
$c->with('Publisher');
$this->assertCorrectHydration1($c, 'without instance pool');
}
public function testFindOneWithAlias()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND);
$c->orderBy('Book.Title');
$c->join('Book.Author a');
$c->with('a');
$c->join('Book.Publisher p');
$c->with('p');
$this->assertCorrectHydration1($c, 'with alias');
}
public function testFindOneWithMainAlias()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND);
$c->setModelAlias('b', true);
$c->orderBy('b.Title');
$c->join('b.Author a');
$c->with('a');
$c->join('b.Publisher p');
$c->with('p');
$this->assertCorrectHydration1($c, 'with main alias');
}
public function testFindOneWithUsingInstancePool()
{
BookstoreDataPopulator::populate();
// instance pool contains all objects by default, since they were just populated
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND);
$c->orderBy('Book.Title');
$c->join('Book.Author');
$c->with('Author');
$c->join('Book.Publisher');
$c->with('Publisher');
$this->assertCorrectHydration1($c, 'with instance pool');
}
public function testFindOneWithEmptyLeftJoin()
{
// save a book with no author
$b = new Book();
$b->setTitle('Foo');
$b->save();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND);
$c->where('Book.Title = ?', 'Foo');
$c->leftJoin('Book.Author');
$c->with('Author');
$c->limit(1);
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$books = $c->find($con);
foreach ($books as $book) {
break;
}
$count = $con->getQueryCount();
$author = $book->getAuthor();
$this->assertNull($author, 'Related object is not hydrated if empty');
}
public function testFindOneWithRelationName()
{
BookstoreDataPopulator::populate();
BookstoreEmployeePeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'BookstoreEmployee');
$c->join('BookstoreEmployee.Supervisor s');
$c->with('s');
$c->where('s.Name = ?', 'John');
$c->limit(1);
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$emps = $c->find($con);
foreach ($emps as $emp) {
break;
}
$count = $con->getQueryCount();
$this->assertEquals($emp->getName(), 'Pieter', 'Main object is correctly hydrated');
$sup = $emp->getSupervisor();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query');
$this->assertEquals($sup->getName(), 'John', 'Related object is correctly hydrated');
}
public function testFindOneWithDuplicateRelation()
{
EssayPeer::doDeleteAll();
$auth1 = new Author();
$auth1->setFirstName('John');
$auth1->save();
$auth2 = new Author();
$auth2->setFirstName('Jack');
$auth2->save();
$essay = new Essay();
$essay->setTitle('Foo');
$essay->setFirstAuthor($auth1->getId());
$essay->setSecondAuthor($auth2->getId());
$essay->save();
AuthorPeer::clearInstancePool();
EssayPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Essay');
$c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND);
$c->join('Essay.AuthorRelatedByFirstAuthor');
$c->with('AuthorRelatedByFirstAuthor');
$c->where('Essay.Title = ?', 'Foo');
$c->limit(1);
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$essays = $c->find($con);
foreach ($essays as $essay) {
break;
}
$count = $con->getQueryCount();
$this->assertEquals($essay->getTitle(), 'Foo', 'Main object is correctly hydrated');
$firstAuthor = $essay->getAuthorRelatedByFirstAuthor();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query');
$this->assertEquals($firstAuthor->getFirstName(), 'John', 'Related object is correctly hydrated');
$secondAuthor = $essay->getAuthorRelatedBySecondAuthor();
$this->assertEquals($count + 1, $con->getQueryCount(), 'with() does not hydrate objects not in with');
}
public function testFindOneWithDistantClass()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Review');
$c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND);
$c->where('Review.Recommended = ?', true);
$c->join('Review.Book');
$c->with('Book');
$c->join('Book.Author');
$c->with('Author');
$c->limit(1);
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$reviews = $c->find($con);
foreach ($reviews as $review) {
break;
}
$count = $con->getQueryCount();
$this->assertEquals($review->getReviewedBy(), 'Washington Post', 'Main object is correctly hydrated');
$book = $review->getBook();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query');
$this->assertEquals('Harry Potter and the Order of the Phoenix', $book->getTitle(), 'Related object is correctly hydrated');
$author = $book->getAuthor();
$this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query');
$this->assertEquals('J.K.', $author->getFirstName(), 'Related object is correctly hydrated');
}
/**
* @expectedException PropelException
*/
public function testFindOneWithOneToMany()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND);
$c->add(BookPeer::ISBN, '043935806X');
$c->leftJoin('Book.Review');
$c->with('Review');
$books = $c->find();
}
public function testFindOneWithColumn()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND);
$c->filterByTitle('The Tin Drum');
$c->join('Book.Author');
$c->withColumn('Author.FirstName', 'AuthorName');
$c->withColumn('Author.LastName', 'AuthorName2');
$c->limit(1);
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$books = $c->find($con);
foreach ($books as $book) {
break;
}
$this->assertTrue($book instanceof Book, 'withColumn() do not change the resulting model class');
$this->assertEquals('The Tin Drum', $book->getTitle());
$this->assertEquals('Gunter', $book->getVirtualColumn('AuthorName'), 'PropelObjectFormatter adds withColumns as virtual columns');
$this->assertEquals('Grass', $book->getVirtualColumn('AuthorName2'), 'PropelObjectFormatter correctly hydrates all virtual columns');
$this->assertEquals('Gunter', $book->getAuthorName(), 'PropelObjectFormatter adds withColumns as virtual columns');
}
public function testFindOneWithClassAndColumn()
{
BookstoreDataPopulator::populate();
BookPeer::clearInstancePool();
AuthorPeer::clearInstancePool();
ReviewPeer::clearInstancePool();
$c = new ModelCriteria('bookstore', 'Book');
$c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND);
$c->filterByTitle('The Tin Drum');
$c->join('Book.Author');
$c->withColumn('Author.FirstName', 'AuthorName');
$c->withColumn('Author.LastName', 'AuthorName2');
$c->with('Author');
$c->limit(1);
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$books = $c->find($con);
foreach ($books as $book) {
break;
}
$this->assertTrue($book instanceof Book, 'withColumn() do not change the resulting model class');
$this->assertEquals('The Tin Drum', $book->getTitle());
$this->assertTrue($book->getAuthor() instanceof Author, 'PropelObjectFormatter correctly hydrates with class');
$this->assertEquals('Gunter', $book->getAuthor()->getFirstName(), 'PropelObjectFormatter correctly hydrates with class');
$this->assertEquals('Gunter', $book->getVirtualColumn('AuthorName'), 'PropelObjectFormatter adds withColumns as virtual columns');
$this->assertEquals('Grass', $book->getVirtualColumn('AuthorName2'), 'PropelObjectFormatter correctly hydrates all virtual columns');
}
}

View file

@ -0,0 +1,124 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Test class for PropelStatementFormatter.
*
* @author Francois Zaninotto
* @version $Id: PropelStatementFormatterTest.php 1733 2010-05-04 14:25:27Z francois $
* @package runtime.formatter
*/
class PropelStatementFormatterTest extends BookstoreEmptyTestBase
{
protected function setUp()
{
parent::setUp();
BookstoreDataPopulator::populate();
}
public function testFormatNoCriteria()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelStatementFormatter();
try {
$books = $formatter->format($stmt);
$this->assertTrue(true, 'PropelStatementFormatter::format() does not trow an exception when called with no valid criteria');
} catch (PropelException $e) {
$this->fail('PropelStatementFormatter::format() does not trow an exception when called with no valid criteria');
}
}
public function testFormatManyResults()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelStatementFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$books = $formatter->format($stmt);
$this->assertTrue($books instanceof PDOStatement, 'PropelStatementFormatter::format() returns a PDOStatement');
$this->assertEquals(4, $books->rowCount(), 'PropelStatementFormatter::format() returns as many rows as the results in the query');
while ($book = $books->fetch()) {
$this->assertTrue(is_array($book), 'PropelStatementFormatter::format() returns a statement that can be fetched');
}
}
public function testFormatOneResult()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "Quicksilver"');
$formatter = new PropelStatementFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$books = $formatter->format($stmt);
$this->assertTrue($books instanceof PDOStatement, 'PropelStatementFormatter::format() returns a PDOStatement');
$this->assertEquals(1, $books->rowCount(), 'PropelStatementFormatter::format() returns as many rows as the results in the query');
$book = $books->fetch(PDO::FETCH_ASSOC);
$this->assertEquals('Quicksilver', $book['title'], 'PropelStatementFormatter::format() returns the rows matching the query');
}
public function testFormatNoResult()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"');
$formatter = new PropelStatementFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$books = $formatter->format($stmt);
$this->assertTrue($books instanceof PDOStatement, 'PropelStatementFormatter::format() returns a PDOStatement');
$this->assertEquals(0, $books->rowCount(), 'PropelStatementFormatter::format() returns as many rows as the results in the query');
}
public function testFormatoneNoCriteria()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelStatementFormatter();
try {
$books = $formatter->formatOne($stmt);
$this->assertTrue(true, 'PropelStatementFormatter::formatOne() does not trow an exception when called with no valid criteria');
} catch (PropelException $e) {
$this->fail('PropelStatementFormatter::formatOne() does not trow an exception when called with no valid criteria');
}
}
public function testFormatOneManyResults()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book');
$formatter = new PropelStatementFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$book = $formatter->formatOne($stmt);
$this->assertTrue($book instanceof PDOStatement, 'PropelStatementFormatter::formatOne() returns a PDO Statement');
}
public function testFormatOneNoResult()
{
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"');
$formatter = new PropelStatementFormatter();
$formatter->init(new ModelCriteria('bookstore', 'Book'));
$book = $formatter->formatOne($stmt);
$this->assertNull($book, 'PropelStatementFormatter::formatOne() returns null when no result');
}
}

View file

@ -0,0 +1,141 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/map/ColumnMap.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/map/TableMap.php';
/**
* Test class for TableMap.
*
* @author François Zaninotto
* @version $Id: ColumnMapTest.php 1773 2010-05-25 10:25:06Z francois $
* @package runtime.map
*/
class ColumnMapTest extends PHPUnit_Framework_TestCase
{
protected $databaseMap;
protected function setUp()
{
parent::setUp();
$this->dmap = new DatabaseMap('foodb');
$this->tmap = new TableMap('foo', $this->dmap);
$this->columnName = 'bar';
$this->cmap = new ColumnMap($this->columnName, $this->tmap);
}
protected function tearDown()
{
// nothing to do for now
parent::tearDown();
}
public function testConstructor()
{
$this->assertEquals($this->columnName, $this->cmap->getName(), 'constructor sets the column name');
$this->assertEquals($this->tmap, $this->cmap->getTable(), 'Constructor sets the table map');
$this->assertNull($this->cmap->getType(), 'A new column map has no type');
}
public function testPhpName()
{
$this->assertNull($this->cmap->getPhpName(), 'phpName is empty until set');
$this->cmap->setPhpName('FooBar');
$this->assertEquals('FooBar', $this->cmap->getPhpName(), 'phpName is set by setPhpName()');
}
public function testType()
{
$this->assertNull($this->cmap->getType(), 'type is empty until set');
$this->cmap->setType('FooBar');
$this->assertEquals('FooBar', $this->cmap->getType(), 'type is set by setType()');
}
public function tesSize()
{
$this->assertEquals(0, $this->cmap->getSize(), 'size is empty until set');
$this->cmap->setSize(123);
$this->assertEquals(123, $this->cmap->getSize(), 'size is set by setSize()');
}
public function testPrimaryKey()
{
$this->assertFalse($this->cmap->isPrimaryKey(), 'primaryKey is false by default');
$this->cmap->setPrimaryKey(true);
$this->assertTrue($this->cmap->isPrimaryKey(), 'primaryKey is set by setPrimaryKey()');
}
public function testNotNull()
{
$this->assertFalse($this->cmap->isNotNull(), 'notNull is false by default');
$this->cmap->setNotNull(true);
$this->assertTrue($this->cmap->isNotNull(), 'notNull is set by setPrimaryKey()');
}
public function testDefaultValue()
{
$this->assertNull($this->cmap->getDefaultValue(), 'defaultValue is empty until set');
$this->cmap->setDefaultValue('FooBar');
$this->assertEquals('FooBar', $this->cmap->getDefaultValue(), 'defaultValue is set by setDefaultValue()');
}
public function testGetForeignKey()
{
$this->assertFalse($this->cmap->isForeignKey(), 'foreignKey is false by default');
try
{
$this->cmap->getRelatedTable();
$this->fail('getRelatedTable throws an exception when called on a column with no foreign key');
} catch(PropelException $e) {
$this->assertTrue(true, 'getRelatedTable throws an exception when called on a column with no foreign key');
}
try
{
$this->cmap->getRelatedColumn();
$this->fail('getRelatedColumn throws an exception when called on a column with no foreign key');
} catch(PropelException $e) {
$this->assertTrue(true, 'getRelatedColumn throws an exception when called on a column with no foreign key');
}
$relatedTmap = $this->dmap->addTable('foo2');
// required to let the database map use the foreign TableMap
$relatedCmap = $relatedTmap->addColumn('BAR2', 'Bar2', 'INTEGER');
$this->cmap->setForeignKey('foo2', 'BAR2');
$this->assertTrue($this->cmap->isForeignKey(), 'foreignKey is true after setting the foreign key via setForeignKey()');
$this->assertEquals($relatedTmap, $this->cmap->getRelatedTable(), 'getRelatedTable returns the related TableMap object');
$this->assertEquals($relatedCmap, $this->cmap->getRelatedColumn(), 'getRelatedColumn returns the related ColumnMap object');
}
public function testGetRelation()
{
set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes");
Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php');
$bookTable = BookPeer::getTableMap();
$titleColumn = $bookTable->getColumn('TITLE');
$this->assertNull($titleColumn->getRelation(), 'getRelation() returns null for non-foreign key columns');
$publisherColumn = $bookTable->getColumn('PUBLISHER_ID');
$this->assertEquals($publisherColumn->getRelation(), $bookTable->getRelation('Publisher'), 'getRelation() returns the RelationMap object for this foreign key');
$bookstoreTable = BookstoreEmployeePeer::getTableMap();
$supervisorColumn = $bookstoreTable->getColumn('SUPERVISOR_ID');
$this->assertEquals($supervisorColumn->getRelation(), $supervisorColumn->getRelation('Supervisor'), 'getRelation() returns the RelationMap object even whit ha specific refPhpName');
}
public function testNormalizeName()
{
$this->assertEquals('', ColumnMap::normalizeName(''), 'normalizeColumnName() returns an empty string when passed an empty string');
$this->assertEquals('BAR', ColumnMap::normalizeName('bar'), 'normalizeColumnName() uppercases the input');
$this->assertEquals('BAR_BAZ', ColumnMap::normalizeName('bar_baz'), 'normalizeColumnName() does not mind underscores');
$this->assertEquals('BAR', ColumnMap::normalizeName('FOO.BAR'), 'normalizeColumnName() removes table prefix');
$this->assertEquals('BAR', ColumnMap::normalizeName('BAR'), 'normalizeColumnName() leaves normalized column names unchanged');
$this->assertEquals('BAR_BAZ', ColumnMap::normalizeName('foo.bar_baz'), 'normalizeColumnName() can do all the above at the same time');
}
}

View file

@ -0,0 +1,171 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/map/ColumnMap.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/map/TableMap.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/map/DatabaseMap.php';
class TestDatabaseBuilder
{
protected static $dmap = null;
protected static $tmap = null;
public static function getDmap()
{
if (is_null(self::$dmap)) {
self::$dmap = new DatabaseMap('foodb');
}
return self::$dmap;
}
public static function setTmap($tmap)
{
self::$tmap = $tmap;
}
public static function getTmap()
{
return self::$tmap;
}
}
class BazTableMap extends TableMap
{
public function initialize()
{
$this->setName('baz');
$this->setPhpName('Baz');
}
}
/**
* Test class for DatabaseMap.
*
* @author François Zaninotto
* @version $Id: DatabaseMapTest.php 1773 2010-05-25 10:25:06Z francois $
* @package runtime.map
*/
class DatabaseMapTest extends PHPUnit_Framework_TestCase
{
protected $databaseMap;
protected function setUp()
{
parent::setUp();
$this->databaseName = 'foodb';
$this->databaseMap = TestDatabaseBuilder::getDmap();
}
protected function tearDown()
{
// nothing to do for now
parent::tearDown();
}
public function testConstructor()
{
$this->assertEquals($this->databaseName, $this->databaseMap->getName(), 'constructor sets the table name');
}
public function testAddTable()
{
$this->assertFalse($this->databaseMap->hasTable('foo'), 'tables are empty by default');
try
{
$this->databaseMap->getTable('foo');
$this->fail('getTable() throws an exception when called on an inexistent table');
} catch(PropelException $e) {
$this->assertTrue(true, 'getTable() throws an exception when called on an inexistent table');
}
$tmap = $this->databaseMap->addTable('foo');
$this->assertTrue($this->databaseMap->hasTable('foo'), 'hasTable() returns true when the table was added by way of addTable()');
$this->assertEquals($tmap, $this->databaseMap->getTable('foo'), 'getTable() returns a table by name when the table was added by way of addTable()');
}
public function testAddTableObject()
{
$this->assertFalse($this->databaseMap->hasTable('foo2'), 'tables are empty by default');
try
{
$this->databaseMap->getTable('foo2');
$this->fail('getTable() throws an exception when called on a table with no builder');
} catch(PropelException $e) {
$this->assertTrue(true, 'getTable() throws an exception when called on a table with no builder');
}
$tmap = new TableMap('foo2');
$this->databaseMap->addTableObject($tmap);
$this->assertTrue($this->databaseMap->hasTable('foo2'), 'hasTable() returns true when the table was added by way of addTableObject()');
$this->assertEquals($tmap, $this->databaseMap->getTable('foo2'), 'getTable() returns a table by name when the table was added by way of addTableObject()');
}
public function testAddTableFromMapClass()
{
$table1 = $this->databaseMap->addTableFromMapClass('BazTableMap');
try
{
$table2 = $this->databaseMap->getTable('baz');
$this->assertEquals($table1, $table2, 'addTableFromMapClass() adds a table from a map class');
} catch(PropelException $e) {
$this->fail('addTableFromMapClass() adds a table from a map class');
}
}
public function testGetColumn()
{
try
{
$this->databaseMap->getColumn('foo.BAR');
$this->fail('getColumn() throws an exception when called on column of an inexistent table');
} catch(PropelException $e) {
$this->assertTrue(true, 'getColumn() throws an exception when called on column of an inexistent table');
}
$tmap = $this->databaseMap->addTable('foo');
try
{
$this->databaseMap->getColumn('foo.BAR');
$this->fail('getColumn() throws an exception when called on an inexistent column of an existent table');
} catch(PropelException $e) {
$this->assertTrue(true, 'getColumn() throws an exception when called on an inexistent column of an existent table');
}
$column = $tmap->addColumn('BAR', 'Bar', 'INTEGER');
$this->assertEquals($column, $this->databaseMap->getColumn('foo.BAR'), 'getColumn() returns a ColumnMap object based on a fully qualified name');
}
public function testGetTableByPhpName()
{
try
{
$this->databaseMap->getTableByPhpName('Foo1');
$this->fail('getTableByPhpName() throws an exception when called on an inexistent table');
} catch(PropelException $e) {
$this->assertTrue(true, 'getTableByPhpName() throws an exception when called on an inexistent table');
}
$tmap = $this->databaseMap->addTable('foo1');
try
{
$this->databaseMap->getTableByPhpName('Foo1');
$this->fail('getTableByPhpName() throws an exception when called on a table with no phpName');
} catch(PropelException $e) {
$this->assertTrue(true, 'getTableByPhpName() throws an exception when called on a table with no phpName');
}
$tmap2 = new TableMap('foo2');
$tmap2->setClassname('Foo2');
$this->databaseMap->addTableObject($tmap2);
$this->assertEquals($tmap2, $this->databaseMap->getTableByPhpName('Foo2'), 'getTableByPhpName() returns tableMap when phpName was set by way of TableMap::setPhpName()');
}
public function testGetTableByPhpNameNotLoaded()
{
set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes");
require_once 'bookstore/map/BookTableMap.php';
require_once 'bookstore/om/BaseBookPeer.php';
require_once 'bookstore/BookPeer.php';
$this->assertEquals('book', Propel::getDatabaseMap('bookstore')->getTableByPhpName('Book')->getName(), 'getTableByPhpName() can autoload a TableMap when the Peer class is generated and autoloaded');
}
}

View file

@ -0,0 +1,75 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Test class for PHP5TableMapBuilder.
*
* @author François Zaninotto
* @version $Id: GeneratedRelationMapTest.php 1612 2010-03-16 22:56:21Z francois $
* @package runtime.map
*/
class GeneratedRelationMapTest extends BookstoreTestBase
{
protected $databaseMap;
protected function setUp()
{
parent::setUp();
$this->databaseMap = Propel::getDatabaseMap('bookstore');
}
public function testGetRightTable()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$authorTable = $this->databaseMap->getTableByPhpName('Author');
$this->assertEquals($authorTable, $bookTable->getRelation('Author')->getRightTable(), 'getRightTable() returns correct table when called on a many to one relationship');
$this->assertEquals($bookTable, $authorTable->getRelation('Book')->getRightTable(), 'getRightTable() returns correct table when called on a one to many relationship');
$bookEmpTable = $this->databaseMap->getTableByPhpName('BookstoreEmployee');
$bookEmpAccTable = $this->databaseMap->getTableByPhpName('BookstoreEmployeeAccount');
$this->assertEquals($bookEmpAccTable, $bookEmpTable->getRelation('BookstoreEmployeeAccount')->getRightTable(), 'getRightTable() returns correct table when called on a one to one relationship');
$this->assertEquals($bookEmpTable, $bookEmpAccTable->getRelation('BookstoreEmployee')->getRightTable(), 'getRightTable() returns correct table when called on a one to one relationship');
}
public function testColumnMappings()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$this->assertEquals(array('book.AUTHOR_ID' => 'author.ID'), $bookTable->getRelation('Author')->getColumnMappings(), 'getColumnMappings returns local to foreign by default');
$this->assertEquals(array('book.AUTHOR_ID' => 'author.ID'), $bookTable->getRelation('Author')->getColumnMappings(RelationMap::LEFT_TO_RIGHT), 'getColumnMappings returns local to foreign when asked left to right for a many to one relationship');
$authorTable = $this->databaseMap->getTableByPhpName('Author');
$this->assertEquals(array('book.AUTHOR_ID' => 'author.ID'), $authorTable->getRelation('Book')->getColumnMappings(), 'getColumnMappings returns local to foreign by default');
$this->assertEquals(array('author.ID' => 'book.AUTHOR_ID'), $authorTable->getRelation('Book')->getColumnMappings(RelationMap::LEFT_TO_RIGHT), 'getColumnMappings returns foreign to local when asked left to right for a one to many relationship');
$bookEmpTable = $this->databaseMap->getTableByPhpName('BookstoreEmployee');
$this->assertEquals(array('bookstore_employee_account.EMPLOYEE_ID' => 'bookstore_employee.ID'), $bookEmpTable->getRelation('BookstoreEmployeeAccount')->getColumnMappings(), 'getColumnMappings returns local to foreign by default');
$this->assertEquals(array('bookstore_employee.ID' => 'bookstore_employee_account.EMPLOYEE_ID'), $bookEmpTable->getRelation('BookstoreEmployeeAccount')->getColumnMappings(RelationMap::LEFT_TO_RIGHT), 'getColumnMappings returns foreign to local when asked left to right for a one to one relationship');
}
public function testCountColumnMappings()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$this->assertEquals(1, $bookTable->getRelation('Author')->countColumnMappings());
$rfTable = $this->databaseMap->getTableByPhpName('ReaderFavorite');
$this->assertEquals(2, $rfTable->getRelation('BookOpinion')->countColumnMappings());
}
public function testIsComposite()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$this->assertFalse($bookTable->getRelation('Author')->isComposite());
$rfTable = $this->databaseMap->getTableByPhpName('ReaderFavorite');
$this->assertTrue($rfTable->getRelation('BookOpinion')->isComposite());
}
}

View file

@ -0,0 +1,70 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Test class for RelatedMap::getSymmetricalRelation.
*
* @author François Zaninotto
* @version $Id: GeneratedRelationMapTest.php 1347 2009-12-03 21:06:36Z francois $
* @package runtime.map
*/
class RelatedMapSymmetricalTest extends BookstoreTestBase
{
protected $databaseMap;
protected function setUp()
{
parent::setUp();
$this->databaseMap = Propel::getDatabaseMap('bookstore');
}
public function testOneToMany()
{
$bookTable = $this->databaseMap->getTableByPhpName('Book');
$bookToAuthor = $bookTable->getRelation('Author');
$authorTable = $this->databaseMap->getTableByPhpName('Author');
$authorToBook = $authorTable->getRelation('Book');
$this->assertEquals($authorToBook, $bookToAuthor->getSymmetricalRelation());
$this->assertEquals($bookToAuthor, $authorToBook->getSymmetricalRelation());
}
public function testOneToOne()
{
$accountTable = $this->databaseMap->getTableByPhpName('BookstoreEmployeeAccount');
$accountToEmployee = $accountTable->getRelation('BookstoreEmployee');
$employeeTable = $this->databaseMap->getTableByPhpName('BookstoreEmployee');
$employeeToAccount = $employeeTable->getRelation('BookstoreEmployeeAccount');
$this->assertEquals($accountToEmployee, $employeeToAccount->getSymmetricalRelation());
$this->assertEquals($employeeToAccount, $accountToEmployee->getSymmetricalRelation());
}
public function testSeveralRelationsOnSameTable()
{
$authorTable = $this->databaseMap->getTableByPhpName('Author');
$authorToEssay = $authorTable->getRelation('EssayRelatedByFirstAuthor');
$essayTable = $this->databaseMap->getTableByPhpName('Essay');
$essayToAuthor = $essayTable->getRelation('AuthorRelatedByFirstAuthor');
$this->assertEquals($authorToEssay, $essayToAuthor->getSymmetricalRelation());
$this->assertEquals($essayToAuthor, $authorToEssay->getSymmetricalRelation());
}
public function testCompositeForeignKey()
{
$favoriteTable = $this->databaseMap->getTableByPhpName('ReaderFavorite');
$favoriteToOpinion = $favoriteTable->getRelation('BookOpinion');
$opinionTable = $this->databaseMap->getTableByPhpName('BookOpinion');
$opinionToFavorite = $opinionTable->getRelation('ReaderFavorite');
$this->assertEquals($favoriteToOpinion, $opinionToFavorite->getSymmetricalRelation());
$this->assertEquals($opinionToFavorite, $favoriteToOpinion->getSymmetricalRelation());
}
}

View file

@ -0,0 +1,89 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/map/RelationMap.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/map/TableMap.php';
/**
* Test class for RelationMap.
*
* @author François Zaninotto
* @version $Id: RelationMapTest.php 1773 2010-05-25 10:25:06Z francois $
* @package runtime.map
*/
class RelationMapTest extends PHPUnit_Framework_TestCase
{
protected $databaseMap, $relationName, $rmap;
protected function setUp()
{
parent::setUp();
$this->databaseMap = new DatabaseMap('foodb');
$this->relationName = 'foo';
$this->rmap = new RelationMap($this->relationName);
}
public function testConstructor()
{
$this->assertEquals($this->relationName, $this->rmap->getName(), 'constructor sets the relation name');
}
public function testLocalTable()
{
$this->assertNull($this->rmap->getLocalTable(), 'A new relation has no local table');
$tmap1 = new TableMap('foo', $this->databaseMap);
$this->rmap->setLocalTable($tmap1);
$this->assertEquals($tmap1, $this->rmap->getLocalTable(), 'The local table is set by setLocalTable()');
}
public function testForeignTable()
{
$this->assertNull($this->rmap->getForeignTable(), 'A new relation has no foreign table');
$tmap2 = new TableMap('bar', $this->databaseMap);
$this->rmap->setForeignTable($tmap2);
$this->assertEquals($tmap2, $this->rmap->getForeignTable(), 'The foreign table is set by setForeignTable()');
}
public function testProperties()
{
$properties = array('type', 'onUpdate', 'onDelete');
foreach ($properties as $property)
{
$getter = 'get' . ucfirst($property);
$setter = 'set' . ucfirst($property);
$this->assertNull($this->rmap->$getter(), "A new relation has no $property");
$this->rmap->$setter('foo_value');
$this->assertEquals('foo_value', $this->rmap->$getter(), "The $property is set by setType()");
}
}
public function testColumns()
{
$this->assertEquals(array(), $this->rmap->getLocalColumns(), 'A new relation has no local columns');
$this->assertEquals(array(), $this->rmap->getForeignColumns(), 'A new relation has no foreign columns');
$tmap1 = new TableMap('foo', $this->databaseMap);
$col1 = $tmap1->addColumn('FOO1', 'Foo1PhpName', 'INTEGER');
$tmap2 = new TableMap('bar', $this->databaseMap);
$col2 = $tmap2->addColumn('BAR1', 'Bar1PhpName', 'INTEGER');
$this->rmap->addColumnMapping($col1, $col2);
$this->assertEquals(array($col1), $this->rmap->getLocalColumns(), 'addColumnMapping() adds a local table');
$this->assertEquals(array($col2), $this->rmap->getForeignColumns(), 'addColumnMapping() adds a foreign table');
$expected = array('foo.FOO1' => 'bar.BAR1');
$this->assertEquals($expected, $this->rmap->getColumnMappings(), 'getColumnMappings() returns an associative array of column mappings');
$col3 = $tmap1->addColumn('FOOFOO', 'FooFooPhpName', 'INTEGER');
$col4 = $tmap2->addColumn('BARBAR', 'BarBarPhpName', 'INTEGER');
$this->rmap->addColumnMapping($col3, $col4);
$this->assertEquals(array($col1, $col3), $this->rmap->getLocalColumns(), 'addColumnMapping() adds a local table');
$this->assertEquals(array($col2, $col4), $this->rmap->getForeignColumns(), 'addColumnMapping() adds a foreign table');
$expected = array('foo.FOO1' => 'bar.BAR1', 'foo.FOOFOO' => 'bar.BARBAR');
$this->assertEquals($expected, $this->rmap->getColumnMappings(), 'getColumnMappings() returns an associative array of column mappings');
}
}

View file

@ -0,0 +1,286 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/map/ColumnMap.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/map/TableMap.php';
class TestableTableMap extends TableMap
{
public function hasPrefix($data)
{
return parent::hasPrefix($data);
}
public function removePrefix($data)
{
return parent::removePrefix($data);
}
public function normalizeColName($name)
{
return parent::normalizeColName($name);
}
}
class FooTableMap extends TableMap
{
public $rmap;
public function buildRelations()
{
$this->rmap = $this->addRelation('Bar', 'Bar', RelationMap::MANY_TO_ONE);
}
}
class BarTableMap extends TableMap
{
public function initialize()
{
$this->setName('bar');
$this->setPhpName('Bar');
}
}
/**
* Test class for TableMap.
*
* @author François Zaninotto
* @version $Id: TableMapTest.php 1773 2010-05-25 10:25:06Z francois $
* @package runtime.map
*/
class TableMapTest extends PHPUnit_Framework_TestCase
{
protected $databaseMap;
protected function setUp()
{
parent::setUp();
$this->databaseMap = new DatabaseMap('foodb');
$this->tableName = 'foo';
$this->tmap = new TableMap($this->tableName, $this->databaseMap);
}
protected function tearDown()
{
// nothing to do for now
parent::tearDown();
}
public function testConstructor()
{
$this->assertEquals(array(), $this->tmap->getColumns(), 'A new table map has no columns');
$this->assertEquals($this->tableName, $this->tmap->getName(), 'constructor can set the table name');
$this->assertEquals($this->databaseMap, $this->tmap->getDatabaseMap(), 'Constructor can set the database map');
try {
$tmap = new TableMap();
$this->assertTrue(true, 'A table map can be instanciated with no parameters');
} catch (Exception $e) {
$this->fail('A table map can be instanciated with no parameters');
}
}
public function testProperties()
{
$tmap = new TableMap();
$properties = array('name', 'phpName', 'className', 'package');
foreach ($properties as $property)
{
$getter = 'get' . ucfirst($property);
$setter = 'set' . ucfirst($property);
$this->assertNull($tmap->$getter(), "A new relation has no $property");
$tmap->$setter('foo_value');
$this->assertEquals('foo_value', $tmap->$getter(), "The $property is set by setType()");
}
}
public function testHasColumn()
{
$this->assertFalse($this->tmap->hasColumn('BAR'), 'hascolumn() returns false when the column is not in the table map');
$column = $this->tmap->addColumn('BAR', 'Bar', 'INTEGER');
$this->assertTrue($this->tmap->hasColumn('BAR'), 'hascolumn() returns true when the column is in the table map');
$this->assertTrue($this->tmap->hasColumn('foo.bar'), 'hascolumn() accepts a denormalized column name');
$this->assertFalse($this->tmap->hasColumn('foo.bar', false), 'hascolumn() accepts a $normalize parameter to skip name normalization');
$this->assertTrue($this->tmap->hasColumn('BAR', false), 'hascolumn() accepts a $normalize parameter to skip name normalization');
$this->assertTrue($this->tmap->hasColumn($column), 'hascolumn() accepts a ColumnMap object as parameter');
}
public function testGetColumn()
{
$column = $this->tmap->addColumn('BAR', 'Bar', 'INTEGER');
$this->assertEquals($column, $this->tmap->getColumn('BAR'), 'getColumn returns a ColumnMap according to a column name');
try
{
$this->tmap->getColumn('FOO');
$this->fail('getColumn throws an exception when called on an inexistent column');
} catch(PropelException $e) {}
$this->assertEquals($column, $this->tmap->getColumn('foo.bar'), 'getColumn accepts a denormalized column name');
try
{
$this->tmap->getColumn('foo.bar', false);
$this->fail('getColumn accepts a $normalize parameter to skip name normalization');
} catch(PropelException $e) {}
}
public function testGetColumnByPhpName()
{
$column = $this->tmap->addColumn('BAR_BAZ', 'BarBaz', 'INTEGER');
$this->assertEquals($column, $this->tmap->getColumnByPhpName('BarBaz'), 'getColumnByPhpName() returns a ColumnMap according to a column phpName');
try
{
$this->tmap->getColumn('Foo');
$this->fail('getColumnByPhpName() throws an exception when called on an inexistent column');
} catch(PropelException $e) {}
}
public function testGetColumns()
{
$this->assertEquals(array(), $this->tmap->getColumns(), 'getColumns returns an empty array when no columns were added');
$column1 = $this->tmap->addColumn('BAR', 'Bar', 'INTEGER');
$column2 = $this->tmap->addColumn('BAZ', 'Baz', 'INTEGER');
$this->assertEquals(array('BAR' => $column1, 'BAZ' => $column2), $this->tmap->getColumns(), 'getColumns returns the columns indexed by name');
}
public function testAddPrimaryKey()
{
$column1 = $this->tmap->addPrimaryKey('BAR', 'Bar', 'INTEGER');
$this->assertTrue($column1->isPrimaryKey(), 'Columns added by way of addPrimaryKey() are primary keys');
$column2 = $this->tmap->addColumn('BAZ', 'Baz', 'INTEGER');
$this->assertFalse($column2->isPrimaryKey(), 'Columns added by way of addColumn() are not primary keys by default');
$column3 = $this->tmap->addColumn('BAZZ', 'Bazz', 'INTEGER', null, null, null, true);
$this->assertTrue($column3->isPrimaryKey(), 'Columns added by way of addColumn() can be defined as primary keys');
$column4 = $this->tmap->addForeignKey('BAZZZ', 'Bazzz', 'INTEGER', 'Table1', 'column1');
$this->assertFalse($column4->isPrimaryKey(), 'Columns added by way of addForeignKey() are not primary keys');
$column5 = $this->tmap->addForeignPrimaryKey('BAZZZZ', 'Bazzzz', 'INTEGER', 'table1', 'column1');
$this->assertTrue($column5->isPrimaryKey(), 'Columns added by way of addForeignPrimaryKey() are primary keys');
}
public function testGetPrimaryKeyColumns()
{
$this->assertEquals(array(), $this->tmap->getPrimaryKeyColumns(), 'getPrimaryKeyColumns() returns an empty array by default');
$column1 = $this->tmap->addPrimaryKey('BAR', 'Bar', 'INTEGER');
$column3 = $this->tmap->addColumn('BAZZ', 'Bazz', 'INTEGER', null, null, null, true);
$expected = array($column1, $column3);
$this->assertEquals($expected, $this->tmap->getPrimaryKeyColumns(), 'getPrimaryKeyColumns() returns an array of the table primary keys');
}
public function testGetPrimaryKeys()
{
$this->assertEquals(array(), $this->tmap->getPrimaryKeys(), 'getPrimaryKeys() returns an empty array by default');
$column1 = $this->tmap->addPrimaryKey('BAR', 'Bar', 'INTEGER');
$column3 = $this->tmap->addColumn('BAZZ', 'Bazz', 'INTEGER', null, null, null, true);
$expected = array('BAR' => $column1, 'BAZZ' => $column3);
$this->assertEquals($expected, $this->tmap->getPrimaryKeys(), 'getPrimaryKeys() returns an array of the table primary keys');
}
public function testAddForeignKey()
{
$column1 = $this->tmap->addForeignKey('BAR', 'Bar', 'INTEGER', 'Table1', 'column1');
$this->assertTrue($column1->isForeignKey(), 'Columns added by way of addForeignKey() are foreign keys');
$column2 = $this->tmap->addColumn('BAZ', 'Baz', 'INTEGER');
$this->assertFalse($column2->isForeignKey(), 'Columns added by way of addColumn() are not foreign keys by default');
$column3 = $this->tmap->addColumn('BAZZ', 'Bazz', 'INTEGER', null, null, null, false, 'Table1', 'column1');
$this->assertTrue($column3->isForeignKey(), 'Columns added by way of addColumn() can be defined as foreign keys');
$column4 = $this->tmap->addPrimaryKey('BAZZZ', 'Bazzz', 'INTEGER');
$this->assertFalse($column4->isForeignKey(), 'Columns added by way of addPrimaryKey() are not foreign keys');
$column5 = $this->tmap->addForeignPrimaryKey('BAZZZZ', 'Bazzzz', 'INTEGER', 'table1', 'column1');
$this->assertTrue($column5->isForeignKey(), 'Columns added by way of addForeignPrimaryKey() are foreign keys');
}
public function testGetForeignKeys()
{
$this->assertEquals(array(), $this->tmap->getForeignKeys(), 'getForeignKeys() returns an empty array by default');
$column1 = $this->tmap->addForeignKey('BAR', 'Bar', 'INTEGER', 'Table1', 'column1');
$column3 = $this->tmap->addColumn('BAZZ', 'Bazz', 'INTEGER', null, null, null, false, 'Table1', 'column1');
$expected = array('BAR' => $column1, 'BAZZ' => $column3);
$this->assertEquals($expected, $this->tmap->getForeignKeys(), 'getForeignKeys() returns an array of the table foreign keys');
}
public function testLazyLoadRelations()
{
try {
$this->tmap->getRelation('Bar');
$this->fail('getRelation() throws an exception when called on a table with no relations');
} catch (PropelException $e) {
$this->assertTrue(true, 'getRelation() throws an exception when called on a table with no relations');
}
$foreigntmap = new BarTableMap();
$this->databaseMap->addTableObject($foreigntmap);
$localtmap = new FooTableMap();
$this->databaseMap->addTableObject($localtmap);
$rmap = $localtmap->getRelation('Bar');
$this->assertEquals($rmap, $localtmap->rmap, 'getRelation() returns the relations lazy loaded by buildRelations()');
}
public function testAddRelation()
{
$foreigntmap1 = new TableMap('bar');
$foreigntmap1->setClassname('Bar');
$this->databaseMap->addTableObject($foreigntmap1);
$foreigntmap2 = new TableMap('baz');
$foreigntmap2->setClassname('Baz');
$this->databaseMap->addTableObject($foreigntmap2);
$this->rmap1 = $this->tmap->addRelation('Bar', 'Bar', RelationMap::MANY_TO_ONE);
$this->rmap2 = $this->tmap->addRelation('Bazz', 'Baz', RelationMap::ONE_TO_MANY);
$this->tmap->getRelations();
// now on to the test
$this->assertEquals($this->rmap1->getLocalTable(), $this->tmap, 'adding a relation with HAS_ONE sets the local table to the current table');
$this->assertEquals($this->rmap1->getForeignTable(), $foreigntmap1, 'adding a relation with HAS_ONE sets the foreign table according to the name given');
$this->assertEquals(RelationMap::MANY_TO_ONE, $this->rmap1->getType(), 'adding a relation with HAS_ONE sets the foreign table type accordingly');
$this->assertEquals($this->rmap2->getForeignTable(), $this->tmap, 'adding a relation with HAS_MANY sets the foreign table to the current table');
$this->assertEquals($this->rmap2->getLocalTable(), $foreigntmap2, 'adding a relation with HAS_MANY sets the local table according to the name given');
$this->assertEquals(RelationMap::ONE_TO_MANY, $this->rmap2->getType(), 'adding a relation with HAS_MANY sets the foreign table type accordingly');
$expectedRelations = array('Bar' => $this->rmap1, 'Bazz' => $this->rmap2);
$this->assertEquals($expectedRelations, $this->tmap->getRelations(), 'getRelations() returns an associative array of all the relations');
}
// deprecated method
public function testNormalizeColName()
{
$tmap = new TestableTableMap();
$this->assertEquals('', $tmap->normalizeColName(''), 'normalizeColName returns an empty string when passed an empty string');
$this->assertEquals('BAR', $tmap->normalizeColName('bar'), 'normalizeColName uppercases the input');
$this->assertEquals('BAR_BAZ', $tmap->normalizeColName('bar_baz'), 'normalizeColName does not mind underscores');
$this->assertEquals('BAR', $tmap->normalizeColName('FOO.BAR'), 'normalizeColName removes table prefix');
$this->assertEquals('BAR', $tmap->normalizeColName('BAR'), 'normalizeColName leaves normalized column names unchanged');
$this->assertEquals('BAR_BAZ', $tmap->normalizeColName('foo.bar_baz'), 'normalizeColName can do all the above at the same time');
}
// deprecated method
public function testContainsColumn()
{
$this->assertFalse($this->tmap->containsColumn('BAR'), 'containsColumn returns false when the column is not in the table map');
$column = $this->tmap->addColumn('BAR', 'Bar', 'INTEGER');
$this->assertTrue($this->tmap->containsColumn('BAR'), 'containsColumn returns true when the column is in the table map');
$this->assertTrue($this->tmap->containsColumn('foo.bar'), 'containsColumn accepts a denormalized column name');
$this->assertFalse($this->tmap->containsColumn('foo.bar', false), 'containsColumn accepts a $normalize parameter to skip name normalization');
$this->assertTrue($this->tmap->containsColumn('BAR', false), 'containsColumn accepts a $normalize parameter to skip name normalization');
$this->assertTrue($this->tmap->containsColumn($column), 'containsColumn accepts a ColumnMap object as parameter');
}
// deprecated methods
public function testPrefix()
{
$tmap = new TestableTableMap();
$this->assertNull($tmap->getPrefix(), 'prefix is empty until set');
$this->assertFalse($tmap->hasPrefix('barbaz'), 'hasPrefix returns false when prefix is not set');
$tmap->setPrefix('bar');
$this->assertEquals('bar', $tmap->getPrefix(), 'prefix is set by setPrefix()');
$this->assertTrue($tmap->hasPrefix('barbaz'), 'hasPrefix returns true when prefix is set and found in string');
$this->assertFalse($tmap->hasPrefix('baz'), 'hasPrefix returns false when prefix is set and not found in string');
$this->assertFalse($tmap->hasPrefix('bazbar'), 'hasPrefix returns false when prefix is set and not found anywhere in string');
$this->assertEquals('baz', $tmap->removePrefix('barbaz'), 'removePrefix returns string without prefix if found at the beginning');
$this->assertEquals('bazbaz', $tmap->removePrefix('bazbaz'), 'removePrefix returns original string when prefix is not found');
$this->assertEquals('bazbar', $tmap->removePrefix('bazbar'), 'removePrefix returns original string when prefix is not found at the beginning');
}
}

View file

@ -0,0 +1,95 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
require_once 'tools/helpers/bookstore/BookstoreDataPopulator.php';
/**
* Test class for BaseObject serialization.
*
* @author Francois Zaninotto
* @version $Id: PropelCollectionTest.php 1348 2009-12-03 21:49:00Z francois $
* @package runtime.om
*/
class BaseObjectSerializeTest extends BookstoreTestBase
{
public function testSerializeEmptyObject()
{
$book = new Book();
$sb = serialize($book);
$this->assertEquals($book, unserialize($sb));
}
public function testSerializePopulatedObject()
{
$book = new Book();
$book->setTitle('Foo1');
$book->setISBN('1234');
$sb = serialize($book);
$this->assertEquals($book, unserialize($sb));
}
public function testSerializePersistedObject()
{
$book = new Book();
$book->setTitle('Foo2');
$book->setISBN('1234');
$book->save();
$sb = serialize($book);
$this->assertEquals($book, unserialize($sb));
}
public function testSerializeHydratedObject()
{
$book = new Book();
$book->setTitle('Foo3');
$book->setISBN('1234');
$book->save();
BookPeer::clearInstancePool();
$book = BookQuery::create()->findOneByTitle('Foo3');
$sb = serialize($book);
$this->assertEquals($book, unserialize($sb));
}
public function testSerializeObjectWithRelations()
{
$author = new Author();
$author->setFirstName('John');
$book = new Book();
$book->setTitle('Foo4');
$book->setISBN('1234');
$book->setAuthor($author);
$book->save();
$b = clone $book;
$sb = serialize($b);
$book->clearAllReferences();
$this->assertEquals($book, unserialize($sb));
}
public function testSerializeObjectWithCollections()
{
$book1 = new Book();
$book1->setTitle('Foo5');
$book1->setISBN('1234');
$book2 = new Book();
$book2->setTitle('Foo6');
$book2->setISBN('1234');
$author = new Author();
$author->setFirstName('JAne');
$author->addBook($book1);
$author->addBook($book2);
$author->save();
$a = clone $author;
$sa = serialize($a);
$author->clearAllReferences();
$this->assertEquals($author, unserialize($sa));
}
}

View file

@ -0,0 +1,69 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/om/BaseObject.php';
/**
* Test class for BaseObject.
*
* @author François Zaninotto
* @version $Id: BaseObjectTest.php 1347 2009-12-03 21:06:36Z francois $
* @package runtime.om
*/
class BaseObjectTest extends PHPUnit_Framework_TestCase
{
public function testGetVirtualColumns()
{
$b = new TestableBaseObject();
$this->assertEquals(array(), $b->getVirtualColumns(), 'getVirtualColumns() returns an empty array for new objects');
$b->virtualColumns = array('foo' => 'bar');
$this->assertEquals(array('foo' => 'bar'), $b->getVirtualColumns(), 'getVirtualColumns() returns an associative array of virtual columns');
}
public function testHasVirtualColumn()
{
$b = new TestableBaseObject();
$this->assertFalse($b->hasVirtualColumn('foo'), 'hasVirtualColumn() returns false if the virtual column is not set');
$b->virtualColumns = array('foo' => 'bar');
$this->assertTrue($b->hasVirtualColumn('foo'), 'hasVirtualColumn() returns true if the virtual column is set');
}
/**
* @expectedException PropelException
*/
public function testGetVirtualColumnWrongKey()
{
$b = new TestableBaseObject();
$b->getVirtualColumn('foo');
}
public function testGetVirtualColumn()
{
$b = new TestableBaseObject();
$b->virtualColumns = array('foo' => 'bar');
$this->assertEquals('bar', $b->getVirtualColumn('foo'), 'getVirtualColumn() returns a virtual column value based on its key');
}
public function testSetVirtualColumn()
{
$b = new TestableBaseObject();
$b->setVirtualColumn('foo', 'bar');
$this->assertEquals('bar', $b->getVirtualColumn('foo'), 'setVirtualColumn() sets a virtual column value based on its key');
$b->setVirtualColumn('foo', 'baz');
$this->assertEquals('baz', $b->getVirtualColumn('foo'), 'setVirtualColumn() can modify the value of an existing virtual column');
$this->assertEquals($b, $b->setVirtualColumn('foo', 'bar'), 'setVirtualColumn() returns the current object');
}
}
class TestableBaseObject extends BaseObject
{
public $virtualColumns = array();
}

View file

@ -0,0 +1,385 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/BaseTestCase.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/query/Criteria.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/util/BasePeer.php';
set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes");
Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php');
/**
* Test class for Criteria combinations.
*
* @author Francois Zaninotto
* @version $Id: CriteriaCombineTest.php 1773 2010-05-25 10:25:06Z francois $
* @package runtime.query
*/
class CriteriaCombineTest extends BaseTestCase
{
/**
* The criteria to use in the test.
* @var Criteria
*/
private $c;
/**
* DB adapter saved for later.
*
* @var DBAdapter
*/
private $savedAdapter;
protected function setUp()
{
parent::setUp();
$this->c = new Criteria();
$this->savedAdapter = Propel::getDB(null);
Propel::setDB(null, new DBSQLite());
}
protected function tearDown()
{
Propel::setDB(null, $this->savedAdapter);
parent::tearDown();
}
/**
* test various properties of Criterion and nested criterion
*/
public function testNestedCriterion()
{
$table2 = "myTable2";
$column2 = "myColumn2";
$value2 = "myValue2";
$key2 = "$table2.$column2";
$table3 = "myTable3";
$column3 = "myColumn3";
$value3 = "myValue3";
$key3 = "$table3.$column3";
$table4 = "myTable4";
$column4 = "myColumn4";
$value4 = "myValue4";
$key4 = "$table4.$column4";
$table5 = "myTable5";
$column5 = "myColumn5";
$value5 = "myValue5";
$key5 = "$table5.$column5";
$crit2 = $this->c->getNewCriterion($key2, $value2, Criteria::EQUAL);
$crit3 = $this->c->getNewCriterion($key3, $value3, Criteria::EQUAL);
$crit4 = $this->c->getNewCriterion($key4, $value4, Criteria::EQUAL);
$crit5 = $this->c->getNewCriterion($key5, $value5, Criteria::EQUAL);
$crit2->addAnd($crit3)->addOr($crit4->addAnd($crit5));
$expect = "((myTable2.myColumn2=:p1 AND myTable3.myColumn3=:p2) "
. "OR (myTable4.myColumn4=:p3 AND myTable5.myColumn5=:p4))";
$sb = "";
$params = array();
$crit2->appendPsTo($sb, $params);
$expect_params = array(
array('table' => 'myTable2', 'column' => 'myColumn2', 'value' => 'myValue2'),
array('table' => 'myTable3', 'column' => 'myColumn3', 'value' => 'myValue3'),
array('table' => 'myTable4', 'column' => 'myColumn4', 'value' => 'myValue4'),
array('table' => 'myTable5', 'column' => 'myColumn5', 'value' => 'myValue5'),
);
$this->assertEquals($expect, $sb);
$this->assertEquals($expect_params, $params);
$crit6 = $this->c->getNewCriterion($key2, $value2, Criteria::EQUAL);
$crit7 = $this->c->getNewCriterion($key3, $value3, Criteria::EQUAL);
$crit8 = $this->c->getNewCriterion($key4, $value4, Criteria::EQUAL);
$crit9 = $this->c->getNewCriterion($key5, $value5, Criteria::EQUAL);
$crit6->addAnd($crit7)->addOr($crit8)->addAnd($crit9);
$expect = "(((myTable2.myColumn2=:p1 AND myTable3.myColumn3=:p2) "
. "OR myTable4.myColumn4=:p3) AND myTable5.myColumn5=:p4)";
$sb = "";
$params = array();
$crit6->appendPsTo($sb, $params);
$expect_params = array(
array('table' => 'myTable2', 'column' => 'myColumn2', 'value' => 'myValue2'),
array('table' => 'myTable3', 'column' => 'myColumn3', 'value' => 'myValue3'),
array('table' => 'myTable4', 'column' => 'myColumn4', 'value' => 'myValue4'),
array('table' => 'myTable5', 'column' => 'myColumn5', 'value' => 'myValue5'),
);
$this->assertEquals($expect, $sb);
$this->assertEquals($expect_params, $params);
// should make sure we have tests for all possibilities
$crita = $crit2->getAttachedCriterion();
$this->assertEquals($crit2, $crita[0]);
$this->assertEquals($crit3, $crita[1]);
$this->assertEquals($crit4, $crita[2]);
$this->assertEquals($crit5, $crita[3]);
$tables = $crit2->getAllTables();
$this->assertEquals($crit2->getTable(), $tables[0]);
$this->assertEquals($crit3->getTable(), $tables[1]);
$this->assertEquals($crit4->getTable(), $tables[2]);
$this->assertEquals($crit5->getTable(), $tables[3]);
// simple confirmations that equality operations work
$this->assertTrue($crit2->hashCode() === $crit2->hashCode());
}
/**
* Tests <= and >=.
*/
public function testBetweenCriterion()
{
$cn1 = $this->c->getNewCriterion("INVOICE.COST", 1000, Criteria::GREATER_EQUAL);
$cn2 = $this->c->getNewCriterion("INVOICE.COST", 5000, Criteria::LESS_EQUAL);
$this->c->add($cn1->addAnd($cn2));
$expect = "SELECT FROM INVOICE WHERE (INVOICE.COST>=:p1 AND INVOICE.COST<=:p2)";
$expect_params = array(
array('table' => 'INVOICE', 'column' => 'COST', 'value' => 1000),
array('table' => 'INVOICE', 'column' => 'COST', 'value' => 5000),
);
try {
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
} catch (PropelException $e) {
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ".$e->getMessage());
}
$this->assertEquals($expect, $result);
$this->assertEquals($expect_params, $params);
}
/**
* Verify that AND and OR criterion are nested correctly.
*/
public function testPrecedence()
{
$cn1 = $this->c->getNewCriterion("INVOICE.COST", "1000", Criteria::GREATER_EQUAL);
$cn2 = $this->c->getNewCriterion("INVOICE.COST", "2000", Criteria::LESS_EQUAL);
$cn3 = $this->c->getNewCriterion("INVOICE.COST", "8000", Criteria::GREATER_EQUAL);
$cn4 = $this->c->getNewCriterion("INVOICE.COST", "9000", Criteria::LESS_EQUAL);
$this->c->add($cn1->addAnd($cn2));
$this->c->addOr($cn3->addAnd($cn4));
$expect =
"SELECT FROM INVOICE WHERE ((INVOICE.COST>=:p1 AND INVOICE.COST<=:p2) OR (INVOICE.COST>=:p3 AND INVOICE.COST<=:p4))";
$expect_params = array(
array('table' => 'INVOICE', 'column' => 'COST', 'value' => '1000'),
array('table' => 'INVOICE', 'column' => 'COST', 'value' => '2000'),
array('table' => 'INVOICE', 'column' => 'COST', 'value' => '8000'),
array('table' => 'INVOICE', 'column' => 'COST', 'value' => '9000'),
);
try {
$params=array();
$result = BasePeer::createSelectSql($this->c, $params);
} catch (PropelException $e) {
$this->fail("PropelException thrown in BasePeer::createSelectSql()");
}
$this->assertEquals($expect, $result);
$this->assertEquals($expect_params, $params);
}
public function testCombineCriterionAndSimple()
{
$this->c->addCond('cond1', "INVOICE.COST", "1000", Criteria::GREATER_EQUAL);
$this->c->addCond('cond2', "INVOICE.COST", "2000", Criteria::LESS_EQUAL);
$this->c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_AND);
$expect = "SELECT FROM INVOICE WHERE (INVOICE.COST>=:p1 AND INVOICE.COST<=:p2)";
$expect_params = array(
array('table' => 'INVOICE', 'column' => 'COST', 'value' => '1000'),
array('table' => 'INVOICE', 'column' => 'COST', 'value' => '2000'),
);
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$this->assertEquals($expect, $result);
$this->assertEquals($expect_params, $params);
}
public function testCombineCriterionAndLessSimple()
{
$this->c->addCond('cond1', "INVOICE.COST1", "1000", Criteria::GREATER_EQUAL);
$this->c->addCond('cond2', "INVOICE.COST2", "2000", Criteria::LESS_EQUAL);
$this->c->add("INVOICE.COST3", "8000", Criteria::GREATER_EQUAL);
$this->c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_AND);
$this->c->add("INVOICE.COST4", "9000", Criteria::LESS_EQUAL);
$expect = "SELECT FROM INVOICE WHERE INVOICE.COST3>=:p1 AND (INVOICE.COST1>=:p2 AND INVOICE.COST2<=:p3) AND INVOICE.COST4<=:p4";
$expect_params = array(
array('table' => 'INVOICE', 'column' => 'COST3', 'value' => '8000'),
array('table' => 'INVOICE', 'column' => 'COST1', 'value' => '1000'),
array('table' => 'INVOICE', 'column' => 'COST2', 'value' => '2000'),
array('table' => 'INVOICE', 'column' => 'COST4', 'value' => '9000'),
);
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$this->assertEquals($expect, $result);
$this->assertEquals($expect_params, $params);
}
public function testCombineCriterionAndMultiple()
{
$this->c->addCond('cond1',"INVOICE.COST1", "1000", Criteria::GREATER_EQUAL);
$this->c->addCond('cond2', "INVOICE.COST2", "2000", Criteria::LESS_EQUAL);
$this->c->addCond('cond3', "INVOICE.COST3", "8000", Criteria::GREATER_EQUAL);
$this->c->addCond('cond4', "INVOICE.COST4", "9000", Criteria::LESS_EQUAL);
$this->c->combine(array('cond1', 'cond2', 'cond3', 'cond4'), Criteria::LOGICAL_AND);
$expect = "SELECT FROM INVOICE WHERE (((INVOICE.COST1>=:p1 AND INVOICE.COST2<=:p2) AND INVOICE.COST3>=:p3) AND INVOICE.COST4<=:p4)";
$expect_params = array(
array('table' => 'INVOICE', 'column' => 'COST1', 'value' => '1000'),
array('table' => 'INVOICE', 'column' => 'COST2', 'value' => '2000'),
array('table' => 'INVOICE', 'column' => 'COST3', 'value' => '8000'),
array('table' => 'INVOICE', 'column' => 'COST4', 'value' => '9000'),
);
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$this->assertEquals($expect, $result);
$this->assertEquals($expect_params, $params);
}
public function testCombineCriterionOrSimple()
{
$this->c->addCond('cond1', "INVOICE.COST", "1000", Criteria::GREATER_EQUAL);
$this->c->addCond('cond2', "INVOICE.COST", "2000", Criteria::LESS_EQUAL);
$this->c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_OR);
$expect = "SELECT FROM INVOICE WHERE (INVOICE.COST>=:p1 OR INVOICE.COST<=:p2)";
$expect_params = array(
array('table' => 'INVOICE', 'column' => 'COST', 'value' => '1000'),
array('table' => 'INVOICE', 'column' => 'COST', 'value' => '2000'),
);
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$this->assertEquals($expect, $result);
$this->assertEquals($expect_params, $params);
}
public function testCombineCriterionOrLessSimple()
{
$this->c->addCond('cond1', "INVOICE.COST1", "1000", Criteria::GREATER_EQUAL);
$this->c->addCond('cond2', "INVOICE.COST2", "2000", Criteria::LESS_EQUAL);
$this->c->add("INVOICE.COST3", "8000", Criteria::GREATER_EQUAL);
$this->c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_OR);
$this->c->addOr("INVOICE.COST4", "9000", Criteria::LESS_EQUAL);
$expect = "SELECT FROM INVOICE WHERE INVOICE.COST3>=:p1 AND ((INVOICE.COST1>=:p2 OR INVOICE.COST2<=:p3) OR INVOICE.COST4<=:p4)";
$expect_params = array(
array('table' => 'INVOICE', 'column' => 'COST3', 'value' => '8000'),
array('table' => 'INVOICE', 'column' => 'COST1', 'value' => '1000'),
array('table' => 'INVOICE', 'column' => 'COST2', 'value' => '2000'),
array('table' => 'INVOICE', 'column' => 'COST4', 'value' => '9000'),
);
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$this->assertEquals($expect, $result);
$this->assertEquals($expect_params, $params);
}
public function testCombineCriterionOrMultiple()
{
$this->c->addCond('cond1',"INVOICE.COST1", "1000", Criteria::GREATER_EQUAL);
$this->c->addCond('cond2', "INVOICE.COST2", "2000", Criteria::LESS_EQUAL);
$this->c->addCond('cond3', "INVOICE.COST3", "8000", Criteria::GREATER_EQUAL);
$this->c->addCond('cond4', "INVOICE.COST4", "9000", Criteria::LESS_EQUAL);
$this->c->combine(array('cond1', 'cond2', 'cond3', 'cond4'), Criteria::LOGICAL_OR);
$expect = "SELECT FROM INVOICE WHERE (((INVOICE.COST1>=:p1 OR INVOICE.COST2<=:p2) OR INVOICE.COST3>=:p3) OR INVOICE.COST4<=:p4)";
$expect_params = array(
array('table' => 'INVOICE', 'column' => 'COST1', 'value' => '1000'),
array('table' => 'INVOICE', 'column' => 'COST2', 'value' => '2000'),
array('table' => 'INVOICE', 'column' => 'COST3', 'value' => '8000'),
array('table' => 'INVOICE', 'column' => 'COST4', 'value' => '9000'),
);
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$this->assertEquals($expect, $result);
$this->assertEquals($expect_params, $params);
}
public function testCombineNamedCriterions()
{
$this->c->addCond('cond1', "INVOICE.COST1", "1000", Criteria::GREATER_EQUAL);
$this->c->addCond('cond2', "INVOICE.COST2", "2000", Criteria::LESS_EQUAL);
$this->c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_AND, 'cond12');
$this->c->addCond('cond3', "INVOICE.COST3", "8000", Criteria::GREATER_EQUAL);
$this->c->addCond('cond4', "INVOICE.COST4", "9000", Criteria::LESS_EQUAL);
$this->c->combine(array('cond3', 'cond4'), Criteria::LOGICAL_AND, 'cond34');
$this->c->combine(array('cond12', 'cond34'), Criteria::LOGICAL_OR);
$expect = "SELECT FROM INVOICE WHERE ((INVOICE.COST1>=:p1 AND INVOICE.COST2<=:p2) OR (INVOICE.COST3>=:p3 AND INVOICE.COST4<=:p4))";
$expect_params = array(
array('table' => 'INVOICE', 'column' => 'COST1', 'value' => '1000'),
array('table' => 'INVOICE', 'column' => 'COST2', 'value' => '2000'),
array('table' => 'INVOICE', 'column' => 'COST3', 'value' => '8000'),
array('table' => 'INVOICE', 'column' => 'COST4', 'value' => '9000'),
);
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$this->assertEquals($expect, $result);
$this->assertEquals($expect_params, $params);
}
public function testCombineDirtyOperators()
{
$this->c->addCond('cond1', "INVOICE.COST1", "1000", Criteria::GREATER_EQUAL);
$this->c->addCond('cond2', "INVOICE.COST2", "2000", Criteria::LESS_EQUAL);
$this->c->combine(array('cond1', 'cond2'), 'AnD', 'cond12');
$this->c->addCond('cond3', "INVOICE.COST3", "8000", Criteria::GREATER_EQUAL);
$this->c->addCond('cond4', "INVOICE.COST4", "9000", Criteria::LESS_EQUAL);
$this->c->combine(array('cond3', 'cond4'), 'aNd', 'cond34');
$this->c->combine(array('cond12', 'cond34'), 'oR');
$expect = "SELECT FROM INVOICE WHERE ((INVOICE.COST1>=:p1 AND INVOICE.COST2<=:p2) OR (INVOICE.COST3>=:p3 AND INVOICE.COST4<=:p4))";
$expect_params = array(
array('table' => 'INVOICE', 'column' => 'COST1', 'value' => '1000'),
array('table' => 'INVOICE', 'column' => 'COST2', 'value' => '2000'),
array('table' => 'INVOICE', 'column' => 'COST3', 'value' => '8000'),
array('table' => 'INVOICE', 'column' => 'COST4', 'value' => '9000'),
);
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$this->assertEquals($expect, $result);
$this->assertEquals($expect_params, $params);
}
}

View file

@ -0,0 +1,181 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/BaseTestCase.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/query/Criteria.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/util/PropelConditionalProxy.php';
/**
* Test class for Criteria fluid conditions.
*
* @author Francois Zaninotto
* @version $Id: CriteriaCombineTest.php 1347 2009-12-03 21:06:36Z francois $
* @package runtime.query
*/
class CriteriaFluidConditionTest extends BaseTestCase
{
public function testIf()
{
$f = new TestableCriteria();
$f->
_if(true)->
test()->
_endif();
$this->assertTrue($f->getTest(), '_if() executes the next method if the test is true');
$f = new TestableCriteria();
$f->
_if(false)->
foo()->
_endif();
$this->assertFalse($f->getTest(), '_if() does not check the existence of the next method if the test is false');
$f = new TestableCriteria();
$f->
_if(true)->
dummy()->
test()->
_endif();
$this->assertTrue($f->getTest(), '_if() executes the next methods until _endif() if the test is true');
$f = new TestableCriteria();
$f->
_if(false)->
dummy()->
test()->
_endif();
$this->assertFalse($f->getTest(), '_if() does not execute the next methods until _endif() if the test is false');
}
/**
* @expectedException PropelException
*/
public function testNestedIf()
{
$f = new TestableCriteria();
$f->
_if(false)->
_if(true)->
test()->
_endif();
}
public function testElseIf()
{
$f = new TestableCriteria();
$f->
_if(true)->
_elseif(true)->
test()->
_endif();
$this->assertFalse($f->getTest(), '_elseif() does not execute the next method if the main test is true');
$f = new TestableCriteria();
$f->
_if(true)->
_elseif(false)->
test()->
_endif();
$this->assertFalse($f->getTest(), '_elseif() does not execute the next method if the main test is true');
$f = new TestableCriteria();
$f->
_if(false)->
_elseif(true)->
test()->
_endif();
$this->assertTrue($f->getTest(), '_elseif() executes the next method if the main test is false and the elseif test is true');
$f = new TestableCriteria();
$f->
_if(false)->
_elseif(false)->
test()->
_endif();
$this->assertFalse($f->getTest(), '_elseif() does not execute the next method if the main test is false and the elseif test is false');
}
public function testElse()
{
$f = new TestableCriteria();
$f->
_if(true)->
_else()->
test()->
_endif();
$this->assertFalse($f->getTest(), '_else() does not execute the next method if the main test is true');
$f = new TestableCriteria();
$f->
_if(false)->
_else()->
test()->
_endif();
$this->assertTrue($f->getTest(), '_else() executes the next method if the main test is false');
$f = new TestableCriteria();
$f->
_if(false)->
_elseif(true)->
_else()->
test()->
_endif();
$this->assertFalse($f->getTest(), '_else() does not execute the next method if the previous test is true');
$f->
_if(false)->
_elseif(false)->
_else()->
test()->
_endif();
$this->assertTrue($f->getTest(), '_else() executes the next method if all the previous tests are false');
}
public function testEndif()
{
$f = new TestableCriteria();
$res = $f->
_if(true)->
test()->
_endif();
$this->assertEquals($res, $f, '_endif() returns the main object if the test is true');
$f = new TestableCriteria();
$res = $f->
_if(false)->
test()->
_endif();
$this->assertEquals($res, $f, '_endif() returns the main object if the test is false');
$f = new TestableCriteria();
$f->
_if(true)->
_endif()->
test();
$this->assertTrue($f->getTest(), '_endif() stops the condition check');
$f = new TestableCriteria();
$f->
_if(false)->
_endif()->
test();
$this->assertTrue($f->getTest(), '_endif() stops the condition check');
}
}
class TestableCriteria extends Criteria
{
protected $test = false;
public function test()
{
$this->test = true;
return $this;
}
public function dummy()
{
return $this;
}
public function getTest()
{
return $this->test;
}
}

View file

@ -0,0 +1,399 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/BaseTestCase.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/query/Criteria.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/util/BasePeer.php';
set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes");
Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php');
/**
* Test class for Criteria.
*
* @author <a href="mailto:celkins@scardini.com">Christopher Elkins</a>
* @author <a href="mailto:sam@neurogrid.com">Sam Joseph</a>
* @version $Id: CriteriaTest.php 1347 2009-12-03 21:06:36Z francois $
* @package runtime.query
*/
class CriteriaMergeTest extends BaseTestCase
{
protected function assertCriteriaTranslation($criteria, $expectedSql, $message = '')
{
$params = array();
$result = BasePeer::createSelectSql($criteria, $params);
$this->assertEquals($expectedSql, $result, $message);
}
public function testMergeWithLimit()
{
$c1 = new Criteria();
$c1->setLimit(123);
$c2 = new Criteria();
$c1->mergeWith($c2);
$this->assertEquals(123, $c1->getLimit(), 'mergeWith() does not remove an existing limit');
$c1 = new Criteria();
$c2 = new Criteria();
$c2->setLimit(123);
$c1->mergeWith($c2);
$this->assertEquals(123, $c1->getLimit(), 'mergeWith() merges the limit');
$c1 = new Criteria();
$c1->setLimit(456);
$c2 = new Criteria();
$c2->setLimit(123);
$c1->mergeWith($c2);
$this->assertEquals(456, $c1->getLimit(), 'mergeWith() does not merge the limit in case of conflict');
}
public function testMergeWithOffset()
{
$c1 = new Criteria();
$c1->setOffset(123);
$c2 = new Criteria();
$c1->mergeWith($c2);
$this->assertEquals(123, $c1->getOffset(), 'mergeWith() does not remove an existing offset');
$c1 = new Criteria();
$c2 = new Criteria();
$c2->setOffset(123);
$c1->mergeWith($c2);
$this->assertEquals(123, $c1->getOffset(), 'mergeWith() merges the offset');
$c1 = new Criteria();
$c1->setOffset(456);
$c2 = new Criteria();
$c2->setOffset(123);
$c1->mergeWith($c2);
$this->assertEquals(456, $c1->getOffset(), 'mergeWith() does not merge the offset in case of conflict');
}
public function testMergeWithSelectModifiers()
{
$c1 = new Criteria();
$c1->setDistinct();
$c2 = new Criteria();
$c1->mergeWith($c2);
$this->assertEquals(array(Criteria::DISTINCT), $c1->getSelectModifiers(), 'mergeWith() does not remove an existing select modifier');
$c1 = new Criteria();
$c2 = new Criteria();
$c2->setDistinct();
$c1->mergeWith($c2);
$this->assertEquals(array(Criteria::DISTINCT), $c1->getSelectModifiers(), 'mergeWith() merges the select modifiers');
$c1 = new Criteria();
$c1->setDistinct();
$c2 = new Criteria();
$c2->setDistinct();
$c1->mergeWith($c2);
$this->assertEquals(array(Criteria::DISTINCT), $c1->getSelectModifiers(), 'mergeWith() does not duplicate select modifiers');
$c1 = new Criteria();
$c1->setAll();
$c2 = new Criteria();
$c2->setDistinct();
$c1->mergeWith($c2);
$this->assertEquals(array(Criteria::ALL), $c1->getSelectModifiers(), 'mergeWith() does not merge the select modifiers in case of conflict');
}
public function testMergeWithSelectColumns()
{
$c1 = new Criteria();
$c1->addSelectColumn(BookPeer::TITLE);
$c1->addSelectColumn(BookPeer::ID);
$c2 = new Criteria();
$c1->mergeWith($c2);
$this->assertEquals(array(BookPeer::TITLE, BookPeer::ID), $c1->getSelectColumns(), 'mergeWith() does not remove an existing select columns');
$c1 = new Criteria();
$c2 = new Criteria();
$c2->addSelectColumn(BookPeer::TITLE);
$c2->addSelectColumn(BookPeer::ID);
$c1->mergeWith($c2);
$this->assertEquals(array(BookPeer::TITLE, BookPeer::ID), $c1->getSelectColumns(), 'mergeWith() merges the select columns to an empty select');
$c1 = new Criteria();
$c1->addSelectColumn(BookPeer::TITLE);
$c2 = new Criteria();
$c2->addSelectColumn(BookPeer::ID);
$c1->mergeWith($c2);
$this->assertEquals(array(BookPeer::TITLE, BookPeer::ID), $c1->getSelectColumns(), 'mergeWith() merges the select columns after the existing select columns');
$c1 = new Criteria();
$c1->addSelectColumn(BookPeer::TITLE);
$c2 = new Criteria();
$c2->addSelectColumn(BookPeer::TITLE);
$c1->mergeWith($c2);
$this->assertEquals(array(BookPeer::TITLE, BookPeer::TITLE), $c1->getSelectColumns(), 'mergeWith() merges the select columns to an existing select, even if duplicated');
}
public function testMergeWithAsColumns()
{
$c1 = new Criteria();
$c1->addAsColumn('foo', BookPeer::TITLE);
$c1->addAsColumn('bar', BookPeer::ID);
$c2 = new Criteria();
$c1->mergeWith($c2);
$this->assertEquals(array('foo' => BookPeer::TITLE, 'bar' => BookPeer::ID), $c1->getAsColumns(), 'mergeWith() does not remove an existing as columns');
$c1 = new Criteria();
$c2 = new Criteria();
$c2->addAsColumn('foo', BookPeer::TITLE);
$c2->addAsColumn('bar', BookPeer::ID);
$c1->mergeWith($c2);
$this->assertEquals(array('foo' => BookPeer::TITLE, 'bar' => BookPeer::ID), $c1->getAsColumns(), 'mergeWith() merges the select columns to an empty as');
$c1 = new Criteria();
$c1->addAsColumn('foo', BookPeer::TITLE);
$c2 = new Criteria();
$c2->addAsColumn('bar', BookPeer::ID);
$c1->mergeWith($c2);
$this->assertEquals(array('foo' => BookPeer::TITLE, 'bar' => BookPeer::ID), $c1->getAsColumns(), 'mergeWith() merges the select columns after the existing as columns');
}
/**
* @expectedException PropelException
*/
public function testMergeWithAsColumnsThrowsException()
{
$c1 = new Criteria();
$c1->addAsColumn('foo', BookPeer::TITLE);
$c2 = new Criteria();
$c2->addAsColumn('foo', BookPeer::ID);
$c1->mergeWith($c2);
}
public function testMergeWithOrderByColumns()
{
$c1 = new Criteria();
$c1->addAscendingOrderByColumn(BookPeer::TITLE);
$c1->addAscendingOrderByColumn(BookPeer::ID);
$c2 = new Criteria();
$c1->mergeWith($c2);
$this->assertEquals(array(BookPeer::TITLE . ' ASC', BookPeer::ID . ' ASC'), $c1->getOrderByColumns(), 'mergeWith() does not remove an existing orderby columns');
$c1 = new Criteria();
$c2 = new Criteria();
$c2->addAscendingOrderByColumn(BookPeer::TITLE);
$c2->addAscendingOrderByColumn(BookPeer::ID);
$c1->mergeWith($c2);
$this->assertEquals(array(BookPeer::TITLE . ' ASC', BookPeer::ID . ' ASC'), $c1->getOrderByColumns(), 'mergeWith() merges the select columns to an empty order by');
$c1 = new Criteria();
$c1->addAscendingOrderByColumn(BookPeer::TITLE);
$c2 = new Criteria();
$c2->addAscendingOrderByColumn(BookPeer::ID);
$c1->mergeWith($c2);
$this->assertEquals(array(BookPeer::TITLE . ' ASC', BookPeer::ID . ' ASC'), $c1->getOrderByColumns(), 'mergeWith() merges the select columns after the existing orderby columns');
$c1 = new Criteria();
$c1->addAscendingOrderByColumn(BookPeer::TITLE);
$c2 = new Criteria();
$c2->addAscendingOrderByColumn(BookPeer::TITLE);
$c1->mergeWith($c2);
$this->assertEquals(array(BookPeer::TITLE . ' ASC'), $c1->getOrderByColumns(), 'mergeWith() does not merge duplicated orderby columns');
$c1 = new Criteria();
$c1->addAscendingOrderByColumn(BookPeer::TITLE);
$c2 = new Criteria();
$c2->addDescendingOrderByColumn(BookPeer::TITLE);
$c1->mergeWith($c2);
$this->assertEquals(array(BookPeer::TITLE . ' ASC', BookPeer::TITLE . ' DESC'), $c1->getOrderByColumns(), 'mergeWith() merges duplicated orderby columns with inverse direction');
}
public function testMergeWithGroupByColumns()
{
$c1 = new Criteria();
$c1->addGroupByColumn(BookPeer::TITLE);
$c1->addGroupByColumn(BookPeer::ID);
$c2 = new Criteria();
$c1->mergeWith($c2);
$this->assertEquals(array(BookPeer::TITLE, BookPeer::ID), $c1->getGroupByColumns(), 'mergeWith() does not remove an existing groupby columns');
$c1 = new Criteria();
$c2 = new Criteria();
$c2->addGroupByColumn(BookPeer::TITLE);
$c2->addGroupByColumn(BookPeer::ID);
$c1->mergeWith($c2);
$this->assertEquals(array(BookPeer::TITLE, BookPeer::ID), $c1->getGroupByColumns(), 'mergeWith() merges the select columns to an empty groupby');
$c1 = new Criteria();
$c1->addGroupByColumn(BookPeer::TITLE);
$c2 = new Criteria();
$c2->addGroupByColumn(BookPeer::ID);
$c1->mergeWith($c2);
$this->assertEquals(array(BookPeer::TITLE, BookPeer::ID), $c1->getGroupByColumns(), 'mergeWith() merges the select columns after the existing groupby columns');
$c1 = new Criteria();
$c1->addGroupByColumn(BookPeer::TITLE);
$c2 = new Criteria();
$c2->addGroupByColumn(BookPeer::TITLE);
$c1->mergeWith($c2);
$this->assertEquals(array(BookPeer::TITLE), $c1->getGroupByColumns(), 'mergeWith() does not merge duplicated groupby columns');
}
public function testMergeWithWhereConditions()
{
$c1 = new Criteria();
$c1->add(BookPeer::TITLE, 'foo');
$c2 = new Criteria();
$c1->mergeWith($c2);
$sql = 'SELECT FROM `book` WHERE book.TITLE=:p1';
$this->assertCriteriaTranslation($c1, $sql, 'mergeWith() does not remove an existing where condition');
$c1 = new Criteria();
$c2 = new Criteria();
$c2->add(BookPeer::TITLE, 'foo');
$c1->mergeWith($c2);
$sql = 'SELECT FROM `book` WHERE book.TITLE=:p1';
$this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to an empty condition');
$c1 = new Criteria();
$c1->add(BookPeer::ID, 123);
$c2 = new Criteria();
$c2->add(BookPeer::TITLE, 'foo');
$c1->mergeWith($c2);
$sql = 'SELECT FROM `book` WHERE book.ID=:p1 AND book.TITLE=:p2';
$this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions');
$c1 = new Criteria();
$c1->add(BookPeer::TITLE, 'foo');
$c2 = new Criteria();
$c2->add(BookPeer::TITLE, 'bar');
$c1->mergeWith($c2);
$sql = 'SELECT FROM `book` WHERE (book.TITLE=:p1 AND book.TITLE=:p2)';
$this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions on the same column');
$c1 = new Criteria();
$c1->add(BookPeer::TITLE, 'foo');
$c1->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::LEFT_JOIN);
$c2 = new Criteria();
$c2->add(AuthorPeer::FIRST_NAME, 'bar');
$c1->mergeWith($c2);
$sql = 'SELECT FROM `book` LEFT JOIN author ON (book.AUTHOR_ID=author.ID) WHERE book.TITLE=:p1 AND author.FIRST_NAME=:p2';
$this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions on the different tables');
}
public function testMergeOrWithWhereConditions()
{
$c1 = new Criteria();
$c1->add(BookPeer::TITLE, 'foo');
$c2 = new Criteria();
$c1->mergeWith($c2, Criteria::LOGICAL_OR);
$sql = 'SELECT FROM `book` WHERE book.TITLE=:p1';
$this->assertCriteriaTranslation($c1, $sql, 'mergeWith() does not remove an existing where condition');
$c1 = new Criteria();
$c2 = new Criteria();
$c2->add(BookPeer::TITLE, 'foo');
$c1->mergeWith($c2, Criteria::LOGICAL_OR);
$sql = 'SELECT FROM `book` WHERE book.TITLE=:p1';
$this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to an empty condition');
$c1 = new Criteria();
$c1->add(BookPeer::ID, 123);
$c2 = new Criteria();
$c2->add(BookPeer::TITLE, 'foo');
$c1->mergeWith($c2, Criteria::LOGICAL_OR);
$sql = 'SELECT FROM `book` WHERE (book.ID=:p1 OR book.TITLE=:p2)';
$this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions');
$c1 = new Criteria();
$c1->add(BookPeer::TITLE, 'foo');
$c2 = new Criteria();
$c2->add(BookPeer::TITLE, 'bar');
$c1->mergeWith($c2, Criteria::LOGICAL_OR);
$sql = 'SELECT FROM `book` WHERE (book.TITLE=:p1 OR book.TITLE=:p2)';
$this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions on the same column');
$c1 = new Criteria();
$c1->add(BookPeer::TITLE, 'foo');
$c1->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::LEFT_JOIN);
$c2 = new Criteria();
$c2->add(AuthorPeer::FIRST_NAME, 'bar');
$c1->mergeWith($c2, Criteria::LOGICAL_OR);
$sql = 'SELECT FROM `book` LEFT JOIN author ON (book.AUTHOR_ID=author.ID) WHERE (book.TITLE=:p1 OR author.FIRST_NAME=:p2)';
$this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions on the different tables');
}
public function testMergeWithHavingConditions()
{
$c1 = new Criteria();
$cton = $c1->getNewCriterion(BookPeer::TITLE, 'foo', Criteria::EQUAL);
$c1->addHaving($cton);
$c2 = new Criteria();
$c1->mergeWith($c2);
$sql = 'SELECT FROM HAVING book.TITLE=:p1';
$this->assertCriteriaTranslation($c1, $sql, 'mergeWith() does not remove an existing having condition');
$c1 = new Criteria();
$c2 = new Criteria();
$cton = $c2->getNewCriterion(BookPeer::TITLE, 'foo', Criteria::EQUAL);
$c2->addHaving($cton);
$c1->mergeWith($c2);
$sql = 'SELECT FROM HAVING book.TITLE=:p1';
$this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges having condition to an empty having');
$c1 = new Criteria();
$cton = $c1->getNewCriterion(BookPeer::TITLE, 'foo', Criteria::EQUAL);
$c1->addHaving($cton);
$c2 = new Criteria();
$cton = $c2->getNewCriterion(BookPeer::TITLE, 'bar', Criteria::EQUAL);
$c2->addHaving($cton);
$c1->mergeWith($c2);
$sql = 'SELECT FROM HAVING (book.TITLE=:p1 AND book.TITLE=:p2)';
$this->assertCriteriaTranslation($c1, $sql, 'mergeWith() combines having with AND');
}
public function testMergeWithAliases()
{
$c1 = new Criteria();
$c1->addAlias('b', BookPeer::TABLE_NAME);
$c2 = new Criteria();
$c1->mergeWith($c2);
$this->assertEquals(array('b' => BookPeer::TABLE_NAME), $c1->getAliases(), 'mergeWith() does not remove an existing alias');
$c1 = new Criteria();
$c2 = new Criteria();
$c2->addAlias('a', AuthorPeer::TABLE_NAME);
$c1->mergeWith($c2);
$this->assertEquals(array('a' => AuthorPeer::TABLE_NAME), $c1->getAliases(), 'mergeWith() merge aliases to an empty alias');
$c1 = new Criteria();
$c1->addAlias('b', BookPeer::TABLE_NAME);
$c2 = new Criteria();
$c2->addAlias('a', AuthorPeer::TABLE_NAME);
$c1->mergeWith($c2);
$this->assertEquals(array('b' => BookPeer::TABLE_NAME, 'a' => AuthorPeer::TABLE_NAME), $c1->getAliases(), 'mergeWith() merge aliases to an existing alias');
}
/**
* @expectedException PropelException
*/
public function testMergeWithAliasesThrowsException()
{
$c1 = new Criteria();
$c1->addAlias('b', BookPeer::TABLE_NAME);
$c2 = new Criteria();
$c2->addAlias('b', AuthorPeer::TABLE_NAME);
$c1->mergeWith($c2);
}
public function testMergeWithJoins()
{
$c1 = new Criteria();
$c1->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::LEFT_JOIN);
$c2 = new Criteria();
$c1->mergeWith($c2);
$joins = $c1->getJoins();
$this->assertEquals(1, count($joins), 'mergeWith() does not remove an existing join');
$this->assertEquals('LEFT JOIN : book.AUTHOR_ID=author.ID(ignoreCase not considered)', $joins[0]->toString(), 'mergeWith() does not remove an existing join');
$c1 = new Criteria();
$c2 = new Criteria();
$c2->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::LEFT_JOIN);
$c1->mergeWith($c2);
$joins = $c1->getJoins();
$this->assertEquals(1, count($joins), 'mergeWith() merge joins to an empty join');
$this->assertEquals('LEFT JOIN : book.AUTHOR_ID=author.ID(ignoreCase not considered)', $joins[0]->toString(), 'mergeWith() merge joins to an empty join');
$c1 = new Criteria();
$c1->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::LEFT_JOIN);
$c2 = new Criteria();
$c2->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::INNER_JOIN);
$c1->mergeWith($c2);
$joins = $c1->getJoins();
$this->assertEquals(2, count($joins), 'mergeWith() merge joins to an existing join');
$this->assertEquals('LEFT JOIN : book.AUTHOR_ID=author.ID(ignoreCase not considered)', $joins[0]->toString(), 'mergeWith() merge joins to an empty join');
$this->assertEquals('INNER JOIN : book.PUBLISHER_ID=publisher.ID(ignoreCase not considered)', $joins[1]->toString(), 'mergeWith() merge joins to an empty join');
}
public function testMergeWithFurtherModified()
{
$c1 = new Criteria();
$c2 = new Criteria();
$c2->setLimit(123);
$c1->mergeWith($c2);
$this->assertEquals(123, $c1->getLimit(), 'mergeWith() makes the merge');
$c2->setLimit(456);
$this->assertEquals(123, $c1->getLimit(), 'further modifying a merged criteria does not affect the merger');
}
}

View file

@ -0,0 +1,974 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/BaseTestCase.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/query/Criteria.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/util/BasePeer.php';
set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes");
Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php');
/**
* Test class for Criteria.
*
* @author <a href="mailto:celkins@scardini.com">Christopher Elkins</a>
* @author <a href="mailto:sam@neurogrid.com">Sam Joseph</a>
* @version $Id: CriteriaTest.php 1773 2010-05-25 10:25:06Z francois $
* @package runtime.query
*/
class CriteriaTest extends BaseTestCase
{
/**
* The criteria to use in the test.
* @var Criteria
*/
private $c;
/**
* DB adapter saved for later.
*
* @var DBAdapter
*/
private $savedAdapter;
protected function setUp()
{
parent::setUp();
$this->c = new Criteria();
$this->savedAdapter = Propel::getDB(null);
Propel::setDB(null, new DBSQLite());
}
protected function tearDown()
{
Propel::setDB(null, $this->savedAdapter);
parent::tearDown();
}
/**
* Test basic adding of strings.
*/
public function testAddString()
{
$table = "myTable";
$column = "myColumn";
$value = "myValue";
// Add the string
$this->c->add($table . '.' . $column, $value);
// Verify that the key exists
$this->assertTrue($this->c->containsKey($table . '.' . $column));
// Verify that what we get out is what we put in
$this->assertTrue($this->c->getValue($table . '.' . $column) === $value);
}
public function testAddAndSameColumns()
{
$table1 = "myTable1";
$column1 = "myColumn1";
$value1 = "myValue1";
$key1 = "$table1.$column1";
$table2 = "myTable1";
$column2 = "myColumn1";
$value2 = "myValue2";
$key2 = "$table2.$column2";
$this->c->add($key1, $value1, Criteria::EQUAL);
$this->c->addAnd($key2, $value2, Criteria::EQUAL);
$expect = "SELECT FROM myTable1 WHERE (myTable1.myColumn1=:p1 AND myTable1.myColumn1=:p2)";
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$expect_params = array(
array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue1'),
array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue2'),
);
$this->assertEquals($expect, $result, 'addAnd() called on an existing column creates a combined criterion');
$this->assertEquals($expect_params, $params, 'addAnd() called on an existing column creates a combined criterion');
}
public function testAddAndSameColumnsPropel14Compatibility()
{
$table1 = "myTable1";
$column1 = "myColumn1";
$value1 = "myValue1";
$key1 = "$table1.$column1";
$table2 = "myTable1";
$column2 = "myColumn1";
$value2 = "myValue2";
$key2 = "$table2.$column2";
$table3 = "myTable3";
$column3 = "myColumn3";
$value3 = "myValue3";
$key3 = "$table3.$column3";
$this->c->add($key1, $value1, Criteria::EQUAL);
$this->c->add($key3, $value3, Criteria::EQUAL);
$this->c->addAnd($key2, $value2, Criteria::EQUAL);
$expect = "SELECT FROM myTable1, myTable3 WHERE (myTable1.myColumn1=:p1 AND myTable1.myColumn1=:p2) AND myTable3.myColumn3=:p3";
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$expect_params = array(
array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue1'),
array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue2'),
array('table' => 'myTable3', 'column' => 'myColumn3', 'value' => 'myValue3'),
);
$this->assertEquals($expect, $result, 'addAnd() called on an existing column creates a combined criterion');
$this->assertEquals($expect_params, $params, 'addAnd() called on an existing column creates a combined criterion');
}
public function testAddAndDistinctColumns()
{
$table1 = "myTable1";
$column1 = "myColumn1";
$value1 = "myValue1";
$key1 = "$table1.$column1";
$table2 = "myTable2";
$column2 = "myColumn2";
$value2 = "myValue2";
$key2 = "$table2.$column2";
$this->c->add($key1, $value1, Criteria::EQUAL);
$this->c->addAnd($key2, $value2, Criteria::EQUAL);
$expect = "SELECT FROM myTable1, myTable2 WHERE myTable1.myColumn1=:p1 AND myTable2.myColumn2=:p2";
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$expect_params = array(
array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue1'),
array('table' => 'myTable2', 'column' => 'myColumn2', 'value' => 'myValue2'),
);
$this->assertEquals($expect, $result, 'addAnd() called on a distinct column adds a criterion to the criteria');
$this->assertEquals($expect_params, $params, 'addAnd() called on a distinct column adds a criterion to the criteria');
}
public function testAddOrSameColumns()
{
$table1 = "myTable1";
$column1 = "myColumn1";
$value1 = "myValue1";
$key1 = "$table1.$column1";
$table2 = "myTable1";
$column2 = "myColumn1";
$value2 = "myValue2";
$key2 = "$table2.$column2";
$this->c->add($key1, $value1, Criteria::EQUAL);
$this->c->addOr($key2, $value2, Criteria::EQUAL);
$expect = "SELECT FROM myTable1 WHERE (myTable1.myColumn1=:p1 OR myTable1.myColumn1=:p2)";
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$expect_params = array(
array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue1'),
array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue2'),
);
$this->assertEquals($expect, $result, 'addOr() called on an existing column creates a combined criterion');
$this->assertEquals($expect_params, $params, 'addOr() called on an existing column creates a combined criterion');
}
public function testAddAndOrColumnsPropel14Compatibility()
{
$table1 = "myTable1";
$column1 = "myColumn1";
$value1 = "myValue1";
$key1 = "$table1.$column1";
$table2 = "myTable1";
$column2 = "myColumn1";
$value2 = "myValue2";
$key2 = "$table2.$column2";
$table3 = "myTable3";
$column3 = "myColumn3";
$value3 = "myValue3";
$key3 = "$table3.$column3";
$this->c->add($key1, $value1, Criteria::EQUAL);
$this->c->add($key3, $value3, Criteria::EQUAL);
$this->c->addOr($key2, $value2, Criteria::EQUAL);
$expect = "SELECT FROM myTable1, myTable3 WHERE (myTable1.myColumn1=:p1 OR myTable1.myColumn1=:p2) AND myTable3.myColumn3=:p3";
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$expect_params = array(
array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue1'),
array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue2'),
array('table' => 'myTable3', 'column' => 'myColumn3', 'value' => 'myValue3'),
);
$this->assertEquals($expect, $result, 'addOr() called on an existing column creates a combined criterion');
$this->assertEquals($expect_params, $params, 'addOr() called on an existing column creates a combined criterion');
}
public function testAddOrDistinctColumns()
{
$table1 = "myTable1";
$column1 = "myColumn1";
$value1 = "myValue1";
$key1 = "$table1.$column1";
$table2 = "myTable2";
$column2 = "myColumn2";
$value2 = "myValue2";
$key2 = "$table2.$column2";
$this->c->add($key1, $value1, Criteria::EQUAL);
$this->c->addOr($key2, $value2, Criteria::EQUAL);
$expect = "SELECT FROM myTable1, myTable2 WHERE (myTable1.myColumn1=:p1 OR myTable2.myColumn2=:p2)";
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$expect_params = array(
array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue1'),
array('table' => 'myTable2', 'column' => 'myColumn2', 'value' => 'myValue2'),
);
$this->assertEquals($expect, $result, 'addOr() called on a distinct column adds a criterion to the latest criterion');
$this->assertEquals($expect_params, $params, 'addOr() called on a distinct column adds a criterion to the latest criterion');
}
public function testAddOrEmptyCriteria()
{
$table1 = "myTable1";
$column1 = "myColumn1";
$value1 = "myValue1";
$key1 = "$table1.$column1";
$this->c->addOr($key1, $value1, Criteria::EQUAL);
$expect = "SELECT FROM myTable1 WHERE myTable1.myColumn1=:p1";
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
$expect_params = array(
array('table' => 'myTable1', 'column' => 'myColumn1', 'value' => 'myValue1'),
);
$this->assertEquals($expect, $result, 'addOr() called on an empty Criteria adds a criterion to the criteria');
$this->assertEquals($expect_params, $params, 'addOr() called on an empty Criteria adds a criterion to the criteria');
}
/**
* Test Criterion.setIgnoreCase().
* As the output is db specific the test just prints the result to
* System.out
*/
public function testCriterionIgnoreCase()
{
$originalDB = Propel::getDB();
$adapters = array(new DBMySQL(), new DBPostgres());
$expectedIgnore = array("UPPER(TABLE.COLUMN) LIKE UPPER(:p1)", "TABLE.COLUMN ILIKE :p1");
$i =0;
foreach ($adapters as $adapter) {
Propel::setDB(null, $adapter);
$myCriteria = new Criteria();
$myCriterion = $myCriteria->getNewCriterion(
"TABLE.COLUMN", "FoObAr", Criteria::LIKE);
$sb = "";
$params=array();
$myCriterion->appendPsTo($sb, $params);
$expected = "TABLE.COLUMN LIKE :p1";
$this->assertEquals($expected, $sb);
$ignoreCriterion = $myCriterion->setIgnoreCase(true);
$sb = "";
$params=array();
$ignoreCriterion->appendPsTo($sb, $params);
// $expected = "UPPER(TABLE.COLUMN) LIKE UPPER(?)";
$this->assertEquals($expectedIgnore[$i], $sb);
$i++;
}
Propel::setDB(null, $originalDB);
}
public function testOrderByIgnoreCase()
{
$originalDB = Propel::getDB();
Propel::setDB(null, new DBMySQL());
$criteria = new Criteria();
$criteria->setIgnoreCase(true);
$criteria->addAscendingOrderByColumn(BookPeer::TITLE);
BookPeer::addSelectColumns($criteria);
$params=array();
$sql = BasePeer::createSelectSql($criteria, $params);
$expectedSQL = 'SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID, UPPER(book.TITLE) FROM `book` ORDER BY UPPER(book.TITLE) ASC';
$this->assertEquals($expectedSQL, $sql);
Propel::setDB(null, $originalDB);
}
/**
* Test that true is evaluated correctly.
*/
public function testBoolean()
{
$this->c = new Criteria();
$this->c->add("TABLE.COLUMN", true);
$expect = "SELECT FROM TABLE WHERE TABLE.COLUMN=:p1";
$expect_params = array( array('table' => 'TABLE', 'column' => 'COLUMN', 'value' => true),
);
try {
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
} catch (PropelException $e) {
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage());
}
$this->assertEquals($expect, $result, "Boolean test failed.");
$this->assertEquals($expect_params, $params);
}
public function testCurrentDate()
{
$this->c = new Criteria();
$this->c->add("TABLE.TIME_COLUMN", Criteria::CURRENT_TIME);
$this->c->add("TABLE.DATE_COLUMN", Criteria::CURRENT_DATE);
$expect = "SELECT FROM TABLE WHERE TABLE.TIME_COLUMN=CURRENT_TIME AND TABLE.DATE_COLUMN=CURRENT_DATE";
$result = null;
try {
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
} catch (PropelException $e) {
print $e->getTraceAsString();
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage());
}
$this->assertEquals($expect, $result, "Current date test failed!");
}
public function testCountAster()
{
$this->c = new Criteria();
$this->c->addSelectColumn("COUNT(*)");
$this->c->add("TABLE.TIME_COLUMN", Criteria::CURRENT_TIME);
$this->c->add("TABLE.DATE_COLUMN", Criteria::CURRENT_DATE);
$expect = "SELECT COUNT(*) FROM TABLE WHERE TABLE.TIME_COLUMN=CURRENT_TIME AND TABLE.DATE_COLUMN=CURRENT_DATE";
$result = null;
try {
$params = array();
$result = BasePeer::createSelectSql($this->c, $params);
} catch (PropelException $e) {
print $e->getTraceAsString();
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage());
}
$this->assertEquals($expect, $result);
}
public function testIn()
{
$c = new Criteria();
$c->addSelectColumn("*");
$c->add("TABLE.SOME_COLUMN", array(), Criteria::IN);
$c->add("TABLE.OTHER_COLUMN", array(1, 2, 3), Criteria::IN);
$expect = "SELECT * FROM TABLE WHERE 1<>1 AND TABLE.OTHER_COLUMN IN (:p1,:p2,:p3)";
try {
$params = array();
$result = BasePeer::createSelectSql($c, $params);
} catch (PropelException $e) {
print $e->getTraceAsString();
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage());
}
$this->assertEquals($expect, $result);
}
public function testInEmptyAfterFull()
{
$c = new Criteria();
$c->addSelectColumn("*");
$c->add("TABLE.OTHER_COLUMN", array(1, 2, 3), Criteria::IN);
$c->add("TABLE.SOME_COLUMN", array(), Criteria::IN);
$expect = "SELECT * FROM TABLE WHERE TABLE.OTHER_COLUMN IN (:p1,:p2,:p3) AND 1<>1";
try {
$params = array();
$result = BasePeer::createSelectSql($c, $params);
} catch (PropelException $e) {
print $e->getTraceAsString();
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage());
}
$this->assertEquals($expect, $result);
}
public function testInNested()
{
// now do a nested logic test, just for sanity (not that this should be any surprise)
$c = new Criteria();
$c->addSelectColumn("*");
$myCriterion = $c->getNewCriterion("TABLE.COLUMN", array(), Criteria::IN);
$myCriterion->addOr($c->getNewCriterion("TABLE.COLUMN2", array(1,2), Criteria::IN));
$c->add($myCriterion);
$expect = "SELECT * FROM TABLE WHERE (1<>1 OR TABLE.COLUMN2 IN (:p1,:p2))";
try {
$params = array();
$result = BasePeer::createSelectSql($c, $params);
} catch (PropelException $e) {
print $e->getTraceAsString();
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage());
}
$this->assertEquals($expect, $result);
}
public function testJoinObject ()
{
$j = new Join('TABLE_A.COL_1', 'TABLE_B.COL_2');
$this->assertEquals(null, $j->getJoinType());
$this->assertEquals('TABLE_A.COL_1', $j->getLeftColumn());
$this->assertEquals('TABLE_A', $j->getLeftTableName());
$this->assertEquals('COL_1', $j->getLeftColumnName());
$this->assertEquals('TABLE_B.COL_2', $j->getRightColumn());
$this->assertEquals('TABLE_B', $j->getRightTableName());
$this->assertEquals('COL_2', $j->getRightColumnName());
$j = new Join('TABLE_A.COL_1', 'TABLE_B.COL_1', Criteria::LEFT_JOIN);
$this->assertEquals('LEFT JOIN', $j->getJoinType());
$this->assertEquals('TABLE_A.COL_1', $j->getLeftColumn());
$this->assertEquals('TABLE_B.COL_1', $j->getRightColumn());
$j = new Join('TABLE_A.COL_1', 'TABLE_B.COL_1', Criteria::RIGHT_JOIN);
$this->assertEquals('RIGHT JOIN', $j->getJoinType());
$this->assertEquals('TABLE_A.COL_1', $j->getLeftColumn());
$this->assertEquals('TABLE_B.COL_1', $j->getRightColumn());
$j = new Join('TABLE_A.COL_1', 'TABLE_B.COL_1', Criteria::INNER_JOIN);
$this->assertEquals('INNER JOIN', $j->getJoinType());
$this->assertEquals('TABLE_A.COL_1', $j->getLeftColumn());
$this->assertEquals('TABLE_B.COL_1', $j->getRightColumn());
$j = new Join(array('TABLE_A.COL_1', 'TABLE_A.COL_2'), array('TABLE_B.COL_1', 'TABLE_B.COL_2'), Criteria::INNER_JOIN);
$this->assertEquals('TABLE_A.COL_1', $j->getLeftColumn(0));
$this->assertEquals('TABLE_A.COL_2', $j->getLeftColumn(1));
$this->assertEquals('TABLE_B.COL_1', $j->getRightColumn(0));
$this->assertEquals('TABLE_B.COL_2', $j->getRightColumn(1));
}
public function testAddStraightJoin ()
{
$c = new Criteria();
$c->addSelectColumn("*");
$c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_1'); // straight join
$expect = "SELECT * FROM TABLE_A, TABLE_B WHERE TABLE_A.COL_1=TABLE_B.COL_1";
try {
$params = array();
$result = BasePeer::createSelectSql($c, $params);
} catch (PropelException $e) {
print $e->getTraceAsString();
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage());
}
$this->assertEquals($expect, $result);
}
public function testAddSeveralJoins ()
{
$c = new Criteria();
$c->addSelectColumn("*");
$c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_1');
$c->addJoin('TABLE_B.COL_X', 'TABLE_D.COL_X');
$expect = 'SELECT * FROM TABLE_A, TABLE_B, TABLE_D '
.'WHERE TABLE_A.COL_1=TABLE_B.COL_1 AND TABLE_B.COL_X=TABLE_D.COL_X';
try {
$params = array();
$result = BasePeer::createSelectSql($c, $params);
} catch (PropelException $e) {
print $e->getTraceAsString();
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage());
}
$this->assertEquals($expect, $result);
}
public function testAddLeftJoin ()
{
$c = new Criteria();
$c->addSelectColumn("TABLE_A.*");
$c->addSelectColumn("TABLE_B.*");
$c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_2', Criteria::LEFT_JOIN);
$expect = "SELECT TABLE_A.*, TABLE_B.* FROM TABLE_A LEFT JOIN TABLE_B ON (TABLE_A.COL_1=TABLE_B.COL_2)";
try {
$params = array();
$result = BasePeer::createSelectSql($c, $params);
} catch (PropelException $e) {
print $e->getTraceAsString();
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage());
}
$this->assertEquals($expect, $result);
}
public function testAddSeveralLeftJoins ()
{
// Fails.. Suspect answer in the chunk starting at BasePeer:605
$c = new Criteria();
$c->addSelectColumn('*');
$c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_1', Criteria::LEFT_JOIN);
$c->addJoin('TABLE_A.COL_2', 'TABLE_C.COL_2', Criteria::LEFT_JOIN);
$expect = 'SELECT * FROM TABLE_A '
.'LEFT JOIN TABLE_B ON (TABLE_A.COL_1=TABLE_B.COL_1) '
.'LEFT JOIN TABLE_C ON (TABLE_A.COL_2=TABLE_C.COL_2)';
try {
$params = array();
$result = BasePeer::createSelectSql($c, $params);
} catch (PropelException $e) {
print $e->getTraceAsString();
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage());
}
$this->assertEquals($expect, $result);
}
public function testAddRightJoin ()
{
$c = new Criteria();
$c->addSelectColumn("*");
$c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_2', Criteria::RIGHT_JOIN);
$expect = "SELECT * FROM TABLE_A RIGHT JOIN TABLE_B ON (TABLE_A.COL_1=TABLE_B.COL_2)";
try {
$params = array();
$result = BasePeer::createSelectSql($c, $params);
} catch (PropelException $e) {
print $e->getTraceAsString();
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage());
}
$this->assertEquals($expect, $result);
}
public function testAddSeveralRightJoins ()
{
// Fails.. Suspect answer in the chunk starting at BasePeer:605
$c = new Criteria();
$c->addSelectColumn('*');
$c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_1', Criteria::RIGHT_JOIN);
$c->addJoin('TABLE_A.COL_2', 'TABLE_C.COL_2', Criteria::RIGHT_JOIN);
$expect = 'SELECT * FROM TABLE_A '
.'RIGHT JOIN TABLE_B ON (TABLE_A.COL_1=TABLE_B.COL_1) '
.'RIGHT JOIN TABLE_C ON (TABLE_A.COL_2=TABLE_C.COL_2)';
try {
$params = array();
$result = BasePeer::createSelectSql($c, $params);
} catch (PropelException $e) {
print $e->getTraceAsString();
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage());
}
$this->assertEquals($expect, $result);
}
public function testAddInnerJoin ()
{
$c = new Criteria();
$c->addSelectColumn("*");
$c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_1', Criteria::INNER_JOIN);
$expect = "SELECT * FROM TABLE_A INNER JOIN TABLE_B ON (TABLE_A.COL_1=TABLE_B.COL_1)";
try {
$params = array();
$result = BasePeer::createSelectSql($c, $params);
} catch (PropelException $e) {
print $e->getTraceAsString();
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage());
}
$this->assertEquals($expect, $result);
}
public function testAddSeveralInnerJoin ()
{
$c = new Criteria();
$c->addSelectColumn("*");
$c->addJoin('TABLE_A.COL_1', 'TABLE_B.COL_1', Criteria::INNER_JOIN);
$c->addJoin('TABLE_B.COL_1', 'TABLE_C.COL_1', Criteria::INNER_JOIN);
$expect = 'SELECT * FROM TABLE_A '
.'INNER JOIN TABLE_B ON (TABLE_A.COL_1=TABLE_B.COL_1) '
.'INNER JOIN TABLE_C ON (TABLE_B.COL_1=TABLE_C.COL_1)';
try {
$params = array();
$result = BasePeer::createSelectSql($c, $params);
} catch (PropelException $e) {
print $e->getTraceAsString();
$this->fail("PropelException thrown in BasePeer.createSelectSql(): ". $e->getMessage());
}
$this->assertEquals($expect, $result);
}
/**
* @link http://propel.phpdb.org/trac/ticket/451
*/
public function testSeveralMixedJoinOrders()
{
$c = new Criteria();
$c->clearSelectColumns()->
addJoin("TABLE_A.FOO_ID", "TABLE_B.ID", Criteria::LEFT_JOIN)->
addJoin("TABLE_A.BAR_ID", "TABLE_C.ID")->
addSelectColumn("TABLE_A.ID");
# These are no longer different, see http://propel.phpdb.org/trac/ticket/283#comment:8
#$db = Propel::getDB();
#
#if ($db instanceof DBMySQL) {
# $expect = 'SELECT TABLE_A.ID FROM (TABLE_A CROSS JOIN TABLE_C)'
# .' LEFT JOIN TABLE_B ON (TABLE_A.FOO_ID=TABLE_B.ID) WHERE TABLE_A.BAR_ID=TABLE_C.ID';
#} else {
$expect = 'SELECT TABLE_A.ID FROM TABLE_A CROSS JOIN TABLE_C'
.' LEFT JOIN TABLE_B ON (TABLE_A.FOO_ID=TABLE_B.ID) WHERE TABLE_A.BAR_ID=TABLE_C.ID';
#}
$params = array();
$result = BasePeer::createSelectSql($c, $params);
$this->assertEquals($expect, $result);
}
/**
* @link http://propel.phpdb.org/trac/ticket/606
*/
public function testAddJoinArray()
{
$c = new Criteria();
$c->clearSelectColumns()->
addJoin(array('TABLE_A.FOO_ID'), array('TABLE_B.ID'), Criteria::LEFT_JOIN)->
addSelectColumn("TABLE_A.ID");
$expect = 'SELECT TABLE_A.ID FROM TABLE_A'
.' LEFT JOIN TABLE_B ON (TABLE_A.FOO_ID=TABLE_B.ID)';
$params = array();
$result = BasePeer::createSelectSql($c, $params);
$this->assertEquals($expect, $result);
}
/**
* @link http://propel.phpdb.org/trac/ticket/606
*/
public function testAddJoinArrayMultiple()
{
$c = new Criteria();
$c->clearSelectColumns()->
addJoin(
array('TABLE_A.FOO_ID', 'TABLE_A.BAR'),
array('TABLE_B.ID', 'TABLE_B.BAZ'),
Criteria::LEFT_JOIN)->
addSelectColumn("TABLE_A.ID");
$expect = 'SELECT TABLE_A.ID FROM TABLE_A'
.' LEFT JOIN TABLE_B ON (TABLE_A.FOO_ID=TABLE_B.ID AND TABLE_A.BAR=TABLE_B.BAZ)';
$params = array();
$result = BasePeer::createSelectSql($c, $params);
$this->assertEquals($expect, $result);
}
/**
* Test the Criteria::addJoinMultiple() method with an implicit join
*
* @link http://propel.phpdb.org/trac/ticket/606
*/
public function testAddJoinMultiple()
{
$c = new Criteria();
$c->
clearSelectColumns()->
addMultipleJoin(array(
array('TABLE_A.FOO_ID', 'TABLE_B.ID'),
array('TABLE_A.BAR', 'TABLE_B.BAZ')))->
addSelectColumn("TABLE_A.ID");
$expect = 'SELECT TABLE_A.ID FROM TABLE_A, TABLE_B '
. 'WHERE TABLE_A.FOO_ID=TABLE_B.ID AND TABLE_A.BAR=TABLE_B.BAZ';
$params = array();
$result = BasePeer::createSelectSql($c, $params);
$this->assertEquals($expect, $result);
}
/**
* Test the Criteria::addJoinMultiple() method with a value as second argument
*
* @link http://propel.phpdb.org/trac/ticket/606
*/
public function testAddJoinMultipleValue()
{
$c = new Criteria();
$c->
clearSelectColumns()->
addMultipleJoin(array(
array('TABLE_A.FOO_ID', 'TABLE_B.ID'),
array('TABLE_A.BAR', 3)))->
addSelectColumn("TABLE_A.ID");
$expect = 'SELECT TABLE_A.ID FROM TABLE_A, TABLE_B '
. 'WHERE TABLE_A.FOO_ID=TABLE_B.ID AND TABLE_A.BAR=3';
$params = array();
$result = BasePeer::createSelectSql($c, $params);
$this->assertEquals($expect, $result);
}
/**
* Test the Criteria::addJoinMultiple() method with a joinType
*
* @link http://propel.phpdb.org/trac/ticket/606
*/
public function testAddJoinMultipleWithJoinType()
{
$c = new Criteria();
$c->
clearSelectColumns()->
addMultipleJoin(array(
array('TABLE_A.FOO_ID', 'TABLE_B.ID'),
array('TABLE_A.BAR', 'TABLE_B.BAZ')),
Criteria::LEFT_JOIN)->
addSelectColumn("TABLE_A.ID");
$expect = 'SELECT TABLE_A.ID FROM TABLE_A '
. 'LEFT JOIN TABLE_B ON (TABLE_A.FOO_ID=TABLE_B.ID AND TABLE_A.BAR=TABLE_B.BAZ)';
$params = array();
$result = BasePeer::createSelectSql($c, $params);
$this->assertEquals($expect, $result);
}
/**
* Test the Criteria::addJoinMultiple() method with operator
*
* @link http://propel.phpdb.org/trac/ticket/606
*/
public function testAddJoinMultipleWithOperator()
{
$c = new Criteria();
$c->
clearSelectColumns()->
addMultipleJoin(array(
array('TABLE_A.FOO_ID', 'TABLE_B.ID', Criteria::GREATER_EQUAL),
array('TABLE_A.BAR', 'TABLE_B.BAZ', Criteria::LESS_THAN)))->
addSelectColumn("TABLE_A.ID");
$expect = 'SELECT TABLE_A.ID FROM TABLE_A, TABLE_B '
. 'WHERE TABLE_A.FOO_ID>=TABLE_B.ID AND TABLE_A.BAR<TABLE_B.BAZ';
$params = array();
$result = BasePeer::createSelectSql($c, $params);
$this->assertEquals($expect, $result);
}
/**
* Test the Criteria::addJoinMultiple() method with join type and operator
*
* @link http://propel.phpdb.org/trac/ticket/606
*/
public function testAddJoinMultipleWithJoinTypeAndOperator()
{
$c = new Criteria();
$c->
clearSelectColumns()->
addMultipleJoin(array(
array('TABLE_A.FOO_ID', 'TABLE_B.ID', Criteria::GREATER_EQUAL),
array('TABLE_A.BAR', 'TABLE_B.BAZ', Criteria::LESS_THAN)),
Criteria::LEFT_JOIN)->
addSelectColumn("TABLE_A.ID");
$expect = 'SELECT TABLE_A.ID FROM TABLE_A '
. 'LEFT JOIN TABLE_B ON (TABLE_A.FOO_ID>=TABLE_B.ID AND TABLE_A.BAR<TABLE_B.BAZ)';
$params = array();
$result = BasePeer::createSelectSql($c, $params);
$this->assertEquals($expect, $result);
}
/**
* Test the Criteria::CUSTOM behavior.
*/
public function testCustomOperator()
{
$c = new Criteria();
$c->addSelectColumn('A.COL');
$c->add('A.COL', 'date_part(\'YYYY\', A.COL) = \'2007\'', Criteria::CUSTOM);
$expected = "SELECT A.COL FROM A WHERE date_part('YYYY', A.COL) = '2007'";
$params = array();
$result = BasePeer::createSelectSql($c, $params);
$this->assertEquals($expected, $result);
}
/**
* Tests adding duplicate joins.
* @link http://propel.phpdb.org/trac/ticket/613
*/
public function testAddJoin_Duplicate()
{
$c = new Criteria();
$c->addJoin("tbl.COL1", "tbl.COL2", Criteria::LEFT_JOIN);
$c->addJoin("tbl.COL1", "tbl.COL2", Criteria::LEFT_JOIN);
$this->assertEquals(1, count($c->getJoins()), "Expected not to have duplciate LJOIN added.");
$c->addJoin("tbl.COL1", "tbl.COL2", Criteria::RIGHT_JOIN);
$c->addJoin("tbl.COL1", "tbl.COL2", Criteria::RIGHT_JOIN);
$this->assertEquals(2, count($c->getJoins()), "Expected 1 new right join to be added.");
$c->addJoin("tbl.COL1", "tbl.COL2");
$c->addJoin("tbl.COL1", "tbl.COL2");
$this->assertEquals(3, count($c->getJoins()), "Expected 1 new implicit join to be added.");
$c->addJoin("tbl.COL3", "tbl.COL4");
$this->assertEquals(4, count($c->getJoins()), "Expected new col join to be added.");
}
/**
* @link http://propel.phpdb.org/trac/ticket/634
*/
public function testHasSelectClause()
{
$c = new Criteria();
$c->addSelectColumn("foo");
$this->assertTrue($c->hasSelectClause());
$c = new Criteria();
$c->addAsColumn("foo", "bar");
$this->assertTrue($c->hasSelectClause());
}
/**
* Tests including aliases in criterion objects.
* @link http://propel.phpdb.org/trac/ticket/636
*/
public function testAliasInCriterion()
{
$c = new Criteria();
$c->addAsColumn("column_alias", "tbl.COL1");
$crit = $c->getNewCriterion("column_alias", "FOO");
$this->assertNull($crit->getTable());
$this->assertEquals("column_alias", $crit->getColumn());
$c->addHaving($crit); // produces invalid SQL referring to '.olumn_alias'
}
/**
* Test whether GROUP BY is being respected in equals() check.
* @link http://propel.phpdb.org/trac/ticket/674
*/
public function testEqualsGroupBy()
{
$c1 = new Criteria();
$c1->addGroupByColumn('GBY1');
$c2 = new Criteria();
$c2->addGroupByColumn('GBY2');
$this->assertFalse($c2->equals($c1), "Expected Criteria NOT to be the same with different GROUP BY columns");
$c3 = new Criteria();
$c3->addGroupByColumn('GBY1');
$c4 = new Criteria();
$c4->addGroupByColumn('GBY1');
$this->assertTrue($c4->equals($c3), "Expected Criteria objects to match.");
}
/**
* Test whether calling setDistinct twice puts in two distinct keywords or not.
* @link http://propel.phpdb.org/trac/ticket/716
*/
public function testDoubleSelectModifiers()
{
$c = new Criteria();
$c->setDistinct();
$this->assertEquals(array(Criteria::DISTINCT), $c->getSelectModifiers(), 'Initial setDistinct works');
$c->setDistinct();
$this->assertEquals(array(Criteria::DISTINCT), $c->getSelectModifiers(), 'Calling setDistinct again leaves a single distinct');
$c->setAll();
$this->assertEquals(array(Criteria::ALL), $c->getSelectModifiers(), 'All keyword is swaps distinct out');
$c->setAll();
$this->assertEquals(array(Criteria::ALL), $c->getSelectModifiers(), 'Calling setAll leaves a single all');
$c->setDistinct();
$this->assertEquals(array(Criteria::DISTINCT), $c->getSelectModifiers(), 'All back to distinct works');
$c2 = new Criteria();
$c2->setAll();
$this->assertEquals(array(Criteria::ALL), $c2->getSelectModifiers(), 'Initial setAll works');
}
public function testAddSelectModifier()
{
$c = new Criteria();
$c->setDistinct();
$c->addSelectModifier('SQL_CALC_FOUND_ROWS');
$this->assertEquals(array(Criteria::DISTINCT, 'SQL_CALC_FOUND_ROWS'), $c->getSelectModifiers(), 'addSelectModifier() adds a select modifier to the Criteria');
$c->addSelectModifier('SQL_CALC_FOUND_ROWS');
$this->assertEquals(array(Criteria::DISTINCT, 'SQL_CALC_FOUND_ROWS'), $c->getSelectModifiers(), 'addSelectModifier() adds a select modifier only once');
$params = array();
$result = BasePeer::createSelectSql($c, $params);
$this->assertEquals('SELECT DISTINCT SQL_CALC_FOUND_ROWS FROM ', $result, 'addSelectModifier() adds a modifier to the final query');
}
public function testClone()
{
$c1 = new Criteria();
$c1->add('tbl.COL1', 'foo', Criteria::EQUAL);
$c2 = clone $c1;
$c2->addAnd('tbl.COL1', 'bar', Criteria::EQUAL);
$nbCrit = 0;
foreach ($c1->keys() as $key) {
foreach ($c1->getCriterion($key)->getAttachedCriterion() as $criterion) {
$nbCrit++;
}
}
$this->assertEquals(1, $nbCrit, 'cloning a Criteria clones its Criterions');
}
public function testComment()
{
$c = new Criteria();
$this->assertNull($c->getComment(), 'Comment is null by default');
$c2 = $c->setComment('foo');
$this->assertEquals('foo', $c->getComment(), 'Comment is set by setComment()');
$this->assertEquals($c, $c2, 'setComment() returns the current Criteria');
$c->setComment();
$this->assertNull($c->getComment(), 'Comment is reset by setComment(null)');
}
}

View file

@ -0,0 +1,135 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/BaseTestCase.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/query/Criteria.php';
set_include_path(get_include_path() . PATH_SEPARATOR . "fixtures/bookstore/build/classes");
Propel::init('fixtures/bookstore/build/conf/bookstore-conf.php');
/**
* Test class for Join.
*
* @author François Zaninotto
* @version $Id: JoinTest.php 1773 2010-05-25 10:25:06Z francois $
* @package runtime.query
*/
class JoinTest extends BaseTestCase
{
/**
* DB adapter saved for later.
*
* @var DBAdapter
*/
private $savedAdapter;
protected function setUp()
{
parent::setUp();
$this->savedAdapter = Propel::getDB(null);
Propel::setDB(null, new DBSQLite());
}
protected function tearDown()
{
Propel::setDB(null, $this->savedAdapter);
parent::tearDown();
}
public function testEmptyConditions()
{
$j = new Join();
$this->assertEquals(array(), $j->getConditions());
}
public function testAddCondition()
{
$j = new Join();
$j->addCondition('foo', 'bar');
$this->assertEquals('=', $j->getOperator());
$this->assertEquals('foo', $j->getLeftColumn());
$this->assertEquals('bar', $j->getRightColumn());
}
public function testGetConditions()
{
$j = new Join();
$j->addCondition('foo', 'bar');
$expect = array(array('left' => 'foo', 'operator' => '=', 'right' => 'bar'));
$this->assertEquals($expect, $j->getConditions());
}
public function testAddConditionWithOperator()
{
$j = new Join();
$j->addCondition('foo', 'bar', '>=');
$expect = array(array('left' => 'foo', 'operator' => '>=', 'right' => 'bar'));
$this->assertEquals($expect, $j->getConditions());
}
public function testAddConditions()
{
$j = new Join();
$j->addCondition('foo', 'bar');
$j->addCondition('baz', 'bal');
$expect = array(
array('left' => 'foo', 'operator' => '=', 'right' => 'bar'),
array('left' => 'baz', 'operator' => '=', 'right' => 'bal')
);
$this->assertEquals(array('=', '='), $j->getOperators());
$this->assertEquals(array('foo', 'baz'), $j->getLeftColumns());
$this->assertEquals(array('bar', 'bal'), $j->getRightColumns());
$this->assertEquals($expect, $j->getConditions());
}
public function testEmptyJoinType()
{
$j = new Join();
$this->assertNull($j->getJoinType());
}
public function testSetJoinType()
{
$j = new Join();
$j->setJoinType('foo');
$this->assertEquals('foo', $j->getJoinType());
}
public function testSimpleConstructor()
{
$j = new Join('foo', 'bar', 'LEFT JOIN');
$expect = array(array('left' => 'foo', 'operator' => '=', 'right' => 'bar'));
$this->assertEquals($expect, $j->getConditions());
$this->assertEquals('LEFT JOIN', $j->getJoinType());
}
public function testCompositeeConstructor()
{
$j = new Join(array('foo1', 'foo2'), array('bar1', 'bar2'), 'LEFT JOIN');
$expect = array(
array('left' => 'foo1', 'operator' => '=', 'right' => 'bar1'),
array('left' => 'foo2', 'operator' => '=', 'right' => 'bar2')
);
$this->assertEquals($expect, $j->getConditions());
$this->assertEquals('LEFT JOIN', $j->getJoinType());
}
public function testCountConditions()
{
$j = new Join();
$this->assertEquals(0, $j->countConditions());
$j->addCondition('foo', 'bar');
$this->assertEquals(1, $j->countConditions());
$j->addCondition('foo1', 'bar1');
$this->assertEquals(2, $j->countConditions());
}
}

View file

@ -0,0 +1,196 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
require_once 'tools/helpers/bookstore/BookstoreDataPopulator.php';
/**
* Test class for ModelCriteria.
*
* @author Francois Zaninotto
* @version $Id: ModelCriteriaTest.php 1662 2010-04-10 22:02:49Z francois $
* @package runtime.query
*/
class ModelCriteriaHooksTest extends BookstoreTestBase
{
protected function setUp()
{
parent::setUp();
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
}
public function testPreSelect()
{
$c = new ModelCriteriaWithPreSelectHook('bookstore', 'Book');
$books = $c->find();
$this->assertEquals(1, count($books), 'preSelect() can modify the Criteria before find() fires the query');
$c = new ModelCriteriaWithPreSelectHook('bookstore', 'Book');
$nbBooks = $c->count();
$this->assertEquals(1, $nbBooks, 'preSelect() can modify the Criteria before count() fires the query');
}
public function testPreDelete()
{
$c = new ModelCriteria('bookstore', 'Book');
$books = $c->find();
$count = count($books);
$book = $books->shift();
$c = new ModelCriteriaWithPreDeleteHook('bookstore', 'Book', 'b');
$c->where('b.Id = ?', $book->getId());
$nbBooks = $c->delete();
$this->assertEquals(12, $nbBooks, 'preDelete() can change the return value of delete()');
$c = new ModelCriteria('bookstore', 'Book');
$nbBooks = $c->count();
$this->assertEquals($count, $nbBooks, 'preDelete() can bypass the row deletion');
$c = new ModelCriteriaWithPreDeleteHook('bookstore', 'Book');
$nbBooks = $c->deleteAll();
$this->assertEquals(12, $nbBooks, 'preDelete() can change the return value of deleteAll()');
$c = new ModelCriteria('bookstore', 'Book');
$nbBooks = $c->count();
$this->assertEquals($count, $nbBooks, 'preDelete() can bypass the row deletion');
}
public function testPostDelete()
{
$c = new ModelCriteria('bookstore', 'Book');
$books = $c->find();
$count = count($books);
$book = $books->shift();
$this->con->lastAffectedRows = 0;
$c = new ModelCriteriaWithPostDeleteHook('bookstore', 'Book', 'b');
$c->where('b.Id = ?', $book->getId());
$nbBooks = $c->delete($this->con);
$this->assertEquals(1, $this->con->lastAffectedRows, 'postDelete() is called after delete()');
$this->con->lastAffectedRows = 0;
$c = new ModelCriteriaWithPostDeleteHook('bookstore', 'Book');
$nbBooks = $c->deleteAll($this->con);
$this->assertEquals(3, $this->con->lastAffectedRows, 'postDelete() is called after deleteAll()');
}
public function testPreAndPostDelete()
{
$c = new ModelCriteria('bookstore', 'Book');
$books = $c->find();
$count = count($books);
$book = $books->shift();
$this->con->lastAffectedRows = 0;
$c = new ModelCriteriaWithPreAndPostDeleteHook('bookstore', 'Book', 'b');
$c->where('b.Id = ?', $book->getId());
$nbBooks = $c->delete($this->con);
$this->assertEquals(12, $this->con->lastAffectedRows, 'postDelete() is called after delete() even if preDelete() returns not null');
$this->con->lastAffectedRows = 0;
$c = new ModelCriteriaWithPreAndPostDeleteHook('bookstore', 'Book');
$nbBooks = $c->deleteAll($this->con);
$this->assertEquals(12, $this->con->lastAffectedRows, 'postDelete() is called after deleteAll() even if preDelete() returns not null');
}
public function testPreUpdate()
{
$c = new ModelCriteriaWithPreUpdateHook('bookstore', 'Book', 'b');
$c->where('b.Title = ?', 'Don Juan');
$nbBooks = $c->update(array('Title' => 'foo'));
$c = new ModelCriteriaWithPreUpdateHook('bookstore', 'Book', 'b');
$c->where('b.Title = ?', 'foo');
$book = $c->findOne();
$this->assertEquals('1234', $book->getISBN(), 'preUpdate() can modify the values');
}
public function testPostUpdate()
{
$this->con->lastAffectedRows = 0;
$c = new ModelCriteriaWithPostUpdateHook('bookstore', 'Book', 'b');
$c->where('b.Title = ?', 'Don Juan');
$nbBooks = $c->update(array('Title' => 'foo'), $this->con);
$this->assertEquals(1, $this->con->lastAffectedRows, 'postUpdate() is called after update()');
}
public function testPreAndPostUpdate()
{
$this->con->lastAffectedRows = 0;
$c = new ModelCriteriaWithPreAndPostUpdateHook('bookstore', 'Book', 'b');
$c->where('b.Title = ?', 'Don Juan');
$nbBooks = $c->update(array('Title' => 'foo'), $this->con);
$this->assertEquals(52, $this->con->lastAffectedRows, 'postUpdate() is called after update() even if preUpdate() returns not null');
}
}
class ModelCriteriaWithPreSelectHook extends ModelCriteria
{
public function preSelect(PropelPDO $con)
{
$this->where($this->getModelAliasOrName() . '.Title = ?', 'Don Juan');
}
}
class ModelCriteriaWithPreDeleteHook extends ModelCriteria
{
public function preDelete(PropelPDO $con)
{
return 12;
}
}
class ModelCriteriaWithPostDeleteHook extends ModelCriteria
{
public function postDelete($affectedRows, PropelPDO $con)
{
$con->lastAffectedRows = $affectedRows;
}
}
class ModelCriteriaWithPreAndPostDeleteHook extends ModelCriteriaWithPostDeleteHook
{
public function preDelete(PropelPDO $con)
{
return 12;
}
}
class ModelCriteriaWithPreUpdateHook extends ModelCriteria
{
public function preUpdate(&$values, PropelPDO $con, $forceIndividualSaves = false)
{
$values['ISBN'] = '1234';
}
}
class ModelCriteriaWithPostUpdateHook extends ModelCriteria
{
public function postUpdate($affectedRows, PropelPDO $con)
{
$con->lastAffectedRows = $affectedRows;
}
}
class ModelCriteriaWithPreAndPostUpdateHook extends ModelCriteriaWithPostUpdateHook
{
public function preUpdate(&$values, PropelPDO $con, $forceIndividualSaves = false)
{
return 52;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,85 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
require_once 'tools/helpers/bookstore/BookstoreDataPopulator.php';
/**
* Test class for ModelJoin.
*
* @author François Zaninotto
* @version $Id: ModelJoinTest.php 1347 2009-12-03 21:06:36Z francois $
* @package runtime.query
*/
class ModelJoinTest extends BookstoreTestBase
{
public function testTableMap()
{
$join = new ModelJoin();
$this->assertNull($join->getTableMap(), 'getTableMap() returns null as long as no table map is set');
$tmap = new TableMap();
$tmap->foo = 'bar';
$join->setTableMap($tmap);
$this->assertEquals($tmap, $join->getTableMap(), 'getTableMap() returns the TableMap previously set by setTableMap()');
}
public function testSetRelationMap()
{
$join = new ModelJoin();
$this->assertNull($join->getRelationMap(), 'getRelationMap() returns null as long as no relation map is set');
$bookTable = BookPeer::getTableMap();
$relationMap = $bookTable->getRelation('Author');
$join->setRelationMap($relationMap);
$this->assertEquals($relationMap, $join->getRelationMap(), 'getRelationMap() returns the RelationMap previously set by setRelationMap()');
}
public function testSetRelationMapDefinesJoinColumns()
{
$bookTable = BookPeer::getTableMap();
$join = new ModelJoin();
$join->setTableMap($bookTable);
$join->setRelationMap($bookTable->getRelation('Author'));
$this->assertEquals(array(BookPeer::AUTHOR_ID), $join->getLeftColumns(), 'setRelationMap() automatically sets the left columns');
$this->assertEquals(array(AuthorPeer::ID), $join->getRightColumns(), 'setRelationMap() automatically sets the right columns');
}
public function testSetRelationMapLeftAlias()
{
$bookTable = BookPeer::getTableMap();
$join = new ModelJoin();
$join->setTableMap($bookTable);
$join->setRelationMap($bookTable->getRelation('Author'), 'b');
$this->assertEquals(array('b.AUTHOR_ID'), $join->getLeftColumns(), 'setRelationMap() automatically sets the left columns using the left table alias');
$this->assertEquals(array(AuthorPeer::ID), $join->getRightColumns(), 'setRelationMap() automatically sets the right columns');
}
public function testSetRelationMapRightAlias()
{
$bookTable = BookPeer::getTableMap();
$join = new ModelJoin();
$join->setTableMap($bookTable);
$join->setRelationMap($bookTable->getRelation('Author'), null, 'a');
$this->assertEquals(array(BookPeer::AUTHOR_ID), $join->getLeftColumns(), 'setRelationMap() automatically sets the left columns');
$this->assertEquals(array('a.ID'), $join->getRightColumns(), 'setRelationMap() automatically sets the right columns using the right table alias');
}
public function testSetRelationMapComposite()
{
$table = ReaderFavoritePeer::getTableMap();
$join = new ModelJoin();
$join->setTableMap($table);
$join->setRelationMap($table->getRelation('BookOpinion'));
$this->assertEquals(array(ReaderFavoritePeer::BOOK_ID, ReaderFavoritePeer::READER_ID), $join->getLeftColumns(), 'setRelationMap() automatically sets the left columns for composite relationships');
$this->assertEquals(array(BookOpinionPeer::BOOK_ID, BookOpinionPeer::READER_ID), $join->getRightColumns(), 'setRelationMap() automatically sets the right columns for composite relationships');
}
}

View file

@ -0,0 +1,183 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
require_once 'tools/helpers/bookstore/BookstoreDataPopulator.php';
/**
* Test class for ModelWith.
*
* @author François Zaninotto
* @version $Id: ModelJoinTest.php 1347 2009-12-03 21:06:36Z francois $
* @package runtime.query
*/
class ModelWithTest extends BookstoreTestBase
{
public function testModelNameManyToOne()
{
$q = BookQuery::create()
->joinAuthor();
$joins = $q->getJoins();
$join = $joins['Author'];
$with = new ModelWith($join);
$this->assertEquals($with->getModelName(), 'Author', 'A ModelWith computes the model name from the join');
$this->assertEquals($with->getModelPeerName(), 'AuthorPeer', 'A ModelWith computes the model peer name from the join');
}
public function testModelNameOneToMany()
{
$q = AuthorQuery::create()
->joinBook();
$joins = $q->getJoins();
$join = $joins['Book'];
$with = new ModelWith($join);
$this->assertEquals($with->getModelName(), 'Book', 'A ModelWith computes the model peer name from the join');
$this->assertEquals($with->getModelPeerName(), 'BookPeer', 'A ModelWith computes the model peer name from the join');
}
public function testModelNameAlias()
{
$q = BookQuery::create()
->joinAuthor('a');
$joins = $q->getJoins();
$join = $joins['a'];
$with = new ModelWith($join);
$this->assertEquals($with->getModelName(), 'Author', 'A ModelWith computes the model peer name from the join');
$this->assertEquals($with->getModelPeerName(), 'AuthorPeer', 'A ModelWith computes the model peer name from the join');
}
public function testRelationManyToOne()
{
$q = BookQuery::create()
->joinAuthor();
$joins = $q->getJoins();
$join = $joins['Author'];
$with = new ModelWith($join);
$this->assertEquals($with->getRelationMethod(), 'setAuthor', 'A ModelWith computes the relation method from the join');
$this->assertEquals($with->getRelationName(), 'Author', 'A ModelWith computes the relation name from the join');
$this->assertFalse($with->isAdd(), 'A ModelWith computes the relation cardinality from the join');
}
public function testRelationOneToMany()
{
$q = AuthorQuery::create()
->joinBook();
$joins = $q->getJoins();
$join = $joins['Book'];
$with = new ModelWith($join);
$this->assertEquals($with->getRelationMethod(), 'addBook', 'A ModelWith computes the relation method from the join');
$this->assertEquals($with->getRelationName(), 'Books', 'A ModelWith computes the relation name from the join');
$this->assertTrue($with->isAdd(), 'A ModelWith computes the relation cardinality from the join');
}
public function testRelationOneToOne()
{
$q = BookstoreEmployeeQuery::create()
->joinBookstoreEmployeeAccount();
$joins = $q->getJoins();
$join = $joins['BookstoreEmployeeAccount'];
$with = new ModelWith($join);
$this->assertEquals($with->getRelationMethod(), 'setBookstoreEmployeeAccount', 'A ModelWith computes the relation method from the join');
$this->assertEquals($with->getRelationName(), 'BookstoreEmployeeAccount', 'A ModelWith computes the relation name from the join');
$this->assertFalse($with->isAdd(), 'A ModelWith computes the relation cardinality from the join');
}
public function testIsPrimary()
{
$q = AuthorQuery::create()
->joinBook();
$joins = $q->getJoins();
$join = $joins['Book'];
$with = new ModelWith($join);
$this->assertTrue($with->isPrimary(), 'A ModelWith initialized from a primary join is primary');
$q = BookQuery::create()
->joinAuthor()
->joinReview();
$joins = $q->getJoins();
$join = $joins['Review'];
$with = new ModelWith($join);
$this->assertTrue($with->isPrimary(), 'A ModelWith initialized from a primary join is primary');
$q = AuthorQuery::create()
->join('Author.Book')
->join('Book.Publisher');
$joins = $q->getJoins();
$join = $joins['Publisher'];
$with = new ModelWith($join);
$this->assertFalse($with->isPrimary(), 'A ModelWith initialized from a non-primary join is not primary');
}
public function testGetRelatedClass()
{
$q = AuthorQuery::create()
->joinBook();
$joins = $q->getJoins();
$join = $joins['Book'];
$with = new ModelWith($join);
$this->assertNull($with->getRelatedClass(), 'A ModelWith initialized from a primary join has a null related class');
$q = AuthorQuery::create('a')
->joinBook();
$joins = $q->getJoins();
$join = $joins['Book'];
$with = new ModelWith($join);
$this->assertNull($with->getRelatedClass(), 'A ModelWith initialized from a primary join with alias has a null related class');
$q = AuthorQuery::create()
->joinBook('b');
$joins = $q->getJoins();
$join = $joins['b'];
$with = new ModelWith($join);
$this->assertNull($with->getRelatedClass(), 'A ModelWith initialized from a primary join with alias has a null related class');
$q = AuthorQuery::create()
->join('Author.Book')
->join('Book.Publisher');
$joins = $q->getJoins();
$join = $joins['Publisher'];
$with = new ModelWith($join);
$this->assertEquals($with->getRelatedClass(), 'Book', 'A ModelWith uses the previous join relation name as related class');
$q = ReviewQuery::create()
->join('Review.Book')
->join('Book.Author')
->join('Book.Publisher');
$joins = $q->getJoins();
$join = $joins['Publisher'];
$with = new ModelWith($join);
$this->assertEquals($with->getRelatedClass(), 'Book', 'A ModelWith uses the previous join relation name as related class');
$q = ReviewQuery::create()
->join('Review.Book')
->join('Book.BookOpinion')
->join('BookOpinion.BookReader');
$joins = $q->getJoins();
$join = $joins['BookOpinion'];
$with = new ModelWith($join);
$this->assertEquals($with->getRelatedClass(), 'Book', 'A ModelWith uses the previous join relation name as related class');
$join = $joins['BookReader'];
$with = new ModelWith($join);
$this->assertEquals($with->getRelatedClass(), 'BookOpinion', 'A ModelWith uses the previous join relation name as related class');
$q = BookReaderQuery::create()
->join('BookReader.BookOpinion')
->join('BookOpinion.Book')
->join('Book.Author');
$joins = $q->getJoins();
$join = $joins['Book'];
$with = new ModelWith($join);
$this->assertEquals($with->getRelatedClass(), 'BookOpinion', 'A ModelWith uses the previous join relation name as related class');
$join = $joins['Author'];
$with = new ModelWith($join);
$this->assertEquals($with->getRelatedClass(), 'Book', 'A ModelWith uses the previous join relation name as related class');
}
}

View file

@ -0,0 +1,63 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
require_once 'tools/helpers/bookstore/BookstoreDataPopulator.php';
/**
* Test class for PropelQuery
*
* @author Francois Zaninotto
* @version $Id: PropelQueryTest.php 1351 2009-12-04 22:05:01Z francois $
* @package runtime.query
*/
class PropelQueryTest extends BookstoreTestBase
{
public function testFrom()
{
$q = PropelQuery::from('Book');
$expected = new BookQuery();
$this->assertEquals($expected, $q, 'from() returns a Model query instance based on the model name');
$q = PropelQuery::from('Book b');
$expected = new BookQuery();
$expected->setModelAlias('b');
$this->assertEquals($expected, $q, 'from() sets the model alias if found after the blank');
$q = PropelQuery::from('myBook');
$expected = new myBookQuery();
$this->assertEquals($expected, $q, 'from() can find custom query classes');
try {
$q = PropelQuery::from('Foo');
$this->fail('PropelQuery::from() throws an exception when called on a non-existing query class');
} catch (PropelException $e) {
$this->assertTrue(true, 'PropelQuery::from() throws an exception when called on a non-existing query class');
}
}
public function testQuery()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
$book = PropelQuery::from('Book b')
->where('b.Title like ?', 'Don%')
->orderBy('b.ISBN', 'desc')
->findOne();
$this->assertTrue($book instanceof Book);
$this->assertEquals('Don Juan', $book->getTitle());
}
}
class myBookQuery extends BookQuery
{
}

View file

@ -0,0 +1,94 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests the exceptions thrown by the BasePeer classes.
*
* @see BookstoreDataPopulator
* @author Francois Zaninotto
* @package runtime.util
*/
class BasePeerExceptionsTest extends BookstoreTestBase
{
public function testDoSelect()
{
try {
$c = new Criteria();
$c->add(BookPeer::ID, 12, ' BAD SQL');
BookPeer::addSelectColumns($c);
BasePeer::doSelect($c);
} catch (PropelException $e) {
$this->assertContains('[SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.ID BAD SQL:p1]', $e->getMessage(), 'SQL query is written in the exception message');
}
}
public function testDoCount()
{
try {
$c = new Criteria();
$c->add(BookPeer::ID, 12, ' BAD SQL');
BookPeer::addSelectColumns($c);
BasePeer::doCount($c);
} catch (PropelException $e) {
$this->assertContains('[SELECT COUNT(*) FROM `book` WHERE book.ID BAD SQL:p1]', $e->getMessage(), 'SQL query is written in the exception message');
}
}
public function testDoDelete()
{
try {
$c = new Criteria();
$c->setPrimaryTableName(BookPeer::TABLE_NAME);
$c->add(BookPeer::ID, 12, ' BAD SQL');
BasePeer::doDelete($c, Propel::getConnection());
} catch (PropelException $e) {
$this->assertContains('[DELETE FROM `book` WHERE book.ID BAD SQL:p1]', $e->getMessage(), 'SQL query is written in the exception message');
}
}
public function testDoDeleteAll()
{
try {
BasePeer::doDeleteAll('BAD TABLE', Propel::getConnection());
} catch (PropelException $e) {
$this->assertContains('[DELETE FROM `BAD` `TABLE`]', $e->getMessage(), 'SQL query is written in the exception message');
}
}
public function testDoUpdate()
{
try {
$c1 = new Criteria();
$c1->setPrimaryTableName(BookPeer::TABLE_NAME);
$c1->add(BookPeer::ID, 12, ' BAD SQL');
$c2 = new Criteria();
$c2->add(BookPeer::TITLE, 'Foo');
BasePeer::doUpdate($c1, $c2, Propel::getConnection());
} catch (PropelException $e) {
$this->assertContains('[UPDATE `book` SET `TITLE`=:p1 WHERE book.ID BAD SQL:p2]', $e->getMessage(), 'SQL query is written in the exception message');
}
}
public function testDoInsert()
{
try {
$c = new Criteria();
$c->setPrimaryTableName(BookPeer::TABLE_NAME);
$c->add(BookPeer::AUTHOR_ID, 'lkhlkhj');
BasePeer::doInsert($c, Propel::getConnection());
} catch (PropelException $e) {
$this->assertContains('[INSERT INTO `book` (`AUTHOR_ID`) VALUES (:p1)]', $e->getMessage(), 'SQL query is written in the exception message');
}
}
}

View file

@ -0,0 +1,413 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreTestBase.php';
/**
* Tests the BasePeer classes.
*
* @see BookstoreDataPopulator
* @author Hans Lellelid <hans@xmpl.org>
* @package runtime.util
*/
class BasePeerTest extends BookstoreTestBase
{
/**
* @link http://propel.phpdb.org/trac/ticket/425
*/
public function testMultipleFunctionInCriteria()
{
$db = Propel::getDB(BookPeer::DATABASE_NAME);
try {
$c = new Criteria();
$c->setDistinct();
if ($db instanceof DBPostgres) {
$c->addSelectColumn("substring(".BookPeer::TITLE." from position('Potter' in ".BookPeer::TITLE.")) AS col");
} else {
$this->markTestSkipped();
}
$stmt = BookPeer::doSelectStmt( $c );
} catch (PropelException $x) {
$this->fail("Paring of nested functions failed: " . $x->getMessage());
}
}
public function testNeedsSelectAliases()
{
$c = new Criteria();
$this->assertFalse(BasePeer::needsSelectAliases($c), 'Empty Criterias dont need aliases');
$c = new Criteria();
$c->addSelectColumn(BookPeer::ID);
$c->addSelectColumn(BookPeer::TITLE);
$this->assertFalse(BasePeer::needsSelectAliases($c), 'Criterias with distinct column names dont need aliases');
$c = new Criteria();
BookPeer::addSelectColumns($c);
$this->assertFalse(BasePeer::needsSelectAliases($c), 'Criterias with only the columns of a model dont need aliases');
$c = new Criteria();
$c->addSelectColumn(BookPeer::ID);
$c->addSelectColumn(AuthorPeer::ID);
$this->assertTrue(BasePeer::needsSelectAliases($c), 'Criterias with common column names do need aliases');
}
public function testTurnSelectColumnsToAliases()
{
$c1 = new Criteria();
$c1->addSelectColumn(BookPeer::ID);
BasePeer::turnSelectColumnsToAliases($c1);
$c2 = new Criteria();
$c2->addAsColumn('book_ID', BookPeer::ID);
$this->assertTrue($c1->equals($c2));
}
public function testTurnSelectColumnsToAliasesPreservesAliases()
{
$c1 = new Criteria();
$c1->addSelectColumn(BookPeer::ID);
$c1->addAsColumn('foo', BookPeer::TITLE);
BasePeer::turnSelectColumnsToAliases($c1);
$c2 = new Criteria();
$c2->addAsColumn('book_ID', BookPeer::ID);
$c2->addAsColumn('foo', BookPeer::TITLE);
$this->assertTrue($c1->equals($c2));
}
public function testTurnSelectColumnsToAliasesExisting()
{
$c1 = new Criteria();
$c1->addSelectColumn(BookPeer::ID);
$c1->addAsColumn('book_ID', BookPeer::ID);
BasePeer::turnSelectColumnsToAliases($c1);
$c2 = new Criteria();
$c2->addAsColumn('book_ID_1', BookPeer::ID);
$c2->addAsColumn('book_ID', BookPeer::ID);
$this->assertTrue($c1->equals($c2));
}
public function testTurnSelectColumnsToAliasesDuplicate()
{
$c1 = new Criteria();
$c1->addSelectColumn(BookPeer::ID);
$c1->addSelectColumn(BookPeer::ID);
BasePeer::turnSelectColumnsToAliases($c1);
$c2 = new Criteria();
$c2->addAsColumn('book_ID', BookPeer::ID);
$c2->addAsColumn('book_ID_1', BookPeer::ID);
$this->assertTrue($c1->equals($c2));
}
public function testDoCountDuplicateColumnName()
{
$con = Propel::getConnection();
$c = new Criteria();
$c->addSelectColumn(BookPeer::ID);
$c->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID);
$c->addSelectColumn(AuthorPeer::ID);
$c->setLimit(3);
try {
$count = BasePeer::doCount($c, $con);
} catch (Exception $e) {
$this->fail('doCount() cannot deal with a criteria selecting duplicate column names ');
}
}
public function testCreateSelectSqlPart()
{
$c = new Criteria();
$c->addSelectColumn(BookPeer::ID);
$c->addAsColumn('book_ID', BookPeer::ID);
$fromClause = array();
$selectSql = BasePeer::createSelectSqlPart($c, $fromClause);
$this->assertEquals('SELECT book.ID, book.ID AS book_ID', $selectSql, 'createSelectSqlPart() returns a SQL SELECT clause with both select and as columns');
$this->assertEquals(array('book'), $fromClause, 'createSelectSqlPart() adds the tables from the select columns to the from clause');
}
public function testCreateSelectSqlPartSelectModifier()
{
$c = new Criteria();
$c->addSelectColumn(BookPeer::ID);
$c->addAsColumn('book_ID', BookPeer::ID);
$c->setDistinct();
$fromClause = array();
$selectSql = BasePeer::createSelectSqlPart($c, $fromClause);
$this->assertEquals('SELECT DISTINCT book.ID, book.ID AS book_ID', $selectSql, 'createSelectSqlPart() includes the select modifiers in the SELECT clause');
$this->assertEquals(array('book'), $fromClause, 'createSelectSqlPart() adds the tables from the select columns to the from clause');
}
public function testCreateSelectSqlPartAliasAll()
{
$c = new Criteria();
$c->addSelectColumn(BookPeer::ID);
$c->addAsColumn('book_ID', BookPeer::ID);
$fromClause = array();
$selectSql = BasePeer::createSelectSqlPart($c, $fromClause, true);
$this->assertEquals('SELECT book.ID AS book_ID_1, book.ID AS book_ID', $selectSql, 'createSelectSqlPart() aliases all columns if passed true as last parameter');
$this->assertEquals(array(), $fromClause, 'createSelectSqlPart() does not add the tables from an all-aliased list of select columns');
}
public function testBigIntIgnoreCaseOrderBy()
{
BookstorePeer::doDeleteAll();
// Some sample data
$b = new Bookstore();
$b->setStoreName("SortTest1")->setPopulationServed(2000)->save();
$b = new Bookstore();
$b->setStoreName("SortTest2")->setPopulationServed(201)->save();
$b = new Bookstore();
$b->setStoreName("SortTest3")->setPopulationServed(302)->save();
$b = new Bookstore();
$b->setStoreName("SortTest4")->setPopulationServed(10000000)->save();
$c = new Criteria();
$c->setIgnoreCase(true);
$c->add(BookstorePeer::STORE_NAME, 'SortTest%', Criteria::LIKE);
$c->addAscendingOrderByColumn(BookstorePeer::POPULATION_SERVED);
$rows = BookstorePeer::doSelect($c);
$this->assertEquals('SortTest2', $rows[0]->getStoreName());
$this->assertEquals('SortTest3', $rows[1]->getStoreName());
$this->assertEquals('SortTest1', $rows[2]->getStoreName());
$this->assertEquals('SortTest4', $rows[3]->getStoreName());
}
/**
*
*/
public function testMixedJoinOrder()
{
$this->markTestSkipped('Famous cross join problem, to be solved one day');
$c = new Criteria(BookPeer::DATABASE_NAME);
$c->addSelectColumn(BookPeer::ID);
$c->addSelectColumn(BookPeer::TITLE);
$c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::LEFT_JOIN);
$c->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID);
$params = array();
$sql = BasePeer::createSelectSql($c, $params);
$expectedSql = "SELECT book.ID, book.TITLE FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.ID), author WHERE book.AUTHOR_ID=author.ID";
$this->assertEquals($expectedSql, $sql);
}
public function testMssqlApplyLimitNoOffset()
{
$db = Propel::getDB(BookPeer::DATABASE_NAME);
if(! ($db instanceof DBMSSQL))
{
$this->markTestSkipped();
}
$c = new Criteria(BookPeer::DATABASE_NAME);
$c->addSelectColumn(BookPeer::ID);
$c->addSelectColumn(BookPeer::TITLE);
$c->addSelectColumn(PublisherPeer::NAME);
$c->addAsColumn('PublisherName','(SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID)');
$c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::LEFT_JOIN);
$c->setOffset(0);
$c->setLimit(20);
$params = array();
$sql = BasePeer::createSelectSql($c, $params);
$expectedSql = "SELECT TOP 20 book.ID, book.TITLE, publisher.NAME, (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID) AS PublisherName FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.ID)";
$this->assertEquals($expectedSql, $sql);
}
public function testMssqlApplyLimitWithOffset()
{
$db = Propel::getDB(BookPeer::DATABASE_NAME);
if(! ($db instanceof DBMSSQL))
{
$this->markTestSkipped();
}
$c = new Criteria(BookPeer::DATABASE_NAME);
$c->addSelectColumn(BookPeer::ID);
$c->addSelectColumn(BookPeer::TITLE);
$c->addSelectColumn(PublisherPeer::NAME);
$c->addAsColumn('PublisherName','(SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID)');
$c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::LEFT_JOIN);
$c->setOffset(20);
$c->setLimit(20);
$params = array();
$expectedSql = "SELECT [book.ID], [book.TITLE], [publisher.NAME], [PublisherName] FROM (SELECT ROW_NUMBER() OVER(ORDER BY book.ID) AS RowNumber, book.ID AS [book.ID], book.TITLE AS [book.TITLE], publisher.NAME AS [publisher.NAME], (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID) AS [PublisherName] FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.ID)) AS derivedb WHERE RowNumber BETWEEN 21 AND 40";
$sql = BasePeer::createSelectSql($c, $params);
$this->assertEquals($expectedSql, $sql);
}
public function testMssqlApplyLimitWithOffsetOrderByAggregate()
{
$db = Propel::getDB(BookPeer::DATABASE_NAME);
if(! ($db instanceof DBMSSQL))
{
$this->markTestSkipped();
}
$c = new Criteria(BookPeer::DATABASE_NAME);
$c->addSelectColumn(BookPeer::ID);
$c->addSelectColumn(BookPeer::TITLE);
$c->addSelectColumn(PublisherPeer::NAME);
$c->addAsColumn('PublisherName','(SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID)');
$c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::LEFT_JOIN);
$c->addDescendingOrderByColumn('PublisherName');
$c->setOffset(20);
$c->setLimit(20);
$params = array();
$expectedSql = "SELECT [book.ID], [book.TITLE], [publisher.NAME], [PublisherName] FROM (SELECT ROW_NUMBER() OVER(ORDER BY (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID) DESC) AS RowNumber, book.ID AS [book.ID], book.TITLE AS [book.TITLE], publisher.NAME AS [publisher.NAME], (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID) AS [PublisherName] FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.ID)) AS derivedb WHERE RowNumber BETWEEN 21 AND 40";
$sql = BasePeer::createSelectSql($c, $params);
$this->assertEquals($expectedSql, $sql);
}
public function testMssqlApplyLimitWithOffsetMultipleOrderBy()
{
$db = Propel::getDB(BookPeer::DATABASE_NAME);
if(! ($db instanceof DBMSSQL))
{
$this->markTestSkipped();
}
$c = new Criteria(BookPeer::DATABASE_NAME);
$c->addSelectColumn(BookPeer::ID);
$c->addSelectColumn(BookPeer::TITLE);
$c->addSelectColumn(PublisherPeer::NAME);
$c->addAsColumn('PublisherName','(SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID)');
$c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::LEFT_JOIN);
$c->addDescendingOrderByColumn('PublisherName');
$c->addAscendingOrderByColumn(BookPeer::TITLE);
$c->setOffset(20);
$c->setLimit(20);
$params = array();
$expectedSql = "SELECT [book.ID], [book.TITLE], [publisher.NAME], [PublisherName] FROM (SELECT ROW_NUMBER() OVER(ORDER BY (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID) DESC, book.TITLE ASC) AS RowNumber, book.ID AS [book.ID], book.TITLE AS [book.TITLE], publisher.NAME AS [publisher.NAME], (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.ID = book.PUBLISHER_ID) AS [PublisherName] FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.ID)) AS derivedb WHERE RowNumber BETWEEN 21 AND 40";
$sql = BasePeer::createSelectSql($c, $params);
$this->assertEquals($expectedSql, $sql);
}
/**
* @expectedException PropelException
*/
public function testDoDeleteNoCondition()
{
$con = Propel::getConnection();
$c = new Criteria(BookPeer::DATABASE_NAME);
BasePeer::doDelete($c, $con);
}
public function testDoDeleteSimpleCondition()
{
$con = Propel::getConnection();
$c = new Criteria(BookPeer::DATABASE_NAME);
$c->add(BookPeer::TITLE, 'War And Peace');
BasePeer::doDelete($c, $con);
$expectedSQL = "DELETE FROM `book` WHERE book.TITLE='War And Peace'";
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'doDelete() translates a contition into a WHERE');
}
public function testDoDeleteSeveralConditions()
{
$con = Propel::getConnection();
$c = new Criteria(BookPeer::DATABASE_NAME);
$c->add(BookPeer::TITLE, 'War And Peace');
$c->add(BookPeer::ID, 12);
BasePeer::doDelete($c, $con);
$expectedSQL = "DELETE FROM `book` WHERE book.TITLE='War And Peace' AND book.ID=12";
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'doDelete() combines conditions in WHERE whith an AND');
}
public function testDoDeleteTableAlias()
{
$con = Propel::getConnection();
$c = new Criteria(BookPeer::DATABASE_NAME);
$c->addAlias('b', BookPeer::TABLE_NAME);
$c->add('b.TITLE', 'War And Peace');
BasePeer::doDelete($c, $con);
$expectedSQL = "DELETE b FROM `book` AS b WHERE b.TITLE='War And Peace'";
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'doDelete() accepts a Criteria with a table alias');
}
/**
* Not documented anywhere, and probably wrong
* @see http://www.propelorm.org/ticket/952
*/
public function testDoDeleteSeveralTables()
{
$con = Propel::getConnection();
$count = $con->getQueryCount();
$c = new Criteria(BookPeer::DATABASE_NAME);
$c->add(BookPeer::TITLE, 'War And Peace');
$c->add(AuthorPeer::FIRST_NAME, 'Leo');
BasePeer::doDelete($c, $con);
$expectedSQL = "DELETE FROM `author` WHERE author.FIRST_NAME='Leo'";
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'doDelete() issues two DELETE queries when passed conditions on two tables');
$this->assertEquals($count + 2, $con->getQueryCount(), 'doDelete() issues two DELETE queries when passed conditions on two tables');
$c = new Criteria(BookPeer::DATABASE_NAME);
$c->add(AuthorPeer::FIRST_NAME, 'Leo');
$c->add(BookPeer::TITLE, 'War And Peace');
BasePeer::doDelete($c, $con);
$expectedSQL = "DELETE FROM `book` WHERE book.TITLE='War And Peace'";
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'doDelete() issues two DELETE queries when passed conditions on two tables');
$this->assertEquals($count + 4, $con->getQueryCount(), 'doDelete() issues two DELETE queries when passed conditions on two tables');
}
public function testCommentDoSelect()
{
$c = new Criteria();
$c->setComment('Foo');
$c->addSelectColumn(BookPeer::ID);
$expected = 'SELECT /* Foo */ book.ID FROM `book`';
$params = array();
$this->assertEquals($expected, BasePeer::createSelectSQL($c, $params), 'Criteria::setComment() adds a comment to select queries');
}
public function testCommentDoUpdate()
{
$c1 = new Criteria();
$c1->setPrimaryTableName(BookPeer::TABLE_NAME);
$c1->setComment('Foo');
$c2 = new Criteria();
$c2->add(BookPeer::TITLE, 'Updated Title');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
BasePeer::doUpdate($c1, $c2, $con);
$expected = 'UPDATE /* Foo */ `book` SET `TITLE`=\'Updated Title\'';
$this->assertEquals($expected, $con->getLastExecutedQuery(), 'Criteria::setComment() adds a comment to update queries');
}
public function testCommentDoDelete()
{
$c = new Criteria();
$c->setComment('Foo');
$c->add(BookPeer::TITLE, 'War And Peace');
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
BasePeer::doDelete($c, $con);
$expected = 'DELETE /* Foo */ FROM `book` WHERE book.TITLE=\'War And Peace\'';
$this->assertEquals($expected, $con->getLastExecutedQuery(), 'Criteria::setComment() adds a comment to delete queries');
}
}

View file

@ -0,0 +1,69 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'PHPUnit/Framework/TestCase.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/config/PropelConfiguration.php';
/**
* Test for PropelConfiguration class
*
* @author Francois Zaninotto
* @package runtime.util
*/
class PropelConfigurationTest extends PHPUnit_Framework_TestCase
{
protected $testArray = array('foo' => array('fooo' => 'bar', 'fi' => array('fooooo' => 'bara')), 'baz' => 'bar2');
public function testConstruct()
{
$conf = new PropelConfiguration($this->testArray);
$this->assertEquals($this->testArray, $conf->getParameters(), 'constructor sets values from an associative array');
}
public function testGetParameters()
{
$conf = new PropelConfiguration($this->testArray);
$expected = array('foo.fooo' => 'bar', 'foo.fi.fooooo' => 'bara', 'baz' => 'bar2');
$this->assertEquals($expected, $conf->getParameters(PropelConfiguration::TYPE_ARRAY_FLAT), 'getParameters can return a flat array');
}
public function testGetParameter()
{
$conf = new PropelConfiguration($this->testArray);
$this->assertEquals('bar', $conf->getParameter('foo.fooo'), 'getParameter accepts a flat key');
$this->assertEquals('bara', $conf->getParameter('foo.fi.fooooo'), 'getParameter accepts a flat key');
$this->assertEquals('bar2', $conf->getParameter('baz'), 'getParameter accepts a flat key');
}
public function testGetParameterDefault()
{
$conf = new PropelConfiguration($this->testArray);
$this->assertEquals('bar', $conf->getParameter('foo.fooo'), 'getParameter accepts a flat key');
$this->assertEquals('', $conf->getParameter('foo.fooo2'), 'getParameter returns null for nonexistent keys');
$this->assertEquals('babar', $conf->getParameter('foo.fooo3', 'babar'), 'getParameter accepts a default value');
}
public function testSetParameter()
{
$conf = new PropelConfiguration(array());
$conf->setParameter('foo.fooo', 'bar');
$conf->setParameter('foo.fi.fooooo', 'bara');
$conf->setParameter('baz', 'bar2');
$this->assertEquals($this->testArray, $conf->getParameters(), 'setParameter accepts a flat array');
}
public function testArrayAccess()
{
$conf = new PropelConfiguration($this->testArray);
$expected = array('fooo' => 'bar', 'fi' => array('fooooo' => 'bara'));
$this->assertEquals($expected, $conf['foo'], 'PropelConfiguration implements ArrayAccess for OffsetGet');
$this->assertEquals('bar', $conf['foo']['fooo'], 'Array access allows deep access');
}
}

View file

@ -0,0 +1,139 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/BaseTestCase.php';
require_once dirname(__FILE__) . '/../../../../runtime/lib/util/PropelDateTime.php';
/**
* Test for DateTime subclass to support serialization.
*
* @author Alan Pinstein
* @author Soenke Ruempler
* @package runtime.util
*/
class PropelDateTimeTest extends BaseTestCase
{
/**
* Assert that two dates are identical (equal and have same time zone).
*/
protected function assertDatesIdentical(DateTime $dt1, DateTime $dt2, $msg = "Expected DateTime1 IDENTICAL to DateTime2: %s")
{
$this->assertEquals($dt1->format('Y-m-d H:i:s'), $dt1->format('Y-m-d H:i:s'), sprintf($msg, "Dates w/ no timezone resolution were not the same."));
$this->assertEquals($dt1->getTimeZone()->getName(), $dt2->getTimeZone()->getName(), sprintf($msg, "timezones were not the same."));
// We do this last, because a PHP bug will make this true while the dates
// may not truly be equal.
// See: http://bugs.php.net/bug.php?id=40743
$this->assertTrue($dt1 == $dt2, sprintf($msg, "dates did not pass equality check (==)."));
}
/**
* Assert that two dates are equal.
*/
protected function assertDatesEqual(DateTime $dt1, DateTime $dt2, $msg = "Expected DateTime1 == DateTime2: %s")
{
if ($dt1 != $dt2) {
if ($dt1->getTimeZone()->getName() != $dt2->getTimeZone()->getName()) {
$this->fail(sprintf($msg, "Timezones were not the same."));
} else {
$this->fail(sprintf($msg, "Timezones were the same, but date values were different."));
}
}
}
/**
* Assert that two dates are not equal.
*/
protected function assertDatesNotEqual(DateTime $dt1, DateTime $dt2, $msg = "Expected DateTime1 != DateTime2: %s")
{
$this->assertTrue($dt1 != $dt2, $msg);
}
/**
* Ensure that our constructor matches DateTime constructor signature.
*/
public function testConstruct()
{
// Because of a PHP bug ()
// we cannot use a timestamp format that includes a timezone. It gets weird. :)
$now = date('Y-m-d H:i:s');
$dt = new DateTime($now);
$pdt = new PropelDateTime($now);
$this->assertDatesEqual($dt, $pdt, "Expected DateTime == PropelDateTime: %s");
$dt = new DateTime($now, new DateTimeZone('UTC'));
$pdt = new PropelDateTime($now, new DateTimeZone('America/New_York'));
$this->assertDatesNotEqual($dt, $pdt, "Expected DateTime != PropelDateTime: %s");
}
/**
* Tests the ability to serialize() a PropelDateTime object.
*/
public function testSerialize_NoTZ()
{
$now = date('Y-m-d H:i:s');
$dt = new DateTime($now);
$pdt = new PropelDateTime($now);
$this->assertDatesIdentical($dt, $pdt);
// We expect these to be the same -- there's no time zone info
$ser = serialize($pdt);
unset($pdt);
$pdt = unserialize($ser);
$this->assertDatesIdentical($dt, $pdt);
}
/**
* Tests the ability to serialize() a PropelDateTime object.
*/
public function testSerialize_SameTZ()
{
$now = date('Y-m-d H:i:s');
$dt = new DateTime($now, new DateTimeZone('America/New_York'));
$pdt = new PropelDateTime($now, new DateTimeZone('America/New_York'));
$this->assertDatesIdentical($dt, $pdt);
// We expect these to be the same -- there's no time zone info
$ser = serialize($pdt);
unset($pdt);
$pdt = unserialize($ser);
$this->assertDatesIdentical($dt, $pdt);
}
/**
* Tests the ability to serialize() a PropelDateTime object.
*/
public function testSerialize_DiffTZ()
{
$now = date('Y-m-d H:i:s');
$dt = new DateTime($now, new DateTimeZone('UTC'));
$pdt = new PropelDateTime($now, new DateTimeZone('America/New_York'));
$this->assertDatesNotEqual($dt, $pdt);
// We expect these to be the same -- there's no time zone info
$ser = serialize($pdt);
unset($pdt);
$pdt = unserialize($ser);
$this->assertDatesNotEqual($dt, $pdt);
}
}

View file

@ -0,0 +1,149 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Test the utility class PropelPager
*
* @author Francois Zaninotto
* @version $Id: PropelModelPagerTest.php
* @package runtime.util
*/
class PropelModelPagerTest extends BookstoreEmptyTestBase
{
private $authorId;
private $books;
protected function createBooks($nb = 15, $con = null)
{
BookQuery::create()->deleteAll($con);
$books = new PropelObjectCollection();
$books->setModel('Book');
for ($i=0; $i < $nb; $i++) {
$b = new Book();
$b->setTitle('Book' . $i);
$books[]= $b;
}
$books->save($con);
}
protected function getPager($maxPerPage, $page = 1)
{
$pager = new PropelModelPager(BookQuery::create(), $maxPerPage);
$pager->setPage($page);
$pager->init();
return $pager;
}
public function testHaveToPaginate()
{
BookQuery::create()->deleteAll();
$this->assertEquals(false, $this->getPager(0)->haveToPaginate(), 'haveToPaginate() returns false when there is no result');
$this->createBooks(5);
$this->assertEquals(false, $this->getPager(0)->haveToPaginate(), 'haveToPaginate() returns false when the maxPerPage is null');
$this->assertEquals(true, $this->getPager(2)->haveToPaginate(), 'haveToPaginate() returns true when the maxPerPage is less than the number of results');
$this->assertEquals(false, $this->getPager(6)->haveToPaginate(), 'haveToPaginate() returns false when the maxPerPage is greater than the number of results');
$this->assertEquals(false, $this->getPager(5)->haveToPaginate(), 'haveToPaginate() returns false when the maxPerPage is equal to the number of results');
}
public function testGetNbResults()
{
BookQuery::create()->deleteAll();
$pager = $this->getPager(4, 1);
$this->assertEquals(0, $pager->getNbResults(), 'getNbResults() returns 0 when there are no results');
$this->createBooks(5);
$pager = $this->getPager(4, 1);
$this->assertEquals(5, $pager->getNbResults(), 'getNbResults() returns the total number of results');
$pager = $this->getPager(2, 1);
$this->assertEquals(5, $pager->getNbResults(), 'getNbResults() returns the total number of results');
$pager = $this->getPager(2, 2);
$this->assertEquals(5, $pager->getNbResults(), 'getNbResults() returns the total number of results');
$pager = $this->getPager(7, 6);
$this->assertEquals(5, $pager->getNbResults(), 'getNbResults() returns the total number of results');
$pager = $this->getPager(0, 0);
$this->assertEquals(5, $pager->getNbResults(), 'getNbResults() returns the total number of results');
}
public function testGetResults()
{
$this->createBooks(5);
$pager = $this->getPager(4, 1);
$this->assertTrue($pager->getResults() instanceof PropelObjectCollection, 'getResults() returns a PropelObjectCollection');
$this->assertEquals(4, count($pager->getResults()), 'getResults() returns at most $maxPerPage results');
$pager = $this->getPager(4, 2);
$this->assertEquals(1, count($pager->getResults()), 'getResults() returns the remaining results when in the last page');
$pager = $this->getPager(4, 3);
$this->assertEquals(1, count($pager->getResults()), 'getResults() returns the results of the last page when called on nonexistent pages');
}
public function testGetIterator()
{
$this->createBooks(5);
$pager = $this->getPager(4, 1);
$i = 0;
foreach ($pager as $book) {
$this->assertEquals('Book' . $i, $book->getTitle(), 'getIterator() returns an iterator');
$i++;
}
$this->assertEquals(4, $i, 'getIterator() uses the results collection');
}
public function testIterateTwice()
{
$this->createBooks(5);
$pager = $this->getPager(4, 1);
$i = 0;
foreach ($pager as $book) {
$this->assertEquals('Book' . $i, $book->getTitle(), 'getIterator() returns an iterator');
$i++;
}
$this->assertEquals(4, $i, 'getIterator() uses the results collection');
$i = 0;
foreach ($pager as $book) {
$this->assertEquals('Book' . $i, $book->getTitle());
$i++;
}
$this->assertEquals(4, $i, 'getIterator() can be called several times');
}
public function testSetPage()
{
$this->createBooks(5);
$pager = $this->getPager(2, 2);
$i = 2;
foreach ($pager as $book) {
$this->assertEquals('Book' . $i, $book->getTitle(), 'setPage() sets the list to start on a given page');
$i++;
}
$this->assertEquals(4, $i, 'setPage() doesn\'t change the page count');
}
public function testIsFirstPage()
{
$this->createBooks(5);
$pager = $this->getPager(4, 1);
$this->assertTrue($pager->isFirstPage(), 'isFirstPage() returns true on the first page');
$pager = $this->getPager(4, 2);
$this->assertFalse($pager->isFirstPage(), 'isFirstPage() returns false when not on the first page');
}
public function testIsLastPage()
{
$this->createBooks(5);
$pager = $this->getPager(4, 1);
$this->assertFalse($pager->isLastPage(), 'isLastPage() returns false when not on the last page');
$pager = $this->getPager(4, 2);
$this->assertTrue($pager->isLastPage(), 'isLastPage() returns true on the last page');
}
}

View file

@ -0,0 +1,162 @@
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Test the utility class PropelPager
*
* @author Niklas Närhinen <niklas@narhinen.net>
* @version $Id: PropelPagerTest.php
* @package runtime.util
*/
class PropelPagerTest extends BookstoreEmptyTestBase
{
private $authorId;
private $books;
protected function setUp()
{
parent::setUp();
BookstoreDataPopulator::populate();
$cr = new Criteria();
$cr->add(AuthorPeer::LAST_NAME, "Rowling");
$cr->add(AuthorPeer::FIRST_NAME, "J.K.");
$rowling = AuthorPeer::doSelectOne($cr);
$this->authorId = $rowling->getId();
$book = new Book();
$book->setTitle("Harry Potter and the Philosopher's Stone");
$book->setISBN("1234");
$book->setAuthor($rowling);
$book->save();
$this->books[] = $book->getId();
$book = new Book();
$book->setTitle("Harry Potter and the Chamber of Secrets");
$book->setISBN("1234");
$book->setAuthor($rowling);
$book->save();
$this->books[] = $book->getId();
$book = new Book();
$book->setTitle("Harry Potter and the Prisoner of Azkaban");
$book->setISBN("1234");
$book->setAuthor($rowling);
$book->save();
$this->books[] = $book->getId();
$book = new Book();
$book->setTitle("Harry Potter and the Goblet of Fire");
$book->setISBN("1234");
$book->setAuthor($rowling);
$book->save();
$this->books[] = $book->getId();
$book = new Book();
$book->setTitle("Harry Potter and the Half-Blood Prince");
$book->setISBN("1234");
$book->setAuthor($rowling);
$book->save();
$this->books[] = $book->getId();
$book = new Book();
$book->setTitle("Harry Potter and the Deathly Hallows");
$book->setISBN("1234");
$book->setAuthor($rowling);
$book->save();
$this->books[] = $book->getId();
}
protected function tearDown()
{
parent::tearDown();
$cr = new Criteria();
$cr->add(BookPeer::ID, $this->books, Criteria::IN);
BookPeer::doDelete($cr);
}
public function testCountNoPageNoLimit()
{
$cr = new Criteria();
$cr->add(BookPeer::AUTHOR_ID, $this->authorId);
$pager = new PropelPager($cr, "BookPeer", "doSelect");
$this->assertEquals(7, count($pager));
}
public function testCountFirstPageWithLimits()
{
$cr = new Criteria();
$cr->add(BookPeer::AUTHOR_ID, $this->authorId);
$pager = new PropelPager($cr, "BookPeer", "doSelect", 1, 5);
$this->assertEquals(5, count($pager));
}
public function testCountLastPageWithLimits()
{
$cr = new Criteria();
$cr->add(BookPeer::AUTHOR_ID, $this->authorId);
$pager = new PropelPager($cr, "BookPeer", "doSelect", 2, 5);
$this->assertEquals(2, count($pager));
}
public function testIterateAll()
{
$cr = new Criteria();
$cr->add(BookPeer::AUTHOR_ID, $this->authorId);
$pager = new PropelPager($cr, "BookPeer", "doSelect");
$i = 0;
foreach ($pager as $key => $book) {
$i++;
}
$this->assertEquals(7, $i);
}
public function testIterateWithLimits()
{
$cr = new Criteria();
$cr->add(BookPeer::AUTHOR_ID, $this->authorId);
$pager = new PropelPager($cr, "BookPeer", "doSelect", 2, 5);
$i = 0;
foreach ($pager as $key => $book) {
$i++;
}
$this->assertEquals(2, $i);
}
public function testIterateCheckSecond()
{
$cr = new Criteria();
$cr->add(BookPeer::AUTHOR_ID, $this->authorId);
$cr->addAscendingOrderByColumn(BookPeer::TITLE);
$pager = new PropelPager($cr, "BookPeer", "doSelect");
$books = array();
foreach($pager as $book) {
$books[] = $book;
}
$this->assertEquals("Harry Potter and the Goblet of Fire", $books[2]->getTitle());
}
public function testIterateTwice()
{
$cr = new Criteria();
$cr->add(BookPeer::AUTHOR_ID, $this->authorId);
$cr->addAscendingOrderByColumn(BookPeer::TITLE);
$pager = new PropelPager($cr, "BookPeer", "doSelect");
$i = 0;
foreach($pager as $book) {
$i++;
}
foreach($pager as $book) {
$i++;
}
$this->assertEquals(14, $i);
}
}

View file

@ -0,0 +1,228 @@
<?php
/**
* $Id: ValidatorTest.php 1612 2010-03-16 22:56:21Z francois $
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once 'tools/helpers/bookstore/BookstoreEmptyTestBase.php';
/**
* Tests the validator classes.
*
* This test uses generated Bookstore classes to test the behavior of various
* validator operations.
*
* The database is relaoded before every test and flushed after every test. This
* means that you can always rely on the contents of the databases being the same
* for each test method in this class. See the BookstoreDataPopulator::populate()
* method for the exact contents of the database.
*
* @see BookstoreDataPopulator
* @author Michael Aichler <aichler@mediacluster.de>
* @package runtime.validator
*/
class ValidatorTest extends BookstoreEmptyTestBase
{
protected function setUp()
{
parent::setUp();
BookstoreDataPopulator::populate();
require_once 'tools/helpers/bookstore/validator/ISBNValidator.php';
}
/**
* Test minLength validator.
* This also tests the ${value} substitution.
*/
public function testDoValidate_MinLength()
{
$book = new Book();
$book->setTitle("12345"); // min length is 10
$res = $book->validate();
$this->assertFalse($res, "Expected validation to fail.");
$failures = $book->getValidationFailures();
$this->assertSingleValidation($failures, "Book title must be more than 10 characters long.");
}
/**
* Test unique validator.
*/
public function testDoValidate_Unique()
{
$book = new Book();
$book->setTitle("Don Juan");
$ret = $book->validate();
$failures = $book->getValidationFailures();
$this->assertSingleValidation($failures, "Book title already in database.");
}
/**
* Test recursive validaton.
*/
public function testDoValidate_Complex()
{
$book = new Book();
$book->setTitle("12345"); // min length is 10
$author = new Author();
$author->setFirstName("Hans"); // last name required, valid email format, age > 0
$review = new Review();
$review->setReviewDate("08/09/2001"); // reviewed_by column required, invalid status (new, reviewed, archived)
$book->setAuthor($author);
$book->addReview($review);
$res = $book->validate();
$this->assertFalse($res, "Expected validation to fail.");
$failures = $book->getValidationFailures();
/* Make sure 3 validation messages were returned; NOT 6, because the others were NULL */
$this->assertEquals(3, count($failures), "");
/* Make sure correct columns failed */
$expectedCols = array(
AuthorPeer::LAST_NAME,
BookPeer::TITLE,
ReviewPeer::REVIEWED_BY
);
$returnedCols = array_keys($failures);
/* implode for readability */
$this->assertEquals(implode(',', $expectedCols), implode(',', $returnedCols));
}
/**
* Test recursive validaton with specified columns.
*/
public function testDoValidate_ComplexSpecifiedCols()
{
$book = new Book();
$book->setTitle("12345"); // min length is 10
$author = new Author();
$author->setFirstName("Hans"); // last name required, valid email format, age > 0
$review = new Review();
$review->setReviewDate("08/09/2001"); // reviewed_by column required, invalid status (new, reviewed, archived)
$book->setAuthor($author);
$book->addReview($review);
$cols = array(AuthorPeer::LAST_NAME, ReviewPeer::REVIEWED_BY);
$res = $book->validate($cols);
$this->assertFalse($res, "Expected validation to fail.");
$failures = $book->getValidationFailures();
/* Make sure 3 validation messages were returned; NOT 6, because the others were NULL */
$this->assertEquals(2, count($failures), "");
/* Make sure correct columns failed */
$expectedCols = array(
AuthorPeer::LAST_NAME,
ReviewPeer::REVIEWED_BY
);
$returnedCols = array_keys($failures);
/* implode for readability */
$this->assertEquals(implode(',', $expectedCols), implode(',', $returnedCols));
}
/**
* Test the fact that validators should not complain NULL values for non-required columns.
*/
public function testDoValidate_Nulls()
{
$author = new Author();
$author->setFirstName("Malcolm"); // last name required, valid email format, age > 0
$author->setLastName("X");
$author->setEmail(null); // just to be explicit, of course these are the defaults anyway
$author->setAge(null);
$res = $author->validate();
$this->assertTrue($res, "Expected validation to pass with NULL columns");
$author->setEmail('malcolm@'); // fail
$res = $author->validate();
$this->assertFalse($res, "Expected validation to fail.");
$failures = $author->getValidationFailures();
$this->assertEquals(1, count($failures), "Expected 1 column to fail validation.");
$this->assertEquals(array(AuthorPeer::EMAIL), array_keys($failures), "Expected EMAIL to fail validation.");
}
public function testDoValidate_BasicValidatorObj()
{
$author = new Author();
$author->setFirstName("Malcolm"); // last name required, valid email format, age > 0
$author->setLastName("X");
$author->setEmail('malcolm@'); // fail
$res = $author->validate();
$this->assertFalse($res, "Expected validation to fail.");
$failures = $author->getValidationFailures();
$this->assertEquals(1, count($failures), "Expected 1 column to fail validation.");
$this->assertEquals(array(AuthorPeer::EMAIL), array_keys($failures), "Expected EMAIL to fail validation.");
$validator = $failures[AuthorPeer::EMAIL]->getValidator();
$this->assertTrue($validator instanceof MatchValidator, "Expected validator that failed to be MatchValidator");
}
public function testDoValidate_CustomValidator()
{
$book = new Book();
$book->setTitle("testDoValidate_CustomValidator"); // (valid)
$book->setISBN("Foo.Bar.Baz"); // (invalid)
$res = $book->validate();
$this->assertFalse($res, "Expected validation to fail.");
$failures = $book->getValidationFailures();
$this->assertEquals(1, count($failures), "Expected 1 column to fail validation.");
$this->assertEquals(array(BookPeer::ISBN), array_keys($failures), "Expected EMAIL to fail validation.");
$validator = $failures[BookPeer::ISBN]->getValidator();
$this->assertType('ISBNValidator', $validator, "Expected validator that failed to be ISBNValidator");
}
protected function assertSingleValidation($ret, $expectedMsg)
{
/* Make sure validation failed */
$this->assertTrue($ret !== true, "Expected validation to fail !");
/* Make sure 1 validation message was returned */
$count = count($ret);
$this->assertTrue($count === 1, "Expected that exactly one validation failed ($count) !");
/* Make sure expected validation message was returned */
$el = array_shift($ret);
$this->assertEquals($el->getMessage(), $expectedMsg, "Got unexpected validation failed message: " . $el->getMessage());
}
}