function validate()
 {
     if (!($dom_sxe = dom_import_simplexml($this->_xml))) {
         return false;
     }
     $dom = new DOMDocument("1.0");
     $dom_sxe = $dom->importnode($dom_sxe, true);
     $dom_sxe = $dom->appendchild($dom_sxe);
     return $dom->relaxNGValidate();
 }
Example #2
0
/**
 * @package anno
 * This file is part of the Annotum theme for WordPress
 * Built on the Carrington theme framework <http://carringtontheme.com>
 *
 * Copyright 2008-2014 Crowd Favorite, Ltd. All rights reserved. <http://crowdfavorite.com>
 * Released under the GPL license
 * http://www.opensource.org/licenses/gpl-license.php
 */
function anno_validate($content, $schema)
{
    $response = array();
    $response['status'] = '';
    $doc = new DOMDocument();
    libxml_use_internal_errors(true);
    libxml_clear_errors();
    $doc->loadxml($content);
    if (!$doc->relaxNGValidate($schema)) {
        $response['status'] = 'error';
        $errors = libxml_get_errors();
        if (is_array($errors)) {
            foreach ($errors as $libxml_error) {
                $response['errors'][] = array('fullMessage' => sprintf(__('Error on line %d, column %d. %s', 'Error message for validation. %s referes to the error message', 'anno'), $libxml_error->line, $libxml_error->column, str_replace('\\n', '', $libxml_error->message)), 'line' => $libxml_error->line - 1, 'column' => $libxml_error->column, 'message' => str_replace('\\n', '', $libxml_error->message), 'level' => $libxml_error->level);
            }
        }
    } else {
        $response['status'] = 'success';
    }
    return $response;
}
    /**
     * @test
     */
    public function logsTestResultsInRealtimeIntoTheSpecifiedFileInTheJunitXmlFormat()
    {
        $this->loadClasses();
        $this->config->logsResultsInJUnitXMLInRealtime = true;
        $this->config->runnerClass = 'Stagehand_TestRunner_Runner_' . $this->framework . 'Runner_JUnitXMLTest_Mock' . $this->framework . 'Runner';
        $this->collector->collectTestCase('Stagehand_TestRunner_' . $this->framework . 'PassTest');
        $this->collector->collectTestCase('Stagehand_TestRunner_' . $this->framework . 'FailureTest');
        $this->collector->collectTestCase('Stagehand_TestRunner_' . $this->framework . 'ErrorTest');
        $this->runTests();
        $this->assertFileExists($this->config->junitXMLFile);
        $streamContents = $this->readAttribute($this->runner, 'streamContents');
        $this->assertEquals(22, count($streamContents));
        $this->assertEquals('<?xml version="1.0" encoding="UTF-8"?>
<testsuites>', $streamContents[0]);
        $this->assertEquals('<testsuite name="The test suite generated by Stagehand_TestRunner" tests="5">', $streamContents[1]);
        $this->assertRegExp('!^<testsuite name="Stagehand_TestRunner_' . $this->framework . 'PassTest" tests="3" file=".+">$!', $streamContents[2]);
        $this->assertRegExp('!^<testcase name="testPassWithAnAssertion" class="Stagehand_TestRunner_' . $this->framework . 'PassTest" file=".+" line="\\d+">$!', $streamContents[3]);
        $this->assertEquals('</testcase>', $streamContents[4]);
        $this->assertRegExp('!^<testcase name="testPassWithMultipleAssertions" class="Stagehand_TestRunner_' . $this->framework . 'PassTest" file=".+" line="\\d+">$!', $streamContents[5]);
        $this->assertEquals('</testcase>', $streamContents[6]);
        $this->assertRegExp('!^<testcase name="test日本語を使用できる" class="Stagehand_TestRunner_' . $this->framework . 'PassTest" file=".+" line="\\d+">$!', $streamContents[7]);
        $this->assertEquals('</testcase>', $streamContents[8]);
        $this->assertEquals('</testsuite>', $streamContents[9]);
        $this->assertEquals('</testsuite>', $streamContents[20]);
        $this->assertEquals('</testsuites>', $streamContents[21]);
        $junitXML = new DOMDocument();
        $junitXML->load($this->config->junitXMLFile);
        $this->assertTrue($junitXML->relaxNGValidate(dirname(__FILE__) . '/../../../../../data/pear.piece-framework.com/Stagehand_TestRunner/JUnitXMLStream.rng'));
        $parentTestsuite = $junitXML->childNodes->item(0)->childNodes->item(0);
        $this->assertTrue($parentTestsuite->hasChildNodes());
        $this->assertEquals(5, $parentTestsuite->getAttribute('tests'));
        $this->assertEquals(3, $parentTestsuite->childNodes->length);
        $childTestsuite = $parentTestsuite->childNodes->item(0);
        $this->assertTrue($childTestsuite->hasChildNodes());
        $this->assertEquals('Stagehand_TestRunner_' . $this->framework . 'PassTest', $childTestsuite->hasAttribute('name'));
        $this->assertTrue($childTestsuite->hasAttribute('file'));
        $class = new ReflectionClass('Stagehand_TestRunner_' . $this->framework . 'PassTest');
        $this->assertEquals($class->getFileName(), $childTestsuite->getAttribute('file'));
        $this->assertEquals(3, $childTestsuite->getAttribute('tests'));
        $this->assertEquals(3, $childTestsuite->childNodes->length);
        $testcase = $childTestsuite->childNodes->item(0);
        $this->assertFalse($testcase->hasChildNodes());
        $this->assertEquals('testPassWithAnAssertion', $testcase->hasAttribute('name'));
        $this->assertEquals('Stagehand_TestRunner_' . $this->framework . 'PassTest', $testcase->hasAttribute('class'));
        $this->assertEquals($class->getFileName(), $testcase->getAttribute('file'));
        $method = $class->getMethod('testPassWithAnAssertion');
        $this->assertEquals($method->getStartLine(), $testcase->getAttribute('line'));
        $testcase = $childTestsuite->childNodes->item(1);
        $this->assertFalse($testcase->hasChildNodes());
        $this->assertEquals('testPassWithMultipleAssertions', $testcase->hasAttribute('name'));
        $this->assertEquals('Stagehand_TestRunner_' . $this->framework . 'PassTest', $testcase->hasAttribute('class'));
        $this->assertEquals($class->getFileName(), $testcase->getAttribute('file'));
        $method = $class->getMethod('testPassWithMultipleAssertions');
        $this->assertEquals($method->getStartLine(), $testcase->getAttribute('line'));
        $testcase = $childTestsuite->childNodes->item(2);
        $this->assertFalse($testcase->hasChildNodes());
        $this->assertEquals('test日本語を使用できる', $testcase->hasAttribute('name'));
        $this->assertEquals('Stagehand_TestRunner_' . $this->framework . 'PassTest', $testcase->hasAttribute('class'));
        $this->assertEquals($class->getFileName(), $testcase->getAttribute('file'));
        $method = $class->getMethod('test日本語を使用できる');
        $this->assertEquals($method->getStartLine(), $testcase->getAttribute('line'));
        $childTestsuite = $parentTestsuite->childNodes->item(1);
        $this->assertTrue($childTestsuite->hasChildNodes());
        $this->assertEquals('Stagehand_TestRunner_' . $this->framework . 'FailureTest', $childTestsuite->hasAttribute('name'));
        $this->assertTrue($childTestsuite->hasAttribute('file'));
        $class = new ReflectionClass('Stagehand_TestRunner_' . $this->framework . 'FailureTest');
        $this->assertEquals($class->getFileName(), $childTestsuite->getAttribute('file'));
        $this->assertEquals(1, $childTestsuite->getAttribute('tests'));
        $this->assertEquals(1, $childTestsuite->childNodes->length);
        $testcase = $childTestsuite->childNodes->item(0);
        $this->assertTrue($testcase->hasChildNodes());
        $this->assertEquals('testIsFailure', $testcase->hasAttribute('name'));
        $this->assertEquals('Stagehand_TestRunner_' . $this->framework . 'FailureTest', $testcase->hasAttribute('class'));
        $this->assertEquals($class->getFileName(), $testcase->getAttribute('file'));
        $method = $class->getMethod('testIsFailure');
        $this->assertEquals($method->getStartLine(), $testcase->getAttribute('line'));
        $failure = $testcase->childNodes->item(0);
        $this->assertRegexp('/^This is an error message\\./', $failure->nodeValue);
        $childTestsuite = $parentTestsuite->childNodes->item(2);
        $this->assertTrue($childTestsuite->hasChildNodes());
        $this->assertEquals('Stagehand_TestRunner_' . $this->framework . 'ErrorTest', $childTestsuite->hasAttribute('name'));
        $this->assertTrue($childTestsuite->hasAttribute('file'));
        $class = new ReflectionClass('Stagehand_TestRunner_' . $this->framework . 'ErrorTest');
        $this->assertEquals($class->getFileName(), $childTestsuite->getAttribute('file'));
        $this->assertEquals(1, $childTestsuite->getAttribute('tests'));
        $this->assertEquals(1, $childTestsuite->childNodes->length);
        $testcase = $childTestsuite->childNodes->item(0);
        $this->assertTrue($testcase->hasChildNodes());
        $this->assertEquals('testIsError', $testcase->hasAttribute('name'));
        $this->assertEquals('Stagehand_TestRunner_' . $this->framework . 'ErrorTest', $testcase->hasAttribute('class'));
        $this->assertEquals($class->getFileName(), $testcase->getAttribute('file'));
        $method = $class->getMethod('testIsError');
        $this->assertEquals($method->getStartLine(), $testcase->getAttribute('line'));
        $error = $testcase->childNodes->item(0);
        $this->assertRegexp('/^Exception: This is an exception message\\./', $error->nodeValue);
    }
Example #4
0
 /**
  * return a list of all the certificates of the authN user, currently
  * in XML format.
  */
 public function processListCerts()
 {
     $list = $this->ca->getCertList();
     $domTree = new DOMDocument('1.0', 'utf-8');
     $certificates = $domTree->createElement("certificates");
     if (count($list) > 0) {
         foreach ($list as $row) {
             $certificate = $domTree->createElement("certificate");
             $id = $domTree->createElement("id");
             $certID = $row['order_number'];
             $idContent = $domTree->createTextNode("/api/certificates/{$certID}");
             $id->appendChild($idContent);
             $certificate->appendChild($id);
             $status = $domTree->createElement("status");
             $statusContent = $domTree->createTextNode($row['status']);
             $status->appendChild($statusContent);
             $certificate->appendChild($status);
             $beginDate = $domTree->createElement("beginDate");
             /* format the beginDate nicely */
             $timezone = new DateTimeZone($this->person->getTimezone());
             $dt = new DateTime("@" . $row['valid_from']);
             $dt->setTimezone($timezone);
             $valid_from = $dt->format('Y-m-d H:i:s T');
             $beginDateContent = $domTree->createTextNode($valid_from);
             $beginDate->appendChild($beginDateContent);
             $certificate->appendChild($beginDate);
             $endDate = $domTree->createElement("endDate");
             $endDateContent = $domTree->createTextNode($row['valid_untill']);
             $endDate->appendChild($endDateContent);
             $certificate->appendChild($endDate);
             $certificates->appendChild($certificate);
         }
     }
     $domTree->appendChild($certificates);
     if ($domTree->relaxNGValidate("schema/certlist.rng") === FALSE) {
         $msg = "The XML-response the portal built appears to be non-conformant to its schema!\n";
         $this->errorInternal($msg);
     }
     $xmlString = $domTree->saveXML();
     $xmlHash = hash("sha256", $xmlString);
     header("ETag: \"{$xmlHash}\"");
     echo $xmlString;
     exit(0);
 }
 /**
  * @param string $testingClass
  * @test
  * @dataProvider provideDataForReportsOnlyTheFirstFailureInASingleTestToJunitXml
  * @link http://redmine.piece-framework.com/issues/219
  * @since Method available since Release 2.14.0
  */
 public function reportsOnlyTheFirstFailureInASingleTestToJunitXml($testingClass)
 {
     $this->collector->collectTestCase($testingClass);
     $this->runTests();
     $junitXML = new DOMDocument();
     $junitXML->load($this->config->junitXMLFile);
     $this->assertTrue($junitXML->relaxNGValidate(dirname(__FILE__) . '/../../../../data/pear.piece-framework.com/Stagehand_TestRunner/JUnitXMLDOM.rng'));
     $this->assertTestCaseCount(1);
     $this->assertTestCaseExists('isFailure', $testingClass);
     $this->assertTestCaseAssertionCount(1, 'isFailure', $testingClass);
     $this->assertTestCaseFailed('isFailure', $testingClass);
     $this->assertTestCaseFailureMessageEquals('/The First Failure/', 'isFailure', $testingClass);
 }
 /**
  * Performs validation
  *
  * @param string $file
  * @return void
  */
 protected function lint($file)
 {
     if (file_exists($file)) {
         if (is_readable($file)) {
             $dom = new DOMDocument();
             if ($dom->load($file) === false) {
                 $error = libxml_get_last_error();
                 $this->logError($file . ' is not well-formed (See messages above)');
             } else {
                 if (isset($this->schema)) {
                     if ($this->useRNG) {
                         if ($dom->relaxNGValidate($this->schema->getPath())) {
                             $this->log($file . ' validated with RNG grammar', Project::MSG_INFO);
                         } else {
                             $this->logError($file . ' fails to validate (See messages above)');
                         }
                     } else {
                         if ($dom->schemaValidate($this->schema->getPath())) {
                             $this->log($file . ' validated with schema', Project::MSG_INFO);
                         } else {
                             $this->logError($file . ' fails to validate (See messages above)');
                         }
                     }
                 } else {
                     $this->log($file . ' is well-formed (not validated due to missing schema specification)', Project::MSG_INFO);
                 }
             }
         } else {
             $this->logError('Permission denied to read file: ' . $file);
         }
     } else {
         $this->logError('File not found: ' . $file);
     }
 }
Example #7
0
 public function relaxNGValidate()
 {
     $dir = self::getSchemaDir();
     $path = $dir . '/' . $this->relax;
     return $this->model->relaxNGValidate($path);
 }
Example #8
0
 /**
  * First, creates a new Tracker Object by importing its structure from an XML file,
  * then, imports it into the Database, before verifying the consistency
  *
  * @param string         $xmlFile        the location of the imported file
  * @param int            $groupId        the Id of the project to create the tracker
  * @param string         $name           the name of the tracker (label)
  * @param string         $description    the description of the tracker
  * @param string         $itemname       the short name of the tracker
  * @param TrackerManager $trackermanager an instance of TrackerManager
  *
  * @return the new Tracker, or null if error
  */
 public function createFromXML($xmlFile, $groupId, $name, $description, $itemname, $trackermanager)
 {
     $tracker = null;
     if ($this->validMandatoryInfoOnCreate($name, $description, $itemname, $groupId)) {
         // XML validation before creating a new tracker
         $dom = new DOMDocument();
         $dom->load($xmlFile);
         $rng = realpath(dirname(__FILE__) . '/../../www/resources/tracker.rng');
         if (!@$dom->relaxNGValidate($rng)) {
             //hide warning since we will extract the errors below
             //try to be more verbose for the end user (RelaxNG notices are hidden)
             $hp = Codendi_HTMLPurifier::instance();
             $indent = $GLOBALS['codendi_utils_prefix'] . '/xml/indent.xsl';
             $jing = $GLOBALS['codendi_utils_prefix'] . '/xml/jing.jar';
             $temp = tempnam($GLOBALS['tmp_dir'], 'xml');
             $cmd_indent = "xsltproc -o {$temp} {$indent} {$xmlFile}";
             `{$cmd_indent}`;
             $output = array();
             $cmd_valid = "java -jar {$jing} {$rng} {$temp}";
             exec($cmd_valid, $output);
             $errors = array();
             if ($trackermanager) {
                 $project = ProjectManager::instance()->getProject($groupId);
                 $breadcrumbs = array(array('title' => 'Create a new tracker', 'url' => TRACKER_BASE_URL . '/?group_id=' . $project->group_id . '&amp;func=create'));
                 $toolbar = array();
                 $trackermanager->displayHeader($project, 'Trackers', $breadcrumbs, $toolbar);
                 //var_dump($cmd_indent, $cmd_valid);
                 echo '<h2>XML file doesnt have correct format</h2>';
                 foreach ($output as $o) {
                     $matches = array();
                     preg_match('/:(\\d+):(\\d+):([^:]+):(.*)/', $o, $matches);
                     //1 line
                     //2 column
                     //3 type
                     //4 message
                     $errors[$matches[1]][$matches[2]][] = array(trim($matches[3]) => trim($matches[4]));
                     echo '<a href="#line_' . $matches[1] . '">' . $matches[3] . ': ' . $matches[4] . '</a><br />';
                 }
                 $clear = $GLOBALS['HTML']->getimage('clear.png', array('width' => 24, 'height' => 1));
                 $icons = array('error' => $GLOBALS['HTML']->getimage('ic/error.png', array('style' => 'vertical-align:middle')));
                 $styles = array('error' => 'color:red; font-weight:bold;');
                 echo '<pre>';
                 foreach (file($temp) as $number => $line) {
                     echo '<div id="line_' . ($number + 1) . '">';
                     echo '<span style="color:gray;">' . sprintf('%4d', $number + 1) . '</span>' . $clear . $hp->purify($line, CODENDI_PURIFIER_CONVERT_HTML);
                     if (isset($errors[$number + 1])) {
                         foreach ($errors[$number + 1] as $c => $e) {
                             echo '<div>' . sprintf('%3s', '') . $clear . sprintf('%' . ($c - 1) . 's', '') . '<span style="color:blue; font-weight:bold;">^</span></div>';
                             foreach ($e as $error) {
                                 foreach ($error as $type => $message) {
                                     $style = isset($styles['error']) ? $styles['error'] : '';
                                     echo '<div style="' . $style . '">';
                                     if (isset($icons[$type])) {
                                         echo $icons[$type];
                                     } else {
                                         echo $clear;
                                     }
                                     echo sprintf('%3s', '') . sprintf('%' . ($c - 1) . 's', '') . $message;
                                     echo '</div>';
                                 }
                             }
                         }
                     }
                     echo '</div>';
                 }
                 echo '</pre>';
                 unlink($temp);
                 $trackermanager->displayFooter($project);
                 exit;
             } else {
                 unlink($temp);
                 echo PHP_EOL;
                 echo implode(PHP_EOL, $output);
                 echo PHP_EOL;
             }
         } else {
             //create the tracker as a SimpleXMLElement
             $trackerXML = simplexml_load_file($xmlFile);
             $tracker = $this->getInstanceFromXML($trackerXML, $groupId, $name, $description, $itemname);
             //Testing consistency of the imported tracker before updating database
             if ($tracker->testImport()) {
                 if ($tracker_id = $this->saveObject($tracker)) {
                     $tracker->setId($tracker_id);
                 } else {
                     $GLOBALS['Response']->addFeedback('error', $GLOBALS['Language']->getText('plugin_tracker_admin', 'error_during_creation'));
                     $tracker = null;
                 }
             } else {
                 $GLOBALS['Response']->addFeedback('error', 'XML file cannot be imported');
                 $tracker = null;
             }
         }
     }
     return $tracker;
 }
 /**
  * @copydoc TypeDescription::checkType()
  */
 function checkType(&$object)
 {
     // We only accept DOMDocument objects and source strings.
     if (!is_a($object, 'DOMDocument') && !is_string($object)) {
         return false;
     }
     // No validation...
     if ($this->_validationStrategy == XML_TYPE_DESCRIPTION_VALIDATE_NONE) {
         return true;
     }
     // Validation - requires DOMDocument
     if (is_string($object)) {
         $xmlDom = new DOMDocument();
         $xmlDom->loadXML($object);
     } else {
         $xmlDom =& $object;
     }
     switch ($this->_validationStrategy) {
         // We have to suppress validation errors, otherwise the script
         // will stop when validation errors occur.
         case XML_TYPE_DESCRIPTION_VALIDATE_DTD:
             if (!$xmlDom->validate()) {
                 return false;
             }
             break;
         case XML_TYPE_DESCRIPTION_VALIDATE_SCHEMA:
             if (!$xmlDom->schemaValidate($this->_validationSource)) {
                 return false;
             }
             break;
         case XML_TYPE_DESCRIPTION_VALIDATE_RELAX_NG:
             if (!$xmlDom->relaxNGValidate($this->_validationSource)) {
                 return false;
             }
             break;
         default:
             assert(false);
     }
     return true;
 }
 /**
  * @test
  */
 public function treatsDataProviderInRealtime()
 {
     $this->config->logsResultsInJUnitXMLInRealtime = true;
     $this->collector->collectTestCase('Stagehand_TestRunner_PHPUnitDataProviderTest');
     $this->runTests();
     $this->assertFileExists($this->config->junitXMLFile);
     $junitXML = new DOMDocument();
     $junitXML->load($this->config->junitXMLFile);
     $this->assertTrue($junitXML->relaxNGValidate(dirname(__FILE__) . '/../../../../../data/pear.piece-framework.com/Stagehand_TestRunner/JUnitXMLStream.rng'));
     $parentTestsuite = $junitXML->childNodes->item(0)->childNodes->item(0);
     $this->assertTrue($parentTestsuite->hasChildNodes());
     $this->assertEquals(4, $parentTestsuite->getAttribute('tests'));
     $this->assertEquals(1, $parentTestsuite->childNodes->length);
     $childTestsuite = $parentTestsuite->childNodes->item(0);
     $this->assertTrue($childTestsuite->hasChildNodes());
     $this->assertEquals('Stagehand_TestRunner_PHPUnitDataProviderTest', $childTestsuite->getAttribute('name'));
     $class = new ReflectionClass('Stagehand_TestRunner_PHPUnitDataProviderTest');
     $this->assertEquals($class->getFileName(), $childTestsuite->getAttribute('file'));
     $this->assertEquals(4, $childTestsuite->getAttribute('tests'));
     $this->assertEquals(1, $childTestsuite->childNodes->length);
     $grandChildTestsuite = $childTestsuite->childNodes->item(0);
     $this->assertTrue($grandChildTestsuite->hasChildNodes());
     $this->assertEquals('passWithDataProvider', $grandChildTestsuite->getAttribute('name'));
     $class = new ReflectionClass('Stagehand_TestRunner_PHPUnitDataProviderTest');
     $this->assertEquals($class->getFileName(), $grandChildTestsuite->getAttribute('file'));
     $this->assertEquals(4, $grandChildTestsuite->getAttribute('tests'));
     $this->assertEquals(4, $grandChildTestsuite->childNodes->length);
     $testcase = $grandChildTestsuite->childNodes->item(0);
     $this->assertFalse($testcase->hasChildNodes());
     $this->assertEquals('passWithDataProvider with data set #0', $testcase->getAttribute('name'));
     $this->assertEquals('Stagehand_TestRunner_PHPUnitDataProviderTest', $testcase->getAttribute('class'));
     $this->assertEquals($class->getFileName(), $testcase->getAttribute('file'));
     $method = $class->getMethod('passWithDataProvider');
     $this->assertEquals($method->getStartLine(), $testcase->getAttribute('line'));
     $testcase = $grandChildTestsuite->childNodes->item(1);
     $this->assertFalse($testcase->hasChildNodes());
     $this->assertEquals('passWithDataProvider with data set #1', $testcase->getAttribute('name'));
     $this->assertEquals('Stagehand_TestRunner_PHPUnitDataProviderTest', $testcase->getAttribute('class'));
     $this->assertEquals($class->getFileName(), $testcase->getAttribute('file'));
     $method = $class->getMethod('passWithDataProvider');
     $this->assertEquals($method->getStartLine(), $testcase->getAttribute('line'));
     $testcase = $grandChildTestsuite->childNodes->item(2);
     $this->assertFalse($testcase->hasChildNodes());
     $this->assertEquals('passWithDataProvider with data set #2', $testcase->getAttribute('name'));
     $this->assertEquals('Stagehand_TestRunner_PHPUnitDataProviderTest', $testcase->getAttribute('class'));
     $this->assertEquals($class->getFileName(), $testcase->getAttribute('file'));
     $method = $class->getMethod('passWithDataProvider');
     $this->assertEquals($method->getStartLine(), $testcase->getAttribute('line'));
     $testcase = $grandChildTestsuite->childNodes->item(3);
     $this->assertTrue($testcase->hasChildNodes());
     $this->assertEquals('passWithDataProvider with data set #3', $testcase->getAttribute('name'));
     $this->assertEquals('Stagehand_TestRunner_PHPUnitDataProviderTest', $testcase->getAttribute('class'));
     $this->assertEquals($class->getFileName(), $testcase->getAttribute('file'));
     $method = $class->getMethod('passWithDataProvider');
     $this->assertEquals($method->getStartLine(), $testcase->getAttribute('line'));
     $failure = $testcase->childNodes->item(0);
     $this->assertEquals('PHPUnit_Framework_ExpectationFailedException', $failure->getAttribute('type'));
     $this->assertRegexp('/^Stagehand_TestRunner_PHPUnitDataProviderTest::passWithDataProvider with data set #3/', $failure->nodeValue);
 }
 /**
  * @test
  * @link http://redmine.piece-framework.com/issues/222
  * @since Method available since Release 2.14.0
  */
 public function supportsWebPageTesting()
 {
     if (!fsockopen('www.example.com', 80, $errno, $errstr, 1)) {
         $this->markTestSkipped('Cannot connect to http://www.example.com.');
     }
     $testClass = 'Stagehand_TestRunner_' . $this->framework . 'WebPageTest';
     $this->collector->collectTestCase($testClass);
     $this->runTests();
     $junitXML = new DOMDocument();
     $junitXML->load($this->config->junitXMLFile);
     $this->assertTrue($junitXML->relaxNGValidate(dirname(__FILE__) . '/../../../../data/pear.piece-framework.com/Stagehand_TestRunner/JUnitXMLDOM.rng'));
     $this->assertTestCaseCount(1);
     $this->assertTestCaseExists('testIsPass', $testClass);
 }
Example #12
0
 private static function ParseModuleXML($dir, $xml)
 {
     $contents = array();
     $dom = new DOMDocument();
     $dom->load(realpath("{$dir}/{$xml}"));
     $dom->normalizeDocument();
     $src = realpath($_SERVER['DOCUMENT_ROOT'] . "/_private/xmldef/" . self::$rng_file);
     if ($dom->relaxNGValidate($src)) {
         $name_node = $dom->getElementsByTagName("name")->item(0);
         $contents['name'] = $name_node->nodeValue;
         $contents['version'] = $name_node->hasAttribute("version") ? $name_node->getAttributeNode("version")->nodeValue : null;
         unset($name_node);
         $contents['dirname'] = $dom->getElementsByTagName("dirname")->item(0)->nodeValue;
         $contents['description'] = $dom->getElementsByTagName("description")->item(0)->nodeValue;
         $files_node = $dom->getElementsByTagName("files")->item(0);
         $items = array();
         foreach ($files_node->childNodes as $node) {
             if ($node->nodeName == "item") {
                 $items[] = array($node->nodeValue, $node->getAttributeNode("type")->nodeValue);
             }
         }
         $contents['items'] = $items;
         unset($files_node, $items, $dom);
         return $contents;
     } else {
         return false;
     }
 }
 /**
  * @test
  * @dataProvider dataForMultipleFailures
  *
  * @param string $testClass
  * @param string $failingMethod
  *
  * @link http://redmine.piece-framework.com/issues/219
  */
 public function reportsOnlyTheFirstFailureInASingleTestToJunitXml($testClass, $failingMethod)
 {
     $collector = $this->createCollector();
     $collector->collectTestCase($testClass);
     $this->runTests();
     $junitXML = new \DOMDocument();
     $junitXML->load($this->junitXMLFile);
     $this->assertTrue($junitXML->relaxNGValidate(__DIR__ . '/../../src/Resources/config/schema/junit-xml-dom-2.10.0.rng'));
     $this->assertTestCaseCount(1);
     $this->assertTestCaseExists($this->getTestMethodName($failingMethod), $testClass);
     $this->assertTestCaseAssertionCount(1, $this->getTestMethodName($failingMethod), $testClass);
     $this->assertTestCaseFailed($this->getTestMethodName($failingMethod), $testClass);
     $this->assertTestCaseFailureMessageEquals('/The First Failure/', $this->getTestMethodName($failingMethod), $testClass);
 }
 /**
  * Handle uploaded data, overwriting existing data
  */
 public function upload()
 {
     $this->sessionCheck();
     // Another session is either queued or writing — upload data won't be valid,
     // so client should wait and return to /updated with 'upload' flag
     Zotero_DB::beginTransaction();
     if (Zotero_Sync::userIsReadLocked($this->userID) || Zotero_Sync::userIsWriteLocked($this->userID)) {
         Zotero_DB::commit();
         $locked = $this->responseXML->addChild('locked');
         $locked['wait'] = $this->getWaitTime($this->sessionID);
         $this->end();
     }
     Zotero_DB::commit();
     $this->clearWaitTime($this->sessionID);
     if (empty($_REQUEST['updateKey'])) {
         $this->error(400, 'INVALID_UPLOAD_DATA', 'Update key not provided');
     }
     if ($_REQUEST['updateKey'] != Zotero_Users::getUpdateKey($this->userID)) {
         $this->e409("Server data has changed since last retrieval");
     }
     // TODO: change to POST
     if (empty($_REQUEST['data'])) {
         $this->error(400, 'MISSING_UPLOAD_DATA', 'Uploaded data not provided');
     }
     $xmldata =& $_REQUEST['data'];
     $doc = new DOMDocument();
     $doc->loadXML($xmldata);
     function relaxNGErrorHandler($errno, $errstr)
     {
         //Z_Core::logError($errstr);
     }
     set_error_handler('relaxNGErrorHandler');
     set_time_limit(60);
     if (!$doc->relaxNGValidate(Z_ENV_MODEL_PATH . 'relax-ng/upload.rng')) {
         $id = substr(md5(uniqid(rand(), true)), 0, 10);
         $str = date("D M j G:i:s T Y") . "\n";
         $str .= "IP address: " . $_SERVER['REMOTE_ADDR'] . "\n";
         if (isset($_SERVER['HTTP_X_ZOTERO_VERSION'])) {
             $str .= "Version: " . $_SERVER['HTTP_X_ZOTERO_VERSION'] . "\n";
         }
         $str .= "Error: RELAX NG validation failed\n\n";
         $str .= $xmldata;
         file_put_contents(Z_CONFIG::$SYNC_ERROR_PATH . $id, $str);
         $this->error(500, 'INVALID_UPLOAD_DATA', "Uploaded data not well-formed (Report ID: {$id})");
     }
     restore_error_handler();
     try {
         $xml = simplexml_import_dom($doc);
         $queue = true;
         if (Z_ENV_TESTING_SITE && !empty($_GET['noqueue'])) {
             $queue = false;
         }
         if ($queue) {
             $affectedLibraries = Zotero_Sync::parseAffectedLibraries($xmldata);
             // Relations-only uploads don't have affected libraries
             if (!$affectedLibraries) {
                 $affectedLibraries = array(Zotero_Users::getLibraryIDFromUserID($this->userID));
             }
             Zotero_Sync::queueUpload($this->userID, $this->sessionID, $xmldata, $affectedLibraries);
             try {
                 Zotero_Processors::notifyProcessors('upload');
                 Zotero_Processors::notifyProcessors('error');
                 usleep(750000);
             } catch (Exception $e) {
                 Z_Core::logError($e);
             }
             // Give processor a chance to finish while we're still here
             $this->uploadstatus();
         } else {
             set_time_limit(210);
             $timestamp = Zotero_Sync::processUpload($this->userID, $xml);
             $this->responseXML['timestamp'] = $timestamp;
             $this->responseXML->addChild('uploaded');
             Zotero_Processors::notifyProcessors('index');
             $this->end();
         }
     } catch (Exception $e) {
         $this->handleUploadError($e, $xmldata);
     }
 }
Example #15
0
 public function processAttributeRequest()
 {
     $domTree = new DOMDocument('1.0', 'utf-8');
     $userNode = $domTree->createElement("user");
     $uidNode = $domTree->createElement("uid");
     $uidContent = $domTree->createTextNode($this->person->getEPPN());
     $uidNode->appendChild($uidContent);
     $userNode->appendChild($uidNode);
     $nameNode = $domTree->createElement("name");
     $nameContent = $domTree->createTextNode($this->person->getName());
     $nameNode->appendChild($nameContent);
     $userNode->appendChild($nameNode);
     $orgDNNode = $domTree->createElement("orgDN");
     $orgDNContent = $domTree->createTextNode($this->person->getSubscriber()->getOrgName());
     $orgDNNode->appendChild($orgDNContent);
     $userNode->appendChild($orgDNNode);
     $orgIDNode = $domTree->createElement("orgID");
     $orgIDContent = $domTree->createTextNode($this->person->getSubscriber()->getIdPName());
     $orgIDNode->appendChild($orgIDContent);
     $userNode->appendChild($orgIDNode);
     $countryNode = $domTree->createElement("country");
     $countryContent = $domTree->createTextNode($this->person->getCountry());
     $countryNode->appendChild($countryContent);
     $userNode->appendChild($countryNode);
     $nrenNode = $domTree->createElement("nren");
     $nrenContent = $domTree->createTextNode($this->person->getNREN());
     $nrenNode->appendChild($nrenContent);
     $userNode->appendChild($nrenNode);
     $emailsNode = $domTree->createElement("emails");
     $mailList = explode(",", $this->person->getEmail());
     foreach ($mailList as $mail) {
         $emailNode = $domTree->createElement("email");
         $emailNodeContent = $domTree->createTextNode(trim($mail));
         $emailNode->appendChild($emailNodeContent);
         $emailsNode->appendChild($emailNode);
     }
     $userNode->appendChild($emailsNode);
     $enttlsNode = $domTree->createElement("entitlements");
     $enttlList = $this->person->getEntitlement(FALSE);
     foreach ($enttlList as $enttl) {
         $enttlNode = $domTree->createElement("entitlement");
         $enttlNodeContent = $domTree->createTextNode($enttl);
         $enttlNode->appendChild($enttlNodeContent);
         $enttlsNode->appendChild($enttlNode);
     }
     $userNode->appendChild($enttlsNode);
     $domTree->appendChild($userNode);
     if ($domTree->relaxNGValidate("schema/userInfo.rng") === FALSE) {
         $msg = "The XML-response the portal built appears to be non-conformant to its schema!\n";
         $this->errorInternal($msg);
     }
     $xmlString = $domTree->saveXML();
     $xmlHash = hash("sha256", $xmlString);
     header("ETag: \"{$xmlHash}\"");
     echo $xmlString;
     exit(0);
 }
 /**
  * Validates the response.
  *
  * @param mixed $checkDTD Either true to validate against the response DTD or
  *                        provide the path to a *.xsd, *.rng or *.rnc schema
  *
  * @return sfTestFunctionalBase|sfTester
  *
  * @throws LogicException If the response is neither XML nor (X)HTML
  */
 public function isValid($checkDTD = false)
 {
     if (preg_match('/(x|ht)ml/i', $this->response->getContentType())) {
         $revert = libxml_use_internal_errors(true);
         $dom = new DOMDocument('1.0', $this->response->getCharset());
         $content = $this->response->getContent();
         if (true === $checkDTD) {
             $cache = sfConfig::get('sf_cache_dir') . '/sf_tester_response/w3';
             $local = 'file://' . str_replace(DIRECTORY_SEPARATOR, '/', $cache);
             if (!file_exists($cache . '/TR/xhtml11/DTD/xhtml11.dtd')) {
                 $filesystem = new sfFilesystem();
                 $finder = sfFinder::type('any')->discard('.sf');
                 $filesystem->mirror(dirname(__FILE__) . '/w3', $cache, $finder);
                 $finder = sfFinder::type('file');
                 $filesystem->replaceTokens($finder->in($cache), '##', '##', array('LOCAL_W3' => $local));
             }
             $content = preg_replace('#(<!DOCTYPE[^>]+")http://www.w3.org(.*")#i', '\\1' . $local . '\\2', $content);
             $dom->validateOnParse = $checkDTD;
         }
         $dom->loadXML($content);
         switch (pathinfo($checkDTD, PATHINFO_EXTENSION)) {
             case 'xsd':
                 $dom->schemaValidate($checkDTD);
                 $message = sprintf('response validates per XSD schema "%s"', basename($checkDTD));
                 break;
             case 'rng':
             case 'rnc':
                 $dom->relaxNGValidate($checkDTD);
                 $message = sprintf('response validates per relaxNG schema "%s"', basename($checkDTD));
                 break;
             default:
                 $message = $dom->validateOnParse ? sprintf('response validates as "%s"', $dom->doctype->name) : 'response is well-formed "xml"';
         }
         if (count($errors = libxml_get_errors())) {
             $lines = explode(PHP_EOL, $this->response->getContent());
             $this->tester->fail($message);
             foreach ($errors as $error) {
                 $this->tester->diag('    ' . trim($error->message));
                 if (preg_match('/line (\\d+)/', $error->message, $match) && $error->line != $match[1]) {
                     $this->tester->diag('      ' . str_pad($match[1] . ':', 6) . trim($lines[$match[1] - 1]));
                 }
                 $this->tester->diag('      ' . str_pad($error->line . ':', 6) . trim($lines[$error->line - 1]));
             }
         } else {
             $this->tester->pass($message);
         }
         libxml_use_internal_errors($revert);
     } else {
         throw new LogicException(sprintf('Unable to validate responses of content type "%s"', $this->response->getContentType()));
     }
     return $this->getObjectToReturn();
 }
Example #17
0
 /**
  * Validates input string against validation files saved in models directory.
  * For now, only two validation step are set up - RelaxNG (*.rng) and Schema (*.xsd)
  *
  * @param string $xml   xml string to validate with RelaxNG and Schema, if available
  * @return bool
  */
 public function validateXml($xml)
 {
     $finder = new Finder();
     $domDoc = new \DOMDocument();
     $xml = "<mynetconfbase:data  xmlns:mynetconfbase='urn:ietf:params:xml:ns:netconf:base:1.0'>" . $xml . "</mynetconfbase:data>";
     $domDoc->loadXML($xml);
     $iterator = $finder->files()->name("/.*data\\.(rng|xsd)\$/")->in($this->dataModel->getPathToModels());
     try {
         foreach ($iterator as $file) {
             $path = $file->getRealPath();
             if (strpos($path, "rng")) {
                 try {
                     if (!@$domDoc->relaxNGValidate($path)) {
                         return false;
                     }
                 } catch (\ContextErrorException $e) {
                     $this->logger->addWarning($e->getMessage());
                     return false;
                 }
             } else {
                 if (strpos($path, "xsd")) {
                     try {
                         if (!@$domDoc->schemaValidate($path)) {
                             return false;
                         }
                     } catch (\ContextErrorException $e) {
                         $this->logger->addWarning($e->getMessage());
                         return false;
                     }
                 }
             }
         }
     } catch (\ErrorException $e) {
         $this->logger->addWarning("XML is not valid.", array('error' => $e->getMessage(), 'xml' => $xml, 'RNGfile' => $path));
         return false;
     }
     return true;
 }
Example #18
0
File: odt.php Project: bmdevel/ezc
 /**
  * Performs the actual validation on the given $document.
  *
  * Returns true on success, an array of errors otherwise.
  * 
  * @param DOMDocument $document 
  * @return array(ezcDocumentValidationError)|true
  */
 private function performValidation(DOMDocument $document)
 {
     $document->relaxNGValidate(dirname(__FILE__) . '/odt/data/odf_1.2.rng');
     // Get all errors
     $xmlErrors = libxml_get_errors();
     $errors = array();
     foreach ($xmlErrors as $error) {
         $errors[] = ezcDocumentValidationError::createFromLibXmlError($error);
     }
     libxml_clear_errors();
     return count($errors) ? $errors : true;
 }
<?php

$rng = dirname(__FILE__) . '/foo.rng';
$xml = <<<XML
<?xml version="1.0"?> 
<apple> 
  <pear>Pear</pear> 
  <pear>Pear</pear> 
</apple>
XML;
$doc = new DOMDocument();
$doc->loadXML($xml);
$result = $doc->relaxNGValidate($rng);
var_dump($result);
Example #20
0
 /**
  * Handle uploaded data, overwriting existing data
  */
 public function upload()
 {
     $this->sessionCheck();
     // Another session is either queued or writing — upload data won't be valid,
     // so client should wait and return to /updated with 'upload' flag
     Zotero_DB::beginTransaction();
     if (Zotero_Sync::userIsReadLocked($this->userID) || Zotero_Sync::userIsWriteLocked($this->userID)) {
         Zotero_DB::commit();
         $locked = $this->responseXML->addChild('locked');
         $locked['wait'] = $this->getWaitTime($this->sessionID);
         $this->end();
     }
     Zotero_DB::commit();
     $this->clearWaitTime($this->sessionID);
     if (empty($_REQUEST['updateKey'])) {
         $this->error(400, 'INVALID_UPLOAD_DATA', 'Update key not provided');
     }
     if ($_REQUEST['updateKey'] != Zotero_Users::getUpdateKey($this->userID)) {
         $this->e409("Server data has changed since last retrieval");
     }
     // TODO: change to POST
     if (empty($_REQUEST['data'])) {
         $this->error(400, 'MISSING_UPLOAD_DATA', 'Uploaded data not provided');
     }
     $xmldata =& $_REQUEST['data'];
     try {
         $doc = new DOMDocument();
         $doc->loadXML($xmldata, LIBXML_PARSEHUGE);
         // For huge uploads, make sure notes aren't bigger than SimpleXML can parse
         if (strlen($xmldata) > 7000000) {
             $xpath = new DOMXPath($doc);
             $results = $xpath->query('/data/items/item/note[string-length(text()) > ' . Zotero_Notes::$MAX_NOTE_LENGTH . ']');
             if ($results->length) {
                 $noteElem = $results->item(0);
                 $text = $noteElem->textContent;
                 $libraryID = $noteElem->parentNode->getAttribute('libraryID');
                 $key = $noteElem->parentNode->getAttribute('key');
                 // UTF-8 &nbsp; (0xC2 0xA0) isn't trimmed by default
                 $whitespace = chr(0x20) . chr(0x9) . chr(0xa) . chr(0xd) . chr(0x0) . chr(0xb) . chr(0xc2) . chr(0xa0);
                 $excerpt = iconv("UTF-8", "UTF-8//IGNORE", Zotero_Notes::noteToTitle(trim($text), true));
                 $excerpt = trim($excerpt, $whitespace);
                 // If tag-stripped version is empty, just return raw HTML
                 if ($excerpt == '') {
                     $excerpt = iconv("UTF-8", "UTF-8//IGNORE", preg_replace('/\\s+/', ' ', mb_substr(trim($text), 0, Zotero_Notes::$MAX_TITLE_LENGTH)));
                     $excerpt = html_entity_decode($excerpt);
                     $excerpt = trim($excerpt, $whitespace);
                 }
                 $msg = "=Note '" . $excerpt . "...' too long";
                 if ($key) {
                     $msg .= " for item '" . $libraryID . "/" . $key . "'";
                 }
                 throw new Exception($msg, Z_ERROR_NOTE_TOO_LONG);
             }
         }
     } catch (Exception $e) {
         $this->handleUploadError($e, $xmldata);
     }
     function relaxNGErrorHandler($errno, $errstr)
     {
         //Z_Core::logError($errstr);
     }
     set_error_handler('relaxNGErrorHandler');
     set_time_limit(60);
     if (!$doc->relaxNGValidate(Z_ENV_MODEL_PATH . 'relax-ng/upload.rng')) {
         $id = substr(md5(uniqid(rand(), true)), 0, 10);
         $str = date("D M j G:i:s T Y") . "\n";
         $str .= "IP address: " . $_SERVER['REMOTE_ADDR'] . "\n";
         if (isset($_SERVER['HTTP_X_ZOTERO_VERSION'])) {
             $str .= "Version: " . $_SERVER['HTTP_X_ZOTERO_VERSION'] . "\n";
         }
         $str .= "Error: RELAX NG validation failed\n\n";
         $str .= $xmldata;
         if (!file_put_contents(Z_CONFIG::$SYNC_ERROR_PATH . $id, $str)) {
             error_log("Unable to save error report to " . Z_CONFIG::$SYNC_ERROR_PATH . $id);
         }
         $this->error(500, 'INVALID_UPLOAD_DATA', "Uploaded data not well-formed (Report ID: {$id})");
     }
     restore_error_handler();
     try {
         $xml = simplexml_import_dom($doc);
         $queue = true;
         if (Z_ENV_TESTING_SITE && !empty($_GET['noqueue'])) {
             $queue = false;
         }
         if ($queue) {
             $affectedLibraries = Zotero_Sync::parseAffectedLibraries($xmldata);
             // Relations-only uploads don't have affected libraries
             if (!$affectedLibraries) {
                 $affectedLibraries = array(Zotero_Users::getLibraryIDFromUserID($this->userID));
             }
             Zotero_Sync::queueUpload($this->userID, $this->sessionID, $xmldata, $affectedLibraries);
             try {
                 Zotero_Processors::notifyProcessors('upload');
                 Zotero_Processors::notifyProcessors('error');
                 usleep(750000);
             } catch (Exception $e) {
                 Z_Core::logError($e);
             }
             // Give processor a chance to finish while we're still here
             $this->uploadstatus();
         } else {
             set_time_limit(210);
             $timestamp = Zotero_Sync::processUpload($this->userID, $xml);
             $this->responseXML['timestamp'] = $timestamp;
             $this->responseXML->addChild('uploaded');
             $this->end();
         }
     } catch (Exception $e) {
         $this->handleUploadError($e, $xmldata);
     }
 }
Example #21
0
 /**
  * Validate the input string
  *
  * Validate the input string against the specification of the current
  * document format.
  *
  * Returns true, if the validation succeded, and an array with
  * ezcDocumentValidationError objects otherwise.
  *
  * @param string $string
  * @return mixed
  */
 public function validateString($string)
 {
     $oldSetting = libxml_use_internal_errors(true);
     libxml_clear_errors();
     $document = new DOMDocument();
     $document->loadXml($string);
     $document->relaxNGValidate($this->options->relaxNgSchema);
     // Get all errors
     $xmlErrors = libxml_get_errors();
     $errors = array();
     foreach ($xmlErrors as $error) {
         $errors[] = ezcDocumentValidationError::createFromLibXmlError($error);
     }
     libxml_clear_errors();
     libxml_use_internal_errors($oldSetting);
     return count($errors) ? $errors : true;
 }
 /**
  * @test
  */
 public function logsTestResultsIntoTheSpecifiedFileInTheJunitXmlFormatIfSkipIfWithPassTest()
 {
     $this->loadClasses();
     $this->collector->collectTestCase('Stagehand_TestRunner_' . $this->framework . 'SkipIfWithPassTest');
     $this->runTests();
     $this->assertFileExists($this->config->junitXMLFile);
     $junitXML = new DOMDocument();
     $junitXML->load($this->config->junitXMLFile);
     $this->assertTrue($junitXML->relaxNGValidate(dirname(__FILE__) . '/../../../../../data/pear.piece-framework.com/Stagehand_TestRunner/JUnitXMLDOM.rng'));
     $parentTestsuite = $junitXML->childNodes->item(0)->childNodes->item(0);
     $this->assertTrue($parentTestsuite->hasChildNodes());
     $this->assertEquals(2, $parentTestsuite->getAttribute('tests'));
     $this->assertEquals(1, $parentTestsuite->getAttribute('assertions'));
     $this->assertEquals(0, $parentTestsuite->getAttribute('failures'));
     $this->assertEquals(1, $parentTestsuite->getAttribute('errors'));
     $this->assertEquals(1, $parentTestsuite->childNodes->length);
     $childTestsuite = $parentTestsuite->childNodes->item(0);
     $this->assertTrue($childTestsuite->hasChildNodes());
     $this->assertEquals('Stagehand_TestRunner_' . $this->framework . 'SkipIfWithPassTest', $childTestsuite->hasAttribute('name'));
     $this->assertTrue($childTestsuite->hasAttribute('file'));
     $class = new ReflectionClass('Stagehand_TestRunner_' . $this->framework . 'SkipIfWithPassTest');
     $this->assertEquals($class->getFileName(), $childTestsuite->getAttribute('file'));
     $this->assertEquals(2, $childTestsuite->getAttribute('tests'));
     $this->assertEquals(1, $childTestsuite->getAttribute('assertions'));
     $this->assertEquals(0, $childTestsuite->getAttribute('failures'));
     $this->assertEquals(1, $childTestsuite->getAttribute('errors'));
     $this->assertEquals(2, $childTestsuite->childNodes->length);
     $testcase = $childTestsuite->childNodes->item(0);
     $this->assertTrue($testcase->hasChildNodes());
     $this->assertEquals('testSkipIf', $testcase->hasAttribute('name'));
     $this->assertEquals('Stagehand_TestRunner_' . $this->framework . 'SkipIfWithPassTest', $testcase->hasAttribute('class'));
     $this->assertEquals($class->getFileName(), $testcase->getAttribute('file'));
     $method = $class->getMethod('testSkipIf');
     $this->assertEquals($method->getStartLine(), $testcase->getAttribute('line'));
     $this->assertEquals(0, $testcase->getAttribute('assertions'));
     $error = $testcase->childNodes->item(0);
     $this->assertRegexp('/^This is an skip message\\./', $error->nodeValue);
     $testcase = $childTestsuite->childNodes->item(1);
     $this->assertFalse($testcase->hasChildNodes());
     $this->assertEquals('testSkipIf', $testcase->hasAttribute('name'));
     $this->assertEquals('Stagehand_TestRunner_' . $this->framework . 'SkipIfWithPassTest', $testcase->hasAttribute('class'));
     $this->assertEquals($class->getFileName(), $testcase->getAttribute('file'));
     $method = $class->getMethod('testPass');
     $this->assertEquals($method->getStartLine(), $testcase->getAttribute('line'));
     $this->assertEquals(1, $testcase->getAttribute('assertions'));
 }
 /**
  * @test
  *
  * @link http://redmine.piece-framework.com/issues/216
  */
 public function generatesTheValidXmlWithSkippedTestsByDependsAnnotations()
 {
     $this->createCollector()->collectTestCase('Stagehand_TestRunner_PHPUnitDependsTest');
     $this->runTests();
     $this->assertFileExists($this->junitXMLFile);
     $junitXML = new \DOMDocument();
     $junitXML->load($this->junitXMLFile);
     $this->assertTrue($junitXML->relaxNGValidate($this->getSchemaFile(self::LOG_REALTIME_NOT)));
 }
 /**
  * This function takes the dom document and validates it against the
  * GRAMPS RNG schema. It then prints out the results of the validation
  * to the screen.
  *
  * Validating against the DTD could be easily added
  * if that is deemed useful.
  *
  * @param DOMDocument $domObj - this is the dom document to be validated
  * @param boolean $printXML - set to true, this parameter will make validate print out the DOMDocuments XML to the screen
  *
  */
 function validate($domObj, $printXML = true)
 {
     if ($printXML) {
         print "<br /><br /><br />" . nl2br(htmlentities($domObj->saveXML(), ENT_COMPAT, 'UTF-8'));
     }
     print "Loading GRAMPS file... <br />";
     $domObj->loadXML($domObj->saveXML());
     $res = $domObj->relaxNGValidate('includes/grampsxml.rng');
     if ($res) {
         print "Validation: <em style=\"color:green;\"><h1> PASSED against the .RNG</h1></em>";
     } else {
         print "Validation: <em style=\"color:red;\"><h1> FAILED against the .RNG</h1></em>";
     }
 }
 /**
  * Perform RELAX NG validation on the document.
  *
  * @param      string The path to the schema.
  *
  * @return     bool True if the validation is successful; false otherwise.
  *
  * @author     Noah Fontes <*****@*****.**>
  * @since      1.0.0
  */
 public function relaxNGValidate($filename)
 {
     $luie = libxml_use_internal_errors(true);
     libxml_clear_errors();
     // gotta do the @ to suppress PHP warnings when the schema cannot be loaded or is invalid
     if (!($result = @parent::relaxNGValidate($filename))) {
         $errors = array();
         foreach (libxml_get_errors() as $error) {
             $errors[] = sprintf('[%s #%d] Line %d: %s', $error->level == LIBXML_ERR_WARNING ? 'Warning' : ($error->level == LIBXML_ERR_ERROR ? 'Error' : 'Fatal'), $error->code, $error->line, $error->message);
         }
         libxml_clear_errors();
         libxml_use_internal_errors($luie);
         throw new DOMException(sprintf('RELAX NG validation with "%s" failed due to the following error%s: ' . "\n\n%s", $filename, count($errors) > 1 ? 's' : '', implode("\n", $errors)));
     }
     libxml_use_internal_errors($luie);
     return $result;
 }
 /**
  * @test
  */
 public function logsTestResultsWhenNoTestsAreFound()
 {
     $this->runTests();
     $this->assertFileExists($this->junitXMLFile);
     $junitXML = new \DOMDocument();
     $junitXML->load($this->junitXMLFile);
     $this->assertTrue($junitXML->relaxNGValidate($this->getSchemaFile(self::LOG_REALTIME_NOT)));
     $rootTestSuiteNode = $junitXML->childNodes->item(0)->childNodes->item(0);
     $this->assertFalse($rootTestSuiteNode->hasChildNodes());
     $this->assertEquals(0, $rootTestSuiteNode->getAttribute('tests'));
     $this->assertEquals(0, $rootTestSuiteNode->getAttribute('assertions'));
     $this->assertEquals(0, $rootTestSuiteNode->getAttribute('failures'));
     $this->assertEquals(0, $rootTestSuiteNode->getAttribute('errors'));
     $this->assertTrue($rootTestSuiteNode->hasAttribute('time'));
 }
 /**
  * Validates the response.
  *
  * @param mixed $checkDTD Either true to validate against the response DTD or
  *                        provide the path to a *.xsd, *.rng or *.rnc schema
  *
  * @return sfTestFunctionalBase|sfTester
  *
  * @throws LogicException If the response is neither XML nor (X)HTML
  */
 public function isValid($checkDTD = false)
 {
     if (preg_match('/(x|ht)ml/i', $this->response->getContentType())) {
         $revert = libxml_use_internal_errors(true);
         $dom = new DOMDocument('1.0', $this->response->getCharset());
         $content = $this->response->getContent();
         if (true === $checkDTD) {
             $cache = sfConfig::get('sf_cache_dir') . '/sf_tester_response/w3';
             if ($cache[1] == ':') {
                 // On Windows systems the path will be like c:\symfony\cache\xml.dtd
                 // I did not manage to get DOMDocument loading a file protocol url including the drive letter
                 // file://c:\symfony\cache\xml.dtd or file://c:/symfony/cache/xml.dtd
                 // The first one simply doesnt work, the second one is treated as remote call.
                 // However the following works. Unfortunatly this means we can only access the current disk
                 // file:///symfony/cache/xml.dtd
                 // Note that all work for file_get_contents so the bug is most likely in DOMDocument.
                 $local = 'file://' . substr(str_replace(DIRECTORY_SEPARATOR, '/', $cache), 2);
             } else {
                 $local = 'file://' . $cache;
             }
             if (!file_exists($cache . '/TR/xhtml11/DTD/xhtml11.dtd')) {
                 $filesystem = new sfFilesystem();
                 $finder = sfFinder::type('any')->discard('.sf');
                 $filesystem->mirror(dirname(__FILE__) . '/w3', $cache, $finder);
                 $finder = sfFinder::type('file');
                 $filesystem->replaceTokens($finder->in($cache), '##', '##', array('LOCAL_W3' => $local));
             }
             $content = preg_replace('#(<!DOCTYPE[^>]+")http://www.w3.org(.*")#i', '\\1' . $local . '\\2', $content);
             $dom->validateOnParse = $checkDTD;
         }
         $dom->loadXML($content);
         switch (pathinfo($checkDTD, PATHINFO_EXTENSION)) {
             case 'xsd':
                 $dom->schemaValidate($checkDTD);
                 $message = sprintf('response validates per XSD schema "%s"', basename($checkDTD));
                 break;
             case 'rng':
             case 'rnc':
                 $dom->relaxNGValidate($checkDTD);
                 $message = sprintf('response validates per relaxNG schema "%s"', basename($checkDTD));
                 break;
             default:
                 $message = $dom->validateOnParse ? sprintf('response validates as "%s"', $dom->doctype->name) : 'response is well-formed "xml"';
         }
         if (count($errors = libxml_get_errors())) {
             foreach ($errors as $error) {
                 $message .= sprintf("\n * (line:%d) %s", $error->line, $error->message);
             }
             $this->tester->fail($message);
         } else {
             $this->tester->pass($message);
         }
         libxml_use_internal_errors($revert);
     } else {
         throw new LogicException(sprintf('Unable to validate responses of content type "%s"', $this->response->getContentType()));
     }
     return $this->getObjectToReturn();
 }
 /**
  * @test
  * @dataProvider provideWritingModes
  * @param boolean $logsResultsInJUnitXMLInRealtime
  * @link http://redmine.piece-framework.com/issues/216
  * @since Method available since Release 2.14.0
  */
 public function generatesAValidXmlIfAnyTestCasesAreSkippedByDependsAnnotations($logsResultsInJUnitXMLInRealtime)
 {
     $this->config->logsResultsInJUnitXMLInRealtime = $logsResultsInJUnitXMLInRealtime;
     if ($this->config->logsResultsInJUnitXMLInRealtime) {
         $relaxNGSchema = dirname(__FILE__) . '/../../../../../data/pear.piece-framework.com/Stagehand_TestRunner/JUnitXMLStream.rng';
     } else {
         $relaxNGSchema = dirname(__FILE__) . '/../../../../../data/pear.piece-framework.com/Stagehand_TestRunner/JUnitXMLDOM.rng';
     }
     $testClass = 'Stagehand_TestRunner_PHPUnitDependsTest';
     class_exists($testClass);
     $this->collector->collectTestCase($testClass);
     $this->runTests();
     $junitXML = new DOMDocument();
     $junitXML->load($this->config->junitXMLFile);
     $this->assertTrue($junitXML->relaxNGValidate($relaxNGSchema));
     $parentTestsuite = $junitXML->childNodes->item(0)->childNodes->item(0);
     $this->assertTrue($parentTestsuite->hasChildNodes());
     $this->assertEquals(2, $parentTestsuite->getAttribute('tests'));
     if (!$this->config->logsResultsInJUnitXMLInRealtime) {
         $this->assertEquals(1, $parentTestsuite->getAttribute('assertions'));
         $this->assertEquals(1, $parentTestsuite->getAttribute('failures'));
         $this->assertEquals(1, $parentTestsuite->getAttribute('errors'));
     }
     $this->assertEquals(1, $parentTestsuite->childNodes->length);
     $childTestsuite = $parentTestsuite->childNodes->item(0);
     $this->assertTrue($childTestsuite->hasChildNodes());
     $this->assertEquals($testClass, $childTestsuite->getAttribute('name'));
     $this->assertTrue($childTestsuite->hasAttribute('file'));
     $class = new ReflectionClass($testClass);
     $this->assertEquals($class->getFileName(), $childTestsuite->getAttribute('file'));
     $this->assertEquals(2, $childTestsuite->getAttribute('tests'));
     if (!$this->config->logsResultsInJUnitXMLInRealtime) {
         $this->assertEquals(1, $childTestsuite->getAttribute('assertions'));
         $this->assertEquals(1, $childTestsuite->getAttribute('failures'));
         $this->assertEquals(1, $childTestsuite->getAttribute('errors'));
     }
     $this->assertEquals(2, $childTestsuite->childNodes->length);
     $testcase = $childTestsuite->childNodes->item(0);
     $this->assertEquals('pass', $testcase->getAttribute('name'));
     if (!$this->config->logsResultsInJUnitXMLInRealtime) {
         $this->assertEquals(1, $testcase->getAttribute('assertions'));
     }
     $testcase = $childTestsuite->childNodes->item(1);
     $this->assertTrue($testcase->hasChildNodes());
     $this->assertEquals('skip', $testcase->getAttribute('name'));
     if (!$this->config->logsResultsInJUnitXMLInRealtime) {
         $this->assertEquals(0, $testcase->getAttribute('assertions'));
     }
     $error = $testcase->childNodes->item(0);
     $this->assertEquals('PHPUnit_Framework_SkippedTestError', $error->getAttribute('type'));
     $this->assertRegExp('/^Stagehand_TestRunner_PHPUnitDependsTest::skip\\s+This test depends on "Stagehand_TestRunner_PHPUnitDependsTest::pass" to pass./', $error->nodeValue);
 }