DbalFunctionalTestCase.php 2.52 KB
Newer Older
1 2 3 4 5 6
<?php

namespace Doctrine\Tests;

class DbalFunctionalTestCase extends DbalTestCase
{
7 8 9
    /**
     * Shared connection when a TestCase is run alone (outside of it's functional suite)
     *
10
     * @var \Doctrine\DBAL\Connection
11
     */
12
    private static $_sharedConn;
13 14

    /**
15
     * @var \Doctrine\DBAL\Connection
16
     */
17 18
    protected $_conn;

19 20 21 22 23
    /**
     * @var \Doctrine\DBAL\Logging\DebugStack
     */
    protected $_sqlLoggerStack;

24 25
    protected function resetSharedConn()
    {
26 27 28 29
        if (self::$_sharedConn) {
            self::$_sharedConn->close();
            self::$_sharedConn = null;
        }
30 31
    }

32 33
    protected function setUp()
    {
34 35
        if ( ! isset(self::$_sharedConn)) {
            self::$_sharedConn = TestUtil::getConnection();
36
        }
37
        $this->_conn = self::$_sharedConn;
38 39 40 41 42

        $this->_sqlLoggerStack = new \Doctrine\DBAL\Logging\DebugStack();
        $this->_conn->getConfiguration()->setSQLLogger($this->_sqlLoggerStack);
    }

43 44
    protected function tearDown()
    {
45
        while ($this->_conn && $this->_conn->isTransactionActive()) {
46 47 48 49
            $this->_conn->rollBack();
        }
    }

50
    protected function onNotSuccessfulTest(\Exception $e)
51 52 53 54 55 56 57
    {
        if ($e instanceof \PHPUnit_Framework_AssertionFailedError) {
            throw $e;
        }

        if(isset($this->_sqlLoggerStack->queries) && count($this->_sqlLoggerStack->queries)) {
            $queries = "";
58
            $i = count($this->_sqlLoggerStack->queries);
jeroendedauw's avatar
jeroendedauw committed
59
            foreach (array_reverse($this->_sqlLoggerStack->queries) as $query) {
60 61
                $params = array_map(function($p) { if (is_object($p)) return get_class($p); else return "'".$p."'"; }, $query['params'] ?: array());
                $queries .= ($i+1).". SQL: '".$query['sql']."' Params: ".implode(", ", $params).PHP_EOL;
62
                $i--;
63 64 65 66
            }

            $trace = $e->getTrace();
            $traceMsg = "";
jeroendedauw's avatar
jeroendedauw committed
67
            foreach($trace as $part) {
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
                if(isset($part['file'])) {
                    if(strpos($part['file'], "PHPUnit/") !== false) {
                        // Beginning with PHPUnit files we don't print the trace anymore.
                        break;
                    }

                    $traceMsg .= $part['file'].":".$part['line'].PHP_EOL;
                }
            }

            $message = "[".get_class($e)."] ".$e->getMessage().PHP_EOL.PHP_EOL."With queries:".PHP_EOL.$queries.PHP_EOL."Trace:".PHP_EOL.$traceMsg;

            throw new \Exception($message, (int)$e->getCode(), $e);
        }
        throw $e;
83
    }
84
}