PageRenderTime 54ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/test/testsuite/generator/builder/om/GeneratedObjectTest.php

https://github.com/trendone/Propel
PHP | 1548 lines | 1217 code | 190 blank | 141 comment | 13 complexity | 7dbd92177908946ecf34baa04834fb1f MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * This file is part of the Propel package.
  4. * For the full copyright and license information, please view the LICENSE
  5. * file that was distributed with this source code.
  6. *
  7. * @license MIT License
  8. */
  9. require_once dirname(__FILE__) . '/../../../../tools/helpers/bookstore/BookstoreTestBase.php';
  10. require_once dirname(__FILE__) . '/../../../../../generator/lib/util/PropelQuickBuilder.php';
  11. /**
  12. * Tests the generated Object classes.
  13. *
  14. * This test uses generated Bookstore classes to test the behavior of various
  15. * object operations. The _idea_ here is to test every possible generated method
  16. * from Object.tpl; if necessary, bookstore will be expanded to accommodate this.
  17. *
  18. * The database is relaoded before every test and flushed after every test. This
  19. * means that you can always rely on the contents of the databases being the same
  20. * for each test method in this class. See the BookstoreDataPopulator::populate()
  21. * method for the exact contents of the database.
  22. *
  23. * @see BookstoreDataPopulator
  24. * @author Hans Lellelid <hans@xmpl.org>
  25. * @package generator.builder.om
  26. */
  27. class GeneratedObjectTest extends BookstoreTestBase
  28. {
  29. protected function setUp()
  30. {
  31. parent::setUp();
  32. require_once dirname(__FILE__) . '/../../../../tools/helpers/bookstore/behavior/TestAuthor.php';
  33. }
  34. /**
  35. * Test saving an object after setting default values for it.
  36. */
  37. public function testSaveWithDefaultValues()
  38. {
  39. // From the schema.xml, I am relying on the following:
  40. // - that 'Penguin' is the default Name for a Publisher
  41. // - that 2001-01-01 is the default ReviewDate for a Review
  42. // 1) check regular values (VARCHAR)
  43. $pub = new Publisher();
  44. $pub->setName('Penguin');
  45. $pub->save();
  46. $this->assertTrue($pub->getId() !== null, "Expect Publisher to have been saved when default value set.");
  47. // 2) check date/time values
  48. $review = new Review();
  49. // note that this is different from how it's represented in schema, but should resolve to same unix timestamp
  50. $review->setReviewDate('2001-01-01');
  51. $this->assertTrue($review->isModified(), "Expect Review to have been marked 'modified' after default date/time value set.");
  52. }
  53. /**
  54. * Test isModified() to be false after setting default value second time
  55. */
  56. public function testDefaultValueSetTwice()
  57. {
  58. $pub = new Publisher();
  59. $pub->setName('Penguin');
  60. $pub->save();
  61. $pubId = $pub->getId();
  62. PublisherPeer::clearInstancePool();
  63. $pub2 = PublisherPeer::retrieveByPK($pubId);
  64. $pub2->setName('Penguin');
  65. $this->assertFalse($pub2->isModified(), "Expect Publisher to be not modified after setting default value second time.");
  66. }
  67. public function testHasApplyDefaultValues()
  68. {
  69. $this->assertTrue(method_exists('Publisher', 'applyDefaultValues'), 'Tables with default values should have an applyDefaultValues() method');
  70. $this->assertFalse(method_exists('Book', 'applyDefaultValues'), 'Tables with no default values should not have an applyDefaultValues() method');
  71. }
  72. /**
  73. * Test default return values.
  74. */
  75. public function testDefaultValues()
  76. {
  77. $r = new Review();
  78. $this->assertEquals('2001-01-01', $r->getReviewDate('Y-m-d'));
  79. $this->assertFalse($r->isModified(), "expected isModified() to be false");
  80. $acct = new BookstoreEmployeeAccount();
  81. $this->assertEquals(true, $acct->getEnabled());
  82. $this->assertFalse($acct->isModified());
  83. $acct->setLogin("testuser");
  84. $acct->setPassword("testpass");
  85. $this->assertTrue($acct->isModified());
  86. }
  87. /**
  88. * Tests the use of default expressions and the reloadOnInsert and reloadOnUpdate attributes.
  89. *
  90. * @link http://propel.phpdb.org/trac/ticket/378
  91. * @link http://propel.phpdb.org/trac/ticket/555
  92. */
  93. public function testDefaultExpresions()
  94. {
  95. if (Propel::getDb(BookstoreEmployeePeer::DATABASE_NAME) instanceof DBSqlite) {
  96. $this->markTestSkipped("Cannot test default expressions with SQLite");
  97. }
  98. BookstoreEmployeeAccountPeer::doDeleteAll();
  99. $b = new Bookstore();
  100. $b->setStoreName("Foo!");
  101. $b->save();
  102. $employee = new BookstoreEmployee();
  103. $employee->setName("Johnny Walker");
  104. $acct = new BookstoreEmployeeAccount();
  105. $acct->setBookstoreEmployee($employee);
  106. $acct->setLogin("test-login");
  107. $this->assertNull($acct->getCreated(), "Expected created column to be NULL.");
  108. $this->assertNull($acct->getAuthenticator(), "Expected authenticator column to be NULL.");
  109. $acct->save();
  110. $acct = BookstoreEmployeeAccountPeer::retrieveByPK($acct->getEmployeeId());
  111. $this->assertNotNull($acct->getAuthenticator(), "Expected a valid (non-NULL) authenticator column after save.");
  112. $this->assertEquals('Password', $acct->getAuthenticator(), "Expected authenticator='Password' after save.");
  113. $this->assertNotNull($acct->getCreated(), "Expected a valid date after retrieving saved object.");
  114. $now = new DateTime("now");
  115. $this->assertEquals($now->format("Y-m-d"), $acct->getCreated("Y-m-d"));
  116. $acct->setCreated($now);
  117. $this->assertEquals($now->format("Y-m-d"), $acct->getCreated("Y-m-d"));
  118. // Unfortunately we can't really test the conjunction of reloadOnInsert and reloadOnUpdate when using just
  119. // default values. (At least not in a cross-db way.)
  120. }
  121. /**
  122. * Tests the use of default expressions and the reloadOnInsert attribute.
  123. *
  124. * @link http://propel.phpdb.org/trac/ticket/378
  125. * @link http://propel.phpdb.org/trac/ticket/555
  126. */
  127. public function testDefaultExpresions_ReloadOnInsert()
  128. {
  129. if (Propel::getDb(BookstoreEmployeePeer::DATABASE_NAME) instanceof DBSqlite) {
  130. $this->markTestSkipped("Cannot test default date expressions with SQLite");
  131. }
  132. // Create a new bookstore, contest, bookstore_contest, and bookstore_contest_entry
  133. $b = new Bookstore();
  134. $b->setStoreName("Barnes & Noble");
  135. $b->save();
  136. $c = new Contest();
  137. $c->setName("Bookathon Contest");
  138. $c->save();
  139. $bc = new BookstoreContest();
  140. $bc->setBookstore($b);
  141. $bc->setContest($c);
  142. $bc->save();
  143. $c = new Customer();
  144. $c->setName("Happy Customer");
  145. $c->save();
  146. $bce = new BookstoreContestEntry();
  147. $bce->setBookstore($b);
  148. $bce->setBookstoreContest($bc);
  149. $bce->setCustomer($c);
  150. $bce->save();
  151. $this->assertNotNull($bce->getEntryDate(), "Expected a non-null entry_date after save.");
  152. }
  153. /**
  154. * Tests the overriding reloadOnInsert at runtime.
  155. *
  156. * @link http://propel.phpdb.org/trac/ticket/378
  157. * @link http://propel.phpdb.org/trac/ticket/555
  158. */
  159. public function testDefaultExpresions_ReloadOnInsert_Override()
  160. {
  161. if (Propel::getDb(BookstoreEmployeePeer::DATABASE_NAME) instanceof DBSqlite) {
  162. $this->markTestSkipped("Cannot test default date expressions with SQLite");
  163. }
  164. // Create a new bookstore, contest, bookstore_contest, and bookstore_contest_entry
  165. $b = new Bookstore();
  166. $b->setStoreName("Barnes & Noble");
  167. $b->save();
  168. $c = new Contest();
  169. $c->setName("Bookathon Contest");
  170. $c->save();
  171. $bc = new BookstoreContest();
  172. $bc->setBookstore($b);
  173. $bc->setContest($c);
  174. $bc->save();
  175. $c = new Customer();
  176. $c->setName("Happy Customer");
  177. $c->save();
  178. $bce = new BookstoreContestEntry();
  179. $bce->setBookstore($b);
  180. $bce->setBookstoreContest($bc);
  181. $bce->setCustomer($c);
  182. $bce->save(null, $skipReload=true);
  183. $this->assertNull($bce->getEntryDate(), "Expected a NULL entry_date after save.");
  184. }
  185. /**
  186. * Tests the use of default expressions and the reloadOnUpdate attribute.
  187. *
  188. * @link http://propel.phpdb.org/trac/ticket/555
  189. */
  190. public function testDefaultExpresions_ReloadOnUpdate()
  191. {
  192. $b = new Bookstore();
  193. $b->setStoreName("Foo!");
  194. $b->save();
  195. $sale = new BookstoreSale();
  196. $sale->setBookstore(BookstorePeer::doSelectOne(new Criteria()));
  197. $sale->setSaleName("Spring Sale");
  198. $sale->save();
  199. // Expect that default values are set, but not default expressions
  200. $this->assertNull($sale->getDiscount(), "Expected discount to be NULL.");
  201. $sale->setSaleName("Winter Clearance");
  202. $sale->save();
  203. // Since reloadOnUpdate = true, we expect the discount to be set now.
  204. $this->assertNotNull($sale->getDiscount(), "Expected discount to be non-NULL after save.");
  205. }
  206. /**
  207. * Tests the overriding reloadOnUpdate at runtime.
  208. *
  209. * @link http://propel.phpdb.org/trac/ticket/378
  210. * @link http://propel.phpdb.org/trac/ticket/555
  211. */
  212. public function testDefaultExpresions_ReloadOnUpdate_Override()
  213. {
  214. $b = new Bookstore();
  215. $b->setStoreName("Foo!");
  216. $b->save();
  217. $sale = new BookstoreSale();
  218. $sale->setBookstore(BookstorePeer::doSelectOne(new Criteria()));
  219. $sale->setSaleName("Spring Sale");
  220. $sale->save();
  221. // Expect that default values are set, but not default expressions
  222. $this->assertNull($sale->getDiscount(), "Expected discount to be NULL.");
  223. $sale->setSaleName("Winter Clearance");
  224. $sale->save(null, $skipReload=true);
  225. // Since reloadOnUpdate = true, we expect the discount to be set now.
  226. $this->assertNull($sale->getDiscount(), "Expected NULL value for discount after save.");
  227. }
  228. /**
  229. * Testing creating & saving new object & instance pool.
  230. */
  231. public function testObjectInstances_New()
  232. {
  233. $emp = new BookstoreEmployee();
  234. $emp->setName(md5(microtime()));
  235. $emp->save();
  236. $id = $emp->getId();
  237. $retrieved = BookstoreEmployeePeer::retrieveByPK($id);
  238. $this->assertSame($emp, $retrieved, "Expected same object (from instance pool)");
  239. }
  240. /**
  241. *
  242. */
  243. public function testObjectInstances_Fkeys()
  244. {
  245. // Establish a relationship between one employee and account
  246. // and then change the employee_id and ensure that the account
  247. // is not pulling the old employee.
  248. $pub1 = new Publisher();
  249. $pub1->setName('Publisher 1');
  250. $pub1->save();
  251. $pub2 = new Publisher();
  252. $pub2->setName('Publisher 2');
  253. $pub2->save();
  254. $book = new Book();
  255. $book->setTitle("Book Title");
  256. $book->setISBN("1234");
  257. $book->setPublisher($pub1);
  258. $book->save();
  259. $this->assertSame($pub1, $book->getPublisher());
  260. // now change values behind the scenes
  261. $con = Propel::getConnection(BookstoreEmployeeAccountPeer::DATABASE_NAME);
  262. $con->exec("UPDATE " . BookPeer::TABLE_NAME . " SET "
  263. . " publisher_id = " . $pub2->getId()
  264. . " WHERE id = " . $book->getId());
  265. $book2 = BookPeer::retrieveByPK($book->getId());
  266. $this->assertSame($book, $book2, "Expected same book object instance");
  267. $this->assertEquals($pub1->getId(), $book->getPublisherId(), "Expected book to have OLD publisher id before reload()");
  268. $book->reload();
  269. $this->assertEquals($pub2->getId(), $book->getPublisherId(), "Expected book to have new publisher id");
  270. $this->assertSame($pub2, $book->getPublisher(), "Expected book to have new publisher object associated.");
  271. // Now let's set it back, just to be double sure ...
  272. $con->exec("UPDATE " . BookPeer::TABLE_NAME . " SET "
  273. . " publisher_id = " . $pub1->getId()
  274. . " WHERE id = " . $book->getId());
  275. $book->reload();
  276. $this->assertEquals($pub1->getId(), $book->getPublisherId(), "Expected book to have old publisher id (again).");
  277. $this->assertSame($pub1, $book->getPublisher(), "Expected book to have old publisher object associated (again).");
  278. }
  279. /**
  280. * Test the effect of typecast on primary key values and instance pool retrieval.
  281. */
  282. public function testObjectInstancePoolTypecasting()
  283. {
  284. $reader = new BookReader();
  285. $reader->setName("Tester");
  286. $reader->save();
  287. $readerId = $reader->getId();
  288. $book = new Book();
  289. $book->setTitle("BookTest");
  290. $book->setISBN("TEST");
  291. $book->save();
  292. $bookId = $book->getId();
  293. $opinion = new BookOpinion();
  294. $opinion->setBookId((string) $bookId);
  295. $opinion->setReaderId((string) $readerId);
  296. $opinion->setRating(5);
  297. $opinion->setRecommendToFriend(false);
  298. $opinion->save();
  299. $opinion2 = BookOpinionPeer::retrieveByPK($bookId, $readerId);
  300. $this->assertSame($opinion, $opinion2, "Expected same object to be retrieved from differently type-casted primary key values.");
  301. }
  302. /**
  303. * Test saving an object and getting correct number of affected rows from save().
  304. * This includes tests of cascading saves to fk-related objects.
  305. */
  306. public function testSaveReturnValues()
  307. {
  308. $author = new Author();
  309. $author->setFirstName("Mark");
  310. $author->setLastName("Kurlansky");
  311. // do not save
  312. $pub = new Publisher();
  313. $pub->setName("Penguin Books");
  314. // do not save
  315. $book = new Book();
  316. $book->setTitle("Salt: A World History");
  317. $book->setISBN("0142001619");
  318. $book->setAuthor($author);
  319. $book->setPublisher($pub);
  320. $affected = $book->save();
  321. $this->assertEquals(3, $affected, "Expected 3 affected rows when saving book + publisher + author.");
  322. // change nothing ...
  323. $affected = $book->save();
  324. $this->assertEquals(0, $affected, "Expected 0 affected rows when saving already-saved book.");
  325. // modify the book (UPDATE)
  326. $book->setTitle("Salt A World History");
  327. $affected = $book->save();
  328. $this->assertEquals(1, $affected, "Expected 1 affected row when saving modified book.");
  329. // modify the related author
  330. $author->setLastName("Kurlanski");
  331. $affected = $book->save();
  332. $this->assertEquals(1, $affected, "Expected 1 affected row when saving book with updated author.");
  333. // modify both the related author and the book
  334. $author->setLastName("Kurlansky");
  335. $book->setTitle("Salt: A World History");
  336. $affected = $book->save();
  337. $this->assertEquals(2, $affected, "Expected 2 affected rows when saving updated book with updated author.");
  338. }
  339. /*
  340. WTF!!!!!!
  341. public function testSaveCanInsertEmptyObjects()
  342. {
  343. $b = new Book();
  344. $b->save();
  345. $this->assertFalse($b->isNew());
  346. $this->assertNotNull($b->getId());
  347. }
  348. */
  349. public function testSaveCanInsertNonEmptyObjects()
  350. {
  351. $b = new Book();
  352. $b->setTitle('foo');
  353. $b->setIsbn('124');
  354. $b->save();
  355. $this->assertFalse($b->isNew());
  356. $this->assertNotNull($b->getId());
  357. }
  358. /**
  359. *
  360. */
  361. public function testNoColsModified()
  362. {
  363. $e1 = new BookstoreEmployee();
  364. $e1->setName('Employee 1');
  365. $e2 = new BookstoreEmployee();
  366. $e2->setName('Employee 2');
  367. $super = new BookstoreEmployee();
  368. // we don't know who the supervisor is yet
  369. $super->addSubordinate($e1);
  370. $super->addSubordinate($e2);
  371. $affected = $super->save();
  372. }
  373. public function testIsModifiedIsFalseForNewObjects()
  374. {
  375. $a = new Author();
  376. $this->assertFalse($a->isModified());
  377. }
  378. public function testIsModifiedIsTrueForNewObjectsWithModifications()
  379. {
  380. $a = new Author();
  381. $a->setFirstName('Foo');
  382. $this->assertTrue($a->isModified());
  383. }
  384. public function testIsModifiedIsFalseForNewObjectsWithNullModifications()
  385. {
  386. $a = new Author();
  387. $a->setFirstName(null);
  388. $this->assertFalse($a->isModified());
  389. }
  390. public function testIsModifiedIsFalseForObjectsAfterResetModified()
  391. {
  392. $a = new Author();
  393. $a->setFirstName('Foo');
  394. $a->resetModified();
  395. $this->assertFalse($a->isModified());
  396. }
  397. public function testIsModifiedIsFalseForSavedObjects()
  398. {
  399. $a = new Author();
  400. $a->setFirstName('Foo');
  401. $a->setLastName('Bar');
  402. $a->save();
  403. $this->assertFalse($a->isModified());
  404. }
  405. public function testIsModifiedIsTrueForSavedObjectsWithModifications()
  406. {
  407. $a = new Author();
  408. $a->setFirstName('Foo');
  409. $this->assertTrue($a->isModified());
  410. }
  411. public function testIsModifiedIsFalseAfterSetToDefaultValueOnNewObject()
  412. {
  413. $p = new Publisher();
  414. $p->setName('Penguin'); // default column value
  415. $this->assertFalse($p->isModified());
  416. }
  417. public function testIsModifiedIsTrueAfterModifyingOnNonDefaultValueOnNewObject()
  418. {
  419. $p = new Publisher();
  420. $p->setName('Puffin Books');
  421. $this->assertTrue($p->isModified());
  422. }
  423. public function testIsModifiedIsTrueAfterSetToDefaultValueOnModifiedObject()
  424. {
  425. $p = new Publisher();
  426. $p->setName('Puffin Books');
  427. $p->resetModified();
  428. $p->setName('Penguin'); // default column value
  429. $this->assertTrue($p->isModified());
  430. }
  431. public function testIsModifiedIsFalseAfterChangingColumnTypeButNotValue()
  432. {
  433. $a = new Author();
  434. $a->setFirstName('1');
  435. $a->setAge(25);
  436. $a->resetModified();
  437. $a->setAge('25');
  438. $this->assertFalse($a->isModified());
  439. $a->setFirstName(1);
  440. $this->assertFalse($a->isModified());
  441. }
  442. public function testIsModifiedAndNullValues()
  443. {
  444. $a = new Author();
  445. $a->setFirstName('');
  446. $a->setLastName('Bar');
  447. $a->setAge(0);
  448. $a->save();
  449. $a->setFirstName(null);
  450. $this->assertTrue($a->isModified(), "Expected Author to be modified after changing empty string column value to NULL.");
  451. $a->setAge(null);
  452. $this->assertTrue($a->isModified(), "Expected Author to be modified after changing 0-value int column to NULL.");
  453. $a->setFirstName('');
  454. $this->assertTrue($a->isModified(), "Expected Author to be modified after changing NULL column value to empty string.");
  455. $a->setAge(0);
  456. $this->assertTrue($a->isModified(), "Expected Author to be modified after changing NULL column to 0-value int.");
  457. }
  458. /**
  459. * Test checking for non-default values.
  460. * @see http://propel.phpdb.org/trac/ticket/331
  461. */
  462. public function testHasOnlyDefaultValues()
  463. {
  464. $emp = new BookstoreEmployee();
  465. $emp->setName(md5(microtime()));
  466. $acct2 = new BookstoreEmployeeAccount();
  467. $acct = new BookstoreEmployeeAccount();
  468. $acct->setBookstoreEmployee($emp);
  469. $acct->setLogin("foo");
  470. $acct->setPassword("bar");
  471. $acct->save();
  472. $this->assertFalse($acct->isModified(), "Expected BookstoreEmployeeAccount NOT to be modified after save().");
  473. $acct->setEnabled(true);
  474. $acct->setPassword($acct2->getPassword());
  475. $this->assertTrue($acct->isModified(), "Expected BookstoreEmployeeAccount to be modified after setting default values.");
  476. $this->assertTrue($acct->hasOnlyDefaultValues(), "Expected BookstoreEmployeeAccount to not have only default values.");
  477. $acct->setPassword("bar");
  478. $this->assertFalse($acct->hasOnlyDefaultValues(), "Expected BookstoreEmployeeAccount to have at one non-default value after setting one value to non-default.");
  479. // Test a default date/time value
  480. $r = new Review();
  481. $r->setReviewDate(new DateTime("now"));
  482. $this->assertFalse($r->hasOnlyDefaultValues());
  483. }
  484. public function testCountRefFk()
  485. {
  486. $book = new Book();
  487. $book->setTitle("Test Book");
  488. $book->setISBN("TT-EE-SS-TT");
  489. $num = 5;
  490. for ($i=2; $i < $num + 2; $i++) {
  491. $r = new Review();
  492. $r->setReviewedBy('Hans ' . $num);
  493. $dt = new DateTime("now");
  494. $dt->modify("-".$i." weeks");
  495. $r->setReviewDate($dt);
  496. $r->setRecommended(($i % 2) == 0);
  497. $book->addReview($r);
  498. }
  499. $this->assertEquals($num, $book->countReviews(), "Expected countReviews to return $num");
  500. $this->assertEquals($num, count($book->getReviews()), "Expected getReviews to return $num reviews");
  501. $book->save();
  502. BookPeer::clearInstancePool();
  503. ReviewPeer::clearInstancePool();
  504. $book = BookPeer::retrieveByPK($book->getId());
  505. $this->assertEquals($num, $book->countReviews(), "Expected countReviews() to return $num (after save)");
  506. $this->assertEquals($num, count($book->getReviews()), "Expected getReviews() to return $num (after save)");
  507. // Now set different criteria and expect different results
  508. $c = new Criteria();
  509. $c->add(ReviewPeer::RECOMMENDED, false);
  510. $this->assertEquals(floor($num/2), $book->countReviews($c), "Expected " . floor($num/2) . " results from countReviews(recomm=false)");
  511. // Change Criteria, run again -- expect different.
  512. $c = new Criteria();
  513. $c->add(ReviewPeer::RECOMMENDED, true);
  514. $this->assertEquals(ceil($num/2), count($book->getReviews($c)), "Expected " . ceil($num/2) . " results from getReviews(recomm=true)");
  515. $this->assertEquals($num, $book->countReviews(), "Expected countReviews to return $num with new empty Criteria");
  516. }
  517. /**
  518. * Test copying when an object has composite primary key.
  519. * @link http://propel.phpdb.org/trac/ticket/618
  520. */
  521. public function testCopy_CompositePK()
  522. {
  523. $br = new BookReader();
  524. $br->setName("TestReader");
  525. $br->save();
  526. $br->copy();
  527. $b = new Book();
  528. $b->setTitle("TestBook");
  529. $b->setISBN("XX-XX-XX-XX");
  530. $b->save();
  531. $op = new BookOpinion();
  532. $op->setBookReader($br);
  533. $op->setBook($b);
  534. $op->setRating(10);
  535. $op->setRecommendToFriend(true);
  536. $op->save();
  537. $br2 = $br->copy(true);
  538. $this->assertNull($br2->getId());
  539. $opinions = $br2->getBookOpinions();
  540. $this->assertEquals(1, count($opinions), "Expected to have a related BookOpinion after copy()");
  541. // We DO expect the reader_id to be null
  542. $this->assertNull($opinions[0]->getReaderId());
  543. // but we DO NOT expect the book_id to be null
  544. $this->assertEquals($op->getBookId(), $opinions[0]->getBookId());
  545. }
  546. /**
  547. *
  548. */
  549. public function testCopyConcretInheritance()
  550. {
  551. $concreteArticle = new ConcreteArticle();
  552. $concreteArticle->setBody('TestBody');
  553. $concreteArticle->save();
  554. $copy = $concreteArticle->copy();
  555. $this->assertNull($copy->getId(), "single PK not autoincremented shouldn't be copied");
  556. }
  557. public function testDeepCopyConcretInheritance()
  558. {
  559. $comment1 = new ConcreteComment();
  560. $comment1->setMessage('my-new-comment1');
  561. $concreteArticle = new ConcreteArticle();
  562. $concreteArticle->setBody('TestBody');
  563. $concreteArticle->addConcreteComment($comment1);
  564. $concreteArticle->save();
  565. $comment1->save();
  566. $this->assertNotNull($comment1->getId());
  567. $this->assertNotNull($concreteArticle->getId());
  568. $this->assertEquals(1, $concreteArticle->countConcreteComments());
  569. $this->assertEquals($comment1->getConcreteContentId(), $concreteArticle->getId());
  570. $copy = $concreteArticle->copy(true);
  571. $this->assertNull($copy->getId());
  572. $this->assertEquals(1, $concreteArticle->countConcreteComments());
  573. $comments = $copy->getConcreteContent()->getConcreteComments();
  574. $this->assertEquals('my-new-comment1', $comments[0]->getMessage());
  575. }
  576. public function testToArray()
  577. {
  578. $b = new Book();
  579. $b->setTitle('Don Juan');
  580. $arr1 = $b->toArray();
  581. $expectedKeys = array(
  582. 'Id',
  583. 'Title',
  584. 'ISBN',
  585. 'Price',
  586. 'PublisherId',
  587. 'AuthorId'
  588. );
  589. $this->assertEquals($expectedKeys, array_keys($arr1), 'toArray() returns an associative array with BasePeer::TYPE_PHPNAME keys by default');
  590. $this->assertEquals('Don Juan', $arr1['Title'], 'toArray() returns an associative array representation of the object');
  591. }
  592. public function testToArrayKeyType()
  593. {
  594. $b = new Book();
  595. $b->setTitle('Don Juan');
  596. $arr1 = $b->toArray(BasePeer::TYPE_COLNAME);
  597. $expectedKeys = array(
  598. BookPeer::ID,
  599. BookPeer::TITLE,
  600. BookPeer::ISBN,
  601. BookPeer::PRICE,
  602. BookPeer::PUBLISHER_ID,
  603. BookPeer::AUTHOR_ID
  604. );
  605. $this->assertEquals($expectedKeys, array_keys($arr1), 'toArray() accepts a $keyType parameter to change the result keys');
  606. $this->assertEquals('Don Juan', $arr1[BookPeer::TITLE], 'toArray() returns an associative array representation of the object');
  607. }
  608. public function testToArrayKeyTypePreDefined()
  609. {
  610. $schema = <<<EOF
  611. <database name="test">
  612. <table name="test_key_type_table">
  613. <column name="id_key_type" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
  614. <column name="name_key_type" type="VARCHAR" />
  615. </table>
  616. </database>
  617. EOF;
  618. $builder = new PropelQuickBuilder();
  619. $builder->setSchema($schema);
  620. $builder->getConfig()->setBuildProperty('defaultKeyType', 'studlyPhpName');
  621. $builder->buildClasses();
  622. $expectedKeys = array(
  623. 'idKeyType',
  624. 'nameKeyType',
  625. );
  626. $object = new TestKeyTypeTable();
  627. $this->assertEquals($expectedKeys, array_keys($object->toArray()), 'toArray() returns an associative array with pre-defined key type in properties.');
  628. }
  629. /**
  630. * Test regexp validator for ticket:542
  631. * @link http://propel.phpdb.org/trac/ticket/542
  632. */
  633. public function testRegexValidator()
  634. {
  635. $b = new Bookstore();
  636. $b->setWebsite("http://this.is.valid.com/foo.bar");
  637. $res = $b->validate();
  638. $this->assertTrue($res, "Expected URL to validate");
  639. }
  640. /**
  641. * Test that setting the auto-increment primary key will result in exception.
  642. */
  643. public function testSettingAutoIncrementPK()
  644. {
  645. // The whole test is in a transaction, but this test needs real transactions
  646. $this->con->commit();
  647. $b = new Bookstore();
  648. $b->setId(1);
  649. $b->setStoreName("Test");
  650. try {
  651. $b->save();
  652. $this->fail("Expected setting auto-increment primary key to result in Exception");
  653. } catch (Exception $x) {
  654. $this->assertInstanceOf('PropelException', $x);
  655. }
  656. // ... but we should silently ignore NULL values, since these are really
  657. // the same as "not set" in PHP world.
  658. $b = new Bookstore();
  659. $b->setId(null);
  660. $b->setStoreName("Test2");
  661. try {
  662. $b->save();
  663. } catch (Exception $x) {
  664. $this->fail("Expected no exception when setting auto-increment primary key to NULL");
  665. }
  666. // success ...
  667. $this->con->beginTransaction();
  668. }
  669. /**
  670. * Checks wether we are allowed to specify the primary key on a
  671. * table with allowPkInsert=true set
  672. *
  673. * saves the object, gets it from data-source again and then compares
  674. * them for equality (thus the instance pool is also checked)
  675. */
  676. public function testAllowPkInsertOnIdMethodNativeTable()
  677. {
  678. CustomerPeer::doDeleteAll();
  679. $cu = new Customer;
  680. $cu->setPrimaryKey(100000);
  681. $cu->save();
  682. $this->assertEquals(100000, $cu->getPrimaryKey());
  683. $cu2 = CustomerPeer::retrieveByPk(100000);
  684. $this->assertSame($cu, $cu2);
  685. }
  686. /**
  687. * Checks if it is allowed to save new, empty objects with a auto increment column
  688. */
  689. public function testAllowEmptyWithAutoIncrement()
  690. {
  691. $bookreader = new BookReader();
  692. $bookreader->save();
  693. $this->assertFalse($bookreader->isNew());
  694. }
  695. /**
  696. * Test foreign key relationships based on references to unique cols but not PK.
  697. * @link http://propel.phpdb.org/trac/ticket/691
  698. */
  699. public function testUniqueFkRel()
  700. {
  701. BookstoreEmployeeAccountPeer::doDeleteAll();
  702. $employee = new BookstoreEmployee();
  703. $employee->setName("Johnny Walker");
  704. $acct = new BookstoreEmployeeAccount();
  705. $acct->setBookstoreEmployee($employee);
  706. $acct->setLogin("test-login");
  707. $acct->save();
  708. $acctId = $acct->getEmployeeId();
  709. $al = new AcctAuditLog();
  710. $al->setBookstoreEmployeeAccount($acct);
  711. $al->save();
  712. $alId = $al->getId();
  713. BookstoreEmployeePeer::clearInstancePool();
  714. BookstoreEmployeeAccountPeer::clearInstancePool();
  715. AcctAuditLogPeer::clearInstancePool();
  716. $al2 = AcctAuditLogPeer::retrieveByPK($alId);
  717. /* @var $al2 AcctAuditLog */
  718. $mapacct = $al2->getBookstoreEmployeeAccount();
  719. $lookupacct = BookstoreEmployeeAccountPeer::retrieveByPK($acctId);
  720. $logs = $lookupacct->getAcctAuditLogs();
  721. $this->assertTrue(count($logs) == 1, "Expected 1 audit log result.");
  722. $this->assertEquals($logs[0]->getId(), $al->getId(), "Expected returned audit log to match created audit log.");
  723. }
  724. public function testIsPrimaryKeyNull()
  725. {
  726. $b = new Book();
  727. $this->assertTrue($b->isPrimaryKeyNull());
  728. $b->setPrimaryKey(123);
  729. $this->assertFalse($b->isPrimaryKeyNull());
  730. $b->setPrimaryKey(null);
  731. $this->assertTrue($b->isPrimaryKeyNull());
  732. }
  733. public function testIsPrimaryKeyNullCompmosite()
  734. {
  735. $b = new BookOpinion();
  736. $this->assertTrue($b->isPrimaryKeyNull());
  737. $b->setPrimaryKey(array(123, 456));
  738. $this->assertFalse($b->isPrimaryKeyNull());
  739. $b->setPrimaryKey(array(123, null));
  740. $this->assertFalse($b->isPrimaryKeyNull());
  741. $b->setPrimaryKey(array(null, 456));
  742. $this->assertFalse($b->isPrimaryKeyNull());
  743. $b->setPrimaryKey(array(null, null));
  744. $this->assertTrue($b->isPrimaryKeyNull());
  745. }
  746. public function testAddToStringDefault()
  747. {
  748. $this->assertTrue(method_exists('Author', '__toString'), 'addPrimaryString() adds a __toString() method even if no column has the primaryString attribute');
  749. $author = new Author();
  750. $author->setFirstName('Leo');
  751. $author->setLastName('Tolstoi');
  752. $expected = <<<EOF
  753. Id: null
  754. FirstName: Leo
  755. LastName: Tolstoi
  756. Email: null
  757. Age: null
  758. EOF;
  759. $this->assertEquals($expected, (string) $author, 'addPrimaryString() adds a __toString() method returning the YAML representation of the object where no column is defined as primaryString');
  760. }
  761. public function testAddToStringPrimaryString()
  762. {
  763. $this->assertTrue(method_exists('Book', '__toString'), 'addPrimaryString() adds a __toString() method if a column has the primaryString attribute');
  764. $book = new Book();
  765. $book->setTitle('foo');
  766. $this->assertEquals('foo', (string) $book, 'addPrimaryString() adds a __toString() method returning the value of the the first column where primaryString is true');
  767. }
  768. public function testPreInsert()
  769. {
  770. $author = new TestAuthor();
  771. $author->setFirstName("bogus");
  772. $author->setLastName("Lastname");
  773. $author->save();
  774. $this->assertEquals('PreInsertedFirstname', $author->getFirstName());
  775. }
  776. public function testPreUpdate()
  777. {
  778. $author = new TestAuthor();
  779. $author->setFirstName("bogus");
  780. $author->setLastName("Lastname");
  781. $author->save();
  782. $author->setNew(false);
  783. $author->save();
  784. $this->assertEquals('PreUpdatedFirstname', $author->getFirstName());
  785. }
  786. public function testPostInsert()
  787. {
  788. $author = new TestAuthor();
  789. $author->setFirstName("bogus");
  790. $author->setLastName("Lastname");
  791. $author->save();
  792. $this->assertEquals('PostInsertedLastName', $author->getLastName());
  793. }
  794. public function testPostUpdate()
  795. {
  796. $author = new TestAuthor();
  797. $author->setFirstName("bogus");
  798. $author->setLastName("Lastname");
  799. $author->save();
  800. $author->setNew(false);
  801. $author->save();
  802. $this->assertEquals('PostUpdatedLastName', $author->getLastName());
  803. }
  804. public function testPreSave()
  805. {
  806. $author = new TestAuthor();
  807. $author->setFirstName("bogus");
  808. $author->setLastName("Lastname");
  809. $author->save();
  810. $this->assertEquals('pre@save.com', $author->getEmail());
  811. }
  812. public function testPreSaveFalse()
  813. {
  814. $con = Propel::getConnection(AuthorPeer::DATABASE_NAME);
  815. $author = new TestAuthorSaveFalse();
  816. $author->setFirstName("bogus");
  817. $author->setLastName("Lastname");
  818. $res = $author->save($con);
  819. $this->assertEquals(0, $res);
  820. $this->assertEquals('pre@save.com', $author->getEmail());
  821. $this->assertNotEquals(115, $author->getAge());
  822. $this->assertTrue($author->isNew());
  823. $this->assertEquals(1, $con->getNestedTransactionCount());
  824. }
  825. public function testPostSave()
  826. {
  827. $author = new TestAuthor();
  828. $author->setFirstName("bogus");
  829. $author->setLastName("Lastname");
  830. $author->save();
  831. $this->assertEquals(115, $author->getAge());
  832. }
  833. public function testPreDelete()
  834. {
  835. $author = new TestAuthor();
  836. $author->setFirstName("bogus");
  837. $author->setLastName("Lastname");
  838. $author->save();
  839. $author->delete();
  840. $this->assertEquals("Pre-Deleted", $author->getFirstName());
  841. }
  842. public function testPreDeleteFalse()
  843. {
  844. $con = Propel::getConnection(AuthorPeer::DATABASE_NAME);
  845. $author = new TestAuthorDeleteFalse();
  846. $author->setFirstName("bogus");
  847. $author->setLastName("Lastname");
  848. $author->save($con);
  849. $author->delete($con);
  850. $this->assertEquals("Pre-Deleted", $author->getFirstName());
  851. $this->assertNotEquals("Post-Deleted", $author->getLastName());
  852. $this->assertFalse($author->isDeleted());
  853. $this->assertEquals(1, $con->getNestedTransactionCount());
  854. }
  855. public function testPostDelete()
  856. {
  857. $author = new TestAuthor();
  858. $author->setFirstName("bogus");
  859. $author->setLastName("Lastname");
  860. $author->save();
  861. $author->delete();
  862. $this->assertEquals("Post-Deleted", $author->getLastName());
  863. }
  864. public function testPostHydrate()
  865. {
  866. $author = new TestAuthor();
  867. $author->hydrate(array(1, 'bogus', 'Lastname', 'bogus@mail.com', 21));
  868. $this->assertEquals("Post-Hydrated", $author->getLastName());
  869. }
  870. public function testMagicVirtualColumnGetter()
  871. {
  872. $book = new Book();
  873. $book->setVirtualColumn('Foo', 'bar');
  874. $this->assertEquals('bar', $book->getFoo(), 'generated __call() catches getters for virtual columns');
  875. $book = new Book();
  876. $book->setVirtualColumn('foo', 'bar');
  877. $this->assertEquals('bar', $book->getFoo(), 'generated __call() catches getters for virtual columns starting with a lowercase character');
  878. }
  879. /**
  880. * @expectedException PropelException
  881. */
  882. public function testMagicCallUndefined()
  883. {
  884. $book = new Book();
  885. $book->fooMethodName();
  886. }
  887. public static function conditionsForTestReadOnly()
  888. {
  889. return array(
  890. array('reload'),
  891. array('delete'),
  892. array('save'),
  893. array('doSave'),
  894. );
  895. }
  896. /**
  897. * @dataProvider conditionsForTestReadOnly
  898. */
  899. public function testReadOnly($method)
  900. {
  901. $cv = new ContestView();
  902. $this->assertFalse(method_exists($cv, $method), 'readOnly tables end up with no ' . $method . ' method in the generated object class');
  903. }
  904. public function testSetterOneToMany()
  905. {
  906. // Ensure no data
  907. BookQuery::create()->deleteAll();
  908. AuthorQuery::create()->deleteAll();
  909. $coll = new PropelObjectCollection();
  910. $coll->setModel('Book');
  911. for ($i = 0; $i < 3; $i++) {
  912. $b = new Book();
  913. $b->setTitle('Title ' . $i);
  914. $b->setIsbn('1204' . $i);
  915. $coll[] = $b;
  916. }
  917. $this->assertEquals(3, $coll->count());
  918. $a = new Author();
  919. $a->setFirstName('Foo');
  920. $a->setLastName('Bar');
  921. $a->setBooks($coll);
  922. $a->save();
  923. $this->assertInstanceOf('PropelObjectCollection', $a->getBooks());
  924. $this->assertEquals(3, $a->getBooks()->count());
  925. $this->assertEquals(1, AuthorQuery::create()->count());
  926. $this->assertEquals(3, BookQuery::create()->count());
  927. $coll->shift();
  928. $this->assertEquals(2, $coll->count());
  929. $a->setBooks($coll);
  930. $a->save();
  931. $this->assertEquals(2, $a->getBooks()->count());
  932. $this->assertEquals(1, AuthorQuery::create()->count());
  933. //The book is not deleted because his fk is not required
  934. $this->assertEquals(3, BookQuery::create()->count());
  935. $newBook = new Book();
  936. $newBook->setTitle('My New Book');
  937. $newBook->setIsbn(1234);
  938. // Kind of new collection
  939. $coll = clone $coll;
  940. $coll[] = $newBook;
  941. $a->setBooks($coll);
  942. $a->save();
  943. $this->assertEquals(3, $coll->count());
  944. $this->assertEquals(3, $a->getBooks()->count());
  945. $this->assertEquals(1, AuthorQuery::create()->count());
  946. $this->assertEquals(4, BookQuery::create()->count());
  947. // Add a new object
  948. $newBook1 = new Book();
  949. $newBook1->setTitle('My New Book1');
  950. $newBook1->setIsbn(1256);
  951. // Existing collection - The fix around reference is tested here.
  952. $coll[] = $newBook1;
  953. $a->setBooks($coll);
  954. $a->save();
  955. $this->assertEquals(4, $coll->count());
  956. $this->assertEquals(4, $a->getBooks()->count());
  957. $this->assertEquals(1, AuthorQuery::create()->count());
  958. $this->assertEquals(5, BookQuery::create()->count());
  959. // Add the same collection
  960. $books = $a->getBooks();
  961. $a->setBooks($books);
  962. $a->save();
  963. $this->assertEquals(4, $books->count());
  964. $this->assertEquals(4, $a->getBooks()->count());
  965. $this->assertEquals(1, AuthorQuery::create()->count());
  966. $this->assertEquals(5, BookQuery::create()->count());
  967. }
  968. public function testSetterOneToManyWithFkRequired()
  969. {
  970. // Ensure no data
  971. BookSummaryQuery::create()->deleteAll();
  972. BookQuery::create()->deleteAll();
  973. $coll = new PropelObjectCollection();
  974. $coll->setModel('BookSummary');
  975. for ($i = 0; $i < 3; $i++) {
  976. $bs = new BookSummary();
  977. $bs->setSummary('A summary ' . $i);
  978. $coll[] = $bs;
  979. }
  980. $this->assertEquals(3, $coll->count());
  981. $b = new Book();
  982. $b->setTitle('myBook');
  983. $b->setBookSummarys($coll);
  984. $b->setIsbn('12242');
  985. $b->save();
  986. $this->assertInstanceOf('PropelObjectCollection', $b->getBookSummarys());
  987. $this->assertEquals(3, $b->getBookSummarys()->count());
  988. $this->assertEquals(1, BookQuery::create()->count());
  989. $this->assertEquals(3, BookSummaryQuery::create()->count());
  990. $coll->shift();
  991. $this->assertEquals(2, $coll->count());
  992. $b->setBookSummarys($coll);
  993. $b->save();
  994. $this->assertEquals(2, $b->getBookSummarys()->count());
  995. $this->assertEquals(1, BookQuery::create()->count());
  996. $this->assertEquals(2, BookSummaryQuery::create()->count());
  997. $newBookSammary = new BookSummary();
  998. $newBookSammary->setSummary('My sammary');
  999. // Kind of new collection
  1000. $coll = clone $coll;
  1001. $coll[] = $newBookSammary;
  1002. $b->setBookSummarys($coll);
  1003. $b->save();
  1004. $this->assertEquals(3, $coll->count());
  1005. $this->assertEquals(3, $b->getBookSummarys()->count());
  1006. $this->assertEquals(1, BookQuery::create()->count());
  1007. $this->assertEquals(3, BookSummaryQuery::create()->count());
  1008. // Add a new object
  1009. $newBookSammary1 = new BookSummary();
  1010. $newBookSammary1->setSummary('My sammary 1');
  1011. // Existing collection - The fix around reference is tested here.
  1012. $coll[] = $newBookSammary1;
  1013. $b->setBookSummarys($coll);
  1014. $b->save();
  1015. $this->assertEquals(4, $coll->count());
  1016. $this->assertEquals(4, $b->getBookSummarys()->count());
  1017. $this->assertEquals(1, BookQuery::create()->count());
  1018. $this->assertEquals(4, BookSummaryQuery::create()->count());
  1019. // Add the same collection
  1020. $bookSummaries = $b->getBookSummarys();
  1021. $b->setBookSummarys($bookSummaries);
  1022. $b->save();
  1023. $this->assertEquals(4, $coll->count());
  1024. $this->assertEquals(4, $b->getBookSummarys()->count());
  1025. $this->assertEquals(1, BookQuery::create()->count());
  1026. $this->assertEquals(4, BookSummaryQuery::create()->count());
  1027. }
  1028. public function testSetterOneToManyWithNoData()
  1029. {
  1030. // Ensure no data
  1031. BookQuery::create()->deleteAll();
  1032. AuthorQuery::create()->deleteAll();
  1033. $books = new PropelObjectCollection();
  1034. $this->assertEquals(0, $books->count());
  1035. // Basic usage
  1036. $a = new Author();
  1037. $a->setFirstName('Foo');
  1038. $a->setLastName('Bar');
  1039. $a->setBooks($books);
  1040. $a->save();
  1041. $this->assertEquals(0, $a->getBooks()->count());
  1042. $this->assertEquals(1, AuthorQuery::create()->count());
  1043. $this->assertEquals(0, BookQuery::create()->count());
  1044. }
  1045. public function testSetterOneToManySavesForeignObjects()
  1046. {
  1047. // Ensure no data
  1048. BookQuery::create()->deleteAll();
  1049. AuthorQuery::create()->deleteAll();
  1050. $book = new Book();
  1051. $book->setTitle('My Book');
  1052. $book->setIsbn('1245');
  1053. $book->save();
  1054. // Modify it but don't save it
  1055. $book->setTitle('My Title');
  1056. $coll = new PropelObjectCollection();
  1057. $coll[] = $book;
  1058. BookPeer::clearInstancePool();
  1059. $book = BookQuery::create()->findPk($book->getPrimaryKey());
  1060. $a = new Author();
  1061. $a->setFirstName('Foo');
  1062. $a->setLastName('Bar');
  1063. $a->setBooks($coll);
  1064. $a->save();
  1065. $this->assertEquals(1, $a->getBooks()->count());
  1066. $this->assertEquals(1, AuthorQuery::create()->count());
  1067. $this->assertEquals(1, BookQuery::create()->count());
  1068. $result = BookQuery::create()
  1069. ->filterById($book->getId())
  1070. ->select('Title')
  1071. ->findOne();
  1072. $this->assertSame('My Title', $result);
  1073. }
  1074. public function testSetterOneToManyWithNewObjects()
  1075. {
  1076. // Ensure no data
  1077. BookQuery::create()->deleteAll();
  1078. AuthorQuery::create()->deleteAll();
  1079. $coll = new PropelObjectCollection();
  1080. $coll->setModel('Book');
  1081. for ($i = 0; $i < 3; $i++) {
  1082. $b = new Book();
  1083. $b->setTitle('Book ' . $i);
  1084. $b->setIsbn('124' . $i);
  1085. $coll[] = $b;
  1086. }
  1087. $a = new Author();
  1088. $a->setFirstName('Foo');
  1089. $a->setLastName('Bar');
  1090. $a->setBooks($coll);
  1091. $a->save();
  1092. $this->assertEquals(3, $coll->count());
  1093. $this->assertEquals(3, count($a->getBooks()));
  1094. $this->assertSame($coll, $a->getBooks());
  1095. $this->assertEquals(1, AuthorQuery::create()->count());
  1096. $this->assertEquals(3, BookQuery::create()->count());
  1097. }
  1098. public function testSetterOneToManyWithExistingObjects()
  1099. {
  1100. // Ensure no data
  1101. BookQuery::create()->deleteAll();
  1102. AuthorQuery::create()->deleteAll();
  1103. for ($i = 0; $i < 3; $i++) {
  1104. $b = new Book();
  1105. $b->setTitle('Book ' . $i);
  1106. $b->setIsbn('21234' . $i);
  1107. $b->save();
  1108. }
  1109. BookPeer::clearInstancePool();
  1110. $books = BookQuery::create()->find();
  1111. $a = new Author();
  1112. $a->setFirstName('Foo');
  1113. $a->setLastName('Bar');
  1114. $a->setBooks($books);
  1115. $a->save();
  1116. $this->assertEquals(3, count($a->getBooks()));
  1117. $this->assertEquals(1, AuthorQuery::create()->count());
  1118. $this->assertEquals(3, BookQuery::create()->count());
  1119. $i = 0;
  1120. foreach ($a->getBooks() as $book) {
  1121. $this->assertEquals('Book ' . $i++, $book->getTitle());
  1122. }
  1123. }
  1124. public function testSetterOneToManyWithEmptyCollection()
  1125. {
  1126. // Ensure no data
  1127. BookQuery::create()->deleteAll();
  1128. AuthorQuery::create()->deleteAll();
  1129. $a = new Author();
  1130. $a->setFirstName('Foo');
  1131. $a->setLastName('Bar');
  1132. $a->setBooks(new PropelObjectCollection());
  1133. $a->save();
  1134. $this->assertEquals(0, count($a->getBooks()));
  1135. $this->assertEquals(0, BookQuery::create()->count());
  1136. $this->assertEquals(1, AuthorQuery::create()->count());
  1137. }
  1138. public function testSetterOneToManyReplacesOldObjectsByNewObjects()
  1139. {
  1140. // Ensure no data
  1141. BookQuery::create()->deleteAll();
  1142. AuthorQuery::create()->deleteAll();
  1143. $books = new PropelObjectCollection();
  1144. foreach (array('foo', 'bar') as $title) {
  1145. $b = new Book();
  1146. $b->setTitle($title);
  1147. $b->setIsbn('12354');
  1148. $books[] = $b;
  1149. }
  1150. $a = new Author();
  1151. $a->setFirstName('Foo');
  1152. $a->setLastName('Bar');
  1153. $a->setBooks($books);
  1154. $a->save();
  1155. $books = $a->getBooks();
  1156. $this->assertEquals('foo', $books[0]->getTitle());
  1157. $this->assertEquals('bar', $books[1]->getTitle());
  1158. $books = new PropelObjectCollection();
  1159. foreach (array('bam', 'bom') as $title) {
  1160. $b = new Book();
  1161. $b->setTitle($title);
  1162. $b->setIsbn('1235');
  1163. $books[] = $b;
  1164. }
  1165. $a->setBooks($books);
  1166. $a->save();
  1167. $books = $a->getBooks();
  1168. $this->assertEquals('bam', $books[0]->getTitle());
  1169. $this->assertEquals('bom', $books[1]->getTitle());
  1170. $this->assertEquals(1, AuthorQuery::create()->count());
  1171. // the replaced book are still there because the PK is not required
  1172. $this->assertEquals(4, BookQuery::create()->count());
  1173. }
  1174. public function testSetterOneToManyReplacesOldObjectsByNewObjectsWithFkRequired()
  1175. {
  1176. // Ensure no data
  1177. BookSummaryQuery::create()->deleteAll();
  1178. BookQuery::create()->deleteAll();
  1179. $bookSummaries = new PropelObjectCollection();
  1180. foreach (array('foo', 'bar') as $summary) {
  1181. $s = new BookSummary();
  1182. $s->setSummary($summary);
  1183. $bookSummaries[] = $s;
  1184. }
  1185. $b = new Book();
  1186. $b->setTitle('Hello');
  1187. $b->setBookSummarys($bookSummaries);
  1188. $b->setIsbn('1234');
  1189. $b->save();
  1190. $bookSummaries = $b->getBookSummarys();
  1191. $this->assertEquals('foo', $bookSummaries[0]->getSummary());
  1192. $this->assertEquals('bar', $bookSummaries[1]->getSummary());
  1193. $bookSummaries = new PropelObjectCollection();
  1194. foreach (array('bam', 'bom') as $summary) {
  1195. $s = new BookSummary();
  1196. $s->setSummary($summary);
  1197. $bookSummaries[] = $s;
  1198. }
  1199. $b->setBookSummarys($bookSummaries);
  1200. $b->save();
  1201. $bookSummaries = $b->getBookSummarys();
  1202. $this->assertEquals('bam', $bookSummaries[0]->getSummary());
  1203. $this->assertEquals('bom', $bookSummaries[1]->getSummary());
  1204. $this->assertEquals(1, BookQuery::create()->count());
  1205. $this->assertEquals(2, BookSummaryQuery::create()->count());
  1206. }
  1207. public function testHooksCall()
  1208. {
  1209. AuthorQuery::create()->deleteAll();
  1210. BookQuery::create()->deleteAll();
  1211. $author = new CountableAuthor();
  1212. $author->setFirstName('Foo');
  1213. $author->setLastName('Bar');
  1214. $book = new Book();
  1215. $book->setTitle('A title');
  1216. $book->setIsbn('13456');
  1217. $author->addBook($book);
  1218. $author->save();
  1219. $this->assertEquals(1, AuthorQuery::create()->count());
  1220. $this->assertEquals(1, BookQuery::create()->count());
  1221. $this->assertEquals(1, $author->nbCallPreSave);
  1222. }
  1223. /**
  1224. * @expectedException PropelException
  1225. */
  1226. public function testDoInsert()
  1227. {
  1228. if (!class_exists('Unexistent')) {
  1229. $schema = <<<EOF
  1230. <database name="a-database">
  1231. <table name="unexistent">
  1232. <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
  1233. <column name="name" type="VARCHAR" />
  1234. </table>
  1235. </database>
  1236. EOF;
  1237. $build

Large files files are truncated, but you can click here to view the full file