QA: Additional unit tests

This commit is contained in:
Ivan Lanin 2014-05-31 17:39:54 +07:00
parent 269def4b9d
commit 9839222492
22 changed files with 254 additions and 44 deletions

View File

@ -60,49 +60,29 @@ abstract class AbstractContainer extends AbstractElement
if ($withoutP && ($elementName == 'Text' || $elementName == 'PreserveText')) {
$args[3] = null; // Remove paragraph style for texts in textrun
}
$source = '';
if (count($args) > 1) {
$source = $args[1];
}
// Create element using reflection
$reflection = new \ReflectionClass($elementClass);
$elementArgs = $args;
array_shift($elementArgs); // Shift an element off the beginning of array: the $elementName
array_shift($elementArgs); // Shift the $elementName off the beginning of array
/** @var \PhpOffice\PhpWord\Element\AbstractElement $element Type hint */
$element = $reflection->newInstanceArgs($elementArgs);
// Set nested level
if ($this->container == 'Cell') {
$element->setNestedLevel($this->getNestedLevel() + 1);
} else {
$element->setNestedLevel($this->getNestedLevel());
}
// Set relation Id for media collection
$mediaContainer = $this->getMediaContainer();
if (in_array($elementName, array('Link', 'Image', 'Object'))) {
/** @var \PhpOffice\PhpWord\Element\Image $element Type hint */
$image = ($elementName == 'Image') ? $element : null;
$rId = Media::addElement($mediaContainer, strtolower($elementName), $args[1], $image);
$element->setRelationId($rId);
}
if ($elementName == 'Object') {
/** @var \PhpOffice\PhpWord\Element\Object $element Type hint */
$rIdIcon = Media::addElement($mediaContainer, 'image', $element->getIcon(), new Image($element->getIcon()));
$element->setImageRelationId($rIdIcon);
}
// Set relation Id for other collection
if (in_array($elementName, array('Footnote', 'Endnote', 'Title')) && $this->phpWord instanceof PhpWord) {
$addMethod = "add{$elementName}";
$rId = $this->phpWord->$addMethod($element);
$element->setRelationId($rId);
}
// Set nested level and relation Id
$this->setElementNestedLevel($element);
$this->setElementRelationId($element, $elementName, $source);
// Set other properties and add element into collection
$element->setDocPart($this->getDocPart(), $this->getDocPartId());
$element->setElementIndex($this->countElements() + 1);
$element->setElementId();
$element->setPhpWord($this->phpWord);
$this->elements[] = $element;
return $element;
@ -128,6 +108,54 @@ abstract class AbstractContainer extends AbstractElement
return count($this->elements);
}
/**
* Set element nested level based on container; add one when it's inside a cell
*/
private function setElementNestedLevel(AbstractElement $element)
{
if ($this->container == 'Cell') {
$element->setNestedLevel($this->getNestedLevel() + 1);
} else {
$element->setNestedLevel($this->getNestedLevel());
}
}
/**
* Set relation Id
*
* @param string $elementName
* @param string $source
*/
private function setElementRelationId(AbstractElement $element, $elementName, $source)
{
$mediaContainer = $this->getMediaContainer();
$hasMediaRelation = in_array($elementName, array('Link', 'Image', 'Object'));
$hasOtherRelation = in_array($elementName, array('Footnote', 'Endnote', 'Title'));
// Set relation Id for media elements (link, image, object; legacy of OOXML)
// Only Image that needs to be passed to Media class
if ($hasMediaRelation) {
/** @var \PhpOffice\PhpWord\Element\Image $element Type hint */
$image = ($elementName == 'Image') ? $element : null;
$rId = Media::addElement($mediaContainer, strtolower($elementName), $source, $image);
$element->setRelationId($rId);
}
// Set relation Id for icon of object element
if ($elementName == 'Object') {
/** @var \PhpOffice\PhpWord\Element\Object $element Type hint */
$rIdIcon = Media::addElement($mediaContainer, 'image', $element->getIcon(), new Image($element->getIcon()));
$element->setImageRelationId($rIdIcon);
}
// Set relation Id for elements that will be registered in the Collection subnamespaces
if ($hasOtherRelation && $this->phpWord instanceof PhpWord) {
$addMethod = "add{$elementName}";
$rId = $this->phpWord->$addMethod($element);
$element->setRelationId($rId);
}
}
/**
* Add text/preservetext element
*

View File

@ -23,7 +23,7 @@ use PhpOffice\PhpWord\Reader\Word2007\AbstractPart as Word2007AbstractPart;
* Abstract part reader
*
* @since 0.10.0
* @codeCoverageIgnore Nothing in here yet
* @codeCoverageIgnore
*/
abstract class AbstractPart extends Word2007AbstractPart
{

View File

@ -69,9 +69,12 @@ class XMLWriter
$this->tempFile = @tempnam($tempFolder, 'xml');
// Fallback to memory when temporary file cannot be used
// @codeCoverageIgnoreStart
// Can't find any test case. Uncomment when found.
if ($this->xmlWriter->openUri($this->tempFile) === false) {
$this->xmlWriter->openMemory();
}
// @codeCoverageIgnoreEnd
}
// Set xml Compatibility

View File

@ -152,6 +152,7 @@ class ZipArchive
*
* @return bool
* @throws \PhpOffice\PhpWord\Exception\Exception
* @codeCoverageIgnore Can't find any test case. Uncomment when found.
*/
public function close()
{

View File

@ -219,9 +219,12 @@ abstract class AbstractWriter implements WriterInterface
$this->originalFilename = $filename;
if (strtolower($filename) == 'php://output' || strtolower($filename) == 'php://stdout') {
$filename = @tempnam(sys_get_temp_dir(), 'phpword_');
// @codeCoverageIgnoreStart
// Can't find any test case. Uncomment when found.
if ($filename == '') {
$filename = $this->originalFilename;
}
// @codeCoverageIgnoreEnd
}
$this->tempFilename = $filename;
@ -234,9 +237,12 @@ abstract class AbstractWriter implements WriterInterface
protected function cleanupTempFile()
{
if ($this->originalFilename != $this->tempFilename) {
// @codeCoverageIgnoreStart
// Can't find any test case. Uncomment when found.
if (copy($this->tempFilename, $this->originalFilename) === false) {
throw new Exception("Could not copy temporary zip file.");
}
// @codeCoverageIgnoreEnd
@unlink($this->tempFilename);
}
@ -269,11 +275,15 @@ abstract class AbstractWriter implements WriterInterface
// Try opening the ZIP file
$zip = new ZipArchive();
// @codeCoverageIgnoreStart
// Can't find any test case. Uncomment when found.
if ($zip->open($filename, ZipArchive::OVERWRITE) !== true) {
if ($zip->open($filename, ZipArchive::CREATE) !== true) {
throw new \Exception("Could not open '{$filename}' for writing.");
}
}
// @codeCoverageIgnoreEnd
return $zip;
}
@ -290,9 +300,12 @@ abstract class AbstractWriter implements WriterInterface
{
$filename = $this->getTempFile($filename);
$fileHandle = fopen($filename, 'w');
// @codeCoverageIgnoreStart
// Can't find any test case. Uncomment when found.
if ($fileHandle === false) {
throw new \Exception("Could not open '{$filename}' for writing.");
}
// @codeCoverageIgnoreEnd
return $fileHandle;
}

View File

@ -70,6 +70,7 @@ class Text extends AbstractElement
$content = '';
$content .= $this->writeOpening();
$content .= $this->openingText;
$content .= $this->openingTags;
$content .= htmlspecialchars($element->getText());
$content .= $this->closingTags;
@ -113,7 +114,6 @@ class Text extends AbstractElement
$style = $this->getParagraphStyle();
}
$content .= "<p{$style}>";
$content .= $this->openingText;
}
return $content;

View File

@ -49,7 +49,7 @@ class Font extends AbstractStyle
$css['font-family'] = $this->getValueIf($font !== null, "'{$font}'");
$css['font-size'] = $this->getValueIf($size !== null, "{$size}pt");
$css['color'] = $this->getValueIf($color != Settings::DEFAULT_FONT_COLOR, "#{$color}");
$css['color'] = $this->getValueIf($color !== null, "#{$color}");
$css['background'] = $this->getValueIf($fgColor != '', $fgColor);
$css['font-weight'] = $this->getValueIf($style->isBold(), 'bold');
$css['font-style'] = $this->getValueIf($style->isItalic(), 'italic');

View File

@ -89,17 +89,16 @@ class Meta extends AbstractPart
* @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter
* @param string $property
* @param string $value
* @param string $type string (default/null)
*
* @todo Handle other `$type`: double|date|dateTime|duration|boolean
* @todo Handle other `$type`: double|date|dateTime|duration|boolean (4th arguments)
*/
private function writeCustomProperty(XMLWriter $xmlWriter, $property, $value, $type = null)
private function writeCustomProperty(XMLWriter $xmlWriter, $property, $value)
{
$xmlWriter->startElement('meta:user-defined');
$xmlWriter->writeAttribute('meta:name', $property);
if ($type !== null) {
$xmlWriter->writeAttribute('meta:value-type', $type);
}
// if ($type !== null) {
// $xmlWriter->writeAttribute('meta:value-type', $type);
// }
$xmlWriter->writeRaw($value);
$xmlWriter->endElement(); // meta:user-defined
}

View File

@ -87,7 +87,10 @@ abstract class AbstractRenderer extends HTML
/** @noinspection PhpIncludeInspection Dynamic includes */
require_once $includeFile;
} else {
// @codeCoverageIgnoreStart
// Can't find any test case. Uncomment when found.
throw new Exception('Unable to load PDF Rendering library');
// @codeCoverageIgnoreEnd
}
}
@ -172,9 +175,12 @@ abstract class AbstractRenderer extends HTML
protected function prepareForSave($filename = null)
{
$fileHandle = fopen($filename, 'w');
// @codeCoverageIgnoreStart
// Can't find any test case. Uncomment when found.
if ($fileHandle === false) {
throw new Exception("Could not open file $filename for writing.");
}
// @codeCoverageIgnoreEnd
$this->isPdf = true;
return $fileHandle;

View File

@ -43,7 +43,7 @@ class FieldTest extends \PHPUnit_Framework_TestCase
public function testConstructWithType()
{
$oField = new Field('DATE');
$this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Field', $oField);
$this->assertEquals($oField->getType(), 'DATE');
}
@ -54,7 +54,7 @@ class FieldTest extends \PHPUnit_Framework_TestCase
public function testConstructWithTypeProperties()
{
$oField = new Field('DATE', array('dateformat'=>'d-M-yyyy'));
$this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Field', $oField);
$this->assertEquals($oField->getType(), 'DATE');
$this->assertEquals($oField->getProperties(), array('dateformat'=>'d-M-yyyy'));
@ -66,10 +66,46 @@ class FieldTest extends \PHPUnit_Framework_TestCase
public function testConstructWithTypePropertiesOptions()
{
$oField = new Field('DATE', array('dateformat'=>'d-M-yyyy'), array('SakaEraCalendar', 'PreserveFormat'));
$this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Field', $oField);
$this->assertEquals($oField->getType(), 'DATE');
$this->assertEquals($oField->getProperties(), array('dateformat'=>'d-M-yyyy'));
$this->assertEquals($oField->getOptions(), array('SakaEraCalendar', 'PreserveFormat'));
}
/**
* Test setType exception
*
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Invalid type
*/
public function testSetTypeException()
{
$object = new Field();
$object->setType('foo');
}
/**
* Test setProperties exception
*
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Invalid property
*/
public function testSetPropertiesException()
{
$object = new Field('PAGE');
$object->setProperties(array('foo' => 'bar'));
}
/**
* Test setOptions exception
*
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Invalid option
*/
public function testSetOptionsException()
{
$object = new Field('PAGE');
$object->setOptions(array('foo' => 'bar'));
}
}

View File

@ -27,6 +27,19 @@ use PhpOffice\PhpWord\Shared\XMLReader;
*/
class XMLReaderTest extends \PHPUnit_Framework_TestCase
{
/**
* Test get DOMDocument from ZipArchive exception
*
* @expectedException \PhpOffice\PhpWord\Exception\Exception
* @expectedExceptionMessage Cannot find archive file.
*/
public function testGetDomFromZipException()
{
$filename = __DIR__ . "/../_files/documents/foo.zip";
$object = new XMLReader();
$object->getDomFromZip($filename, 'yadayadaya');
}
/**
* Test get DOMDocument from ZipArchive returns false
*/

View File

@ -38,6 +38,7 @@ class NumberingLevelTest extends \PHPUnit_Framework_TestCase
'start' => 1,
'format' => 'decimal',
'restart' => 1,
'pStyle' => 'pStyle',
'suffix' => 'space',
'text' => '%1.',
'align' => 'left',

View File

@ -75,6 +75,8 @@ class ParagraphTest extends \PHPUnit_Framework_TestCase
'spacing' => 120,
'basedOn' => 'Normal',
'next' => 'Normal',
'numStyle' => 'numStyle',
'numLevel' => 1,
'widowControl' => false,
'keepNext' => true,
'keepLines' => true,

View File

@ -16,7 +16,9 @@
*/
namespace PhpOffice\PhpWord\Tests\Writer\HTML;
use PhpOffice\PhpWord\Element\Text as TextElement;
use PhpOffice\PhpWord\Writer\HTML;
use PhpOffice\PhpWord\Writer\HTML\Element\Text;
/**
* Test class for PhpOffice\PhpWord\Writer\HTML\Element subnamespace
@ -38,4 +40,17 @@ class ElementTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('', $object->write());
}
}
/**
* Test write element text
*/
public function testWriteTextElement()
{
$object = new Text(new HTML(), new TextElement('A'));
$object->setOpeningText('-');
$object->setClosingText('-');
$object->setWithoutP(true);
$this->assertEquals('-A-', $object->write());
}
}

View File

@ -0,0 +1,36 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @link https://github.com/PHPOffice/PHPWord
* @copyright 2010-2014 PHPWord contributors
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Tests\Writer\HTML;
use PhpOffice\PhpWord\Writer\HTML\Part\Body;
/**
* Test class for PhpOffice\PhpWord\Writer\HTML\Part subnamespace
*/
class PartTest extends \PHPUnit_Framework_TestCase
{
/**
* Test get parent writer exception
*
* @expectedException \PhpOffice\PhpWord\Exception\Exception
*/
public function testGetParentWriterException()
{
$object = new Body();
$object->getParentWriter();
}
}

View File

@ -67,7 +67,7 @@ class HTMLTest extends \PHPUnit_Framework_TestCase
$phpWord->addTitleStyle(1, array('bold' => true));
$phpWord->addFontStyle('Font', array('name' => 'Verdana', 'size' => 11,
'color' => 'FF0000', 'fgColor' => 'FF0000'));
$phpWord->addParagraphStyle('Paragraph', array('align' => 'center'));
$phpWord->addParagraphStyle('Paragraph', array('align' => 'center', 'spaceAfter' => 20, 'spaceBefore' => 20));
$section = $phpWord->addSection();
$section->addText('Test 1', 'Font', 'Paragraph');
$section->addTextBreak();

View File

@ -47,6 +47,9 @@ class ContentTest extends \PHPUnit_Framework_TestCase
$phpWord = new PhpWord();
$docProps = $phpWord->getDocumentProperties();
$docProps->setCustomProperty('Company', 'PHPWord');
$phpWord->setDefaultFontName('Verdana');
$phpWord->addFontStyle('Font', array('size' => 11));
$phpWord->addParagraphStyle('Paragraph', array('align' => 'center'));

View File

@ -28,7 +28,7 @@ class ElementTest extends \PHPUnit_Framework_TestCase
*/
public function testUnmatchedElements()
{
$elements = array('Container', 'Text', 'Title', 'Link', 'Table');
$elements = array('Container', 'Text', 'Title', 'Link', 'Image', 'Table');
foreach ($elements as $element) {
$objectClass = 'PhpOffice\\PhpWord\\Writer\\RTF\\Element\\' . $element;
$parentWriter = new RTF();

View File

@ -68,7 +68,16 @@ class RTFTest extends \PHPUnit_Framework_TestCase
$section->addLink('http://test.com');
$section->addTitle('Test', 1);
$section->addPageBreak();
$section->addTable()->addRow()->addCell()->addText('Test');
// Rowspan
$table = $section->addTable();
$table->addRow()->addCell(null, array('vMerge' => 'restart'))->addText('Test');
$table->addRow()->addCell(null, array('vMerge' => 'continue'))->addText('Test');
// Nested table
$cell = $section->addTable()->addRow()->addCell();
$cell->addTable()->addRow()->addCell();
$section->addListItem('Test');
$section->addImage($imageSrc);
$section->addObject($objectSrc);

View File

@ -16,13 +16,23 @@
*/
namespace PhpOffice\PhpWord\Tests\Writer\Word2007;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\XMLWriter;
use PhpOffice\PhpWord\Tests\TestHelperDOCX;
/**
* Test class for PhpOffice\PhpWord\Writer\Word2007\Element subnamespace
*/
class ElementTest extends \PHPUnit_Framework_TestCase
{
/**
* Executed before each method of the class
*/
public function tearDown()
{
TestHelperDOCX::clear();
}
/**
* Test unmatched element
*/
@ -43,4 +53,18 @@ class ElementTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('', $xmlWriter->getData());
}
}
/**
* Test line element
*/
public function testLineElement()
{
$phpWord = new PhpWord();
$section = $phpWord->addSection();
$section->addLine(array('width' => 1000, 'height' => 1000, 'positioning' => 'absolute', 'flip' => true));
$doc = TestHelperDOCX::getDocument($phpWord);
$element = "/w:document/w:body/w:p/w:r/w:pict/v:shapetype";
$this->assertTrue($doc->elementExists($element));
}
}

View File

@ -43,6 +43,8 @@ class DocumentTest extends \PHPUnit_Framework_TestCase
{
$phpWord = new PhpWord();
$section = $phpWord->addSection();
$section->addHeader();
$section->addHeader('first');
$settings = $section->getSettings();
$settings->setLandscape();
$settings->setPageNumberingStart(2);

View File

@ -42,4 +42,23 @@ class StyleTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('', $xmlWriter->getData());
}
}
/**
* Test method exceptions
*/
public function testMethodExceptions()
{
$styles = array(
'Image' => 'writeAlignment',
'Line' => 'writeStroke',
);
foreach ($styles as $style => $method) {
$objectClass = 'PhpOffice\\PhpWord\\Writer\\Word2007\\Style\\' . $style;
$xmlWriter = new XMLWriter();
$object = new $objectClass($xmlWriter);
$object->$method();
$this->assertEquals('', $xmlWriter->getData());
}
}
}