FixtureManagerTest.php 17 KB

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