Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 7147f47793
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 429 lines (371 sloc) 17.465 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
<?php
/**
* LICENSE:
*
* This file is part of Isosceles (http://isosceleskit.org/).
*
* Isosceles is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any
* later version.
*
* Isosceles is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with Isosceles. If not, see
* <http://www.gnu.org/licenses/>.
*
* @license http://www.gnu.org/licenses/gpl.html
*/

require_once dirname(__FILE__).'/init.tests.php';
require_once ISOSCELES_PATH.'extlibs/simpletest/autorun.php';
require_once ISOSCELES_PATH.'libs/config.inc.php';

class TestOfPDODAO extends IsoscelesUnitTestCase {

    public function setUp() {
        parent::setUp();
    }

    protected function buildData() {
        $config = Config::getInstance();
        $config_array = $config->getValuesArray();
        $builders = array();

        $test_table_sql = 'CREATE TABLE ' . $config_array['table_prefix'] . 'test_table(' .
            'id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,' .
            'test_name varchar(20),' .
            'test_id int(11),' .
            'unique key test_id_idx (test_id)' .
            ')';
        $this->testdb_helper->runSQL($test_table_sql);

        for($i = 1; $i <= 20; $i++) {
            $builders[] = FixtureBuilder::build('test_table', array('test_name'=>'name'.$i, 'test_id'=>$i));
        }

        // Insert test data into test user table
        $builders[] = FixtureBuilder::build('users', array('user_id'=>12, 'user_name'=>'mary',
        'full_name'=>'Mary Jane', 'avatar'=>'avatar.jpg'));
        $builders[] = FixtureBuilder::build('users', array('user_id'=>13, 'user_name'=>'sweetmary',
        'full_name'=>'Sweet Mary Jane', 'avatar'=>'avatar.jpg'));
        return $builders;
    }

    /*
* Test whether the database supports time zones or only offsets
*/
    private function isTimeZoneSupported() {
        $testdao = DAOFactory::getDAO('TestDAO');
        try {
            TestMySQLDAO::$PDO->exec("SET time_zone = 'America/Los_Angeles'");
            return true;
        } catch (PDOException $e) {
            return false;
        }
    }

    public function tearDown() {
        $this->builders = null;
        parent::tearDown();
    }

    public function testInitDAO() {
        $testdao = DAOFactory::getDAO('TestDAO');
        $this->assertNotNull(TestMySQLDAO::$PDO);
        $this->assertNotNull($testdao->config);
    }

    public function testConvertBetweenBoolAndDB() {
        $testdao = DAOFactory::getDAO('TestDAO');
        $this->assertEqual(0, $testdao->testBoolToDB(null), 'should be 0');
        $this->assertEqual(0, $testdao->testBoolToDB(''), 'should be 0');
        $this->assertEqual(0, $testdao->testBoolToDB(false), 'should be 0');
        $this->assertEqual(0, $testdao->testBoolToDB(0), 'should be 0');
        $this->assertEqual(1, $testdao->testBoolToDB('a'), 'should be 1');
        $this->assertEqual(1, $testdao->testBoolToDB(true), 'should be 1');
        $this->assertEqual(1, $testdao->testBoolToDB(new TestData()), 'should be 1');
        $this->assertEqual(1, $testdao->testBoolToDB(1), 'should be 1');

        $this->assertEqual(false, $testdao->convertDBToBool(0), 'should be true');
        $this->assertEqual(true, $testdao->convertDBToBool(1), 'should be false');
    }

    public function testTwoObjectsOneConnection() {
        DAOFactory::getDAO('TestDAO');
        $this->assertNotNull(TestMySQLDAO::$PDO);
        TestMySQLDAO::$PDO->tu_testing = "testing";
        $testdao2 = DAOFactory::getDAO('TestDAO');
        $this->assertEqual(TestMySQLDAO::$PDO->tu_testing, "testing");
    }

    public function testBasicSelectUsingStatementHandleDirectly() {
        $this->builders = self::buildData();
        $testdao = DAOFactory::getDAO('TestDAO');
        $users = $testdao->getUserCount(0, 'mary');
        $this->assertIsA($users, "array");
        $this->assertEqual(count($users), 2);
        $this->assertEqual($users[0]['user_name'], 'mary');
        $this->assertEqual($users[1]['user_name'], 'sweetmary');
    }

    public function testBadSql() {
        $testdao = DAOFactory::getDAO('TestDAO');
        try {
            $testdao->badSql();
        } catch(PDOException $e) {
            $this->assertPattern('/Syntax error/', $e->getMessage(), 'should get a Syntax error message');
        }
    }

    public function testBadBinds() {
        $testdao = DAOFactory::getDAO('TestDAO');
        try {
            $testdao->badBinds();
        } catch(PDOException $e) {
            $this->assertPattern('/Invalid parameter number/', $e->getMessage(),
            'should get an Invalid parameter number error message');
        }
    }

    public function testInsertData() {
        $this->builders = self::buildData();
        $testdao = DAOFactory::getDAO('TestDAO');

        // ad a test_user with a test_id get insert count
        $cnt = $testdao->insertDataGetCount('test_user', '1000');
        $this->assertEqual(1, $cnt, "should have inserted 1 record");

        // add test_naem and id get last insert id
        $cnt = $testdao->insertDataGetId('test_user', '1001');
        $this->assertEqual(22, $cnt, "should get an insert id of 22");

        // add multiple records and get count
        $cnt = $testdao->insertMultiDataGetCount(array( array( 'test_user23', '23'), array( 'test_user24', '24') ));
        $this->assertEqual(2, $cnt, "should get an insert count of 2");

        // test duplicate key err, check for message?
        try {
            $cnt = $testdao->insertDataGetCount('test_user', '1000');
            $this->fail('should throw a PDOException');
        } catch(PDOException $e) {
            $this->assertPattern('/Duplicate entry/', $e->getMessage(), 'should get a dup key message');
        }
    }

    public function testUpdateData() {
        $this->builders = self::buildData();
        $testdao = DAOFactory::getDAO('TestDAO');

        // update a with a bad test_id get 0 insert count
        $cnt = $testdao->update( 'sally', 9999);
        $this->assertEqual(0, $cnt, "updated 0 records");

        // update a test_user with a test_id get insert count
        $cnt = $testdao->update('harry', 1);
        $this->assertEqual(1, $cnt, "updated 1 record");

        // update multiple test_users
        $cnt = $testdao->updateMulti('nick', 1);
        $this->assertEqual(19, $cnt, "updated 19 records");
    }

    public function testSelectSingleRecord() {
        $this->builders = self::buildData();
        $testdao = DAOFactory::getDAO('TestDAO');

        $data_obj = $testdao->selectRecord(999);
        $this->assertNull($data_obj);

        $data_obj = $testdao->selectRecord(2);
        $this->assertEqual($data_obj->id, '2');
        $this->assertEqual($data_obj->test_name, 'name2');
        $this->assertEqual($data_obj->test_id, '2');
    }

    public function testSelectSingleRecordAsArray() {
        $this->builders = self::buildData();
        $testdao = DAOFactory::getDAO('TestDAO');
        $data_obj = $testdao->selectRecordAsArray(999);
        $this->assertNull($data_obj);

        $data_obj = $testdao->selectRecordAsArray(3);
        $this->assertEqual($data_obj['id'], '3');
        $this->assertEqual($data_obj['test_name'], 'name3');
        $this->assertEqual($data_obj['test_id'], '3');
    }

    public function testSelectRecordsAsArrayWithLimit() {
        $this->builders = self::buildData();
        $testdao = DAOFactory::getDAO('TestDAO');
        $data_obj = $testdao->selectRecordsWithLimit(2);
        $this->assertEqual(count($data_obj), 2, 'should have limited to two records');
    }

    public function testSelectRecords() {
        $this->builders = self::buildData();
        $testdao = DAOFactory::getDAO('TestDAO');

        //this should return no records
        $data_array = $testdao->selectRecords(999);
        $this->assertIsA($data_array, "array", "array should be returned");
        $this->assertEqual(count($data_array), 0, "Empty array should be returned");

        // get all data with a test_id greater than 5
        $data_array = $testdao->selectRecords(5);
        $this->assertIsA($data_array, "array", "array should be returned");
        $this->assertEqual(count($data_array), 16, 'we have 16 records');
        for( $i = 0; $i < 16; $i++ ) {
            $data_obj = $data_array[$i];
            $this->assertIsA($data_obj, "TestData");
            $id = $i + 5;
            $this->assertEqual($data_obj->test_id, $id, "we have test_id $i");
        }
    }

    public function testSelectRecodsAsArray() {
        $this->builders = self::buildData();
        $testdao = DAOFactory::getDAO('TestDAO');

        //this should return no records
        $data_array = $testdao->selectRecordsAsArrays(999);
        $this->assertIsA($data_array, "array", "array should be returned");
        $this->assertEqual(count($data_array), 0, "Empty array should be returned");

        // get all data with a test_id greater than 8
        $data_array = $testdao->selectRecordsAsArrays(8);
        $this->assertIsA($data_array, "array", "array should be returned");
        $this->assertEqual(count($data_array), 13, 'we have 13 records');
        for( $i = 0; $i < 13; $i++ ) {
            $data_obj = $data_array[$i];
            $this->assertIsA($data_obj, "array");
            $id = $i + 8;
            $this->assertEqual($data_obj['test_id'], $id, "we have test_id $i");
        }
    }

    public function testDeleteData() {
        $this->builders = self::buildData();
        $testdao = DAOFactory::getDAO('TestDAO');

        // nothing deleted
        $cnt = $testdao->delete(9999);
        $this->assertEqual(0, $cnt, "deleted 0 records");

        // one record deleted
        $cnt = $testdao->delete(19);
        $this->assertEqual(1, $cnt, "deleted 1 record");

        // delete multiple test_users
        $cnt = $testdao->delete(5);
        $this->assertEqual(14, $cnt, "deleted 14 records");
    }

    public function testIsPattern() {
        $this->builders = self::buildData();
        $testdao = DAOFactory::getDAO('TestDAO');

        // nothing deleted
        $cnt = $testdao->isExisting(9999);
        $this->assertFalse($cnt);

        // one record deleted
        $cnt = $testdao->isExisting(19);
        $this->assertTrue($cnt);
    }

    public function testInstantiateDaoWithoutConfigFile() {
        $config = Config::getInstance();
        $config_array = $config->getValuesArray();
        $this->builders = self::buildData();
        try {
            $this->removeConfigFile();
            Config::destroyInstance();
            $cfg_values = array("table_prefix"=> $config_array['table_prefix'], "db_host"=>"localhost");
            $config = Config::getInstance($cfg_values);
            $test_dao = new TestMySQLDAO($cfg_values);
            $users = $test_dao->getUserCount(0, 'mary');
            $this->assertIsA($users, "array");
            $this->assertEqual(count($users), 2);
            $this->assertEqual($users[0]['user_name'], 'mary');
            $this->assertEqual($users[1]['user_name'], 'sweetmary');
        } catch (Exception $e) {
            // restore config file if something goes wrong
            $this->restoreConfigFile();
            throw $e;
        }
        $this->restoreConfigFile();
    }

    public function testGetConnectString() {
        $this->removeConfigFile();
        Config::destroyInstance();
        $cfg_values = array("db_host"=>"localhost");
        $config = Config::getInstance($cfg_values);
        $this->assertEqual(PDODAO::getConnectString($config), "mysql:dbname=;host=localhost");

        $this->removeConfigFile();
        Config::destroyInstance();
        $cfg_values = array("db_type" => "mysql", "db_host"=>"localhost", "db_name" => "isosceles");
        $config = Config::getInstance($cfg_values);
        $this->assertEqual(PDODAO::getConnectString($config), "mysql:dbname=isosceles;host=localhost");

        $this->removeConfigFile();
        Config::destroyInstance();
        $cfg_values = array("db_host"=>"localhost", "db_name" => "isosceles", "db_port" => "3306");
        $config = Config::getInstance($cfg_values);
        $this->assertEqual(PDODAO::getConnectString($config), "mysql:dbname=isosceles;host=localhost;port=3306");

        $this->removeConfigFile();
        Config::destroyInstance();
        $cfg_values = array("db_host"=>"localhost", "db_name" => "isosceles", "db_socket" => "/var/mysql");
        $config = Config::getInstance($cfg_values);
        $this->assertEqual(PDODAO::getConnectString($config),
        "mysql:dbname=isosceles;host=localhost;unix_socket=/var/mysql");
        $this->restoreConfigFile();
    }

    public function testCompareTimezoneOffsets() {
        $config = Config::getInstance();
        $config->setValue('timezone', 'Europe/London');
        $timezone = $config->getValue('timezone');
        $time = new DateTime("now", new DateTimeZone($timezone) );
        $tz_config = $time->format('P');

        //destroy the existing PDO connection which gets established in setUp to start with a clean slate
        TestMySQLDAO::destroyPDO();

        // this should return the same timezone offset as the config value
        $test_dao = new TestMySQLDAO();
        $tz_server = $test_dao->getTimezoneOffset();

        if ($this->isTimeZoneSupported()) {
            $this->assertEqual('Europe/London', $tz_server['tz_offset']);
        } else {
            $this->assertEqual($tz_config, $tz_server['tz_offset']);
        }
        Config::destroyInstance();
    }

    /*
* To fully test this, you need to run the test with the timezone tables both empty and populated, and during DST
* and outside of DST.
*
* Truncate the timezone tables.
*
* $ echo "TRUNCATE TABLE time_zone; TRUNCATE TABLE time_zone_name; TRUNCATE TABLE time_zone_transition;
* TRUNCATE TABLE time_zone_transition_type;" | sudo mysql mysql
* $ sudo /etc/init.d/mysql restart
* Stopping MySQL database server: mysqld.
* Starting MySQL database server: mysqld.
* Checking for tables which need an upgrade, are corrupt or were not closed cleanly..
*
* Tests should fail because we can't set the time_zone session variable correctly
*
* $ faketime '2011-11-01' php tests/TestOfPDODAO.php -t testCompareMySQLAndPHPTimezoneOffsets
* TestOfPDODAO.php
* 1) Equal expectation fails at character 6 with [1293865200] and [1293868800] at
* [/home/cwarden/git/ThinkUp/tests/TestOfPDODAO.php line 351]
* in testCompareMySQLAndPHPTimezoneOffsets
* in TestOfPDODAO
* FAILURES!!!
*
* Test cases run: 1/3, Passes: 1, Failures: 1, Exceptions: 0
* $ faketime '2011-01-01' php tests/TestOfPDODAO.php -t testCompareMySQLAndPHPTimezoneOffsets
* TestOfPDODAO.php
* 1) Equal expectation fails at character 6 with [1314864000] and [1314860400] at
* [/home/cwarden/git/ThinkUp/tests/TestOfPDODAO.php line 358]
* in testCompareMySQLAndPHPTimezoneOffsets
* in TestOfPDODAO
* FAILURES!!!
* Test cases run: 1/3, Passes: 1, Failures: 1, Exceptions: 0
*
* Populate the timezone tables
*
* $ mysql_tzinfo_to_sql /usr/share/zoneinfo | sudo mysql mysql
*
* Now the tests will succeed
*
* $ faketime '2011-11-01' php tests/TestOfPDODAO.php -t testCompareMySQLAndPHPTimezoneOffsets
* TestOfPDODAO.php
* OK
* Test cases run: 1/3, Passes: 2, Failures: 0, Exceptions: 0
* $ faketime '2011-01-01' php tests/TestOfPDODAO.php -t testCompareMySQLAndPHPTimezoneOffsets
* TestOfPDODAO.php
* OK
* Test cases run: 1/3, Passes: 2, Failures: 0, Exceptions: 0
*/
    public function testCompareMySQLAndPHPTimezoneOffsets() {
        if (!$this->isTimeZoneSupported()) {
            return;
        }
        // These tests will only be run if the time_zone tables are populated in MySQL.
        // See http://dev.mysql.com/doc/refman/5.1/en/mysql-tzinfo-to-sql.html
        $config = Config::getInstance();
        // set timezones the same for MySQL and PHP
        $config->setValue('timezone', 'America/Los_Angeles');
        date_default_timezone_set('America/Los_Angeles');
        $timezone = $config->getValue('timezone');

        TestMySQLDAO::destroyPDO();
        $testdao = DAOFactory::getDAO('TestDAO');

        // test time outside of daylight saving time
        $stmt = TestMySQLDAO::$PDO->query('SELECT UNIX_TIMESTAMP("2011-01-01 00:00:00") AS time');
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $mysql_time = $row['time'];
        $php_time = strtotime('2011-01-01 00:00:00');
        $this->assertEqual($mysql_time, $php_time);

        // test time during daylight saving time
        $stmt = TestMySQLDAO::$PDO->query('SELECT UNIX_TIMESTAMP("2011-09-01 00:00:00") AS time');
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $mysql_time = $row['time'];
        $php_time = strtotime('2011-09-01 00:00:00');
        $this->assertEqual($mysql_time, $php_time);
    }
}
Something went wrong with that request. Please try again.