xref: /PHP-8.2/ext/pdo/tests/pdo_test.inc (revision d114812f)
1<?php
2# PDO test framework utilities
3
4if (getenv('PDOTEST_DSN') === false) {
5    $common = '';
6    $append = false;
7    foreach(file(dirname($_SERVER['PHP_SELF']).'/common.phpt') as $line) {
8        if ($append) {
9            $common .= $line;
10        } elseif (trim($line) == '--REDIRECTTEST--') {
11            $append = true;
12        }
13    }
14    $conf = eval($common);
15    foreach($conf['ENV'] as $n=>$v) putenv("$n=$v");
16}
17
18class PDOTest {
19    // create an instance of the PDO driver, based on
20    // the current environment
21    static function factory($classname = 'PDO', $drop_test_tables = true) {
22        $dsn = getenv('PDOTEST_DSN');
23        $user = getenv('PDOTEST_USER');
24        $pass = getenv('PDOTEST_PASS');
25        $attr = getenv('PDOTEST_ATTR');
26        if (is_string($attr) && strlen($attr)) {
27            $attr = unserialize($attr);
28        } else {
29            $attr = null;
30        }
31
32        if ($user === false) $user = NULL;
33        if ($pass === false) $pass = NULL;
34
35        $db = new $classname($dsn, $user, $pass, $attr);
36
37        if (!$db) {
38            die("Could not create PDO object (DSN=$dsn, user=$user)\n");
39        }
40        // Ignore errors about non-existent tables
41        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
42
43        // clean up any crufty test tables we might have left behind
44        // on a previous run
45        static $test_tables = array(
46            'test',
47            'test2',
48            'classtypes'
49            );
50        if ($drop_test_tables) {
51            foreach ($test_tables as $table) {
52                $db->exec("DROP TABLE $table");
53            }
54        }
55
56        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
57        $db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
58        $db->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true);
59        return $db;
60    }
61
62    static function skip() {
63        try {
64            $db = PDOTest::factory();
65        } catch (PDOException $e) {
66            die("skip " . $e->getMessage());
67        }
68    }
69
70    static function test_factory($file) {
71        $config = self::get_config($file);
72        foreach ($config['ENV'] as $k => $v) {
73            putenv("$k=$v");
74        }
75        return self::factory();
76    }
77
78    static function get_config($file) {
79        $data = file_get_contents($file);
80        $data = preg_replace('/^.*--REDIRECTTEST--/s', '', $data);
81        $config = eval($data);
82
83        return $config;
84    }
85}
86?>
87