OrmFunctionalTestCase.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. <?php
  2. namespace Doctrine\Tests;
  3. /**
  4. * Base testcase class for all functional ORM testcases.
  5. *
  6. * @since 2.0
  7. */
  8. abstract class OrmFunctionalTestCase extends OrmTestCase
  9. {
  10. /* The metadata cache shared between all functional tests. */
  11. private static $_metadataCacheImpl = null;
  12. /* The query cache shared between all functional tests. */
  13. private static $_queryCacheImpl = null;
  14. /* Shared connection when a TestCase is run alone (outside of it's functional suite) */
  15. protected static $_sharedConn;
  16. /**
  17. * @var \Doctrine\ORM\EntityManager
  18. */
  19. protected $_em;
  20. /**
  21. * @var \Doctrine\ORM\Tools\SchemaTool
  22. */
  23. protected $_schemaTool;
  24. /**
  25. * @var \Doctrine\DBAL\Logging\DebugStack
  26. */
  27. protected $_sqlLoggerStack;
  28. /** The names of the model sets used in this testcase. */
  29. protected $_usedModelSets = array();
  30. /** Whether the database schema has already been created. */
  31. protected static $_tablesCreated = array();
  32. /** List of model sets and their classes. */
  33. protected static $_modelSets = array(
  34. 'cms' => array(
  35. 'Doctrine\Tests\Models\CMS\CmsUser',
  36. 'Doctrine\Tests\Models\CMS\CmsPhonenumber',
  37. 'Doctrine\Tests\Models\CMS\CmsAddress',
  38. 'Doctrine\Tests\Models\CMS\CmsGroup',
  39. 'Doctrine\Tests\Models\CMS\CmsArticle',
  40. 'Doctrine\Tests\Models\CMS\CmsComment',
  41. ),
  42. 'forum' => array(),
  43. 'company' => array(
  44. 'Doctrine\Tests\Models\Company\CompanyPerson',
  45. 'Doctrine\Tests\Models\Company\CompanyEmployee',
  46. 'Doctrine\Tests\Models\Company\CompanyManager',
  47. 'Doctrine\Tests\Models\Company\CompanyOrganization',
  48. 'Doctrine\Tests\Models\Company\CompanyEvent',
  49. 'Doctrine\Tests\Models\Company\CompanyAuction',
  50. 'Doctrine\Tests\Models\Company\CompanyRaffle',
  51. 'Doctrine\Tests\Models\Company\CompanyCar',
  52. 'Doctrine\Tests\Models\Company\CompanyContract',
  53. ),
  54. 'ecommerce' => array(
  55. 'Doctrine\Tests\Models\ECommerce\ECommerceCart',
  56. 'Doctrine\Tests\Models\ECommerce\ECommerceCustomer',
  57. 'Doctrine\Tests\Models\ECommerce\ECommerceProduct',
  58. 'Doctrine\Tests\Models\ECommerce\ECommerceShipping',
  59. 'Doctrine\Tests\Models\ECommerce\ECommerceFeature',
  60. 'Doctrine\Tests\Models\ECommerce\ECommerceCategory'
  61. ),
  62. 'generic' => array(
  63. 'Doctrine\Tests\Models\Generic\BooleanModel',
  64. 'Doctrine\Tests\Models\Generic\DateTimeModel',
  65. 'Doctrine\Tests\Models\Generic\DecimalModel',
  66. 'Doctrine\Tests\Models\Generic\SerializationModel',
  67. ),
  68. 'routing' => array(
  69. 'Doctrine\Tests\Models\Routing\RoutingLeg',
  70. 'Doctrine\Tests\Models\Routing\RoutingLocation',
  71. 'Doctrine\Tests\Models\Routing\RoutingRoute',
  72. 'Doctrine\Tests\Models\Routing\RoutingRouteBooking',
  73. ),
  74. 'navigation' => array(
  75. 'Doctrine\Tests\Models\Navigation\NavCountry',
  76. 'Doctrine\Tests\Models\Navigation\NavPhotos',
  77. 'Doctrine\Tests\Models\Navigation\NavTour',
  78. 'Doctrine\Tests\Models\Navigation\NavPointOfInterest',
  79. ),
  80. 'directorytree' => array(
  81. 'Doctrine\Tests\Models\DirectoryTree\AbstractContentItem',
  82. 'Doctrine\Tests\Models\DirectoryTree\File',
  83. 'Doctrine\Tests\Models\DirectoryTree\Directory',
  84. ),
  85. 'ddc117' => array(
  86. 'Doctrine\Tests\Models\DDC117\DDC117Article',
  87. 'Doctrine\Tests\Models\DDC117\DDC117Reference',
  88. 'Doctrine\Tests\Models\DDC117\DDC117Translation',
  89. 'Doctrine\Tests\Models\DDC117\DDC117ArticleDetails',
  90. 'Doctrine\Tests\Models\DDC117\DDC117ApproveChanges',
  91. 'Doctrine\Tests\Models\DDC117\DDC117Editor',
  92. 'Doctrine\Tests\Models\DDC117\DDC117Link',
  93. ),
  94. 'stockexchange' => array(
  95. 'Doctrine\Tests\Models\StockExchange\Bond',
  96. 'Doctrine\Tests\Models\StockExchange\Stock',
  97. 'Doctrine\Tests\Models\StockExchange\Market',
  98. ),
  99. 'legacy' => array(
  100. 'Doctrine\Tests\Models\Legacy\LegacyUser',
  101. 'Doctrine\Tests\Models\Legacy\LegacyUserReference',
  102. 'Doctrine\Tests\Models\Legacy\LegacyArticle',
  103. 'Doctrine\Tests\Models\Legacy\LegacyCar',
  104. ),
  105. );
  106. protected function useModelSet($setName)
  107. {
  108. $this->_usedModelSets[$setName] = true;
  109. }
  110. /**
  111. * Sweeps the database tables and clears the EntityManager.
  112. */
  113. protected function tearDown()
  114. {
  115. $conn = static::$_sharedConn;
  116. $this->_sqlLoggerStack->enabled = false;
  117. if (isset($this->_usedModelSets['cms'])) {
  118. $conn->executeUpdate('DELETE FROM cms_users_groups');
  119. $conn->executeUpdate('DELETE FROM cms_groups');
  120. $conn->executeUpdate('DELETE FROM cms_addresses');
  121. $conn->executeUpdate('DELETE FROM cms_phonenumbers');
  122. $conn->executeUpdate('DELETE FROM cms_comments');
  123. $conn->executeUpdate('DELETE FROM cms_articles');
  124. $conn->executeUpdate('DELETE FROM cms_users');
  125. }
  126. if (isset($this->_usedModelSets['ecommerce'])) {
  127. $conn->executeUpdate('DELETE FROM ecommerce_carts_products');
  128. $conn->executeUpdate('DELETE FROM ecommerce_products_categories');
  129. $conn->executeUpdate('DELETE FROM ecommerce_products_related');
  130. $conn->executeUpdate('DELETE FROM ecommerce_carts');
  131. $conn->executeUpdate('DELETE FROM ecommerce_customers');
  132. $conn->executeUpdate('DELETE FROM ecommerce_features');
  133. $conn->executeUpdate('DELETE FROM ecommerce_products');
  134. $conn->executeUpdate('DELETE FROM ecommerce_shippings');
  135. $conn->executeUpdate('UPDATE ecommerce_categories SET parent_id = NULL');
  136. $conn->executeUpdate('DELETE FROM ecommerce_categories');
  137. }
  138. if (isset($this->_usedModelSets['company'])) {
  139. $conn->executeUpdate('DELETE FROM company_contract_employees');
  140. $conn->executeUpdate('DELETE FROM company_contracts');
  141. $conn->executeUpdate('DELETE FROM company_persons_friends');
  142. $conn->executeUpdate('DELETE FROM company_managers');
  143. $conn->executeUpdate('DELETE FROM company_employees');
  144. $conn->executeUpdate('UPDATE company_persons SET spouse_id = NULL');
  145. $conn->executeUpdate('DELETE FROM company_persons');
  146. $conn->executeUpdate('DELETE FROM company_raffles');
  147. $conn->executeUpdate('DELETE FROM company_auctions');
  148. $conn->executeUpdate('UPDATE company_organizations SET main_event_id = NULL');
  149. $conn->executeUpdate('DELETE FROM company_events');
  150. $conn->executeUpdate('DELETE FROM company_organizations');
  151. }
  152. if (isset($this->_usedModelSets['generic'])) {
  153. $conn->executeUpdate('DELETE FROM boolean_model');
  154. $conn->executeUpdate('DELETE FROM date_time_model');
  155. $conn->executeUpdate('DELETE FROM decimal_model');
  156. $conn->executeUpdate('DELETE FROM serialize_model');
  157. }
  158. if (isset($this->_usedModelSets['routing'])) {
  159. $conn->executeUpdate('DELETE FROM RoutingRouteLegs');
  160. $conn->executeUpdate('DELETE FROM RoutingRouteBooking');
  161. $conn->executeUpdate('DELETE FROM RoutingRoute');
  162. $conn->executeUpdate('DELETE FROM RoutingLeg');
  163. $conn->executeUpdate('DELETE FROM RoutingLocation');
  164. }
  165. if(isset($this->_usedModelSets['navigation'])) {
  166. $conn->executeUpdate('DELETE FROM navigation_tour_pois');
  167. $conn->executeUpdate('DELETE FROM navigation_photos');
  168. $conn->executeUpdate('DELETE FROM navigation_pois');
  169. $conn->executeUpdate('DELETE FROM navigation_tours');
  170. $conn->executeUpdate('DELETE FROM navigation_countries');
  171. }
  172. if (isset($this->_usedModelSets['directorytree'])) {
  173. $conn->executeUpdate('DELETE FROM ' . $this->_em->getConnection()->getDatabasePlatform()->quoteIdentifier("file"));
  174. // MySQL doesnt know deferred deletions therefore only executing the second query gives errors.
  175. $conn->executeUpdate('DELETE FROM Directory WHERE parentDirectory_id IS NOT NULL');
  176. $conn->executeUpdate('DELETE FROM Directory');
  177. }
  178. if (isset($this->_usedModelSets['ddc117'])) {
  179. return;
  180. $conn->executeUpdate('DELETE FROM ddc117editor_ddc117translation');
  181. $conn->executeUpdate('DELETE FROM DDC117Editor');
  182. $conn->executeUpdate('DELETE FROM DDC117ApproveChanges');
  183. $conn->executeUpdate('DELETE FROM DDC117Link');
  184. $conn->executeUpdate('DELETE FROM DDC117Reference');
  185. $conn->executeUpdate('DELETE FROM DDC117ArticleDetails');
  186. $conn->executeUpdate('DELETE FROM DDC117Translation');
  187. $conn->executeUpdate('DELETE FROM DDC117Article');
  188. }
  189. if (isset($this->_usedModelSets['stockexchange'])) {
  190. $conn->executeUpdate('DELETE FROM exchange_bonds_stocks');
  191. $conn->executeUpdate('DELETE FROM exchange_bonds');
  192. $conn->executeUpdate('DELETE FROM exchange_stocks');
  193. $conn->executeUpdate('DELETE FROM exchange_markets');
  194. }
  195. if (isset($this->_usedModelSets['legacy'])) {
  196. $conn->executeUpdate('DELETE FROM legacy_users_cars');
  197. $conn->executeUpdate('DELETE FROM legacy_users_reference');
  198. $conn->executeUpdate('DELETE FROM legacy_articles');
  199. $conn->executeUpdate('DELETE FROM legacy_cars');
  200. $conn->executeUpdate('DELETE FROM legacy_users');
  201. }
  202. $this->_em->clear();
  203. }
  204. /**
  205. * Creates a connection to the test database, if there is none yet, and
  206. * creates the necessary tables.
  207. */
  208. protected function setUp()
  209. {
  210. $forceCreateTables = false;
  211. if ( ! isset(static::$_sharedConn)) {
  212. static::$_sharedConn = TestUtil::getConnection();
  213. if (static::$_sharedConn->getDriver() instanceof \Doctrine\DBAL\Driver\PDOSqlite\Driver) {
  214. $forceCreateTables = true;
  215. }
  216. }
  217. if (isset($GLOBALS['DOCTRINE_MARK_SQL_LOGS'])) {
  218. if (in_array(static::$_sharedConn->getDatabasePlatform()->getName(), array("mysql", "postgresql"))) {
  219. static::$_sharedConn->executeQuery('SELECT 1 /*' . get_class($this) . '*/');
  220. } else if (static::$_sharedConn->getDatabasePlatform()->getName() == "oracle") {
  221. static::$_sharedConn->executeQuery('SELECT 1 /*' . get_class($this) . '*/ FROM dual');
  222. }
  223. }
  224. if ( ! $this->_em) {
  225. $this->_em = $this->_getEntityManager();
  226. $this->_schemaTool = new \Doctrine\ORM\Tools\SchemaTool($this->_em);
  227. }
  228. $classes = array();
  229. foreach ($this->_usedModelSets as $setName => $bool) {
  230. if ( ! isset(static::$_tablesCreated[$setName])/* || $forceCreateTables*/) {
  231. foreach (static::$_modelSets[$setName] as $className) {
  232. $classes[] = $this->_em->getClassMetadata($className);
  233. }
  234. static::$_tablesCreated[$setName] = true;
  235. }
  236. }
  237. if ($classes) {
  238. $this->_schemaTool->createSchema($classes);
  239. }
  240. $this->_sqlLoggerStack->enabled = true;
  241. }
  242. /**
  243. * Gets an EntityManager for testing purposes.
  244. *
  245. * @param Configuration $config The Configuration to pass to the EntityManager.
  246. * @param EventManager $eventManager The EventManager to pass to the EntityManager.
  247. * @return EntityManager
  248. */
  249. protected function _getEntityManager($config = null, $eventManager = null) {
  250. // NOTE: Functional tests use their own shared metadata cache, because
  251. // the actual database platform used during execution has effect on some
  252. // metadata mapping behaviors (like the choice of the ID generation).
  253. if (is_null(self::$_metadataCacheImpl)) {
  254. self::$_metadataCacheImpl = new \Doctrine\Common\Cache\ArrayCache;
  255. }
  256. if (is_null(self::$_queryCacheImpl)) {
  257. self::$_queryCacheImpl = new \Doctrine\Common\Cache\ArrayCache;
  258. }
  259. $this->_sqlLoggerStack = new \Doctrine\DBAL\Logging\DebugStack();
  260. $this->_sqlLoggerStack->enabled = false;
  261. //FIXME: two different configs! $conn and the created entity manager have
  262. // different configs.
  263. $config = new \Doctrine\ORM\Configuration();
  264. $config->setMetadataCacheImpl(self::$_metadataCacheImpl);
  265. $config->setQueryCacheImpl(self::$_queryCacheImpl);
  266. $config->setProxyDir(__DIR__ . '/Proxies');
  267. $config->setProxyNamespace('Doctrine\Tests\Proxies');
  268. $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver());
  269. $conn = static::$_sharedConn;
  270. $conn->getConfiguration()->setSQLLogger($this->_sqlLoggerStack);
  271. // get rid of more global state
  272. $evm = $conn->getEventManager();
  273. foreach ($evm->getListeners() AS $event => $listeners) {
  274. foreach ($listeners AS $listener) {
  275. $evm->removeEventListener(array($event), $listener);
  276. }
  277. }
  278. if (isset($GLOBALS['db_event_subscribers'])) {
  279. foreach (explode(",", $GLOBALS['db_event_subscribers']) AS $subscriberClass) {
  280. $subscriberInstance = new $subscriberClass();
  281. $evm->addEventSubscriber($subscriberInstance);
  282. }
  283. }
  284. return \Doctrine\ORM\EntityManager::create($conn, $config);
  285. }
  286. protected function onNotSuccessfulTest(\Exception $e)
  287. {
  288. if ($e instanceof \PHPUnit_Framework_AssertionFailedError) {
  289. throw $e;
  290. }
  291. if(isset($this->_sqlLoggerStack->queries) && count($this->_sqlLoggerStack->queries)) {
  292. $queries = "";
  293. for($i = count($this->_sqlLoggerStack->queries)-1; $i > max(count($this->_sqlLoggerStack->queries)-25, 0) && isset($this->_sqlLoggerStack->queries[$i]); $i--) {
  294. $query = $this->_sqlLoggerStack->queries[$i];
  295. $params = array_map(function($p) { if (is_object($p)) return get_class($p); else return "'".$p."'"; }, $query['params'] ?: array());
  296. $queries .= ($i+1).". SQL: '".$query['sql']."' Params: ".implode(", ", $params).PHP_EOL;
  297. }
  298. $trace = $e->getTrace();
  299. $traceMsg = "";
  300. foreach($trace AS $part) {
  301. if(isset($part['file'])) {
  302. if(strpos($part['file'], "PHPUnit/") !== false) {
  303. // Beginning with PHPUnit files we don't print the trace anymore.
  304. break;
  305. }
  306. $traceMsg .= $part['file'].":".$part['line'].PHP_EOL;
  307. }
  308. }
  309. $message = "[".get_class($e)."] ".$e->getMessage().PHP_EOL.PHP_EOL."With queries:".PHP_EOL.$queries.PHP_EOL."Trace:".PHP_EOL.$traceMsg;
  310. throw new \Exception($message, (int)$e->getCode(), $e);
  311. }
  312. throw $e;
  313. }
  314. /**
  315. * Using the SQL Logger Stack this method retrieves the current query count executed in this test.
  316. *
  317. * @return int
  318. */
  319. protected function getCurrentQueryCount()
  320. {
  321. return count($this->_sqlLoggerStack->queries);
  322. }
  323. }