FixtureManagerTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestSuite;
  16. use Cake\Core\Exception\Exception as CakeException;
  17. use Cake\Core\Plugin;
  18. use Cake\Database\Schema\TableSchema;
  19. use Cake\Datasource\ConnectionManager;
  20. use Cake\Log\Log;
  21. use Cake\TestSuite\Fixture\FixtureManager;
  22. use Cake\TestSuite\Stub\ConsoleOutput;
  23. use Cake\TestSuite\TestCase;
  24. use PDOException;
  25. /**
  26. * Fixture manager test case.
  27. */
  28. class FixtureManagerTest extends TestCase
  29. {
  30. /**
  31. * Setup method
  32. *
  33. * @return void
  34. */
  35. public function setUp()
  36. {
  37. parent::setUp();
  38. $this->manager = new FixtureManager();
  39. }
  40. public function tearDown()
  41. {
  42. parent::tearDown();
  43. Log::reset();
  44. $this->clearPlugins();
  45. }
  46. /**
  47. * Test loading core fixtures.
  48. *
  49. * @return void
  50. */
  51. public function testFixturizeCore()
  52. {
  53. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  54. $test->fixtures = ['core.Articles'];
  55. $this->manager->fixturize($test);
  56. $fixtures = $this->manager->loaded();
  57. $this->assertCount(1, $fixtures);
  58. $this->assertArrayHasKey('core.Articles', $fixtures);
  59. $this->assertInstanceOf('Cake\Test\Fixture\ArticlesFixture', $fixtures['core.Articles']);
  60. }
  61. /**
  62. * Test logging depends on fixture manager debug.
  63. *
  64. * @return void
  65. */
  66. public function testLogSchemaWithDebug()
  67. {
  68. $db = ConnectionManager::get('test');
  69. $restore = $db->isQueryLoggingEnabled();
  70. $db->enableQueryLogging(true);
  71. $this->manager->setDebug(true);
  72. $buffer = new ConsoleOutput();
  73. Log::setConfig('testQueryLogger', [
  74. 'className' => 'Console',
  75. 'stream' => $buffer,
  76. ]);
  77. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  78. $test->fixtures = ['core.Articles'];
  79. $this->manager->fixturize($test);
  80. // Need to load/shutdown twice to ensure fixture is created.
  81. $this->manager->load($test);
  82. $this->manager->shutdown();
  83. $this->manager->load($test);
  84. $this->manager->shutdown();
  85. $db->enableQueryLogging($restore);
  86. $this->assertContains('CREATE TABLE', implode('', $buffer->messages()));
  87. }
  88. /**
  89. * Test that if a table already exists in the test database, it will dropped
  90. * before being recreated
  91. *
  92. * @return void
  93. */
  94. public function testResetDbIfTableExists()
  95. {
  96. $db = ConnectionManager::get('test');
  97. $restore = $db->isQueryLoggingEnabled();
  98. $db->enableQueryLogging(true);
  99. $this->manager->setDebug(true);
  100. $buffer = new ConsoleOutput();
  101. Log::setConfig('testQueryLogger', [
  102. 'className' => 'Console',
  103. 'stream' => $buffer,
  104. ]);
  105. $table = new TableSchema('articles', [
  106. 'id' => ['type' => 'integer', 'unsigned' => true],
  107. 'title' => ['type' => 'string', 'length' => 255],
  108. ]);
  109. $table->addConstraint('primary', ['type' => 'primary', 'columns' => ['id']]);
  110. $sql = $table->createSql($db);
  111. foreach ($sql as $stmt) {
  112. $db->execute($stmt);
  113. }
  114. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  115. $test->fixtures = ['core.Articles'];
  116. $this->manager->fixturize($test);
  117. $this->manager->load($test);
  118. $db->enableQueryLogging($restore);
  119. $this->assertContains('DROP TABLE', implode('', $buffer->messages()));
  120. }
  121. /**
  122. * Test loading fixtures with constraints.
  123. *
  124. * @return void
  125. */
  126. public function testFixturizeCoreConstraint()
  127. {
  128. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  129. $test->fixtures = ['core.Articles', 'core.ArticlesTags', 'core.Tags'];
  130. $this->manager->fixturize($test);
  131. $this->manager->load($test);
  132. $table = $this->getTableLocator()->get('ArticlesTags');
  133. $schema = $table->getSchema();
  134. $expectedConstraint = [
  135. 'type' => 'foreign',
  136. 'columns' => [
  137. 'tag_id',
  138. ],
  139. 'references' => [
  140. 'tags',
  141. 'id',
  142. ],
  143. 'update' => 'cascade',
  144. 'delete' => 'cascade',
  145. 'length' => [],
  146. ];
  147. $this->assertEquals($expectedConstraint, $schema->getConstraint('tag_id_fk'));
  148. $this->manager->unload($test);
  149. $this->manager->load($test);
  150. $table = $this->getTableLocator()->get('ArticlesTags');
  151. $schema = $table->getSchema();
  152. $expectedConstraint = [
  153. 'type' => 'foreign',
  154. 'columns' => [
  155. 'tag_id',
  156. ],
  157. 'references' => [
  158. 'tags',
  159. 'id',
  160. ],
  161. 'update' => 'cascade',
  162. 'delete' => 'cascade',
  163. 'length' => [],
  164. ];
  165. $this->assertEquals($expectedConstraint, $schema->getConstraint('tag_id_fk'));
  166. $this->manager->unload($test);
  167. }
  168. /**
  169. * Test loading plugin fixtures.
  170. *
  171. * @return void
  172. */
  173. public function testFixturizePlugin()
  174. {
  175. $this->loadPlugins(['TestPlugin']);
  176. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  177. $test->fixtures = ['plugin.TestPlugin.Articles'];
  178. $this->manager->fixturize($test);
  179. $fixtures = $this->manager->loaded();
  180. $this->assertCount(1, $fixtures);
  181. $this->assertArrayHasKey('plugin.TestPlugin.Articles', $fixtures);
  182. $this->assertInstanceOf(
  183. 'TestPlugin\Test\Fixture\ArticlesFixture',
  184. $fixtures['plugin.TestPlugin.Articles']
  185. );
  186. }
  187. /**
  188. * Test loading plugin fixtures.
  189. *
  190. * @return void
  191. */
  192. public function testFixturizePluginSubdirectory()
  193. {
  194. $this->loadPlugins(['TestPlugin']);
  195. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  196. $test->fixtures = ['plugin.TestPlugin.Blog/Comments'];
  197. $this->manager->fixturize($test);
  198. $fixtures = $this->manager->loaded();
  199. $this->assertCount(1, $fixtures);
  200. $this->assertArrayHasKey('plugin.TestPlugin.Blog/Comments', $fixtures);
  201. $this->assertInstanceOf(
  202. 'TestPlugin\Test\Fixture\Blog\CommentsFixture',
  203. $fixtures['plugin.TestPlugin.Blog/Comments']
  204. );
  205. }
  206. /**
  207. * Test loading plugin fixtures from a vendor namespaced plugin
  208. *
  209. * @return void
  210. */
  211. public function testFixturizeVendorPlugin()
  212. {
  213. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  214. $test->fixtures = ['plugin.Company/TestPluginThree.Articles'];
  215. $this->manager->fixturize($test);
  216. $fixtures = $this->manager->loaded();
  217. $this->assertCount(1, $fixtures);
  218. $this->assertArrayHasKey('plugin.Company/TestPluginThree.Articles', $fixtures);
  219. $this->assertInstanceOf(
  220. 'Company\TestPluginThree\Test\Fixture\ArticlesFixture',
  221. $fixtures['plugin.Company/TestPluginThree.Articles']
  222. );
  223. }
  224. /**
  225. * Test loading fixtures with fully-qualified namespaces.
  226. *
  227. * @return void
  228. */
  229. public function testFixturizeClassName()
  230. {
  231. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  232. $test->fixtures = ['Company\TestPluginThree\Test\Fixture\ArticlesFixture'];
  233. $this->manager->fixturize($test);
  234. $fixtures = $this->manager->loaded();
  235. $this->assertCount(1, $fixtures);
  236. $this->assertArrayHasKey('Company\TestPluginThree\Test\Fixture\ArticlesFixture', $fixtures);
  237. $this->assertInstanceOf(
  238. 'Company\TestPluginThree\Test\Fixture\ArticlesFixture',
  239. $fixtures['Company\TestPluginThree\Test\Fixture\ArticlesFixture']
  240. );
  241. }
  242. /**
  243. * Test that unknown types are handled gracefully.
  244. *
  245. */
  246. public function testFixturizeInvalidType()
  247. {
  248. $this->expectException(\UnexpectedValueException::class);
  249. $this->expectExceptionMessage('Referenced fixture class "Test\Fixture\Derp.DerpFixture" not found. Fixture "Derp.Derp" was referenced');
  250. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  251. $test->fixtures = ['Derp.Derp'];
  252. $this->manager->fixturize($test);
  253. }
  254. /**
  255. * Test load uses aliased connections via a mock.
  256. *
  257. * Ensure that FixtureManager uses connection aliases
  258. * protecting 'live' tables from being wiped by mistakes in
  259. * fixture connection names.
  260. *
  261. * @return void
  262. */
  263. public function testLoadConnectionAliasUsage()
  264. {
  265. $connection = ConnectionManager::get('test');
  266. $statement = $this->getMockBuilder('Cake\Database\StatementInterface')
  267. ->getMock();
  268. // This connection should _not_ be used.
  269. $other = $this->getMockBuilder('Cake\Database\Connection')
  270. ->setMethods(['execute'])
  271. ->setConstructorArgs([['driver' => $connection->getDriver()]])
  272. ->getMock();
  273. $other->expects($this->never())
  274. ->method('execute')
  275. ->will($this->returnValue($statement));
  276. // This connection should be used instead of
  277. // the 'other' connection as the alias should not be ignored.
  278. $testOther = $this->getMockBuilder('Cake\Database\Connection')
  279. ->setMethods(['execute'])
  280. ->setConstructorArgs([[
  281. 'database' => $connection->config()['database'],
  282. 'driver' => $connection->getDriver(),
  283. ]])
  284. ->getMock();
  285. $testOther->expects($this->atLeastOnce())
  286. ->method('execute')
  287. ->will($this->returnValue($statement));
  288. ConnectionManager::setConfig('other', $other);
  289. ConnectionManager::setConfig('test_other', $testOther);
  290. // Connect the alias making test_other an alias of other.
  291. ConnectionManager::alias('test_other', 'other');
  292. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  293. $test->fixtures = ['core.OtherArticles'];
  294. $this->manager->fixturize($test);
  295. $this->manager->load($test);
  296. ConnectionManager::drop('other');
  297. ConnectionManager::drop('test_other');
  298. }
  299. /**
  300. * Test loading fixtures using loadSingle()
  301. *
  302. * @return void
  303. */
  304. public function testLoadSingle()
  305. {
  306. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  307. $test->autoFixtures = false;
  308. $test->fixtures = ['core.Articles', 'core.ArticlesTags', 'core.Tags'];
  309. $this->manager->fixturize($test);
  310. $this->manager->loadSingle('Articles');
  311. $this->manager->loadSingle('Tags');
  312. $this->manager->loadSingle('ArticlesTags');
  313. $table = $this->getTableLocator()->get('ArticlesTags');
  314. $results = $table->find('all')->toArray();
  315. $schema = $table->getSchema();
  316. $expectedConstraint = [
  317. 'type' => 'foreign',
  318. 'columns' => [
  319. 'tag_id',
  320. ],
  321. 'references' => [
  322. 'tags',
  323. 'id',
  324. ],
  325. 'update' => 'cascade',
  326. 'delete' => 'cascade',
  327. 'length' => [],
  328. ];
  329. $this->assertEquals($expectedConstraint, $schema->getConstraint('tag_id_fk'));
  330. $this->assertCount(4, $results);
  331. $this->manager->unload($test);
  332. $this->manager->loadSingle('Articles');
  333. $this->manager->loadSingle('Tags');
  334. $this->manager->loadSingle('ArticlesTags');
  335. $table = $this->getTableLocator()->get('ArticlesTags');
  336. $results = $table->find('all')->toArray();
  337. $schema = $table->getSchema();
  338. $expectedConstraint = [
  339. 'type' => 'foreign',
  340. 'columns' => [
  341. 'tag_id',
  342. ],
  343. 'references' => [
  344. 'tags',
  345. 'id',
  346. ],
  347. 'update' => 'cascade',
  348. 'delete' => 'cascade',
  349. 'length' => [],
  350. ];
  351. $this->assertEquals($expectedConstraint, $schema->getConstraint('tag_id_fk'));
  352. $this->assertCount(4, $results);
  353. $this->manager->unload($test);
  354. }
  355. /**
  356. * Test exception on load
  357. *
  358. * @return void
  359. */
  360. public function testExceptionOnLoad()
  361. {
  362. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  363. $test->fixtures = ['core.Products'];
  364. $manager = $this->getMockBuilder(FixtureManager::class)
  365. ->setMethods(['_runOperation'])
  366. ->getMock();
  367. $manager->expects($this->any())
  368. ->method('_runOperation')
  369. ->will($this->returnCallback(function () {
  370. throw new PDOException('message');
  371. }));
  372. $manager->fixturize($test);
  373. $e = null;
  374. try {
  375. $manager->load($test);
  376. } catch (CakeException $e) {
  377. }
  378. $this->assertNotNull($e);
  379. $this->assertRegExp('/^Unable to insert fixtures for "Mock_TestCase_\w+" test case. message$/D', $e->getMessage());
  380. $this->assertInstanceOf('PDOException', $e->getPrevious());
  381. }
  382. /**
  383. * Test exception on load fixture
  384. *
  385. * @dataProvider loadErrorMessageProvider
  386. * @return void
  387. */
  388. public function testExceptionOnLoadFixture($method, $expectedMessage)
  389. {
  390. $fixture = $this->getMockBuilder('Cake\Test\Fixture\ProductsFixture')
  391. ->setMethods([$method])
  392. ->getMock();
  393. $fixture->expects($this->once())
  394. ->method($method)
  395. ->will($this->returnCallback(function () {
  396. throw new PDOException('message');
  397. }));
  398. $fixtures = [
  399. 'core.Products' => $fixture,
  400. ];
  401. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  402. $test->fixtures = array_keys($fixtures);
  403. $manager = $this->getMockBuilder(FixtureManager::class)
  404. ->setMethods(['_fixtureConnections'])
  405. ->getMock();
  406. $manager->expects($this->any())
  407. ->method('_fixtureConnections')
  408. ->will($this->returnValue([
  409. 'test' => $fixtures,
  410. ]));
  411. $manager->fixturize($test);
  412. $manager->loadSingle('Products');
  413. $e = null;
  414. try {
  415. $manager->load($test);
  416. } catch (CakeException $e) {
  417. }
  418. $this->assertNotNull($e);
  419. $this->assertRegExp($expectedMessage, $e->getMessage());
  420. $this->assertInstanceOf('PDOException', $e->getPrevious());
  421. }
  422. /**
  423. * Data provider for testExceptionOnLoadFixture
  424. *
  425. * @return array
  426. */
  427. public function loadErrorMessageProvider()
  428. {
  429. return [
  430. [
  431. 'createConstraints',
  432. '/^Unable to create constraints for fixture "Mock_ProductsFixture_\w+" in "Mock_TestCase_\w+" test case: \nmessage$/D',
  433. ],
  434. [
  435. 'dropConstraints',
  436. '/^Unable to drop constraints for fixture "Mock_ProductsFixture_\w+" in "Mock_TestCase_\w+" test case: \nmessage$/D',
  437. ],
  438. [
  439. 'insert',
  440. '/^Unable to insert fixture "Mock_ProductsFixture_\w+" in "Mock_TestCase_\w+" test case: \nmessage$/D',
  441. ],
  442. ];
  443. }
  444. }