コード例 #1
0
 /**
  * @access public
  */
 protected function runTest()
 {
     $timer = new Benchmark_Timer();
     $timer->start();
     parent::runTest();
     $timer->stop();
     if ($this->fMaxRunningTime != 0 && $timer->timeElapsed() > $this->fMaxRunningTime) {
         PHPUnit_Framework_Assert::fail(sprintf('expected running time: <= %s but was: %s', $this->fMaxRunningTime, $timer->timeElapsed()));
     }
 }
コード例 #2
0
 /**
  * Cleanly end the current test
  */
 protected function endCurrentTest()
 {
     if (!$this->currentTest || !$this->currentSuite) {
         return;
     }
     // Time the current test
     $testDuration = microtime(true) - $this->startTestTime;
     $this->testSpeeds[$this->currentSuite['suite']->getName() . '.' . $this->currentTest['name']] = $testDuration;
     if ($this->hasTimer) {
         $this->timer->stop();
         $this->currentTest['timeElapsed'] = $this->timer->timeElapsed();
     }
     // Save and reset current state
     array_push($this->currentSuite['tests'], $this->currentTest);
     $this->currentTest = null;
 }
コード例 #3
0
ファイル: sparql_read.php プロジェクト: helenadeus/s3db.map
function sparql($I)
{
    ##Parse the query and build the dataset
    #global $timer;
    if (is_file(S3DB_SERVER_ROOT . '/pearlib/Benchmark/Timer.php')) {
        require_once S3DB_SERVER_ROOT . '/pearlib/Benchmark/Timer.php';
        $timer = new Benchmark_Timer();
        $timer->start();
    }
    extract($I);
    ##To use SPARQL with ARC library, we will need it to work with a remote endpoint. That means that we do not want to configure ARC as a datastore, but rather to retrieve the data from s3db deployments, convert it to RDF and then use ARC to run the query on it
    /* ARC2 static class inclusion */
    ini_set("include_path", S3DB_SERVER_ROOT . "/pearlib/arc" . PATH_SEPARATOR . ini_get("include_path"));
    include_once "ARC2.php";
    $s3ql['url'] = $in['url'] != '' ? $in['url'] : $default_uri;
    $s3ql['key'] = $in['key'] != '' ? $in['key'] : get_user_key($user_id, $db);
    $q = $in['query'];
    list($query, $triples, $prefixes) = parse_sparql_query($q, $s3ql);
    $bq .= "PREFIX " . implode("\n PREFIX ", $query['prefix']) . "\n ";
    $bq .= "SELECT " . $query['select'][0] . "\n ";
    $bq .= "FROM" . implode(" FROM ", $query['from']) . "\n ";
    $bq .= "WHERE " . $query['where'][0] . "\n ";
    preg_match_all('(\\?[A-Za-z0-9]+) ', $bq, $vars);
    if ($vars[0]) {
        $vars = array_unique($vars[0]);
        $sparql_vars = implode(" ", $vars);
    }
    if ($query['select'][0] != "" && $query['select'][0] != "*") {
        $outputCols = explode(" ", trim($query['select'][0]));
        $outputCols = array_filter($outputCols);
        $outputCols = array_intersect($vars, $outputCols);
    }
    $sparql = ereg_replace("FROM(.*)WHERE", "WHERE", $bq);
    #lets preprocess the order by which the must be queries must be performed to optimize speedness
    list($iterations, $scrambled) = iterationOrder($triples, $prefixes, true);
    ##$rdf_results will contain the totality of triples retrieved from s3db;
    ##Start a rdf-api model
    $iterations = array_values($iterations);
    $rdf = S3DB_URI_BASE . '/s3dbcore/model.n3';
    #base s3db rdf model
    $filename = md5($rdf);
    $file_place = $GLOBALS['uploads'] . '/';
    #$queryModel = rdf2php($rdf);
    #$data = $queryModel->sparqlQuery($sparql);
    #echo '<pre>';print_r($data);exit;
    if ($timer) {
        $timer->setMarker('Core model read into results');
    }
    $rdf_results = array();
    $performedQueries = array();
    $r = 0;
    foreach ($iterations as $it => $triples2query) {
        $S3QL = array();
        $S3QLfinal = array();
        foreach ($triples2query as $i => $tripleInd) {
            $tripleString = $tripleInd;
            list($subject, $predicate, $object) = explode(' ', trim($tripleString));
            $subject = ereg_replace('^<|>$', '', $subject);
            $predicate = ereg_replace('^<|>$', '', $predicate);
            $object = ereg_replace('^<|>$', '', $object);
            $triple = compact('subject', 'predicate', 'object');
            #sparql triple is used to calculate the values of the variables in the triple
            #$sparql_triple = $sparql_prefixes_default.' SELECT * WHERE { '.ltrim($tripleString).' . }';
            #now lets interpret the triple to explore the space of possible queries on S3QL
            $pack = compact('triple', 's3ql', 'user_id', 'db', 'prefixes', 'varType', 'discoveredData', 'it', 'varTypeWhere', 'collected_data', 'performedQueries');
            $sp = sparql_navigator($pack);
            extract($sp);
            # if($timer) $timer->setMarker('Built query '.$i);
            ##Remove queries that were already performed
            if ($S3QL[0]) {
                foreach ($S3QL as $s => $q) {
                    $S3QLfinal[] = $q;
                    $queried_elements[] = $element[$s];
                }
                $localQueries[$tripleString] = $localQueries[0];
                $remoteQueries[$tripleString] = $remoteQueries[0];
                $localQueries = array_filter($localQueries);
                $remoteQueries = array_filter($remoteQueries);
            }
        }
        $S3QL = $S3QLfinal;
        ##Remove repeated queries
        $S3QL = array_unique($S3QL);
        #if only the s3ql is requested, we can return it now
        if ($in['output'] == 'S3QL') {
            foreach ($localQueries as $sparqlVersion => $s3qlVersion) {
                $Q[]['S3QL'] = S3QLQuery($s3qlVersion);
            }
            foreach ($remoteQueries as $rq) {
                $Q[]['S3QL'] = $rq;
            }
            $root = 's3ql';
            #root is just the word that xml should parse as the root for each entry
            $data = $Q;
            $cols = array('S3QL');
            $format = $in['format'] == '' ? 'html' : $in['format'];
            $z = compact('data', 'cols', 'format', 'root');
            $out = outputFormat($z);
            return array(true, $out);
        }
        #If paralel library is activated, use it for the data. Otherwise use the custom version
        #$query_answers_file = 'sparql_query_ans'.rand(100,200);	$a=fopen($query_answers_file, 'a');
        if (!empty($S3QL)) {
            if (extension_loaded('curl') && $goparallel) {
                // Create cURL handlers
                if ($timer) {
                    $timer->setMarker('Starting queries from group ' . $it);
                }
                foreach ($S3QL as $k => $url) {
                    $qURL = $url;
                    $ch[$k] = curl_init();
                    // Set options
                    curl_setopt($ch[$k], CURLOPT_URL, $qURL . '&format=php');
                    curl_setopt($ch[$k], CURLOPT_RETURNTRANSFER, 1);
                }
                $mh = curl_multi_init();
                foreach ($S3QL as $k => $url) {
                    curl_multi_add_handle($mh, $ch[$k]);
                }
                $running = null;
                do {
                    curl_multi_exec($mh, $running);
                    if ($timer) {
                        $timer->setMarker('Query ' . $k . ' of group ' . $it . ' executed');
                    }
                } while ($running > 0);
                foreach ($S3QL as $k => $url) {
                    $answer[$k] = curl_multi_getcontent($ch[$k]);
                    if (!empty($answer[$k])) {
                        #@fwrite($a, $answer[$k]);
                        ##This is what takes the longest after the query, can it be replaced?
                        $ans = unserialize($answer[$k]);
                        $letter = $queried_elements[$r][0];
                        if (empty($ans)) {
                            ##is this query part is not optional, then the result will be null
                            ##TO BE DEVELOPED SOON
                        } else {
                            $rdf_results[$letter][] = $ans;
                        }
                        $r++;
                        ##Add the triples to already existing triples
                        #Line up the answer with the model
                        if ($timer) {
                            $timer->setMarker('Query ' . $it . '=>' . $k . ' converted to php ');
                        }
                    }
                }
                curl_multi_close($mh);
                ####Time count
                #$time_end = microtime(true);
                #$time = $time_end - $time_start;
                #echo "Query took ".$time." seconds\n";exit;
                ###
            } else {
                #Now solve the remaining triples with the constants found in this one
                if (is_array($localQueries) && !empty($localQueries)) {
                    foreach ($localQueries as $sparql_triple => $s3ql) {
                        $s3ql = array_filter(array_diff_key($s3ql, array('url' => '')));
                        $answer = localQ($s3ql);
                        if (!empty($answer)) {
                            $rdfanswer = rdf2php($answer);
                            #Line up the answer with the model
                            $queryModel->addModel($rdfanswer);
                            #Now perform the query on the small model to find a constant for the remaining queries
                            #list($data,$discovered, $discoveredData,$queryModel) = executeQuery($queryModel,$sparql_triple,$discovered,$format);
                        }
                    }
                }
                if (is_array($remoteQueries) && !empty($remoteQueries)) {
                    foreach ($remoteQueries as $remoteQuery) {
                        $answer = remoteQ($remoteQuery);
                        if (!empty($answer)) {
                            $rdfanswer = rdf2php($answer);
                            #Line up the answer with the model
                            $queryModel->addModel($rdfanswer);
                            #Now perform the query on the small model to find a constant for the remaining queries
                            #list($data,$discovered, $discoveredData,$queryModel) = executeQuery($queryModel,$sparql_triple,$discovered,$format);
                        }
                    }
                }
            }
        }
    }
    ##Get the data from the file
    ##Now, add the dictionary data
    if ($complete) {
        include_once S3DB_SERVER_ROOT . '/s3dbcore/dictionary.php';
        $s3qlN = compact('user_id', 'db');
        $s3qlN['from'] = 'link';
        $s3qlN['format'] = 'php';
        $links = query_user_dictionaries($s3qlN, $db, $user_id);
        $links = unserialize($links);
        $rdf_results['E'][0] = $links;
        $s3qlN = compact('user_id', 'db');
        $s3qlN['from'] = 'namespaces';
        $s3qlN['format'] = 'php';
        $ns = query_user_dictionaries($s3qlN, $db, $user_id);
        $ns = unserialize($ns);
        if ($timer) {
            $timer->setMarker('Dictionary links retrieved');
        }
    }
    ##Convert the result into an RDF file
    $data_triples = array();
    if (is_array($rdf_results)) {
        foreach ($rdf_results as $letter => $results2rdfize) {
            $dont_skip_core_name = false;
            $dont_skip_serialized = true;
            if (ereg('S', $letter)) {
                $dont_skip_serialized = false;
            }
            if (ereg('C|R|P', $letter)) {
                $dont_skip_core_name = true;
            }
            foreach ($results2rdfize as $k => $data) {
                $tmp_triples = rdf_encode($data, $letter, 'array', $s3ql['db'], $ns, $collected_data, $dont_skip_serialized, $dont_skip_core_name);
                if (is_array($tmp_triples)) {
                    $data_triples = array_merge($data_triples, $tmp_triples);
                }
            }
        }
    }
    if (!empty($data_triples)) {
        $tmp['ns'] = $prefixes;
        /*
        #this one for turtle
        $parser = ARC2::getComponent('TurtleParser', $a);
        $index = ARC2::getSimpleIndex($triples, false) ; # false -> non-flat version 
        $rdf_doc = $parser->toTurtle($index,$prefixes);
        */
        $parser = ARC2::getComponent('RDFXMLParser', $tmp);
        $index = ARC2::getSimpleIndex($data_triples, false);
        /* false -> non-flat version */
        $rdf_doc = $parser->toRDFXML($index, $prefixes);
        $filename = S3DB_SERVER_ROOT . '/tmp/' . random_string(15) . '.rdf';
        $rr = fopen($filename, 'a+');
        fwrite($rr, $rdf_doc);
        fclose($rr);
        if ($timer) {
            $timer->setMarker(count($data_triples) . ' triples written to file ' . $filename);
        }
        ##The better strategy would be to let the client cpu resolve the query; return the graphs with the rdf so that a sparql on the client can handle it
        if ($return_file_name) {
            if (filesize($filename) > 0) {
                return array(true, $filename);
            } else {
                return array(false);
            }
            exit;
        }
        if ($redirect) {
            ##And now use an external service ( I gave up with ARC) to parse the query
            $url2search = str_replace(S3DB_SERVER_ROOT, S3DB_URI_BASE, $filename);
            ##Giving up on ARC, surrender to sparql.com
            $remote_endpoint = "http://sparql.org/sparql?query=";
            $bq = ereg_replace("FROM <.*>", "FROM <" . $url2search . ">", $bq);
            $bq = urlencode($bq);
            $remote_endpoint .= $bq . '&default-graph-uri=&stylesheet=/xml-to-html.xsl';
            return array(true, $remote_endpoint);
        }
        #echo $filename;exit;
        #And finally perform the query on the model.
        $queryModel = rdf2php($filename);
        $format = $in['format'] != '' ? $in['format'] : 'html';
        unlink($filename);
        if ($timer) {
            $timer->setMarker('Data converted to a model the rdf-api can query');
        }
        if (eregi('^(sparql-xml|sparql-html)$', $format)) {
            switch ($format) {
                case 'sparql-xml':
                    $result = $queryModel->sparqlQuery($sparql, 'XML');
                    break;
                case 'sparql-html':
                    $result = $queryModel->sparqlQuery($sparql, 'HTML');
                    if ($_REQUEST['su3d']) {
                        $timer->stop();
                        $profiling = $timer->getProfiling();
                        echo "Query took " . $profiling[count($profiling) - 1]['total'] . ' sec';
                    }
                    break;
            }
            if ($result) {
                return array(true, $result);
            } else {
                return false;
            }
        } elseif ($format == 'html.form') {
            $form .= '
				<html>
				<head>

				</head><body>
				<form method="GET" action="sparql.php" id="sparqlform">
				<h5>Target Deployment(s)</h5>
				<input type="hidden" name="key" value="' . $s3ql['key'] . '"/>
				<input type="hidden" name="format" value="' . $_REQUEST['format'] . '"/>
				<input type = "text" id="url" size = "100%" value="' . $GLOBALS['url'] . '" name="url">
				<h5>SPARQL  <a href="http://www.w3.org/TR/rdf-sparql-query/" target="_blank">(help!!)</a></h5>
				<br />

				<textarea cols="100" id="sparql" rows="10" name = "query">' . stripslashes($sparql) . '</textarea><br />
				<input type="submit" value="SPARQL this!" id="submitsparql"></body>
				</form>
				';
            $form .= '<br />' . count($data) . " rows";
            $form .= '<br />Query took ' . (strtotime(date('His')) - $start) . ' sec';
            if (count($data) > 0) {
                return array(true, $form);
            } else {
                return array(false);
            }
        } else {
            #and output the result according to requested format
            $data = $queryModel->sparqlQuery($sparql);
            if ($timer) {
                $timer->setMarker('Query on SPARQL data executed by rdf-api.');
            }
            if (is_array($outputCols) && !empty($outputCols)) {
                ##only this one are to be shown in the final result
                $vars = $outputCols;
            }
            $cleanCols = array();
            foreach ($vars as $varname) {
                $cleanCols[] = ereg_replace('^\\?', '', $varname);
            }
            $outputData = array();
            if (is_array($data)) {
                foreach ($data as $s => $sparql_line) {
                    foreach ($sparql_line as $sparql_var => $sparql_var_value) {
                        if ($sparql_var_value->uri != '') {
                            $outputData[$s][ereg_replace('^\\?', '', $sparql_var)] = $sparql_var_value->uri;
                        } elseif ($sparql_var_value->label != '') {
                            $outputData[$s][ereg_replace('^\\?', '', $sparql_var)] = $sparql_var_value->label;
                        } else {
                            $outputData[$s][ereg_replace('^\\?', '', $sparql_var)] = "";
                        }
                    }
                }
            }
            if ($timer) {
                $timer->setMarker('Data converted in a format that fun outputformat can read');
            }
            #$timer ->display();
            #root is just the word that xml should parse as the root for each entry
            $root = 'sparql';
            if ($timer) {
                $timer->setMarker('All variables fitted into their places to represent in the final output');
            }
            $data = $outputData;
            $cols = $cleanCols;
            if ($_REQUEST['su3d']) {
                $timer->stop();
                $profiling = $timer->getProfiling();
                echo "Query took " . $profiling[count($profiling) - 1]['total'] . ' sec<br>';
            }
            $z = compact('data', 'cols', 'format', 'root');
            $out = outputFormat($z);
            echo $out;
            exit;
            if (count($data) > 0) {
                return array(true, $out);
            } else {
                return array(false);
            }
        }
    } else {
        return array(false);
    }
    #else {
    #$out= formatReturn($GLOBALS['error_codes']['no_results'], 'Your query did not return any results.', $format,'');
    #}
}
コード例 #4
0
ファイル: sample03.php プロジェクト: ngyuki/PHPPEG
$t->start();
// メモ化していないパーサ
$a = PEG::ref($a_ref);
$p = PEG::ref($p_ref);
$a_ref = PEG::choice(PEG::seq($p, '+', $a), PEG::seq($p, '-', $a), $p);
$p_ref = PEG::choice(PEG::seq('(', $a, ')'), '1');
$a->parse(PEG::context($str));
$t->setMarker('no memoize');
// メモ化しているパーサ
$a = PEG::ref($a_ref);
$p = PEG::ref($p_ref);
$a_ref = PEG::memo(PEG::choice(PEG::seq($p, '+', $a), PEG::seq($p, '-', $a), $p));
$p_ref = PEG::memo(PEG::choice(PEG::seq('(', $a, ')'), '1'));
$a->parse($c = PEG::context($str));
$t->setMarker('memoize');
$t->stop();
$t->display();
/* 結果
---------------------------------------------------------
marker       time index            ex time         perct   
---------------------------------------------------------
Start        1242400475.10093900   -                0.00%
---------------------------------------------------------
no memoize   1242400476.30805000   1.207111        99.74%
---------------------------------------------------------
memoize      1242400476.31115500   0.003105         0.26%
---------------------------------------------------------
Stop         1242400476.31117700   0.000022         0.00%
---------------------------------------------------------
total        -                     1.210238       100.00%
---------------------------------------------------------
コード例 #5
0
ファイル: bookstore-test.php プロジェクト: yasirgit/afids
    print "Attempting to delete publisher [id = {$morrow_id}]: ";
    PublisherPeer::doDelete($morrow_id);
    print boolTest(true);
    print "Attempting to delete publisher [id = {$penguin_id}]: ";
    PublisherPeer::doDelete($penguin_id);
    print boolTest(true);
    print "Attempting to delete publisher [id = {$vintage_id}]: ";
    $vintage->delete();
    print boolTest(true);
    // These have to be deleted manually also since we have onDelete
    // set to SETNULL in the foreign keys in book. Is this correct?
    print "Attempting to delete author [lastname = 'Rowling']: ";
    $rowling->delete();
    print boolTest(true);
    print "Attempting to delete publisher [lastname = 'Scholastic']: ";
    $scholastic->delete();
    print boolTest(true);
    print "Attempting to delete BookClubList 1: ";
    $blc1->delete();
    print boolTest(true);
    print "Attempting to delete BookClubList 2: ";
    $blc2->delete();
    print boolTest(true);
} catch (Exception $e) {
    die("Error deleting book: " . $e->__toString());
}
// Check again to make sure that tables are empty
// ----------------------------------------------
check_tables_empty();
$timer->stop();
print $timer->display();
コード例 #6
0
ファイル: function.inc.php プロジェクト: Blu2z/implsk
/**
 * Выполнение sql-запроса
 *
 * @param string запрос
 *
 * @global $nc_core
 *
 * @return bool выполнился запрос или нет
 */
function ExecuteSQLQuery($Query)
{
    global $nc_core;
    $SHOW_MYSQL_ERRORS = $nc_core->SHOW_MYSQL_ERRORS;
    $db = $nc_core->db;
    // таймер
    $nccttimer = new Benchmark_Timer();
    $Query = trim(stripslashes($Query));
    $db->query("DELETE FROM `SQLQueries` WHERE MD5(`SQL_text`) = '" . md5($Query) . "' ");
    // если в истории запросов больше 15, то нужно удалить
    if ($db->get_var("SELECT COUNT(`SQL_ID`) FROM `SQLQueries`") >= 15) {
        $db->query("DELETE FROM `SQLQueries` ORDER BY `SQL_ID` LIMIT 1");
    }
    $db->query("INSERT INTO SQLQueries (SQL_ID, SQL_text) VALUES ('', '" . $db->escape($Query) . "')");
    // скроем ошибки в случае неправильного запроса, чтобы вывести свое сообщение об ошибке
    $db->hide_errors();
    // выполение запроса
    $nccttimer->start();
    $res = $db->get_results(stripslashes($Query), ARRAY_A);
    $nccttimer->stop();
    // если показ ошибок MySQL включен, то включим его обратно
    if ($SHOW_MYSQL_ERRORS == 'on') {
        $db->show_errors();
    }
    if ($db->captured_errors) {
        echo "<br /><b>Query:</b> " . $db->captured_errors[0][query] . "<br><br><b>Error:</b> " . $db->captured_errors[0][error_str] . "<br /><br />";
        return false;
    }
    $count = $db->num_rows;
    // вывод таблицы с результатом, если нет ошибок
    if ($res && $count) {
        echo "<br /><b>" . htmlspecialchars(stripslashes($Query)) . "</b><br /><br />";
        $data = $res;
        echo "<table border='0' cellpadding='0' cellspacing='0' width='100%'>\n            <tr><td>\n              <table class='admin_table sql_table' width='100%'><tr>";
        //вывод полей
        while (list($key, $val) = each($res[0])) {
            echo "<td><font>" . $key . "</td>";
        }
        echo "</tr>";
        reset($res[0]);
        for ($i = 0; $i < $count; $i++) {
            echo "<tr>";
            while (list($key, $val) = each($res[$i])) {
                echo "<td><font> " . htmlspecialchars($res[$i][$key]) . "</td>";
            }
            echo "</tr>";
        }
        echo "</table></td></tr></table><br>";
        $res_num = $count ? $count : $db->rows_affected;
    } elseif (!$res) {
        if (preg_match("/^(insert|delete|update|replace)\\s+/i", $db->last_query)) {
            $res_num = $db->rows_affected;
        } else {
            $res_num = $db->num_rows;
        }
    }
    echo "<div>" . TOOLS_SQL_OK . "</div>";
    echo "<div>" . TOOLS_SQL_TOTROWS . ": " . $res_num . "</div>";
    echo "<div>" . TOOLS_SQL_BENCHMARK . ": " . $nccttimer->timeElapsed() . "</div>";
    echo "<br />";
}
コード例 #7
0
 /**
  * @param  PHPUnit2_Framework_Test $suite
  * @param  boolean                 $wait
  * @return PHPUnit2_Framework_TestResult
  * @access public
  */
 public function doRun(PHPUnit2_Framework_Test $suite, $wait = false)
 {
     $result = $this->createTestResult();
     if ($this->printer === null) {
         $this->printer = new PHPUnit2_TextUI_ResultPrinter();
     }
     $this->printer->write(PHPUnit2_Runner_Version::getVersionString() . "\n\n");
     $result->addListener($this->printer);
     if (class_exists('Benchmark_Timer')) {
         $timer = new Benchmark_Timer();
     }
     if (isset($timer)) {
         $timer->start();
     }
     $suite->run($result);
     if (isset($timer)) {
         $timer->stop();
         $timeElapsed = $timer->timeElapsed();
     } else {
         $timeElapsed = false;
     }
     $this->pause($wait);
     $this->printer->printResult($result, $timeElapsed);
     return $result;
 }
コード例 #8
0
ファイル: XML.php プロジェクト: ookwudili/chisimba
 /**
  * A test ended.
  *
  * @param  PHPUnit2_Framework_Test $test
  * @access public
  */
 public function endTest(PHPUnit2_Framework_Test $test)
 {
     $this->timer->stop();
     $time = $this->timer->timeElapsed();
     $this->currentTestCase->setAttribute('time', $time);
     $this->testSuiteTimes[$this->testSuiteLevel] += $time;
     $this->currentTestCase = NULL;
 }
コード例 #9
0
ファイル: TestRunner.php プロジェクト: ookwudili/chisimba
 /**
  * @param  PHPUnit2_Framework_Test $suite
  * @param  mixed                   $coverageDataFile
  * @param  mixed                   $coverageHTMLFile
  * @param  mixed                   $coverageTextFile
  * @param  mixed                   $testdoxHTMLFile
  * @param  mixed                   $testdoxTextFile
  * @param  mixed                   $xmlLogfile
  * @param  boolean                 $wait
  * @return PHPUnit2_Framework_TestResult
  * @access public
  */
 public function doRun(PHPUnit2_Framework_Test $suite, $coverageDataFile = FALSE, $coverageHTMLFile = FALSE, $coverageTextFile = FALSE, $testdoxHTMLFile = FALSE, $testdoxTextFile = FALSE, $xmlLogfile = FALSE, $wait = FALSE)
 {
     $result = $this->createTestResult();
     $timer = new Benchmark_Timer();
     if ($this->printer === NULL) {
         $this->printer = new PHPUnit2_TextUI_ResultPrinter();
     }
     $this->printer->write(PHPUnit2_Runner_Version::getVersionString() . "\n\n");
     $result->addListener($this->printer);
     if ($testdoxHTMLFile !== FALSE || $testdoxTextFile !== FALSE) {
         require_once 'PHPUnit2/Util/TestDox/ResultPrinter.php';
         if ($testdoxHTMLFile !== FALSE) {
             $result->addListener(PHPUnit2_Util_TestDox_ResultPrinter::factory('HTML', $testdoxHTMLFile));
         }
         if ($testdoxTextFile !== FALSE) {
             $result->addListener(PHPUnit2_Util_TestDox_ResultPrinter::factory('Text', $testdoxTextFile));
         }
     }
     if ($xmlLogfile !== FALSE) {
         require_once 'PHPUnit2/Util/Log/XML.php';
         $result->addListener(new PHPUnit2_Util_Log_XML($xmlLogfile));
     }
     if ($coverageDataFile !== FALSE || $coverageHTMLFile !== FALSE || $coverageTextFile !== FALSE) {
         $result->collectCodeCoverageInformation(TRUE);
     }
     $timer->start();
     $suite->run($result);
     $timer->stop();
     $timeElapsed = $timer->timeElapsed();
     $this->pause($wait);
     $this->printer->printResult($result, $timeElapsed);
     $this->handleCodeCoverageInformation($result, $coverageDataFile, $coverageHTMLFile, $coverageTextFile);
     return $result;
 }
コード例 #10
0
ファイル: nc_db.class.php プロジェクト: pzotov/cheetah
 /**
  * Perform mySQL query and try to determine result value
  *
  * @param string $query
  * @param string $output
  * @param string $index_field    if set, the resulting array will have the value
  *                               of the $index_field as a key
  *                               (use with caution if a get_row() call will follow!)
  * @return bool|int
  */
 public function query($query, $output = OBJECT, $index_field = null)
 {
     global $MODULE_VARS;
     // Keep track of the time the query took?
     $sql_time = is_array($MODULE_VARS['default']) && array_key_exists('NC_DEBUG_SQL_TIME', $MODULE_VARS['default']) && $MODULE_VARS['default']['NC_DEBUG_SQL_TIME'];
     // Keep track of from where the method was executed?
     $sql_func = is_array($MODULE_VARS['default']) && array_key_exists('NC_DEBUG_SQL_FUNC', $MODULE_VARS['default']) && $MODULE_VARS['default']['NC_DEBUG_SQL_FUNC'];
     if ($sql_time && !class_exists('Benchmark_Timer')) {
         require_once "Benchmark/Timer.php";
     }
     if ($this->benchmark || $sql_time) {
         $timer = new Benchmark_Timer();
         $timer->start();
     }
     // For reg expressions
     $query = trim($query);
     // Initialise return
     $return_val = 0;
     $this->is_error = 0;
     $func = '';
     $this->errno = 0;
     // Flush cached values..
     $this->flush();
     // Log how the function was called
     //        $this->func_call = "\$db->query(\"$query\")";
     // Keep track of the last query for debug..
     $this->last_query = $query;
     // Perform the query via std mysql_query function..
     $this->result = @mysql_query($query, $this->dbh);
     $this->num_queries++;
     $q = ['query' => $query];
     // таймер
     if ($this->benchmark || $sql_time) {
         $timer->stop();
         if ($this->benchmark) {
             $timer->display();
         }
         $sql_time = $timer->timeElapsed();
         $q['sql_time'] = $sql_time;
     }
     if ($sql_func) {
         $backtrace = debug_backtrace();
         $func = ($backtrace[2]['class'] ? $backtrace[2]['class'] . '::' : '') . $backtrace[2]['function'];
         $q['sql_func'] = $func;
     }
     $this->queries_arr[] = $q;
     // If there is an error then take note of it..
     if ($str = @mysql_error($this->dbh)) {
         $this->register_error($str);
         $this->is_error = 1;
         $this->show_errors ? trigger_error($str, E_USER_WARNING) : null;
         $this->errno = mysql_errno();
         if ($this->debug_all || $this->trace) {
             echo "<div style='border: 2pt solid red; margin: 10px; padding:10px; font-size:13px; color:black;'><br/>\n";
             echo "Query: <b>" . $query . "</b><br/>\n";
             echo "Error: <b>" . $str . "</b><br/>\n";
             echo "</div>\n";
         }
     }
     $this->debugMessage($this->num_queries . ". " . $query, $func, $sql_time, $this->is_error ? 'error' : 'ok');
     if ($this->is_error) {
         return false;
     }
     // Query was an insert, delete, update, replace
     if (preg_match("/^(insert|delete|update|replace)\\s+/i", $query)) {
         $this->rows_affected = @mysql_affected_rows($this->dbh);
         // Take note of the insert_id
         // NB: не нужно заменять на nc_preg_match(), поскольку запрос не обязательно
         // является корректной UTF строкой - в этом случае условие не будет выполнено!
         if (preg_match("/^(insert|replace)\\s+/i", $query)) {
             $this->insert_id = @mysql_insert_id($this->dbh);
         }
         // Return number of rows affected
         $return_val = $this->rows_affected;
     } else {
         // Take note of column info
         if ($this->fill_col_info) {
             $this->col_info = array();
             $i = 0;
             while ($i < @mysql_num_fields($this->result)) {
                 $this->col_info[$i] = @mysql_fetch_field($this->result);
                 $i++;
             }
         } else {
             $this->col_info = false;
         }
         // mysql_query returns TRUE for INSERT/UPDATE/DROP queries and FALSE on error
         if (!is_bool($this->result)) {
             // Store Query Results
             $this->result_output_type = $output;
             if ($output == ARRAY_N) {
                 $fetch_function = 'mysql_fetch_row';
             } elseif ($output == ARRAY_A) {
                 $fetch_function = 'mysql_fetch_assoc';
             } else {
                 $fetch_function = 'mysql_fetch_object';
             }
             // Store results as an objects within main array
             $num_rows = 0;
             while ($row = $fetch_function($this->result)) {
                 $key = $index_field !== null ? is_array($row) ? $row[$index_field] : $row->{$index_field} : $num_rows;
                 $this->last_result[$key] = $row;
                 $num_rows++;
             }
             mysql_free_result($this->result);
             // Log number of rows the query returned
             $this->num_rows = $num_rows;
         }
         // Return number of rows selected
         $return_val = $this->num_rows;
     }
     // If debug ALL queries
     $this->trace || $this->debug_all ? $this->debug() : null;
     if (1 || $this->debug_all) {
         preg_match("/(from\\s+\\w+)/si", $query, $regs);
         $from = preg_replace("/\\s+/s", " ", $regs[1]);
         $from = preg_replace("/from /i", "FROM ", $from);
         $this->groupped_queries[$from][$this->num_queries] = $query;
     }
     if ($this->benchmark && $GLOBALS["nccttimer"] instanceof Benchmark_Timer) {
         $GLOBALS["nccttimer"]->setMarker("QRY {$this->num_queries}<br />");
     }
     return $return_val;
 }
コード例 #11
0
ファイル: TestRunner.php プロジェクト: amjadtbssm/website
 /**
  * Runs a test suite.
  *
  * @param           PHPUnit_Framework_Test $suite
  * @param  optional boolean                $wait
  * @return PHPUnit_Framework_TestResult
  * @access public
  */
 public function doRun(PHPUnit_Framework_Test $suite, $wait = false)
 {
     printf("PHPUnit %s by Sebastian Bergmann.\n\n", PHPUnit_Framework_Version);
     $result = new PHPUnit_Framework_TestResult();
     $result->addListener($this->fPrinter);
     $timer = new Benchmark_Timer();
     $timer->start();
     $suite->run($result);
     $timer->stop();
     $this->pause($wait);
     $this->fPrinter->printResult($result, $timer->timeElapsed());
     return $result;
 }