Advertisement
rfv123

Q32451215Test_02B_EmulatesOff__WithSuperUserAsIntegerParamTy

Sep 15th, 2015
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 11.40 KB | None | 0 0
  1. <?php // http://stackoverflow.com/questions/32451215/prepared-insert-doesnt-do-anything-if-attr-emulate-prepares-is-false
  2.  
  3. include 'P:/developer/xampp/htdocs/testmysql/Q32451215/IMysqlGeneralLogging.php';
  4. include 'P:/developer/xampp/htdocs/testmysql/Q32451215/MysqlGeneralLogging.php';
  5.  
  6. class Q23451215Test extends PHPUnit_Framework_TestCase {
  7.  
  8.     /**
  9.      * Test Data
  10.      */
  11.     protected $guid             = '420D4B65565311E5958000FFD7CBE75F';
  12.     protected $displayname     = 'Example User 42';
  13.     protected $hash             = '$2y$17$12345678901234567890121234567890123456789012345678942';
  14.     protected $salt             = '$2y$17$1234567890123456789042$';
  15.     protected $email            = 'example42@example.com';
  16.     protected $superuser       =  true;
  17.  
  18.     /**
  19.      * I will also record all the return codes from the PDO functions
  20.      * so that I can see what was returned with what happened vs what we expect.
  21.      *
  22.      * This will be useful with the later test.
  23.      * Must be static so they are not reset with each test
  24.      */
  25.     protected static $rcActual = array(
  26.         'prepare'       => false,
  27.         'execute'       => false,
  28.         'exception'     => false,
  29.         'exceptionMsg'  => '',
  30.         'errorCode'     => '',  // return code from the statement or connection
  31.         'errorInfo'     => ''   // return message from the statement or connection
  32.     );
  33.  
  34.     /**
  35.      * Expected Results
  36.      * Must be static so they are not reset with each test
  37.      */
  38.     protected static $rcExpected = array(
  39.         'prepare'       => true,
  40.         'execute'       => true,
  41.         'exception'     => false,
  42.         'exceptionMsg'  => '',
  43.     );
  44.  
  45.     /**
  46.      * Testing settings:
  47.      *
  48.      *   PDO::ATTR_ERRMODE           => PDO::ERRMODE_EXCEPTION);
  49.      *   PDO::ATTR_EMULATE_PREPARES  => FALSE;
  50.      */
  51.  
  52.     /**
  53.      * Expected Results:
  54.      *
  55.      * All Ok -
  56.      *
  57.      * 1) An inserted row of the supplied test data
  58.      * 2) An 'INSERT' statement in the trace log
  59.      */
  60.  
  61.     public function testEmululatesPreparesOff2B_WithSuperUserAsIntegerParamType() {
  62.         echo PHP_EOL, "----------- ". __METHOD__.__LINE__ ." -----------", PHP_EOL;
  63.  
  64.         $this->userPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  65.         $this->userPDO->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  66.  
  67.         $testFilename = $this->logging->newTraceFilename($this->parseMethod(__METHOD__));
  68.         $this->logging->setLogFile($testFilename);
  69.         $this->logging->clearFileLog();
  70.         $this->logging->startLoggingToFile(); // start logging...
  71.         // --------------------------------------------------------
  72.  
  73.         /*
  74.          * The actual code to be tested is here...
  75.          */
  76.  
  77.         try
  78.         {
  79.             self::$rcActual['exception'] = false;
  80.  
  81.             $stmt = $this->userPDO->prepare(
  82.                        "INSERT INTO `account`
  83.                                (`guid`,       `displayname`, `password_hash`, `password_salt`, `email`, `superuser`)
  84.                        VALUES
  85.                                (UNHEX(:guid), :displayname,  :passwordhash,   :passwordsalt,   :email,  :superuser);");
  86.  
  87.             self::$rcActual['prepare'] = $stmt !== false;
  88.  
  89.             $stmt->bindValue(':guid',         $this->guid,         PDO::PARAM_STR);
  90.             $stmt->bindValue(':displayname',  $this->displayname, PDO::PARAM_STR);
  91.             $stmt->bindValue(':passwordhash', $this->hash,         PDO::PARAM_STR);
  92.             $stmt->bindValue(':passwordsalt', $this->salt,         PDO::PARAM_STR);
  93.             $stmt->bindValue(':email',        $this->email,        PDO::PARAM_STR);
  94.             $stmt->bindValue(':superuser',    $this->superuser,   PDO::PARAM_INT);
  95.  
  96.             self::$rcActual['execute'] = $stmt->execute();
  97.  
  98.             self::$rcActual['errorCode'] = $stmt->errorCode();
  99.             self::$rcActual['errorInfo'] = $stmt->errorInfo();
  100.  
  101.  
  102.             $this->assertTrue(self::$rcActual['execute']);
  103.             $this->assertFalse(self::$rcActual['exception']);
  104.         }
  105.         catch (\Exception $e) {
  106.             self::$rcActual['exception'] = true;
  107.             self::$rcActual['exceptionMsg'] = $e->getCode() .' : '. $e->getMessage();
  108.  
  109.             var_dump(__METHOD__.__LINE__ .'error codes',
  110.                      'pdo:',  $this->userPDO->errorCode(), $this->userPDO->errorInfo(),
  111.                      'stmt:', $stmt->errorCode(), $stmt->errorInfo()
  112.                      );
  113.             $this->assertTrue(self::$rcActual['exception']);
  114.         }
  115.  
  116.         // --------------------------------------------------------
  117.         $this->logging->stopLogging();
  118.         echo PHP_EOL, "----------- ". __METHOD__.__LINE__ ." -----------", PHP_EOL;
  119.     }
  120.  
  121.     /**
  122.      * Show the results of the
  123.      */
  124.     public function testShowResults() {
  125.         echo PHP_EOL, "----------- ". __METHOD__.__LINE__ ." -----------", PHP_EOL;
  126.             echo PHP_EOL, "prepare   : Expected:  ", var_export(self::$rcExpected['prepare'], true),
  127.                                    ", Actual: ",   var_export(self::$rcActual['prepare'], true);
  128.  
  129.  
  130.             echo PHP_EOL, "execute   : Expected:  ", var_export(self::$rcExpected['execute'], true),
  131.                                    ", Actual: ",     var_export(self::$rcActual['execute'], true);
  132.  
  133.             echo PHP_EOL, "exception : Expected:  ", var_export(self::$rcExpected['exception'], true),
  134.                                      ", Actual: ",    var_export(self::$rcActual['exception'], true);
  135.  
  136.             echo PHP_EOL, "exceptionMsg : Expected:  ", var_export(self::$rcExpected['exceptionMsg'], true),
  137.                                        ", Actual: ",    var_export(self::$rcActual['exceptionMsg'], true);
  138.  
  139.             if (!empty(self::$rcActual['errorInfo'])) {
  140.                echo PHP_EOL, "errorCode : ", var_export(self::$rcActual['errorCode'], true),
  141.                                        ", ErrorMsg: ",    var_export(self::$rcActual['errorInfo'], true);
  142.             }
  143.  
  144.         echo PHP_EOL, "----------- ". __METHOD__.__LINE__ ." -----------", PHP_EOL;
  145.  
  146.         $this->assertEquals(self::$rcExpected['prepare'],   self::$rcActual['prepare']);
  147.         $this->assertEquals(self::$rcExpected['execute'],   self::$rcActual['execute']);
  148.         $this->assertEquals(self::$rcExpected['exception'], self::$rcActual['exception']);
  149.     }
  150.  
  151.     /* -----------------------------------------------------------------------
  152.      * Standard setup stuff after this...
  153.      * No need to change it once you have set it up to work.
  154.      */
  155.  
  156.     /**
  157.      * @var MysqlGeneralLogging
  158.      */
  159.     protected $logging;
  160.  
  161.     /**
  162.      * SQL Testing Connection
  163.      *
  164.      * @var PDO
  165.      */
  166.     protected $userPDO = null;
  167.  
  168.     public function parseMethod($method, $which = 'method')
  169.     {
  170.         $fields = explode('::', $method);
  171.         if ($which == 'method') {
  172.            return ($fields[1]);
  173.         }
  174.         return $fields[0];
  175.     }
  176.  
  177.  
  178.     protected static $runAtStart = true;
  179.  
  180.     /**
  181.      * Sets up the fixture, for example, opens a network connection.
  182.      * This method is called before a test is executed.
  183.      */
  184.     protected function setUp() {
  185.         $this->logging = MysqlGeneralLogging::newInstanceFromParams(
  186.                                 'localhost', 'root', 'root', 'Q32451215',
  187.                                  __DIR__);
  188.  
  189.         // MySql User account
  190.         $host      = 'localhost';
  191.         $username  = 'test';
  192.         $password  = 'test';
  193.         $dbname    = 'test';
  194.  
  195.         $dsn = "mysql:host={$host};" . (!empty($dbname) ? "dbname={$dbname};" : '');
  196.         $pdoConnection = new \PDO($dsn, $username, $password);
  197.         $pdoConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  198.         $pdoConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
  199.         $this->userPDO = $pdoConnection;
  200.  
  201. //        echo PHP_EOL;
  202.         $this->runAtStart();
  203.         // echo PHP_EOL, ' <<<<<<<<<< test starting >>>>>>>>>', PHP_EOL;
  204.     }
  205.  
  206.    public function initAccountTable()
  207.    {
  208.        $sql = "CREATE TABLE IF NOT EXISTS `account` (
  209.                    `guid` binary(16) NOT NULL,
  210.                    `displayname` varchar(32) NOT NULL,
  211.                    `password_hash` binary(60) NOT NULL,
  212.                    `password_salt` binary(30) NOT NULL,
  213.                    `email` varchar(256) NOT NULL,
  214.                    `superuser` tinyint(1) NOT NULL DEFAULT '0',
  215.                    `account_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  216.                PRIMARY KEY (`guid`))
  217.                ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  218.              ";
  219.  
  220.        $this->userPDO->exec($sql);
  221.        $this->userPDO->exec("truncate table `test`.`account`;");
  222.  
  223.        $dataArray = array(
  224.         "INSERT INTO `account` (`guid`, `displayname`, `password_hash`, `password_salt`, `email`) VALUES (UNHEX(REPLACE(UUID(), '-', '')), 'Example User 1', '$2y$17$12345678901234567890121234567890123456789012345678901', '$2y$17$1234567890123456789012$', 'example1@example.com');",
  225.         "INSERT INTO `account` (`guid`, `displayname`, `password_hash`, `password_salt`, `email`) VALUES (UNHEX(REPLACE(UUID(), '-', '')), 'Example User 2', '$2y$17$12345678901234567890121234567890123456789012345678901', '$2y$17$1234567890123456789012$', 'example2@example.com');",
  226.         "INSERT INTO `account` (`guid`, `displayname`, `password_hash`, `password_salt`, `email`) VALUES (UNHEX(REPLACE(UUID(), '-', '')), 'Example User 3', '$2y$17$12345678901234567890121234567890123456789012345678901', '$2y$17$1234567890123456789012$', 'example3@example.com');",
  227.         "INSERT INTO `account` (`guid`, `displayname`, `password_hash`, `password_salt`, `email`) VALUES (UNHEX(REPLACE(UUID(), '-', '')), 'Example User 4', '$2y$17$12345678901234567890121234567890123456789012345678901', '$2y$17$1234567890123456789012$', 'example4@example.com');",
  228.         "INSERT INTO `account` (`guid`, `displayname`, `password_hash`, `password_salt`, `email`) VALUES (UNHEX(REPLACE(UUID(), '-', '')), 'Example User 5', '$2y$17$12345678901234567890121234567890123456789012345678901', '$2y$17$1234567890123456789012$', 'example5@example.com');",
  229.        );
  230.  
  231.        foreach ($dataArray as $insertSql) {
  232.             $this->userPDO->exec($insertSql);
  233.        }
  234.  
  235.        // confirm all ok...
  236.        $resultSet = $this->userPDO->query("SELECT count(*) as `rowCount` FROM `account`");
  237.        $result = current($resultSet->fetchAll(PDO::FETCH_ASSOC));
  238.        $this->assertEquals(count($dataArray), $result['rowCount']);
  239.    }
  240.  
  241.     protected function runAtStart()
  242.     {
  243.         if (!self::$runAtStart) { return; }
  244.         self::$runAtStart = false;
  245.  
  246.  
  247.         $this->initAccountTable();
  248.  
  249.         // Clear all the current trace logs and table
  250.         $this->logging->stopLogging();
  251.         $this->logging->clearLogs();
  252.         $testLogFile = $this->logging->newTraceFilename(
  253.                 $this->parseMethod(__METHOD__.__LINE__));
  254.         $this->logging->setLogFile($testLogFile);
  255.         $files = $this->logging->deleteAllTraceFiles();
  256.         // var_dump(__METHOD__.__LINE__, $files);
  257.     }
  258.  
  259.     /**
  260.      * Tears down the fixture, for example, closes a network connection.
  261.      * This method is called after a test is executed.
  262.      */
  263.     protected function tearDown() {
  264.         $this->logging->stopLogging();
  265.         $this->logging = null;
  266.         $this->userPDO = null;
  267.         // echo ' <<<<<<<<<< test ending >>>>>>>>>', PHP_EOL;
  268.     }
  269. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement