FixtureManagerTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\TestSuite;
  17. use Cake\Core\Exception\Exception as CakeException;
  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(): void
  36. {
  37. parent::setUp();
  38. $this->manager = new FixtureManager();
  39. }
  40. public function tearDown(): void
  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->assertStringContainsString('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->assertStringContainsString('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->assertSame($expectedConstraint, $schema->getConstraint('tag_id_fk'));
  157. $this->manager->unload($test);
  158. }
  159. /**
  160. * Test loading plugin fixtures.
  161. *
  162. * @return void
  163. */
  164. public function testFixturizePlugin()
  165. {
  166. $this->loadPlugins(['TestPlugin']);
  167. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  168. $test->expects($this->any())
  169. ->method('getFixtures')
  170. ->willReturn(['plugin.TestPlugin.Articles']);
  171. $this->manager->fixturize($test);
  172. $fixtures = $this->manager->loaded();
  173. $this->assertCount(1, $fixtures);
  174. $this->assertArrayHasKey('plugin.TestPlugin.Articles', $fixtures);
  175. $this->assertInstanceOf(
  176. 'TestPlugin\Test\Fixture\ArticlesFixture',
  177. $fixtures['plugin.TestPlugin.Articles']
  178. );
  179. }
  180. /**
  181. * Test loading plugin fixtures.
  182. *
  183. * @return void
  184. */
  185. public function testFixturizePluginSubdirectory()
  186. {
  187. $this->loadPlugins(['TestPlugin']);
  188. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  189. $test->expects($this->any())
  190. ->method('getFixtures')
  191. ->willReturn(['plugin.TestPlugin.Blog/Comments']);
  192. $this->manager->fixturize($test);
  193. $fixtures = $this->manager->loaded();
  194. $this->assertCount(1, $fixtures);
  195. $this->assertArrayHasKey('plugin.TestPlugin.Blog/Comments', $fixtures);
  196. $this->assertInstanceOf(
  197. 'TestPlugin\Test\Fixture\Blog\CommentsFixture',
  198. $fixtures['plugin.TestPlugin.Blog/Comments']
  199. );
  200. }
  201. /**
  202. * Test loading plugin fixtures from a vendor namespaced plugin
  203. *
  204. * @return void
  205. */
  206. public function testFixturizeVendorPlugin()
  207. {
  208. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  209. $test->expects($this->any())
  210. ->method('getFixtures')
  211. ->willReturn(['plugin.Company/TestPluginThree.Articles']);
  212. $this->manager->fixturize($test);
  213. $fixtures = $this->manager->loaded();
  214. $this->assertCount(1, $fixtures);
  215. $this->assertArrayHasKey('plugin.Company/TestPluginThree.Articles', $fixtures);
  216. $this->assertInstanceOf(
  217. 'Company\TestPluginThree\Test\Fixture\ArticlesFixture',
  218. $fixtures['plugin.Company/TestPluginThree.Articles']
  219. );
  220. }
  221. /**
  222. * Test loading fixtures with fully-qualified namespaces.
  223. *
  224. * @return void
  225. */
  226. public function testFixturizeClassName()
  227. {
  228. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  229. $test->expects($this->any())
  230. ->method('getFixtures')
  231. ->willReturn(['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->expects($this->any())
  251. ->method('getFixtures')
  252. ->willReturn(['Derp.Derp']);
  253. $this->manager->fixturize($test);
  254. }
  255. /**
  256. * Test load uses aliased connections via a mock.
  257. *
  258. * Ensure that FixtureManager uses connection aliases
  259. * protecting 'live' tables from being wiped by mistakes in
  260. * fixture connection names.
  261. *
  262. * @return void
  263. */
  264. public function testLoadConnectionAliasUsage()
  265. {
  266. $connection = ConnectionManager::get('test');
  267. $statement = $this->getMockBuilder('Cake\Database\StatementInterface')
  268. ->getMock();
  269. // This connection should _not_ be used.
  270. $other = $this->getMockBuilder('Cake\Database\Connection')
  271. ->setMethods(['execute'])
  272. ->setConstructorArgs([['driver' => $connection->getDriver()]])
  273. ->getMock();
  274. $other->expects($this->never())
  275. ->method('execute')
  276. ->will($this->returnValue($statement));
  277. // This connection should be used instead of
  278. // the 'other' connection as the alias should not be ignored.
  279. $testOther = $this->getMockBuilder('Cake\Database\Connection')
  280. ->setMethods(['execute'])
  281. ->setConstructorArgs([[
  282. 'database' => $connection->config()['database'],
  283. 'driver' => $connection->getDriver(),
  284. ]])
  285. ->getMock();
  286. $testOther->expects($this->atLeastOnce())
  287. ->method('execute')
  288. ->will($this->returnValue($statement));
  289. ConnectionManager::setConfig('other', $other);
  290. ConnectionManager::setConfig('test_other', $testOther);
  291. // Connect the alias making test_other an alias of other.
  292. ConnectionManager::alias('test_other', 'other');
  293. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  294. $test->expects($this->any())
  295. ->method('getFixtures')
  296. ->willReturn(['core.OtherArticles']);
  297. $this->manager->fixturize($test);
  298. $this->manager->load($test);
  299. ConnectionManager::drop('other');
  300. ConnectionManager::drop('test_other');
  301. }
  302. /**
  303. * Test loading fixtures using loadSingle()
  304. *
  305. * @return void
  306. */
  307. public function testLoadSingle()
  308. {
  309. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')
  310. ->setMethods(['getFixtures'])
  311. ->getMock();
  312. $test->autoFixtures = false;
  313. $test->expects($this->any())
  314. ->method('getFixtures')
  315. ->willReturn(['core.Articles', 'core.Tags']);
  316. $this->manager->fixturize($test);
  317. $this->manager->loadSingle('Articles');
  318. $this->manager->loadSingle('Tags');
  319. $table = $this->getTableLocator()->get('Articles');
  320. $results = $table->find('all')->toArray();
  321. $schema = $table->getSchema();
  322. $expectedConstraint = [
  323. 'type' => 'primary',
  324. 'columns' => [
  325. 'id',
  326. ],
  327. 'length' => [],
  328. ];
  329. $this->assertSame($expectedConstraint, $schema->getConstraint('primary'));
  330. $this->assertCount(3, $results);
  331. $this->manager->unload($test);
  332. }
  333. /**
  334. * Test exception on load
  335. *
  336. * @return void
  337. */
  338. public function testExceptionOnLoad()
  339. {
  340. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  341. $test->expects($this->any())
  342. ->method('getFixtures')
  343. ->willReturn(['core.Products']);
  344. $manager = $this->getMockBuilder(FixtureManager::class)
  345. ->setMethods(['_runOperation'])
  346. ->getMock();
  347. $manager->expects($this->any())
  348. ->method('_runOperation')
  349. ->will($this->returnCallback(function () {
  350. throw new PDOException('message');
  351. }));
  352. $manager->fixturize($test);
  353. $e = null;
  354. try {
  355. $manager->load($test);
  356. } catch (\Exception $e) {
  357. }
  358. $this->assertNotNull($e);
  359. $this->assertRegExp('/^Unable to insert fixtures for "Mock_TestCase_\w+" test case. message$/D', $e->getMessage());
  360. $this->assertInstanceOf('PDOException', $e->getPrevious());
  361. }
  362. /**
  363. * Test exception on load fixture
  364. *
  365. * @dataProvider loadErrorMessageProvider
  366. * @return void
  367. */
  368. public function testExceptionOnLoadFixture($method, $expectedMessage)
  369. {
  370. $fixture = $this->getMockBuilder('Cake\Test\Fixture\ProductsFixture')
  371. ->setMethods([$method])
  372. ->getMock();
  373. $fixture->expects($this->once())
  374. ->method($method)
  375. ->will($this->returnCallback(function () {
  376. throw new PDOException('message');
  377. }));
  378. $fixtures = [
  379. 'core.Products' => $fixture,
  380. ];
  381. $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
  382. $test->expects($this->any())
  383. ->method('getFixtures')
  384. ->willReturn(array_keys($fixtures));
  385. $manager = $this->getMockBuilder(FixtureManager::class)
  386. ->setMethods(['_fixtureConnections'])
  387. ->getMock();
  388. $manager->expects($this->any())
  389. ->method('_fixtureConnections')
  390. ->will($this->returnValue([
  391. 'test' => $fixtures,
  392. ]));
  393. $manager->fixturize($test);
  394. $manager->loadSingle('Products');
  395. $e = null;
  396. try {
  397. $manager->load($test);
  398. } catch (CakeException $e) {
  399. }
  400. $this->assertNotNull($e);
  401. $this->assertRegExp($expectedMessage, $e->getMessage());
  402. $this->assertInstanceOf('PDOException', $e->getPrevious());
  403. }
  404. /**
  405. * Data provider for testExceptionOnLoadFixture
  406. *
  407. * @return array
  408. */
  409. public function loadErrorMessageProvider()
  410. {
  411. return [
  412. [
  413. 'createConstraints',
  414. '/^Unable to create constraints for fixture "Mock_ProductsFixture_\w+" in "Mock_TestCase_\w+" test case: \nmessage$/D',
  415. ],
  416. [
  417. 'dropConstraints',
  418. '/^Unable to drop constraints for fixture "Mock_ProductsFixture_\w+" in "Mock_TestCase_\w+" test case: \nmessage$/D',
  419. ],
  420. [
  421. 'insert',
  422. '/^Unable to insert fixture "Mock_ProductsFixture_\w+" in "Mock_TestCase_\w+" test case: \nmessage$/D',
  423. ],
  424. ];
  425. }
  426. }