Browse Source

Use exception chaining

Refs #9824
chinpei215 8 years ago
parent
commit
0c342051b6

+ 1 - 1
src/Cache/Cache.php

@@ -182,7 +182,7 @@ class Cache
 
             if ($config['fallback'] === $name) {
                 throw new InvalidArgumentException(
-                    sprintf('"%s" cache configuration cannot fallback to itself.', $name)
+                    sprintf('"%s" cache configuration cannot fallback to itself.', $name), null, $e
                 );
             }
 

+ 1 - 1
src/Controller/Component/PaginatorComponent.php

@@ -205,7 +205,7 @@ class PaginatorComponent extends Component
         } catch (PageOutOfBoundsException $e) {
             $this->_setPagingParams();
 
-            throw new NotFoundException();
+            throw new NotFoundException(null, null, $e);
         }
 
         return $results;

+ 1 - 1
src/Database/Connection.php

@@ -224,7 +224,7 @@ class Connection implements ConnectionInterface
         try {
             return $this->_driver->connect();
         } catch (\Exception $e) {
-            throw new MissingConnectionException(['reason' => $e->getMessage()]);
+            throw new MissingConnectionException(['reason' => $e->getMessage()], null, $e);
         }
     }
 

+ 4 - 4
src/Mailer/Transport/SmtpTransport.php

@@ -228,12 +228,12 @@ class SmtpTransport extends AbstractTransport
             }
         } catch (SocketException $e) {
             if ($config['tls']) {
-                throw new SocketException('SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.');
+                throw new SocketException('SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.', null, $e);
             }
             try {
                 $this->_smtpSend("HELO {$host}", '250');
             } catch (SocketException $e2) {
-                throw new SocketException('SMTP server did not accept the connection.');
+                throw new SocketException('SMTP server did not accept the connection.', null, $e2);
             }
         }
     }
@@ -252,12 +252,12 @@ class SmtpTransport extends AbstractTransport
                 try {
                     $this->_smtpSend(base64_encode($this->_config['username']), '334');
                 } catch (SocketException $e) {
-                    throw new SocketException('SMTP server did not accept the username.');
+                    throw new SocketException('SMTP server did not accept the username.', null, $e);
                 }
                 try {
                     $this->_smtpSend(base64_encode($this->_config['password']), '235');
                 } catch (SocketException $e) {
-                    throw new SocketException('SMTP server did not accept the password.');
+                    throw new SocketException('SMTP server did not accept the password.', null, $e);
                 }
             } elseif ($replyCode === '504') {
                 throw new SocketException('SMTP authentication method not allowed, check if SMTP server requires TLS.');

+ 1 - 1
src/Network/Socket.php

@@ -435,7 +435,7 @@ class Socket
             $enableCryptoResult = stream_socket_enable_crypto($this->connection, $enable, $this->_encryptMethods[$type . '_' . $clientOrServer]);
         } catch (Exception $e) {
             $this->setLastError(null, $e->getMessage());
-            throw new SocketException($e->getMessage());
+            throw new SocketException($e->getMessage(), null, $e);
         }
         if ($enableCryptoResult === true) {
             $this->encrypted = $enable;

+ 4 - 4
src/TestSuite/Fixture/FixtureManager.php

@@ -303,7 +303,7 @@ class FixtureManager
                                 get_class($test),
                                 $e->getMessage()
                             );
-                            throw new Exception($msg);
+                            throw new Exception($msg, null, $e);
                         }
                     }
                 }
@@ -326,7 +326,7 @@ class FixtureManager
                             get_class($test),
                             $e->getMessage()
                         );
-                        throw new Exception($msg);
+                        throw new Exception($msg, null, $e);
                     }
                 }
             };
@@ -344,7 +344,7 @@ class FixtureManager
                             get_class($test),
                             $e->getMessage()
                         );
-                        throw new Exception($msg);
+                        throw new Exception($msg, null, $e);
                     }
                 }
             };
@@ -355,7 +355,7 @@ class FixtureManager
                 get_class($test),
                 $e->getMessage()
             );
-            throw new Exception($msg);
+            throw new Exception($msg, null, $e);
         }
     }
 

+ 1 - 1
src/View/Cell.php

@@ -215,7 +215,7 @@ abstract class Cell
             try {
                 return $this->View->render($template);
             } catch (MissingTemplateException $e) {
-                throw new MissingCellViewException(['file' => $template, 'name' => $name]);
+                throw new MissingCellViewException(['file' => $template, 'name' => $name], null, $e);
             }
         };
 

+ 9 - 4
tests/TestCase/Cache/CacheTest.php

@@ -106,9 +106,6 @@ class CacheTest extends TestCase
     {
         $filename = tempnam(TMP, 'tmp_');
 
-        $this->expectException(InvalidArgumentException::class);
-        $this->expectExceptionMessage('cannot fallback to itself');
-
         Cache::setConfig('tests', [
             'engine' => 'File',
             'path' => $filename,
@@ -116,10 +113,18 @@ class CacheTest extends TestCase
             'fallback' => 'tests'
         ]);
 
-        Cache::engine('tests');
+        $e = null;
+        try {
+            Cache::engine('tests');
+        } catch (InvalidArgumentException $e) {
+        }
 
         Cache::drop('tests');
         unlink($filename);
+
+        $this->assertNotNull($e);
+        $this->assertStringEndsWith('cannot fallback to itself.', $e->getMessage());
+        $this->assertInstanceOf('RunTimeException', $e->getPrevious());
     }
 
     /**

+ 23 - 12
tests/TestCase/Controller/Component/PaginatorComponentTest.php

@@ -19,6 +19,7 @@ use Cake\Controller\Component\PaginatorComponent;
 use Cake\Controller\Controller;
 use Cake\Datasource\ConnectionManager;
 use Cake\Datasource\EntityInterface;
+use Cake\Datasource\Exception\PageOutOfBoundsException;
 use Cake\Datasource\Paginator;
 use Cake\Http\ServerRequest;
 use Cake\Network\Exception\NotFoundException;
@@ -720,16 +721,21 @@ class PaginatorComponentTest extends TestCase
         $this->request->query['page'] = 3000;
 
         $table = TableRegistry::get('PaginatorPosts');
+
+        $e = null;
         try {
             $this->Paginator->paginate($table);
-            $this->fail('No exception raised');
         } catch (NotFoundException $e) {
-            $this->assertEquals(
-                1,
-                $this->request->params['paging']['PaginatorPosts']['page'],
-                'Page number should not be 0'
-            );
         }
+
+        $this->assertEquals(
+            1,
+            $this->request->params['paging']['PaginatorPosts']['page'],
+            'Page number should not be 0'
+        );
+
+        $this->assertNotNull($e);
+        $this->assertInstanceOf(PageOutOfBoundsException::class, $e->getPrevious());
     }
 
     /**
@@ -744,16 +750,21 @@ class PaginatorComponentTest extends TestCase
         $this->request->query['page'] = 4;
 
         $table = TableRegistry::get('PaginatorPosts');
+
+        $e = null;
         try {
             $this->Paginator->paginate($table);
-            $this->fail('No exception raised');
         } catch (NotFoundException $e) {
-            $this->assertEquals(
-                3,
-                $this->request->params['paging']['PaginatorPosts']['pageCount'],
-                'Page count number should not be 0'
-            );
         }
+
+        $this->assertEquals(
+            3,
+            $this->request->params['paging']['PaginatorPosts']['pageCount'],
+            'Page count number should not be 0'
+        );
+
+        $this->assertNotNull($e);
+        $this->assertInstanceOf(PageOutOfBoundsException::class, $e->getPrevious());
     }
 
     /**

+ 11 - 2
tests/TestCase/Database/ConnectionTest.php

@@ -16,6 +16,7 @@ namespace Cake\Test\TestCase\Database;
 
 use Cake\Database\Connection;
 use Cake\Database\Driver\Mysql;
+use Cake\Database\Exception\MissingConnectionException;
 use Cake\Database\Exception\NestedTransactionRollbackException;
 use Cake\Database\Log\LoggingStatement;
 use Cake\Database\Log\QueryLogger;
@@ -161,7 +162,6 @@ class ConnectionTest extends TestCase
     /**
      * Tests that connecting with invalid credentials or database name throws an exception
      *
-     * @expectedException \Cake\Database\Exception\MissingConnectionException
      * @return void
      */
     public function testWrongCredentials()
@@ -169,7 +169,16 @@ class ConnectionTest extends TestCase
         $config = ConnectionManager::getConfig('test');
         $this->skipIf(isset($config['url']), 'Datasource has dsn, skipping.');
         $connection = new Connection(['database' => '/dev/nonexistent'] + ConnectionManager::getConfig('test'));
-        $connection->connect();
+
+        $e = null;
+        try {
+            $connection->connect();
+        } catch (MissingConnectionException $e) {
+        }
+
+        $this->assertNotNull($e);
+        $this->assertStringStartsWith('Connection to database could not be established:', $e->getMessage());
+        $this->assertInstanceOf('PDOException', $e->getPrevious());
     }
 
     /**

+ 45 - 12
tests/TestCase/Mailer/Transport/SmtpTransportTest.php

@@ -16,6 +16,7 @@ namespace Cake\Test\TestCase\Mailer\Transport;
 
 use Cake\Mailer\Email;
 use Cake\Mailer\Transport\SmtpTransport;
+use Cake\Network\Exception\SocketException;
 use Cake\Network\Socket;
 use Cake\TestSuite\TestCase;
 
@@ -124,8 +125,6 @@ class SmtpTransportTest extends TestCase
     /**
      * testConnectEhloTlsOnNonTlsServer method
      *
-     * @expectedException \Cake\Network\Exception\SocketException
-     * @expectedExceptionMessage SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.
      * @return void
      */
     public function testConnectEhloTlsOnNonTlsServer()
@@ -138,7 +137,17 @@ class SmtpTransportTest extends TestCase
         $this->socket->expects($this->at(4))->method('write')->with("STARTTLS\r\n");
         $this->socket->expects($this->at(5))->method('read')
             ->will($this->returnValue("500 5.3.3 Unrecognized command\r\n"));
-        $this->SmtpTransport->connect();
+
+        $e = null;
+        try {
+            $this->SmtpTransport->connect();
+        } catch (SocketException $e) {
+        }
+
+        $this->assertNotNull($e);
+        $this->assertEquals('SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.', $e->getMessage());
+        $this->assertInstanceOf(SocketException::class, $e->getPrevious());
+        $this->assertContains('500 5.3.3 Unrecognized command', $e->getPrevious()->getMessage());
     }
 
     /**
@@ -180,8 +189,6 @@ class SmtpTransportTest extends TestCase
     /**
      * testConnectFail method
      *
-     * @expectedException \Cake\Network\Exception\SocketException
-     * @expectedExceptionMessage SMTP server did not accept the connection.
      * @return void
      */
     public function testConnectFail()
@@ -192,7 +199,17 @@ class SmtpTransportTest extends TestCase
         $this->socket->expects($this->at(3))->method('read')->will($this->returnValue("200 Not Accepted\r\n"));
         $this->socket->expects($this->at(4))->method('write')->with("HELO localhost\r\n");
         $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("200 Not Accepted\r\n"));
-        $this->SmtpTransport->connect();
+
+        $e = null;
+        try {
+            $this->SmtpTransport->connect();
+        } catch (SocketException $e) {
+        }
+
+        $this->assertNotNull($e);
+        $this->assertEquals('SMTP server did not accept the connection.', $e->getMessage());
+        $this->assertInstanceOf(SocketException::class, $e->getPrevious());
+        $this->assertContains('200 Not Accepted', $e->getPrevious()->getMessage());
     }
 
     /**
@@ -263,8 +280,6 @@ class SmtpTransportTest extends TestCase
     /**
      * testAuthBadUsername method
      *
-     * @expectedException \Cake\Network\Exception\SocketException
-     * @expectedExceptionMessage SMTP server did not accept the username.
      * @return void
      */
     public function testAuthBadUsername()
@@ -275,14 +290,22 @@ class SmtpTransportTest extends TestCase
         $this->socket->expects($this->at(3))->method('read')
             ->will($this->returnValue("535 5.7.8 Authentication failed\r\n"));
         $this->SmtpTransport->config(['username' => 'mark', 'password' => 'story']);
-        $this->SmtpTransport->auth();
+
+        $e = null;
+        try {
+            $this->SmtpTransport->auth();
+        } catch (SocketException $e) {
+        }
+
+        $this->assertNotNull($e);
+        $this->assertEquals('SMTP server did not accept the username.', $e->getMessage());
+        $this->assertInstanceOf(SocketException::class, $e->getPrevious());
+        $this->assertContains('535 5.7.8 Authentication failed', $e->getPrevious()->getMessage());
     }
 
     /**
      * testAuthBadPassword method
      *
-     * @expectedException \Cake\Network\Exception\SocketException
-     * @expectedExceptionMessage SMTP server did not accept the password.
      * @return void
      */
     public function testAuthBadPassword()
@@ -294,7 +317,17 @@ class SmtpTransportTest extends TestCase
         $this->socket->expects($this->at(4))->method('write')->with("c3Rvcnk=\r\n");
         $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("535 5.7.8 Authentication failed\r\n"));
         $this->SmtpTransport->config(['username' => 'mark', 'password' => 'story']);
-        $this->SmtpTransport->auth();
+
+        $e = null;
+        try {
+            $this->SmtpTransport->auth();
+        } catch (SocketException $e) {
+        }
+
+        $this->assertNotNull($e);
+        $this->assertEquals('SMTP server did not accept the password.', $e->getMessage());
+        $this->assertInstanceOf(SocketException::class, $e->getPrevious());
+        $this->assertContains('535 5.7.8 Authentication failed', $e->getPrevious()->getMessage());
     }
 
     /**

+ 9 - 2
tests/TestCase/Network/SocketTest.php

@@ -277,7 +277,6 @@ class SocketTest extends TestCase
     /**
      * testEnableCryptoSocketExceptionNoTls
      *
-     * @expectedException \Cake\Network\Exception\SocketException
      * @return void
      */
     public function testEnableCryptoSocketExceptionNoTls()
@@ -287,7 +286,15 @@ class SocketTest extends TestCase
         // testing exception on no ssl socket server for ssl and tls methods
         $this->Socket = new Socket($configNoSslOrTls);
         $this->Socket->connect();
-        $this->Socket->enableCrypto('tls', 'client');
+
+        $e = null;
+        try {
+            $this->Socket->enableCrypto('tls', 'client');
+        } catch (SocketException $e) {
+        }
+
+        $this->assertNotNull($e);
+        $this->assertInstanceOf('Exception', $e->getPrevious());
     }
 
     /**

+ 103 - 0
tests/TestCase/TestSuite/FixtureManagerTest.php

@@ -14,6 +14,7 @@
  */
 namespace Cake\Test\TestSuite;
 
+use Cake\Core\Exception\Exception as CakeException;
 use Cake\Core\Plugin;
 use Cake\Database\Schema\Table;
 use Cake\Datasource\ConnectionManager;
@@ -22,6 +23,7 @@ use Cake\ORM\TableRegistry;
 use Cake\TestSuite\Fixture\FixtureManager;
 use Cake\TestSuite\Stub\ConsoleOutput;
 use Cake\TestSuite\TestCase;
+use PDOException;
 
 /**
  * Fixture manager test case.
@@ -387,4 +389,105 @@ class FixtureManagerTest extends TestCase
         $this->assertCount(4, $results);
         $this->manager->unload($test);
     }
+
+    /**
+     * Test exception on load
+     *
+     * @return void
+     */
+    public function testExceptionOnLoad()
+    {
+        $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
+        $test->fixtures = ['core.products'];
+
+        $manager = $this->getMockBuilder(FixtureManager::class)
+            ->setMethods(['_runOperation'])
+            ->getMock();
+        $manager->expects($this->any())
+            ->method('_runOperation')
+            ->will($this->returnCallback(function () {
+                throw new PDOException('message');
+            }));
+
+        $manager->fixturize($test);
+
+        $e = null;
+        try {
+            $manager->load($test);
+        } catch (CakeException $e) {
+        }
+
+        $this->assertNotNull($e);
+        $this->assertRegExp('/^Unable to insert fixtures for "Mock_TestCase_\w+" test case. message$/D', $e->getMessage());
+        $this->assertInstanceOf('PDOException', $e->getPrevious());
+    }
+
+    /**
+     * Test exception on load fixture
+     *
+     * @dataProvider loadErrorMessageProvider
+     * @return void
+     */
+    public function testExceptionOnLoadFixture($method, $expectedMessage)
+    {
+        $fixture = $this->getMockBuilder('Cake\Test\Fixture\ProductsFixture')
+            ->setMethods([$method])
+            ->getMock();
+        $fixture->expects($this->once())
+            ->method($method)
+            ->will($this->returnCallback(function () {
+                throw new PDOException('message');
+            }));
+
+        $fixtures = [
+            'core.products' => $fixture,
+        ];
+
+        $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
+        $test->fixtures = array_keys($fixtures);
+
+        $manager = $this->getMockBuilder(FixtureManager::class)
+            ->setMethods(['_fixtureConnections'])
+            ->getMock();
+        $manager->expects($this->any())
+            ->method('_fixtureConnections')
+            ->will($this->returnValue([
+                'test' => $fixtures,
+            ]));
+        $manager->fixturize($test);
+        $manager->loadSingle('Products');
+
+        $e = null;
+        try {
+            $manager->load($test);
+        } catch (CakeException $e) {
+        }
+
+        $this->assertNotNull($e);
+        $this->assertRegExp($expectedMessage, $e->getMessage());
+        $this->assertInstanceOf('PDOException', $e->getPrevious());
+    }
+
+    /**
+     * Data provider for testExceptionOnLoadFixture
+     *
+     * @return array
+     */
+    public function loadErrorMessageProvider()
+    {
+        return [
+            [
+                'createConstraints',
+                '/^Unable to create constraints for fixture "Mock_ProductsFixture_\w+" in "Mock_TestCase_\w+" test case: \nmessage$/D',
+            ],
+            [
+                'dropConstraints',
+                '/^Unable to drop constraints for fixture "Mock_ProductsFixture_\w+" in "Mock_TestCase_\w+" test case: \nmessage$/D',
+            ],
+            [
+                'insert',
+                '/^Unable to insert fixture "Mock_ProductsFixture_\w+" in "Mock_TestCase_\w+" test case: \nmessage$/D',
+            ],
+        ];
+    }
 }

+ 12 - 2
tests/TestCase/View/CellTest.php

@@ -18,6 +18,8 @@ use Cake\Cache\Cache;
 use Cake\Core\Plugin;
 use Cake\TestSuite\TestCase;
 use Cake\View\View;
+use Cake\View\Exception\MissingCellViewException;
+use Cake\View\Exception\MissingTemplateException;
 use TestApp\Controller\CellTraitTestController;
 use TestApp\View\CustomJsonView;
 
@@ -192,13 +194,21 @@ class CellTest extends TestCase
     /**
      * Tests manual render() invocation with error
      *
-     * @expectedException \Cake\View\Exception\MissingCellViewException
      * @return void
      */
     public function testCellManualRenderError()
     {
         $cell = $this->View->cell('Articles');
-        $cell->render('derp');
+
+        $e = null;
+        try {
+            $cell->render('derp');
+        } catch (MissingCellViewException $e) {
+        }
+
+        $this->assertNotNull($e);
+        $this->assertEquals('Cell view file "derp" is missing.', $e->getMessage());
+        $this->assertInstanceOf(MissingTemplateException::class, $e->getPrevious());
     }
 
     /**