<property name="build.classes.dir" value="${build.dir}/classes"/>
<property name="build.sandbox-classes.dir" value="${build.dir}/sandbox-classes"/>
<property name="build.codegen-classes.dir" value="${build.dir}/codegen-classes"/>
+ <property name="build.codegen.fonts.dir" value="${build.gensrc.dir}/org/apache/fop/fonts/"/>
<property name="build.javadocs.dir" value="${build.dir}/javadocs"/>
<property name="build.examples.dir" value="${build.dir}/examples"/>
+ <property name="build.unit.tests.dir" value="${build.dir}/test-classes"/>
<property name="build.tests.dir" value="${build.dir}/tests"/>
<property name="build.viewer.resources.dir" value="${build.classes.dir}/org/apache/fop/render/awt/viewer/resources"/>
<property name="build.viewer.images.dir" value="${build.classes.dir}/org/apache/fop/render/awt/viewer/images"/>
<!-- =================================================================== -->
<!-- Generate the source code -->
<!-- =================================================================== -->
+ <macrodef name="create-font">
+ <attribute name="name"/>
+ <sequential>
+ <xslt in="${src.codegen.fonts.dir}/@{name}.xml" style="${src.codegen.fonts.dir}/font-file.xsl" out="${build.codegen.fonts.dir}/base14/@{name}.java"/>
+ </sequential>
+ </macrodef>
<target name="codegen" depends="init" description="Generates the java files from the xml resources">
<echo message="Generating the java files from xml resources"/>
<mkdir dir="${build.gensrc.dir}"/>
<mkdir dir="${build.gensrc.dir}/org/apache/fop/fonts/base14"/>
- <xslt in="${src.codegen.fonts.dir}/encodings.xml" style="${src.codegen.fonts.dir}/code-point-mapping.xsl" out="${build.gensrc.dir}/org/apache/fop/fonts/CodePointMapping.java"/>
-<!-- Task unrolled because of a bug in Xalan included in some
- JDK 1.4 releases
- <xslt basedir="src/codegen" includes="Helvetica*.xml,Times*.xml,Courier*.xml"
- style="${src.codegen.fonts.dir}/font-file.xsl"
- destdir="${build.gensrc.dir}/org/apache/fop/fonts/base14" extension=".java">
- <param name="encoding" expression="WinAnsiEncoding"/>
- </xslt>
- -->
- <xslt in="${src.codegen.fonts.dir}/Courier.xml" style="${src.codegen.fonts.dir}/font-file.xsl" out="${build.gensrc.dir}/org/apache/fop/fonts/base14/Courier.java">
- <param name="encoding" expression="WinAnsiEncoding"/>
- </xslt>
- <xslt in="${src.codegen.fonts.dir}/CourierOblique.xml" style="${src.codegen.fonts.dir}/font-file.xsl" out="${build.gensrc.dir}/org/apache/fop/fonts/base14/CourierOblique.java">
- <param name="encoding" expression="WinAnsiEncoding"/>
- </xslt>
- <xslt in="${src.codegen.fonts.dir}/CourierBold.xml" style="${src.codegen.fonts.dir}/font-file.xsl" out="${build.gensrc.dir}/org/apache/fop/fonts/base14/CourierBold.java">
- <param name="encoding" expression="WinAnsiEncoding"/>
- </xslt>
- <xslt in="${src.codegen.fonts.dir}/CourierBoldOblique.xml" style="${src.codegen.fonts.dir}/font-file.xsl" out="${build.gensrc.dir}/org/apache/fop/fonts/base14/CourierBoldOblique.java">
- <param name="encoding" expression="WinAnsiEncoding"/>
- </xslt>
- <xslt in="${src.codegen.fonts.dir}/Helvetica.xml" style="${src.codegen.fonts.dir}/font-file.xsl" destdir="${build.gensrc.dir}/org/apache/fop/fonts/base14" out="${build.gensrc.dir}/org/apache/fop/fonts/base14/Helvetica.java">
- <param name="encoding" expression="WinAnsiEncoding"/>
- </xslt>
- <xslt in="${src.codegen.fonts.dir}/HelveticaBold.xml" style="${src.codegen.fonts.dir}/font-file.xsl" out="${build.gensrc.dir}/org/apache/fop/fonts/base14/HelveticaBold.java">
+ <xslt in="${src.codegen.fonts.dir}/encodings.xml" style="${src.codegen.fonts.dir}/code-point-mapping.xsl" out="${build.codegen.fonts.dir}/CodePointMapping.java"/>
+ <xslt basedir="${src.codegen.fonts.dir}" includes="Helvetica*.xml,Times*.xml,Courier*.xml" style="${src.codegen.fonts.dir}/font-file.xsl" destdir="${build.codegen.fonts.dir}/base14/" extension=".java">
<param name="encoding" expression="WinAnsiEncoding"/>
</xslt>
- <xslt in="${src.codegen.fonts.dir}/HelveticaOblique.xml" style="${src.codegen.fonts.dir}/font-file.xsl" out="${build.gensrc.dir}/org/apache/fop/fonts/base14/HelveticaOblique.java">
- <param name="encoding" expression="WinAnsiEncoding"/>
- </xslt>
- <xslt in="${src.codegen.fonts.dir}/HelveticaBoldOblique.xml" style="${src.codegen.fonts.dir}/font-file.xsl" out="${build.gensrc.dir}/org/apache/fop/fonts/base14/HelveticaBoldOblique.java">
- <param name="encoding" expression="WinAnsiEncoding"/>
- </xslt>
- <xslt in="${src.codegen.fonts.dir}/TimesRoman.xml" style="${src.codegen.fonts.dir}/font-file.xsl" out="${build.gensrc.dir}/org/apache/fop/fonts/base14/TimesRoman.java">
- <param name="encoding" expression="WinAnsiEncoding"/>
- </xslt>
- <xslt in="${src.codegen.fonts.dir}/TimesItalic.xml" style="${src.codegen.fonts.dir}/font-file.xsl" out="${build.gensrc.dir}/org/apache/fop/fonts/base14/TimesItalic.java">
- <param name="encoding" expression="WinAnsiEncoding"/>
- </xslt>
- <xslt in="${src.codegen.fonts.dir}/TimesBold.xml" style="${src.codegen.fonts.dir}/font-file.xsl" out="${build.gensrc.dir}/org/apache/fop/fonts/base14/TimesBold.java">
- <param name="encoding" expression="WinAnsiEncoding"/>
- </xslt>
- <xslt in="${src.codegen.fonts.dir}/TimesBoldItalic.xml" style="${src.codegen.fonts.dir}/font-file.xsl" out="${build.gensrc.dir}/org/apache/fop/fonts/base14/TimesBoldItalic.java">
- <param name="encoding" expression="WinAnsiEncoding"/>
- </xslt>
- <xslt in="${src.codegen.fonts.dir}/Symbol.xml" style="${src.codegen.fonts.dir}/font-file.xsl" out="${build.gensrc.dir}/org/apache/fop/fonts/base14/Symbol.java"/>
- <xslt in="${src.codegen.fonts.dir}/ZapfDingbats.xml" style="${src.codegen.fonts.dir}/font-file.xsl" out="${build.gensrc.dir}/org/apache/fop/fonts/base14/ZapfDingbats.java"/>
+ <create-font name="Symbol"/>
+ <create-font name="ZapfDingbats"/>
</target>
<!-- =================================================================== -->
<!-- Compiles the source directory -->
</patternset>
</target>
<target name="junit-compile-java" depends="package, transcoder-pkg, junit-with-xmlunit, junit-without-xmlunit" if="junit.present">
- <mkdir dir="${build.dir}/test-classes"/>
+ <mkdir dir="${build.unit.tests.dir}"/>
<mkdir dir="${build.dir}/test-gensrc"/>
<mkdir dir="${junit.reports.dir}"/>
- <javac destdir="${build.dir}/test-classes" includeAntRuntime="true">
+ <javac destdir="${build.unit.tests.dir}" includeAntRuntime="true">
<src path="${test.dir}/java"/>
<patternset refid="test-sources"/>
<classpath>
</fileset>
</classpath>
</javac>
- <copy todir="${build.dir}/test-classes">
+ <copy todir="${build.unit.tests.dir}">
<fileset dir="${test.dir}/java">
<include name="**/*.xsl"/>
</fileset>
<include name="**/*.java"/>
</fileset>
</eventResourceGenerator>
- <copy todir="${build.dir}/test-classes">
+ <copy todir="${build.unit.tests.dir}">
<fileset dir="${test.dir}/java">
<include name="META-INF/**"/>
<include name="**/*.xml"/>
<target name="junit-compile" depends="junit-compile-java, junit-compile-copy-resources" description="Compiles FOP's JUnit tests" if="junit.present"/>
<target name="junit-transcoder" depends="junit-compile" description="Runs FOP's JUnit transcoder tests" if="junit.present">
<path id="transcoder-classpath">
- <pathelement location="${build.dir}/test-classes"/>
+ <pathelement location="${build.unit.tests.dir}"/>
<path refid="libs-build-classpath"/>
<fileset dir="${build.dir}">
<include name="fop-transcoder.jar"/>
JAR needs to be updated.
-->
<path id="transcoder-all-classpath">
- <pathelement location="${build.dir}/test-classes"/>
+ <pathelement location="${build.unit.tests.dir}"/>
<path refid="libs-build-classpath"/>
<fileset dir="build">
<include name="fop-transcoder-allinone.jar"/>
<echo message="${hyphenation.message}"/>
</target>
<path id="standard-junit-classpath">
- <pathelement location="${build.dir}/test-classes"/>
+ <pathelement location="${build.unit.tests.dir}"/>
<path refid="libs-tools-build-classpath"/>
<pathelement location="${build.dir}/fop.jar"/>
</path>
</junit>
</sequential>
</macrodef>
+ <target name="junit-all" depends="junit-compile, junit-transcoder, junit-layout-hyphenation, setup-xml-schema" description="Runs FOP's JUnit basic tests" if="junit.present">
+ <junit dir="${basedir}" haltonfailure="yes" fork="${junit.fork}" errorproperty="fop.junit.error" failureproperty="fop.junit.failure">
+ <sysproperty key="jawa.awt.headless" value="true"/>
+ <formatter type="brief" usefile="false"/>
+ <formatter type="plain" usefile="true"/>
+ <formatter type="xml" usefile="true"/>
+ <classpath>
+ <path refid="standard-junit-classpath"/>
+ </classpath>
+ <batchtest todir="${junit.reports.dir}">
+ <fileset dir="${build.unit.tests.dir}" includes="**/*TestCase.class"/>
+ </batchtest>
+ </junit>
+ </target>
<target name="junit-basic" depends="junit-compile" description="Runs FOP's JUnit basic tests" if="junit.present">
<junit-run title="Standard test suite" testsuite="org.apache.fop.StandardTestSuite" outfile="TEST-standard-tests-suite"/>
</target>
outfile="TEST-intermediate-format"/>
</target>
<target name="junit-events" depends="junit-compile" description="Runs FOP's event JUnit tests" if="junit.present">
- <junit-run title="event" basedir="test/events" testsuite="org.apache.fop.events.EventProcessingTestCase" outfile="TEST-events"/>
+ <junit-run title="event" testsuite="org.apache.fop.events.EventProcessingTestCase" outfile="TEST-events"/>
</target>
<target name="junit-text-linebreak" depends="junit-compile" description="Runs FOP's JUnit unicode linebreak tests" if="junit.present">
- <junit-run title="Unicode UAX#14 support" testsuite="org.apache.fop.text.linebreak.LineBreakStatusTest" outfile="TEST-linebreak"/>
+ <junit-run title="Unicode UAX#14 support" testsuite="org.apache.fop.text.linebreak.LineBreakStatusTestCase" outfile="TEST-linebreak"/>
</target>
<target name="junit-render-pdf" depends="junit-compile">
<junit-run title="render-pdf" testsuite="org.apache.fop.render.pdf.RenderPDFTestSuite" outfile="TEST-render-pdf"/>
</target>
<target name="junit-reduced" depends="junit-userconfig, junit-basic, junit-transcoder, junit-text-linebreak, junit-fotree, junit-render-pdf"/>
- <target name="junit-full" depends="junit-reduced, junit-layout, junit-area-tree-xml-format, junit-intermediate-format"/>
- <target name="junit" depends="junit-full" description="Runs all of FOP's JUnit tests" if="junit.present">
+ <target name="junit" depends="junit-all" description="Runs all of FOP's JUnit tests" if="junit.present">
<fail><condition><or><isset property="fop.junit.error"/><isset property="fop.junit.failure"/><not><isset property="hyphenation.present"/></not></or></condition>
NOTE:
**************************************************************************
<!-- Special target for Gump -->
<!-- =================================================================== -->
<target name="gump" depends="package,transcoder-pkg"/>
- <target name="gump-test" depends="junit-full">
+ <target name="gump-test" depends="junit-all">
<fail>
<condition>
<or>
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
+import org.apache.xmlgraphics.util.ClasspathResource;
+
import org.apache.fop.apps.FOPException;
import org.apache.fop.fonts.autodetect.FontFileFinder;
import org.apache.fop.util.LogUtil;
-import org.apache.xmlgraphics.util.ClasspathResource;
/**
* Detector of operating system and classpath fonts
private final FontManager fontManager;
private final FontAdder fontAdder;
private final boolean strict;
+ private final FontEventListener eventListener;
/**
* Main constructor
* @param manager the font manager
* @param adder the font adder
* @param strict true if an Exception should be thrown if an error is found.
+ * @param listener for throwing font related events
*/
- public FontDetector(FontManager manager, FontAdder adder, boolean strict) {
+ public FontDetector(FontManager manager, FontAdder adder, boolean strict,
+ FontEventListener listener) {
this.fontManager = manager;
this.fontAdder = adder;
this.strict = strict;
+ this.eventListener = listener;
}
/**
public void detect(List<EmbedFontInfo> fontInfoList) throws FOPException {
// search in font base if it is defined and
// is a directory but don't recurse
- FontFileFinder fontFileFinder = new FontFileFinder();
+ FontFileFinder fontFileFinder = new FontFileFinder(eventListener);
String fontBaseURL = fontManager.getFontBaseURL();
if (fontBaseURL != null) {
try {
getEventProducer().glyphNotAvailable(source, ch, fontName);
}
+ /** {@inheritDoc} */
+ public void fontDirectoryNotFound(Object source, String dir) {
+ getEventProducer().fontDirectoryNotFound(source, dir);
+ }
+
}
*/
void glyphNotAvailable(Object source, char ch, String fontName);
+ /**
+ * An error occurred trying to find the font directory specified in the config file.
+ * @param source the event source
+ * @param dir the directory in the config file
+ */
+ void fontDirectoryNotFound(Object source, String dir);
}
*/
void glyphNotAvailable(Object source, char ch, String fontName);
+ /**
+ * An error occurred trying to find the font directory specified in the config file.
+ * @param source the event sourece
+ * @param dir the directory in the config file
+ * @event.severity WARN
+ */
+ void fontDirectoryNotFound(Object source, String dir);
+
}
<message key="fontSubstituted">Font "{requested}" not found. Substituting with "{effective}".</message>
<message key="fontLoadingErrorAtAutoDetection">Unable to load font file: {fontURL}.[ Reason: {e}]</message>
<message key="glyphNotAvailable">Glyph "{ch}" (0x{ch,hex}[, {ch,glyph-name}]) not available in font "{fontName}".</message>
+ <message key="fontDirectoryNotFound">'{dir}' does not exist or is not a directory.</message>
</catalogue>
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.apache.fop.apps.FOPException;
import org.apache.fop.fonts.autodetect.FontFileFinder;
import org.apache.fop.fonts.autodetect.FontInfoFinder;
// native o/s search (autodetect) configuration
boolean autodetectFonts = (fontsCfg.getChild("auto-detect", false) != null);
if (autodetectFonts) {
- FontDetector fontDetector = new FontDetector(fontManager, fontAdder, strict);
+ FontDetector fontDetector = new FontDetector(fontManager, fontAdder, strict,
+ listener);
fontDetector.detect(fontInfoList);
}
}
// add fonts found in directory
- FontFileFinder fontFileFinder = new FontFileFinder(recursive ? -1 : 1);
+ FontFileFinder fontFileFinder = new FontFileFinder(recursive ? -1 : 1, listener);
List<URL> fontURLList;
try {
fontURLList = fontFileFinder.find(directory);
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.apache.fop.fonts.FontEventListener;
+
/**
* Helps to autodetect/locate available operating system fonts.
*/
/** default depth limit of recursion when searching for font files **/
public static final int DEFAULT_DEPTH_LIMIT = -1;
+ private final FontEventListener eventListener;
/**
* Default constructor
+ * @param listener for throwing font related events
*/
- public FontFileFinder() {
- super(getDirectoryFilter(), getFileFilter(), DEFAULT_DEPTH_LIMIT);
+ public FontFileFinder(FontEventListener listener) {
+ this(DEFAULT_DEPTH_LIMIT, listener);
}
/**
* Constructor
* @param depthLimit recursion depth limit
+ * @param listener for throwing font related events
*/
- public FontFileFinder(int depthLimit) {
+ public FontFileFinder(int depthLimit, FontEventListener listener) {
super(getDirectoryFilter(), getFileFilter(), depthLimit);
+ eventListener = listener;
}
/**
public List<URL> find(String dir) throws IOException {
List<URL> results = new java.util.ArrayList<URL>();
super.walk(new File(dir), results);
+ File directory = new File(dir);
+ if (!directory.isDirectory()) {
+ eventListener.fontDirectoryNotFound(this, dir);
+ } else {
+ super.walk(directory, results);
+ }
return results;
}
}
//ignore
}
+ public void fontDirectoryNotFound(Object source, String msg) {
+ //ignore
+ }
+
};
FontListGenerator listGenerator = new FontListGenerator();
documents. Example: the fix of marks layering will be such a case when it's done.
-->
<release version="FOP Trunk" date="TBD">
+ <action context="Code" dev="VH" type="add" fixes-bug="52136" due-to="Mehdi Houshmand">
+ Added to build file JUnit target that uses a regex to run all of the test cases. This
+ reduces the risk that some of them are omitted when building FOP.
+ </action>
<action context="Code" dev="PH" type="add" fixes-bug="52089" due-to="JM, Mehdi Houshmand">
Allow JPEG images to be embedded in an AFP document as is, without being decoded and
encoded.
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.InputStream;
+
+import org.apache.batik.transcoder.Transcoder;
+import org.apache.batik.transcoder.TranscoderInput;
+import org.apache.batik.transcoder.TranscoderOutput;
+import org.apache.commons.io.output.ByteArrayOutputStream;
+import org.junit.Test;
+
+/**
+ * Basic runtime test for FOP's transcoders. It is used to verify that
+ * nothing obvious is broken after compiling.
+ */
+public abstract class AbstractBasicTranscoderTest extends AbstractFOPTest {
+
+ /**
+ * Creates the transcoder to test.
+ * @return the newly instantiated transcoder
+ */
+ protected abstract Transcoder createTranscoder();
+
+ /**
+ * Runs the PDF transcoder as if it were called by Batik's rasterizer.
+ * Without special configuration stuff.
+ * @throws Exception if a problem occurs
+ */
+ @Test
+ public void testGenericPDFTranscoder() throws Exception {
+ //Create transcoder
+ Transcoder transcoder = createTranscoder();
+
+ //Setup input
+ File svgFile = new File(getBaseDir(), "test/resources/fop/svg/text.svg");
+ InputStream in = new java.io.FileInputStream(svgFile);
+ try {
+ TranscoderInput input = new TranscoderInput(in);
+
+ //Setup output
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ try {
+ TranscoderOutput output = new TranscoderOutput(out);
+
+ //Do the transformation
+ transcoder.transcode(input, output);
+ } finally {
+ out.close();
+ }
+ assertTrue("Some output expected", out.size() > 0);
+ } finally {
+ in.close();
+ }
+ }
+
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop;
-
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.InputStream;
-
-import org.apache.batik.transcoder.Transcoder;
-import org.apache.batik.transcoder.TranscoderInput;
-import org.apache.batik.transcoder.TranscoderOutput;
-import org.apache.commons.io.output.ByteArrayOutputStream;
-import org.junit.Test;
-
-/**
- * Basic runtime test for FOP's transcoders. It is used to verify that
- * nothing obvious is broken after compiling.
- */
-public abstract class AbstractBasicTranscoderTestCase extends AbstractFOPTestCase {
-
- /**
- * Creates the transcoder to test.
- * @return the newly instantiated transcoder
- */
- protected abstract Transcoder createTranscoder();
-
- /**
- * Runs the PDF transcoder as if it were called by Batik's rasterizer.
- * Without special configuration stuff.
- * @throws Exception if a problem occurs
- */
- @Test
- public void testGenericPDFTranscoder() throws Exception {
- //Create transcoder
- Transcoder transcoder = createTranscoder();
-
- //Setup input
- File svgFile = new File(getBaseDir(), "test/resources/fop/svg/text.svg");
- InputStream in = new java.io.FileInputStream(svgFile);
- try {
- TranscoderInput input = new TranscoderInput(in);
-
- //Setup output
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- try {
- TranscoderOutput output = new TranscoderOutput(out);
-
- //Do the transformation
- transcoder.transcode(input, output);
- } finally {
- out.close();
- }
- assertTrue("Some output expected", out.size() > 0);
- } finally {
- in.close();
- }
- }
-
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop;
+
+import java.io.File;
+
+/**
+ * Abstract base test class for FOP's tests.
+ */
+public abstract class AbstractFOPTest {
+
+ /**
+ * Returns the base directory to use for the tests.
+ * @return the base directory
+ */
+ protected static File getBaseDir() {
+ return new File(".");
+ }
+
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop;
-
-import java.io.File;
-
-/**
- * Abstract base test class for FOP's tests.
- */
-public abstract class AbstractFOPTestCase {
-
- /**
- * Returns the base directory to use for the tests.
- * @return the base directory
- */
- protected static File getBaseDir() {
- String basedir = System.getProperty("basedir");
- if (basedir != null) {
- return new File(basedir);
- } else {
- return new File(".");
- }
- }
-
-}
* Basic runtime test for the old Fop class. It is used to verify that
* nothing obvious is broken after compiling.
*/
-public class BasicDriverTestCase extends AbstractFOPTestCase {
+public class BasicDriverTestCase extends AbstractFOPTest {
private FopFactory fopFactory = FopFactory.newInstance();
* Basic runtime test for the PDF transcoder. It is used to verify that
* nothing obvious is broken after compiling.
*/
-public class BasicPDFTranscoderTestCase extends AbstractBasicTranscoderTestCase {
+public class BasicPDFTranscoderTestCase extends AbstractBasicTranscoderTest {
@Override
protected Transcoder createTranscoder() {
* Basic runtime test for the PS transcoder. It is used to verify that
* nothing obvious is broken after compiling.
*/
-public class BasicPSTranscoderTestCase extends AbstractBasicTranscoderTestCase {
+public class BasicPSTranscoderTestCase extends AbstractBasicTranscoderTest {
@Override
protected Transcoder createTranscoder() {
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop;
-import static org.junit.Assert.fail;
-
-import java.io.ByteArrayOutputStream;
-import java.io.StringReader;
-import java.security.DigestOutputStream;
-import java.security.MessageDigest;
-import java.util.Date;
-
-import javax.xml.parsers.SAXParserFactory;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.xml.sax.InputSource;
-
-import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.apps.Fop;
-import org.apache.fop.apps.FopFactory;
-import org.apache.fop.apps.MimeConstants;
-import org.apache.fop.util.DigestFilter;
-
-/**
- * Framework for simple regression testing.
- * The testcase reads a control XML file which specifies a FO source,
- * a MD5 for the source to help diferentiating failures caused by causal
- * source modification from failures caused by regression, a renderer (only
- * PDF currently supported) and a MD5 for the result.
- *
- */
-public final class GenericFOPTestCase {
-
- // configure fopFactory as desired
- private FopFactory fopFactory = FopFactory.newInstance();
-
- private SAXParserFactory parserFactory;
-
- @Before
- public void setUp() throws Exception {
- parserFactory = SAXParserFactory.newInstance();
- parserFactory.setNamespaceAware(true);
- }
-
- @org.junit.Test
- public void testSimple() throws Exception {
- final String digestIn = "17bf13298796065f7775db8707133aeb";
- final String digestOut = "e2761f51152f6663911e567901596707";
- final String fo
- = "<fo:root xmlns:fo='http://www.w3.org/1999/XSL/Format'>"
- + " <fo:layout-master-set>"
- + " <fo:simple-page-master master-name='simple'"
- + " page-height='25cm' page-width='20cm'>"
- + " <fo:region-body/>"
- + " </fo:simple-page-master>"
- + " </fo:layout-master-set>"
- + " <fo:page-sequence master-reference='simple'>"
- + " <fo:flow flow-name='xsl-region-body'>"
- + " <fo:block>This is a blind text.</fo:block>"
- + " </fo:flow>"
- + " </fo:page-sequence>"
- + "</fo:root>";
- renderPDF(fo, digestIn, digestOut);
- }
-
- private String digestToString(byte[] value) {
- StringBuffer buffer = new StringBuffer(2 * value.length);
- for (int i = 0; i < value.length; i++) {
- int val = value[i];
- int hi = (val >> 4) & 0xF;
- int lo = val & 0xF;
- if (hi < 10) {
- buffer.append((char) (hi + 0x30));
- } else {
- buffer.append((char) (hi + 0x61 - 10));
- }
- if (lo < 10) {
- buffer.append((char) (lo + 0x30));
- } else {
- buffer.append((char) (lo + 0x61 - 10));
- }
- }
- return buffer.toString();
- }
-
- private void renderPDF(String fo, String digestIn, String digestOut)
- throws Exception {
- FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
- foUserAgent.setCreationDate(new Date(10000));
- MessageDigest outDigest = MessageDigest.getInstance("MD5");
- DigestOutputStream out = new DigestOutputStream(new ByteArrayOutputStream(), outDigest);
- Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
- InputSource source = new InputSource(new StringReader(fo));
- DigestFilter filter = new DigestFilter("MD5");
- filter.setParent(parserFactory.newSAXParser().getXMLReader());
- filter.setContentHandler(fop.getDefaultHandler());
- filter.parse(source);
- String digestInActual = digestToString(filter.getDigestValue());
- if (!digestIn.equals(digestInActual)) {
- fail("input MD5: was " + digestInActual + ", expected " + digestIn);
- }
- String digestOutActual = digestToString(outDigest.digest());
- if (!digestOut.equals(digestOutActual)) {
- fail(
- "output MD5: was "
- + digestOutActual
- + ", expected "
- + digestOut);
- }
- }
-
-}
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
-import org.apache.fop.afp.fonts.CharactersetEncoderTest;
+import org.apache.fop.afp.fonts.CharactersetEncoderTestCase;
import org.apache.fop.afp.parser.MODCAParserTestCase;
import org.apache.fop.area.ViewportTestSuite;
-import org.apache.fop.fonts.DejaVuLGCSerifTest;
+import org.apache.fop.fonts.DejaVuLGCSerifTestCase;
import org.apache.fop.fonts.truetype.GlyfTableTestCase;
import org.apache.fop.image.loader.batik.ImageLoaderTestCase;
import org.apache.fop.image.loader.batik.ImagePreloaderTestCase;
import org.apache.fop.intermediate.IFMimickingTestCase;
-import org.apache.fop.render.extensions.prepress.PageBoundariesTest;
-import org.apache.fop.render.extensions.prepress.PageScaleTest;
+import org.apache.fop.render.extensions.prepress.PageBoundariesTestCase;
+import org.apache.fop.render.extensions.prepress.PageScaleTestCase;
import org.apache.fop.render.pdf.PDFAConformanceTestCase;
import org.apache.fop.render.pdf.PDFCMapTestCase;
import org.apache.fop.render.pdf.PDFEncodingTestCase;
import org.apache.fop.render.pdf.RenderPDFTestSuite;
import org.apache.fop.render.ps.PSTestSuite;
import org.apache.fop.render.rtf.RichTextFormatTestSuite;
-import org.apache.fop.traits.MinOptMaxTest;
+import org.apache.fop.traits.MinOptMaxTestCase;
/**
* Test suite for basic functionality of FOP.
PDFEncodingTestCase.class,
PDFCMapTestCase.class,
PDFsRGBSettingsTestCase.class,
- DejaVuLGCSerifTest.class,
+ DejaVuLGCSerifTestCase.class,
RichTextFormatTestSuite.class,
ImageLoaderTestCase.class,
ImagePreloaderTestCase.class,
IFMimickingTestCase.class,
- PageBoundariesTest.class,
- PageScaleTest.class,
+ PageBoundariesTestCase.class,
+ PageScaleTestCase.class,
org.apache.fop.afp.AFPTestSuite.class,
GlyfTableTestCase.class,
ViewportTestSuite.class,
RenderPDFTestSuite.class,
MODCAParserTestCase.class,
- CharactersetEncoderTest.class,
+ CharactersetEncoderTestCase.class,
org.apache.fop.render.afp.AFPTestSuite.class,
PSTestSuite.class,
- MinOptMaxTest.class
+ MinOptMaxTestCase.class
})
public class StandardTestSuite {
}
/**
* Tests URI resolution facilities.
*/
-public class URIResolutionTestCase extends AbstractFOPTestCase {
+public class URIResolutionTestCase extends AbstractFOPTest {
// configure fopFactory as desired
private FopFactory fopFactory = FopFactory.newInstance();
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.afp.fonts;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.charset.CharacterCodingException;
-
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * Test {@link CharactersetEncoder}
- */
-public class CharactersetEncoderTest {
- private CharactersetEncoder singlebyteEncoder;
- private CharactersetEncoder doublebyteEncoder;
-
- @Before
- public void setUp() {
- singlebyteEncoder = CharactersetEncoder.newInstance("cp500", false);
- doublebyteEncoder = CharactersetEncoder.newInstance("cp937", true);
- }
-
- // This is just an arbitrary CJK string
- private final String testCJKText = "\u8ACB\u65BC\u627F\u505A\u65E5\u4E03\u65E5\u5167\u672A\u9054"
- + "\u4E03\u65E5\u4E4B\u5B9A\u5B58\u8005\u4EE5\u5BE6\u969B\u5230\u671F\u65E5\u5167\u78BA"
- + "\u8A8D\u672C\u4EA4\u6613\u5167\u5BB9\u3002\u5982\u672A\u65BC\u4E0A\u8FF0\u671F\u9593"
- + "\u5167\u63D0\u51FA\u7570\u8B70\uFF0C\u8996\u540C\u610F\u627F\u8A8D\u672C\u4EA4\u6613"
- + "\u3002";
-
- private final byte[] test6CJKChars = {
- (byte) 0x61, (byte) 0x99,
- (byte) 0x50, (byte) 0xf4,
- (byte) 0x50, (byte) 0xd4,
- (byte) 0x56, (byte) 0x99,
- (byte) 0x4c, (byte) 0xc9,
- (byte) 0x4c, (byte) 0x44 };
-
- private final String testEngText = "Hello World!";
- private final byte[] testEngChars = {
- (byte) 0xc8, // H
- (byte) 0x85, // e
- (byte) 0x93, // l
- (byte) 0x93, // l
- (byte) 0x96, // o
- (byte) 0x40, // " "
- (byte) 0xe6, // W
- (byte) 0x96, // o
- (byte) 0x99, // r
- (byte) 0x93, // l
- (byte) 0x84, // d
- (byte) 0x4f // !
- };
-
- /**
- * Tests canEncode() - tests that canEncode() responds properly to various input characters.
- */
- @Test
- public void testCanEncode() {
- // Both SBCS and DBCS should support Latin characters
- for (char c = '!'; c < '~'; c++) {
- assertTrue(singlebyteEncoder.canEncode(c));
- assertTrue(doublebyteEncoder.canEncode(c));
- }
- // ONLY the double byte characters can handle CJK text
- for (char c : testCJKText.toCharArray()) {
- assertFalse(singlebyteEncoder.canEncode(c));
- assertTrue(doublebyteEncoder.canEncode(c));
- }
- // Ensure that double byte encoder doesn't just return true all the time...
- assertFalse(doublebyteEncoder.canEncode('\u00BB'));
- }
-
- @Test
- public void testEncode() throws CharacterCodingException, IOException {
- CharactersetEncoder.EncodedChars encChars;// = doublebyteEncoder.encode(testCJKText);
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
- // JAVA 1.5 has a bug in the JVM in which these err for some reason... JAVA 1.6 no issues
- /*encChars.writeTo(bOut, 0, encChars.getLength());
- byte[] bytes = bOut.toByteArray();
- for (int i = 0; i < 12; i++) {
- assertEquals(test6CJKChars[i], bytes[i]);
- }
- bOut.reset();*/
-
- encChars = singlebyteEncoder.encode(testEngText);
- encChars.writeTo(bOut, 0, encChars.getLength());
- byte[] engBytes = bOut.toByteArray();
- for (int i = 0; i < testEngChars.length; i++) {
- assertEquals(testEngChars[i], engBytes[i]);
- }
- assertEquals(testEngChars.length, engBytes.length);
- }
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.afp.fonts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.charset.CharacterCodingException;
+
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Test {@link CharactersetEncoder}
+ */
+public class CharactersetEncoderTestCase {
+ private CharactersetEncoder singlebyteEncoder;
+ private CharactersetEncoder doublebyteEncoder;
+
+ @Before
+ public void setUp() {
+ singlebyteEncoder = CharactersetEncoder.newInstance("cp500", false);
+ doublebyteEncoder = CharactersetEncoder.newInstance("cp937", true);
+ }
+
+ // This is just an arbitrary CJK string
+ private final String testCJKText = "\u8ACB\u65BC\u627F\u505A\u65E5\u4E03\u65E5\u5167\u672A\u9054"
+ + "\u4E03\u65E5\u4E4B\u5B9A\u5B58\u8005\u4EE5\u5BE6\u969B\u5230\u671F\u65E5\u5167\u78BA"
+ + "\u8A8D\u672C\u4EA4\u6613\u5167\u5BB9\u3002\u5982\u672A\u65BC\u4E0A\u8FF0\u671F\u9593"
+ + "\u5167\u63D0\u51FA\u7570\u8B70\uFF0C\u8996\u540C\u610F\u627F\u8A8D\u672C\u4EA4\u6613"
+ + "\u3002";
+
+ private final byte[] test6CJKChars = {
+ (byte) 0x61, (byte) 0x99,
+ (byte) 0x50, (byte) 0xf4,
+ (byte) 0x50, (byte) 0xd4,
+ (byte) 0x56, (byte) 0x99,
+ (byte) 0x4c, (byte) 0xc9,
+ (byte) 0x4c, (byte) 0x44 };
+
+ private final String testEngText = "Hello World!";
+ private final byte[] testEngChars = {
+ (byte) 0xc8, // H
+ (byte) 0x85, // e
+ (byte) 0x93, // l
+ (byte) 0x93, // l
+ (byte) 0x96, // o
+ (byte) 0x40, // " "
+ (byte) 0xe6, // W
+ (byte) 0x96, // o
+ (byte) 0x99, // r
+ (byte) 0x93, // l
+ (byte) 0x84, // d
+ (byte) 0x4f // !
+ };
+
+ /**
+ * Tests canEncode() - tests that canEncode() responds properly to various input characters.
+ */
+ @Test
+ public void testCanEncode() {
+ // Both SBCS and DBCS should support Latin characters
+ for (char c = '!'; c < '~'; c++) {
+ assertTrue(singlebyteEncoder.canEncode(c));
+ assertTrue(doublebyteEncoder.canEncode(c));
+ }
+ // ONLY the double byte characters can handle CJK text
+ for (char c : testCJKText.toCharArray()) {
+ assertFalse(singlebyteEncoder.canEncode(c));
+ assertTrue(doublebyteEncoder.canEncode(c));
+ }
+ // Ensure that double byte encoder doesn't just return true all the time...
+ assertFalse(doublebyteEncoder.canEncode('\u00BB'));
+ }
+
+ @Test
+ public void testEncode() throws CharacterCodingException, IOException {
+ CharactersetEncoder.EncodedChars encChars;// = doublebyteEncoder.encode(testCJKText);
+ ByteArrayOutputStream bOut = new ByteArrayOutputStream();
+ // JAVA 1.5 has a bug in the JVM in which these err for some reason... JAVA 1.6 no issues
+ /*encChars.writeTo(bOut, 0, encChars.getLength());
+ byte[] bytes = bOut.toByteArray();
+ for (int i = 0; i < 12; i++) {
+ assertEquals(test6CJKChars[i], bytes[i]);
+ }
+ bOut.reset();*/
+
+ encChars = singlebyteEncoder.encode(testEngText);
+ encChars.writeTo(bOut, 0, encChars.getLength());
+ byte[] engBytes = bOut.toByteArray();
+ for (int i = 0; i < testEngChars.length; i++) {
+ assertEquals(testEngChars[i], engBytes[i]);
+ }
+ assertEquals(testEngChars.length, engBytes.length);
+ }
+}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.afp.modca;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.fop.afp.Streamable;
+import org.junit.Test;
+
+/**
+ * Tests the {@link AbstractAFPObject} class.
+ */
+public abstract class AbstractAFPObjectTest<S extends AbstractAFPObject> {
+
+ private S sut;
+
+ protected final S getSut() {
+ return sut;
+ }
+
+ protected final void setSut(S sut) {
+ if ( this.sut == null) {
+ this.sut = sut;
+ }
+ }
+
+
+ private byte[] header = new byte[] {
+ 0x5A, // Structured field identifier
+ 0x00, // Length byte 1
+ 0x10, // Length byte 2
+ 0x00, // Structured field id byte 1
+ 0x00, // Structured field id byte 2
+ 0x00, // Structured field id byte 3
+ 0x00, // Flags
+ 0x00, // Reserved
+ 0x00 // Reserved
+ };
+
+ @Test
+ public void testCopySFStatic() {
+ byte[] actual = new byte[9];
+ Arrays.fill(actual, (byte)-1);
+
+ S.copySF(actual, (byte)0, (byte)0, (byte)0);
+
+ assertTrue(Arrays.equals(actual, header));
+
+ byte[] expected2 = new byte[9];
+ System.arraycopy(header, 0, expected2, 0, header.length);
+
+ final byte clazz = (byte) 0x01;
+ final byte type = (byte) 0x02;
+ final byte catagory = (byte) 0x03;
+ expected2[3] = clazz;
+ expected2[4] = type;
+ expected2[5] = catagory;
+
+ AbstractAFPObject.copySF(actual, clazz, type, catagory);
+
+ assertTrue(Arrays.equals(actual, expected2));
+ }
+
+ @Test
+ public void testCopySF() {
+ byte[] expected = new byte[9];
+ S.copySF(expected, (byte) 0xD3, (byte)0, (byte)0);
+
+ byte[] actual = new byte[9];
+ Arrays.fill(actual, (byte)-1);
+
+ getSut().copySF(actual, (byte)0, (byte)0);
+
+ assertTrue(Arrays.equals(actual, expected));
+
+ byte[] expected2 = new byte[9];
+ System.arraycopy(expected, 0, expected2, 0, expected.length);
+
+ final byte type = (byte)1;
+ final byte catagory = (byte)2;
+ expected2[4] = type;
+ expected2[5] = catagory;
+
+ getSut().copySF(actual, type, catagory);
+
+ assertTrue(Arrays.equals(actual, expected2));
+ }
+
+ /**
+ *
+ */
+ @Test
+ public void testwriteObjects() {
+ final byte[][] expected = {{(byte)0, (byte)1}, {(byte)2, (byte)3}, {(byte)4, (byte)5}};
+
+ List<Streamable> objects = new ArrayList<Streamable>() {
+ {
+ add(StreamableObject.instance(expected[0]));
+ add(StreamableObject.instance(expected[1]));
+ add(StreamableObject.instance(expected[2]));
+ } };
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ try {
+ getSut().writeObjects(objects, baos);
+ } catch (IOException e) {
+ fail();
+ }
+
+ byte[] actual = baos.toByteArray();
+
+ int index = 0;
+ for (int i = 0; i < expected.length; i++) {
+ for (int j = 0; j < expected[i].length; j++) {
+ assertTrue("" + index, actual[index] == expected[i][j]);
+ index++;
+ }
+ }
+ }
+
+ /**
+ *
+ */
+ @Test
+ public void testTruncate() {
+ String expected = "abc";
+ assertTrue(AbstractAFPObject.truncate(expected, 4) == expected);
+ assertTrue(AbstractAFPObject.truncate(expected, 3) == expected);
+ assertEquals(AbstractAFPObject.truncate(expected + "d", 3), expected);
+ assertEquals(AbstractAFPObject.truncate(expected, 0), "");
+ try {
+ assertTrue(AbstractAFPObject.truncate(null, 4) == null);
+ fail();
+ } catch (NullPointerException e) {
+ // PASS
+ }
+ }
+
+ /**
+ *
+ */
+ @Test
+ public void testWriteChunksToStream() throws IOException {
+ final byte[] data = new byte[256];
+ int counter = 0;
+ for (int i = 0; i < data.length; i++) {
+ data[i] = (byte) counter++;
+ }
+
+ byte[] header = new byte[9];
+ // Test when chunk size % data.length == 0
+ testWithGivenChunkSize(data, header, 16);
+
+ // test when chunk size % data.length != 0
+ testWithGivenChunkSize(data, header, 10);
+
+ // test with an odd number...
+ testWithGivenChunkSize(data, header, 13);
+ }
+
+ private void testWithGivenChunkSize(byte[] data, byte[] header, int chunkSize)
+ throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ S.writeChunksToStream(data, header, 0, chunkSize, baos);
+ byte[] testData = baos.toByteArray();
+
+ int numberOfFullDataChunks = data.length / chunkSize;
+ int lastChunkSize = data.length % chunkSize;
+ int lengthOfTestData = numberOfFullDataChunks * (chunkSize + header.length);
+ lengthOfTestData += lastChunkSize == 0 ? 0 : header.length + lastChunkSize;
+
+ putLengthInHeader(header, chunkSize);
+
+ assertEquals(lengthOfTestData, testData.length);
+ int testIndex = 0;
+ int expectedIndex = 0;
+ for (int i = 0; i < numberOfFullDataChunks; i++) {
+ checkHeaderAndData(header, data, testData, expectedIndex, testIndex, chunkSize);
+ expectedIndex += chunkSize + header.length;
+ testIndex += chunkSize;
+ }
+
+ putLengthInHeader(header, lastChunkSize);
+ // check last chunk
+ if (lastChunkSize != 0) {
+ checkHeaderAndData(header, data, testData, expectedIndex, testIndex, lastChunkSize);
+ }
+ }
+
+ private void putLengthInHeader(byte[] header, int chunkSize) {
+ header[0] = 0;
+ header[1] = (byte) (chunkSize + header.length);
+ }
+
+ private void checkHeaderAndData(byte[] header, byte[] data, byte[] testData, int expectedIndex,
+ int testIndex, int chunkSize) {
+ for (int i = 0; i < header.length; i++) {
+ assertEquals(testData[expectedIndex++], header[i]);
+ }
+ for (int i = 0; i < chunkSize; i++) {
+ assertEquals(testData[expectedIndex++], data[i + testIndex]);
+ }
+ }
+
+ /**
+ *
+ */
+ private static class StreamableObject implements Streamable {
+ private byte[] bytes;
+
+ StreamableObject(byte[] bytes) {
+ this.bytes = new byte[bytes.length];
+ System.arraycopy(bytes, 0, this.bytes, 0, bytes.length);
+ }
+
+ private static Streamable instance(byte[] bytes) {
+ return new StreamableObject(bytes);
+ }
+
+ public void writeToStream(OutputStream os) throws IOException {
+ os.write(bytes);
+ }
+ }
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.afp.modca;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.fop.afp.Streamable;
-import org.junit.Test;
-
-/**
- * Tests the {@link AbstractAFPObject} class.
- */
-public abstract class AbstractAFPObjectTestCase<S extends AbstractAFPObject> {
-
- private S sut;
-
- protected final S getSut() {
- return sut;
- }
-
- protected final void setSut(S sut) {
- if ( this.sut == null) {
- this.sut = sut;
- }
- }
-
-
- private byte[] header = new byte[] {
- 0x5A, // Structured field identifier
- 0x00, // Length byte 1
- 0x10, // Length byte 2
- 0x00, // Structured field id byte 1
- 0x00, // Structured field id byte 2
- 0x00, // Structured field id byte 3
- 0x00, // Flags
- 0x00, // Reserved
- 0x00 // Reserved
- };
-
- @Test
- public void testCopySFStatic() {
- byte[] actual = new byte[9];
- Arrays.fill(actual, (byte)-1);
-
- S.copySF(actual, (byte)0, (byte)0, (byte)0);
-
- assertTrue(Arrays.equals(actual, header));
-
- byte[] expected2 = new byte[9];
- System.arraycopy(header, 0, expected2, 0, header.length);
-
- final byte clazz = (byte) 0x01;
- final byte type = (byte) 0x02;
- final byte catagory = (byte) 0x03;
- expected2[3] = clazz;
- expected2[4] = type;
- expected2[5] = catagory;
-
- AbstractAFPObject.copySF(actual, clazz, type, catagory);
-
- assertTrue(Arrays.equals(actual, expected2));
- }
-
- @Test
- public void testCopySF() {
- byte[] expected = new byte[9];
- S.copySF(expected, (byte) 0xD3, (byte)0, (byte)0);
-
- byte[] actual = new byte[9];
- Arrays.fill(actual, (byte)-1);
-
- getSut().copySF(actual, (byte)0, (byte)0);
-
- assertTrue(Arrays.equals(actual, expected));
-
- byte[] expected2 = new byte[9];
- System.arraycopy(expected, 0, expected2, 0, expected.length);
-
- final byte type = (byte)1;
- final byte catagory = (byte)2;
- expected2[4] = type;
- expected2[5] = catagory;
-
- getSut().copySF(actual, type, catagory);
-
- assertTrue(Arrays.equals(actual, expected2));
- }
-
- /**
- *
- */
- @Test
- public void testwriteObjects() {
- final byte[][] expected = {{(byte)0, (byte)1}, {(byte)2, (byte)3}, {(byte)4, (byte)5}};
-
- List<Streamable> objects = new ArrayList<Streamable>() {
- {
- add(StreamableObject.instance(expected[0]));
- add(StreamableObject.instance(expected[1]));
- add(StreamableObject.instance(expected[2]));
- } };
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- try {
- getSut().writeObjects(objects, baos);
- } catch (IOException e) {
- fail();
- }
-
- byte[] actual = baos.toByteArray();
-
- int index = 0;
- for (int i = 0; i < expected.length; i++) {
- for (int j = 0; j < expected[i].length; j++) {
- assertTrue("" + index, actual[index] == expected[i][j]);
- index++;
- }
- }
- }
-
- /**
- *
- */
- @Test
- public void testTruncate() {
- String expected = "abc";
- assertTrue(AbstractAFPObject.truncate(expected, 4) == expected);
- assertTrue(AbstractAFPObject.truncate(expected, 3) == expected);
- assertEquals(AbstractAFPObject.truncate(expected + "d", 3), expected);
- assertEquals(AbstractAFPObject.truncate(expected, 0), "");
- try {
- assertTrue(AbstractAFPObject.truncate(null, 4) == null);
- fail();
- } catch (NullPointerException e) {
- // PASS
- }
- }
-
- /**
- *
- */
- @Test
- public void testWriteChunksToStream() throws IOException {
- final byte[] data = new byte[256];
- int counter = 0;
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) counter++;
- }
-
- byte[] header = new byte[9];
- // Test when chunk size % data.length == 0
- testWithGivenChunkSize(data, header, 16);
-
- // test when chunk size % data.length != 0
- testWithGivenChunkSize(data, header, 10);
-
- // test with an odd number...
- testWithGivenChunkSize(data, header, 13);
- }
-
- private void testWithGivenChunkSize(byte[] data, byte[] header, int chunkSize)
- throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- S.writeChunksToStream(data, header, 0, chunkSize, baos);
- byte[] testData = baos.toByteArray();
-
- int numberOfFullDataChunks = data.length / chunkSize;
- int lastChunkSize = data.length % chunkSize;
- int lengthOfTestData = numberOfFullDataChunks * (chunkSize + header.length);
- lengthOfTestData += lastChunkSize == 0 ? 0 : header.length + lastChunkSize;
-
- putLengthInHeader(header, chunkSize);
-
- assertEquals(lengthOfTestData, testData.length);
- int testIndex = 0;
- int expectedIndex = 0;
- for (int i = 0; i < numberOfFullDataChunks; i++) {
- checkHeaderAndData(header, data, testData, expectedIndex, testIndex, chunkSize);
- expectedIndex += chunkSize + header.length;
- testIndex += chunkSize;
- }
-
- putLengthInHeader(header, lastChunkSize);
- // check last chunk
- if (lastChunkSize != 0) {
- checkHeaderAndData(header, data, testData, expectedIndex, testIndex, lastChunkSize);
- }
- }
-
- private void putLengthInHeader(byte[] header, int chunkSize) {
- header[0] = 0;
- header[1] = (byte) (chunkSize + header.length);
- }
-
- private void checkHeaderAndData(byte[] header, byte[] data, byte[] testData, int expectedIndex,
- int testIndex, int chunkSize) {
- for (int i = 0; i < header.length; i++) {
- assertEquals(testData[expectedIndex++], header[i]);
- }
- for (int i = 0; i < chunkSize; i++) {
- assertEquals(testData[expectedIndex++], data[i + testIndex]);
- }
- }
-
- /**
- *
- */
- private static class StreamableObject implements Streamable {
- private byte[] bytes;
-
- StreamableObject(byte[] bytes) {
- this.bytes = new byte[bytes.length];
- System.arraycopy(bytes, 0, this.bytes, 0, bytes.length);
- }
-
- private static Streamable instance(byte[] bytes) {
- return new StreamableObject(bytes);
- }
-
- public void writeToStream(OutputStream os) throws IOException {
- os.write(bytes);
- }
- }
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.afp.modca;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+
+import org.junit.Test;
+
+/**
+ * Tests the {@linkplain AbstractAFPObject} class.
+ */
+public abstract class AbstractNamedAFPObjectTest<S extends AbstractNamedAFPObject>
+ extends AbstractAFPObjectTest<S> {
+ @Test
+ public void testCopySF() {
+
+ final S sut = getSut();
+
+ byte[] expected = new byte[17];
+ S.copySF(expected, (byte) 0xD3, (byte)0, (byte)0);
+
+ byte[] nameData = sut.getNameBytes();
+ System.arraycopy(nameData, 0, expected, 9, nameData.length);
+
+ byte[] actual = new byte[17];
+ Arrays.fill(actual, (byte)-1);
+
+ getSut().copySF(actual, (byte)0, (byte)0);
+
+ assertTrue(Arrays.equals(actual, expected));
+
+ byte[] expected2 = new byte[17];
+ System.arraycopy(expected, 0, expected2, 0, expected.length);
+ System.arraycopy(nameData, 0, expected, 9, nameData.length);
+
+ final byte type = (byte)1;
+ final byte catagory = (byte)2;
+ expected2[4] = type;
+ expected2[5] = catagory;
+
+ getSut().copySF(actual, type, catagory);
+
+ assertTrue(Arrays.equals(actual, expected2));
+ }
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.afp.modca;
-
-import static org.junit.Assert.assertTrue;
-
-import java.util.Arrays;
-
-import org.junit.Test;
-
-/**
- * Tests the {@linkplain AbstractAFPObject} class.
- */
-public abstract class AbstractNamedAFPObjectTestCase<S extends AbstractNamedAFPObject>
- extends AbstractAFPObjectTestCase<S> {
- @Test
- public void testCopySF() {
-
- final S sut = getSut();
-
- byte[] expected = new byte[17];
- S.copySF(expected, (byte) 0xD3, (byte)0, (byte)0);
-
- byte[] nameData = sut.getNameBytes();
- System.arraycopy(nameData, 0, expected, 9, nameData.length);
-
- byte[] actual = new byte[17];
- Arrays.fill(actual, (byte)-1);
-
- getSut().copySF(actual, (byte)0, (byte)0);
-
- assertTrue(Arrays.equals(actual, expected));
-
- byte[] expected2 = new byte[17];
- System.arraycopy(expected, 0, expected2, 0, expected.length);
- System.arraycopy(nameData, 0, expected, 9, nameData.length);
-
- final byte type = (byte)1;
- final byte catagory = (byte)2;
- expected2[4] = type;
- expected2[5] = catagory;
-
- getSut().copySF(actual, type, catagory);
-
- assertTrue(Arrays.equals(actual, expected2));
- }
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.afp.modca;
+
+import java.io.IOException;
+
+public abstract class AbstractStructuredObjectTest<S extends AbstractStructuredObject> extends AbstractAFPObjectTest<S> {
+
+ /**
+ * Test writeStart() - test that the contract is maintained with
+ * {@link AbstractStructuredObject}.
+ *
+ * @throws IOException
+ */
+ public void testwriteStart() throws IOException {
+ }
+
+ /**
+ * Test writeEnd() - test that the contract is maintained with {@link AbstractStructuredObject}.
+ *
+ * @throws IOException
+ */
+ public void testWriteEnd() throws IOException {
+ }
+
+ /**
+ * Test writeContent() - test that the contract is maintained with
+ * {@link AbstractStructuredObject}.
+ *
+ * @throws IOException
+ */
+ public void testWriteContent() throws IOException {
+ }
+
+ /**
+ * Test writeToStream() - test that the contract is maintained with
+ * {@link AbstractStructuredObject}.
+ *
+ * @throws IOException
+ */
+ public void testWriteToStream() throws IOException {
+ testwriteStart();
+ testWriteEnd();
+ testWriteContent();
+ }
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.afp.modca;
-
-import java.io.IOException;
-
-public abstract class AbstractStructuredObjectTestCase<S extends AbstractStructuredObject> extends AbstractAFPObjectTestCase<S> {
-
- /**
- * Test writeStart() - test that the contract is maintained with
- * {@link AbstractStructuredObject}.
- *
- * @throws IOException
- */
- public void testwriteStart() throws IOException {
- }
-
- /**
- * Test writeEnd() - test that the contract is maintained with {@link AbstractStructuredObject}.
- *
- * @throws IOException
- */
- public void testWriteEnd() throws IOException {
- }
-
- /**
- * Test writeContent() - test that the contract is maintained with
- * {@link AbstractStructuredObject}.
- *
- * @throws IOException
- */
- public void testWriteContent() throws IOException {
- }
-
- /**
- * Test writeToStream() - test that the contract is maintained with
- * {@link AbstractStructuredObject}.
- *
- * @throws IOException
- */
- public void testWriteToStream() throws IOException {
- testwriteStart();
- testWriteEnd();
- testWriteContent();
- }
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.afp.modca;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import org.apache.fop.afp.modca.triplets.AbstractTriplet;
+import org.apache.fop.afp.modca.triplets.AttributeQualifierTriplet;
+import org.apache.fop.afp.modca.triplets.CommentTriplet;
+import org.apache.fop.afp.modca.triplets.ObjectAreaSizeTriplet;
+import org.apache.fop.afp.modca.triplets.Triplet;
+
+/**
+ * Test {@link AbstractTripletStructuredObject}
+ */
+public class AbstractTripletStructuredObjectTest<S extends AbstractTripletStructuredObject>
+ extends AbstractStructuredObjectTest<AbstractTripletStructuredObject> {
+
+ private static final List<AbstractTriplet> TRIPLETS;
+
+ static {
+ List<AbstractTriplet> triplets = new ArrayList<AbstractTriplet>();
+
+ triplets.add(new CommentTriplet((byte) 0x01, "test comment"));
+
+ triplets.add(new AttributeQualifierTriplet(1, 1));
+
+ triplets.add(new ObjectAreaSizeTriplet(10, 20));
+
+ TRIPLETS = Collections.unmodifiableList(triplets);
+ }
+
+ private AbstractTripletStructuredObject emptyStructuredObject
+ = new AbstractTripletStructuredObject() { };
+
+ @Before
+ public void setUp() throws Exception {
+ AbstractTripletStructuredObject sut = getSut();
+
+ for (AbstractTriplet triplet : TRIPLETS) {
+ sut.addTriplet(triplet);
+ }
+ }
+
+
+ /**
+ * Test getTripletLength() - ensure a sum of all enclosing object lengths is returned.
+ */
+ public void testGetTripletLength() {
+
+ int dataLength = 0;
+ for (Triplet t : TRIPLETS) {
+ dataLength += t.getDataLength();
+ }
+ assertEquals(dataLength, getSut().getTripletDataLength());
+ assertEquals(0, emptyStructuredObject.getTripletDataLength());
+ }
+
+ /**
+ * Test hasTriplets()
+ */
+ public void testHasTriplets() {
+ assertTrue(getSut().hasTriplets());
+ assertFalse(emptyStructuredObject.hasTriplets());
+ }
+
+ /**
+ * Test writeTriplets() - Ensure the triplets are written properly.
+ *
+ * @throws IOException -
+ */
+ public void testWriteObjects() throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ for (AbstractTriplet triplet : TRIPLETS) {
+ triplet.writeToStream(baos);
+ }
+ byte[] expected = baos.toByteArray();
+ baos.reset();
+ getSut().writeTriplets(baos);
+ assertTrue(Arrays.equals(expected, baos.toByteArray()));
+
+ baos.reset();
+ // Ensure it doesn't die if no data has been added
+ emptyStructuredObject.writeTriplets(baos);
+ byte[] emptyArray = baos.toByteArray();
+ assertTrue(Arrays.equals(emptyArray, new byte[0]));
+ }
+
+ /**
+ * Test hasTriplet() - ensure both positive and negative values are returned.
+ */
+ public void testHasTriplet() {
+ for (AbstractTriplet triplet : TRIPLETS) {
+ assertTrue(getSut().hasTriplet(triplet.getId()));
+ assertFalse(emptyStructuredObject.hasTriplet(triplet.getId()));
+ }
+ CommentTriplet notInSystem = new CommentTriplet((byte) 0x30, "This should return false");
+ assertFalse(getSut().hasTriplet(notInSystem.getId()));
+ }
+
+ /**
+ * Test addTriplet() - mostly tested above, but check boundary cases
+ */
+ public void testAddTriplet() {
+ // ensure null doesn't kill it... not sure what else to test
+ getSut().addTriplet(null);
+ }
+
+ /**
+ * Test addTriplets() - ensure all triplets are added.
+ */
+ @Test
+ public void testAddTriplets() {
+ // Tested on empty object
+ List<AbstractTriplet> expectedList = TRIPLETS;
+ emptyStructuredObject.addTriplets(expectedList);
+ // checks equals() on each member of both lists
+ assertEquals(expectedList, emptyStructuredObject.getTriplets());
+
+ // Add a list to an already populated list
+ getSut().addTriplets(expectedList);
+
+ List<AbstractTriplet> newExpected = new ArrayList<AbstractTriplet>(expectedList);
+ newExpected.addAll(expectedList);
+ assertEquals(newExpected, getSut().getTriplets());
+
+ // Ensure null doesn't throw exception
+ emptyStructuredObject.addTriplets(null);
+ }
+
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.afp.modca;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.fop.afp.modca.triplets.AbstractTriplet;
-import org.apache.fop.afp.modca.triplets.AttributeQualifierTriplet;
-import org.apache.fop.afp.modca.triplets.CommentTriplet;
-import org.apache.fop.afp.modca.triplets.ObjectAreaSizeTriplet;
-import org.apache.fop.afp.modca.triplets.Triplet;
-import org.junit.Before;
-
-/**
- * Test {@link AbstractTripletStructuredObject}
- */
-public abstract class AbstractTripletStructuredObjectTestCase<S extends AbstractTripletStructuredObject>
- extends AbstractStructuredObjectTestCase<AbstractTripletStructuredObject> {
-
- private static final List<AbstractTriplet> TRIPLETS;
-
- static {
- List<AbstractTriplet> triplets = new ArrayList<AbstractTriplet>();
-
- triplets.add(new CommentTriplet((byte) 0x01, "test comment"));
-
- triplets.add(new AttributeQualifierTriplet(1, 1));
-
- triplets.add(new ObjectAreaSizeTriplet(10, 20));
-
- TRIPLETS = Collections.unmodifiableList(triplets);
- }
-
- private AbstractTripletStructuredObject emptyStructuredObject
- = new AbstractTripletStructuredObject() { };
-
- @Before
- public void setUp() throws Exception {
- AbstractTripletStructuredObject sut = getSut();
-
- for (AbstractTriplet triplet : TRIPLETS) {
- sut.addTriplet(triplet);
- }
- }
-
-
- /**
- * Test getTripletLength() - ensure a sum of all enclosing object lengths is returned.
- */
- public void testGetTripletLength() {
-
- int dataLength = 0;
- for (Triplet t : TRIPLETS) {
- dataLength += t.getDataLength();
- }
- assertEquals(dataLength, getSut().getTripletDataLength());
- assertEquals(0, emptyStructuredObject.getTripletDataLength());
- }
-
- /**
- * Test hasTriplets()
- */
- public void testHasTriplets() {
- assertTrue(getSut().hasTriplets());
- assertFalse(emptyStructuredObject.hasTriplets());
- }
-
- /**
- * Test writeTriplets() - Ensure the triplets are written properly.
- *
- * @throws IOException -
- */
- public void testWriteObjects() throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- for (AbstractTriplet triplet : TRIPLETS) {
- triplet.writeToStream(baos);
- }
- byte[] expected = baos.toByteArray();
- baos.reset();
- getSut().writeTriplets(baos);
- assertTrue(Arrays.equals(expected, baos.toByteArray()));
-
- baos.reset();
- // Ensure it doesn't die if no data has been added
- emptyStructuredObject.writeTriplets(baos);
- byte[] emptyArray = baos.toByteArray();
- assertTrue(Arrays.equals(emptyArray, new byte[0]));
- }
-
- /**
- * Test hasTriplet() - ensure both positive and negative values are returned.
- */
- public void testHasTriplet() {
- for (AbstractTriplet triplet : TRIPLETS) {
- assertTrue(getSut().hasTriplet(triplet.getId()));
- assertFalse(emptyStructuredObject.hasTriplet(triplet.getId()));
- }
- CommentTriplet notInSystem = new CommentTriplet((byte) 0x30, "This should return false");
- assertFalse(getSut().hasTriplet(notInSystem.getId()));
- }
-
- /**
- * Test addTriplet() - mostly tested above, but check boundary cases
- */
- public void testAddTriplet() {
- // ensure null doesn't kill it... not sure what else to test
- getSut().addTriplet(null);
- }
-
- /**
- * Test addTriplets() - ensure all triplets are added.
- */
- public void testAddTriplets() {
- // Tested on empty object
- List<AbstractTriplet> expectedList = TRIPLETS;
- emptyStructuredObject.addTriplets(expectedList);
- // checks equals() on each member of both lists
- assertEquals(expectedList, emptyStructuredObject.getTriplets());
-
- // Add a list to an already populated list
- getSut().addTriplets(expectedList);
-
- List<AbstractTriplet> newExpected = new ArrayList<AbstractTriplet>(expectedList);
- newExpected.addAll(expectedList);
- assertEquals(newExpected, getSut().getTriplets());
-
- // Ensure null doesn't throw exception
- emptyStructuredObject.addTriplets(null);
- }
-
-}
\ No newline at end of file
/**
* Test {@link IncludeObject}
*/
-public class IncludeObjectTestCase extends AbstractNamedAFPObjectTestCase<IncludeObject> {
+public class IncludeObjectTestCase extends AbstractNamedAFPObjectTest<IncludeObject> {
@Before
public void setUp() throws Exception {
/**
* Tests the {@linkplain BlockViewport} class.
*/
-public class BlockViewportTestCase extends ViewportTestCase {
+public class BlockViewportTestCase extends ViewportTest {
@Test
public void testNonClip() throws Exception {
/**
* Tests the {@linkplain RegionViewport} class.
*/
-public class RegionViewportTestCase extends ViewportTestCase {
+public class RegionViewportTestCase extends ViewportTest {
private RegionViewport createRegionViewport(int x, int y, int ipd, int bpd) {
Rectangle2D v = new Rectangle(x, y, ipd, bpd);
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.area;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.awt.Rectangle;
+
+/**
+ * Tests implementations of the {@linkplain Viewport} interface.
+ */
+public abstract class ViewportTest {
+
+ protected void checkNonClip(Viewport v) throws Exception {
+ assertFalse(v.hasClip());
+ assertNull(v.getClipRectangle());
+ }
+
+ protected void checkClip(Viewport v, int expectedWidth, int expectedHeight) throws Exception {
+ assertTrue(v.hasClip());
+ assertEquals(new Rectangle(0, 0, expectedWidth, expectedHeight), v.getClipRectangle());
+ }
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.area;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.awt.Rectangle;
-
-/**
- * Tests implementations of the {@linkplain Viewport} interface.
- */
-public abstract class ViewportTestCase {
-
- protected void checkNonClip(Viewport v) throws Exception {
- assertFalse(v.hasClip());
- assertNull(v.getClipRectangle());
- }
-
- protected void checkClip(Viewport v, int expectedWidth, int expectedHeight) throws Exception {
- assertTrue(v.hasClip());
- assertEquals(new Rectangle(0, 0, expectedWidth, expectedHeight), v.getClipRectangle());
- }
-}
package org.apache.fop.area.inline;
-import org.apache.fop.area.ViewportTestCase;
+import org.apache.fop.area.ViewportTest;
import org.junit.Test;
/**
* Tests the {@linkplain InlineViewport} class.
*/
-public class InlineViewportTestCase extends ViewportTestCase {
+public class InlineViewportTestCase extends ViewportTest {
@Test
public void testNonClip() throws Exception {
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.config;
+
+import static org.junit.Assert.fail;
+
+import org.junit.Test;
+
+/**
+ * Super class of several user config cases.
+ */
+public abstract class BaseConstructiveUserConfigTest extends BaseUserConfigTest {
+
+ /**
+ * Test using a standard FOP font
+ * @throws Exception checkstyle wants a comment here, even a silly one
+ */
+ @Test
+ public void testUserConfig() throws Exception {
+ try {
+ initConfig();
+ convertFO();
+ } catch (Exception e) {
+ // this should *not* happen!
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ }
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.config;
-
-import static org.junit.Assert.fail;
-
-import org.junit.Test;
-
-/**
- * Super class of several user config cases.
- */
-public abstract class BaseConstructiveUserConfigTestCase extends BaseUserConfigTestCase {
-
- /**
- * Test using a standard FOP font
- * @throws Exception checkstyle wants a comment here, even a silly one
- */
- @Test
- public void testUserConfig() throws Exception {
- try {
- initConfig();
- convertFO();
- } catch (Exception e) {
- // this should *not* happen!
- e.printStackTrace();
- fail(e.getMessage());
- }
- }
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.config;
+
+import static org.junit.Assert.fail;
+
+import org.apache.fop.apps.FOPException;
+import org.junit.Test;
+
+/**
+ * Super class for several user configuration failure cases.
+ */
+public abstract class BaseDestructiveUserConfigTest extends BaseUserConfigTest {
+
+ /**
+ * Test the user configuration failure.
+ */
+ @Test
+ public void testUserConfig() {
+ try {
+ initConfig();
+ convertFO();
+ fail( getName() + ": Expected Configuration Exception" );
+ } catch (FOPException e) {
+ // this *should* happen!
+ } catch (Exception e) {
+ e.printStackTrace();
+ fail( getName() + ": Expected FOPException but got: " + e.getMessage() );
+ }
+ }
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.config;
-
-import static org.junit.Assert.fail;
-
-import org.apache.fop.apps.FOPException;
-import org.junit.Test;
-
-/**
- * Super class for several user configuration failure cases.
- */
-public abstract class BaseDestructiveUserConfigTestCase extends BaseUserConfigTestCase {
-
- /**
- * Test the user configuration failure.
- */
- @Test
- public void testUserConfig() {
- try {
- initConfig();
- convertFO();
- fail( getName() + ": Expected Configuration Exception" );
- } catch (FOPException e) {
- // this *should* happen!
- } catch (Exception e) {
- e.printStackTrace();
- fail( getName() + ": Expected FOPException but got: " + e.getMessage() );
- }
- }
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.config;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.avalon.framework.configuration.Configuration;
+import org.apache.avalon.framework.configuration.ConfigurationException;
+import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.render.pdf.BasePDFTest;
+import org.xml.sax.SAXException;
+
+/**
+ * Basic runtime test for FOP's font configuration. It is used to verify that
+ * nothing obvious is broken after compiling.
+ */
+public abstract class BaseUserConfigTest extends BasePDFTest {
+
+ protected DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
+
+ /** logging instance */
+ protected Log log = LogFactory.getLog(BaseUserConfigTest.class);
+
+
+ /**
+ * @see org.apache.fop.render.pdf.BasePDFTest#init()
+ */
+ protected void init() {
+ // do nothing
+ }
+
+ protected void initConfig() throws Exception {
+ fopFactory.setUserConfig(getUserConfig());
+ }
+
+ protected void convertFO() throws Exception {
+ final File baseDir = getBaseDir();
+ final String fontFOFilePath = getFontFOFilePath();
+ File foFile = new File(baseDir, fontFOFilePath);
+ final boolean dumpOutput = false;
+ FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
+ convertFO(foFile, foUserAgent, dumpOutput);
+ }
+
+ /**
+ * get test FOP config File
+ * @return fo test filepath
+ */
+ protected String getFontFOFilePath() {
+ return "test/xml/bugtests/font.fo";
+ }
+
+ /**
+ * get test FOP Configuration
+ * @return fo test filepath
+ * @throws IOException
+ * @throws SAXException
+ * @throws ConfigurationException
+ */
+ protected Configuration getUserConfig(String configString) throws ConfigurationException, SAXException, IOException {
+ return cfgBuilder.build(new ByteArrayInputStream(configString.getBytes()));
+ }
+
+ /** get base config directory */
+ protected String getBaseConfigDir() {
+ return "test/config";
+ }
+
+ /**
+ * @return user config File
+ */
+ protected abstract String getUserConfigFilename();
+
+ /**
+ * The name of this test.
+ */
+ public String getName() {
+ return getUserConfigFilename();
+ }
+
+ protected File getUserConfigFile() {
+ return new File(getBaseConfigDir() + File.separator + getUserConfigFilename());
+ }
+
+ /**
+ * get test FOP Configuration
+ * @return fo test filepath
+ * @throws IOException
+ * @throws SAXException
+ * @throws ConfigurationException
+ */
+ protected Configuration getUserConfig() throws ConfigurationException, SAXException, IOException {
+ return cfgBuilder.buildFromFile(getUserConfigFile());
+ }
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.config;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.IOException;
-
-import org.apache.avalon.framework.configuration.Configuration;
-import org.apache.avalon.framework.configuration.ConfigurationException;
-import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.render.pdf.BasePDFTestCase;
-import org.xml.sax.SAXException;
-
-/**
- * Basic runtime test for FOP's font configuration. It is used to verify that
- * nothing obvious is broken after compiling.
- */
-public abstract class BaseUserConfigTestCase extends BasePDFTestCase {
-
- protected DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
-
- /** logging instance */
- protected Log log = LogFactory.getLog(BaseUserConfigTestCase.class);
-
-
- /**
- * @see org.apache.fop.render.pdf.BasePDFTestCase#init()
- */
- protected void init() {
- // do nothing
- }
-
- protected void initConfig() throws Exception {
- fopFactory.setUserConfig(getUserConfig());
- }
-
- protected void convertFO() throws Exception {
- final File baseDir = getBaseDir();
- final String fontFOFilePath = getFontFOFilePath();
- File foFile = new File(baseDir, fontFOFilePath);
- final boolean dumpOutput = false;
- FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
- convertFO(foFile, foUserAgent, dumpOutput);
- }
-
- /**
- * get test FOP config File
- * @return fo test filepath
- */
- protected String getFontFOFilePath() {
- return "test/xml/bugtests/font.fo";
- }
-
- /**
- * get test FOP Configuration
- * @return fo test filepath
- * @throws IOException
- * @throws SAXException
- * @throws ConfigurationException
- */
- protected Configuration getUserConfig(String configString) throws ConfigurationException, SAXException, IOException {
- return cfgBuilder.build(new ByteArrayInputStream(configString.getBytes()));
- }
-
- /** get base config directory */
- protected String getBaseConfigDir() {
- return "test/config";
- }
-
- /**
- * @return user config File
- */
- protected abstract String getUserConfigFilename();
-
- /**
- * The name of this test.
- */
- public String getName() {
- return getUserConfigFilename();
- }
-
- protected File getUserConfigFile() {
- return new File(getBaseConfigDir() + File.separator + getUserConfigFilename());
- }
-
- /**
- * get test FOP Configuration
- * @return fo test filepath
- * @throws IOException
- * @throws SAXException
- * @throws ConfigurationException
- */
- protected Configuration getUserConfig() throws ConfigurationException, SAXException, IOException {
- return cfgBuilder.buildFromFile(getUserConfigFile());
- }
-}
/**
* this font is without a metrics-url or an embed-url
*/
-public class FontAttributesMissingTestCase extends BaseDestructiveUserConfigTestCase {
+public class FontAttributesMissingTestCase extends BaseDestructiveUserConfigTest {
@Override
public String getUserConfigFilename() {
/**
* This font base does not exist and a relative font path is used.
*/
-public class FontBaseBadTestCase extends BaseDestructiveUserConfigTestCase {
+public class FontBaseBadTestCase extends BaseDestructiveUserConfigTest {
@Override
public String getUserConfigFilename() {
/**
* this font has an embed-url that does not exist on filesystem.
*/
-public class FontEmbedUrlBadTestCase extends BaseDestructiveUserConfigTestCase {
+public class FontEmbedUrlBadTestCase extends BaseDestructiveUserConfigTest {
@Override
public String getUserConfigFilename() {
/**
* this font has a malformed embed-url
*/
-public class FontEmbedUrlMalformedTestCase extends BaseDestructiveUserConfigTestCase {
+public class FontEmbedUrlMalformedTestCase extends BaseDestructiveUserConfigTest {
@Override
public String getUserConfigFilename() {
/**
* this font has a metrics-url that does not exist on filesystem
*/
-public class FontMetricsUrlBadTestCase extends BaseDestructiveUserConfigTestCase {
+public class FontMetricsUrlBadTestCase extends BaseDestructiveUserConfigTest {
@Override
public String getUserConfigFilename() {
/**
* this font has a malformed metrics-url
*/
-public class FontMetricsUrlMalformedTestCase extends BaseDestructiveUserConfigTestCase {
+public class FontMetricsUrlMalformedTestCase extends BaseDestructiveUserConfigTest {
@Override
public String getUserConfigFilename() {
/**
* this font has a missing font triplet attribute
*/
-public class FontTripletAttributeMissingTestCase extends BaseDestructiveUserConfigTestCase {
+public class FontTripletAttributeMissingTestCase extends BaseDestructiveUserConfigTest {
@Override
public String getUserConfigFilename() {
package org.apache.fop.config;
-public class FontsAutoDetectTestCase extends BaseConstructiveUserConfigTestCase {
+public class FontsAutoDetectTestCase extends BaseConstructiveUserConfigTest {
@Override
public String getUserConfigFilename() {
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.config;
-
-/**
- * this font has a metrics-url that does not exist on filesystem
- */
-public class FontsDirectoryBadTestCase extends BaseDestructiveUserConfigTestCase {
-
- @Override
- public String getUserConfigFilename() {
- return "test_fonts_directory_bad.xconf";
- }
-
- @Override
- protected String getFontFOFilePath() {
- return "test/xml/bugtests/font-dir.fo";
- }
-}
/**
* tests font directory on system
*/
-public class FontsDirectoryRecursiveTestCase extends BaseConstructiveUserConfigTestCase {
+public class FontsDirectoryRecursiveTestCase extends BaseConstructiveUserConfigTest {
@Override
protected String getUserConfigFilename() {
* Tests the font substitution mechanism
*/
public class FontsSubstitutionTestCase extends
- BaseConstructiveUserConfigTestCase {
+ BaseConstructiveUserConfigTest {
@Override
protected byte[] convertFO(File foFile, FOUserAgent ua, boolean dumpPdfFile)
FontMetricsUrlBadTestCase.class,
FontEmbedUrlBadTestCase.class,
FontMetricsUrlMalformedTestCase.class,
- FontMetricsUrlMalformedTestCase.class,
FontsDirectoryRecursiveTestCase.class,
FontsAutoDetectTestCase.class,
FontsSubstitutionTestCase.class,
public void processEvent(Event event) {
// Always create the message to make sure there is no error in the formatting process
- String msg = EventFormatter.format(event);
- if (event.getEventID().equals(expectedEventID)) {
+ String id = event.getEventID();
+ if (id.equals(expectedEventID)) {
eventReceived = true;
- } else {
- fail("Unexpected event: id = " + event.getEventID() + ": " + msg);
}
}
package org.apache.fop.events;
import java.io.File;
+import java.io.IOException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
+import org.junit.Test;
+import org.xml.sax.SAXException;
+
import org.apache.commons.io.output.NullOutputStream;
+
+import org.apache.xmlgraphics.util.MimeConstants;
+
import org.apache.fop.ResourceEventProducer;
import org.apache.fop.apps.FOPException;
+import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.area.AreaEventProducer;
import org.apache.fop.fonts.FontEventProducer;
import org.apache.fop.layoutmgr.BlockLevelEventProducer;
import org.apache.fop.layoutmgr.inline.InlineLevelEventProducer;
-import org.apache.xmlgraphics.util.MimeConstants;
-import org.junit.Test;
/**
* Tests that the event notification system runs smoothly.
private final TransformerFactory tFactory = TransformerFactory.newInstance();
- private final File basedir;
-
- public EventProcessingTestCase() {
- String base = System.getProperty("basedir");
- if (base != null) {
- basedir = new File(base);
- } else {
- basedir = new File(".");
- }
- }
-
- private void doTest(String filename, String expectedEventID)
- throws FOPException, TransformerException {
- Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, new NullOutputStream());
+ private void doTest(String filename, String fopConf, String expectedEventID)
+ throws FOPException, TransformerException, IOException, SAXException {
EventChecker eventChecker = new EventChecker(expectedEventID);
- fop.getUserAgent().getEventBroadcaster().addEventListener(eventChecker);
+ if (fopConf != null) {
+ fopFactory.setUserConfig(fopConf);
+ }
+ FOUserAgent userAgent = fopFactory.newFOUserAgent();
+ userAgent.getEventBroadcaster().addEventListener(eventChecker);
+ Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, new NullOutputStream());
Transformer transformer = tFactory.newTransformer();
- Source src = new StreamSource(new File(basedir, filename));
+ Source src = new StreamSource(new File("test/events/" + filename));
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
eventChecker.end();
}
+ private void doTest(String filename, String expectedEventID) throws
+ FOPException, TransformerException, IOException, SAXException {
+ doTest(filename, null, expectedEventID);
+ }
+
@Test
- public void testArea() throws FOPException, TransformerException {
+ public void testArea() throws TransformerException, IOException, SAXException {
doTest("area.fo",
AreaEventProducer.class.getName() + ".unresolvedIDReferenceOnPage");
}
@Test
- public void testResource() throws FOPException, TransformerException {
+ public void testResource() throws FOPException, TransformerException, IOException,
+ SAXException {
doTest("resource.fo",
ResourceEventProducer.class.getName() + ".imageNotFound");
}
@Test
- public void testValidation() throws FOPException, TransformerException {
+ public void testValidation() throws FOPException, TransformerException, IOException,
+ SAXException {
doTest("validation.fo",
FOValidationEventProducer.class.getName() + ".invalidPropertyValue");
}
@Test
- public void testTable() throws FOPException, TransformerException {
+ public void testTable() throws FOPException, TransformerException, IOException, SAXException {
doTest("table.fo",
TableEventProducer.class.getName() + ".noTablePaddingWithCollapsingBorderModel");
}
@Test
- public void testBlockLevel() throws FOPException, TransformerException {
+ public void testBlockLevel() throws FOPException, TransformerException, IOException,
+ SAXException {
doTest("block-level.fo",
BlockLevelEventProducer.class.getName() + ".overconstrainedAdjustEndIndent");
}
@Test
- public void testInlineLevel() throws FOPException, TransformerException {
+ public void testInlineLevel() throws FOPException, TransformerException, IOException,
+ SAXException {
doTest("inline-level.fo",
InlineLevelEventProducer.class.getName() + ".lineOverflows");
}
@Test
- public void testFont() throws FOPException, TransformerException {
+ public void testFont() throws FOPException, TransformerException, IOException, SAXException {
doTest("font.fo",
FontEventProducer.class.getName() + ".fontSubstituted");
}
+
+ @Test
+ public void testFontWithBadDirectory() throws FOPException, TransformerException, IOException,
+ SAXException {
+ doTest("font.fo", "test/config/test_fonts_directory_bad.xconf",
+ FontEventProducer.class.getName() + ".fontDirectoryNotFound");
+ }
}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.fo.flow.table;
+
+import java.util.Iterator;
+
+import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.fo.FOEventHandler;
+import org.apache.fop.fotreetest.FOTreeUnitTester;
+
+/**
+ * Superclass for testcases related to tables, factoring the common stuff.
+ */
+abstract class AbstractTableTest extends FOTreeUnitTester {
+
+ private FOTreeUnitTester.FOEventHandlerFactory tableHandlerFactory;
+
+ private TableHandler tableHandler;
+
+ public AbstractTableTest() throws Exception {
+ super();
+ tableHandlerFactory = new FOEventHandlerFactory() {
+ public FOEventHandler createFOEventHandler(FOUserAgent foUserAgent) {
+ tableHandler = new TableHandler(foUserAgent);
+ return tableHandler;
+ }
+ };
+ }
+
+ protected void setUp(String filename) throws Exception {
+ setUp(filename, tableHandlerFactory);
+ }
+
+ protected TableHandler getTableHandler() {
+ return tableHandler;
+ }
+
+ protected Iterator getTableIterator() {
+ return tableHandler.getTables().iterator();
+ }
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.fo.flow.table;
-
-import java.util.Iterator;
-
-import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.fo.FOEventHandler;
-import org.apache.fop.fotreetest.FOTreeUnitTester;
-
-/**
- * Superclass for testcases related to tables, factoring the common stuff.
- */
-abstract class AbstractTableTestCase extends FOTreeUnitTester {
-
- private FOTreeUnitTester.FOEventHandlerFactory tableHandlerFactory;
-
- private TableHandler tableHandler;
-
- public AbstractTableTestCase() throws Exception {
- super();
- tableHandlerFactory = new FOEventHandlerFactory() {
- public FOEventHandler createFOEventHandler(FOUserAgent foUserAgent) {
- tableHandler = new TableHandler(foUserAgent);
- return tableHandler;
- }
- };
- }
-
- protected void setUp(String filename) throws Exception {
- setUp(filename, tableHandlerFactory);
- }
-
- protected TableHandler getTableHandler() {
- return tableHandler;
- }
-
- protected Iterator getTableIterator() {
- return tableHandler.getTables().iterator();
- }
-}
* conditionality into account. The resolved borders are generated by the
* collapsed-conditional-borders_test-generator.py Python script.
*/
-public class CollapsedConditionalBorderTestCase extends AbstractTableTestCase {
+public class CollapsedConditionalBorderTestCase extends AbstractTableTest {
private final Integer border0pt = new Integer(0);
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.fo.flow.table;
+
+import static org.junit.Assert.fail;
+
+import org.apache.fop.fo.ValidationException;
+
+/**
+ * Abstract class for testing erroneous files, checking that a ValidationException is thrown.
+ */
+abstract class ErrorCheckTest extends AbstractTableTest {
+
+ public ErrorCheckTest() throws Exception {
+ super();
+ }
+
+ protected void launchTest(String filename) throws Exception {
+ try {
+ setUp(filename);
+ fail();
+ } catch (ValidationException e) {
+ // TODO check location
+ }
+ }
+
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.fo.flow.table;
-
-import static org.junit.Assert.fail;
-
-import org.apache.fop.fo.ValidationException;
-
-/**
- * Abstract class for testing erroneous files, checking that a ValidationException is thrown.
- */
-abstract class ErrorCheckTestCase extends AbstractTableTestCase {
-
- public ErrorCheckTestCase() throws Exception {
- super();
- }
-
- protected void launchTest(String filename) throws Exception {
- try {
- setUp(filename);
- fail();
- } catch (ValidationException e) {
- // TODO check location
- }
- }
-
-}
* Testcase checking that cells spanning further than their parent element aren't
* accepted.
*/
-public class IllegalRowSpanTestCase extends ErrorCheckTestCase {
+public class IllegalRowSpanTestCase extends ErrorCheckTest {
public IllegalRowSpanTestCase() throws Exception {
super();
* Tests that RowGroupBuilder returns, for each part of a table, the expected number of
* row-groups with the expected number or rows in each.
*/
-public class RowGroupBuilderTestCase extends AbstractTableTestCase {
+public class RowGroupBuilderTestCase extends AbstractTableTest {
public RowGroupBuilderTestCase() throws Exception {
super();
import org.junit.Test;
-public class TableColumnColumnNumberTestCase extends AbstractTableTestCase {
+public class TableColumnColumnNumberTestCase extends AbstractTableTest {
/**
* A percentBaseContext that mimics the behaviour of TableLM for computing the widths
import org.junit.Test;
-public class TooManyColumnsTestCase extends ErrorCheckTestCase {
+public class TooManyColumnsTestCase extends ErrorCheckTest {
public TooManyColumnsTestCase() throws Exception {
super();
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.fonts;
-
-import static org.junit.Assert.assertEquals;
-
-import java.io.File;
-
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- *
- */
-public class DejaVuLGCSerifTest {
-
- private FontResolver fontResolver = FontManager.createMinimalFontResolver();
- private CustomFont font;
-
- /**
- * sets up the testcase by loading the DejaVu Font.
- *
- * @throws Exception
- * if the test fails.
- */
- @Before
- public void setUp() throws Exception {
- File file = new File("test/resources/fonts/DejaVuLGCSerif.ttf");
- font = FontLoader.loadFont(file, "", true, EncodingMode.AUTO,
- fontResolver);
- }
-
- /**
- * Simple test to see if font name was detected correctly.
- */
- @Test
- public void testFontName() {
- assertEquals("DejaVuLGCSerif", font.getFontName());
- }
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.fonts;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.File;
+
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ *
+ */
+public class DejaVuLGCSerifTestCase {
+
+ private FontResolver fontResolver = FontManager.createMinimalFontResolver();
+ private CustomFont font;
+
+ /**
+ * sets up the testcase by loading the DejaVu Font.
+ *
+ * @throws Exception
+ * if the test fails.
+ */
+ @Before
+ public void setUp() throws Exception {
+ File file = new File("test/resources/fonts/DejaVuLGCSerif.ttf");
+ font = FontLoader.loadFont(file, "", true, EncodingMode.AUTO,
+ fontResolver);
+ }
+
+ /**
+ * Simple test to see if font name was detected correctly.
+ */
+ @Test
+ public void testFontName() {
+ assertEquals("DejaVuLGCSerif", font.getFontName());
+ }
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.fonts;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-
-public class EncodingModeTest {
-
- @Test
- public void testGetName() {
- assertEquals("auto", EncodingMode.AUTO.getName());
- assertEquals("single-byte", EncodingMode.SINGLE_BYTE.getName());
- assertEquals("cid", EncodingMode.CID.getName());
- }
-
- @Test
- public void testGetValue() {
- assertEquals(EncodingMode.AUTO, EncodingMode.getEncodingMode("auto"));
- assertEquals(EncodingMode.SINGLE_BYTE, EncodingMode.getEncodingMode("single-byte"));
- assertEquals(EncodingMode.CID, EncodingMode.getEncodingMode("cid"));
- }
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.fonts;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class EncodingModeTestCase {
+
+ @Test
+ public void testGetName() {
+ assertEquals("auto", EncodingMode.AUTO.getName());
+ assertEquals("single-byte", EncodingMode.SINGLE_BYTE.getName());
+ assertEquals("cid", EncodingMode.CID.getName());
+ }
+
+ @Test
+ public void testGetValue() {
+ assertEquals(EncodingMode.AUTO, EncodingMode.getEncodingMode("auto"));
+ assertEquals(EncodingMode.SINGLE_BYTE, EncodingMode.getEncodingMode("single-byte"));
+ assertEquals(EncodingMode.CID, EncodingMode.getEncodingMode("cid"));
+ }
+}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.fotreetest;
+
+import java.io.File;
+import java.util.Collection;
+import java.util.List;
+
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.XMLFilterImpl;
+
+import org.apache.fop.DebugHelper;
+import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.apps.Fop;
+import org.apache.fop.apps.FopFactory;
+import org.apache.fop.apps.FopFactoryConfigurator;
+import org.apache.fop.fotreetest.ext.TestElementMapping;
+import org.apache.fop.layoutengine.LayoutEngineTestUtils;
+import org.apache.fop.layoutengine.TestFilesConfiguration;
+import org.apache.fop.util.ConsoleEventListenerForTests;
+
+/**
+ * Test driver class for FO tree tests.
+ */
+@RunWith(Parameterized.class)
+public class FOTreeTestCase {
+
+ @BeforeClass
+ public static void registerElementListObservers() {
+ DebugHelper.registerStandardElementListObservers();
+ }
+
+ /**
+ * Gets the parameters to run the FO tree test cases.
+ * @return a collection of file arrays containing the test files
+ */
+ @Parameters
+ public static Collection<File[]> getParameters() {
+ TestFilesConfiguration.Builder builder = new TestFilesConfiguration.Builder();
+ builder.testDir("test/fotree")
+ .singleProperty("fop.fotree.single")
+ .startsWithProperty("fop.fotree.starts-with")
+ .suffix(".fo")
+ .testSet("testcases")
+ .disabledProperty("fop.layoutengine.disabled", "test/fotree/disabled-testcases.xml")
+ .privateTestsProperty("fop.fotree.private");
+
+ TestFilesConfiguration testConfig = builder.build();
+ return LayoutEngineTestUtils.getTestFiles(testConfig);
+ }
+
+ private FopFactory fopFactory = FopFactory.newInstance();
+
+ private final File testFile;
+
+ /**
+ * Main constructor
+ *
+ * @param testFile the FO file to test
+ */
+ public FOTreeTestCase(File testFile) {
+ fopFactory.addElementMapping(new TestElementMapping());
+ this.testFile = testFile;
+ }
+
+ /**
+ * Runs a test.
+ * @throws Exception if a test or FOP itself fails
+ */
+ @Test
+ public void runTest() throws Exception {
+ try {
+ ResultCollector collector = ResultCollector.getInstance();
+ collector.reset();
+
+ SAXParserFactory spf = SAXParserFactory.newInstance();
+ spf.setNamespaceAware(true);
+ spf.setValidating(false);
+ SAXParser parser = spf.newSAXParser();
+ XMLReader reader = parser.getXMLReader();
+
+ // Resetting values modified by processing instructions
+ fopFactory.setBreakIndentInheritanceOnReferenceAreaBoundary(
+ FopFactoryConfigurator.DEFAULT_BREAK_INDENT_INHERITANCE);
+ fopFactory.setSourceResolution(FopFactoryConfigurator.DEFAULT_SOURCE_RESOLUTION);
+
+ FOUserAgent ua = fopFactory.newFOUserAgent();
+ ua.setBaseURL(testFile.getParentFile().toURI().toURL().toString());
+ ua.setFOEventHandlerOverride(new DummyFOEventHandler(ua));
+ ua.getEventBroadcaster().addEventListener(
+ new ConsoleEventListenerForTests(testFile.getName()));
+
+ // Used to set values in the user agent through processing instructions
+ reader = new PIListener(reader, ua);
+
+ Fop fop = fopFactory.newFop(ua);
+
+ reader.setContentHandler(fop.getDefaultHandler());
+ reader.setDTDHandler(fop.getDefaultHandler());
+ reader.setErrorHandler(fop.getDefaultHandler());
+ reader.setEntityResolver(fop.getDefaultHandler());
+ try {
+ reader.parse(testFile.toURI().toURL().toExternalForm());
+ } catch (Exception e) {
+ collector.notifyError(e.getLocalizedMessage());
+ throw e;
+ }
+
+ List<String> results = collector.getResults();
+ if (results.size() > 0) {
+ for (int i = 0; i < results.size(); i++) {
+ System.out.println((String) results.get(i));
+ }
+ throw new IllegalStateException((String) results.get(0));
+ }
+ } catch (Exception e) {
+ org.apache.commons.logging.LogFactory.getLog(this.getClass()).info(
+ "Error on " + testFile.getName());
+ throw e;
+ }
+ }
+
+ private static class PIListener extends XMLFilterImpl {
+
+ private FOUserAgent userAgent;
+
+ public PIListener(XMLReader parent, FOUserAgent userAgent) {
+ super(parent);
+ this.userAgent = userAgent;
+ }
+
+ /** @see org.xml.sax.helpers.XMLFilterImpl */
+ public void processingInstruction(String target, String data) throws SAXException {
+ if ("fop-useragent-break-indent-inheritance".equals(target)) {
+ userAgent.getFactory().setBreakIndentInheritanceOnReferenceAreaBoundary(
+ Boolean.valueOf(data).booleanValue());
+ } else if ("fop-source-resolution".equals(target)) {
+ userAgent.getFactory().setSourceResolution(Float.parseFloat(data));
+ }
+ super.processingInstruction(target, data);
+ }
+
+ }
+
+}
package org.apache.fop.fotreetest;
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
import org.apache.fop.fo.flow.table.CollapsedConditionalBorderTestCase;
import org.apache.fop.fo.flow.table.IllegalRowSpanTestCase;
import org.apache.fop.fo.flow.table.RowGroupBuilderTestCase;
import org.apache.fop.fo.flow.table.TableColumnColumnNumberTestCase;
import org.apache.fop.fo.flow.table.TooManyColumnsTestCase;
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
/**
* JUnit test suit for running layout engine test under JUnit control.
*/
@RunWith(Suite.class)
-@Suite.SuiteClasses({ TooManyColumnsTestCase.class, IllegalRowSpanTestCase.class,
- RowGroupBuilderTestCase.class, TableColumnColumnNumberTestCase.class,
- CollapsedConditionalBorderTestCase.class, FOTreeTester.class })
+@Suite.SuiteClasses({
+ TooManyColumnsTestCase.class,
+ IllegalRowSpanTestCase.class,
+ RowGroupBuilderTestCase.class,
+ TableColumnColumnNumberTestCase.class,
+ CollapsedConditionalBorderTestCase.class,
+ FOTreeTestCase.class })
public final class FOTreeTestSuite {
}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.fotreetest;
-
-import java.io.File;
-import java.util.Collection;
-import java.util.List;
-
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
-import org.xml.sax.SAXException;
-import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.XMLFilterImpl;
-
-import org.apache.fop.DebugHelper;
-import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.apps.Fop;
-import org.apache.fop.apps.FopFactory;
-import org.apache.fop.apps.FopFactoryConfigurator;
-import org.apache.fop.fotreetest.ext.TestElementMapping;
-import org.apache.fop.layoutengine.LayoutEngineTestUtils;
-import org.apache.fop.layoutengine.TestFilesConfiguration;
-import org.apache.fop.util.ConsoleEventListenerForTests;
-
-/**
- * Test driver class for FO tree tests.
- */
-@RunWith(Parameterized.class)
-public class FOTreeTester {
-
- @BeforeClass
- public static void registerElementListObservers() {
- DebugHelper.registerStandardElementListObservers();
- }
-
- /**
- * Gets the parameters to run the FO tree test cases.
- * @return a collection of file arrays containing the test files
- */
- @Parameters
- public static Collection<File[]> getParameters() {
- TestFilesConfiguration.Builder builder = new TestFilesConfiguration.Builder();
- builder.testDir("test/fotree")
- .singleProperty("fop.fotree.single")
- .startsWithProperty("fop.fotree.starts-with")
- .suffix(".fo")
- .testSet("testcases")
- .disabledProperty("fop.layoutengine.disabled", "test/fotree/disabled-testcases.xml")
- .privateTestsProperty("fop.fotree.private");
-
- TestFilesConfiguration testConfig = builder.build();
- return LayoutEngineTestUtils.getTestFiles(testConfig);
- }
-
- private FopFactory fopFactory = FopFactory.newInstance();
-
- private final File testFile;
-
- /**
- * Main constructor
- *
- * @param testFile the FO file to test
- */
- public FOTreeTester(File testFile) {
- fopFactory.addElementMapping(new TestElementMapping());
- this.testFile = testFile;
- }
-
- /**
- * Runs a test.
- * @throws Exception if a test or FOP itself fails
- */
- @Test
- public void runTest() throws Exception {
- try {
- ResultCollector collector = ResultCollector.getInstance();
- collector.reset();
-
- SAXParserFactory spf = SAXParserFactory.newInstance();
- spf.setNamespaceAware(true);
- spf.setValidating(false);
- SAXParser parser = spf.newSAXParser();
- XMLReader reader = parser.getXMLReader();
-
- // Resetting values modified by processing instructions
- fopFactory.setBreakIndentInheritanceOnReferenceAreaBoundary(
- FopFactoryConfigurator.DEFAULT_BREAK_INDENT_INHERITANCE);
- fopFactory.setSourceResolution(FopFactoryConfigurator.DEFAULT_SOURCE_RESOLUTION);
-
- FOUserAgent ua = fopFactory.newFOUserAgent();
- ua.setBaseURL(testFile.getParentFile().toURI().toURL().toString());
- ua.setFOEventHandlerOverride(new DummyFOEventHandler(ua));
- ua.getEventBroadcaster().addEventListener(
- new ConsoleEventListenerForTests(testFile.getName()));
-
- // Used to set values in the user agent through processing instructions
- reader = new PIListener(reader, ua);
-
- Fop fop = fopFactory.newFop(ua);
-
- reader.setContentHandler(fop.getDefaultHandler());
- reader.setDTDHandler(fop.getDefaultHandler());
- reader.setErrorHandler(fop.getDefaultHandler());
- reader.setEntityResolver(fop.getDefaultHandler());
- try {
- reader.parse(testFile.toURI().toURL().toExternalForm());
- } catch (Exception e) {
- collector.notifyError(e.getLocalizedMessage());
- throw e;
- }
-
- List<String> results = collector.getResults();
- if (results.size() > 0) {
- for (int i = 0; i < results.size(); i++) {
- System.out.println((String) results.get(i));
- }
- throw new IllegalStateException((String) results.get(0));
- }
- } catch (Exception e) {
- org.apache.commons.logging.LogFactory.getLog(this.getClass()).info(
- "Error on " + testFile.getName());
- throw e;
- }
- }
-
- private static class PIListener extends XMLFilterImpl {
-
- private FOUserAgent userAgent;
-
- public PIListener(XMLReader parent, FOUserAgent userAgent) {
- super(parent);
- this.userAgent = userAgent;
- }
-
- /** @see org.xml.sax.helpers.XMLFilterImpl */
- public void processingInstruction(String target, String data) throws SAXException {
- if ("fop-useragent-break-indent-inheritance".equals(target)) {
- userAgent.getFactory().setBreakIndentInheritanceOnReferenceAreaBoundary(
- Boolean.valueOf(data).booleanValue());
- } else if ("fop-source-resolution".equals(target)) {
- userAgent.getFactory().setSourceResolution(Float.parseFloat(data));
- }
- super.processingInstruction(target, data);
- }
-
- }
-
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.intermediate;
+
+import java.io.File;
+import java.io.IOException;
+
+import javax.xml.XMLConstants;
+import javax.xml.transform.Result;
+import javax.xml.transform.Templates;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.dom.DOMResult;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.sax.SAXResult;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+import javax.xml.validation.Validator;
+
+import org.w3c.dom.Document;
+
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+
+import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.apps.Fop;
+import org.apache.fop.render.intermediate.IFContext;
+import org.apache.fop.render.intermediate.IFDocumentHandler;
+import org.apache.fop.render.intermediate.IFSerializer;
+
+/**
+ * A common super-class for intermediate format test cases.
+ */
+abstract class AbstractIFTest extends AbstractIntermediateTest {
+
+ private static final Schema IF_SCHEMA;
+
+ static {
+ Schema ifSchema = null;
+ try {
+ SchemaFactory sFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+ sFactory.setErrorHandler(new ErrorHandler() {
+
+ public void error(SAXParseException exception) throws SAXException {
+ throw exception;
+ }
+
+ public void fatalError(SAXParseException exception) throws SAXException {
+ throw exception;
+ }
+
+ public void warning(SAXParseException exception) throws SAXException {
+ throw exception;
+ }
+
+ });
+ sFactory.setResourceResolver(XMLSchemaResolver.getInstance());
+ File ifSchemaFile = new File(
+ "src/documentation/intermediate-format-ng/fop-intermediate-format-ng.xsd");
+ ifSchema = sFactory.newSchema(ifSchemaFile);
+ } catch (IllegalArgumentException iae) {
+ System.err.println("No suitable SchemaFactory for XML Schema validation found!");
+ } catch (SAXException e) {
+ throw new ExceptionInInitializerError(e);
+ }
+ IF_SCHEMA = ifSchema;
+ }
+
+ /**
+ * Creates a new test case.
+ *
+ * @param testFile the file containing the document and the tests
+ * @throws IOException if an I/O error occurs while loading the test case
+ */
+ public AbstractIFTest(File testFile) throws IOException {
+ super(testFile);
+ }
+
+ @Override
+ protected String getIntermediateFileExtension() {
+ return ".if.xml";
+ }
+
+ @Override
+ protected Document buildIntermediateDocument(Templates templates) throws Exception {
+ Transformer transformer = templates.newTransformer();
+ setErrorListener(transformer);
+
+ //Set up XMLRenderer to render to a DOM
+ DOMResult domResult = new DOMResult();
+
+ FOUserAgent userAgent = createUserAgent();
+
+ //Create an instance of the target renderer so the XMLRenderer can use its font setup
+ IFDocumentHandler targetHandler = userAgent.getRendererFactory().createDocumentHandler(
+ userAgent, getTargetMIME());
+
+ //Setup painter
+ IFSerializer serializer = new IFSerializer();
+ serializer.setContext(new IFContext(userAgent));
+ serializer.mimicDocumentHandler(targetHandler);
+ serializer.setResult(domResult);
+
+ userAgent.setDocumentHandlerOverride(serializer);
+
+ Fop fop = fopFactory.newFop(userAgent);
+ Result res = new SAXResult(fop.getDefaultHandler());
+ transformer.transform(new DOMSource(testDoc), res);
+
+ return (Document) domResult.getNode();
+ }
+
+ @Override
+ protected void validate(Document doc) throws SAXException, IOException {
+ if (IF_SCHEMA == null) {
+ return; //skip validation;
+ }
+ Validator validator = IF_SCHEMA.newValidator();
+ validator.setErrorHandler(new ErrorHandler() {
+
+ public void error(SAXParseException exception) throws SAXException {
+ throw exception;
+ }
+
+ public void fatalError(SAXParseException exception) throws SAXException {
+ throw exception;
+ }
+
+ public void warning(SAXParseException exception) throws SAXException {
+ //ignore
+ }
+
+ });
+ validator.validate(new DOMSource(doc));
+ }
+
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.intermediate;
-
-import java.io.File;
-import java.io.IOException;
-
-import javax.xml.XMLConstants;
-import javax.xml.transform.Result;
-import javax.xml.transform.Templates;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.dom.DOMResult;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.sax.SAXResult;
-import javax.xml.validation.Schema;
-import javax.xml.validation.SchemaFactory;
-import javax.xml.validation.Validator;
-
-import org.w3c.dom.Document;
-
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-
-import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.apps.Fop;
-import org.apache.fop.render.intermediate.IFContext;
-import org.apache.fop.render.intermediate.IFDocumentHandler;
-import org.apache.fop.render.intermediate.IFSerializer;
-
-/**
- * A common super-class for intermediate format test cases.
- */
-abstract class AbstractIFTestCase extends AbstractIntermediateTestCase {
-
- private static final Schema IF_SCHEMA;
-
- static {
- Schema ifSchema = null;
- try {
- SchemaFactory sFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
- sFactory.setErrorHandler(new ErrorHandler() {
-
- public void error(SAXParseException exception) throws SAXException {
- throw exception;
- }
-
- public void fatalError(SAXParseException exception) throws SAXException {
- throw exception;
- }
-
- public void warning(SAXParseException exception) throws SAXException {
- throw exception;
- }
-
- });
- sFactory.setResourceResolver(XMLSchemaResolver.getInstance());
- File ifSchemaFile = new File(
- "src/documentation/intermediate-format-ng/fop-intermediate-format-ng.xsd");
- ifSchema = sFactory.newSchema(ifSchemaFile);
- } catch (IllegalArgumentException iae) {
- System.err.println("No suitable SchemaFactory for XML Schema validation found!");
- } catch (SAXException e) {
- throw new ExceptionInInitializerError(e);
- }
- IF_SCHEMA = ifSchema;
- }
-
- /**
- * Creates a new test case.
- *
- * @param testFile the file containing the document and the tests
- * @throws IOException if an I/O error occurs while loading the test case
- */
- public AbstractIFTestCase(File testFile) throws IOException {
- super(testFile);
- }
-
- @Override
- protected String getIntermediateFileExtension() {
- return ".if.xml";
- }
-
- @Override
- protected Document buildIntermediateDocument(Templates templates) throws Exception {
- Transformer transformer = templates.newTransformer();
- setErrorListener(transformer);
-
- //Set up XMLRenderer to render to a DOM
- DOMResult domResult = new DOMResult();
-
- FOUserAgent userAgent = createUserAgent();
-
- //Create an instance of the target renderer so the XMLRenderer can use its font setup
- IFDocumentHandler targetHandler = userAgent.getRendererFactory().createDocumentHandler(
- userAgent, getTargetMIME());
-
- //Setup painter
- IFSerializer serializer = new IFSerializer();
- serializer.setContext(new IFContext(userAgent));
- serializer.mimicDocumentHandler(targetHandler);
- serializer.setResult(domResult);
-
- userAgent.setDocumentHandlerOverride(serializer);
-
- Fop fop = fopFactory.newFop(userAgent);
- Result res = new SAXResult(fop.getDefaultHandler());
- transformer.transform(new DOMSource(testDoc), res);
-
- return (Document) domResult.getNode();
- }
-
- @Override
- protected void validate(Document doc) throws SAXException, IOException {
- if (IF_SCHEMA == null) {
- return; //skip validation;
- }
- Validator validator = IF_SCHEMA.newValidator();
- validator.setErrorHandler(new ErrorHandler() {
-
- public void error(SAXParseException exception) throws SAXException {
- throw exception;
- }
-
- public void fatalError(SAXParseException exception) throws SAXException {
- throw exception;
- }
-
- public void warning(SAXParseException exception) throws SAXException {
- //ignore
- }
-
- });
- validator.validate(new DOMSource(doc));
- }
-
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.intermediate;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.MalformedURLException;
+
+import javax.xml.transform.ErrorListener;
+import javax.xml.transform.Source;
+import javax.xml.transform.Templates;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.dom.DOMSource;
+
+import org.custommonkey.xmlunit.XMLAssert;
+import org.junit.After;
+import org.junit.Before;
+import org.w3c.dom.Document;
+import org.xml.sax.SAXException;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.output.NullOutputStream;
+
+import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.apps.FopFactory;
+import org.apache.fop.apps.MimeConstants;
+import org.apache.fop.events.model.EventSeverity;
+import org.apache.fop.util.ConsoleEventListenerForTests;
+
+/**
+ * Abstract base class for intermediate format tests.
+ */
+public abstract class AbstractIntermediateTest {
+
+ /** the test environment */
+ protected static TestAssistant testAssistant = new TestAssistant();
+
+ /** the FOP factory */
+ protected FopFactory fopFactory;
+
+ /** the directory containing the tests */
+ protected File testDir = new File("test/layoutengine/standard-testcases");
+ /** the output directory for any files generated by the tests */
+ protected File outputDir;
+
+ /** the test file */
+ protected File testFile;
+ /** the test document as DOM */
+ protected Document testDoc;
+ /** the intermediate format document as DOM */
+ protected Document intermediate;
+
+ /**
+ * Constructor for the test suite that is used for each test file.
+ * @param testFile the test file to run
+ * @throws IOException if an I/O error occurs while loading the test case
+ */
+ public AbstractIntermediateTest(File testFile)
+ throws IOException {
+ this.testFile = testFile;
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ setupOutputDirectory();
+ this.testDoc = testAssistant.loadTestCase(testFile);
+ this.fopFactory = testAssistant.getFopFactory(testDoc);
+ intermediate = buildIntermediateDocument(testAssistant.getTestcase2FOStylesheet());
+ if (outputDir != null) {
+ testAssistant.saveDOM(intermediate, new File(outputDir,
+ testFile.getName() + ".1" + getIntermediateFileExtension()));
+ }
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ //Release memory
+ this.intermediate = null;
+ this.fopFactory = null;
+ this.testDoc = null;
+ }
+
+ /**
+ * Returns the file extension for the intermediate file format.
+ * @return the file extension
+ */
+ protected abstract String getIntermediateFileExtension();
+
+ /**
+ * Returns the MIME type for which to test or to mimic for the intermediate format.
+ * @return the MIME type
+ */
+ protected String getTargetMIME() {
+ return MimeConstants.MIME_PDF;
+ }
+
+ /**
+ * Validates the intermediate format file.
+ * @param doc the intermediate file
+ * @throws IOException if an IO error occurs while loading the schema
+ * @throws SAXException if a SAX-related exception (including a validation error) occurs
+ */
+ protected void validate(Document doc) throws SAXException, IOException {
+ //nop by default
+ }
+
+ /**
+ * Builds an intermediate format document from a source file.
+ * @param templates the (optional) stylesheet
+ * @return the intermediate format document as a DOM
+ * @throws Exception if an error occurs while processing the document
+ */
+ protected abstract Document buildIntermediateDocument(Templates templates) throws Exception;
+
+ /**
+ * Creates a new FOP user agent.
+ * @return the user agent
+ */
+ protected FOUserAgent createUserAgent() {
+ FOUserAgent userAgent = fopFactory.newFOUserAgent();
+ try {
+ userAgent.setBaseURL(testDir.toURI().toURL().toExternalForm());
+ userAgent.getEventBroadcaster().addEventListener(
+ new ConsoleEventListenerForTests(testFile.getName(), EventSeverity.FATAL));
+ } catch (MalformedURLException e) {
+ // Shouldn't happen
+ throw new AssertionError();
+ }
+ return userAgent;
+ }
+
+ /**
+ * Sets up the output directory.
+ */
+ protected void setupOutputDirectory() {
+ String s = System.getProperty("fop.intermediate.outdir");
+ if (s != null && s.length() > 0) {
+ outputDir = new File(s);
+ outputDir.mkdirs();
+ }
+ }
+
+ /**
+ * Tests the area tree parser by running the parsed area tree again through the area tree
+ * renderer. The source and result documents are compared to each other.
+ * @throws Exception if the test fails
+ */
+ public void testParserToIntermediateFormat() throws Exception {
+ validate(intermediate);
+ Source src = new DOMSource(intermediate);
+ Document doc = parseAndRenderToIntermediateFormat(src);
+ if (outputDir != null) {
+ File tgtFile = new File(outputDir, testFile.getName() + ".2"
+ + getIntermediateFileExtension());
+ testAssistant.saveDOM(doc, tgtFile);
+ }
+
+ XMLAssert.assertXMLEqual(intermediate, doc);
+ }
+
+ /**
+ * Parses the intermediate file and renders it back to the intermediate format.
+ * @param src the source for the intermediate file
+ * @return a DOM Document with the re-created intermediate file
+ * @throws Exception if an error occurs while processing the document
+ */
+ protected abstract Document parseAndRenderToIntermediateFormat(Source src) throws Exception;
+
+ /**
+ * Tests the area tree parser by sending the parsed area tree to the PDF Renderer. Some
+ * errors might be caught by the PDFRenderer.
+ * @throws Exception if the test fails
+ */
+ public void testParserToPDF() throws Exception {
+ OutputStream out;
+ if (outputDir != null) {
+ File tgtFile = new File(outputDir, testFile.getName() + ".pdf");
+ out = new FileOutputStream(tgtFile);
+ out = new BufferedOutputStream(out);
+ } else {
+ out = new NullOutputStream();
+ }
+ try {
+ Source src = new DOMSource(intermediate);
+ parseAndRender(src, out);
+ } finally {
+ IOUtils.closeQuietly(out);
+ }
+ }
+
+ /**
+ * Parses and renders an intermediate format document to a final format.
+ * @param src the source document
+ * @param out the target output stream
+ * @throws Exception if an error occurs while rendering the document
+ */
+ protected abstract void parseAndRender(Source src, OutputStream out)
+ throws Exception;
+
+ /**
+ * Run the test.
+ *
+ * @throws Exception if an error occurs during the test
+ */
+ public abstract void runTest() throws Exception;
+
+ /**
+ * Sets an error listener which doesn't swallow errors like Xalan's default one.
+ * @param transformer the transformer to set the error listener on
+ */
+ protected void setErrorListener(Transformer transformer) {
+ transformer.setErrorListener(new ErrorListener() {
+
+ public void error(TransformerException exception) throws TransformerException {
+ throw exception;
+ }
+
+ public void fatalError(TransformerException exception) throws TransformerException {
+ throw exception;
+ }
+
+ public void warning(TransformerException exception) throws TransformerException {
+ //ignore
+ }
+
+ });
+ }
+
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.intermediate;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.net.MalformedURLException;
-
-import javax.xml.transform.ErrorListener;
-import javax.xml.transform.Source;
-import javax.xml.transform.Templates;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.dom.DOMSource;
-
-import org.custommonkey.xmlunit.XMLAssert;
-import org.junit.After;
-import org.junit.Before;
-import org.w3c.dom.Document;
-import org.xml.sax.SAXException;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.io.output.NullOutputStream;
-
-import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.apps.FopFactory;
-import org.apache.fop.apps.MimeConstants;
-import org.apache.fop.events.model.EventSeverity;
-import org.apache.fop.util.ConsoleEventListenerForTests;
-
-/**
- * Abstract base class for intermediate format tests.
- */
-public abstract class AbstractIntermediateTestCase {
-
- /** the test environment */
- protected static TestAssistant testAssistant = new TestAssistant();
-
- /** the FOP factory */
- protected FopFactory fopFactory;
-
- /** the directory containing the tests */
- protected File testDir = new File("test/layoutengine/standard-testcases");
- /** the output directory for any files generated by the tests */
- protected File outputDir;
-
- /** the test file */
- protected File testFile;
- /** the test document as DOM */
- protected Document testDoc;
- /** the intermediate format document as DOM */
- protected Document intermediate;
-
- /**
- * Constructor for the test suite that is used for each test file.
- * @param testFile the test file to run
- * @throws IOException if an I/O error occurs while loading the test case
- */
- public AbstractIntermediateTestCase(File testFile)
- throws IOException {
- this.testFile = testFile;
- }
-
- @Before
- public void setUp() throws Exception {
- setupOutputDirectory();
- this.testDoc = testAssistant.loadTestCase(testFile);
- this.fopFactory = testAssistant.getFopFactory(testDoc);
- intermediate = buildIntermediateDocument(testAssistant.getTestcase2FOStylesheet());
- if (outputDir != null) {
- testAssistant.saveDOM(intermediate, new File(outputDir,
- testFile.getName() + ".1" + getIntermediateFileExtension()));
- }
- }
-
- @After
- public void tearDown() throws Exception {
- //Release memory
- this.intermediate = null;
- this.fopFactory = null;
- this.testDoc = null;
- }
-
- /**
- * Returns the file extension for the intermediate file format.
- * @return the file extension
- */
- protected abstract String getIntermediateFileExtension();
-
- /**
- * Returns the MIME type for which to test or to mimic for the intermediate format.
- * @return the MIME type
- */
- protected String getTargetMIME() {
- return MimeConstants.MIME_PDF;
- }
-
- /**
- * Validates the intermediate format file.
- * @param doc the intermediate file
- * @throws IOException if an IO error occurs while loading the schema
- * @throws SAXException if a SAX-related exception (including a validation error) occurs
- */
- protected void validate(Document doc) throws SAXException, IOException {
- //nop by default
- }
-
- /**
- * Builds an intermediate format document from a source file.
- * @param templates the (optional) stylesheet
- * @return the intermediate format document as a DOM
- * @throws Exception if an error occurs while processing the document
- */
- protected abstract Document buildIntermediateDocument(Templates templates) throws Exception;
-
- /**
- * Creates a new FOP user agent.
- * @return the user agent
- */
- protected FOUserAgent createUserAgent() {
- FOUserAgent userAgent = fopFactory.newFOUserAgent();
- try {
- userAgent.setBaseURL(testDir.toURI().toURL().toExternalForm());
- userAgent.getEventBroadcaster().addEventListener(
- new ConsoleEventListenerForTests(testFile.getName(), EventSeverity.FATAL));
- } catch (MalformedURLException e) {
- // Shouldn't happen
- throw new AssertionError();
- }
- return userAgent;
- }
-
- /**
- * Sets up the output directory.
- */
- protected void setupOutputDirectory() {
- String s = System.getProperty("fop.intermediate.outdir");
- if (s != null && s.length() > 0) {
- outputDir = new File(s);
- outputDir.mkdirs();
- }
- }
-
- /**
- * Tests the area tree parser by running the parsed area tree again through the area tree
- * renderer. The source and result documents are compared to each other.
- * @throws Exception if the test fails
- */
- public void testParserToIntermediateFormat() throws Exception {
- validate(intermediate);
- Source src = new DOMSource(intermediate);
- Document doc = parseAndRenderToIntermediateFormat(src);
- if (outputDir != null) {
- File tgtFile = new File(outputDir, testFile.getName() + ".2"
- + getIntermediateFileExtension());
- testAssistant.saveDOM(doc, tgtFile);
- }
-
- XMLAssert.assertXMLEqual(intermediate, doc);
- }
-
- /**
- * Parses the intermediate file and renders it back to the intermediate format.
- * @param src the source for the intermediate file
- * @return a DOM Document with the re-created intermediate file
- * @throws Exception if an error occurs while processing the document
- */
- protected abstract Document parseAndRenderToIntermediateFormat(Source src) throws Exception;
-
- /**
- * Tests the area tree parser by sending the parsed area tree to the PDF Renderer. Some
- * errors might be caught by the PDFRenderer.
- * @throws Exception if the test fails
- */
- public void testParserToPDF() throws Exception {
- OutputStream out;
- if (outputDir != null) {
- File tgtFile = new File(outputDir, testFile.getName() + ".pdf");
- out = new FileOutputStream(tgtFile);
- out = new BufferedOutputStream(out);
- } else {
- out = new NullOutputStream();
- }
- try {
- Source src = new DOMSource(intermediate);
- parseAndRender(src, out);
- } finally {
- IOUtils.closeQuietly(out);
- }
- }
-
- /**
- * Parses and renders an intermediate format document to a final format.
- * @param src the source document
- * @param out the target output stream
- * @throws Exception if an error occurs while rendering the document
- */
- protected abstract void parseAndRender(Source src, OutputStream out)
- throws Exception;
-
- /**
- * Run the test.
- *
- * @throws Exception if an error occurs during the test
- */
- public abstract void runTest() throws Exception;
-
- /**
- * Sets an error listener which doesn't swallow errors like Xalan's default one.
- * @param transformer the transformer to set the error listener on
- */
- protected void setErrorListener(Transformer transformer) {
- transformer.setErrorListener(new ErrorListener() {
-
- public void error(TransformerException exception) throws TransformerException {
- throw exception;
- }
-
- public void fatalError(TransformerException exception) throws TransformerException {
- throw exception;
- }
-
- public void warning(TransformerException exception) throws TransformerException {
- //ignore
- }
-
- });
- }
-
-}
* Tests the area tree parser.
*/
@RunWith(Parameterized.class)
-public class AreaTreeParserTestCase extends AbstractIntermediateTestCase {
+public class AreaTreeParserTestCase extends AbstractIntermediateTest {
/**
* Creates the parameters for this test.
* Tests the intermediate format parser.
*/
@RunWith(Parameterized.class)
-public class IFParserTestCase extends AbstractIFTestCase {
+public class IFParserTestCase extends AbstractIFTest {
/**
* Gets the parameters for this test
* Test case for the IF output.
*/
@RunWith(Parameterized.class)
-public class IFTestCase extends AbstractIFTestCase {
+public class IFTestCase extends AbstractIFTest {
/**
* Gets the files for this test.
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.layoutengine;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.List;
+
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMResult;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.sax.SAXResult;
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
+
+import org.apache.fop.DebugHelper;
+import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.apps.Fop;
+import org.apache.fop.apps.FopFactory;
+import org.apache.fop.apps.FormattingResults;
+import org.apache.fop.area.AreaTreeModel;
+import org.apache.fop.area.AreaTreeParser;
+import org.apache.fop.area.RenderPagesModel;
+import org.apache.fop.events.model.EventSeverity;
+import org.apache.fop.fonts.FontInfo;
+import org.apache.fop.intermediate.IFTester;
+import org.apache.fop.intermediate.TestAssistant;
+import org.apache.fop.layoutmgr.ElementListObserver;
+import org.apache.fop.render.intermediate.IFContext;
+import org.apache.fop.render.intermediate.IFRenderer;
+import org.apache.fop.render.intermediate.IFSerializer;
+import org.apache.fop.render.xml.XMLRenderer;
+import org.apache.fop.util.ConsoleEventListenerForTests;
+import org.apache.fop.util.DelegatingContentHandler;
+
+/**
+ * Class for testing the FOP's layout engine using testcases specified in XML
+ * files.
+ */
+@RunWith(Parameterized.class)
+public class LayoutEngineTestCase {
+ private static File areaTreeBackupDir;
+
+ @BeforeClass
+ public static void makeDirAndRegisterDebugHelper() throws IOException {
+ DebugHelper.registerStandardElementListObservers();
+ areaTreeBackupDir = new File("build/test-results/layoutengine");
+ if (!areaTreeBackupDir.mkdirs() && !areaTreeBackupDir.exists()) {
+ throw new IOException("Failed to create the layout engine directory at "
+ + "build/test-results/layoutengine");
+ }
+ }
+
+ /**
+ * Creates the parameters for this test.
+ *
+ * @return the list of file arrays populated with test files
+ * @throws IOException if an I/O error occurs while reading the test file
+ */
+ @Parameters
+ public static Collection<File[]> getParameters() throws IOException {
+ return LayoutEngineTestUtils.getLayoutTestFiles();
+ }
+
+ private TestAssistant testAssistant = new TestAssistant();
+
+ private LayoutEngineChecksFactory layoutEngineChecksFactory = new LayoutEngineChecksFactory();
+
+ private IFTester ifTester;
+ private File testFile;
+
+ private TransformerFactory tfactory = TransformerFactory.newInstance();
+
+ /**
+ * Constructs a new instance.
+ *
+ * @param testFile the test file
+ */
+ public LayoutEngineTestCase(File testFile) {
+ this.ifTester = new IFTester(tfactory, areaTreeBackupDir);
+ this.testFile = testFile;
+ }
+
+ /**
+ * Runs a single layout engine test case.
+ * @throws TransformerException In case of an XSLT/JAXP problem
+ * @throws IOException In case of an I/O problem
+ * @throws SAXException In case of a problem during SAX processing
+ * @throws ParserConfigurationException In case of a problem with the XML parser setup
+ */
+ @Test
+ public void runTest() throws TransformerException, SAXException, IOException,
+ ParserConfigurationException {
+
+ DOMResult domres = new DOMResult();
+
+ ElementListCollector elCollector = new ElementListCollector();
+ ElementListObserver.addObserver(elCollector);
+
+ Fop fop;
+ FopFactory effFactory;
+ try {
+ Document testDoc = testAssistant.loadTestCase(testFile);
+ effFactory = testAssistant.getFopFactory(testDoc);
+
+ //Setup Transformer to convert the testcase XML to XSL-FO
+ Transformer transformer = testAssistant.getTestcase2FOStylesheet().newTransformer();
+ Source src = new DOMSource(testDoc);
+
+ //Setup Transformer to convert the area tree to a DOM
+ TransformerHandler athandler;
+ athandler = testAssistant.getTransformerFactory().newTransformerHandler();
+ athandler.setResult(domres);
+
+ //Setup FOP for area tree rendering
+ FOUserAgent ua = effFactory.newFOUserAgent();
+ ua.setBaseURL(testFile.getParentFile().toURI().toURL().toString());
+ ua.getEventBroadcaster().addEventListener(
+ new ConsoleEventListenerForTests(testFile.getName(), EventSeverity.WARN));
+
+ XMLRenderer atrenderer = new XMLRenderer();
+ atrenderer.setUserAgent(ua);
+ atrenderer.setContentHandler(athandler);
+ ua.setRendererOverride(atrenderer);
+ fop = effFactory.newFop(ua);
+
+ SAXResult fores = new SAXResult(fop.getDefaultHandler());
+ transformer.transform(src, fores);
+ } finally {
+ ElementListObserver.removeObserver(elCollector);
+ }
+
+ Document doc = (Document)domres.getNode();
+ if (areaTreeBackupDir != null) {
+ testAssistant.saveDOM(doc,
+ new File(areaTreeBackupDir, testFile.getName() + ".at.xml"));
+ }
+ FormattingResults results = fop.getResults();
+ LayoutResult result = new LayoutResult(doc, elCollector, results);
+ checkAll(effFactory, testFile, result);
+ }
+
+ /**
+ * Perform all checks on the area tree and, optionally, on the intermediate format.
+ * @param fopFactory the FOP factory
+ * @param testFile Test case XML file
+ * @param result The layout results
+ * @throws TransformerException if a problem occurs in XSLT/JAXP
+ */
+ protected void checkAll(FopFactory fopFactory, File testFile, LayoutResult result)
+ throws TransformerException {
+ Element testRoot = testAssistant.getTestRoot(testFile);
+
+ NodeList nodes;
+ //AT tests only when checks are available
+ nodes = testRoot.getElementsByTagName("at-checks");
+ if (nodes.getLength() > 0) {
+ Element atChecks = (Element)nodes.item(0);
+ doATChecks(atChecks, result);
+ }
+
+ //IF tests only when checks are available
+ nodes = testRoot.getElementsByTagName("if-checks");
+ if (nodes.getLength() > 0) {
+ Element ifChecks = (Element)nodes.item(0);
+ Document ifDocument = createIF(fopFactory, testFile, result.getAreaTree());
+ ifTester.doIFChecks(testFile.getName(), ifChecks, ifDocument);
+ }
+ }
+
+ private Document createIF(FopFactory fopFactory, File testFile, Document areaTreeXML)
+ throws TransformerException {
+ try {
+ FOUserAgent ua = fopFactory.newFOUserAgent();
+ ua.setBaseURL(testFile.getParentFile().toURI().toURL().toExternalForm());
+ ua.getEventBroadcaster().addEventListener(
+ new ConsoleEventListenerForTests(testFile.getName(), EventSeverity.WARN));
+
+ IFRenderer ifRenderer = new IFRenderer();
+ ifRenderer.setUserAgent(ua);
+
+ IFSerializer serializer = new IFSerializer();
+ serializer.setContext(new IFContext(ua));
+ DOMResult result = new DOMResult();
+ serializer.setResult(result);
+ ifRenderer.setDocumentHandler(serializer);
+
+ ua.setRendererOverride(ifRenderer);
+ FontInfo fontInfo = new FontInfo();
+ //Construct the AreaTreeModel that will received the individual pages
+ final AreaTreeModel treeModel = new RenderPagesModel(ua,
+ null, fontInfo, null);
+
+ //Iterate over all intermediate files
+ AreaTreeParser parser = new AreaTreeParser();
+ ContentHandler handler = parser.getContentHandler(treeModel, ua);
+
+ DelegatingContentHandler proxy = new DelegatingContentHandler() {
+
+ public void endDocument() throws SAXException {
+ super.endDocument();
+ //Signal the end of the processing.
+ //The renderer can finalize the target document.
+ treeModel.endDocument();
+ }
+
+ };
+ proxy.setDelegateContentHandler(handler);
+
+ Transformer transformer = tfactory.newTransformer();
+ transformer.transform(new DOMSource(areaTreeXML), new SAXResult(proxy));
+
+ return (Document)result.getNode();
+ } catch (Exception e) {
+ throw new TransformerException(
+ "Error while generating intermediate format file: " + e.getMessage(), e);
+ }
+ }
+
+ private void doATChecks(Element checksRoot, LayoutResult result) {
+ List<LayoutEngineCheck> checks = layoutEngineChecksFactory.createCheckList(checksRoot);
+ if (checks.size() == 0) {
+ throw new RuntimeException("No available area tree check");
+ }
+ for (LayoutEngineCheck check : checks) {
+ check.check(result);
+ }
+ }
+
+}
* JUnit test suit for running layout engine test under JUnit control.
*/
@RunWith(Suite.class)
-@SuiteClasses({ LayoutEngineTester.class })
+@SuiteClasses({ LayoutEngineTestCase.class })
public class LayoutEngineTestSuite {
}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.layoutengine;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.List;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.Source;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMResult;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.sax.SAXResult;
-import javax.xml.transform.sax.TransformerHandler;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-import org.xml.sax.ContentHandler;
-import org.xml.sax.SAXException;
-
-import org.apache.fop.DebugHelper;
-import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.apps.Fop;
-import org.apache.fop.apps.FopFactory;
-import org.apache.fop.apps.FormattingResults;
-import org.apache.fop.area.AreaTreeModel;
-import org.apache.fop.area.AreaTreeParser;
-import org.apache.fop.area.RenderPagesModel;
-import org.apache.fop.events.model.EventSeverity;
-import org.apache.fop.fonts.FontInfo;
-import org.apache.fop.intermediate.IFTester;
-import org.apache.fop.intermediate.TestAssistant;
-import org.apache.fop.layoutmgr.ElementListObserver;
-import org.apache.fop.render.intermediate.IFContext;
-import org.apache.fop.render.intermediate.IFRenderer;
-import org.apache.fop.render.intermediate.IFSerializer;
-import org.apache.fop.render.xml.XMLRenderer;
-import org.apache.fop.util.ConsoleEventListenerForTests;
-import org.apache.fop.util.DelegatingContentHandler;
-
-/**
- * Class for testing the FOP's layout engine using testcases specified in XML
- * files.
- */
-@RunWith(Parameterized.class)
-public class LayoutEngineTester {
- private static File areaTreeBackupDir;
-
- @BeforeClass
- public static void makeDirAndRegisterDebugHelper() throws IOException {
- DebugHelper.registerStandardElementListObservers();
- areaTreeBackupDir = new File("build/test-results/layoutengine");
- if (!areaTreeBackupDir.mkdirs() && !areaTreeBackupDir.exists()) {
- throw new IOException("Failed to create the layout engine directory at "
- + "build/test-results/layoutengine");
- }
- }
-
- /**
- * Creates the parameters for this test.
- *
- * @return the list of file arrays populated with test files
- * @throws IOException if an I/O error occurs while reading the test file
- */
- @Parameters
- public static Collection<File[]> getParameters() throws IOException {
- return LayoutEngineTestUtils.getLayoutTestFiles();
- }
-
- private TestAssistant testAssistant = new TestAssistant();
-
- private LayoutEngineChecksFactory layoutEngineChecksFactory = new LayoutEngineChecksFactory();
-
- private IFTester ifTester;
- private File testFile;
-
- private TransformerFactory tfactory = TransformerFactory.newInstance();
-
- /**
- * Constructs a new instance.
- *
- * @param testFile the test file
- */
- public LayoutEngineTester(File testFile) {
- this.ifTester = new IFTester(tfactory, areaTreeBackupDir);
- this.testFile = testFile;
- }
-
- /**
- * Runs a single layout engine test case.
- * @throws TransformerException In case of an XSLT/JAXP problem
- * @throws IOException In case of an I/O problem
- * @throws SAXException In case of a problem during SAX processing
- * @throws ParserConfigurationException In case of a problem with the XML parser setup
- */
- @Test
- public void runTest() throws TransformerException, SAXException, IOException,
- ParserConfigurationException {
-
- DOMResult domres = new DOMResult();
-
- ElementListCollector elCollector = new ElementListCollector();
- ElementListObserver.addObserver(elCollector);
-
- Fop fop;
- FopFactory effFactory;
- try {
- Document testDoc = testAssistant.loadTestCase(testFile);
- effFactory = testAssistant.getFopFactory(testDoc);
-
- //Setup Transformer to convert the testcase XML to XSL-FO
- Transformer transformer = testAssistant.getTestcase2FOStylesheet().newTransformer();
- Source src = new DOMSource(testDoc);
-
- //Setup Transformer to convert the area tree to a DOM
- TransformerHandler athandler;
- athandler = testAssistant.getTransformerFactory().newTransformerHandler();
- athandler.setResult(domres);
-
- //Setup FOP for area tree rendering
- FOUserAgent ua = effFactory.newFOUserAgent();
- ua.setBaseURL(testFile.getParentFile().toURI().toURL().toString());
- ua.getEventBroadcaster().addEventListener(
- new ConsoleEventListenerForTests(testFile.getName(), EventSeverity.WARN));
-
- XMLRenderer atrenderer = new XMLRenderer();
- atrenderer.setUserAgent(ua);
- atrenderer.setContentHandler(athandler);
- ua.setRendererOverride(atrenderer);
- fop = effFactory.newFop(ua);
-
- SAXResult fores = new SAXResult(fop.getDefaultHandler());
- transformer.transform(src, fores);
- } finally {
- ElementListObserver.removeObserver(elCollector);
- }
-
- Document doc = (Document)domres.getNode();
- if (areaTreeBackupDir != null) {
- testAssistant.saveDOM(doc,
- new File(areaTreeBackupDir, testFile.getName() + ".at.xml"));
- }
- FormattingResults results = fop.getResults();
- LayoutResult result = new LayoutResult(doc, elCollector, results);
- checkAll(effFactory, testFile, result);
- }
-
- /**
- * Perform all checks on the area tree and, optionally, on the intermediate format.
- * @param fopFactory the FOP factory
- * @param testFile Test case XML file
- * @param result The layout results
- * @throws TransformerException if a problem occurs in XSLT/JAXP
- */
- protected void checkAll(FopFactory fopFactory, File testFile, LayoutResult result)
- throws TransformerException {
- Element testRoot = testAssistant.getTestRoot(testFile);
-
- NodeList nodes;
- //AT tests only when checks are available
- nodes = testRoot.getElementsByTagName("at-checks");
- if (nodes.getLength() > 0) {
- Element atChecks = (Element)nodes.item(0);
- doATChecks(atChecks, result);
- }
-
- //IF tests only when checks are available
- nodes = testRoot.getElementsByTagName("if-checks");
- if (nodes.getLength() > 0) {
- Element ifChecks = (Element)nodes.item(0);
- Document ifDocument = createIF(fopFactory, testFile, result.getAreaTree());
- ifTester.doIFChecks(testFile.getName(), ifChecks, ifDocument);
- }
- }
-
- private Document createIF(FopFactory fopFactory, File testFile, Document areaTreeXML)
- throws TransformerException {
- try {
- FOUserAgent ua = fopFactory.newFOUserAgent();
- ua.setBaseURL(testFile.getParentFile().toURI().toURL().toExternalForm());
- ua.getEventBroadcaster().addEventListener(
- new ConsoleEventListenerForTests(testFile.getName(), EventSeverity.WARN));
-
- IFRenderer ifRenderer = new IFRenderer();
- ifRenderer.setUserAgent(ua);
-
- IFSerializer serializer = new IFSerializer();
- serializer.setContext(new IFContext(ua));
- DOMResult result = new DOMResult();
- serializer.setResult(result);
- ifRenderer.setDocumentHandler(serializer);
-
- ua.setRendererOverride(ifRenderer);
- FontInfo fontInfo = new FontInfo();
- //Construct the AreaTreeModel that will received the individual pages
- final AreaTreeModel treeModel = new RenderPagesModel(ua,
- null, fontInfo, null);
-
- //Iterate over all intermediate files
- AreaTreeParser parser = new AreaTreeParser();
- ContentHandler handler = parser.getContentHandler(treeModel, ua);
-
- DelegatingContentHandler proxy = new DelegatingContentHandler() {
-
- public void endDocument() throws SAXException {
- super.endDocument();
- //Signal the end of the processing.
- //The renderer can finalize the target document.
- treeModel.endDocument();
- }
-
- };
- proxy.setDelegateContentHandler(handler);
-
- Transformer transformer = tfactory.newTransformer();
- transformer.transform(new DOMSource(areaTreeXML), new SAXResult(proxy));
-
- return (Document)result.getNode();
- } catch (Exception e) {
- throw new TransformerException(
- "Error while generating intermediate format file: " + e.getMessage(), e);
- }
- }
-
- private void doATChecks(Element checksRoot, LayoutResult result) {
- List<LayoutEngineCheck> checks = layoutEngineChecksFactory.createCheckList(checksRoot);
- if (checks.size() == 0) {
- throw new RuntimeException("No available area tree check");
- }
- for (LayoutEngineCheck check : checks) {
- check.check(result);
- }
- }
-
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.render;
+
+import java.io.File;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Map;
+import java.util.MissingResourceException;
+
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.sax.SAXResult;
+import javax.xml.transform.stream.StreamSource;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.apps.Fop;
+import org.apache.fop.apps.FopFactory;
+import org.apache.fop.apps.MimeConstants;
+
+/**
+ * Abstract base class for rendering (output) verification tests.
+ */
+public abstract class AbstractRenderingTest {
+
+ private static final Map<String, String> MIME_MAP = new java.util.HashMap<String, String>();
+
+ static {
+ MIME_MAP.put(MimeConstants.MIME_PDF, ".pdf");
+ MIME_MAP.put(MimeConstants.MIME_POSTSCRIPT, ".ps");
+ MIME_MAP.put(MimeConstants.MIME_AFP, ".afp");
+ }
+
+ /** the JAXP TransformerFactory */
+ protected TransformerFactory tFactory = TransformerFactory.newInstance();
+ /** the FopFactory */
+ protected FopFactory fopFactory = FopFactory.newInstance();
+
+ /**
+ * Renders a test file.
+ * @param ua the user agent (with override set!)
+ * @param resourceName the resource name for the FO file
+ * @param suffix a suffix for the output filename
+ * @param outputFormat MIME type of the requested output format
+ * @return the output file
+ * @throws Exception if an error occurs
+ */
+ protected File renderFile(FOUserAgent ua, String resourceName, String suffix,
+ String outputFormat) throws Exception {
+ String extension = MIME_MAP.get(outputFormat);
+ assert extension != null;
+ File outputFile = new File("build/test-results/" + resourceName + suffix + extension);
+ File outputDir = outputFile.getParentFile();
+ FileUtils.forceMkdir(outputDir);
+
+ // Prepare input file
+ InputStream in = getClass().getResourceAsStream(resourceName);
+ if (in == null) {
+ throw new MissingResourceException(resourceName + " not found in resources",
+ getClass().getName(), null);
+ }
+ try {
+ Source src = new StreamSource(in);
+
+ // Create output file
+ OutputStream out = new java.io.FileOutputStream(outputFile);
+ out = new java.io.BufferedOutputStream(out);
+ try {
+ Fop fop = fopFactory.newFop(outputFormat, ua, out);
+ SAXResult res = new SAXResult(fop.getDefaultHandler());
+
+ Transformer transformer = tFactory.newTransformer();
+ transformer.transform(src, res);
+ } finally {
+ IOUtils.closeQuietly(out);
+ }
+ } finally {
+ IOUtils.closeQuietly(in);
+ }
+ return outputFile;
+ }
+
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.render;
-
-import java.io.File;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Map;
-import java.util.MissingResourceException;
-
-import javax.xml.transform.Source;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.sax.SAXResult;
-import javax.xml.transform.stream.StreamSource;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.IOUtils;
-import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.apps.Fop;
-import org.apache.fop.apps.FopFactory;
-import org.apache.fop.apps.MimeConstants;
-
-/**
- * Abstract base class for rendering (output) verification tests.
- */
-public abstract class AbstractRenderingTestCase {
-
- private static final Map<String, String> MIME_MAP = new java.util.HashMap<String, String>();
-
- static {
- MIME_MAP.put(MimeConstants.MIME_PDF, ".pdf");
- MIME_MAP.put(MimeConstants.MIME_POSTSCRIPT, ".ps");
- MIME_MAP.put(MimeConstants.MIME_AFP, ".afp");
- }
-
- /** the JAXP TransformerFactory */
- protected TransformerFactory tFactory = TransformerFactory.newInstance();
- /** the FopFactory */
- protected FopFactory fopFactory = FopFactory.newInstance();
-
- /**
- * Renders a test file.
- * @param ua the user agent (with override set!)
- * @param resourceName the resource name for the FO file
- * @param suffix a suffix for the output filename
- * @param outputFormat MIME type of the requested output format
- * @return the output file
- * @throws Exception if an error occurs
- */
- protected File renderFile(FOUserAgent ua, String resourceName, String suffix,
- String outputFormat) throws Exception {
- String extension = MIME_MAP.get(outputFormat);
- assert extension != null;
- File outputFile = new File("build/test-results/" + resourceName + suffix + extension);
- File outputDir = outputFile.getParentFile();
- FileUtils.forceMkdir(outputDir);
-
- // Prepare input file
- InputStream in = getClass().getResourceAsStream(resourceName);
- if (in == null) {
- throw new MissingResourceException(resourceName + " not found in resources",
- getClass().getName(), null);
- }
- try {
- Source src = new StreamSource(in);
-
- // Create output file
- OutputStream out = new java.io.FileOutputStream(outputFile);
- out = new java.io.BufferedOutputStream(out);
- try {
- Fop fop = fopFactory.newFop(outputFormat, ua, out);
- SAXResult res = new SAXResult(fop.getDefaultHandler());
-
- Transformer transformer = tFactory.newTransformer();
- transformer.transform(src, res);
- } finally {
- IOUtils.closeQuietly(out);
- }
- } finally {
- IOUtils.closeQuietly(in);
- }
- return outputFile;
- }
-
-}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.render;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import org.apache.commons.io.output.NullOutputStream;
-import org.apache.fop.apps.FOPException;
-import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.apps.FopFactory;
-import org.apache.fop.apps.MimeConstants;
-import org.apache.fop.area.AreaTreeHandler;
-import org.apache.fop.fo.FOEventHandler;
-import org.apache.fop.render.intermediate.IFContext;
-import org.apache.fop.render.intermediate.IFDocumentHandler;
-import org.apache.fop.render.intermediate.IFRenderer;
-import org.apache.fop.render.pdf.PDFDocumentHandler;
-import org.apache.fop.render.rtf.RTFHandler;
-import org.junit.Test;
-
-/**
- * Tests for {@link RendererFactory}.
- */
-public class RendererFactoryTest {
-
- @Test
- public void testDocumentHandlerLevel() throws Exception {
- FopFactory fopFactory = FopFactory.newInstance();
- RendererFactory factory = fopFactory.getRendererFactory();
- FOUserAgent ua;
- IFDocumentHandler handler;
- IFDocumentHandler overrideHandler;
-
- ua = fopFactory.newFOUserAgent();
- handler = factory.createDocumentHandler(ua, MimeConstants.MIME_PDF);
- assertTrue(handler instanceof PDFDocumentHandler);
-
- ua = fopFactory.newFOUserAgent();
- overrideHandler = new PDFDocumentHandler();
- overrideHandler.setContext(new IFContext(ua));
- ua.setDocumentHandlerOverride(overrideHandler);
- handler = factory.createDocumentHandler(ua, null);
- assertTrue(handler == overrideHandler);
-
- ua = fopFactory.newFOUserAgent();
- try {
- handler = factory.createDocumentHandler(ua, "invalid/format");
- fail("Expected UnsupportedOperationException");
- } catch (UnsupportedOperationException uoe) {
- //expected
- }
- }
-
- @Test
- public void testRendererLevel() throws Exception {
- FopFactory fopFactory = FopFactory.newInstance();
- RendererFactory factory = fopFactory.getRendererFactory();
- FOUserAgent ua;
- Renderer renderer;
-
- ua = fopFactory.newFOUserAgent();
- renderer = factory.createRenderer(ua, MimeConstants.MIME_PDF);
- assertTrue(renderer instanceof IFRenderer);
-
- ua = fopFactory.newFOUserAgent();
- renderer = factory.createRenderer(ua, MimeConstants.MIME_FOP_IF);
- assertTrue(renderer instanceof IFRenderer);
-
- ua = fopFactory.newFOUserAgent();
- IFDocumentHandler overrideHandler;
- overrideHandler = new PDFDocumentHandler();
- overrideHandler.setContext(new IFContext(ua));
- ua.setDocumentHandlerOverride(overrideHandler);
- renderer = factory.createRenderer(ua, null);
- assertTrue(renderer instanceof IFRenderer);
-
- ua = fopFactory.newFOUserAgent();
- try {
- renderer = factory.createRenderer(ua, "invalid/format");
- fail("Expected UnsupportedOperationException");
- } catch (UnsupportedOperationException uoe) {
- //expected
- }
- }
-
- @Test
- public void testFOEventHandlerLevel() throws Exception {
- FopFactory fopFactory = FopFactory.newInstance();
- RendererFactory factory = fopFactory.getRendererFactory();
- FOUserAgent ua;
- FOEventHandler foEventHandler;
- FOEventHandler overrideFOEventHandler;
-
- ua = fopFactory.newFOUserAgent();
- foEventHandler = factory.createFOEventHandler(
- ua, MimeConstants.MIME_PDF, new NullOutputStream());
- assertTrue(foEventHandler instanceof AreaTreeHandler);
-
- ua = fopFactory.newFOUserAgent();
- foEventHandler = factory.createFOEventHandler(
- ua, MimeConstants.MIME_RTF, new NullOutputStream());
- assertTrue(foEventHandler instanceof RTFHandler);
-
- ua = fopFactory.newFOUserAgent();
- try {
- foEventHandler = factory.createFOEventHandler(
- ua, "invalid/format", new NullOutputStream());
- fail("Expected UnsupportedOperationException");
- } catch (UnsupportedOperationException uoe) {
- //expected
- }
-
- ua = fopFactory.newFOUserAgent();
- try {
- foEventHandler = factory.createFOEventHandler(
- ua, MimeConstants.MIME_PDF, null);
- fail("Expected FOPException because of missing OutputStream");
- } catch (FOPException fe) {
- //expected
- }
-
- ua = fopFactory.newFOUserAgent();
- overrideFOEventHandler = new RTFHandler(ua, new NullOutputStream());
- ua.setFOEventHandlerOverride(overrideFOEventHandler);
- foEventHandler = factory.createFOEventHandler(
- ua, null, null);
- assertTrue(foEventHandler == overrideFOEventHandler);
- }
-
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.render;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import org.junit.Test;
+
+import org.apache.commons.io.output.NullOutputStream;
+
+import org.apache.fop.apps.FOPException;
+import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.apps.FopFactory;
+import org.apache.fop.apps.MimeConstants;
+import org.apache.fop.area.AreaTreeHandler;
+import org.apache.fop.fo.FOEventHandler;
+import org.apache.fop.render.intermediate.IFContext;
+import org.apache.fop.render.intermediate.IFDocumentHandler;
+import org.apache.fop.render.intermediate.IFRenderer;
+import org.apache.fop.render.pdf.PDFDocumentHandler;
+import org.apache.fop.render.rtf.RTFHandler;
+
+/**
+ * Tests for {@link RendererFactory}.
+ */
+public class RendererFactoryTestCase {
+
+ @Test
+ public void testDocumentHandlerLevel() throws Exception {
+ FopFactory fopFactory = FopFactory.newInstance();
+ RendererFactory factory = fopFactory.getRendererFactory();
+ FOUserAgent ua;
+ IFDocumentHandler handler;
+ IFDocumentHandler overrideHandler;
+
+ ua = fopFactory.newFOUserAgent();
+ handler = factory.createDocumentHandler(ua, MimeConstants.MIME_PDF);
+
+ ua = fopFactory.newFOUserAgent();
+ overrideHandler = new PDFDocumentHandler();
+ overrideHandler.setContext(new IFContext(ua));
+ ua.setDocumentHandlerOverride(overrideHandler);
+ handler = factory.createDocumentHandler(ua, null);
+ assertTrue(handler == overrideHandler);
+
+ ua = fopFactory.newFOUserAgent();
+ try {
+ handler = factory.createDocumentHandler(ua, "invalid/format");
+ fail("Expected UnsupportedOperationException");
+ } catch (UnsupportedOperationException uoe) {
+ //expected
+ }
+ }
+
+ @Test
+ public void testRendererLevel() throws Exception {
+ FopFactory fopFactory = FopFactory.newInstance();
+ RendererFactory factory = fopFactory.getRendererFactory();
+ FOUserAgent ua;
+ Renderer renderer;
+
+ ua = fopFactory.newFOUserAgent();
+ renderer = factory.createRenderer(ua, MimeConstants.MIME_PDF);
+ assertTrue(renderer instanceof IFRenderer);
+
+ ua = fopFactory.newFOUserAgent();
+ renderer = factory.createRenderer(ua, MimeConstants.MIME_FOP_IF);
+ assertTrue(renderer instanceof IFRenderer);
+
+ ua = fopFactory.newFOUserAgent();
+ IFDocumentHandler overrideHandler;
+ overrideHandler = new PDFDocumentHandler();
+ overrideHandler.setContext(new IFContext(ua));
+ ua.setDocumentHandlerOverride(overrideHandler);
+ renderer = factory.createRenderer(ua, null);
+ assertTrue(renderer instanceof IFRenderer);
+
+ ua = fopFactory.newFOUserAgent();
+ try {
+ renderer = factory.createRenderer(ua, "invalid/format");
+ fail("Expected UnsupportedOperationException");
+ } catch (UnsupportedOperationException uoe) {
+ //expected
+ }
+ }
+
+ @Test
+ public void testFOEventHandlerLevel() throws Exception {
+ FopFactory fopFactory = FopFactory.newInstance();
+ RendererFactory factory = fopFactory.getRendererFactory();
+ FOUserAgent ua;
+ FOEventHandler foEventHandler;
+ FOEventHandler overrideFOEventHandler;
+
+ ua = fopFactory.newFOUserAgent();
+ foEventHandler = factory.createFOEventHandler(
+ ua, MimeConstants.MIME_PDF, new NullOutputStream());
+ assertTrue(foEventHandler instanceof AreaTreeHandler);
+
+ ua = fopFactory.newFOUserAgent();
+ foEventHandler = factory.createFOEventHandler(
+ ua, MimeConstants.MIME_RTF, new NullOutputStream());
+ assertTrue(foEventHandler instanceof RTFHandler);
+
+ ua = fopFactory.newFOUserAgent();
+ try {
+ foEventHandler = factory.createFOEventHandler(
+ ua, "invalid/format", new NullOutputStream());
+ fail("Expected UnsupportedOperationException");
+ } catch (UnsupportedOperationException uoe) {
+ //expected
+ }
+
+ ua = fopFactory.newFOUserAgent();
+ try {
+ foEventHandler = factory.createFOEventHandler(
+ ua, MimeConstants.MIME_PDF, null);
+ fail("Expected FOPException because of missing OutputStream");
+ } catch (FOPException fe) {
+ //expected
+ }
+
+ ua = fopFactory.newFOUserAgent();
+ overrideFOEventHandler = new RTFHandler(ua, new NullOutputStream());
+ ua.setFOEventHandlerOverride(overrideFOEventHandler);
+ foEventHandler = factory.createFOEventHandler(
+ ua, null, null);
+ assertTrue(foEventHandler == overrideFOEventHandler);
+ }
+
+}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.render.afp;
+
+import java.io.File;
+
+import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.apps.MimeConstants;
+import org.apache.fop.render.AbstractRenderingTest;
+
+/**
+ * Abstract base class for AFP verification tests.
+ */
+abstract class AbstractAFPTest extends AbstractRenderingTest {
+
+ /**
+ * Renders a test file.
+ * @param ua the user agent (with override set!)
+ * @param resourceName the resource name for the FO file
+ * @param suffix a suffix for the output filename
+ * @return the output file
+ * @throws Exception if an error occurs
+ */
+ protected File renderFile(FOUserAgent ua, String resourceName, String suffix)
+ throws Exception {
+ return renderFile(ua, resourceName, suffix, MimeConstants.MIME_AFP);
+ }
+
+
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.render.afp;
-
-import java.io.File;
-
-import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.apps.MimeConstants;
-import org.apache.fop.render.AbstractRenderingTestCase;
-
-/**
- * Abstract base class for AFP verification tests.
- */
-abstract class AbstractAFPTestCase extends AbstractRenderingTestCase {
-
- /**
- * Renders a test file.
- * @param ua the user agent (with override set!)
- * @param resourceName the resource name for the FO file
- * @param suffix a suffix for the output filename
- * @return the output file
- * @throws Exception if an error occurs
- */
- protected File renderFile(FOUserAgent ua, String resourceName, String suffix)
- throws Exception {
- return renderFile(ua, resourceName, suffix, MimeConstants.MIME_AFP);
- }
-
-
-}
/**
* Tests generation of afp:no-operation (NOPs).
*/
-public class NoOperationTestCase extends AbstractAFPTestCase {
+public class NoOperationTestCase extends AbstractAFPTest {
/**
* Tests afp:no-operation.
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.render.extensions.prepress;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
-
-import java.awt.Dimension;
-import java.awt.Rectangle;
-
-import org.junit.Test;
-
-/**
- * Tests for the fox:bleed, fox:crop-offset, fox:crop-box extension properties.
- */
-public class PageBoundariesTest {
-
- private static final Dimension TEST_AREA_SIZE = new Dimension(20000, 15000);
-
- private static final Rectangle TEST_AREA = new Rectangle(TEST_AREA_SIZE);
-
- private static final String BLEED = "5pt";
-
- private static final String CROP_OFFSET = "8pt";
-
- /** Test for page boundaries. */
- @Test
- public void testBoundaries1() {
- PageBoundaries boundaries = new PageBoundaries(TEST_AREA_SIZE, BLEED, CROP_OFFSET, null);
- assertEquals(TEST_AREA, boundaries.getTrimBox());
-
- Rectangle bleedBox = boundaries.getBleedBox();
- assertNotNull("Expected not null object", bleedBox);
- assertEquals(-5000, bleedBox.x);
- assertEquals(-5000, bleedBox.y);
- assertEquals(30000, bleedBox.width);
- assertEquals(25000, bleedBox.height);
-
- Rectangle mediaBox = boundaries.getMediaBox();
- assertNotNull("Expected not null object", mediaBox);
- assertEquals(-8000, mediaBox.x);
- assertEquals(-8000, mediaBox.y);
- assertEquals(36000, mediaBox.width);
- assertEquals(31000, mediaBox.height);
- }
-
- /** Test for page boundaries. */
- @Test
- public void testBoundaries2() {
- PageBoundaries boundaries = new PageBoundaries(
- TEST_AREA_SIZE, BLEED, null, null);
- Rectangle bleedBox = boundaries.getBleedBox();
- assertNotNull("Expected not null object", bleedBox);
- assertEquals(-5000, bleedBox.x);
- assertEquals(-5000, bleedBox.y);
- assertEquals(30000, bleedBox.width);
- assertEquals(25000, bleedBox.height);
- assertEquals(bleedBox, boundaries.getMediaBox());
- }
-
- /** Two values for the properties. */
- @Test
- public void testBoundaries2Values() {
- PageBoundaries boundaries = new PageBoundaries(
- TEST_AREA_SIZE, "5pt 10pt", "6pt \t 12pt", null);
- Rectangle bleedBox = boundaries.getBleedBox();
- assertEquals(-10000, bleedBox.x);
- assertEquals(-5000, bleedBox.y);
- assertEquals(40000, bleedBox.width);
- assertEquals(25000, bleedBox.height);
-
- Rectangle mediaBox = boundaries.getMediaBox();
- assertEquals(-12000, mediaBox.x);
- assertEquals(-6000, mediaBox.y);
- assertEquals(44000, mediaBox.width);
- assertEquals(27000, mediaBox.height);
- }
-
- /** Three values for the properties. */
- @Test
- public void testBoundaries3Values() {
- PageBoundaries boundaries = new PageBoundaries(
- TEST_AREA_SIZE, "5pt 10pt 7pt", "6pt \t 12pt 14pt", null);
- Rectangle bleedBox = boundaries.getBleedBox();
- assertEquals(-10000, bleedBox.x);
- assertEquals(-5000, bleedBox.y);
- assertEquals(40000, bleedBox.width);
- assertEquals(27000, bleedBox.height);
-
- Rectangle mediaBox = boundaries.getMediaBox();
- assertEquals(-12000, mediaBox.x);
- assertEquals(-6000, mediaBox.y);
- assertEquals(44000, mediaBox.width);
- assertEquals(35000, mediaBox.height);
- }
-
- /** Four values for the properties. */
- @Test
- public void testBoundaries4Values() {
- PageBoundaries boundaries = new PageBoundaries(
- TEST_AREA_SIZE, "5pt 6pt 7pt 8pt", "9pt 10pt 11pt 12pt", null);
- Rectangle bleedBox = boundaries.getBleedBox();
- assertEquals(-8000, bleedBox.x);
- assertEquals(-5000, bleedBox.y);
- assertEquals(34000, bleedBox.width);
- assertEquals(27000, bleedBox.height);
-
- Rectangle mediaBox = boundaries.getMediaBox();
- assertEquals(-12000, mediaBox.x);
- assertEquals(-9000, mediaBox.y);
- assertEquals(42000, mediaBox.width);
- assertEquals(35000, mediaBox.height);
- }
-
- /** Test for the different values of crop-box. */
- @Test
- public void testCropBox() {
- PageBoundaries boundaries = new PageBoundaries(TEST_AREA_SIZE, BLEED, CROP_OFFSET, null);
- assertEquals(boundaries.getMediaBox(), boundaries.getCropBox());
-
- boundaries = new PageBoundaries(TEST_AREA_SIZE, BLEED, CROP_OFFSET, "");
- assertEquals(boundaries.getMediaBox(), boundaries.getCropBox());
-
- boundaries = new PageBoundaries(TEST_AREA_SIZE, BLEED, CROP_OFFSET, "trim-box");
- assertEquals(TEST_AREA, boundaries.getCropBox());
-
- boundaries = new PageBoundaries(TEST_AREA_SIZE, BLEED, CROP_OFFSET, "bleed-box");
- assertEquals(boundaries.getBleedBox(), boundaries.getCropBox());
-
- boundaries = new PageBoundaries(TEST_AREA_SIZE, BLEED, CROP_OFFSET, "media-box");
- assertEquals(boundaries.getMediaBox(), boundaries.getCropBox());
- }
-
- /** Test for default values returned when properties are null. */
- @Test
- public void testBoundariesNull() {
- PageBoundaries b = new PageBoundaries(TEST_AREA_SIZE, null, null, null);
-
- assertEquals("Result should be the same as TEST_AREA object", b.getTrimBox(), TEST_AREA);
- assertEquals("Result should be the same as TEST_AREA object", b.getBleedBox(), TEST_AREA);
- assertEquals("Result should be the same as TEST_AREA object", b.getMediaBox(), TEST_AREA);
- assertEquals("Result should be the same as TEST_AREA object", b.getCropBox(), TEST_AREA);
- }
-
- /** Units must be specified. */
- @Test
- public void testBoundariesFail() {
- try {
- new PageBoundaries(TEST_AREA_SIZE, "0", null, null);
- fail("Expected IllegalArgumentException. Box should have units");
- } catch (IllegalArgumentException iae) {
- // Good!
- }
- }
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.render.extensions.prepress;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
+import java.awt.Dimension;
+import java.awt.Rectangle;
+
+import org.junit.Test;
+
+/**
+ * Tests for the fox:bleed, fox:crop-offset, fox:crop-box extension properties.
+ */
+public class PageBoundariesTestCase {
+
+ private static final Dimension TEST_AREA_SIZE = new Dimension(20000, 15000);
+
+ private static final Rectangle TEST_AREA = new Rectangle(TEST_AREA_SIZE);
+
+ private static final String BLEED = "5pt";
+
+ private static final String CROP_OFFSET = "8pt";
+
+ /** Test for page boundaries. */
+ @Test
+ public void testBoundaries1() {
+ PageBoundaries boundaries = new PageBoundaries(TEST_AREA_SIZE, BLEED, CROP_OFFSET, null);
+ assertEquals(TEST_AREA, boundaries.getTrimBox());
+
+ Rectangle bleedBox = boundaries.getBleedBox();
+ assertNotNull("Expected not null object", bleedBox);
+ assertEquals(-5000, bleedBox.x);
+ assertEquals(-5000, bleedBox.y);
+ assertEquals(30000, bleedBox.width);
+ assertEquals(25000, bleedBox.height);
+
+ Rectangle mediaBox = boundaries.getMediaBox();
+ assertNotNull("Expected not null object", mediaBox);
+ assertEquals(-8000, mediaBox.x);
+ assertEquals(-8000, mediaBox.y);
+ assertEquals(36000, mediaBox.width);
+ assertEquals(31000, mediaBox.height);
+ }
+
+ /** Test for page boundaries. */
+ @Test
+ public void testBoundaries2() {
+ PageBoundaries boundaries = new PageBoundaries(
+ TEST_AREA_SIZE, BLEED, null, null);
+ Rectangle bleedBox = boundaries.getBleedBox();
+ assertNotNull("Expected not null object", bleedBox);
+ assertEquals(-5000, bleedBox.x);
+ assertEquals(-5000, bleedBox.y);
+ assertEquals(30000, bleedBox.width);
+ assertEquals(25000, bleedBox.height);
+ assertEquals(bleedBox, boundaries.getMediaBox());
+ }
+
+ /** Two values for the properties. */
+ @Test
+ public void testBoundaries2Values() {
+ PageBoundaries boundaries = new PageBoundaries(
+ TEST_AREA_SIZE, "5pt 10pt", "6pt \t 12pt", null);
+ Rectangle bleedBox = boundaries.getBleedBox();
+ assertEquals(-10000, bleedBox.x);
+ assertEquals(-5000, bleedBox.y);
+ assertEquals(40000, bleedBox.width);
+ assertEquals(25000, bleedBox.height);
+
+ Rectangle mediaBox = boundaries.getMediaBox();
+ assertEquals(-12000, mediaBox.x);
+ assertEquals(-6000, mediaBox.y);
+ assertEquals(44000, mediaBox.width);
+ assertEquals(27000, mediaBox.height);
+ }
+
+ /** Three values for the properties. */
+ @Test
+ public void testBoundaries3Values() {
+ PageBoundaries boundaries = new PageBoundaries(
+ TEST_AREA_SIZE, "5pt 10pt 7pt", "6pt \t 12pt 14pt", null);
+ Rectangle bleedBox = boundaries.getBleedBox();
+ assertEquals(-10000, bleedBox.x);
+ assertEquals(-5000, bleedBox.y);
+ assertEquals(40000, bleedBox.width);
+ assertEquals(27000, bleedBox.height);
+
+ Rectangle mediaBox = boundaries.getMediaBox();
+ assertEquals(-12000, mediaBox.x);
+ assertEquals(-6000, mediaBox.y);
+ assertEquals(44000, mediaBox.width);
+ assertEquals(35000, mediaBox.height);
+ }
+
+ /** Four values for the properties. */
+ @Test
+ public void testBoundaries4Values() {
+ PageBoundaries boundaries = new PageBoundaries(
+ TEST_AREA_SIZE, "5pt 6pt 7pt 8pt", "9pt 10pt 11pt 12pt", null);
+ Rectangle bleedBox = boundaries.getBleedBox();
+ assertEquals(-8000, bleedBox.x);
+ assertEquals(-5000, bleedBox.y);
+ assertEquals(34000, bleedBox.width);
+ assertEquals(27000, bleedBox.height);
+
+ Rectangle mediaBox = boundaries.getMediaBox();
+ assertEquals(-12000, mediaBox.x);
+ assertEquals(-9000, mediaBox.y);
+ assertEquals(42000, mediaBox.width);
+ assertEquals(35000, mediaBox.height);
+ }
+
+ /** Test for the different values of crop-box. */
+ @Test
+ public void testCropBox() {
+ PageBoundaries boundaries = new PageBoundaries(TEST_AREA_SIZE, BLEED, CROP_OFFSET, null);
+ assertEquals(boundaries.getMediaBox(), boundaries.getCropBox());
+
+ boundaries = new PageBoundaries(TEST_AREA_SIZE, BLEED, CROP_OFFSET, "");
+ assertEquals(boundaries.getMediaBox(), boundaries.getCropBox());
+
+ boundaries = new PageBoundaries(TEST_AREA_SIZE, BLEED, CROP_OFFSET, "trim-box");
+ assertEquals(TEST_AREA, boundaries.getCropBox());
+
+ boundaries = new PageBoundaries(TEST_AREA_SIZE, BLEED, CROP_OFFSET, "bleed-box");
+ assertEquals(boundaries.getBleedBox(), boundaries.getCropBox());
+
+ boundaries = new PageBoundaries(TEST_AREA_SIZE, BLEED, CROP_OFFSET, "media-box");
+ assertEquals(boundaries.getMediaBox(), boundaries.getCropBox());
+ }
+
+ /** Test for default values returned when properties are null. */
+ @Test
+ public void testBoundariesNull() {
+ PageBoundaries b = new PageBoundaries(TEST_AREA_SIZE, null, null, null);
+
+ assertEquals("Result should be the same as TEST_AREA object", b.getTrimBox(), TEST_AREA);
+ assertEquals("Result should be the same as TEST_AREA object", b.getBleedBox(), TEST_AREA);
+ assertEquals("Result should be the same as TEST_AREA object", b.getMediaBox(), TEST_AREA);
+ assertEquals("Result should be the same as TEST_AREA object", b.getCropBox(), TEST_AREA);
+ }
+
+ /** Units must be specified. */
+ @Test
+ public void testBoundariesFail() {
+ try {
+ new PageBoundaries(TEST_AREA_SIZE, "0", null, null);
+ fail("Expected IllegalArgumentException. Box should have units");
+ } catch (IllegalArgumentException iae) {
+ // Good!
+ }
+ }
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.render.extensions.prepress;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
-
-import java.awt.geom.Point2D;
-
-import org.junit.Test;
-
-/**
- * Tests for the fox:scale extension property.
- */
-public class PageScaleTest {
-
- /** 1 value is used for both x and y. */
- @Test
- public void testScale1() {
- Point2D res = PageScale.getScale(".5");
- assertEquals(0.5, res.getX(), 0.0);
- assertEquals(0.5, res.getY(), 0.0);
- }
-
- /** Two values, used resp. for x and y. */
- @Test
- public void testScale2() {
- Point2D res = PageScale.getScale("1. \t \n 1.2");
- assertEquals(1.0, res.getX(), 0.0);
- assertEquals(1.2, res.getY(), 0.0);
- }
-
- /** Scale must not contain units. */
- @Test
- public void testScaleFail() {
- try {
- PageScale.getScale("0.5mm 0.5cm");
- fail("Expected IllegalArgumentException. Scale shouldn't contain units");
- } catch (IllegalArgumentException iae) {
- // Good!
- }
- }
-
- /** @{code null} is returned when scale is unspecified. */
- @Test
- public void testScaleNull() {
- Point2D res = PageScale.getScale(null);
- assertNull("Result should be null", res);
- res = PageScale.getScale("");
- assertNull("Result should be null", res);
- }
-
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.render.extensions.prepress;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+
+import java.awt.geom.Point2D;
+
+import org.junit.Test;
+
+/**
+ * Tests for the fox:scale extension property.
+ */
+public class PageScaleTestCase {
+
+ /** 1 value is used for both x and y. */
+ @Test
+ public void testScale1() {
+ Point2D res = PageScale.getScale(".5");
+ assertEquals(0.5, res.getX(), 0.0);
+ assertEquals(0.5, res.getY(), 0.0);
+ }
+
+ /** Two values, used resp. for x and y. */
+ @Test
+ public void testScale2() {
+ Point2D res = PageScale.getScale("1. \t \n 1.2");
+ assertEquals(1.0, res.getX(), 0.0);
+ assertEquals(1.2, res.getY(), 0.0);
+ }
+
+ /** Scale must not contain units. */
+ @Test
+ public void testScaleFail() {
+ try {
+ PageScale.getScale("0.5mm 0.5cm");
+ fail("Expected IllegalArgumentException. Scale shouldn't contain units");
+ } catch (IllegalArgumentException iae) {
+ // Good!
+ }
+ }
+
+ /** @{code null} is returned when scale is unspecified. */
+ @Test
+ public void testScaleNull() {
+ Point2D res = PageScale.getScale(null);
+ assertNull("Result should be null", res);
+ res = PageScale.getScale("");
+ assertNull("Result should be null", res);
+ }
+
+}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.render.pdf;
+
+import java.io.File;
+
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.sax.SAXResult;
+import javax.xml.transform.stream.StreamSource;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.output.ByteArrayOutputStream;
+import org.apache.fop.AbstractFOPTest;
+import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.apps.Fop;
+import org.apache.fop.apps.FopFactory;
+import org.apache.fop.apps.MimeConstants;
+import org.xml.sax.SAXException;
+
+/**
+ * Base class for automated tests that create PDF files
+ */
+public class BasePDFTest extends AbstractFOPTest {
+
+ /** the FopFactory */
+ protected final FopFactory fopFactory = FopFactory.newInstance();
+
+ /** the JAXP TransformerFactory */
+ protected final TransformerFactory tFactory = TransformerFactory.newInstance();
+
+ /**
+ * Main constructor
+ */
+ protected BasePDFTest() {
+ init();
+ }
+
+ /**
+ * initalizes the test
+ */
+ protected void init() {
+ final File uc = getUserConfigFile();
+
+ try {
+ fopFactory.setUserConfig(uc);
+ } catch (Exception e) {
+ throw new RuntimeException("fopFactory.setUserConfig ("
+ + uc.getAbsolutePath() + ") failed: " + e.getMessage());
+ }
+ }
+
+ /**
+ * Convert a test FO file to PDF
+ * @param foFile the FO file
+ * @param ua the preconfigured user agent
+ * @param dumpPdfFile if true, dumps the generated PDF file to a file name (foFile).pdf
+ * @return the generated PDF data
+ * @throws Exception if the conversion fails
+ */
+ protected byte[] convertFO(File foFile, FOUserAgent ua, boolean dumpPdfFile)
+ throws Exception {
+ ByteArrayOutputStream baout = new ByteArrayOutputStream();
+ Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, ua, baout);
+ Transformer transformer = tFactory.newTransformer();
+ Source src = new StreamSource(foFile);
+ SAXResult res = new SAXResult(fop.getDefaultHandler());
+ try {
+ transformer.transform(src, res);
+ final byte[] result = baout.toByteArray();
+ if (dumpPdfFile) {
+ final File outFile = new File(foFile.getParentFile(), foFile.getName() + ".pdf");
+ FileUtils.writeByteArrayToFile(outFile, result);
+ }
+ return result;
+ } catch (TransformerException e) {
+ throw extractOriginalException(e);
+ }
+ }
+
+ private static Exception extractOriginalException(Exception e) {
+ if (e.getCause() != null) {
+ return extractOriginalException((Exception)e.getCause());
+ } else if (e instanceof SAXException) {
+ SAXException se = (SAXException)e;
+ if (se.getException() != null) {
+ return extractOriginalException(se.getException());
+ }
+ }
+ return e;
+ }
+
+ /**
+ * get FOP config File
+ * @return user config file to be used for testing
+ */
+ protected File getUserConfigFile() {
+ return new File("test/test.xconf");
+ }
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.render.pdf;
-
-import java.io.File;
-
-import javax.xml.transform.Source;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.sax.SAXResult;
-import javax.xml.transform.stream.StreamSource;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.output.ByteArrayOutputStream;
-import org.apache.fop.AbstractFOPTestCase;
-import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.apps.Fop;
-import org.apache.fop.apps.FopFactory;
-import org.apache.fop.apps.MimeConstants;
-import org.xml.sax.SAXException;
-
-/**
- * Base class for automated tests that create PDF files
- */
-public class BasePDFTestCase extends AbstractFOPTestCase {
-
- /** the FopFactory */
- protected final FopFactory fopFactory = FopFactory.newInstance();
-
- /** the JAXP TransformerFactory */
- protected final TransformerFactory tFactory = TransformerFactory.newInstance();
-
- /**
- * Main constructor
- */
- protected BasePDFTestCase() {
- init();
- }
-
- /**
- * initalizes the test
- */
- protected void init() {
- final File uc = getUserConfigFile();
-
- try {
- fopFactory.setUserConfig(uc);
- } catch (Exception e) {
- throw new RuntimeException("fopFactory.setUserConfig ("
- + uc.getAbsolutePath() + ") failed: " + e.getMessage());
- }
- }
-
- /**
- * Convert a test FO file to PDF
- * @param foFile the FO file
- * @param ua the preconfigured user agent
- * @param dumpPdfFile if true, dumps the generated PDF file to a file name (foFile).pdf
- * @return the generated PDF data
- * @throws Exception if the conversion fails
- */
- protected byte[] convertFO(File foFile, FOUserAgent ua, boolean dumpPdfFile)
- throws Exception {
- ByteArrayOutputStream baout = new ByteArrayOutputStream();
- Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, ua, baout);
- Transformer transformer = tFactory.newTransformer();
- Source src = new StreamSource(foFile);
- SAXResult res = new SAXResult(fop.getDefaultHandler());
- try {
- transformer.transform(src, res);
- final byte[] result = baout.toByteArray();
- if (dumpPdfFile) {
- final File outFile = new File(foFile.getParentFile(), foFile.getName() + ".pdf");
- FileUtils.writeByteArrayToFile(outFile, result);
- }
- return result;
- } catch (TransformerException e) {
- throw extractOriginalException(e);
- }
- }
-
- private static Exception extractOriginalException(Exception e) {
- if (e.getCause() != null) {
- return extractOriginalException((Exception)e.getCause());
- } else if (e instanceof SAXException) {
- SAXException se = (SAXException)e;
- if (se.getException() != null) {
- return extractOriginalException(se.getException());
- }
- }
- return e;
- }
-
- /**
- * get FOP config File
- * @return user config file to be used for testing
- */
- protected File getUserConfigFile() {
- return new File("test/test.xconf");
- }
-}
/**
* Tests PDF/A-1 functionality.
*/
-public class PDFAConformanceTestCase extends BasePDFTestCase {
+public class PDFAConformanceTestCase extends BasePDFTest {
private File foBaseDir = new File("test/xml/pdf-a");
private boolean dumpPDF = Boolean.getBoolean("PDFAConformanceTestCase.dumpPDF");
import org.junit.Test;
/** Test that characters are correctly encoded in a generated PDF file */
-public class PDFEncodingTestCase extends BasePDFTestCase {
+public class PDFEncodingTestCase extends BasePDFTest {
private File foBaseDir = new File("test/xml/pdf-encoding");
private final boolean dumpPDF = Boolean.getBoolean("PDFEncodingTestCase.dumpPDF");
static final String INPUT_FILE = "test/xml/pdf-encoding/pdf-encoding-test.xconf";
/**
* Tests the disables-srgb-colorspace setting.
*/
-public class PDFsRGBSettingsTestCase extends BasePDFTestCase {
+public class PDFsRGBSettingsTestCase extends BasePDFTest {
private File foBaseDir = new File("test/xml/pdf-a");
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.render.ps;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.xmlgraphics.ps.PSResource;
+import org.apache.xmlgraphics.ps.dsc.DSCException;
+import org.apache.xmlgraphics.ps.dsc.DSCParser;
+import org.apache.xmlgraphics.ps.dsc.events.AbstractResourceDSCComment;
+import org.apache.xmlgraphics.ps.dsc.events.DSCComment;
+import org.apache.xmlgraphics.ps.dsc.events.DSCEvent;
+
+import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.apps.MimeConstants;
+import org.apache.fop.render.AbstractRenderingTest;
+
+/**
+ * Abstract base class for PostScript verification tests.
+ */
+public abstract class AbstractPostScriptTest extends AbstractRenderingTest {
+
+ /**
+ * Renders a test file.
+ * @param ua the user agent (with override set!)
+ * @param resourceName the resource name for the FO file
+ * @param suffix a suffix for the output filename
+ * @return the output file
+ * @throws Exception if an error occurs
+ */
+ protected File renderFile(FOUserAgent ua, String resourceName, String suffix)
+ throws Exception {
+ return renderFile(ua, resourceName, suffix, MimeConstants.MIME_POSTSCRIPT);
+ }
+
+ /**
+ * Scans for a certain resource DSC comment and checks against a given resource.
+ * @param parser the DSC parser
+ * @param comment the comment to scan for
+ * @param resource the resource to check against
+ * @throws IOException if an I/O error occurs
+ * @throws DSCException if a DSC error occurs
+ */
+ protected void checkResourceComment(DSCParser parser, String comment, PSResource resource)
+ throws IOException, DSCException {
+ AbstractResourceDSCComment resComment;
+ resComment = (AbstractResourceDSCComment)gotoDSCComment(parser, comment);
+ assertEquals(resource, resComment.getResource());
+ }
+
+ /**
+ * Advances the DSC parser to a DSC comment with the given name.
+ * @param parser the DSC parser
+ * @param name the name of the DSC comment
+ * @return the DSC comment
+ * @throws IOException if an I/O error occurs
+ * @throws DSCException if a DSC error occurs
+ */
+ protected static DSCComment gotoDSCComment(DSCParser parser, String name)
+ throws IOException, DSCException {
+ while (parser.hasNext()) {
+ DSCEvent event = parser.nextEvent();
+ if (event.isDSCComment()) {
+ DSCComment comment = event.asDSCComment();
+ if (comment.getName().equals(name)) {
+ return comment;
+ }
+ }
+ }
+ return null;
+ }
+
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.render.ps;
-
-import static org.junit.Assert.assertEquals;
-
-import java.io.File;
-import java.io.IOException;
-
-import org.apache.xmlgraphics.ps.PSResource;
-import org.apache.xmlgraphics.ps.dsc.DSCException;
-import org.apache.xmlgraphics.ps.dsc.DSCParser;
-import org.apache.xmlgraphics.ps.dsc.events.AbstractResourceDSCComment;
-import org.apache.xmlgraphics.ps.dsc.events.DSCComment;
-import org.apache.xmlgraphics.ps.dsc.events.DSCEvent;
-
-import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.apps.MimeConstants;
-import org.apache.fop.render.AbstractRenderingTestCase;
-
-/**
- * Abstract base class for PostScript verification tests.
- */
-public abstract class AbstractPostScriptTestCase extends AbstractRenderingTestCase {
-
- /**
- * Renders a test file.
- * @param ua the user agent (with override set!)
- * @param resourceName the resource name for the FO file
- * @param suffix a suffix for the output filename
- * @return the output file
- * @throws Exception if an error occurs
- */
- protected File renderFile(FOUserAgent ua, String resourceName, String suffix)
- throws Exception {
- return renderFile(ua, resourceName, suffix, MimeConstants.MIME_POSTSCRIPT);
- }
-
- /**
- * Scans for a certain resource DSC comment and checks against a given resource.
- * @param parser the DSC parser
- * @param comment the comment to scan for
- * @param resource the resource to check against
- * @throws IOException if an I/O error occurs
- * @throws DSCException if a DSC error occurs
- */
- protected void checkResourceComment(DSCParser parser, String comment, PSResource resource)
- throws IOException, DSCException {
- AbstractResourceDSCComment resComment;
- resComment = (AbstractResourceDSCComment)gotoDSCComment(parser, comment);
- assertEquals(resource, resComment.getResource());
- }
-
- /**
- * Advances the DSC parser to a DSC comment with the given name.
- * @param parser the DSC parser
- * @param name the name of the DSC comment
- * @return the DSC comment
- * @throws IOException if an I/O error occurs
- * @throws DSCException if a DSC error occurs
- */
- protected static DSCComment gotoDSCComment(DSCParser parser, String name)
- throws IOException, DSCException {
- while (parser.hasNext()) {
- DSCEvent event = parser.nextEvent();
- if (event.isDSCComment()) {
- DSCComment comment = event.asDSCComment();
- if (comment.getName().equals(name)) {
- return comment;
- }
- }
- }
- return null;
- }
-
-}
import java.io.IOException;
import java.io.InputStream;
+import org.junit.Test;
+
import org.apache.commons.io.IOUtils;
-import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.render.intermediate.IFContext;
+
import org.apache.xmlgraphics.ps.DSCConstants;
import org.apache.xmlgraphics.ps.PSResource;
import org.apache.xmlgraphics.ps.dsc.DSCException;
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentPages;
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentTitle;
import org.apache.xmlgraphics.ps.dsc.events.DSCEvent;
-import org.junit.Test;
+
+import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.render.intermediate.IFContext;
/**
* Tests the image handling in PostScript output.
*/
-public class ImageHandlingTestCase extends AbstractPostScriptTestCase {
+public class ImageHandlingTestCase extends AbstractPostScriptTest {
/**
* Tests JPEG handling.
ua.setDocumentHandlerOverride(handler);
// Prepare output file
- File outputFile = renderFile(ua, "ps-jpeg-image.fo", "-if-l" + psUtil.getLanguageLevel());
+ File outputFile = renderFile(ua, "ps-jpeg-image.fo",
+ "-if-l" + psUtil.getLanguageLevel());
verifyPostScriptFile(outputFile, psUtil.getLanguageLevel());
}
import java.util.Collection;
import java.util.Set;
+import org.junit.Test;
+
import org.apache.commons.io.IOUtils;
-import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.render.intermediate.IFContext;
+
import org.apache.xmlgraphics.ps.DSCConstants;
import org.apache.xmlgraphics.ps.PSResource;
import org.apache.xmlgraphics.ps.dsc.DSCException;
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentIncludeResource;
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentPage;
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentPages;
-import org.junit.Test;
+
+import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.render.intermediate.IFContext;
/**
* Tests the PostScript resource optimization (selective de-duplication of
* images that are used multiple times).
*/
-public class ResourceOptimizationTestCase extends AbstractPostScriptTestCase {
+public class ResourceOptimizationTestCase extends AbstractPostScriptTest {
/**
* Tests resource optimization.
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.text.linebreak;
-
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-
-
-/**
- * JUnit test case for the LineBreakStatus class
- */
-public class LineBreakStatusTest {
-
- /*
- * These symbols are used to indicate the break action returned
- * by the paragraph breaking. Their meaning is as per Unicode
- * <a href="http://unicode.org/reports/tr14/#PairBasedImplementation">technical
- * report #14</a>.
- */
- private static final String BREAK_ACTION = "_%#@^!";
-
- /**
- * Test of reset method, of class org.apache.commons.text.linebreak.LineBreakStatus.
- */
- @Test
- public void testReset() {
- System.out.println("testReset");
- // TODO
- }
-
- /**
- * Test of nextChar method, of class org.apache.commons.text.linebreak.LineBreakStatus.
- * Runs tests for most of the Line Breaking Properties defined in the Unicode standard.
- */
- @Test
- public void testNextChar() {
- System.out.println("testNextChar");
-
- // AL -- Ordinary Alphabetic and Symbol Characters (XP)
- assertTrue(testBreak(
- "Nobreak",
- "^^^^^^^"
- ));
-
- // BA -- Break Opportunity After (A)
- assertTrue(testBreak(
- "Thin Space" + "\u2009" + "break",
- "^^^^^%^^^^" + "^" + "_^^^^"
- ));
-
- assertTrue(testBreak(
- "Shy" + "\u00AD" + "break",
- "^^^" + "^" + "_^^^^"
- ));
-
-
- // BB -- Break opportunites before characters (B)
- assertTrue(testBreak(
- "Acute Accent" + "\u00B4" + "break",
- "^^^^^^%^^^^^" + "_" + "^^^^^"
- ));
-
- // B2 -- Break Opportunity Before and After (B/A/XP)
- assertTrue(testBreak(
- "Em Dash" + "\u2014" + "break",
- "^^^%^^^" + "_" + "_^^^^"
- ));
-
- assertTrue(testBreak(
- "Em Dash Dash" + "\u2014" + "\u2014" + "break",
- "^^^%^^^^%^^^" + "_" + "^" + "_^^^^"
- ));
-
- // BK Mandatory Break (A) -- normative
- assertTrue(testBreak(
- "Form Feed" + "\u000C" + "break",
- "^^^^^%^^^" + "^" + "!^^^^"
- ));
-
- assertTrue(testBreak(
- "Line Separator" + "\u2028" + "break",
- "^^^^^%^^^^^^^^" + "^" + "!^^^^"
- ));
-
- assertTrue(testBreak(
- "Paragraph Separator" + "\u2029" + "break",
- "^^^^^^^^^^%^^^^^^^^" + "^" + "!^^^^"
- ));
-
- // CB Contingent Break Opportunity (B/A) -- normative
- // TODO Don't know quite what to do here
-
- // CL -- Closing Punctuation (XB)
- assertTrue(testBreak(
- "Right Parenthesis ) break",
- "^^^^^^%^^^^^^^^^^^^^%^^^^"
- ));
-
- // CM -- Attached Characters and Combining Marks (XB) -- normative
- assertTrue(testBreak(
- "Grave Accent" + "\u0300" + " break",
- "^^^^^^%^^^^^" + "^" + "^%^^^^"
- ));
-
- // CR -- Carriage Return (A) -- normative
- assertTrue(testBreak(
- "CR" + "\r" + "break",
- "^^" + "^" + "!^^^^"
- ));
-
- assertTrue(testBreak(
- "CRLF" + "\r\n" + "break",
- "^^^^" + "^^" + "!^^^^"
- ));
-
- // EX -- Exclamation / interrogation (XB)
- assertTrue(testBreak(
- "EX CL ! ) break",
- "^^^%^^^^^^%^^^^"
- ));
-
- assertTrue(testBreak(
- "EX Wave Dash ! " + "\u301C" + " break",
- "^^^%^^^^%^^^^^^" + "%" + "^_^^^^"
- ));
-
- // GL -- Non-breaking ("Glue") (XB/XA) -- normative
- assertTrue(testBreak(
- "No" + "\u00a0" + "break",
- "^^" + "^" + "^^^^^"
- ));
-
- assertTrue(testBreak(
- "Non" + "\u2011" + " Hyphen",
- "^^^" + "^" + "^%^^^^^"
- ));
-
- // H2 -- Hangul LVT Syllable (B/A)
- // TODO
-
- // H3 -- Hangul LVT Syllable (B/A)
- // TODO
-
- // HY -- Hyphen Minus
- assertTrue(testBreak(
- "Normal-Hyphen",
- "^^^^^^^_^^^^^"
- ));
-
- assertTrue(testBreak(
- "Normal - Hyphen",
- "^^^^^^^%^_^^^^^"
- ));
-
- assertTrue(testBreak(
- "123-456",
- "^^^^^^^"
- ));
-
- assertTrue(testBreak(
- "123 - 456",
- "^^^^%^%^^"
- ));
-
- // ID -- Ideographic (B/A)
- assertTrue(testBreak(
- "\u4E00" + "\u3000" + "\u4E02",
- "^" + "_" + "_"
- ));
-
- // IN -- Inseperable characters (XP)
- assertTrue(testBreak(
- "IN " + "\u2024" + "\u2025" + "\u2026",
- "^^^" + "%" + "^" + "^"
- ));
-
- // IS -- Numeric Separator (Infix) (XB)
- assertTrue(testBreak(
- "123,456.00 12:59",
- "^^^^^^^^^^^%^^^^"
- ));
-
- // JL -- Hangul L Jamo (B)
- // TODO
-
- // JT -- Hangul T Jamo (A)
- // TODO
-
- // JV -- Hangul V Jamo (XA/XB)
- // TODO
-
- // LF -- Line Feed (A) -- normative
- assertTrue(testBreak(
- "Simple" + "\n" + "\n" + "break",
- "^^^^^^" + "^" + "!" + "!^^^^"
- ));
-
- // NL -- Next Line (A) -- normative
- assertTrue(testBreak(
- "NL" + "\u0085" + "break",
- "^^" + "^" + "!^^^^"
- ));
-
- // NS -- Non-starters (XB)
- // TODO
-
- // NU -- Numeric (XP)
- // Tested as part of IS
-
- // OP -- Opening Punctuation (XA)
- assertTrue(testBreak(
- "[ Bracket ( Parenthesis",
- "^^^^^^^^^^%^^^^^^^^^^^^"
- ));
-
- // PO -- Postfix (Numeric) (XB)
- assertTrue(testBreak(
- "(12.00)%",
- "^^^^^^^^"
- ));
-
- // PR -- Prefix (Numeric) (XA)
- assertTrue(testBreak(
- "$1000.00",
- "^^^^^^^^"
- ));
-
- // QU -- Ambiguous Quotation (XB/XA)
- assertTrue(testBreak(
- "'In Quotes'",
- "^^^^%^^^^^^"
- ));
-
- assertTrue(testBreak(
- "' (In Quotes) '",
- "^^^^^^%^^^^^^^%"
- ));
-
- // SA -- Complex-context Dependent Characters (South East Asian) (P)
- // TODO
-
- // SP -- Space (A) -- normative
- assertTrue(testBreak(
- "Simple break",
- "^^^^^^^%^^^^"
- ));
-
- assertTrue(testBreak(
- "Simple break2",
- "^^^^^^^^^^%^^^^^"
- ));
-
- // SY -- Symbols Allowing Break After (A)
- assertTrue(testBreak(
- "http://xmlgraphics.apache.org/fop",
- "^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^_^^"
- ));
-
- assertTrue(testBreak(
- "1/2 31/10/2005",
- "^^^^%^^^^^^^^^"
- ));
-
- // WJ -- Word Joiner (XA/XB) -- (normative)
- assertTrue(testBreak(
- "http://" + "\u2060" + "xmlgraphics.apache.org/" + "\uFEFF" + "fop",
- "^^^^^^^" + "^" + "^^^^^^^^^^^^^^^^^^^^^^^" + "^" + "^^^"
- ));
-
- assertTrue(testBreak(
- "Simple " + "\u2060" + "break",
- "^^^^^^^" + "^" + "^^^^^"
- ));
-
- assertTrue(testBreak(
- "Simple" + "\u200B" + "\u2060" + "break",
- "^^^^^^" + "^" + "_" + "^^^^^"
- ));
-
- // XX -- Unknown (XP)
- // TODO
-
- // ZW -- Zero Width Space (A) -- (normative)
- assertTrue(testBreak(
- "Simple" + "\u200B" + "break",
- "^^^^^^" + "^" + "_^^^^"
- ));
-
- // Unassigned codepoint: should yield same result as AL
- assertTrue(testBreak(
- "No" + "\u1F7E" + "break",
- "^^" + "^" + "^^^^^"
- ));
-
- }
-
- /**
- * Tests the paragraph break status (break actions) returned from calling
- * LineBreakStatus.nextChar() on each character of paragraph against
- * the expected break actions. There must be a positional match between
- * the characters in paragraph and characters in breakAction.
- * @param paragraph The text to be analysed for line breaks
- * @param breakActions The symbolic representation of the break actions
- * expected to be returned.
- */
- private boolean testBreak(String paragraph, String breakActions) {
- boolean result = true;
- int length = paragraph.length();
- LineBreakStatus lbs = new LineBreakStatus();
- for (int i = 0; i < length; i++) {
- byte breakAction = lbs.nextChar(paragraph.charAt(i));
- if (BREAK_ACTION.charAt(breakAction) != breakActions.charAt(i)) {
- System.err.println(paragraph);
- System.err.println(breakActions);
- System.err.println("pos = " + i
- + " expected '" + breakActions.charAt(i)
- + "' got '" + BREAK_ACTION.charAt(breakAction) + "'");
- result = false;
- }
- }
- return result;
- }
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.text.linebreak;
+
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+
+/**
+ * JUnit test case for the LineBreakStatus class
+ */
+public class LineBreakStatusTestCase {
+
+ /*
+ * These symbols are used to indicate the break action returned
+ * by the paragraph breaking. Their meaning is as per Unicode
+ * <a href="http://unicode.org/reports/tr14/#PairBasedImplementation">technical
+ * report #14</a>.
+ */
+ private static final String BREAK_ACTION = "_%#@^!";
+
+ /**
+ * Test of reset method, of class org.apache.commons.text.linebreak.LineBreakStatus.
+ */
+ @Test
+ public void testReset() {
+ System.out.println("testReset");
+ // TODO
+ }
+
+ /**
+ * Test of nextChar method, of class org.apache.commons.text.linebreak.LineBreakStatus.
+ * Runs tests for most of the Line Breaking Properties defined in the Unicode standard.
+ */
+ @Test
+ public void testNextChar() {
+ System.out.println("testNextChar");
+
+ // AL -- Ordinary Alphabetic and Symbol Characters (XP)
+ assertTrue(testBreak(
+ "Nobreak",
+ "^^^^^^^"
+ ));
+
+ // BA -- Break Opportunity After (A)
+ assertTrue(testBreak(
+ "Thin Space" + "\u2009" + "break",
+ "^^^^^%^^^^" + "^" + "_^^^^"
+ ));
+
+ assertTrue(testBreak(
+ "Shy" + "\u00AD" + "break",
+ "^^^" + "^" + "_^^^^"
+ ));
+
+
+ // BB -- Break opportunites before characters (B)
+ assertTrue(testBreak(
+ "Acute Accent" + "\u00B4" + "break",
+ "^^^^^^%^^^^^" + "_" + "^^^^^"
+ ));
+
+ // B2 -- Break Opportunity Before and After (B/A/XP)
+ assertTrue(testBreak(
+ "Em Dash" + "\u2014" + "break",
+ "^^^%^^^" + "_" + "_^^^^"
+ ));
+
+ assertTrue(testBreak(
+ "Em Dash Dash" + "\u2014" + "\u2014" + "break",
+ "^^^%^^^^%^^^" + "_" + "^" + "_^^^^"
+ ));
+
+ // BK Mandatory Break (A) -- normative
+ assertTrue(testBreak(
+ "Form Feed" + "\u000C" + "break",
+ "^^^^^%^^^" + "^" + "!^^^^"
+ ));
+
+ assertTrue(testBreak(
+ "Line Separator" + "\u2028" + "break",
+ "^^^^^%^^^^^^^^" + "^" + "!^^^^"
+ ));
+
+ assertTrue(testBreak(
+ "Paragraph Separator" + "\u2029" + "break",
+ "^^^^^^^^^^%^^^^^^^^" + "^" + "!^^^^"
+ ));
+
+ // CB Contingent Break Opportunity (B/A) -- normative
+ // TODO Don't know quite what to do here
+
+ // CL -- Closing Punctuation (XB)
+ assertTrue(testBreak(
+ "Right Parenthesis ) break",
+ "^^^^^^%^^^^^^^^^^^^^%^^^^"
+ ));
+
+ // CM -- Attached Characters and Combining Marks (XB) -- normative
+ assertTrue(testBreak(
+ "Grave Accent" + "\u0300" + " break",
+ "^^^^^^%^^^^^" + "^" + "^%^^^^"
+ ));
+
+ // CR -- Carriage Return (A) -- normative
+ assertTrue(testBreak(
+ "CR" + "\r" + "break",
+ "^^" + "^" + "!^^^^"
+ ));
+
+ assertTrue(testBreak(
+ "CRLF" + "\r\n" + "break",
+ "^^^^" + "^^" + "!^^^^"
+ ));
+
+ // EX -- Exclamation / interrogation (XB)
+ assertTrue(testBreak(
+ "EX CL ! ) break",
+ "^^^%^^^^^^%^^^^"
+ ));
+
+ assertTrue(testBreak(
+ "EX Wave Dash ! " + "\u301C" + " break",
+ "^^^%^^^^%^^^^^^" + "%" + "^_^^^^"
+ ));
+
+ // GL -- Non-breaking ("Glue") (XB/XA) -- normative
+ assertTrue(testBreak(
+ "No" + "\u00a0" + "break",
+ "^^" + "^" + "^^^^^"
+ ));
+
+ assertTrue(testBreak(
+ "Non" + "\u2011" + " Hyphen",
+ "^^^" + "^" + "^%^^^^^"
+ ));
+
+ // H2 -- Hangul LVT Syllable (B/A)
+ // TODO
+
+ // H3 -- Hangul LVT Syllable (B/A)
+ // TODO
+
+ // HY -- Hyphen Minus
+ assertTrue(testBreak(
+ "Normal-Hyphen",
+ "^^^^^^^_^^^^^"
+ ));
+
+ assertTrue(testBreak(
+ "Normal - Hyphen",
+ "^^^^^^^%^_^^^^^"
+ ));
+
+ assertTrue(testBreak(
+ "123-456",
+ "^^^^^^^"
+ ));
+
+ assertTrue(testBreak(
+ "123 - 456",
+ "^^^^%^%^^"
+ ));
+
+ // ID -- Ideographic (B/A)
+ assertTrue(testBreak(
+ "\u4E00" + "\u3000" + "\u4E02",
+ "^" + "_" + "_"
+ ));
+
+ // IN -- Inseperable characters (XP)
+ assertTrue(testBreak(
+ "IN " + "\u2024" + "\u2025" + "\u2026",
+ "^^^" + "%" + "^" + "^"
+ ));
+
+ // IS -- Numeric Separator (Infix) (XB)
+ assertTrue(testBreak(
+ "123,456.00 12:59",
+ "^^^^^^^^^^^%^^^^"
+ ));
+
+ // JL -- Hangul L Jamo (B)
+ // TODO
+
+ // JT -- Hangul T Jamo (A)
+ // TODO
+
+ // JV -- Hangul V Jamo (XA/XB)
+ // TODO
+
+ // LF -- Line Feed (A) -- normative
+ assertTrue(testBreak(
+ "Simple" + "\n" + "\n" + "break",
+ "^^^^^^" + "^" + "!" + "!^^^^"
+ ));
+
+ // NL -- Next Line (A) -- normative
+ assertTrue(testBreak(
+ "NL" + "\u0085" + "break",
+ "^^" + "^" + "!^^^^"
+ ));
+
+ // NS -- Non-starters (XB)
+ // TODO
+
+ // NU -- Numeric (XP)
+ // Tested as part of IS
+
+ // OP -- Opening Punctuation (XA)
+ assertTrue(testBreak(
+ "[ Bracket ( Parenthesis",
+ "^^^^^^^^^^%^^^^^^^^^^^^"
+ ));
+
+ // PO -- Postfix (Numeric) (XB)
+ assertTrue(testBreak(
+ "(12.00)%",
+ "^^^^^^^^"
+ ));
+
+ // PR -- Prefix (Numeric) (XA)
+ assertTrue(testBreak(
+ "$1000.00",
+ "^^^^^^^^"
+ ));
+
+ // QU -- Ambiguous Quotation (XB/XA)
+ assertTrue(testBreak(
+ "'In Quotes'",
+ "^^^^%^^^^^^"
+ ));
+
+ assertTrue(testBreak(
+ "' (In Quotes) '",
+ "^^^^^^%^^^^^^^%"
+ ));
+
+ // SA -- Complex-context Dependent Characters (South East Asian) (P)
+ // TODO
+
+ // SP -- Space (A) -- normative
+ assertTrue(testBreak(
+ "Simple break",
+ "^^^^^^^%^^^^"
+ ));
+
+ assertTrue(testBreak(
+ "Simple break2",
+ "^^^^^^^^^^%^^^^^"
+ ));
+
+ // SY -- Symbols Allowing Break After (A)
+ assertTrue(testBreak(
+ "http://xmlgraphics.apache.org/fop",
+ "^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^_^^"
+ ));
+
+ assertTrue(testBreak(
+ "1/2 31/10/2005",
+ "^^^^%^^^^^^^^^"
+ ));
+
+ // WJ -- Word Joiner (XA/XB) -- (normative)
+ assertTrue(testBreak(
+ "http://" + "\u2060" + "xmlgraphics.apache.org/" + "\uFEFF" + "fop",
+ "^^^^^^^" + "^" + "^^^^^^^^^^^^^^^^^^^^^^^" + "^" + "^^^"
+ ));
+
+ assertTrue(testBreak(
+ "Simple " + "\u2060" + "break",
+ "^^^^^^^" + "^" + "^^^^^"
+ ));
+
+ assertTrue(testBreak(
+ "Simple" + "\u200B" + "\u2060" + "break",
+ "^^^^^^" + "^" + "_" + "^^^^^"
+ ));
+
+ // XX -- Unknown (XP)
+ // TODO
+
+ // ZW -- Zero Width Space (A) -- (normative)
+ assertTrue(testBreak(
+ "Simple" + "\u200B" + "break",
+ "^^^^^^" + "^" + "_^^^^"
+ ));
+
+ // Unassigned codepoint: should yield same result as AL
+ assertTrue(testBreak(
+ "No" + "\u1F7E" + "break",
+ "^^" + "^" + "^^^^^"
+ ));
+
+ }
+
+ /**
+ * Tests the paragraph break status (break actions) returned from calling
+ * LineBreakStatus.nextChar() on each character of paragraph against
+ * the expected break actions. There must be a positional match between
+ * the characters in paragraph and characters in breakAction.
+ * @param paragraph The text to be analysed for line breaks
+ * @param breakActions The symbolic representation of the break actions
+ * expected to be returned.
+ */
+ private boolean testBreak(String paragraph, String breakActions) {
+ boolean result = true;
+ int length = paragraph.length();
+ LineBreakStatus lbs = new LineBreakStatus();
+ for (int i = 0; i < length; i++) {
+ byte breakAction = lbs.nextChar(paragraph.charAt(i));
+ if (BREAK_ACTION.charAt(breakAction) != breakActions.charAt(i)) {
+ System.err.println(paragraph);
+ System.err.println(breakActions);
+ System.err.println("pos = " + i
+ + " expected '" + breakActions.charAt(i)
+ + "' got '" + BREAK_ACTION.charAt(breakAction) + "'");
+ result = false;
+ }
+ }
+ return result;
+ }
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.text.linebreak;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-
-/**
- * TODO add javadoc
- *
- *
- */
-public class LineBreakUtilsTest {
-
- @Test
- public void testLineBreakProperty() {
- assertEquals(LineBreakUtils.getLineBreakProperty('A'), LineBreakUtils.LINE_BREAK_PROPERTY_AL);
- assertEquals(LineBreakUtils.getLineBreakProperty('1'), LineBreakUtils.LINE_BREAK_PROPERTY_NU);
- assertEquals(LineBreakUtils.getLineBreakProperty('\n'), LineBreakUtils.LINE_BREAK_PROPERTY_LF);
- assertEquals(LineBreakUtils.getLineBreakProperty('\r'), LineBreakUtils.LINE_BREAK_PROPERTY_CR);
- assertEquals(LineBreakUtils.getLineBreakProperty('('), LineBreakUtils.LINE_BREAK_PROPERTY_OP);
- assertEquals(LineBreakUtils.getLineBreakProperty('\u1F7E'), 0);
- }
-
- @Test
- public void testLineBreakPair() {
- assertEquals(
- LineBreakUtils.getLineBreakPairProperty(
- LineBreakUtils.LINE_BREAK_PROPERTY_CM,
- LineBreakUtils.LINE_BREAK_PROPERTY_CL),
- LineBreakUtils.PROHIBITED_BREAK);
- assertEquals(
- LineBreakUtils.getLineBreakPairProperty(
- LineBreakUtils.LINE_BREAK_PROPERTY_CL,
- LineBreakUtils.LINE_BREAK_PROPERTY_CM),
- LineBreakUtils.COMBINING_INDIRECT_BREAK);
- assertEquals(
- LineBreakUtils.getLineBreakPairProperty(
- LineBreakUtils.LINE_BREAK_PROPERTY_IS,
- LineBreakUtils.LINE_BREAK_PROPERTY_PR),
- LineBreakUtils.DIRECT_BREAK);
- assertEquals(
- LineBreakUtils.getLineBreakPairProperty(
- LineBreakUtils.LINE_BREAK_PROPERTY_AL,
- LineBreakUtils.LINE_BREAK_PROPERTY_OP),
- LineBreakUtils.DIRECT_BREAK);
- assertEquals(
- LineBreakUtils.getLineBreakPairProperty(
- LineBreakUtils.LINE_BREAK_PROPERTY_LF,
- LineBreakUtils.LINE_BREAK_PROPERTY_CM),
- 0);
- }
-
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.text.linebreak;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+/**
+ * TODO add javadoc
+ *
+ *
+ */
+public class LineBreakUtilsTestCase {
+
+ @Test
+ public void testLineBreakProperty() {
+ assertEquals(LineBreakUtils.getLineBreakProperty('A'), LineBreakUtils.LINE_BREAK_PROPERTY_AL);
+ assertEquals(LineBreakUtils.getLineBreakProperty('1'), LineBreakUtils.LINE_BREAK_PROPERTY_NU);
+ assertEquals(LineBreakUtils.getLineBreakProperty('\n'), LineBreakUtils.LINE_BREAK_PROPERTY_LF);
+ assertEquals(LineBreakUtils.getLineBreakProperty('\r'), LineBreakUtils.LINE_BREAK_PROPERTY_CR);
+ assertEquals(LineBreakUtils.getLineBreakProperty('('), LineBreakUtils.LINE_BREAK_PROPERTY_OP);
+ assertEquals(LineBreakUtils.getLineBreakProperty('\u1F7E'), 0);
+ }
+
+ @Test
+ public void testLineBreakPair() {
+ assertEquals(
+ LineBreakUtils.getLineBreakPairProperty(
+ LineBreakUtils.LINE_BREAK_PROPERTY_CM,
+ LineBreakUtils.LINE_BREAK_PROPERTY_CL),
+ LineBreakUtils.PROHIBITED_BREAK);
+ assertEquals(
+ LineBreakUtils.getLineBreakPairProperty(
+ LineBreakUtils.LINE_BREAK_PROPERTY_CL,
+ LineBreakUtils.LINE_BREAK_PROPERTY_CM),
+ LineBreakUtils.COMBINING_INDIRECT_BREAK);
+ assertEquals(
+ LineBreakUtils.getLineBreakPairProperty(
+ LineBreakUtils.LINE_BREAK_PROPERTY_IS,
+ LineBreakUtils.LINE_BREAK_PROPERTY_PR),
+ LineBreakUtils.DIRECT_BREAK);
+ assertEquals(
+ LineBreakUtils.getLineBreakPairProperty(
+ LineBreakUtils.LINE_BREAK_PROPERTY_AL,
+ LineBreakUtils.LINE_BREAK_PROPERTY_OP),
+ LineBreakUtils.INDIRECT_BREAK);
+ assertEquals(
+ LineBreakUtils.getLineBreakPairProperty(
+ LineBreakUtils.LINE_BREAK_PROPERTY_LF,
+ LineBreakUtils.LINE_BREAK_PROPERTY_CM),
+ 0);
+ }
+
+}
+++ /dev/null
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.traits;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import org.junit.Test;
-
-/**
- * Tests the {@link MinOptMaxTest} class.
- */
-public class MinOptMaxTest {
-
- /**
- * Tests that the constant <code>MinOptMax.ZERO</code> is really zero.
- */
- @Test
- public void testZero() {
- assertEquals(MinOptMax.getInstance(0), MinOptMax.ZERO);
- }
-
- @Test
- public void testNewStiffMinOptMax() {
- MinOptMax value = MinOptMax.getInstance(1);
- assertTrue(value.isStiff());
- assertEquals(1, value.getMin());
- assertEquals(1, value.getOpt());
- assertEquals(1, value.getMax());
- }
-
- @Test
- public void testNewMinOptMax() {
- MinOptMax value = MinOptMax.getInstance(1, 2, 3);
- assertTrue(value.isElastic());
- assertEquals(1, value.getMin());
- assertEquals(2, value.getOpt());
- assertEquals(3, value.getMax());
- }
-
- /**
- * Test that it is possible to create stiff instances with the normal factory method.
- */
- @Test
- public void testNewMinOptMaxStiff() {
- MinOptMax value = MinOptMax.getInstance(1, 1, 1);
- assertTrue(value.isStiff());
- assertEquals(1, value.getMin());
- assertEquals(1, value.getOpt());
- assertEquals(1, value.getMax());
- }
-
- @Test
- public void testNewMinOptMaxMinGreaterOpt() {
- try {
- MinOptMax.getInstance(1, 0, 2);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("min (1) > opt (0)", e.getMessage());
- }
- }
-
- @Test
- public void testNewMinOptMaxMaxSmallerOpt() {
- try {
- MinOptMax.getInstance(0, 1, 0);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("max (0) < opt (1)", e.getMessage());
- }
- }
-
- @Test
- public void testShrinkablility() {
- assertEquals(0, MinOptMax.getInstance(1).getShrink());
- assertEquals(1, MinOptMax.getInstance(1, 2, 2).getShrink());
- assertEquals(2, MinOptMax.getInstance(1, 3, 3).getShrink());
- }
-
- @Test
- public void testStrechablilty() {
- assertEquals(0, MinOptMax.getInstance(1).getStretch());
- assertEquals(1, MinOptMax.getInstance(1, 1, 2).getStretch());
- assertEquals(2, MinOptMax.getInstance(1, 1, 3).getStretch());
- }
-
- @Test
- public void testPlus() {
- assertEquals(MinOptMax.ZERO,
- MinOptMax.ZERO.plus(MinOptMax.ZERO));
- assertEquals(MinOptMax.getInstance(1, 2, 3),
- MinOptMax.ZERO.plus(MinOptMax.getInstance(1, 2, 3)));
- assertEquals(MinOptMax.getInstance(2, 4, 6),
- MinOptMax.getInstance(1, 2, 3).plus(MinOptMax.getInstance(1, 2, 3)));
- assertEquals(MinOptMax.getInstance(4, 5, 6), MinOptMax.getInstance(1, 2, 3).plus(3));
- }
-
- @Test
- public void testMinus() {
- assertEquals(MinOptMax.ZERO,
- MinOptMax.ZERO.minus(MinOptMax.ZERO));
- assertEquals(MinOptMax.getInstance(1, 2, 3),
- MinOptMax.getInstance(1, 2, 3).plus(MinOptMax.ZERO));
- assertEquals(MinOptMax.getInstance(1, 2, 3),
- MinOptMax.getInstance(2, 4, 6).minus(MinOptMax.getInstance(1, 2, 3)));
- assertEquals(MinOptMax.getInstance(1, 2, 3), MinOptMax.getInstance(5, 6, 7).minus(4));
- }
-
- @Test
- public void testMinusFail1() {
- try {
- MinOptMax.ZERO.minus(MinOptMax.getInstance(1, 2, 3));
- fail();
- } catch (ArithmeticException e) {
- // Ok
- }
- }
-
- @Test
- public void testMinusFail2() {
- try {
- MinOptMax.getInstance(1, 2, 3).minus(MinOptMax.getInstance(1, 3, 3));
- fail();
- } catch (ArithmeticException e) {
- // Ok
- }
- }
-
- @Test
- public void testMinusFail3() {
- try {
- MinOptMax.ZERO.minus(MinOptMax.getInstance(1, 1, 2));
- fail();
- } catch (ArithmeticException e) {
- // Ok
- }
- }
-
- @Test
- public void testMinusFail4() {
- try {
- MinOptMax.getInstance(1, 2, 3).minus(MinOptMax.getInstance(1, 1, 3));
- fail();
- } catch (ArithmeticException e) {
- // Ok
- }
- }
-
- @Test
- public void testMult() {
- assertEquals(MinOptMax.ZERO, MinOptMax.ZERO.mult(0));
- assertEquals(MinOptMax.getInstance(1, 2, 3), MinOptMax.getInstance(1, 2, 3).mult(1));
- assertEquals(MinOptMax.getInstance(2, 4, 6), MinOptMax.getInstance(1, 2, 3).mult(2));
- }
-
- @Test
- public void testMultFail() {
- try {
- MinOptMax.getInstance(1, 2, 3).mult(-1);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("factor < 0; was: -1", e.getMessage());
- }
- }
-
- @Test
- public void testNonZero() {
- assertFalse(MinOptMax.ZERO.isNonZero());
- assertTrue(MinOptMax.getInstance(1).isNonZero());
- assertTrue(MinOptMax.getInstance(1, 2, 3).isNonZero());
- }
-
- @Test
- public void testExtendMinimum() {
- assertEquals(MinOptMax.getInstance(1, 1, 1),
- MinOptMax.ZERO.extendMinimum(1));
- assertEquals(MinOptMax.getInstance(1, 2, 3),
- MinOptMax.getInstance(1, 2, 3).extendMinimum(1));
- assertEquals(MinOptMax.getInstance(2, 2, 3),
- MinOptMax.getInstance(1, 2, 3).extendMinimum(2));
- assertEquals(MinOptMax.getInstance(3, 3, 3),
- MinOptMax.getInstance(1, 2, 3).extendMinimum(3));
- assertEquals(MinOptMax.getInstance(4, 4, 4),
- MinOptMax.getInstance(1, 2, 3).extendMinimum(4));
- }
-
- @Test
- public void testEquals() {
- MinOptMax number = MinOptMax.getInstance(1, 3, 5);
- assertEquals(number, number);
- assertEquals(number, MinOptMax.getInstance(1, 3, 5));
- assertFalse(number.equals(MinOptMax.getInstance(2, 3, 5)));
- assertFalse(number.equals(MinOptMax.getInstance(1, 4, 5)));
- assertFalse(number.equals(MinOptMax.getInstance(1, 3, 4)));
- assertFalse(number.equals(null));
- assertFalse(number.equals(new Integer(1)));
- }
-
- @Test
- public void testHashCode() {
- MinOptMax number = MinOptMax.getInstance(1, 2, 3);
- assertEquals(number.hashCode(), number.hashCode());
- assertEquals(number.hashCode(), MinOptMax.getInstance(1, 2, 3).hashCode());
- }
-}
--- /dev/null
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.traits;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import org.junit.Test;
+
+/**
+ * Tests the {@link MinOptMax} class.
+ */
+public class MinOptMaxTestCase {
+
+ /**
+ * Tests that the constant <code>MinOptMax.ZERO</code> is really zero.
+ */
+ @Test
+ public void testZero() {
+ assertEquals(MinOptMax.getInstance(0), MinOptMax.ZERO);
+ }
+
+ @Test
+ public void testNewStiffMinOptMax() {
+ MinOptMax value = MinOptMax.getInstance(1);
+ assertTrue(value.isStiff());
+ assertEquals(1, value.getMin());
+ assertEquals(1, value.getOpt());
+ assertEquals(1, value.getMax());
+ }
+
+ @Test
+ public void testNewMinOptMax() {
+ MinOptMax value = MinOptMax.getInstance(1, 2, 3);
+ assertTrue(value.isElastic());
+ assertEquals(1, value.getMin());
+ assertEquals(2, value.getOpt());
+ assertEquals(3, value.getMax());
+ }
+
+ /**
+ * Test that it is possible to create stiff instances with the normal factory method.
+ */
+ @Test
+ public void testNewMinOptMaxStiff() {
+ MinOptMax value = MinOptMax.getInstance(1, 1, 1);
+ assertTrue(value.isStiff());
+ assertEquals(1, value.getMin());
+ assertEquals(1, value.getOpt());
+ assertEquals(1, value.getMax());
+ }
+
+ @Test
+ public void testNewMinOptMaxMinGreaterOpt() {
+ try {
+ MinOptMax.getInstance(1, 0, 2);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("min (1) > opt (0)", e.getMessage());
+ }
+ }
+
+ @Test
+ public void testNewMinOptMaxMaxSmallerOpt() {
+ try {
+ MinOptMax.getInstance(0, 1, 0);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("max (0) < opt (1)", e.getMessage());
+ }
+ }
+
+ @Test
+ public void testShrinkablility() {
+ assertEquals(0, MinOptMax.getInstance(1).getShrink());
+ assertEquals(1, MinOptMax.getInstance(1, 2, 2).getShrink());
+ assertEquals(2, MinOptMax.getInstance(1, 3, 3).getShrink());
+ }
+
+ @Test
+ public void testStrechablilty() {
+ assertEquals(0, MinOptMax.getInstance(1).getStretch());
+ assertEquals(1, MinOptMax.getInstance(1, 1, 2).getStretch());
+ assertEquals(2, MinOptMax.getInstance(1, 1, 3).getStretch());
+ }
+
+ @Test
+ public void testPlus() {
+ assertEquals(MinOptMax.ZERO,
+ MinOptMax.ZERO.plus(MinOptMax.ZERO));
+ assertEquals(MinOptMax.getInstance(1, 2, 3),
+ MinOptMax.ZERO.plus(MinOptMax.getInstance(1, 2, 3)));
+ assertEquals(MinOptMax.getInstance(2, 4, 6),
+ MinOptMax.getInstance(1, 2, 3).plus(MinOptMax.getInstance(1, 2, 3)));
+ assertEquals(MinOptMax.getInstance(4, 5, 6), MinOptMax.getInstance(1, 2, 3).plus(3));
+ }
+
+ @Test
+ public void testMinus() {
+ assertEquals(MinOptMax.ZERO,
+ MinOptMax.ZERO.minus(MinOptMax.ZERO));
+ assertEquals(MinOptMax.getInstance(1, 2, 3),
+ MinOptMax.getInstance(1, 2, 3).plus(MinOptMax.ZERO));
+ assertEquals(MinOptMax.getInstance(1, 2, 3),
+ MinOptMax.getInstance(2, 4, 6).minus(MinOptMax.getInstance(1, 2, 3)));
+ assertEquals(MinOptMax.getInstance(1, 2, 3), MinOptMax.getInstance(5, 6, 7).minus(4));
+ }
+
+ @Test
+ public void testMinusFail1() {
+ try {
+ MinOptMax.ZERO.minus(MinOptMax.getInstance(1, 2, 3));
+ fail();
+ } catch (ArithmeticException e) {
+ // Ok
+ }
+ }
+
+ @Test
+ public void testMinusFail2() {
+ try {
+ MinOptMax.getInstance(1, 2, 3).minus(MinOptMax.getInstance(1, 3, 3));
+ fail();
+ } catch (ArithmeticException e) {
+ // Ok
+ }
+ }
+
+ @Test
+ public void testMinusFail3() {
+ try {
+ MinOptMax.ZERO.minus(MinOptMax.getInstance(1, 1, 2));
+ fail();
+ } catch (ArithmeticException e) {
+ // Ok
+ }
+ }
+
+ @Test
+ public void testMinusFail4() {
+ try {
+ MinOptMax.getInstance(1, 2, 3).minus(MinOptMax.getInstance(1, 1, 3));
+ fail();
+ } catch (ArithmeticException e) {
+ // Ok
+ }
+ }
+
+ @Test
+ public void testMult() {
+ assertEquals(MinOptMax.ZERO, MinOptMax.ZERO.mult(0));
+ assertEquals(MinOptMax.getInstance(1, 2, 3), MinOptMax.getInstance(1, 2, 3).mult(1));
+ assertEquals(MinOptMax.getInstance(2, 4, 6), MinOptMax.getInstance(1, 2, 3).mult(2));
+ }
+
+ @Test
+ public void testMultFail() {
+ try {
+ MinOptMax.getInstance(1, 2, 3).mult(-1);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("factor < 0; was: -1", e.getMessage());
+ }
+ }
+
+ @Test
+ public void testNonZero() {
+ assertFalse(MinOptMax.ZERO.isNonZero());
+ assertTrue(MinOptMax.getInstance(1).isNonZero());
+ assertTrue(MinOptMax.getInstance(1, 2, 3).isNonZero());
+ }
+
+ @Test
+ public void testExtendMinimum() {
+ assertEquals(MinOptMax.getInstance(1, 1, 1),
+ MinOptMax.ZERO.extendMinimum(1));
+ assertEquals(MinOptMax.getInstance(1, 2, 3),
+ MinOptMax.getInstance(1, 2, 3).extendMinimum(1));
+ assertEquals(MinOptMax.getInstance(2, 2, 3),
+ MinOptMax.getInstance(1, 2, 3).extendMinimum(2));
+ assertEquals(MinOptMax.getInstance(3, 3, 3),
+ MinOptMax.getInstance(1, 2, 3).extendMinimum(3));
+ assertEquals(MinOptMax.getInstance(4, 4, 4),
+ MinOptMax.getInstance(1, 2, 3).extendMinimum(4));
+ }
+
+ @Test
+ public void testEquals() {
+ MinOptMax number = MinOptMax.getInstance(1, 3, 5);
+ assertEquals(number, number);
+ assertEquals(number, MinOptMax.getInstance(1, 3, 5));
+ assertFalse(number.equals(MinOptMax.getInstance(2, 3, 5)));
+ assertFalse(number.equals(MinOptMax.getInstance(1, 4, 5)));
+ assertFalse(number.equals(MinOptMax.getInstance(1, 3, 4)));
+ assertFalse(number.equals(null));
+ assertFalse(number.equals(new Integer(1)));
+ }
+
+ @Test
+ public void testHashCode() {
+ MinOptMax number = MinOptMax.getInstance(1, 2, 3);
+ assertEquals(number.hashCode(), number.hashCode());
+ assertEquals(number.hashCode(), MinOptMax.getInstance(1, 2, 3).hashCode());
+ }
+}