FixtureManagerTest.php 17 KB

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