FixtureManagerTest.php 16 KB

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