adding zend project folders into old campcaster.

This commit is contained in:
naomiaro 2010-12-07 14:19:27 -05:00
parent 56abfaf28e
commit 7ef0c18b26
4045 changed files with 1054952 additions and 0 deletions

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 ?>